LLVM 24.0.0git
TargetInstrInfo.h
Go to the documentation of this file.
1//===- llvm/CodeGen/TargetInstrInfo.h - Instruction Info --------*- C++ -*-===//
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// This file describes the target machine instruction set to the code generator.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CODEGEN_TARGETINSTRINFO_H
14#define LLVM_CODEGEN_TARGETINSTRINFO_H
15
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/Uniformity.h"
30#include "llvm/MC/MCInstrInfo.h"
35#include <array>
36#include <cassert>
37#include <cstddef>
38#include <cstdint>
39#include <utility>
40#include <vector>
41
42namespace llvm {
43
44class DFAPacketizer;
46class LiveIntervals;
47class LiveVariables;
49class MachineLoop;
50class MachineLoopInfo;
54class MCAsmInfo;
55class MCInst;
56struct MCSchedModel;
57class Module;
58class ScheduleDAG;
59class ScheduleDAGMI;
61class SDNode;
62class SelectionDAG;
63class SMSchedule;
65class RegScavenger;
66class MCRegisterClass;
71enum class MachineTraceStrategy;
72
73template <class T> class SmallVectorImpl;
74
75using ParamLoadedValue = std::pair<MachineOperand, DIExpression*>;
76
80
82 : Destination(&Dest), Source(&Src) {}
83};
84
85/// Used to describe a register and immediate addition.
86struct RegImmPair {
88 int64_t Imm;
89
90 RegImmPair(Register Reg, int64_t Imm) : Reg(Reg), Imm(Imm) {}
91};
92
93/// Used to describe addressing mode similar to ExtAddrMode in CodeGenPrepare.
94/// It holds the register values, the scale value and the displacement.
95/// It also holds a descriptor for the expression used to calculate the address
96/// from the operands.
98 enum class Formula {
99 Basic = 0, // BaseReg + ScaledReg * Scale + Displacement
100 SExtScaledReg = 1, // BaseReg + sext(ScaledReg) * Scale + Displacement
101 ZExtScaledReg = 2 // BaseReg + zext(ScaledReg) * Scale + Displacement
102 };
103
106 int64_t Scale = 0;
107 int64_t Displacement = 0;
109 ExtAddrMode() = default;
110};
111
112//---------------------------------------------------------------------------
113///
114/// TargetInstrInfo - Interface to description of machine instruction set
115///
117protected:
119
120 /// Subtarget specific sub-array of MCInstrInfo's RegClassByHwModeTables
121 /// (i.e. the table for the active HwMode). This should be indexed by
122 /// MCOperandInfo's RegClass field for LookupRegClassByHwMode operands.
123 const int16_t *const RegClassByHwMode;
124
125 TargetInstrInfo(const TargetRegisterInfo &TRI, unsigned CFSetupOpcode = ~0u,
126 unsigned CFDestroyOpcode = ~0u, unsigned CatchRetOpcode = ~0u,
127 unsigned ReturnOpcode = ~0u,
128 const int16_t *const RegClassByHwModeTable = nullptr)
129 : TRI(TRI), RegClassByHwMode(RegClassByHwModeTable),
130 CallFrameSetupOpcode(CFSetupOpcode),
131 CallFrameDestroyOpcode(CFDestroyOpcode), CatchRetOpcode(CatchRetOpcode),
132 ReturnOpcode(ReturnOpcode) {}
133
134public:
138
139 const TargetRegisterInfo &getRegisterInfo() const { return TRI; }
140
141 static bool isGenericOpcode(unsigned Opc) {
142 return Opc <= TargetOpcode::GENERIC_OP_END;
143 }
144
145 static bool isGenericAtomicRMWOpcode(unsigned Opc) {
146 return Opc >= TargetOpcode::GENERIC_ATOMICRMW_OP_START &&
147 Opc <= TargetOpcode::GENERIC_ATOMICRMW_OP_END;
148 }
149
150 /// \returns the subtarget appropriate RegClassID for \p OpInfo
151 ///
152 /// Note this shadows a version of getOpRegClassID in MCInstrInfo which takes
153 /// an additional argument for the subtarget's HwMode, since TargetInstrInfo
154 /// is owned by a subtarget in CodeGen but MCInstrInfo is a TargetMachine
155 /// constant.
156 int16_t getOpRegClassID(const MCOperandInfo &OpInfo) const {
157 if (OpInfo.isLookupRegClassByHwMode())
158 return RegClassByHwMode[OpInfo.RegClass];
159 return OpInfo.RegClass;
160 }
161
162 /// Given a machine instruction descriptor, returns the register
163 /// class constraint for OpNum, or NULL.
164 virtual const TargetRegisterClass *getRegClass(const MCInstrDesc &MCID,
165 unsigned OpNum) const;
166
167 /// Returns true if MI is an instruction we are unable to reason about
168 /// (like a call or something with unmodeled side effects).
169 virtual bool isGlobalMemoryObject(const MachineInstr *MI) const;
170
171 /// Return true if the instruction is trivially rematerializable, meaning it
172 /// has no side effects and requires no operands that aren't always available.
173 /// This means the only allowed uses are constants and unallocatable physical
174 /// registers so that the instructions result is independent of the place
175 /// in the function.
178 return false;
179 for (const MachineOperand &MO : MI.all_uses()) {
180 if (MO.getReg().isVirtual())
181 return false;
182 }
183 return true;
184 }
185
186 /// Return true if the instruction would be materializable at a point
187 /// in the containing function where all virtual register uses were
188 /// known to be live and available in registers.
189 bool isReMaterializable(const MachineInstr &MI) const {
190 return (MI.getOpcode() == TargetOpcode::IMPLICIT_DEF &&
191 MI.getNumOperands() == 1) ||
192 (MI.getDesc().isRematerializable() && isReMaterializableImpl(MI));
193 }
194
195 /// Given operand \p OpIdx of \p MI is a PhysReg use, return if it can be
196 /// ignored for the purpose of instruction rematerialization or sinking.
197 virtual bool isIgnorableUse(const MachineInstr &MI, unsigned OpIdx) const {
198 return false;
199 }
200
201 virtual bool isSafeToSink(MachineInstr &MI, MachineBasicBlock *SuccToSinkTo,
202 MachineCycleInfo *CI) const {
203 return true;
204 }
205
206 /// For a "cheap" instruction which doesn't enable additional sinking,
207 /// should MachineSink break a critical edge to sink it anyways?
209 return false;
210 }
211
212protected:
213 /// For instructions with opcodes for which the M_REMATERIALIZABLE flag is
214 /// set, this hook lets the target specify whether the instruction is actually
215 /// rematerializable, taking into consideration its operands. This
216 /// predicate must return false if the instruction has any side effects other
217 /// than producing a value.
218 virtual bool isReMaterializableImpl(const MachineInstr &MI) const;
219
220 /// This method commutes the operands of the given machine instruction MI.
221 /// The operands to be commuted are specified by their indices OpIdx1 and
222 /// OpIdx2.
223 ///
224 /// If a target has any instructions that are commutable but require
225 /// converting to different instructions or making non-trivial changes
226 /// to commute them, this method can be overloaded to do that.
227 /// The default implementation simply swaps the commutable operands.
228 ///
229 /// If NewMI is false, MI is modified in place and returned; otherwise, a
230 /// new machine instruction is created and returned.
231 ///
232 /// Do not call this method for a non-commutable instruction.
233 /// Even though the instruction is commutable, the method may still
234 /// fail to commute the operands, null pointer is returned in such cases.
235 virtual MachineInstr *commuteInstructionImpl(MachineInstr &MI, bool NewMI,
236 unsigned OpIdx1,
237 unsigned OpIdx2) const;
238
239 /// Assigns the (CommutableOpIdx1, CommutableOpIdx2) pair of commutable
240 /// operand indices to (ResultIdx1, ResultIdx2).
241 /// One or both input values of the pair: (ResultIdx1, ResultIdx2) may be
242 /// predefined to some indices or be undefined (designated by the special
243 /// value 'CommuteAnyOperandIndex').
244 /// The predefined result indices cannot be re-defined.
245 /// The function returns true iff after the result pair redefinition
246 /// the fixed result pair is equal to or equivalent to the source pair of
247 /// indices: (CommutableOpIdx1, CommutableOpIdx2). It is assumed here that
248 /// the pairs (x,y) and (y,x) are equivalent.
249 static bool fixCommutedOpIndices(unsigned &ResultIdx1, unsigned &ResultIdx2,
250 unsigned CommutableOpIdx1,
251 unsigned CommutableOpIdx2);
252
253public:
254 /// These methods return the opcode of the frame setup/destroy instructions
255 /// if they exist (-1 otherwise). Some targets use pseudo instructions in
256 /// order to abstract away the difference between operating with a frame
257 /// pointer and operating without, through the use of these two instructions.
258 /// A FrameSetup MI in MF implies MFI::AdjustsStack.
259 ///
260 unsigned getCallFrameSetupOpcode() const { return CallFrameSetupOpcode; }
261 unsigned getCallFrameDestroyOpcode() const { return CallFrameDestroyOpcode; }
262
263 /// Returns true if the argument is a frame pseudo instruction.
264 bool isFrameInstr(const MachineInstr &I) const {
265 return I.getOpcode() == getCallFrameSetupOpcode() ||
266 I.getOpcode() == getCallFrameDestroyOpcode();
267 }
268
269 /// Returns true if the argument is a frame setup pseudo instruction.
270 bool isFrameSetup(const MachineInstr &I) const {
271 return I.getOpcode() == getCallFrameSetupOpcode();
272 }
273
274 /// Returns size of the frame associated with the given frame instruction.
275 /// For frame setup instruction this is frame that is set up space set up
276 /// after the instruction. For frame destroy instruction this is the frame
277 /// freed by the caller.
278 /// Note, in some cases a call frame (or a part of it) may be prepared prior
279 /// to the frame setup instruction. It occurs in the calls that involve
280 /// inalloca arguments. This function reports only the size of the frame part
281 /// that is set up between the frame setup and destroy pseudo instructions.
282 int64_t getFrameSize(const MachineInstr &I) const {
283 assert(isFrameInstr(I) && "Not a frame instruction");
284 assert(I.getOperand(0).getImm() >= 0);
285 return I.getOperand(0).getImm();
286 }
287
288 /// Returns the total frame size, which is made up of the space set up inside
289 /// the pair of frame start-stop instructions and the space that is set up
290 /// prior to the pair.
291 int64_t getFrameTotalSize(const MachineInstr &I) const {
292 if (isFrameSetup(I)) {
293 assert(I.getOperand(1).getImm() >= 0 &&
294 "Frame size must not be negative");
295 return getFrameSize(I) + I.getOperand(1).getImm();
296 }
297 return getFrameSize(I);
298 }
299
300 unsigned getCatchReturnOpcode() const { return CatchRetOpcode; }
301 unsigned getReturnOpcode() const { return ReturnOpcode; }
302
303 /// Returns the actual stack pointer adjustment made by an instruction
304 /// as part of a call sequence. By default, only call frame setup/destroy
305 /// instructions adjust the stack, but targets may want to override this
306 /// to enable more fine-grained adjustment, or adjust by a different value.
307 virtual int getSPAdjust(const MachineInstr &MI) const;
308
309 /// Return true if the instruction is a "coalescable" extension instruction.
310 /// That is, it's like a copy where it's legal for the source to overlap the
311 /// destination. e.g. X86::MOVSX64rr32. If this returns true, then it's
312 /// expected the pre-extension value is available as a subreg of the result
313 /// register. This also returns the sub-register index in SubIdx.
314 virtual bool isCoalescableExtInstr(const MachineInstr &MI, Register &SrcReg,
315 Register &DstReg, unsigned &SubIdx) const {
316 return false;
317 }
318
319 /// If the specified machine instruction is a direct
320 /// load from a stack slot, return the virtual or physical register number of
321 /// the destination along with the FrameIndex of the loaded stack slot. If
322 /// not, return 0. This predicate must return 0 if the instruction has
323 /// any side effects other than loading from the stack slot.
325 int &FrameIndex) const {
326 return 0;
327 }
328
329 /// Optional extension of isLoadFromStackSlot that returns the number of
330 /// bytes loaded from the stack. This must be implemented if a backend
331 /// supports partial stack slot spills/loads to further disambiguate
332 /// what the load does.
334 int &FrameIndex,
335 TypeSize &MemBytes) const {
336 MemBytes = TypeSize::getZero();
337 return isLoadFromStackSlot(MI, FrameIndex);
338 }
339
340 /// Check for post-frame ptr elimination stack locations as well.
341 /// This uses a heuristic so it isn't reliable for correctness.
343 int &FrameIndex) const {
344 return 0;
345 }
346
347 /// If the specified machine instruction has a load from a stack slot,
348 /// return true along with the FrameIndices of the loaded stack slot and the
349 /// machine mem operands containing the reference.
350 /// If not, return false. Unlike isLoadFromStackSlot, this returns true for
351 /// any instructions that loads from the stack. This is just a hint, as some
352 /// cases may be missed.
353 virtual bool hasLoadFromStackSlot(
354 const MachineInstr &MI,
356
357 /// If the specified machine instruction is a direct
358 /// store to a stack slot, return the virtual or physical register number of
359 /// the source reg along with the FrameIndex of the loaded stack slot. If
360 /// not, return 0. This predicate must return 0 if the instruction has
361 /// any side effects other than storing to the stack slot.
363 int &FrameIndex) const {
364 return 0;
365 }
366
367 /// Optional extension of isStoreToStackSlot that returns the number of
368 /// bytes stored to the stack. This must be implemented if a backend
369 /// supports partial stack slot spills/loads to further disambiguate
370 /// what the store does.
372 int &FrameIndex,
373 TypeSize &MemBytes) const {
374 MemBytes = TypeSize::getZero();
375 return isStoreToStackSlot(MI, FrameIndex);
376 }
377
378 /// Check for post-frame ptr elimination stack locations as well.
379 /// This uses a heuristic, so it isn't reliable for correctness.
381 int &FrameIndex) const {
382 return 0;
383 }
384
385 /// If the specified machine instruction has a store to a stack slot,
386 /// return true along with the FrameIndices of the loaded stack slot and the
387 /// machine mem operands containing the reference.
388 /// If not, return false. Unlike isStoreToStackSlot,
389 /// this returns true for any instructions that stores to the
390 /// stack. This is just a hint, as some cases may be missed.
391 virtual bool hasStoreToStackSlot(
392 const MachineInstr &MI,
394
395 /// Return true if the specified machine instruction
396 /// is a copy of one stack slot to another and has no other effect.
397 /// Provide the identity of the two frame indices.
398 virtual bool isStackSlotCopy(const MachineInstr &MI, int &DestFrameIndex,
399 int &SrcFrameIndex) const {
400 return false;
401 }
402
403 /// Compute the size in bytes and offset within a stack slot of a spilled
404 /// register or subregister.
405 ///
406 /// \param [out] Size in bytes of the spilled value.
407 /// \param [out] Offset in bytes within the stack slot.
408 /// \returns true if both Size and Offset are successfully computed.
409 ///
410 /// Not all subregisters have computable spill slots. For example,
411 /// subregisters registers may not be byte-sized, and a pair of discontiguous
412 /// subregisters has no single offset.
413 ///
414 /// Targets with nontrivial bigendian implementations may need to override
415 /// this, particularly to support spilled vector registers.
416 virtual bool getStackSlotRange(const TargetRegisterClass *RC, unsigned SubIdx,
417 unsigned &Size, unsigned &Offset,
418 const MachineFunction &MF) const;
419
420 /// Return true if the given instruction is terminator that is unspillable,
421 /// according to isUnspillableTerminatorImpl.
423 return MI->isTerminator() && isUnspillableTerminatorImpl(MI);
424 }
425
426 /// Sum the sizes of instructions inside of a BUNDLE, by calling \ref
427 /// getInstSizeInBytes on each. This is a utility function for implementations
428 /// of \ref getInstSizeInBytes to use.
429 unsigned getInstBundleSize(const MachineInstr &MI) const;
430
431 /// Returns the size in bytes of the specified MachineInstr, or ~0U
432 /// when this function is not implemented by a target.
433
434 /// For BUNDLE instructions, target implementations are responsible for
435 /// accounting for the size of all bundled instructions.
436 virtual unsigned getInstSizeInBytes(const MachineInstr &MI) const {
437 return ~0U;
438 }
439
441 /// Do not verify instruction size.
443 /// Check that the instruction size matches exactly.
445 /// Allow the reported instruction size to be larger than the actual size.
447 };
448
449 /// Determine whether/how the instruction size returned by
450 /// getInstSizeInBytes() should be verified.
451 virtual InstSizeVerifyMode
455
456 /// Return true if the instruction is as cheap as a move instruction.
457 ///
458 /// Targets for different archs need to override this, and different
459 /// micro-architectures can also be finely tuned inside.
460 virtual bool isAsCheapAsAMove(const MachineInstr &MI) const {
461 return MI.isAsCheapAsAMove();
462 }
463
464 /// Return true if the instruction should be sunk by MachineSink.
465 ///
466 /// MachineSink determines on its own whether the instruction is safe to sink;
467 /// this gives the target a hook to override the default behavior with regards
468 /// to which instructions should be sunk.
469 ///
470 /// shouldPostRASink() is used by PostRAMachineSink.
471 virtual bool shouldSink(const MachineInstr &MI) const { return true; }
472 virtual bool shouldPostRASink(const MachineInstr &MI) const { return true; }
473
474 /// Return false if the instruction should not be hoisted by MachineLICM.
475 ///
476 /// MachineLICM determines on its own whether the instruction is safe to
477 /// hoist; this gives the target a hook to extend this assessment and prevent
478 /// an instruction being hoisted from a given loop for target specific
479 /// reasons.
480 virtual bool shouldHoist(const MachineInstr &MI,
481 const MachineLoop *FromLoop) const {
482 return true;
483 }
484
485 /// Re-issue the specified 'original' instruction at the
486 /// specific location targeting a new destination register.
487 /// The register in Orig->getOperand(0).getReg() will be substituted by
488 /// DestReg:SubIdx. Any existing subreg index is preserved or composed with
489 /// SubIdx.
490 /// \p UsedLanes is a bitmask of the lanes that are live at the
491 /// rematerialization point.
492 virtual void
494 Register DestReg, unsigned SubIdx, const MachineInstr &Orig,
495 LaneBitmask UsedLanes = LaneBitmask::getAll()) const;
496
497 /// Clones instruction or the whole instruction bundle \p Orig and
498 /// insert into \p MBB before \p InsertBefore. The target may update operands
499 /// that are required to be unique.
500 ///
501 /// \p Orig must not return true for MachineInstr::isNotDuplicable().
502 virtual MachineInstr &duplicate(MachineBasicBlock &MBB,
503 MachineBasicBlock::iterator InsertBefore,
504 const MachineInstr &Orig) const;
505
506 /// This method must be implemented by targets that
507 /// set the M_CONVERTIBLE_TO_3_ADDR flag. When this flag is set, the target
508 /// may be able to convert a two-address instruction into one or more true
509 /// three-address instructions on demand. This allows the X86 target (for
510 /// example) to convert ADD and SHL instructions into LEA instructions if they
511 /// would require register copies due to two-addressness.
512 ///
513 /// This method returns a null pointer if the transformation cannot be
514 /// performed, otherwise it returns the last new instruction.
515 ///
516 /// If \p LIS is not nullptr, the LiveIntervals info should be updated for
517 /// replacing \p MI with new instructions, even though this function does not
518 /// remove MI.
520 LiveVariables *LV,
521 LiveIntervals *LIS) const {
522 return nullptr;
523 }
524
525 // This constant can be used as an input value of operand index passed to
526 // the method findCommutedOpIndices() to tell the method that the
527 // corresponding operand index is not pre-defined and that the method
528 // can pick any commutable operand.
529 static const unsigned CommuteAnyOperandIndex = ~0U;
530
531 /// This method commutes the operands of the given machine instruction MI.
532 ///
533 /// The operands to be commuted are specified by their indices OpIdx1 and
534 /// OpIdx2. OpIdx1 and OpIdx2 arguments may be set to a special value
535 /// 'CommuteAnyOperandIndex', which means that the method is free to choose
536 /// any arbitrarily chosen commutable operand. If both arguments are set to
537 /// 'CommuteAnyOperandIndex' then the method looks for 2 different commutable
538 /// operands; then commutes them if such operands could be found.
539 ///
540 /// If NewMI is false, MI is modified in place and returned; otherwise, a
541 /// new machine instruction is created and returned.
542 ///
543 /// Do not call this method for a non-commutable instruction or
544 /// for non-commuable operands.
545 /// Even though the instruction is commutable, the method may still
546 /// fail to commute the operands, null pointer is returned in such cases.
548 commuteInstruction(MachineInstr &MI, bool NewMI = false,
549 unsigned OpIdx1 = CommuteAnyOperandIndex,
550 unsigned OpIdx2 = CommuteAnyOperandIndex) const;
551
552 /// Returns true iff the routine could find two commutable operands in the
553 /// given machine instruction.
554 /// The 'SrcOpIdx1' and 'SrcOpIdx2' are INPUT and OUTPUT arguments.
555 /// If any of the INPUT values is set to the special value
556 /// 'CommuteAnyOperandIndex' then the method arbitrarily picks a commutable
557 /// operand, then returns its index in the corresponding argument.
558 /// If both of INPUT values are set to 'CommuteAnyOperandIndex' then method
559 /// looks for 2 commutable operands.
560 /// If INPUT values refer to some operands of MI, then the method simply
561 /// returns true if the corresponding operands are commutable and returns
562 /// false otherwise.
563 ///
564 /// For example, calling this method this way:
565 /// unsigned Op1 = 1, Op2 = CommuteAnyOperandIndex;
566 /// findCommutedOpIndices(MI, Op1, Op2);
567 /// can be interpreted as a query asking to find an operand that would be
568 /// commutable with the operand#1.
569 virtual bool findCommutedOpIndices(const MachineInstr &MI,
570 unsigned &SrcOpIdx1,
571 unsigned &SrcOpIdx2) const;
572
573 /// Returns true if the target has a preference on the operands order of
574 /// the given machine instruction. And specify if \p Commute is required to
575 /// get the desired operands order.
576 virtual bool hasCommutePreference(MachineInstr &MI, bool &Commute) const {
577 return false;
578 }
579
580 /// If possible, converts the instruction to a simplified/canonical form.
581 /// Returns true if the instruction was modified.
582 ///
583 /// This function is only called after register allocation. The MI will be
584 /// modified in place. This is called by passes such as
585 /// MachineCopyPropagation, where their mutation of the MI operands may
586 /// expose opportunities to convert the instruction to a simpler form (e.g.
587 /// a load of 0).
588 virtual bool simplifyInstruction(MachineInstr &MI) const { return false; }
589
590 /// A pair composed of a register and a sub-register index.
591 /// Used to give some type checking when modeling Reg:SubReg.
594 unsigned SubReg;
595
597 : Reg(Reg), SubReg(SubReg) {}
598
599 bool operator==(const RegSubRegPair& P) const {
600 return Reg == P.Reg && SubReg == P.SubReg;
601 }
602 bool operator!=(const RegSubRegPair& P) const {
603 return !(*this == P);
604 }
605 };
606
607 /// A pair composed of a pair of a register and a sub-register index,
608 /// and another sub-register index.
609 /// Used to give some type checking when modeling Reg:SubReg1, SubReg2.
611 unsigned SubIdx;
612
614 unsigned SubIdx = 0)
616 };
617
618 /// Build the equivalent inputs of a REG_SEQUENCE for the given \p MI
619 /// and \p DefIdx.
620 /// \p [out] InputRegs of the equivalent REG_SEQUENCE. Each element of
621 /// the list is modeled as <Reg:SubReg, SubIdx>. Operands with the undef
622 /// flag are not added to this list.
623 /// E.g., REG_SEQUENCE %1:sub1, sub0, %2, sub1 would produce
624 /// two elements:
625 /// - %1:sub1, sub0
626 /// - %2<:0>, sub1
627 ///
628 /// \returns true if it is possible to build such an input sequence
629 /// with the pair \p MI, \p DefIdx. False otherwise.
630 ///
631 /// \pre MI.isRegSequence() or MI.isRegSequenceLike().
632 ///
633 /// \note The generic implementation does not provide any support for
634 /// MI.isRegSequenceLike(). In other words, one has to override
635 /// getRegSequenceLikeInputs for target specific instructions.
636 bool
637 getRegSequenceInputs(const MachineInstr &MI, unsigned DefIdx,
638 SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const;
639
640 /// Build the equivalent inputs of a EXTRACT_SUBREG for the given \p MI
641 /// and \p DefIdx.
642 /// \p [out] InputReg of the equivalent EXTRACT_SUBREG.
643 /// E.g., EXTRACT_SUBREG %1:sub1, sub0, sub1 would produce:
644 /// - %1:sub1, sub0
645 ///
646 /// \returns true if it is possible to build such an input sequence
647 /// with the pair \p MI, \p DefIdx and the operand has no undef flag set.
648 /// False otherwise.
649 ///
650 /// \pre MI.isExtractSubreg() or MI.isExtractSubregLike().
651 ///
652 /// \note The generic implementation does not provide any support for
653 /// MI.isExtractSubregLike(). In other words, one has to override
654 /// getExtractSubregLikeInputs for target specific instructions.
655 bool getExtractSubregInputs(const MachineInstr &MI, unsigned DefIdx,
656 RegSubRegPairAndIdx &InputReg) const;
657
658 /// Build the equivalent inputs of a INSERT_SUBREG for the given \p MI
659 /// and \p DefIdx.
660 /// \p [out] BaseReg and \p [out] InsertedReg contain
661 /// the equivalent inputs of INSERT_SUBREG.
662 /// E.g., INSERT_SUBREG %0:sub0, %1:sub1, sub3 would produce:
663 /// - BaseReg: %0:sub0
664 /// - InsertedReg: %1:sub1, sub3
665 ///
666 /// \returns true if it is possible to build such an input sequence
667 /// with the pair \p MI, \p DefIdx and the operand has no undef flag set.
668 /// False otherwise.
669 ///
670 /// \pre MI.isInsertSubreg() or MI.isInsertSubregLike().
671 ///
672 /// \note The generic implementation does not provide any support for
673 /// MI.isInsertSubregLike(). In other words, one has to override
674 /// getInsertSubregLikeInputs for target specific instructions.
675 bool getInsertSubregInputs(const MachineInstr &MI, unsigned DefIdx,
676 RegSubRegPair &BaseReg,
677 RegSubRegPairAndIdx &InsertedReg) const;
678
679 /// Return true if two machine instructions would produce identical values.
680 /// By default, this is only true when the two instructions
681 /// are deemed identical except for defs. If this function is called when the
682 /// IR is still in SSA form, the caller can pass the MachineRegisterInfo for
683 /// aggressive checks.
684 virtual bool produceSameValue(const MachineInstr &MI0,
685 const MachineInstr &MI1,
686 const MachineRegisterInfo *MRI = nullptr) const;
687
688 /// \returns true if a branch from an instruction with opcode \p BranchOpc
689 /// bytes is capable of jumping to a position \p BrOffset bytes away.
690 virtual bool isBranchOffsetInRange(unsigned BranchOpc,
691 int64_t BrOffset) const {
692 llvm_unreachable("target did not implement");
693 }
694
695 /// \returns The block that branch instruction \p MI jumps to.
697 llvm_unreachable("target did not implement");
698 }
699
700 /// Insert an unconditional indirect branch at the end of \p MBB to \p
701 /// NewDestBB. Optionally, insert the clobbered register restoring in \p
702 /// RestoreBB. \p BrOffset indicates the offset of \p NewDestBB relative to
703 /// the offset of the position to insert the new branch.
705 MachineBasicBlock &NewDestBB,
706 MachineBasicBlock &RestoreBB,
707 const DebugLoc &DL, int64_t BrOffset = 0,
708 RegScavenger *RS = nullptr) const {
709 llvm_unreachable("target did not implement");
710 }
711
712 /// Analyze the branching code at the end of MBB, returning
713 /// true if it cannot be understood (e.g. it's a switch dispatch or isn't
714 /// implemented for a target). Upon success, this returns false and returns
715 /// with the following information in various cases:
716 ///
717 /// 1. If this block ends with no branches (it just falls through to its succ)
718 /// just return false, leaving TBB/FBB null.
719 /// 2. If this block ends with only an unconditional branch, it sets TBB to be
720 /// the destination block.
721 /// 3. If this block ends with a conditional branch and it falls through to a
722 /// successor block, it sets TBB to be the branch destination block and a
723 /// list of operands that evaluate the condition. These operands can be
724 /// passed to other TargetInstrInfo methods to create new branches.
725 /// 4. If this block ends with a conditional branch followed by an
726 /// unconditional branch, it returns the 'true' destination in TBB, the
727 /// 'false' destination in FBB, and a list of operands that evaluate the
728 /// condition. These operands can be passed to other TargetInstrInfo
729 /// methods to create new branches.
730 ///
731 /// Note that removeBranch and insertBranch must be implemented to support
732 /// cases where this method returns success.
733 ///
734 /// If AllowModify is true, then this routine is allowed to modify the basic
735 /// block (e.g. delete instructions after the unconditional branch).
736 ///
737 /// The CFG information in MBB.Predecessors and MBB.Successors must be valid
738 /// before calling this function.
740 MachineBasicBlock *&FBB,
742 bool AllowModify = false) const {
743 return true;
744 }
745
747 const MachineBasicBlock *&TBB,
748 const MachineBasicBlock *&FBB,
750 MachineBasicBlock *TempTBB = nullptr, *TempFBB = nullptr;
751 bool NotUnderstandable = analyzeBranch(const_cast<MachineBasicBlock &>(MBB),
752 TempTBB, TempFBB, Cond,
753 /*AllowModify=*/false);
754 TBB = TempTBB;
755 FBB = TempFBB;
756 return NotUnderstandable;
757 }
758
759 /// Represents a predicate at the MachineFunction level. The control flow a
760 /// MachineBranchPredicate represents is:
761 ///
762 /// Reg = LHS `Predicate` RHS == ConditionDef
763 /// if Reg then goto TrueDest else goto FalseDest
764 ///
767 PRED_EQ, // True if two values are equal
768 PRED_NE, // True if two values are not equal
769 PRED_INVALID // Sentinel value
770 };
771
778
779 /// SingleUseCondition is true if ConditionDef is dead except for the
780 /// branch(es) at the end of the basic block.
781 ///
782 bool SingleUseCondition = false;
783
784 explicit MachineBranchPredicate() = default;
785 };
786
787 /// Analyze the branching code at the end of MBB and parse it into the
788 /// MachineBranchPredicate structure if possible. Returns false on success
789 /// and true on failure.
790 ///
791 /// If AllowModify is true, then this routine is allowed to modify the basic
792 /// block (e.g. delete instructions after the unconditional branch).
793 ///
796 bool AllowModify = false) const {
797 return true;
798 }
799
800 /// Remove the branching code at the end of the specific MBB.
801 /// This is only invoked in cases where analyzeBranch returns success. It
802 /// returns the number of instructions that were removed.
803 /// If \p BytesRemoved is non-null, report the change in code size from the
804 /// removed instructions.
806 int *BytesRemoved = nullptr) const {
807 llvm_unreachable("Target didn't implement TargetInstrInfo::removeBranch!");
808 }
809
810 /// Insert branch code into the end of the specified MachineBasicBlock. The
811 /// operands to this method are the same as those returned by analyzeBranch.
812 /// This is only invoked in cases where analyzeBranch returns success. It
813 /// returns the number of instructions inserted. If \p BytesAdded is non-null,
814 /// report the change in code size from the added instructions.
815 ///
816 /// It is also invoked by tail merging to add unconditional branches in
817 /// cases where analyzeBranch doesn't apply because there was no original
818 /// branch to analyze. At least this much must be implemented, else tail
819 /// merging needs to be disabled.
820 ///
821 /// The CFG information in MBB.Predecessors and MBB.Successors must be valid
822 /// before calling this function.
826 const DebugLoc &DL,
827 int *BytesAdded = nullptr) const {
828 llvm_unreachable("Target didn't implement TargetInstrInfo::insertBranch!");
829 }
830
832 MachineBasicBlock *DestBB,
833 const DebugLoc &DL,
834 int *BytesAdded = nullptr) const {
835 return insertBranch(MBB, DestBB, nullptr, ArrayRef<MachineOperand>(), DL,
836 BytesAdded);
837 }
838
839 /// Object returned by analyzeLoopForPipelining. Allows software pipelining
840 /// implementations to query attributes of the loop being pipelined and to
841 /// apply target-specific updates to the loop once pipelining is complete.
843 public:
845 /// Return true if the given instruction should not be pipelined and should
846 /// be ignored. An example could be a loop comparison, or induction variable
847 /// update with no users being pipelined.
848 virtual bool shouldIgnoreForPipelining(const MachineInstr *MI) const = 0;
849
850 /// Return true if the proposed schedule should used. Otherwise return
851 /// false to not pipeline the loop. This function should be used to ensure
852 /// that pipelined loops meet target-specific quality heuristics.
854 return true;
855 }
856
857 /// Create a condition to determine if the trip count of the loop is greater
858 /// than TC, where TC is always one more than for the previous prologue or
859 /// 0 if this is being called for the outermost prologue.
860 ///
861 /// If the trip count is statically known to be greater than TC, return
862 /// true. If the trip count is statically known to be not greater than TC,
863 /// return false. Otherwise return nullopt and fill out Cond with the test
864 /// condition.
865 ///
866 /// Note: This hook is guaranteed to be called from the innermost to the
867 /// outermost prologue of the loop being software pipelined.
868 virtual std::optional<bool>
871
872 /// Create a condition to determine if the remaining trip count for a phase
873 /// is greater than TC. Some instructions such as comparisons may be
874 /// inserted at the bottom of MBB. All instructions expanded for the
875 /// phase must be inserted in MBB before calling this function.
876 /// LastStage0Insts is the map from the original instructions scheduled at
877 /// stage#0 to the expanded instructions for the last iteration of the
878 /// kernel. LastStage0Insts is intended to obtain the instruction that
879 /// refers the latest loop counter value.
880 ///
881 /// MBB can also be a predecessor of the prologue block. Then
882 /// LastStage0Insts must be empty and the compared value is the initial
883 /// value of the trip count.
888 "Target didn't implement "
889 "PipelinerLoopInfo::createRemainingIterationsGreaterCondition!");
890 }
891
892 /// Modify the loop such that the trip count is
893 /// OriginalTC + TripCountAdjust.
894 virtual void adjustTripCount(int TripCountAdjust) = 0;
895
896 /// Called when the loop's preheader has been modified to NewPreheader.
897 virtual void setPreheader(MachineBasicBlock *NewPreheader) = 0;
898
899 /// Called when the loop is being removed. Any instructions in the preheader
900 /// should be removed.
901 ///
902 /// Once this function is called, no other functions on this object are
903 /// valid; the loop has been removed.
904 virtual void disposed(LiveIntervals *LIS = nullptr) {}
905
906 /// Return true if the target can expand pipelined schedule with modulo
907 /// variable expansion.
908 virtual bool isMVEExpanderSupported() { return false; }
909 };
910
911 /// Analyze loop L, which must be a single-basic-block loop, and if the
912 /// conditions can be understood enough produce a PipelinerLoopInfo object.
913 virtual std::unique_ptr<PipelinerLoopInfo>
915 return nullptr;
916 }
917
918 /// Analyze the loop code, return true if it cannot be understood. Upon
919 /// success, this function returns false and returns information about the
920 /// induction variable and compare instruction used at the end.
921 virtual bool analyzeLoop(MachineLoop &L, MachineInstr *&IndVarInst,
922 MachineInstr *&CmpInst) const {
923 return true;
924 }
925
926 /// Generate code to reduce the loop iteration by one and check if the loop
927 /// is finished. Return the value/register of the new loop count. We need
928 /// this function when peeling off one or more iterations of a loop. This
929 /// function assumes the nth iteration is peeled first.
931 MachineBasicBlock &PreHeader,
932 MachineInstr *IndVar, MachineInstr &Cmp,
935 unsigned Iter, unsigned MaxIter) const {
936 llvm_unreachable("Target didn't implement ReduceLoopCount");
937 }
938
939 /// Delete the instruction OldInst and everything after it, replacing it with
940 /// an unconditional branch to NewDest. This is used by the tail merging pass.
941 virtual void ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail,
942 MachineBasicBlock *NewDest) const;
943
944 /// Return true if it's legal to split the given basic
945 /// block at the specified instruction (i.e. instruction would be the start
946 /// of a new basic block).
949 return true;
950 }
951
952 /// Return true if it's profitable to predicate
953 /// instructions with accumulated instruction latency of "NumCycles"
954 /// of the specified basic block, where the probability of the instructions
955 /// being executed is given by Probability, and Confidence is a measure
956 /// of our confidence that it will be properly predicted.
957 virtual bool isProfitableToIfCvt(MachineBasicBlock &MBB, unsigned NumCycles,
958 unsigned ExtraPredCycles,
959 BranchProbability Probability) const {
960 return false;
961 }
962
963 /// Second variant of isProfitableToIfCvt. This one
964 /// checks for the case where two basic blocks from true and false path
965 /// of a if-then-else (diamond) are predicated on mutually exclusive
966 /// predicates, where the probability of the true path being taken is given
967 /// by Probability, and Confidence is a measure of our confidence that it
968 /// will be properly predicted.
969 virtual bool isProfitableToIfCvt(MachineBasicBlock &TMBB, unsigned NumTCycles,
970 unsigned ExtraTCycles,
971 MachineBasicBlock &FMBB, unsigned NumFCycles,
972 unsigned ExtraFCycles,
973 BranchProbability Probability) const {
974 return false;
975 }
976
977 /// Return true if it's profitable for if-converter to duplicate instructions
978 /// of specified accumulated instruction latencies in the specified MBB to
979 /// enable if-conversion.
980 /// The probability of the instructions being executed is given by
981 /// Probability, and Confidence is a measure of our confidence that it
982 /// will be properly predicted.
984 unsigned NumCycles,
985 BranchProbability Probability) const {
986 return false;
987 }
988
989 /// Return the increase in code size needed to predicate a contiguous run of
990 /// NumInsts instructions.
992 unsigned NumInsts) const {
993 return 0;
994 }
995
996 /// Return an estimate for the code size reduction (in bytes) which will be
997 /// caused by removing the given branch instruction during if-conversion.
998 virtual unsigned predictBranchSizeForIfCvt(MachineInstr &MI) const {
999 return getInstSizeInBytes(MI);
1000 }
1001
1002 /// Return true if it's profitable to unpredicate
1003 /// one side of a 'diamond', i.e. two sides of if-else predicated on mutually
1004 /// exclusive predicates.
1005 /// e.g.
1006 /// subeq r0, r1, #1
1007 /// addne r0, r1, #1
1008 /// =>
1009 /// sub r0, r1, #1
1010 /// addne r0, r1, #1
1011 ///
1012 /// This may be profitable is conditional instructions are always executed.
1014 MachineBasicBlock &FMBB) const {
1015 return false;
1016 }
1017
1018 /// Return true if it is possible to insert a select
1019 /// instruction that chooses between TrueReg and FalseReg based on the
1020 /// condition code in Cond.
1021 ///
1022 /// When successful, also return the latency in cycles from TrueReg,
1023 /// FalseReg, and Cond to the destination register. In most cases, a select
1024 /// instruction will be 1 cycle, so CondCycles = TrueCycles = FalseCycles = 1
1025 ///
1026 /// Some x86 implementations have 2-cycle cmov instructions.
1027 ///
1028 /// @param MBB Block where select instruction would be inserted.
1029 /// @param Cond Condition returned by analyzeBranch.
1030 /// @param DstReg Virtual dest register that the result should write to.
1031 /// @param TrueReg Virtual register to select when Cond is true.
1032 /// @param FalseReg Virtual register to select when Cond is false.
1033 /// @param CondCycles Latency from Cond+Branch to select output.
1034 /// @param TrueCycles Latency from TrueReg to select output.
1035 /// @param FalseCycles Latency from FalseReg to select output.
1038 Register TrueReg, Register FalseReg,
1039 int &CondCycles, int &TrueCycles,
1040 int &FalseCycles) const {
1041 return false;
1042 }
1043
1044 /// Insert a select instruction into MBB before I that will copy TrueReg to
1045 /// DstReg when Cond is true, and FalseReg to DstReg when Cond is false.
1046 ///
1047 /// This function can only be called after canInsertSelect() returned true.
1048 /// The condition in Cond comes from analyzeBranch, and it can be assumed
1049 /// that the same flags or registers required by Cond are available at the
1050 /// insertion point.
1051 ///
1052 /// @param MBB Block where select instruction should be inserted.
1053 /// @param I Insertion point.
1054 /// @param DL Source location for debugging.
1055 /// @param DstReg Virtual register to be defined by select instruction.
1056 /// @param Cond Condition as computed by analyzeBranch.
1057 /// @param TrueReg Virtual register to copy when Cond is true.
1058 /// @param FalseReg Virtual register to copy when Cons is false.
1062 Register TrueReg, Register FalseReg) const {
1063 llvm_unreachable("Target didn't implement TargetInstrInfo::insertSelect!");
1064 }
1065
1066 /// Given an instruction marked as `isSelect = true`, attempt to optimize MI
1067 /// by merging it with one of its operands. Returns nullptr on failure.
1068 ///
1069 /// When successful, returns the new select instruction. The client is
1070 /// responsible for deleting MI.
1071 ///
1072 /// If both sides of the select can be optimized, PreferFalse is used to pick
1073 /// a side.
1074 ///
1075 /// @param MI Optimizable select instruction.
1076 /// @param NewMIs Set that record all MIs in the basic block up to \p
1077 /// MI. Has to be updated with any newly created MI or deleted ones.
1078 /// @param PreferFalse Try to optimize FalseOp instead of TrueOp.
1079 /// @returns Optimized instruction or NULL.
1082 bool PreferFalse = false) const {
1083 assert(MI.isSelect() && "MI must be a select instruction");
1084 return nullptr;
1085 }
1086
1087 /// Emit instructions to copy a pair of physical registers.
1088 ///
1089 /// This function should support copies within any legal register class as
1090 /// well as any cross-class copies created during instruction selection.
1091 ///
1092 /// The source and destination registers may overlap, which may require a
1093 /// careful implementation when multiple copy instructions are required for
1094 /// large registers. See for example the ARM target.
1095 ///
1096 /// If RenamableDest is true, the copy instruction's destination operand is
1097 /// marked renamable.
1098 /// If RenamableSrc is true, the copy instruction's source operand is
1099 /// marked renamable.
1102 Register DestReg, Register SrcReg, bool KillSrc,
1103 bool RenamableDest = false,
1104 bool RenamableSrc = false) const {
1105 llvm_unreachable("Target didn't implement TargetInstrInfo::copyPhysReg!");
1106 }
1107
1108 /// Allow targets to tell MachineVerifier whether a specific register
1109 /// MachineOperand can be used as part of PC-relative addressing.
1110 /// PC-relative addressing modes in many CISC architectures contain
1111 /// (non-PC) registers as offsets or scaling values, which inherently
1112 /// tags the corresponding MachineOperand with OPERAND_PCREL.
1113 ///
1114 /// @param MO The MachineOperand in question. MO.isReg() should always
1115 /// be true.
1116 /// @return Whether this operand is allowed to be used PC-relatively.
1117 virtual bool isPCRelRegisterOperandLegal(const MachineOperand &MO) const {
1118 return false;
1119 }
1120
1121 /// Return an index for MachineJumpTableInfo if \p insn is an indirect jump
1122 /// using a jump table, otherwise -1.
1123 virtual int getJumpTableIndex(const MachineInstr &MI) const { return -1; }
1124
1125protected:
1126 /// Target-dependent implementation for IsCopyInstr.
1127 /// If the specific machine instruction is a instruction that moves/copies
1128 /// value from one register to another register return destination and source
1129 /// registers as machine operands.
1130 virtual std::optional<DestSourcePair>
1132 return std::nullopt;
1133 }
1134
1135 virtual std::optional<DestSourcePair>
1137 return std::nullopt;
1138 }
1139
1140 /// Return true if the given terminator MI is not expected to spill. This
1141 /// sets the live interval as not spillable and adjusts phi node lowering to
1142 /// not introduce copies after the terminator. Use with care, these are
1143 /// currently used for hardware loop intrinsics in very controlled situations,
1144 /// created prior to registry allocation in loops that only have single phi
1145 /// users for the terminators value. They may run out of registers if not used
1146 /// carefully.
1147 virtual bool isUnspillableTerminatorImpl(const MachineInstr *MI) const {
1148 return false;
1149 }
1150
1151public:
1152 /// If the specific machine instruction is a instruction that moves/copies
1153 /// value from one register to another register return destination and source
1154 /// registers as machine operands.
1155 /// For COPY-instruction the method naturally returns destination and source
1156 /// registers as machine operands, for all other instructions the method calls
1157 /// target-dependent implementation.
1158 std::optional<DestSourcePair> isCopyInstr(const MachineInstr &MI) const {
1159 if (MI.isCopy()) {
1160 return DestSourcePair{MI.getOperand(0), MI.getOperand(1)};
1161 }
1162 return isCopyInstrImpl(MI);
1163 }
1164
1165 // Similar to `isCopyInstr`, but adds non-copy semantics on MIR, but
1166 // ultimately generates a copy instruction.
1167 std::optional<DestSourcePair> isCopyLikeInstr(const MachineInstr &MI) const {
1168 if (auto IsCopyInstr = isCopyInstr(MI))
1169 return IsCopyInstr;
1170 return isCopyLikeInstrImpl(MI);
1171 }
1172
1173 bool isFullCopyInstr(const MachineInstr &MI) const {
1174 auto DestSrc = isCopyInstr(MI);
1175 if (!DestSrc)
1176 return false;
1177
1178 const MachineOperand *DestRegOp = DestSrc->Destination;
1179 const MachineOperand *SrcRegOp = DestSrc->Source;
1180 return !DestRegOp->getSubReg() && !SrcRegOp->getSubReg();
1181 }
1182
1183 /// If the specific machine instruction is an instruction that adds an
1184 /// immediate value and a register, and stores the result in the given
1185 /// register \c Reg, return a pair of the source register and the offset
1186 /// which has been added.
1187 virtual std::optional<RegImmPair> isAddImmediate(const MachineInstr &MI,
1188 Register Reg) const {
1189 return std::nullopt;
1190 }
1191
1192 /// Returns true if MI is an instruction that defines Reg to have a constant
1193 /// value and the value is recorded in ImmVal. The ImmVal is a result that
1194 /// should be interpreted as modulo size of Reg.
1196 const Register Reg,
1197 int64_t &ImmVal) const {
1198 return false;
1199 }
1200
1201 /// Store the specified register of the given register class to the specified
1202 /// stack frame index. The store instruction is to be added to the given
1203 /// machine basic block before the specified machine instruction. If isKill
1204 /// is true, the register operand is the last use and must be marked kill. If
1205 /// \p SrcReg is being directly spilled as part of assigning a virtual
1206 /// register, \p VReg is the register being assigned. This additional register
1207 /// argument is needed for certain targets when invoked from RegAllocFast to
1208 /// map the spilled physical register to its virtual register. A null register
1209 /// can be passed elsewhere. The \p Flags is used to set appropriate machine
1210 /// flags on the spill instruction e.g. FrameSetup flag on a callee saved
1211 /// register spill instruction, part of prologue, during the frame lowering.
1214 bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg,
1216 llvm_unreachable("Target didn't implement "
1217 "TargetInstrInfo::storeRegToStackSlot!");
1218 }
1219
1220 /// Load the specified register of the given register class from the specified
1221 /// stack frame index. The load instruction is to be added to the given
1222 /// machine basic block before the specified machine instruction. If \p
1223 /// DestReg is being directly reloaded as part of assigning a virtual
1224 /// register, \p VReg is the register being assigned. This additional register
1225 /// argument is needed for certain targets when invoked from RegAllocFast to
1226 /// map the loaded physical register to its virtual register. A null register
1227 /// can be passed elsewhere. \p SubReg is required for partial reload of
1228 /// tuples if the target supports it. The \p Flags is used to set appropriate
1229 /// machine flags on the spill instruction e.g. FrameDestroy flag on a callee
1230 /// saved register reload instruction, part of epilogue, during the frame
1231 /// lowering.
1234 int FrameIndex, const TargetRegisterClass *RC, Register VReg,
1235 unsigned SubReg = 0,
1237 llvm_unreachable("Target didn't implement "
1238 "TargetInstrInfo::loadRegFromStackSlot!");
1239 }
1240
1241 /// This function is called for all pseudo instructions
1242 /// that remain after register allocation. Many pseudo instructions are
1243 /// created to help register allocation. This is the place to convert them
1244 /// into real instructions. The target can edit MI in place, or it can insert
1245 /// new instructions and erase MI. The function should return true if
1246 /// anything was changed.
1247 virtual bool expandPostRAPseudo(MachineInstr &MI) const { return false; }
1248
1249 /// Check whether the target can fold a load that feeds a subreg operand
1250 /// (or a subreg operand that feeds a store).
1251 /// For example, X86 may want to return true if it can fold
1252 /// movl (%esp), %eax
1253 /// subb, %al, ...
1254 /// Into:
1255 /// subb (%esp), ...
1256 ///
1257 /// Ideally, we'd like the target implementation of foldMemoryOperand() to
1258 /// reject subregs - but since this behavior used to be enforced in the
1259 /// target-independent code, moving this responsibility to the targets
1260 /// has the potential of causing nasty silent breakage in out-of-tree targets.
1261 virtual bool isSubregFoldable() const { return false; }
1262
1263 /// For a patchpoint, stackmap, or statepoint intrinsic, return the range of
1264 /// operands which can't be folded into stack references. Operands outside
1265 /// of the range are most likely foldable but it is not guaranteed.
1266 /// These instructions are unique in that stack references for some operands
1267 /// have the same execution cost (e.g. none) as the unfolded register forms.
1268 /// The ranged return is guaranteed to include all operands which can't be
1269 /// folded at zero cost.
1270 virtual std::pair<unsigned, unsigned>
1271 getPatchpointUnfoldableRange(const MachineInstr &MI) const;
1272
1273 /// Attempt to fold a load or store of the specified stack
1274 /// slot into the specified machine instruction for the specified operand(s).
1275 /// If this is possible, a new instruction is returned with the specified
1276 /// operand folded, otherwise NULL is returned.
1277 /// The new instruction is inserted before MI, and the client is responsible
1278 /// for removing the old instruction.
1279 /// If a copy instruction being created during fold, return it by CopyMI.
1280 /// If VRM is passed, the assigned physregs can be inspected by target to
1281 /// decide on using an opcode (note that those assignments can still change).
1282 MachineInstr *foldMemoryOperand(MachineInstr &MI, ArrayRef<unsigned> Ops,
1283 int FI, MachineInstr *&CopyMI,
1284 LiveIntervals *LIS = nullptr,
1285 VirtRegMap *VRM = nullptr) const;
1286
1287 /// Same as the previous version except it allows folding of any load and
1288 /// store from / to any address, not just from a specific stack slot.
1289 MachineInstr *foldMemoryOperand(MachineInstr &MI, ArrayRef<unsigned> Ops,
1290 MachineInstr &LoadMI, MachineInstr *&CopyMI,
1291 LiveIntervals *LIS = nullptr,
1292 VirtRegMap *VRM = nullptr) const;
1293
1294 /// This function defines the logic to lower COPY instruction to
1295 /// target specific instruction(s).
1296 void lowerCopy(MachineInstr *MI, const TargetRegisterInfo *TRI) const;
1297
1298 /// Return true when there is potentially a faster code sequence
1299 /// for an instruction chain ending in \p Root. All potential patterns are
1300 /// returned in the \p Patterns vector. Patterns should be sorted in priority
1301 /// order since the pattern evaluator stops checking as soon as it finds a
1302 /// faster sequence.
1303 /// \param Root - Instruction that could be combined with one of its operands
1304 /// \param Patterns - Vector of possible combination patterns
1305 virtual bool getMachineCombinerPatterns(MachineInstr &Root,
1306 SmallVectorImpl<unsigned> &Patterns,
1307 bool DoRegPressureReduce) const;
1308
1309 /// Return true if target supports reassociation of instructions in machine
1310 /// combiner pass to reduce register pressure for a given BB.
1311 virtual bool
1313 const RegisterClassInfo *RegClassInfo) const {
1314 return false;
1315 }
1316
1317 /// Fix up the placeholder we may add in genAlternativeCodeSequence().
1318 virtual void
1320 SmallVectorImpl<MachineInstr *> &InsInstrs) const {}
1321
1322 /// Return true when a code sequence can improve throughput. It
1323 /// should be called only for instructions in loops.
1324 /// \param Pattern - combiner pattern
1325 virtual bool isThroughputPattern(unsigned Pattern) const;
1326
1327 /// Return the objective of a combiner pattern.
1328 /// \param Pattern - combiner pattern
1329 virtual CombinerObjective getCombinerObjective(unsigned Pattern) const;
1330
1331 /// Return true if the input \P Inst is part of a chain of dependent ops
1332 /// that are suitable for reassociation, otherwise return false.
1333 /// If the instruction's operands must be commuted to have a previous
1334 /// instruction of the same type define the first source operand, \P Commuted
1335 /// will be set to true.
1336 bool isReassociationCandidate(const MachineInstr &Inst, bool &Commuted) const;
1337
1338 /// Return true when \P Inst is both associative and commutative. If \P Invert
1339 /// is true, then the inverse of \P Inst operation must be tested.
1341 bool Invert = false) const {
1342 return false;
1343 }
1344
1345 /// Find chains of accumulations that can be rewritten as a tree for increased
1346 /// ILP.
1347 bool getAccumulatorReassociationPatterns(
1348 MachineInstr &Root, SmallVectorImpl<unsigned> &Patterns) const;
1349
1350 /// Find the chain of accumulator instructions in \P MBB and return them in
1351 /// \P Chain.
1352 void getAccumulatorChain(MachineInstr *CurrentInstr,
1353 SmallVectorImpl<Register> &Chain) const;
1354
1355 /// Return true when \P OpCode is an instruction which performs
1356 /// accumulation into one of its operand registers.
1357 virtual bool isAccumulationOpcode(unsigned Opcode) const { return false; }
1358
1359 /// Returns an opcode which defines the accumulator used by \P Opcode.
1360 virtual unsigned getAccumulationStartOpcode(unsigned Opcode) const {
1361 llvm_unreachable("Function not implemented for target!");
1362 return 0;
1363 }
1364
1365 /// Returns the opcode that should be use to reduce accumulation registers.
1366 virtual unsigned
1367 getReduceOpcodeForAccumulator(unsigned int AccumulatorOpCode) const {
1368 llvm_unreachable("Function not implemented for target!");
1369 return 0;
1370 }
1371
1372 /// Reduces branches of the accumulator tree into a single register.
1373 void reduceAccumulatorTree(SmallVectorImpl<Register> &RegistersToReduce,
1375 MachineFunction &MF, MachineInstr &Root,
1377 DenseMap<Register, unsigned> &InstrIdxForVirtReg,
1378 Register ResultReg) const;
1379
1380 /// Return the inverse operation opcode if it exists for \P Opcode (e.g. add
1381 /// for sub and vice versa).
1382 virtual std::optional<unsigned> getInverseOpcode(unsigned Opcode) const {
1383 return std::nullopt;
1384 }
1385
1386 /// Return true when \P Opcode1 or its inversion is equal to \P Opcode2.
1387 bool areOpcodesEqualOrInverse(unsigned Opcode1, unsigned Opcode2) const;
1388
1389 /// Return true when \P Inst has reassociable operands in the same \P MBB.
1390 virtual bool hasReassociableOperands(const MachineInstr &Inst,
1391 const MachineBasicBlock *MBB) const;
1392
1393 /// Return true when \P Inst has reassociable sibling.
1394 virtual bool hasReassociableSibling(const MachineInstr &Inst,
1395 bool &Commuted) const;
1396
1397 /// When getMachineCombinerPatterns() finds patterns, this function generates
1398 /// the instructions that could replace the original code sequence. The client
1399 /// has to decide whether the actual replacement is beneficial or not.
1400 /// \param Root - Instruction that could be combined with one of its operands
1401 /// \param Pattern - Combination pattern for Root
1402 /// \param InsInstrs - Vector of new instructions that implement Pattern
1403 /// \param DelInstrs - Old instructions, including Root, that could be
1404 /// replaced by InsInstr
1405 /// \param InstIdxForVirtReg - map of virtual register to instruction in
1406 /// InsInstr that defines it
1407 virtual void genAlternativeCodeSequence(
1408 MachineInstr &Root, unsigned Pattern,
1411 DenseMap<Register, unsigned> &InstIdxForVirtReg) const;
1412
1413 /// When calculate the latency of the root instruction, accumulate the
1414 /// latency of the sequence to the root latency.
1415 /// \param Root - Instruction that could be combined with one of its operands
1417 return true;
1418 }
1419
1420 /// The returned array encodes the operand index for each parameter because
1421 /// the operands may be commuted; the operand indices for associative
1422 /// operations might also be target-specific. Each element specifies the index
1423 /// of {Prev, A, B, X, Y}.
1424 virtual void
1425 getReassociateOperandIndices(const MachineInstr &Root, unsigned Pattern,
1426 std::array<unsigned, 5> &OperandIndices) const;
1427
1428 /// Attempt to reassociate \P Root and \P Prev according to \P Pattern to
1429 /// reduce critical path length.
1430 void reassociateOps(MachineInstr &Root, MachineInstr &Prev, unsigned Pattern,
1434 DenseMap<Register, unsigned> &InstrIdxForVirtReg) const;
1435
1436 /// Reassociation of some instructions requires inverse operations (e.g.
1437 /// (X + A) - Y => (X - Y) + A). This method returns a pair of new opcodes
1438 /// (new root opcode, new prev opcode) that must be used to reassociate \P
1439 /// Root and \P Prev accoring to \P Pattern.
1440 std::pair<unsigned, unsigned>
1441 getReassociationOpcodes(unsigned Pattern, const MachineInstr &Root,
1442 const MachineInstr &Prev) const;
1443
1444 /// The limit on resource length extension we accept in MachineCombiner Pass.
1445 virtual int getExtendResourceLenLimit() const { return 0; }
1446
1447 /// This is an architecture-specific helper function of reassociateOps.
1448 /// Set special operand attributes for new instructions after reassociation.
1449 virtual void setSpecialOperandAttr(MachineInstr &OldMI1, MachineInstr &OldMI2,
1450 MachineInstr &NewMI1,
1451 MachineInstr &NewMI2) const {}
1452
1453 /// Return true when a target supports MachineCombiner.
1454 virtual bool useMachineCombiner() const { return false; }
1455
1456 /// Return a strategy that MachineCombiner must use when creating traces.
1457 virtual MachineTraceStrategy getMachineCombinerTraceStrategy() const;
1458
1459 /// Return true if the given SDNode can be copied during scheduling
1460 /// even if it has glue.
1461 virtual bool canCopyGluedNodeDuringSchedule(SDNode *N) const { return false; }
1462
1463protected:
1464 /// Target-dependent implementation for foldMemoryOperand.
1465 /// Target-independent code in foldMemoryOperand will
1466 /// take care of adding a MachineMemOperand to the newly created instruction.
1467 /// The instruction and any auxiliary instructions necessary will be inserted
1468 /// at MI.
1469 virtual MachineInstr *
1471 ArrayRef<unsigned> Ops, int FrameIndex,
1472 MachineInstr *&CopyMI, LiveIntervals *LIS = nullptr,
1473 VirtRegMap *VRM = nullptr) const {
1474 return nullptr;
1475 }
1476
1477 /// Target-dependent implementation for foldMemoryOperand.
1478 /// Target-independent code in foldMemoryOperand will
1479 /// take care of adding a MachineMemOperand to the newly created instruction.
1480 /// The instruction and any auxiliary instructions necessary will be inserted
1481 /// at MI.
1482 virtual MachineInstr *
1485 MachineInstr *&CopyMI, LiveIntervals *LIS = nullptr,
1486 VirtRegMap *VRM = nullptr) const {
1487 return nullptr;
1488 }
1489
1490 /// Target-dependent implementation of getRegSequenceInputs.
1491 ///
1492 /// \returns true if it is possible to build the equivalent
1493 /// REG_SEQUENCE inputs with the pair \p MI, \p DefIdx. False otherwise.
1494 ///
1495 /// \pre MI.isRegSequenceLike().
1496 ///
1497 /// \see TargetInstrInfo::getRegSequenceInputs.
1499 const MachineInstr &MI, unsigned DefIdx,
1500 SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const {
1501 return false;
1502 }
1503
1504 /// Target-dependent implementation of getExtractSubregInputs.
1505 ///
1506 /// \returns true if it is possible to build the equivalent
1507 /// EXTRACT_SUBREG inputs with the pair \p MI, \p DefIdx. False otherwise.
1508 ///
1509 /// \pre MI.isExtractSubregLike().
1510 ///
1511 /// \see TargetInstrInfo::getExtractSubregInputs.
1513 unsigned DefIdx,
1514 RegSubRegPairAndIdx &InputReg) const {
1515 return false;
1516 }
1517
1518 /// Target-dependent implementation of getInsertSubregInputs.
1519 ///
1520 /// \returns true if it is possible to build the equivalent
1521 /// INSERT_SUBREG inputs with the pair \p MI, \p DefIdx. False otherwise.
1522 ///
1523 /// \pre MI.isInsertSubregLike().
1524 ///
1525 /// \see TargetInstrInfo::getInsertSubregInputs.
1526 virtual bool
1528 RegSubRegPair &BaseReg,
1529 RegSubRegPairAndIdx &InsertedReg) const {
1530 return false;
1531 }
1532
1533public:
1534 /// unfoldMemoryOperand - Separate a single instruction which folded a load or
1535 /// a store or a load and a store into two or more instruction. If this is
1536 /// possible, returns true as well as the new instructions by reference.
1537 virtual bool
1539 bool UnfoldLoad, bool UnfoldStore,
1540 SmallVectorImpl<MachineInstr *> &NewMIs) const {
1541 return false;
1542 }
1543
1545 SmallVectorImpl<SDNode *> &NewNodes) const {
1546 return false;
1547 }
1548
1549 /// Returns the opcode of the would be new
1550 /// instruction after load / store are unfolded from an instruction of the
1551 /// specified opcode. It returns zero if the specified unfolding is not
1552 /// possible. If LoadRegIndex is non-null, it is filled in with the operand
1553 /// index of the operand which will hold the register holding the loaded
1554 /// value.
1555 virtual unsigned
1556 getOpcodeAfterMemoryUnfold(unsigned Opc, bool UnfoldLoad, bool UnfoldStore,
1557 unsigned *LoadRegIndex = nullptr) const {
1558 return 0;
1559 }
1560
1561 /// This is used by the pre-regalloc scheduler to determine if two loads are
1562 /// loading from the same base address. It should only return true if the base
1563 /// pointers are the same and the only differences between the two addresses
1564 /// are the offset. It also returns the offsets by reference.
1565 virtual bool areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2,
1566 int64_t &Offset1,
1567 int64_t &Offset2) const {
1568 return false;
1569 }
1570
1571 /// This is a used by the pre-regalloc scheduler to determine (in conjunction
1572 /// with areLoadsFromSameBasePtr) if two loads should be scheduled together.
1573 /// On some targets if two loads are loading from
1574 /// addresses in the same cache line, it's better if they are scheduled
1575 /// together. This function takes two integers that represent the load offsets
1576 /// from the common base address. It returns true if it decides it's desirable
1577 /// to schedule the two loads together. "NumLoads" is the number of loads that
1578 /// have already been scheduled after Load1.
1579 virtual bool shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
1580 int64_t Offset1, int64_t Offset2,
1581 unsigned NumLoads) const {
1582 return false;
1583 }
1584
1585 /// Get the base operand and byte offset of an instruction that reads/writes
1586 /// memory. This is a convenience function for callers that are only prepared
1587 /// to handle a single base operand.
1588 /// FIXME: Move Offset and OffsetIsScalable to some ElementCount-style
1589 /// abstraction that supports negative offsets.
1590 bool getMemOperandWithOffset(const MachineInstr &MI,
1591 const MachineOperand *&BaseOp, int64_t &Offset,
1592 bool &OffsetIsScalable,
1593 const TargetRegisterInfo *TRI) const;
1594
1595 /// Get zero or more base operands and the byte offset of an instruction that
1596 /// reads/writes memory. Note that there may be zero base operands if the
1597 /// instruction accesses a constant address.
1598 /// It returns false if MI does not read/write memory.
1599 /// It returns false if base operands and offset could not be determined.
1600 /// It is not guaranteed to always recognize base operands and offsets in all
1601 /// cases.
1602 /// FIXME: Move Offset and OffsetIsScalable to some ElementCount-style
1603 /// abstraction that supports negative offsets.
1606 int64_t &Offset, bool &OffsetIsScalable, LocationSize &Width,
1607 const TargetRegisterInfo *TRI) const {
1608 return false;
1609 }
1610
1611 /// Return true if the instruction contains a base register and offset. If
1612 /// true, the function also sets the operand position in the instruction
1613 /// for the base register and offset.
1615 unsigned &BasePos,
1616 unsigned &OffsetPos) const {
1617 return false;
1618 }
1619
1620 /// Target dependent implementation to get the values constituting the address
1621 /// MachineInstr that is accessing memory. These values are returned as a
1622 /// struct ExtAddrMode which contains all relevant information to make up the
1623 /// address.
1624 virtual std::optional<ExtAddrMode>
1626 const TargetRegisterInfo *TRI) const {
1627 return std::nullopt;
1628 }
1629
1630 /// Check if it's possible and beneficial to fold the addressing computation
1631 /// `AddrI` into the addressing mode of the load/store instruction `MemI`. The
1632 /// memory instruction is a user of the virtual register `Reg`, which in turn
1633 /// is the ultimate destination of zero or more COPY instructions from the
1634 /// output register of `AddrI`.
1635 /// Return the adddressing mode after folding in `AM`.
1637 const MachineInstr &AddrI,
1638 ExtAddrMode &AM) const {
1639 return false;
1640 }
1641
1642 /// Emit a load/store instruction with the same value register as `MemI`, but
1643 /// using the address from `AM`. The addressing mode must have been obtained
1644 /// from `canFoldIntoAddr` for the same memory instruction.
1646 const ExtAddrMode &AM) const {
1647 llvm_unreachable("target did not implement emitLdStWithAddr()");
1648 }
1649
1650 /// Returns true if MI's Def is NullValueReg, and the MI
1651 /// does not change the Zero value. i.e. cases such as rax = shr rax, X where
1652 /// NullValueReg = rax. Note that if the NullValueReg is non-zero, this
1653 /// function can return true even if becomes zero. Specifically cases such as
1654 /// NullValueReg = shl NullValueReg, 63.
1656 const Register NullValueReg,
1657 const TargetRegisterInfo *TRI) const {
1658 return false;
1659 }
1660
1661 /// If the instruction is an increment of a constant value, return the amount.
1662 virtual bool getIncrementValue(const MachineInstr &MI, int &Value) const {
1663 return false;
1664 }
1665
1666 /// Returns true if the two given memory operations should be scheduled
1667 /// adjacent. Note that you have to add:
1668 /// DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
1669 /// or
1670 /// DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
1671 /// to TargetMachine::createMachineScheduler() to have an effect.
1672 ///
1673 /// \p BaseOps1 and \p BaseOps2 are memory operands of two memory operations.
1674 /// \p Offset1 and \p Offset2 are the byte offsets for the memory
1675 /// operations.
1676 /// \p OffsetIsScalable1 and \p OffsetIsScalable2 indicate if the offset is
1677 /// scaled by a runtime quantity.
1678 /// \p ClusterSize is the number of operations in the resulting load/store
1679 /// cluster if this hook returns true.
1680 /// \p NumBytes is the number of bytes that will be loaded from all the
1681 /// clustered loads if this hook returns true.
1683 int64_t Offset1, bool OffsetIsScalable1,
1685 int64_t Offset2, bool OffsetIsScalable2,
1686 unsigned ClusterSize,
1687 unsigned NumBytes) const {
1688 llvm_unreachable("target did not implement shouldClusterMemOps()");
1689 }
1690
1691 /// Reverses the branch condition of the specified condition list,
1692 /// returning false on success and true if it cannot be reversed.
1693 virtual bool
1697
1698 /// Insert a noop into the instruction stream at the specified point.
1699 virtual void insertNoop(MachineBasicBlock &MBB,
1701
1702 /// Insert noops into the instruction stream at the specified point.
1703 virtual void insertNoops(MachineBasicBlock &MBB,
1705 unsigned Quantity) const;
1706
1707 /// Return the noop instruction to use for a noop.
1708 virtual MCInst getNop() const;
1709
1710 /// Return true for post-incremented instructions.
1711 virtual bool isPostIncrement(const MachineInstr &MI) const { return false; }
1712
1713 /// Returns true if the instruction is already predicated.
1714 virtual bool isPredicated(const MachineInstr &MI) const { return false; }
1715
1716 /// Assumes the instruction is already predicated and returns true if the
1717 /// instruction can be predicated again.
1718 virtual bool canPredicatePredicatedInstr(const MachineInstr &MI) const {
1719 assert(isPredicated(MI) && "Instruction is not predicated");
1720 return false;
1721 }
1722
1723 // Returns a MIRPrinter comment for this machine operand.
1724 virtual std::string
1725 createMIROperandComment(const MachineInstr &MI, const MachineOperand &Op,
1726 unsigned OpIdx, const TargetRegisterInfo *TRI) const;
1727
1728 /// Returns true if the instruction is a
1729 /// terminator instruction that has not been predicated.
1730 bool isUnpredicatedTerminator(const MachineInstr &MI) const;
1731
1732 /// Returns true if MI is an unconditional tail call.
1733 virtual bool isUnconditionalTailCall(const MachineInstr &MI) const {
1734 return false;
1735 }
1736
1737 /// Returns true if the tail call can be made conditional on BranchCond.
1739 const MachineInstr &TailCall) const {
1740 return false;
1741 }
1742
1743 /// Replace the conditional branch in MBB with a conditional tail call.
1746 const MachineInstr &TailCall) const {
1747 llvm_unreachable("Target didn't implement replaceBranchWithTailCall!");
1748 }
1749
1750 /// Convert the instruction into a predicated instruction.
1751 /// It returns true if the operation was successful.
1752 virtual bool PredicateInstruction(MachineInstr &MI,
1753 ArrayRef<MachineOperand> Pred) const;
1754
1755 /// Returns true if the first specified predicate
1756 /// subsumes the second, e.g. GE subsumes GT.
1758 ArrayRef<MachineOperand> Pred2) const {
1759 return false;
1760 }
1761
1762 /// If the specified instruction defines any predicate
1763 /// or condition code register(s) used for predication, returns true as well
1764 /// as the definition predicate(s) by reference.
1765 /// SkipDead should be set to false at any point that dead
1766 /// predicate instructions should be considered as being defined.
1767 /// A dead predicate instruction is one that is guaranteed to be removed
1768 /// after a call to PredicateInstruction.
1770 std::vector<MachineOperand> &Pred,
1771 bool SkipDead) const {
1772 return false;
1773 }
1774
1775 /// Return true if the specified instruction can be predicated.
1776 /// By default, this returns true for every instruction with a
1777 /// PredicateOperand.
1778 virtual bool isPredicable(const MachineInstr &MI) const {
1779 return MI.getDesc().isPredicable();
1780 }
1781
1782 /// Return true if it's safe to move a machine
1783 /// instruction that defines the specified register class.
1784 virtual bool isSafeToMoveRegClassDefs(const TargetRegisterClass *RC) const {
1785 return true;
1786 }
1787
1788 /// Return true if it's safe to move a machine instruction.
1789 /// This allows the backend to prevent certain special instruction
1790 /// sequences from being broken by instruction motion in optimization
1791 /// passes.
1792 /// By default, this returns true for every instruction.
1793 virtual bool isSafeToMove(const MachineInstr &MI,
1794 const MachineBasicBlock *MBB,
1795 const MachineFunction &MF) const {
1796 return true;
1797 }
1798
1799 /// Test if the given instruction should be considered a scheduling boundary.
1800 /// This primarily includes labels and terminators.
1801 virtual bool isSchedulingBoundary(const MachineInstr &MI,
1802 const MachineBasicBlock *MBB,
1803 const MachineFunction &MF) const;
1804
1805 /// Measure the specified inline asm to determine an approximation of its
1806 /// length.
1807 virtual unsigned getInlineAsmLength(
1808 const char *Str, const MCAsmInfo &MAI,
1809 const TargetSubtargetInfo *STI = nullptr) const;
1810
1811 /// Allocate and return a hazard recognizer to use for this target when
1812 /// scheduling the machine instructions before register allocation.
1813 virtual ScheduleHazardRecognizer *
1814 CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
1815 const ScheduleDAG *DAG) const;
1816
1817 /// Allocate and return a hazard recognizer to use for this target when
1818 /// scheduling the machine instructions before register allocation.
1819 virtual ScheduleHazardRecognizer *
1820 CreateTargetMIHazardRecognizer(const InstrItineraryData *,
1821 const ScheduleDAGMI *DAG) const;
1822
1823 /// Allocate and return a hazard recognizer to use for this target when
1824 /// scheduling the machine instructions after register allocation.
1825 virtual ScheduleHazardRecognizer *
1826 CreateTargetPostRAHazardRecognizer(const InstrItineraryData *,
1827 const ScheduleDAG *DAG) const;
1828
1829 /// Allocate and return a hazard recognizer to use for by non-scheduling
1830 /// passes.
1831 virtual ScheduleHazardRecognizer *
1833 MachineLoopInfo *MLI) const {
1834 return nullptr;
1835 }
1836
1837 /// Provide a global flag for disabling the PreRA hazard recognizer that
1838 /// targets may choose to honor.
1839 bool usePreRAHazardRecognizer() const;
1840
1841 /// For a comparison instruction, return the source registers
1842 /// in SrcReg and SrcReg2 if having two register operands, and the value it
1843 /// compares against in CmpValue. Return true if the comparison instruction
1844 /// can be analyzed.
1845 virtual bool analyzeCompare(const MachineInstr &MI, Register &SrcReg,
1846 Register &SrcReg2, int64_t &Mask,
1847 int64_t &Value) const {
1848 return false;
1849 }
1850
1851 /// See if the comparison instruction can be converted
1852 /// into something more efficient. E.g., on ARM most instructions can set the
1853 /// flags register, obviating the need for a separate CMP.
1854 virtual bool optimizeCompareInstr(MachineInstr &CmpInstr, Register SrcReg,
1855 Register SrcReg2, int64_t Mask,
1856 int64_t Value,
1857 const MachineRegisterInfo *MRI) const {
1858 return false;
1859 }
1860 virtual bool optimizeCondBranch(MachineInstr &MI) const { return false; }
1861
1862 /// Try to remove the load by folding it to a register operand at the use.
1863 /// We fold the load instructions if and only if the
1864 /// def and use are in the same BB. We only look at one load and see
1865 /// whether it can be folded into MI. FoldAsLoadDefReg is the virtual register
1866 /// defined by the load we are trying to fold. DefMI returns the machine
1867 /// instruction that defines FoldAsLoadDefReg, and the function returns
1868 /// the machine instruction generated due to folding. CopyMI returns the
1869 /// copy instruction possibly generated due to folding.
1870 virtual MachineInstr *optimizeLoadInstr(MachineInstr &MI,
1871 const MachineRegisterInfo *MRI,
1872 Register &FoldAsLoadDefReg,
1874 MachineInstr *&CopyMI) const;
1875
1876 /// 'Reg' is known to be defined by a move immediate instruction,
1877 /// try to fold the immediate into the use instruction.
1878 /// If MRI->hasOneNonDBGUse(Reg) is true, and this function returns true,
1879 /// then the caller may assume that DefMI has been erased from its parent
1880 /// block. The caller may assume that it will not be erased by this
1881 /// function otherwise.
1883 Register Reg, MachineRegisterInfo *MRI) const {
1884 return false;
1885 }
1886
1887 /// Return the number of u-operations the given machine
1888 /// instruction will be decoded to on the target cpu. The itinerary's
1889 /// IssueWidth is the number of microops that can be dispatched each
1890 /// cycle. An instruction with zero microops takes no dispatch resources.
1891 virtual unsigned getNumMicroOps(const InstrItineraryData *ItinData,
1892 const MachineInstr &MI) const;
1893
1894 /// Return true for pseudo instructions that don't consume any
1895 /// machine resources in their current form. These are common cases that the
1896 /// scheduler should consider free, rather than conservatively handling them
1897 /// as instructions with no itinerary.
1898 bool isZeroCost(unsigned Opcode) const {
1899 return Opcode <= TargetOpcode::COPY;
1900 }
1901
1902 virtual std::optional<unsigned>
1903 getOperandLatency(const InstrItineraryData *ItinData, SDNode *DefNode,
1904 unsigned DefIdx, SDNode *UseNode, unsigned UseIdx) const;
1905
1906 /// Compute and return the use operand latency of a given pair of def and use.
1907 /// In most cases, the static scheduling itinerary was enough to determine the
1908 /// operand latency. But it may not be possible for instructions with variable
1909 /// number of defs / uses.
1910 ///
1911 /// This is a raw interface to the itinerary that may be directly overridden
1912 /// by a target. Use computeOperandLatency to get the best estimate of
1913 /// latency.
1914 virtual std::optional<unsigned>
1915 getOperandLatency(const InstrItineraryData *ItinData,
1916 const MachineInstr &DefMI, unsigned DefIdx,
1917 const MachineInstr &UseMI, unsigned UseIdx) const;
1918
1919 /// Compute the instruction latency of a given instruction.
1920 /// If the instruction has higher cost when predicated, it's returned via
1921 /// PredCost.
1922 virtual unsigned getInstrLatency(const InstrItineraryData *ItinData,
1923 const MachineInstr &MI,
1924 unsigned *PredCost = nullptr) const;
1925
1926 virtual unsigned getPredicationCost(const MachineInstr &MI) const;
1927
1928 virtual unsigned getInstrLatency(const InstrItineraryData *ItinData,
1929 SDNode *Node) const;
1930
1931 /// Return the default expected latency for a def based on its opcode.
1932 unsigned defaultDefLatency(const TargetSubtargetInfo &STI,
1933 const MCSchedModel &SchedModel,
1934 const MachineInstr &DefMI) const;
1935
1936 /// Return true if this opcode has high latency to its result.
1937 virtual bool isHighLatencyDef(int opc) const { return false; }
1938
1939 /// Compute operand latency between a def of 'Reg'
1940 /// and a use in the current loop. Return true if the target considered
1941 /// it 'high'. This is used by optimization passes such as machine LICM to
1942 /// determine whether it makes sense to hoist an instruction out even in a
1943 /// high register pressure situation.
1944 virtual bool hasHighOperandLatency(const TargetSchedModel &SchedModel,
1945 const MachineRegisterInfo *MRI,
1946 const MachineInstr &DefMI, unsigned DefIdx,
1947 const MachineInstr &UseMI,
1948 unsigned UseIdx) const {
1949 return false;
1950 }
1951
1952 /// Compute operand latency of a def of 'Reg'. Return true
1953 /// if the target considered it 'low'.
1954 virtual bool hasLowDefLatency(const TargetSchedModel &SchedModel,
1955 const MachineInstr &DefMI,
1956 unsigned DefIdx) const;
1957
1958 /// Perform target-specific instruction verification.
1959 virtual bool verifyInstruction(const MachineInstr &MI,
1960 StringRef &ErrInfo) const {
1961 return true;
1962 }
1963
1964 /// Return the current execution domain and bit mask of
1965 /// possible domains for instruction.
1966 ///
1967 /// Some micro-architectures have multiple execution domains, and multiple
1968 /// opcodes that perform the same operation in different domains. For
1969 /// example, the x86 architecture provides the por, orps, and orpd
1970 /// instructions that all do the same thing. There is a latency penalty if a
1971 /// register is written in one domain and read in another.
1972 ///
1973 /// This function returns a pair (domain, mask) containing the execution
1974 /// domain of MI, and a bit mask of possible domains. The setExecutionDomain
1975 /// function can be used to change the opcode to one of the domains in the
1976 /// bit mask. Instructions whose execution domain can't be changed should
1977 /// return a 0 mask.
1978 ///
1979 /// The execution domain numbers don't have any special meaning except domain
1980 /// 0 is used for instructions that are not associated with any interesting
1981 /// execution domain.
1982 ///
1983 virtual std::pair<uint16_t, uint16_t>
1985 return std::make_pair(0, 0);
1986 }
1987
1988 /// Change the opcode of MI to execute in Domain.
1989 ///
1990 /// The bit (1 << Domain) must be set in the mask returned from
1991 /// getExecutionDomain(MI).
1992 virtual void setExecutionDomain(MachineInstr &MI, unsigned Domain) const {}
1993
1994 /// Returns the preferred minimum clearance
1995 /// before an instruction with an unwanted partial register update.
1996 ///
1997 /// Some instructions only write part of a register, and implicitly need to
1998 /// read the other parts of the register. This may cause unwanted stalls
1999 /// preventing otherwise unrelated instructions from executing in parallel in
2000 /// an out-of-order CPU.
2001 ///
2002 /// For example, the x86 instruction cvtsi2ss writes its result to bits
2003 /// [31:0] of the destination xmm register. Bits [127:32] are unaffected, so
2004 /// the instruction needs to wait for the old value of the register to become
2005 /// available:
2006 ///
2007 /// addps %xmm1, %xmm0
2008 /// movaps %xmm0, (%rax)
2009 /// cvtsi2ss %rbx, %xmm0
2010 ///
2011 /// In the code above, the cvtsi2ss instruction needs to wait for the addps
2012 /// instruction before it can issue, even though the high bits of %xmm0
2013 /// probably aren't needed.
2014 ///
2015 /// This hook returns the preferred clearance before MI, measured in
2016 /// instructions. Other defs of MI's operand OpNum are avoided in the last N
2017 /// instructions before MI. It should only return a positive value for
2018 /// unwanted dependencies. If the old bits of the defined register have
2019 /// useful values, or if MI is determined to otherwise read the dependency,
2020 /// the hook should return 0.
2021 ///
2022 /// The unwanted dependency may be handled by:
2023 ///
2024 /// 1. Allocating the same register for an MI def and use. That makes the
2025 /// unwanted dependency identical to a required dependency.
2026 ///
2027 /// 2. Allocating a register for the def that has no defs in the previous N
2028 /// instructions.
2029 ///
2030 /// 3. Calling breakPartialRegDependency() with the same arguments. This
2031 /// allows the target to insert a dependency breaking instruction.
2032 ///
2033 virtual unsigned
2035 const TargetRegisterInfo *TRI) const {
2036 // The default implementation returns 0 for no partial register dependency.
2037 return 0;
2038 }
2039
2040 /// Return the minimum clearance before an instruction that reads an
2041 /// unused register.
2042 ///
2043 /// For example, AVX instructions may copy part of a register operand into
2044 /// the unused high bits of the destination register.
2045 ///
2046 /// vcvtsi2sdq %rax, undef %xmm0, %xmm14
2047 ///
2048 /// In the code above, vcvtsi2sdq copies %xmm0[127:64] into %xmm14 creating a
2049 /// false dependence on any previous write to %xmm0.
2050 ///
2051 /// This hook works similarly to getPartialRegUpdateClearance, except that it
2052 /// does not take an operand index. Instead sets \p OpNum to the index of the
2053 /// unused register.
2054 virtual unsigned getUndefRegClearance(const MachineInstr &MI, unsigned OpNum,
2055 const TargetRegisterInfo *TRI) const {
2056 // The default implementation returns 0 for no undef register dependency.
2057 return 0;
2058 }
2059
2060 /// Insert a dependency-breaking instruction
2061 /// before MI to eliminate an unwanted dependency on OpNum.
2062 ///
2063 /// If it wasn't possible to avoid a def in the last N instructions before MI
2064 /// (see getPartialRegUpdateClearance), this hook will be called to break the
2065 /// unwanted dependency.
2066 ///
2067 /// On x86, an xorps instruction can be used as a dependency breaker:
2068 ///
2069 /// addps %xmm1, %xmm0
2070 /// movaps %xmm0, (%rax)
2071 /// xorps %xmm0, %xmm0
2072 /// cvtsi2ss %rbx, %xmm0
2073 ///
2074 /// An <imp-kill> operand should be added to MI if an instruction was
2075 /// inserted. This ties the instructions together in the post-ra scheduler.
2076 ///
2077 virtual void breakPartialRegDependency(MachineInstr &MI, unsigned OpNum,
2078 const TargetRegisterInfo *TRI) const {}
2079
2080 /// Create machine specific model for scheduling.
2081 virtual DFAPacketizer *
2083 return nullptr;
2084 }
2085
2086 /// Sometimes, it is possible for the target
2087 /// to tell, even without aliasing information, that two MIs access different
2088 /// memory addresses. This function returns true if two MIs access different
2089 /// memory addresses and false otherwise.
2090 ///
2091 /// Assumes any physical registers used to compute addresses have the same
2092 /// value for both instructions. (This is the most useful assumption for
2093 /// post-RA scheduling.)
2094 ///
2095 /// See also MachineInstr::mayAlias, which is implemented on top of this
2096 /// function.
2097 virtual bool
2099 const MachineInstr &MIb) const {
2100 assert(MIa.mayLoadOrStore() &&
2101 "MIa must load from or modify a memory location");
2102 assert(MIb.mayLoadOrStore() &&
2103 "MIb must load from or modify a memory location");
2104 return false;
2105 }
2106
2107 /// Return the value to use for the MachineCSE's LookAheadLimit,
2108 /// which is a heuristic used for CSE'ing phys reg defs.
2109 virtual unsigned getMachineCSELookAheadLimit() const {
2110 // The default lookahead is small to prevent unprofitable quadratic
2111 // behavior.
2112 return 5;
2113 }
2114
2115 /// Return the maximal number of alias checks on memory operands. For
2116 /// instructions with more than one memory operands, the alias check on a
2117 /// single MachineInstr pair has quadratic overhead and results in
2118 /// unacceptable performance in the worst case. The limit here is to clamp
2119 /// that maximal checks performed. Usually, that's the product of memory
2120 /// operand numbers from that pair of MachineInstr to be checked. For
2121 /// instance, with two MachineInstrs with 4 and 5 memory operands
2122 /// correspondingly, a total of 20 checks are required. With this limit set to
2123 /// 16, their alias check is skipped. We choose to limit the product instead
2124 /// of the individual instruction as targets may have special MachineInstrs
2125 /// with a considerably high number of memory operands, such as `ldm` in ARM.
2126 /// Setting this limit per MachineInstr would result in either too high
2127 /// overhead or too rigid restriction.
2128 virtual unsigned getMemOperandAACheckLimit() const { return 16; }
2129
2130 /// Return an array that contains the ids of the target indices (used for the
2131 /// TargetIndex machine operand) and their names.
2132 ///
2133 /// MIR Serialization is able to serialize only the target indices that are
2134 /// defined by this method.
2137 return {};
2138 }
2139
2140 /// Decompose the machine operand's target flags into two values - the direct
2141 /// target flag value and any of bit flags that are applied.
2142 virtual std::pair<unsigned, unsigned>
2144 return std::make_pair(0u, 0u);
2145 }
2146
2147 /// Return an array that contains the direct target flag values and their
2148 /// names.
2149 ///
2150 /// MIR Serialization is able to serialize only the target flags that are
2151 /// defined by this method.
2154 return {};
2155 }
2156
2157 /// Return an array that contains the bitmask target flag values and their
2158 /// names.
2159 ///
2160 /// MIR Serialization is able to serialize only the target flags that are
2161 /// defined by this method.
2164 return {};
2165 }
2166
2167 /// Return an array that contains the MMO target flag values and their
2168 /// names.
2169 ///
2170 /// MIR Serialization is able to serialize only the MMO target flags that are
2171 /// defined by this method.
2174 return {};
2175 }
2176
2177 /// Determines whether \p Inst is a tail call instruction. Override this
2178 /// method on targets that do not properly set MCID::Return and MCID::Call on
2179 /// tail call instructions."
2180 virtual bool isTailCall(const MachineInstr &Inst) const {
2181 return Inst.isReturn() && Inst.isCall();
2182 }
2183
2184 /// True if the instruction is bound to the top of its basic block and no
2185 /// other instructions shall be inserted before it. This can be implemented
2186 /// to prevent register allocator to insert spills for \p Reg before such
2187 /// instructions.
2189 Register Reg = Register()) const {
2190 return false;
2191 }
2192
2193 /// Allows targets to use appropriate copy instruction while spilitting live
2194 /// range of a register in register allocation.
2196 const MachineFunction &MF) const {
2197 return TargetOpcode::COPY;
2198 }
2199
2200 /// During PHI eleimination lets target to make necessary checks and
2201 /// insert the copy to the PHI destination register in a target specific
2202 /// manner.
2205 const DebugLoc &DL, Register Src, Register Dst) const {
2206 return BuildMI(MBB, InsPt, DL, get(TargetOpcode::COPY), Dst)
2207 .addReg(Src);
2208 }
2209
2210 /// During PHI eleimination lets target to make necessary checks and
2211 /// insert the copy to the PHI destination register in a target specific
2212 /// manner.
2215 const DebugLoc &DL, Register Src,
2216 unsigned SrcSubReg,
2217 Register Dst) const {
2218 return BuildMI(MBB, InsPt, DL, get(TargetOpcode::COPY), Dst)
2219 .addReg(Src, {}, SrcSubReg);
2220 }
2221
2222 /// Returns a \p outliner::OutlinedFunction struct containing target-specific
2223 /// information for a set of outlining candidates. Returns std::nullopt if the
2224 /// candidates are not suitable for outlining. \p MinRepeats is the minimum
2225 /// number of times the instruction sequence must be repeated.
2226 virtual std::optional<std::unique_ptr<outliner::OutlinedFunction>>
2228 const MachineModuleInfo &MMI,
2229 std::vector<outliner::Candidate> &RepeatedSequenceLocs,
2230 unsigned MinRepeats) const {
2232 "Target didn't implement TargetInstrInfo::getOutliningCandidateInfo!");
2233 }
2234
2235 /// Optional target hook to create the LLVM IR attributes for the outlined
2236 /// function. If overridden, the overriding function must call the default
2237 /// implementation.
2238 virtual void mergeOutliningCandidateAttributes(
2239 Function &F, std::vector<outliner::Candidate> &Candidates) const;
2240
2241protected:
2242 /// Target-dependent implementation for getOutliningTypeImpl.
2243 virtual outliner::InstrType
2245 MachineBasicBlock::iterator &MIT, unsigned Flags) const {
2247 "Target didn't implement TargetInstrInfo::getOutliningTypeImpl!");
2248 }
2249
2250public:
2251 /// Returns how or if \p MIT should be outlined. \p Flags is the
2252 /// target-specific information returned by isMBBSafeToOutlineFrom.
2253 outliner::InstrType getOutliningType(const MachineModuleInfo &MMI,
2255 unsigned Flags) const;
2256
2257 /// Optional target hook that returns true if \p MBB is safe to outline from,
2258 /// and returns any target-specific information in \p Flags.
2259 virtual bool isMBBSafeToOutlineFrom(MachineBasicBlock &MBB,
2260 unsigned &Flags) const;
2261
2262 /// Optional target hook which partitions \p MBB into outlinable ranges for
2263 /// instruction mapping purposes. Each range is defined by two iterators:
2264 /// [start, end).
2265 ///
2266 /// Ranges are expected to be ordered top-down. That is, ranges closer to the
2267 /// top of the block should come before ranges closer to the end of the block.
2268 ///
2269 /// Ranges cannot overlap.
2270 ///
2271 /// If an entire block is mappable, then its range is [MBB.begin(), MBB.end())
2272 ///
2273 /// All non-debug instructions not present in an outlinable range are
2274 /// considered illegal. Debug instructions are ignored wherever they appear,
2275 /// so each gap between ranges must contain a non-debug instruction.
2276 virtual SmallVector<
2277 std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator>>
2278 getOutlinableRanges(MachineBasicBlock &MBB, unsigned &Flags) const {
2279 return {std::make_pair(MBB.begin(), MBB.end())};
2280 }
2281
2282 /// Insert a custom frame for outlined functions.
2284 const outliner::OutlinedFunction &OF) const {
2286 "Target didn't implement TargetInstrInfo::buildOutlinedFrame!");
2287 }
2288
2289 /// Insert a call to an outlined function into the program.
2290 /// Returns an iterator to the spot where we inserted the call. This must be
2291 /// implemented by the target.
2295 outliner::Candidate &C) const {
2297 "Target didn't implement TargetInstrInfo::insertOutlinedCall!");
2298 }
2299
2300 /// Insert an architecture-specific instruction to clear a register. If you
2301 /// need to avoid sideeffects (e.g. avoid XOR on x86, which sets EFLAGS), set
2302 /// \p AllowSideEffects to \p false.
2305 DebugLoc &DL,
2306 bool AllowSideEffects = true) const {
2308 "Target didn't implement TargetInstrInfo::buildClearRegister!");
2309 }
2310
2311 /// Return true if the function can safely be outlined from.
2312 /// A function \p MF is considered safe for outlining if an outlined function
2313 /// produced from instructions in F will produce a program which produces the
2314 /// same output for any set of given inputs.
2316 bool OutlineFromLinkOnceODRs) const {
2317 llvm_unreachable("Target didn't implement "
2318 "TargetInstrInfo::isFunctionSafeToOutlineFrom!");
2319 }
2320
2321 /// Return true if the function should be outlined from by default.
2323 return false;
2324 }
2325
2326 /// Return true if the function is a viable candidate for machine function
2327 /// splitting. The criteria for if a function can be split may vary by target.
2328 virtual bool isFunctionSafeToSplit(const MachineFunction &MF) const;
2329
2330 /// Return true if the MachineBasicBlock can safely be split to the cold
2331 /// section. On AArch64, certain instructions may cause a block to be unsafe
2332 /// to split to the cold section.
2333 virtual bool isMBBSafeToSplitToCold(const MachineBasicBlock &MBB) const {
2334 return true;
2335 }
2336
2337 /// Produce the expression describing the \p MI loading a value into
2338 /// the physical register \p Reg. This hook should only be used with
2339 /// \p MIs belonging to VReg-less functions.
2340 virtual std::optional<ParamLoadedValue>
2341 describeLoadedValue(const MachineInstr &MI, Register Reg) const;
2342
2343 /// Given the generic extension instruction \p ExtMI, returns true if this
2344 /// extension is a likely candidate for being folded into an another
2345 /// instruction.
2347 MachineRegisterInfo &MRI) const {
2348 return false;
2349 }
2350
2351 /// Return MIR formatter to format/parse MIR operands. Target can override
2352 /// this virtual function and return target specific MIR formatter.
2353 virtual const MIRFormatter *getMIRFormatter() const {
2354 if (!Formatter)
2355 Formatter = std::make_unique<MIRFormatter>();
2356 return Formatter.get();
2357 }
2358
2359 /// Returns the target-specific default value for tail duplication.
2360 /// This value will be used if the tail-dup-placement-threshold argument is
2361 /// not provided.
2362 virtual unsigned getTailDuplicateSize(CodeGenOptLevel OptLevel) const {
2363 return OptLevel >= CodeGenOptLevel::Aggressive ? 4 : 2;
2364 }
2365
2366 /// Returns the target-specific default value for tail merging.
2367 /// This value will be used if the tail-merge-size argument is not provided.
2368 virtual unsigned getTailMergeSize(const MachineFunction &MF) const {
2369 return 3;
2370 }
2371
2372 /// Returns the callee operand from the given \p MI.
2373 virtual const MachineOperand &getCalleeOperand(const MachineInstr &MI) const {
2374 assert(MI.isCall());
2375
2376 switch (MI.getOpcode()) {
2377 case TargetOpcode::STATEPOINT:
2378 case TargetOpcode::STACKMAP:
2379 case TargetOpcode::PATCHPOINT:
2380 return MI.getOperand(3);
2381 default:
2382 return MI.getOperand(0);
2383 }
2384
2385 llvm_unreachable("impossible call instruction");
2386 }
2387
2388 /// Return the uniformity behavior of the given value.
2392
2393 /// Returns true if the given \p MI defines a TargetIndex operand that can be
2394 /// tracked by their offset, can have values, and can have debug info
2395 /// associated with it. If so, sets \p Index and \p Offset of the target index
2396 /// operand.
2397 virtual bool isExplicitTargetIndexDef(const MachineInstr &MI, int &Index,
2398 int64_t &Offset) const {
2399 return false;
2400 }
2401
2402 // Get the call frame size just before MI.
2403 unsigned getCallFrameSizeAt(MachineInstr &MI) const;
2404
2405 /// Fills in the necessary MachineOperands to refer to a frame index.
2406 /// The best way to understand this is to print `asm(""::"m"(x));` after
2407 /// finalize-isel. Example:
2408 /// INLINEASM ... 262190 /* mem:m */, %stack.0.x.addr, 1, $noreg, 0, $noreg
2409 /// we would add placeholders for: ^ ^ ^ ^
2411 int FI) const {
2412 llvm_unreachable("unknown number of operands necessary");
2413 }
2414
2415 /// Inserts a code prefetch instruction before `InsertBefore` in block `MBB`
2416 /// targetting `GV`.
2417 virtual MachineInstr *
2419 MachineBasicBlock::iterator InsertBefore,
2420 const GlobalValue *GV) const {
2421 llvm_unreachable("target did not implement");
2422 }
2423
2424private:
2425 mutable std::unique_ptr<MIRFormatter> Formatter;
2426 unsigned CallFrameSetupOpcode, CallFrameDestroyOpcode;
2427 unsigned CatchRetOpcode;
2428 unsigned ReturnOpcode;
2429};
2430
2431/// Provide DenseMapInfo for TargetInstrInfo::RegSubRegPair.
2435
2436 /// Reuse getHashValue implementation from
2437 /// std::pair<unsigned, unsigned>.
2438 static unsigned getHashValue(const TargetInstrInfo::RegSubRegPair &Val) {
2440 std::make_pair(Val.Reg, Val.SubReg));
2441 }
2442
2445 return LHS == RHS;
2446 }
2447};
2448
2449} // end namespace llvm
2450
2451#endif // LLVM_CODEGEN_TARGETINSTRINFO_H
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
static const TargetRegisterClass * getRegClass(const MachineInstr &MI, Register Reg)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
SmallVector< int16_t, MAX_SRC_OPERANDS_NUM > OperandIndices
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
#define LLVM_ABI
Definition Compiler.h:215
DXIL Forward Handle Accesses
This file defines DenseMapInfo traits for DenseMap.
This file defines the DenseMap class.
static bool isGlobalMemoryObject(MachineInstr *MI)
Return true if MI is an instruction we are unable to reason about (like something with unmodeled memo...
IRTranslator LLVM IR MI
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Contains all data structures shared between the outliner implemented in MachineOutliner....
TargetInstrInfo::RegSubRegPair RegSubRegPair
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define P(N)
TargetInstrInfo::RegSubRegPairAndIdx RegSubRegPairAndIdx
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
const SmallVectorImpl< MachineOperand > & Cond
static unsigned getInstSizeInBytes(const MachineInstr &MI, const SystemZInstrInfo *TII)
Value * RHS
Value * LHS
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
A debug info location.
Definition DebugLoc.h:126
Itinerary data supplied by a subtarget to be used by a target.
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition MCAsmInfo.h:67
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:188
Describe properties that are true of each instruction in the target description file.
Interface to description of machine instruction set.
Definition MCInstrInfo.h:27
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode.
Definition MCInstrInfo.h:89
This holds information about one operand of a machine instruction, indicating the register class for ...
Definition MCInstrDesc.h:88
MCRegisterClass - Base class of TargetRegisterClass.
MIRFormater - Interface to format MIR operand based on target.
MachineInstrBundleIterator< MachineInstr > iterator
Representation of each machine instruction.
bool isReturn(QueryType Type=AnyInBundle) const
bool mayLoadOrStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read or modify memory.
bool isCall(QueryType Type=AnyInBundle) const
A description of a memory reference used in the backend.
This class contains meta information specific to a module.
MachineOperand class - Representation of each machine instruction operand.
unsigned getSubReg() const
static MachineOperand CreateImm(int64_t Val)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Represents one node in the SelectionDAG.
This class represents the scheduled code.
ScheduleDAGMI is an implementation of ScheduleDAGInstrs that simply schedules machine instructions ac...
HazardRecognizer - This determines whether or not an instruction can be issued this cycle,...
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
This class builds the dependence graph for the instructions in a loop, and attempts to schedule the i...
Object returned by analyzeLoopForPipelining.
virtual bool isMVEExpanderSupported()
Return true if the target can expand pipelined schedule with modulo variable expansion.
virtual void createRemainingIterationsGreaterCondition(int TC, MachineBasicBlock &MBB, SmallVectorImpl< MachineOperand > &Cond, DenseMap< MachineInstr *, MachineInstr * > &LastStage0Insts)
Create a condition to determine if the remaining trip count for a phase is greater than TC.
virtual void adjustTripCount(int TripCountAdjust)=0
Modify the loop such that the trip count is OriginalTC + TripCountAdjust.
virtual void disposed(LiveIntervals *LIS=nullptr)
Called when the loop is being removed.
virtual bool shouldIgnoreForPipelining(const MachineInstr *MI) const =0
Return true if the given instruction should not be pipelined and should be ignored.
virtual void setPreheader(MachineBasicBlock *NewPreheader)=0
Called when the loop's preheader has been modified to NewPreheader.
virtual bool shouldUseSchedule(SwingSchedulerDAG &SSD, SMSchedule &SMS)
Return true if the proposed schedule should used.
virtual std::optional< bool > createTripCountGreaterCondition(int TC, MachineBasicBlock &MBB, SmallVectorImpl< MachineOperand > &Cond)=0
Create a condition to determine if the trip count of the loop is greater than TC, where TC is always ...
TargetInstrInfo - Interface to description of machine instruction set.
virtual SmallVector< std::pair< MachineBasicBlock::iterator, MachineBasicBlock::iterator > > getOutlinableRanges(MachineBasicBlock &MBB, unsigned &Flags) const
Optional target hook which partitions MBB into outlinable ranges for instruction mapping purposes.
virtual bool isProfitableToIfCvt(MachineBasicBlock &MBB, unsigned NumCycles, unsigned ExtraPredCycles, BranchProbability Probability) const
Return true if it's profitable to predicate instructions with accumulated instruction latency of "Num...
virtual bool isBasicBlockPrologue(const MachineInstr &MI, Register Reg=Register()) const
True if the instruction is bound to the top of its basic block and no other instructions shall be ins...
virtual bool reverseBranchCondition(SmallVectorImpl< MachineOperand > &Cond) const
Reverses the branch condition of the specified condition list, returning false on success and true if...
virtual MachineInstr * foldMemoryOperandImpl(MachineFunction &MF, MachineInstr &MI, ArrayRef< unsigned > Ops, MachineInstr &LoadMI, MachineInstr *&CopyMI, LiveIntervals *LIS=nullptr, VirtRegMap *VRM=nullptr) const
Target-dependent implementation for foldMemoryOperand.
virtual unsigned removeBranch(MachineBasicBlock &MBB, int *BytesRemoved=nullptr) const
Remove the branching code at the end of the specific MBB.
virtual std::unique_ptr< PipelinerLoopInfo > analyzeLoopForPipelining(MachineBasicBlock *LoopBB) const
Analyze loop L, which must be a single-basic-block loop, and if the conditions can be understood enou...
virtual ValueUniformity getValueUniformity(const MachineInstr &MI) const
Return the uniformity behavior of the given value.
virtual bool ClobbersPredicate(MachineInstr &MI, std::vector< MachineOperand > &Pred, bool SkipDead) const
If the specified instruction defines any predicate or condition code register(s) used for predication...
virtual bool canPredicatePredicatedInstr(const MachineInstr &MI) const
Assumes the instruction is already predicated and returns true if the instruction can be predicated a...
virtual void setSpecialOperandAttr(MachineInstr &OldMI1, MachineInstr &OldMI2, MachineInstr &NewMI1, MachineInstr &NewMI2) const
This is an architecture-specific helper function of reassociateOps.
bool isZeroCost(unsigned Opcode) const
Return true for pseudo instructions that don't consume any machine resources in their current form.
virtual void buildClearRegister(Register Reg, MachineBasicBlock &MBB, MachineBasicBlock::iterator Iter, DebugLoc &DL, bool AllowSideEffects=true) const
Insert an architecture-specific instruction to clear a register.
virtual void getFrameIndexOperands(SmallVectorImpl< MachineOperand > &Ops, int FI) const
Fills in the necessary MachineOperands to refer to a frame index.
virtual bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify=false) const
Analyze the branching code at the end of MBB, returning true if it cannot be understood (e....
virtual bool isExtendLikelyToBeFolded(MachineInstr &ExtMI, MachineRegisterInfo &MRI) const
Given the generic extension instruction ExtMI, returns true if this extension is a likely candidate f...
virtual bool isSafeToSink(MachineInstr &MI, MachineBasicBlock *SuccToSinkTo, MachineCycleInfo *CI) const
const TargetRegisterInfo & TRI
virtual std::optional< DestSourcePair > isCopyLikeInstrImpl(const MachineInstr &MI) const
virtual unsigned getPartialRegUpdateClearance(const MachineInstr &MI, unsigned OpNum, const TargetRegisterInfo *TRI) const
Returns the preferred minimum clearance before an instruction with an unwanted partial register updat...
virtual bool canMakeTailCallConditional(SmallVectorImpl< MachineOperand > &Cond, const MachineInstr &TailCall) const
Returns true if the tail call can be made conditional on BranchCond.
virtual DFAPacketizer * CreateTargetScheduleState(const TargetSubtargetInfo &) const
Create machine specific model for scheduling.
virtual unsigned reduceLoopCount(MachineBasicBlock &MBB, MachineBasicBlock &PreHeader, MachineInstr *IndVar, MachineInstr &Cmp, SmallVectorImpl< MachineOperand > &Cond, SmallVectorImpl< MachineInstr * > &PrevInsts, unsigned Iter, unsigned MaxIter) const
Generate code to reduce the loop iteration by one and check if the loop is finished.
virtual bool isPostIncrement(const MachineInstr &MI) const
Return true for post-incremented instructions.
bool isTriviallyReMaterializable(const MachineInstr &MI) const
Return true if the instruction is trivially rematerializable, meaning it has no side effects and requ...
virtual bool isIgnorableUse(const MachineInstr &MI, unsigned OpIdx) const
Given operand OpIdx of MI is a PhysReg use, return if it can be ignored for the purpose of instructio...
virtual bool isCoalescableExtInstr(const MachineInstr &MI, Register &SrcReg, Register &DstReg, unsigned &SubIdx) const
Return true if the instruction is a "coalescable" extension instruction.
virtual void insertIndirectBranch(MachineBasicBlock &MBB, MachineBasicBlock &NewDestBB, MachineBasicBlock &RestoreBB, const DebugLoc &DL, int64_t BrOffset=0, RegScavenger *RS=nullptr) const
Insert an unconditional indirect branch at the end of MBB to NewDestBB.
virtual ArrayRef< std::pair< MachineMemOperand::Flags, const char * > > getSerializableMachineMemOperandTargetFlags() const
Return an array that contains the MMO target flag values and their names.
virtual bool getBaseAndOffsetPosition(const MachineInstr &MI, unsigned &BasePos, unsigned &OffsetPos) const
Return true if the instruction contains a base register and offset.
int16_t getOpRegClassID(const MCOperandInfo &OpInfo) const
virtual unsigned getOpcodeAfterMemoryUnfold(unsigned Opc, bool UnfoldLoad, bool UnfoldStore, unsigned *LoadRegIndex=nullptr) const
Returns the opcode of the would be new instruction after load / store are unfolded from an instructio...
virtual outliner::InstrType getOutliningTypeImpl(const MachineModuleInfo &MMI, MachineBasicBlock::iterator &MIT, unsigned Flags) const
Target-dependent implementation for getOutliningTypeImpl.
virtual bool analyzeBranchPredicate(MachineBasicBlock &MBB, MachineBranchPredicate &MBP, bool AllowModify=false) const
Analyze the branching code at the end of MBB and parse it into the MachineBranchPredicate structure i...
virtual bool getInsertSubregLikeInputs(const MachineInstr &MI, unsigned DefIdx, RegSubRegPair &BaseReg, RegSubRegPairAndIdx &InsertedReg) const
Target-dependent implementation of getInsertSubregInputs.
virtual bool shouldOutlineFromFunctionByDefault(MachineFunction &MF) const
Return true if the function should be outlined from by default.
virtual MachineInstr * optimizeSelect(MachineInstr &MI, SmallPtrSetImpl< MachineInstr * > &NewMIs, bool PreferFalse=false) const
Given an instruction marked as isSelect = true, attempt to optimize MI by merging it with one of its ...
virtual bool canFoldIntoAddrMode(const MachineInstr &MemI, Register Reg, const MachineInstr &AddrI, ExtAddrMode &AM) const
Check if it's possible and beneficial to fold the addressing computation AddrI into the addressing mo...
virtual const MIRFormatter * getMIRFormatter() const
Return MIR formatter to format/parse MIR operands.
bool isReMaterializable(const MachineInstr &MI) const
Return true if the instruction would be materializable at a point in the containing function where al...
virtual InstSizeVerifyMode getInstSizeVerifyMode(const MachineInstr &MI) const
Determine whether/how the instruction size returned by getInstSizeInBytes() should be verified.
virtual bool shouldReduceRegisterPressure(const MachineBasicBlock *MBB, const RegisterClassInfo *RegClassInfo) const
Return true if target supports reassociation of instructions in machine combiner pass to reduce regis...
virtual ArrayRef< std::pair< int, const char * > > getSerializableTargetIndices() const
Return an array that contains the ids of the target indices (used for the TargetIndex machine operand...
bool isFullCopyInstr(const MachineInstr &MI) const
virtual unsigned getUndefRegClearance(const MachineInstr &MI, unsigned OpNum, const TargetRegisterInfo *TRI) const
Return the minimum clearance before an instruction that reads an unused register.
virtual bool findCommutedOpIndices(const MachineInstr &MI, unsigned &SrcOpIdx1, unsigned &SrcOpIdx2) const
Returns true iff the routine could find two commutable operands in the given machine instruction.
virtual bool preservesZeroValueInReg(const MachineInstr *MI, const Register NullValueReg, const TargetRegisterInfo *TRI) const
Returns true if MI's Def is NullValueReg, and the MI does not change the Zero value.
virtual bool verifyInstruction(const MachineInstr &MI, StringRef &ErrInfo) const
Perform target-specific instruction verification.
virtual void finalizeInsInstrs(MachineInstr &Root, unsigned &Pattern, SmallVectorImpl< MachineInstr * > &InsInstrs) const
Fix up the placeholder we may add in genAlternativeCodeSequence().
virtual bool isUnconditionalTailCall(const MachineInstr &MI) const
Returns true if MI is an unconditional tail call.
virtual bool hasHighOperandLatency(const TargetSchedModel &SchedModel, const MachineRegisterInfo *MRI, const MachineInstr &DefMI, unsigned DefIdx, const MachineInstr &UseMI, unsigned UseIdx) const
Compute operand latency between a def of 'Reg' and a use in the current loop.
bool isUnspillableTerminator(const MachineInstr *MI) const
Return true if the given instruction is terminator that is unspillable, according to isUnspillableTer...
virtual bool isProfitableToUnpredicate(MachineBasicBlock &TMBB, MachineBasicBlock &FMBB) const
Return true if it's profitable to unpredicate one side of a 'diamond', i.e.
virtual bool useMachineCombiner() const
Return true when a target supports MachineCombiner.
virtual bool SubsumesPredicate(ArrayRef< MachineOperand > Pred1, ArrayRef< MachineOperand > Pred2) const
Returns true if the first specified predicate subsumes the second, e.g.
bool isFrameInstr(const MachineInstr &I) const
Returns true if the argument is a frame pseudo instruction.
virtual void breakPartialRegDependency(MachineInstr &MI, unsigned OpNum, const TargetRegisterInfo *TRI) const
Insert a dependency-breaking instruction before MI to eliminate an unwanted dependency on OpNum.
virtual bool getRegSequenceLikeInputs(const MachineInstr &MI, unsigned DefIdx, SmallVectorImpl< RegSubRegPairAndIdx > &InputRegs) const
Target-dependent implementation of getRegSequenceInputs.
virtual bool isProfitableToIfCvt(MachineBasicBlock &TMBB, unsigned NumTCycles, unsigned ExtraTCycles, MachineBasicBlock &FMBB, unsigned NumFCycles, unsigned ExtraFCycles, BranchProbability Probability) const
Second variant of isProfitableToIfCvt.
virtual int getExtendResourceLenLimit() const
The limit on resource length extension we accept in MachineCombiner Pass.
virtual void insertSelect(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, Register DstReg, ArrayRef< MachineOperand > Cond, Register TrueReg, Register FalseReg) const
Insert a select instruction into MBB before I that will copy TrueReg to DstReg when Cond is true,...
virtual bool shouldBreakCriticalEdgeToSink(MachineInstr &MI) const
For a "cheap" instruction which doesn't enable additional sinking, should MachineSink break a critica...
virtual bool areMemAccessesTriviallyDisjoint(const MachineInstr &MIa, const MachineInstr &MIb) const
Sometimes, it is possible for the target to tell, even without aliasing information,...
virtual bool isBranchOffsetInRange(unsigned BranchOpc, int64_t BrOffset) const
unsigned getReturnOpcode() const
bool analyzeBranch(const MachineBasicBlock &MBB, const MachineBasicBlock *&TBB, const MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond) const
virtual void storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register SrcReg, bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg, MachineInstr::MIFlag Flags=MachineInstr::NoFlags) const
Store the specified register of the given register class to the specified stack frame index.
virtual unsigned getReduceOpcodeForAccumulator(unsigned int AccumulatorOpCode) const
Returns the opcode that should be use to reduce accumulation registers.
virtual Register isLoadFromStackSlot(const MachineInstr &MI, int &FrameIndex) const
If the specified machine instruction is a direct load from a stack slot, return the virtual or physic...
virtual bool shouldPostRASink(const MachineInstr &MI) const
virtual bool shouldClusterMemOps(ArrayRef< const MachineOperand * > BaseOps1, int64_t Offset1, bool OffsetIsScalable1, ArrayRef< const MachineOperand * > BaseOps2, int64_t Offset2, bool OffsetIsScalable2, unsigned ClusterSize, unsigned NumBytes) const
Returns true if the two given memory operations should be scheduled adjacent.
virtual unsigned getLiveRangeSplitOpcode(Register Reg, const MachineFunction &MF) const
Allows targets to use appropriate copy instruction while spilitting live range of a register in regis...
virtual bool optimizeCompareInstr(MachineInstr &CmpInstr, Register SrcReg, Register SrcReg2, int64_t Mask, int64_t Value, const MachineRegisterInfo *MRI) const
See if the comparison instruction can be converted into something more efficient.
virtual unsigned getMemOperandAACheckLimit() const
Return the maximal number of alias checks on memory operands.
virtual bool isFunctionSafeToOutlineFrom(MachineFunction &MF, bool OutlineFromLinkOnceODRs) const
Return true if the function can safely be outlined from.
virtual bool isMBBSafeToSplitToCold(const MachineBasicBlock &MBB) const
Return true if the MachineBasicBlock can safely be split to the cold section.
virtual void buildOutlinedFrame(MachineBasicBlock &MBB, MachineFunction &MF, const outliner::OutlinedFunction &OF) const
Insert a custom frame for outlined functions.
TargetInstrInfo(const TargetRegisterInfo &TRI, unsigned CFSetupOpcode=~0u, unsigned CFDestroyOpcode=~0u, unsigned CatchRetOpcode=~0u, unsigned ReturnOpcode=~0u, const int16_t *const RegClassByHwModeTable=nullptr)
virtual bool shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2, int64_t Offset1, int64_t Offset2, unsigned NumLoads) const
This is a used by the pre-regalloc scheduler to determine (in conjunction with areLoadsFromSameBasePt...
virtual unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB, ArrayRef< MachineOperand > Cond, const DebugLoc &DL, int *BytesAdded=nullptr) const
Insert branch code into the end of the specified MachineBasicBlock.
virtual void copyPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const DebugLoc &DL, Register DestReg, Register SrcReg, bool KillSrc, bool RenamableDest=false, bool RenamableSrc=false) const
Emit instructions to copy a pair of physical registers.
virtual unsigned getAccumulationStartOpcode(unsigned Opcode) const
Returns an opcode which defines the accumulator used by \P Opcode.
virtual bool canCopyGluedNodeDuringSchedule(SDNode *N) const
Return true if the given SDNode can be copied during scheduling even if it has glue.
virtual bool simplifyInstruction(MachineInstr &MI) const
If possible, converts the instruction to a simplified/canonical form.
virtual std::optional< ExtAddrMode > getAddrModeFromMemoryOp(const MachineInstr &MemI, const TargetRegisterInfo *TRI) const
Target dependent implementation to get the values constituting the address MachineInstr that is acces...
virtual std::optional< DestSourcePair > isCopyInstrImpl(const MachineInstr &MI) const
Target-dependent implementation for IsCopyInstr.
virtual MachineInstr * createPHIDestinationCopy(MachineBasicBlock &MBB, MachineBasicBlock::iterator InsPt, const DebugLoc &DL, Register Src, Register Dst) const
During PHI eleimination lets target to make necessary checks and insert the copy to the PHI destinati...
virtual bool getConstValDefinedInReg(const MachineInstr &MI, const Register Reg, int64_t &ImmVal) const
Returns true if MI is an instruction that defines Reg to have a constant value and the value is recor...
static bool isGenericOpcode(unsigned Opc)
TargetInstrInfo & operator=(const TargetInstrInfo &)=delete
const TargetRegisterInfo & getRegisterInfo() const
std::optional< DestSourcePair > isCopyLikeInstr(const MachineInstr &MI) const
virtual ArrayRef< std::pair< unsigned, const char * > > getSerializableBitmaskMachineOperandTargetFlags() const
Return an array that contains the bitmask target flag values and their names.
unsigned getCallFrameSetupOpcode() const
These methods return the opcode of the frame setup/destroy instructions if they exist (-1 otherwise).
virtual bool isSubregFoldable() const
Check whether the target can fold a load that feeds a subreg operand (or a subreg operand that feeds ...
virtual bool isReMaterializableImpl(const MachineInstr &MI) const
For instructions with opcodes for which the M_REMATERIALIZABLE flag is set, this hook lets the target...
virtual MachineInstr * insertCodePrefetchInstr(MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore, const GlobalValue *GV) const
Inserts a code prefetch instruction before InsertBefore in block MBB targetting GV.
virtual Register isStoreToStackSlotPostFE(const MachineInstr &MI, int &FrameIndex) const
Check for post-frame ptr elimination stack locations as well.
virtual Register isLoadFromStackSlotPostFE(const MachineInstr &MI, int &FrameIndex) const
Check for post-frame ptr elimination stack locations as well.
virtual ScheduleHazardRecognizer * CreateTargetPostRAHazardRecognizer(const MachineFunction &MF, MachineLoopInfo *MLI) const
Allocate and return a hazard recognizer to use for by non-scheduling passes.
@ AllowOverEstimate
Allow the reported instruction size to be larger than the actual size.
@ NoVerify
Do not verify instruction size.
@ ExactSize
Check that the instruction size matches exactly.
virtual std::pair< uint16_t, uint16_t > getExecutionDomain(const MachineInstr &MI) const
Return the current execution domain and bit mask of possible domains for instruction.
virtual bool optimizeCondBranch(MachineInstr &MI) const
virtual bool analyzeLoop(MachineLoop &L, MachineInstr *&IndVarInst, MachineInstr *&CmpInst) const
Analyze the loop code, return true if it cannot be understood.
unsigned getCatchReturnOpcode() const
virtual unsigned getTailMergeSize(const MachineFunction &MF) const
Returns the target-specific default value for tail merging.
virtual bool isAsCheapAsAMove(const MachineInstr &MI) const
Return true if the instruction is as cheap as a move instruction.
virtual bool isTailCall(const MachineInstr &Inst) const
Determines whether Inst is a tail call instruction.
const int16_t *const RegClassByHwMode
Subtarget specific sub-array of MCInstrInfo's RegClassByHwModeTables (i.e.
virtual const MachineOperand & getCalleeOperand(const MachineInstr &MI) const
Returns the callee operand from the given MI.
virtual Register isStoreToStackSlot(const MachineInstr &MI, int &FrameIndex) const
If the specified machine instruction is a direct store to a stack slot, return the virtual or physica...
int64_t getFrameTotalSize(const MachineInstr &I) const
Returns the total frame size, which is made up of the space set up inside the pair of frame start-sto...
MachineInstr * commuteInstruction(MachineInstr &MI, bool NewMI=false, unsigned OpIdx1=CommuteAnyOperandIndex, unsigned OpIdx2=CommuteAnyOperandIndex) const
This method commutes the operands of the given machine instruction MI.
virtual bool foldImmediate(MachineInstr &UseMI, MachineInstr &DefMI, Register Reg, MachineRegisterInfo *MRI) const
'Reg' is known to be defined by a move immediate instruction, try to fold the immediate into the use ...
virtual bool isStackSlotCopy(const MachineInstr &MI, int &DestFrameIndex, int &SrcFrameIndex) const
Return true if the specified machine instruction is a copy of one stack slot to another and has no ot...
virtual int getJumpTableIndex(const MachineInstr &MI) const
Return an index for MachineJumpTableInfo if insn is an indirect jump using a jump table,...
virtual bool isAssociativeAndCommutative(const MachineInstr &Inst, bool Invert=false) const
Return true when \P Inst is both associative and commutative.
virtual bool isExplicitTargetIndexDef(const MachineInstr &MI, int &Index, int64_t &Offset) const
Returns true if the given MI defines a TargetIndex operand that can be tracked by their offset,...
virtual bool unfoldMemoryOperand(MachineFunction &MF, MachineInstr &MI, Register Reg, bool UnfoldLoad, bool UnfoldStore, SmallVectorImpl< MachineInstr * > &NewMIs) const
unfoldMemoryOperand - Separate a single instruction which folded a load or a store or a load and a st...
virtual bool isPCRelRegisterOperandLegal(const MachineOperand &MO) const
Allow targets to tell MachineVerifier whether a specific register MachineOperand can be used as part ...
virtual std::optional< std::unique_ptr< outliner::OutlinedFunction > > getOutliningCandidateInfo(const MachineModuleInfo &MMI, std::vector< outliner::Candidate > &RepeatedSequenceLocs, unsigned MinRepeats) const
Returns a outliner::OutlinedFunction struct containing target-specific information for a set of outli...
virtual MachineInstr * createPHISourceCopy(MachineBasicBlock &MBB, MachineBasicBlock::iterator InsPt, const DebugLoc &DL, Register Src, unsigned SrcSubReg, Register Dst) const
During PHI eleimination lets target to make necessary checks and insert the copy to the PHI destinati...
virtual MachineBasicBlock::iterator insertOutlinedCall(Module &M, MachineBasicBlock &MBB, MachineBasicBlock::iterator &It, MachineFunction &MF, outliner::Candidate &C) const
Insert a call to an outlined function into the program.
virtual std::optional< unsigned > getInverseOpcode(unsigned Opcode) const
Return the inverse operation opcode if it exists for \P Opcode (e.g.
unsigned getCallFrameDestroyOpcode() const
int64_t getFrameSize(const MachineInstr &I) const
Returns size of the frame associated with the given frame instruction.
virtual MachineBasicBlock * getBranchDestBlock(const MachineInstr &MI) const
virtual bool isPredicated(const MachineInstr &MI) const
Returns true if the instruction is already predicated.
virtual void replaceBranchWithTailCall(MachineBasicBlock &MBB, SmallVectorImpl< MachineOperand > &Cond, const MachineInstr &TailCall) const
Replace the conditional branch in MBB with a conditional tail call.
TargetInstrInfo(const TargetInstrInfo &)=delete
virtual unsigned predictBranchSizeForIfCvt(MachineInstr &MI) const
Return an estimate for the code size reduction (in bytes) which will be caused by removing the given ...
virtual ~TargetInstrInfo()
virtual bool isAccumulationOpcode(unsigned Opcode) const
Return true when \P OpCode is an instruction which performs accumulation into one of its operand regi...
bool isFrameSetup(const MachineInstr &I) const
Returns true if the argument is a frame setup pseudo instruction.
virtual unsigned extraSizeToPredicateInstructions(const MachineFunction &MF, unsigned NumInsts) const
Return the increase in code size needed to predicate a contiguous run of NumInsts instructions.
virtual bool accumulateInstrSeqToRootLatency(MachineInstr &Root) const
When calculate the latency of the root instruction, accumulate the latency of the sequence to the roo...
std::optional< DestSourcePair > isCopyInstr(const MachineInstr &MI) const
If the specific machine instruction is a instruction that moves/copies value from one register to ano...
virtual MachineInstr * foldMemoryOperandImpl(MachineFunction &MF, MachineInstr &MI, ArrayRef< unsigned > Ops, int FrameIndex, MachineInstr *&CopyMI, LiveIntervals *LIS=nullptr, VirtRegMap *VRM=nullptr) const
Target-dependent implementation for foldMemoryOperand.
virtual Register isStoreToStackSlot(const MachineInstr &MI, int &FrameIndex, TypeSize &MemBytes) const
Optional extension of isStoreToStackSlot that returns the number of bytes stored to the stack.
virtual Register isLoadFromStackSlot(const MachineInstr &MI, int &FrameIndex, TypeSize &MemBytes) const
Optional extension of isLoadFromStackSlot that returns the number of bytes loaded from the stack.
virtual bool getMemOperandsWithOffsetWidth(const MachineInstr &MI, SmallVectorImpl< const MachineOperand * > &BaseOps, int64_t &Offset, bool &OffsetIsScalable, LocationSize &Width, const TargetRegisterInfo *TRI) const
Get zero or more base operands and the byte offset of an instruction that reads/writes memory.
virtual unsigned getInstSizeInBytes(const MachineInstr &MI) const
Returns the size in bytes of the specified MachineInstr, or ~0U when this function is not implemented...
virtual bool isProfitableToDupForIfCvt(MachineBasicBlock &MBB, unsigned NumCycles, BranchProbability Probability) const
Return true if it's profitable for if-converter to duplicate instructions of specified accumulated in...
virtual bool shouldSink(const MachineInstr &MI) const
Return true if the instruction should be sunk by MachineSink.
virtual MachineInstr * convertToThreeAddress(MachineInstr &MI, LiveVariables *LV, LiveIntervals *LIS) const
This method must be implemented by targets that set the M_CONVERTIBLE_TO_3_ADDR flag.
virtual void loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register DestReg, int FrameIndex, const TargetRegisterClass *RC, Register VReg, unsigned SubReg=0, MachineInstr::MIFlag Flags=MachineInstr::NoFlags) const
Load the specified register of the given register class from the specified stack frame index.
virtual void setExecutionDomain(MachineInstr &MI, unsigned Domain) const
Change the opcode of MI to execute in Domain.
virtual bool isPredicable(const MachineInstr &MI) const
Return true if the specified instruction can be predicated.
virtual std::pair< unsigned, unsigned > decomposeMachineOperandsTargetFlags(unsigned) const
Decompose the machine operand's target flags into two values - the direct target flag value and any o...
virtual bool isSafeToMoveRegClassDefs(const TargetRegisterClass *RC) const
Return true if it's safe to move a machine instruction that defines the specified register class.
virtual bool canInsertSelect(const MachineBasicBlock &MBB, ArrayRef< MachineOperand > Cond, Register DstReg, Register TrueReg, Register FalseReg, int &CondCycles, int &TrueCycles, int &FalseCycles) const
Return true if it is possible to insert a select instruction that chooses between TrueReg and FalseRe...
virtual bool isUnspillableTerminatorImpl(const MachineInstr *MI) const
Return true if the given terminator MI is not expected to spill.
virtual std::optional< RegImmPair > isAddImmediate(const MachineInstr &MI, Register Reg) const
If the specific machine instruction is an instruction that adds an immediate value and a register,...
static bool isGenericAtomicRMWOpcode(unsigned Opc)
virtual bool hasCommutePreference(MachineInstr &MI, bool &Commute) const
Returns true if the target has a preference on the operands order of the given machine instruction.
static const unsigned CommuteAnyOperandIndex
virtual bool isSafeToMove(const MachineInstr &MI, const MachineBasicBlock *MBB, const MachineFunction &MF) const
Return true if it's safe to move a machine instruction.
virtual bool isHighLatencyDef(int opc) const
Return true if this opcode has high latency to its result.
virtual MachineInstr * emitLdStWithAddr(MachineInstr &MemI, const ExtAddrMode &AM) const
Emit a load/store instruction with the same value register as MemI, but using the address from AM.
virtual bool expandPostRAPseudo(MachineInstr &MI) const
This function is called for all pseudo instructions that remain after register allocation.
virtual ArrayRef< std::pair< unsigned, const char * > > getSerializableDirectMachineOperandTargetFlags() const
Return an array that contains the direct target flag values and their names.
virtual bool shouldHoist(const MachineInstr &MI, const MachineLoop *FromLoop) const
Return false if the instruction should not be hoisted by MachineLICM.
virtual bool getExtractSubregLikeInputs(const MachineInstr &MI, unsigned DefIdx, RegSubRegPairAndIdx &InputReg) const
Target-dependent implementation of getExtractSubregInputs.
virtual unsigned getTailDuplicateSize(CodeGenOptLevel OptLevel) const
Returns the target-specific default value for tail duplication.
unsigned insertUnconditionalBranch(MachineBasicBlock &MBB, MachineBasicBlock *DestBB, const DebugLoc &DL, int *BytesAdded=nullptr) const
virtual bool getIncrementValue(const MachineInstr &MI, int &Value) const
If the instruction is an increment of a constant value, return the amount.
virtual bool areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2, int64_t &Offset1, int64_t &Offset2) const
This is used by the pre-regalloc scheduler to determine if two loads are loading from the same base a...
virtual bool unfoldMemoryOperand(SelectionDAG &DAG, SDNode *N, SmallVectorImpl< SDNode * > &NewNodes) const
virtual bool analyzeCompare(const MachineInstr &MI, Register &SrcReg, Register &SrcReg2, int64_t &Mask, int64_t &Value) const
For a comparison instruction, return the source registers in SrcReg and SrcReg2 if having two registe...
virtual unsigned getMachineCSELookAheadLimit() const
Return the value to use for the MachineCSE's LookAheadLimit, which is a heuristic used for CSE'ing ph...
virtual bool isLegalToSplitMBBAt(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const
Return true if it's legal to split the given basic block at the specified instruction (i....
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
Provide an instruction scheduling machine model to CodeGen passes.
TargetSubtargetInfo - Generic base class for all target subtargets.
static constexpr TypeSize getZero()
Definition TypeSize.h:345
LLVM Value Representation.
Definition Value.h:75
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
InstrType
Represents how an instruction should be mapped by the outliner.
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
MachineTraceStrategy
Strategies for selecting traces.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
CombinerObjective
The combiner's goal may differ based on which pattern it is attempting to optimize.
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:177
DWARFExpression::Operation Op
std::pair< MachineOperand, DIExpression * > ParamLoadedValue
ValueUniformity
Enum describing how values behave with respect to uniformity and divergence, to answer the question: ...
Definition Uniformity.h:18
@ Default
The result value is uniform if and only if all operands are uniform.
Definition Uniformity.h:20
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
#define N
static unsigned getHashValue(const TargetInstrInfo::RegSubRegPair &Val)
Reuse getHashValue implementation from std::pair<unsigned, unsigned>.
static bool isEqual(const TargetInstrInfo::RegSubRegPair &LHS, const TargetInstrInfo::RegSubRegPair &RHS)
An information struct used to provide DenseMap with the various necessary components for a given valu...
const MachineOperand * Source
DestSourcePair(const MachineOperand &Dest, const MachineOperand &Src)
const MachineOperand * Destination
Used to describe addressing mode similar to ExtAddrMode in CodeGenPrepare.
ExtAddrMode()=default
static constexpr LaneBitmask getAll()
Definition LaneBitmask.h:82
Machine model for scheduling, bundling, and heuristics.
Definition MCSchedule.h:273
RegImmPair(Register Reg, int64_t Imm)
Represents a predicate at the MachineFunction level.
bool SingleUseCondition
SingleUseCondition is true if ConditionDef is dead except for the branch(es) at the end of the basic ...
A pair composed of a pair of a register and a sub-register index, and another sub-register index.
RegSubRegPairAndIdx(Register Reg=Register(), unsigned SubReg=0, unsigned SubIdx=0)
A pair composed of a register and a sub-register index.
bool operator==(const RegSubRegPair &P) const
RegSubRegPair(Register Reg=Register(), unsigned SubReg=0)
bool operator!=(const RegSubRegPair &P) const
An individual sequence of instructions to be replaced with a call to an outlined function.
The information necessary to create an outlined function for some class of candidate.