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