LLVM 24.0.0git
MipsISelLowering.cpp
Go to the documentation of this file.
1//===- MipsISelLowering.cpp - Mips DAG Lowering Implementation ------------===//
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 defines the interfaces that Mips uses to lower LLVM code into a
10// selection DAG.
11//
12//===----------------------------------------------------------------------===//
13
14#include "MipsISelLowering.h"
18#include "MipsCCState.h"
19#include "MipsInstrInfo.h"
20#include "MipsMachineFunction.h"
21#include "MipsRegisterInfo.h"
22#include "MipsSubtarget.h"
23#include "MipsTargetMachine.h"
25#include "llvm/ADT/APFloat.h"
26#include "llvm/ADT/ArrayRef.h"
28#include "llvm/ADT/Statistic.h"
29#include "llvm/ADT/StringRef.h"
49#include "llvm/IR/CallingConv.h"
50#include "llvm/IR/Constants.h"
51#include "llvm/IR/DataLayout.h"
52#include "llvm/IR/DebugLoc.h"
54#include "llvm/IR/Function.h"
55#include "llvm/IR/GlobalValue.h"
56#include "llvm/IR/Module.h"
57#include "llvm/IR/Type.h"
58#include "llvm/IR/Value.h"
59#include "llvm/MC/MCContext.h"
68#include <algorithm>
69#include <cassert>
70#include <cctype>
71#include <cstdint>
72#include <deque>
73#include <iterator>
74#include <string>
75#include <utility>
76#include <vector>
77
78using namespace llvm;
79
80#define DEBUG_TYPE "mips-lower"
81
82STATISTIC(NumTailCalls, "Number of tail calls");
83
86
87static cl::opt<bool> UseMipsTailCalls("mips-tail-calls", cl::Hidden,
88 cl::desc("MIPS: permit tail calls."),
89 cl::init(false));
90
91static const MCPhysReg Mips64DPRegs[8] = {
92 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
93 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
94};
95
97 Break, // MIPS I
98 Teq, // MIPS II+
99 TeqMM, // microMIPS
100};
101
102// The MIPS MSA ABI passes vector arguments in the integer register set.
103// The number of integer registers used is dependant on the ABI used.
106 EVT VT) const {
107 if (!VT.isVector())
108 return getRegisterType(Context, VT);
109
111 return Subtarget.isABI_O32() || VT.getSizeInBits() == 32 ? MVT::i32
112 : MVT::i64;
113 return getRegisterType(Context, VT.getVectorElementType());
114}
115
118 EVT VT) const {
119 if (VT.isVector()) {
121 return divideCeil(VT.getSizeInBits(), Subtarget.isABI_O32() ? 32 : 64);
122 return VT.getVectorNumElements() *
124 }
125 return MipsTargetLowering::getNumRegisters(Context, VT);
126}
127
129 LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
130 unsigned &NumIntermediates, MVT &RegisterVT) const {
131 if (VT.isPow2VectorType() && VT.getVectorElementType().isRound()) {
132 IntermediateVT = getRegisterTypeForCallingConv(Context, CC, VT);
133 RegisterVT = IntermediateVT.getSimpleVT();
134 NumIntermediates = getNumRegistersForCallingConv(Context, CC, VT);
135 return NumIntermediates;
136 }
137 IntermediateVT = VT.getVectorElementType();
138 NumIntermediates = VT.getVectorNumElements();
139 RegisterVT = getRegisterType(Context, IntermediateVT);
140 return NumIntermediates * getNumRegisters(Context, IntermediateVT);
141}
142
148
149SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
150 SelectionDAG &DAG,
151 unsigned Flag) const {
152 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
153}
154
155SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
156 SelectionDAG &DAG,
157 unsigned Flag) const {
158 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
159}
160
161SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
162 SelectionDAG &DAG,
163 unsigned Flag) const {
164 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
165}
166
167SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
168 SelectionDAG &DAG,
169 unsigned Flag) const {
170 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
171}
172
173SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
174 SelectionDAG &DAG,
175 unsigned Flag) const {
176 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
177 N->getOffset(), Flag);
178}
179
181 const MipsSubtarget &STI)
182 : TargetLowering(TM, STI), Subtarget(STI), ABI(TM.getABI()) {
183 // Mips does not have i1 type, so use i32 for
184 // setcc operations results (slt, sgt, ...).
187 // The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA
188 // does. Integer booleans still use 0 and 1.
189 if (Subtarget.hasMips32r6())
192
193 // Load extented operations for i1 types must be promoted
194 for (MVT VT : MVT::integer_valuetypes()) {
198 }
199
200 // MIPS doesn't have extending float->double load/store. Set LoadExtAction
201 // for f32, f16
202 for (MVT VT : MVT::fp_valuetypes()) {
203 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
204 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
205 }
206
207 // Set LoadExtAction for f16 vectors to Expand
209 MVT F16VT = MVT::getVectorVT(MVT::f16, VT.getVectorNumElements());
210 if (F16VT.isValid())
212 }
213
214 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
215 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
216
217 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
218
219 // Used by legalize types to correctly generate the setcc result.
220 // Without this, every float setcc comes with a AND/OR with the result,
221 // we don't want this, since the fpcmp result goes to a flag register,
222 // which is used implicitly by brcond and select operations.
223 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
224
225 // Mips Custom Operations
231 if (!Subtarget.inMips16Mode())
246
251
252 if (Subtarget.hasMips32r2() ||
253 getTargetMachine().getTargetTriple().isOSLinux())
255
256 // Lower fmin/fmax/fclass operations for MIPS R6.
257 if (Subtarget.hasMips32r6()) {
270 } else {
273 }
274
275 if (Subtarget.isGP64bit()) {
280 if (!Subtarget.inMips16Mode())
283 if (Subtarget.hasMips64r6()) {
286 } else {
289 }
296 }
297
298 if (!Subtarget.isGP64bit()) {
302 }
303
305 if (Subtarget.isGP64bit())
307
316
317 // Operations not directly supported by Mips.
331
332 if (Subtarget.hasCnMips()) {
335 } else {
338 }
345
346 if (!Subtarget.hasMips32r2())
348
349 if (!Subtarget.hasMips64r2())
351
368
369 // Lower f16 conversion operations into library calls
374
376
381
382 // Use the default for now
385
386 if (!Subtarget.isGP64bit()) {
389 }
390
391 if (!Subtarget.hasMips32r2()) {
394 }
395
396 // MIPS16 lacks MIPS32's clz and clo instructions.
397 if (!Subtarget.hasMips32() || Subtarget.inMips16Mode())
399 if (!Subtarget.hasMips64())
401
402 if (!Subtarget.hasMips32r2())
404 if (!Subtarget.hasMips64r2())
406
407 if (Subtarget.isGP64bit() && Subtarget.hasMips64r6()) {
408 setLoadExtAction(ISD::SEXTLOAD, MVT::i64, MVT::i32, Legal);
409 setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, MVT::i32, Legal);
410 setLoadExtAction(ISD::EXTLOAD, MVT::i64, MVT::i32, Legal);
411 setTruncStoreAction(MVT::i64, MVT::i32, Legal);
412 } else if (Subtarget.isGP64bit()) {
413 setLoadExtAction(ISD::SEXTLOAD, MVT::i64, MVT::i32, Custom);
414 setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, MVT::i32, Custom);
415 setLoadExtAction(ISD::EXTLOAD, MVT::i64, MVT::i32, Custom);
416 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
417 }
418
419 setOperationAction(ISD::TRAP, MVT::Other, Legal);
420
424
425 // R5900 has no LL/SC instructions for atomic operations
426 if (Subtarget.isR5900())
428 else if (Subtarget.isGP64bit())
430 else
432
433 setMinFunctionAlignment(Subtarget.isGP64bit() ? Align(8) : Align(4));
434
435 // The arguments on the stack are defined in terms of 4-byte slots on O32
436 // and 8-byte slots on N32/N64.
437 setMinStackArgumentAlignment((ABI.IsN32() || ABI.IsN64()) ? Align(8)
438 : Align(4));
439
440 setStackPointerRegisterToSaveRestore(ABI.IsN64() ? Mips::SP_64 : Mips::SP);
441
443
444 isMicroMips = Subtarget.inMicroMipsMode();
445}
446
447const MipsTargetLowering *
449 const MipsSubtarget &STI) {
450 if (STI.inMips16Mode())
451 return createMips16TargetLowering(TM, STI);
452
453 return createMipsSETargetLowering(TM, STI);
454}
455
456// Create a fast isel object.
458 FunctionLoweringInfo &funcInfo, const TargetLibraryInfo *libInfo,
459 const LibcallLoweringInfo *libcallLowering) const {
460 const MipsTargetMachine &TM =
461 static_cast<const MipsTargetMachine &>(funcInfo.MF->getTarget());
462
463 // We support only the standard encoding [MIPS32,MIPS32R5] ISAs.
464 bool UseFastISel = TM.Options.EnableFastISel && Subtarget.hasMips32() &&
465 !Subtarget.hasMips32r6() && !Subtarget.inMips16Mode() &&
466 !Subtarget.inMicroMipsMode();
467
468 // Disable if either of the following is true:
469 // We do not generate PIC, the ABI is not O32, XGOT is being used.
470 if (!TM.isPositionIndependent() || !TM.getABI().IsO32() ||
471 Subtarget.useXGOT())
472 UseFastISel = false;
473
474 return UseFastISel ? Mips::createFastISel(funcInfo, libInfo, libcallLowering)
475 : nullptr;
476}
477
479 EVT VT) const {
480 if (!VT.isVector())
481 return MVT::i32;
483}
484
487 const MipsSubtarget &Subtarget) {
488 if (DCI.isBeforeLegalizeOps())
489 return SDValue();
490
491 EVT Ty = N->getValueType(0);
492 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
493 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
494 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
495 MipsISD::DivRemU16;
496 SDLoc DL(N);
497
498 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
499 N->getOperand(0), N->getOperand(1));
500 SDValue InChain = DAG.getEntryNode();
501 SDValue InGlue = DivRem;
502
503 // insert MFLO
504 if (N->hasAnyUseOfValue(0)) {
505 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
506 InGlue);
507 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
508 InChain = CopyFromLo.getValue(1);
509 InGlue = CopyFromLo.getValue(2);
510 }
511
512 // insert MFHI
513 if (N->hasAnyUseOfValue(1)) {
514 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
515 HI, Ty, InGlue);
516 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
517 }
518
519 return SDValue();
520}
521
523 switch (CC) {
524 default: llvm_unreachable("Unknown fp condition code!");
525 case ISD::SETEQ:
526 case ISD::SETOEQ: return Mips::FCOND_OEQ;
527 case ISD::SETUNE: return Mips::FCOND_UNE;
528 case ISD::SETLT:
529 case ISD::SETOLT: return Mips::FCOND_OLT;
530 case ISD::SETGT:
531 case ISD::SETOGT: return Mips::FCOND_OGT;
532 case ISD::SETLE:
533 case ISD::SETOLE: return Mips::FCOND_OLE;
534 case ISD::SETGE:
535 case ISD::SETOGE: return Mips::FCOND_OGE;
536 case ISD::SETULT: return Mips::FCOND_ULT;
537 case ISD::SETULE: return Mips::FCOND_ULE;
538 case ISD::SETUGT: return Mips::FCOND_UGT;
539 case ISD::SETUGE: return Mips::FCOND_UGE;
540 case ISD::SETUO: return Mips::FCOND_UN;
541 case ISD::SETO: return Mips::FCOND_OR;
542 case ISD::SETNE:
543 case ISD::SETONE: return Mips::FCOND_ONE;
544 case ISD::SETUEQ: return Mips::FCOND_UEQ;
545 }
546}
547
548/// This function returns true if the floating point conditional branches and
549/// conditional moves which use condition code CC should be inverted.
551 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
552 return false;
553
554 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
555 "Illegal Condition Code");
556
557 return true;
558}
559
560// Creates and returns an FPCmp node from a setcc node.
561// Returns Op if setcc is not a floating point comparison.
563 // must be a SETCC node
564 if (Op.getOpcode() != ISD::SETCC && Op.getOpcode() != ISD::STRICT_FSETCC &&
565 Op.getOpcode() != ISD::STRICT_FSETCCS)
566 return Op;
567
568 SDValue LHS = Op.getOperand(0);
569
570 if (!LHS.getValueType().isFloatingPoint())
571 return Op;
572
573 SDValue RHS = Op.getOperand(1);
574 SDLoc DL(Op);
575
576 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
577 // node if necessary.
578 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
579
580 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
581 DAG.getConstant(condCodeToFCC(CC), DL, MVT::i32));
582}
583
584// Creates and returns a CMovFPT/F node.
586 SDValue False, const SDLoc &DL) {
587 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
589 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
590
591 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
592 True.getValueType(), True, FCC0, False, Cond);
593}
594
597 const MipsSubtarget &Subtarget) {
598 if (DCI.isBeforeLegalizeOps())
599 return SDValue();
600
601 SDValue SetCC = N->getOperand(0);
602
603 if ((SetCC.getOpcode() != ISD::SETCC) ||
604 !SetCC.getOperand(0).getValueType().isInteger())
605 return SDValue();
606
607 SDValue False = N->getOperand(2);
608 EVT FalseTy = False.getValueType();
609
610 if (!FalseTy.isInteger())
611 return SDValue();
612
614
615 // If the RHS (False) is 0, we swap the order of the operands
616 // of ISD::SELECT (obviously also inverting the condition) so that we can
617 // take advantage of conditional moves using the $0 register.
618 // Example:
619 // return (a != 0) ? x : 0;
620 // load $reg, x
621 // movz $reg, $0, a
622 if (!FalseC)
623 return SDValue();
624
625 const SDLoc DL(N);
626
627 if (!FalseC->getZExtValue()) {
628 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
629 SDValue True = N->getOperand(1);
630
631 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
632 SetCC.getOperand(1),
634
635 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
636 }
637
638 // If both operands are integer constants there's a possibility that we
639 // can do some interesting optimizations.
640 SDValue True = N->getOperand(1);
642
643 if (!TrueC || !True.getValueType().isInteger())
644 return SDValue();
645
646 // We'll also ignore MVT::i64 operands as this optimizations proves
647 // to be ineffective because of the required sign extensions as the result
648 // of a SETCC operator is always MVT::i32 for non-vector types.
649 if (True.getValueType() == MVT::i64)
650 return SDValue();
651
652 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
653
654 // 1) (a < x) ? y : y-1
655 // slti $reg1, a, x
656 // addiu $reg2, $reg1, y-1
657 if (Diff == 1)
658 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
659
660 // 2) (a < x) ? y-1 : y
661 // slti $reg1, a, x
662 // xor $reg1, $reg1, 1
663 // addiu $reg2, $reg1, y-1
664 if (Diff == -1) {
665 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
666 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
667 SetCC.getOperand(1),
669 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
670 }
671
672 // Could not optimize.
673 return SDValue();
674}
675
678 const MipsSubtarget &Subtarget) {
679 if (DCI.isBeforeLegalizeOps())
680 return SDValue();
681
682 SDValue ValueIfTrue = N->getOperand(0), ValueIfFalse = N->getOperand(2);
683
684 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(ValueIfFalse);
685 if (!FalseC || FalseC->getZExtValue())
686 return SDValue();
687
688 // Since RHS (False) is 0, we swap the order of the True/False operands
689 // (obviously also inverting the condition) so that we can
690 // take advantage of conditional moves using the $0 register.
691 // Example:
692 // return (a != 0) ? x : 0;
693 // load $reg, x
694 // movz $reg, $0, a
695 unsigned Opc = (N->getOpcode() == MipsISD::CMovFP_T) ? MipsISD::CMovFP_F :
696 MipsISD::CMovFP_T;
697
698 SDValue FCC = N->getOperand(1), Glue = N->getOperand(3);
699 return DAG.getNode(Opc, SDLoc(N), ValueIfFalse.getValueType(),
700 ValueIfFalse, FCC, ValueIfTrue, Glue);
701}
702
705 const MipsSubtarget &Subtarget) {
706 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
707 return SDValue();
708
709 SDValue FirstOperand = N->getOperand(0);
710 unsigned FirstOperandOpc = FirstOperand.getOpcode();
711 SDValue Mask = N->getOperand(1);
712 EVT ValTy = N->getValueType(0);
713 SDLoc DL(N);
714
715 uint64_t Pos = 0;
716 unsigned SMPos, SMSize;
717 ConstantSDNode *CN;
718 SDValue NewOperand;
719 unsigned Opc;
720
721 // Op's second operand must be a shifted mask.
722 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
723 !isShiftedMask_64(CN->getZExtValue(), SMPos, SMSize))
724 return SDValue();
725
726 if (FirstOperandOpc == ISD::SRA || FirstOperandOpc == ISD::SRL) {
727 // Pattern match EXT.
728 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
729 // => ext $dst, $src, pos, size
730
731 // The second operand of the shift must be an immediate.
732 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))))
733 return SDValue();
734
735 Pos = CN->getZExtValue();
736
737 // Return if the shifted mask does not start at bit 0 or the sum of its size
738 // and Pos exceeds the word's size.
739 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
740 return SDValue();
741
742 Opc = MipsISD::Ext;
743 NewOperand = FirstOperand.getOperand(0);
744 } else if (FirstOperandOpc == ISD::SHL && Subtarget.hasCnMips()) {
745 // Pattern match CINS.
746 // $dst = and (shl $src , pos), mask
747 // => cins $dst, $src, pos, size
748 // mask is a shifted mask with consecutive 1's, pos = shift amount,
749 // size = population count.
750
751 // The second operand of the shift must be an immediate.
752 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))))
753 return SDValue();
754
755 Pos = CN->getZExtValue();
756
757 if (SMPos != Pos || Pos >= ValTy.getSizeInBits() || SMSize >= 32 ||
758 Pos + SMSize > ValTy.getSizeInBits())
759 return SDValue();
760
761 NewOperand = FirstOperand.getOperand(0);
762 // SMSize is 'location' (position) in this case, not size.
763 SMSize--;
764 Opc = MipsISD::CIns;
765 } else {
766 // Pattern match EXT.
767 // $dst = and $src, (2**size - 1) , if size > 16
768 // => ext $dst, $src, pos, size , pos = 0
769
770 // If the mask is <= 0xffff, andi can be used instead.
771 if (CN->getZExtValue() <= 0xffff)
772 return SDValue();
773
774 // Return if the mask doesn't start at position 0.
775 if (SMPos)
776 return SDValue();
777
778 Opc = MipsISD::Ext;
779 NewOperand = FirstOperand;
780 }
781 return DAG.getNode(Opc, DL, ValTy, NewOperand,
782 DAG.getConstant(Pos, DL, MVT::i32),
783 DAG.getConstant(SMSize, DL, MVT::i32));
784}
785
788 const MipsSubtarget &Subtarget) {
789 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
790 return SDValue();
791
792 SDValue FirstOperand = N->getOperand(0), SecondOperand = N->getOperand(1);
793 unsigned SMPos0, SMSize0, SMPos1, SMSize1;
794 ConstantSDNode *CN, *CN1;
795
796 if ((FirstOperand.getOpcode() == ISD::AND &&
797 SecondOperand.getOpcode() == ISD::SHL) ||
798 (FirstOperand.getOpcode() == ISD::SHL &&
799 SecondOperand.getOpcode() == ISD::AND)) {
800 // Pattern match INS.
801 // $dst = or (and $src1, (2**size0 - 1)), (shl $src2, size0)
802 // ==> ins $src1, $src2, pos, size, pos = size0, size = 32 - pos;
803 // Or:
804 // $dst = or (shl $src2, size0), (and $src1, (2**size0 - 1))
805 // ==> ins $src1, $src2, pos, size, pos = size0, size = 32 - pos;
806 SDValue AndOperand0 = FirstOperand.getOpcode() == ISD::AND
807 ? FirstOperand.getOperand(0)
808 : SecondOperand.getOperand(0);
809 SDValue ShlOperand0 = FirstOperand.getOpcode() == ISD::AND
810 ? SecondOperand.getOperand(0)
811 : FirstOperand.getOperand(0);
812 SDValue AndMask = FirstOperand.getOpcode() == ISD::AND
813 ? FirstOperand.getOperand(1)
814 : SecondOperand.getOperand(1);
815 if (!(CN = dyn_cast<ConstantSDNode>(AndMask)) ||
816 !isShiftedMask_64(CN->getZExtValue(), SMPos0, SMSize0))
817 return SDValue();
818
819 SDValue ShlShift = FirstOperand.getOpcode() == ISD::AND
820 ? SecondOperand.getOperand(1)
821 : FirstOperand.getOperand(1);
822 if (!(CN = dyn_cast<ConstantSDNode>(ShlShift)))
823 return SDValue();
824 uint64_t ShlShiftValue = CN->getZExtValue();
825
826 if (SMPos0 != 0 || SMSize0 != ShlShiftValue)
827 return SDValue();
828
829 SDLoc DL(N);
830 EVT ValTy = N->getValueType(0);
831 SMPos1 = ShlShiftValue;
832 assert(SMPos1 < ValTy.getSizeInBits());
833 SMSize1 = (ValTy == MVT::i64 ? 64 : 32) - SMPos1;
834 return DAG.getNode(MipsISD::Ins, DL, ValTy, ShlOperand0,
835 DAG.getConstant(SMPos1, DL, MVT::i32),
836 DAG.getConstant(SMSize1, DL, MVT::i32), AndOperand0);
837 }
838
839 // See if Op's first operand matches (and $src1 , mask0).
840 if (FirstOperand.getOpcode() != ISD::AND)
841 return SDValue();
842
843 // Pattern match INS.
844 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
845 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
846 // => ins $dst, $src, size, pos, $src1
847 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))) ||
848 !isShiftedMask_64(~CN->getSExtValue(), SMPos0, SMSize0))
849 return SDValue();
850
851 // See if Op's second operand matches (and (shl $src, pos), mask1).
852 if (SecondOperand.getOpcode() == ISD::AND &&
853 SecondOperand.getOperand(0).getOpcode() == ISD::SHL) {
854
855 if (!(CN = dyn_cast<ConstantSDNode>(SecondOperand.getOperand(1))) ||
856 !isShiftedMask_64(CN->getZExtValue(), SMPos1, SMSize1))
857 return SDValue();
858
859 // The shift masks must have the same position and size.
860 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
861 return SDValue();
862
863 SDValue Shl = SecondOperand.getOperand(0);
864
865 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
866 return SDValue();
867
868 unsigned Shamt = CN->getZExtValue();
869
870 // Return if the shift amount and the first bit position of mask are not the
871 // same.
872 EVT ValTy = N->getValueType(0);
873 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
874 return SDValue();
875
876 SDLoc DL(N);
877 return DAG.getNode(MipsISD::Ins, DL, ValTy, Shl.getOperand(0),
878 DAG.getConstant(SMPos0, DL, MVT::i32),
879 DAG.getConstant(SMSize0, DL, MVT::i32),
880 FirstOperand.getOperand(0));
881 } else {
882 // Pattern match DINS.
883 // $dst = or (and $src, mask0), mask1
884 // where mask0 = maskTrailingOnes<uint64_t>(SMSize0) << SMPos0
885 // => dins $dst, $src, pos, size
886 uint64_t Mask = maskTrailingOnes<uint64_t>(SMSize0) << SMPos0;
887 if (~CN->getSExtValue() == (int64_t)Mask &&
888 ((SMSize0 + SMPos0 <= 64 && Subtarget.hasMips64r2()) ||
889 (SMSize0 + SMPos0 <= 32))) {
890 // Check if AND instruction has constant as argument
891 bool isConstCase = SecondOperand.getOpcode() != ISD::AND;
892 if (SecondOperand.getOpcode() == ISD::AND) {
893 if (!(CN1 = dyn_cast<ConstantSDNode>(SecondOperand->getOperand(1))))
894 return SDValue();
895 } else {
896 if (!(CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1))))
897 return SDValue();
898 }
899 // Don't generate INS if constant OR operand doesn't fit into bits
900 // cleared by constant AND operand.
901 if (CN->getSExtValue() & CN1->getSExtValue())
902 return SDValue();
903
904 SDLoc DL(N);
905 EVT ValTy = N->getOperand(0)->getValueType(0);
906 SDValue Const1;
907 SDValue SrlX;
908 if (!isConstCase) {
909 Const1 = DAG.getConstant(SMPos0, DL, MVT::i32);
910 SrlX = DAG.getNode(ISD::SRL, DL, SecondOperand->getValueType(0),
911 SecondOperand, Const1);
912 }
913 return DAG.getNode(
914 MipsISD::Ins, DL, N->getValueType(0),
915 isConstCase
916 ? DAG.getSignedConstant(CN1->getSExtValue() >> SMPos0, DL, ValTy)
917 : SrlX,
918 DAG.getConstant(SMPos0, DL, MVT::i32),
919 DAG.getConstant(ValTy.getSizeInBits() / 8 < 8 ? SMSize0 & 31
920 : SMSize0,
921 DL, MVT::i32),
922 FirstOperand->getOperand(0));
923 }
924 return SDValue();
925 }
926}
927
929 const MipsSubtarget &Subtarget) {
930 // ROOTNode must have a multiplication as an operand for the match to be
931 // successful.
932 if (ROOTNode->getOperand(0).getOpcode() != ISD::MUL &&
933 ROOTNode->getOperand(1).getOpcode() != ISD::MUL)
934 return SDValue();
935
936 // In the case where we have a multiplication as the left operand of
937 // of a subtraction, we can't combine into a MipsISD::MSub node as the
938 // the instruction definition of msub(u) places the multiplication on
939 // on the right.
940 if (ROOTNode->getOpcode() == ISD::SUB &&
941 ROOTNode->getOperand(0).getOpcode() == ISD::MUL)
942 return SDValue();
943
944 // We don't handle vector types here.
945 if (ROOTNode->getValueType(0).isVector())
946 return SDValue();
947
948 // For MIPS64, madd / msub instructions are inefficent to use with 64 bit
949 // arithmetic. E.g.
950 // (add (mul a b) c) =>
951 // let res = (madd (mthi (drotr c 32))x(mtlo c) a b) in
952 // MIPS64: (or (dsll (mfhi res) 32) (dsrl (dsll (mflo res) 32) 32)
953 // or
954 // MIPS64R2: (dins (mflo res) (mfhi res) 32 32)
955 //
956 // The overhead of setting up the Hi/Lo registers and reassembling the
957 // result makes this a dubious optimzation for MIPS64. The core of the
958 // problem is that Hi/Lo contain the upper and lower 32 bits of the
959 // operand and result.
960 //
961 // It requires a chain of 4 add/mul for MIPS64R2 to get better code
962 // density than doing it naively, 5 for MIPS64. Additionally, using
963 // madd/msub on MIPS64 requires the operands actually be 32 bit sign
964 // extended operands, not true 64 bit values.
965 //
966 // FIXME: For the moment, disable this completely for MIPS64.
967 if (Subtarget.hasMips64())
968 return SDValue();
969
970 SDValue Mult = ROOTNode->getOperand(0).getOpcode() == ISD::MUL
971 ? ROOTNode->getOperand(0)
972 : ROOTNode->getOperand(1);
973
974 SDValue AddOperand = ROOTNode->getOperand(0).getOpcode() == ISD::MUL
975 ? ROOTNode->getOperand(1)
976 : ROOTNode->getOperand(0);
977
978 // Transform this to a MADD only if the user of this node is the add.
979 // If there are other users of the mul, this function returns here.
980 if (!Mult.hasOneUse())
981 return SDValue();
982
983 // maddu and madd are unusual instructions in that on MIPS64 bits 63..31
984 // must be in canonical form, i.e. sign extended. For MIPS32, the operands
985 // of the multiply must have 32 or more sign bits, otherwise we cannot
986 // perform this optimization. We have to check this here as we're performing
987 // this optimization pre-legalization.
988 SDValue MultLHS = Mult->getOperand(0);
989 SDValue MultRHS = Mult->getOperand(1);
990
991 bool IsSigned = MultLHS->getOpcode() == ISD::SIGN_EXTEND &&
992 MultRHS->getOpcode() == ISD::SIGN_EXTEND;
993 bool IsUnsigned = MultLHS->getOpcode() == ISD::ZERO_EXTEND &&
994 MultRHS->getOpcode() == ISD::ZERO_EXTEND;
995
996 if (!IsSigned && !IsUnsigned)
997 return SDValue();
998
999 // Initialize accumulator.
1000 SDLoc DL(ROOTNode);
1001 SDValue BottomHalf, TopHalf;
1002 std::tie(BottomHalf, TopHalf) =
1003 CurDAG.SplitScalar(AddOperand, DL, MVT::i32, MVT::i32);
1004 SDValue ACCIn =
1005 CurDAG.getNode(MipsISD::MTLOHI, DL, MVT::Untyped, BottomHalf, TopHalf);
1006
1007 // Create MipsMAdd(u) / MipsMSub(u) node.
1008 bool IsAdd = ROOTNode->getOpcode() == ISD::ADD;
1009 unsigned Opcode = IsAdd ? (IsUnsigned ? MipsISD::MAddu : MipsISD::MAdd)
1010 : (IsUnsigned ? MipsISD::MSubu : MipsISD::MSub);
1011 SDValue MAddOps[3] = {
1012 CurDAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mult->getOperand(0)),
1013 CurDAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mult->getOperand(1)), ACCIn};
1014 SDValue MAdd = CurDAG.getNode(Opcode, DL, MVT::Untyped, MAddOps);
1015
1016 SDValue ResLo = CurDAG.getNode(MipsISD::MFLO, DL, MVT::i32, MAdd);
1017 SDValue ResHi = CurDAG.getNode(MipsISD::MFHI, DL, MVT::i32, MAdd);
1018 SDValue Combined =
1019 CurDAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResLo, ResHi);
1020 return Combined;
1021}
1022
1025 const MipsSubtarget &Subtarget) {
1026 // (sub v0 (mul v1, v2)) => (msub v1, v2, v0)
1027 if (DCI.isBeforeLegalizeOps()) {
1028 if (Subtarget.hasMips32() && !Subtarget.hasMips32r6() &&
1029 !Subtarget.inMips16Mode() && N->getValueType(0) == MVT::i64)
1030 return performMADD_MSUBCombine(N, DAG, Subtarget);
1031
1032 return SDValue();
1033 }
1034
1035 return SDValue();
1036}
1037
1040 const MipsSubtarget &Subtarget) {
1041 // (add v0 (mul v1, v2)) => (madd v1, v2, v0)
1042 if (DCI.isBeforeLegalizeOps()) {
1043 if (Subtarget.hasMips32() && !Subtarget.hasMips32r6() &&
1044 !Subtarget.inMips16Mode() && N->getValueType(0) == MVT::i64)
1045 return performMADD_MSUBCombine(N, DAG, Subtarget);
1046
1047 return SDValue();
1048 }
1049
1050 // When loading from a jump table, push the Lo node to the position that
1051 // allows folding it into a load immediate.
1052 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
1053 // (add (add abs_lo(tjt), v1), v0) => (add (add v0, v1), abs_lo(tjt))
1054 SDValue InnerAdd = N->getOperand(1);
1055 SDValue Index = N->getOperand(0);
1056 if (InnerAdd.getOpcode() != ISD::ADD)
1057 std::swap(InnerAdd, Index);
1058 if (InnerAdd.getOpcode() != ISD::ADD)
1059 return SDValue();
1060
1061 SDValue Lo = InnerAdd.getOperand(0);
1062 SDValue Other = InnerAdd.getOperand(1);
1063 if (Lo.getOpcode() != MipsISD::Lo)
1064 std::swap(Lo, Other);
1065
1066 if ((Lo.getOpcode() != MipsISD::Lo) ||
1067 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
1068 return SDValue();
1069
1070 EVT ValTy = N->getValueType(0);
1071 SDLoc DL(N);
1072
1073 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, Index, Other);
1074 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
1075}
1076
1079 const MipsSubtarget &Subtarget) {
1080 // Pattern match CINS.
1081 // $dst = shl (and $src , imm), pos
1082 // => cins $dst, $src, pos, size
1083
1084 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasCnMips())
1085 return SDValue();
1086
1087 SDValue FirstOperand = N->getOperand(0);
1088 unsigned FirstOperandOpc = FirstOperand.getOpcode();
1089 SDValue SecondOperand = N->getOperand(1);
1090 EVT ValTy = N->getValueType(0);
1091 SDLoc DL(N);
1092
1093 uint64_t Pos = 0;
1094 unsigned SMPos, SMSize;
1095 ConstantSDNode *CN;
1096 SDValue NewOperand;
1097
1098 // The second operand of the shift must be an immediate.
1099 if (!(CN = dyn_cast<ConstantSDNode>(SecondOperand)))
1100 return SDValue();
1101
1102 Pos = CN->getZExtValue();
1103
1104 if (Pos >= ValTy.getSizeInBits())
1105 return SDValue();
1106
1107 if (FirstOperandOpc != ISD::AND)
1108 return SDValue();
1109
1110 // AND's second operand must be a shifted mask.
1111 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))) ||
1112 !isShiftedMask_64(CN->getZExtValue(), SMPos, SMSize))
1113 return SDValue();
1114
1115 // Return if the shifted mask does not start at bit 0 or the sum of its size
1116 // and Pos exceeds the word's size.
1117 if (SMPos != 0 || SMSize > 32 || Pos + SMSize > ValTy.getSizeInBits())
1118 return SDValue();
1119
1120 NewOperand = FirstOperand.getOperand(0);
1121 // SMSize is 'location' (position) in this case, not size.
1122 SMSize--;
1123
1124 return DAG.getNode(MipsISD::CIns, DL, ValTy, NewOperand,
1125 DAG.getConstant(Pos, DL, MVT::i32),
1126 DAG.getConstant(SMSize, DL, MVT::i32));
1127}
1128
1131 const MipsSubtarget &Subtarget) {
1132 if (DCI.Level != AfterLegalizeDAG || !Subtarget.isGP64bit()) {
1133 return SDValue();
1134 }
1135
1136 SDValue N0 = N->getOperand(0);
1137 EVT VT = N->getValueType(0);
1138
1139 // Pattern match XOR.
1140 // $dst = sign_extend (xor (trunc $src, i32), imm)
1141 // => $dst = xor (signext_inreg $src, i32), imm
1142 if (N0.getOpcode() == ISD::XOR &&
1143 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
1144 N0.getOperand(1).getOpcode() == ISD::Constant) {
1145 SDValue TruncateSource = N0.getOperand(0).getOperand(0);
1146 auto *ConstantOperand = dyn_cast<ConstantSDNode>(N0->getOperand(1));
1147
1148 SDValue FirstOperand =
1149 DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N0), VT, TruncateSource,
1150 DAG.getValueType(N0.getOperand(0).getValueType()));
1151
1152 int64_t ConstImm = ConstantOperand->getSExtValue();
1153 return DAG.getNode(ISD::XOR, SDLoc(N0), VT, FirstOperand,
1154 DAG.getConstant(ConstImm, SDLoc(N0), VT));
1155 }
1156
1157 return SDValue();
1158}
1159
1161 const {
1162 SelectionDAG &DAG = DCI.DAG;
1163 unsigned Opc = N->getOpcode();
1164
1165 switch (Opc) {
1166 default: break;
1167 case ISD::SDIVREM:
1168 case ISD::UDIVREM:
1169 return performDivRemCombine(N, DAG, DCI, Subtarget);
1170 case ISD::SELECT:
1171 return performSELECTCombine(N, DAG, DCI, Subtarget);
1172 case MipsISD::CMovFP_F:
1173 case MipsISD::CMovFP_T:
1174 return performCMovFPCombine(N, DAG, DCI, Subtarget);
1175 case ISD::AND:
1176 return performANDCombine(N, DAG, DCI, Subtarget);
1177 case ISD::OR:
1178 return performORCombine(N, DAG, DCI, Subtarget);
1179 case ISD::ADD:
1180 return performADDCombine(N, DAG, DCI, Subtarget);
1181 case ISD::SHL:
1182 return performSHLCombine(N, DAG, DCI, Subtarget);
1183 case ISD::SUB:
1184 return performSUBCombine(N, DAG, DCI, Subtarget);
1185 case ISD::SIGN_EXTEND:
1186 return performSignExtendCombine(N, DAG, DCI, Subtarget);
1187 }
1188
1189 return SDValue();
1190}
1191
1193 return Subtarget.hasMips32();
1194}
1195
1197 return Subtarget.hasMips32();
1198}
1199
1201 // We can use ANDI+SLTIU as a bit test. Y contains the bit position.
1202 // For MIPSR2 or later, we may be able to use the `ext` instruction or its
1203 // double-word variants.
1204 if (auto *C = dyn_cast<ConstantSDNode>(Y))
1205 return C->getAPIntValue().ule(15);
1206
1207 return false;
1208}
1209
1211 const SDNode *N) const {
1212 assert(((N->getOpcode() == ISD::SHL &&
1213 N->getOperand(0).getOpcode() == ISD::SRL) ||
1214 (N->getOpcode() == ISD::SRL &&
1215 N->getOperand(0).getOpcode() == ISD::SHL)) &&
1216 "Expected shift-shift mask");
1217
1218 if (N->getOperand(0).getValueType().isVector())
1219 return false;
1220 return true;
1221}
1222
1223void
1229
1232{
1233 switch (Op.getOpcode())
1234 {
1235 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
1236 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
1237 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
1238 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
1239 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
1240 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
1241 case ISD::SELECT: return lowerSELECT(Op, DAG);
1242 case ISD::SETCC: return lowerSETCC(Op, DAG);
1243 case ISD::STRICT_FSETCC:
1245 return lowerFSETCC(Op, DAG);
1246 case ISD::VASTART: return lowerVASTART(Op, DAG);
1247 case ISD::VAARG: return lowerVAARG(Op, DAG);
1248 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
1249 case ISD::FABS: return lowerFABS(Op, DAG);
1250 case ISD::FCANONICALIZE:
1251 return lowerFCANONICALIZE(Op, DAG);
1252 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
1253 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
1254 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
1255 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
1256 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
1257 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
1258 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
1259 case ISD::LOAD: return lowerLOAD(Op, DAG);
1260 case ISD::STORE: return lowerSTORE(Op, DAG);
1261 case ISD::EH_DWARF_CFA: return lowerEH_DWARF_CFA(Op, DAG);
1264 return lowerSTRICT_FP_TO_INT(Op, DAG);
1265 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
1267 return lowerREADCYCLECOUNTER(Op, DAG);
1268 }
1269 return SDValue();
1270}
1271
1272//===----------------------------------------------------------------------===//
1273// Lower helper functions
1274//===----------------------------------------------------------------------===//
1275
1276// addLiveIn - This helper function adds the specified physical register to the
1277// MachineFunction as a live in value. It also creates a corresponding
1278// virtual register for it.
1279static unsigned
1280addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
1281{
1283 MF.getRegInfo().addLiveIn(PReg, VReg);
1284 return VReg;
1285}
1286
1287static MachineBasicBlock *
1289 const TargetInstrInfo &TII, bool Is64Bit,
1290 const DivByZeroTrapKind TrapKind) {
1291 if (NoZeroDivCheck)
1292 return &MBB;
1293
1294 MachineOperand &Divisor = MI.getOperand(2);
1295
1296 if (TrapKind == DivByZeroTrapKind::Break) {
1297 // Build instructions:
1298 // MBB:
1299 // bnez $divisor, $zero, SinkMBB
1300 // MI $dst, $dividend, $divisor (delay slot)
1301 //
1302 // BreakMBB:
1303 // break 7
1304 //
1305 // SinkMBB:
1306 // fallthrough
1307 const DebugLoc &DL = MI.getDebugLoc();
1308 const BasicBlock *BB = MBB.getBasicBlock();
1309
1310 // Place all instructions after MI into SinkMBB.
1311 MachineBasicBlock *SinkMBB = MBB.splitAt(MI, true);
1312
1313 // BreakMBB setup.
1314 MachineFunction *MF = MBB.getParent();
1315 MachineBasicBlock *BreakMBB = MF->CreateMachineBasicBlock(BB);
1316 MF->insert(++MBB.getIterator(), BreakMBB);
1317
1318 // Place the branch at the end of the block. Since MI is defined as having
1319 // no side effects in TableGen, the filler will place it in the branch delay
1320 // slot.
1321 BuildMI(&MBB, DL, TII.get(Mips::BNE))
1322 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
1323 .addReg(Mips::ZERO)
1324 .addMBB(SinkMBB);
1325
1326 // BreakMBB: break 7
1327 BuildMI(BreakMBB, DL, TII.get(Mips::BREAK)).addImm(7).addImm(0);
1328
1329 MBB.addSuccessor(BreakMBB);
1330 BreakMBB->addSuccessor(SinkMBB);
1331
1332 Divisor.setIsKill(false);
1333
1334 return SinkMBB;
1335 }
1336
1337 // Insert instruction "teq $divisor_reg, $zero, 7".
1340 MIB = BuildMI(MBB, std::next(I), MI.getDebugLoc(),
1341 TII.get(TrapKind == DivByZeroTrapKind::TeqMM ? Mips::TEQ_MM
1342 : Mips::TEQ))
1343 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
1344 .addReg(Mips::ZERO)
1345 .addImm(7);
1346
1347 // Use the 32-bit sub-register if this is a 64-bit division.
1348 if (Is64Bit)
1349 MIB->getOperand(0).setSubReg(Mips::sub_32);
1350
1351 // Clear Divisor's kill flag.
1352 Divisor.setIsKill(false);
1353
1354 // We would normally delete the original instruction here but in this case
1355 // we only needed to inject an additional instruction rather than replace it.
1356
1357 return &MBB;
1358}
1359
1362 MachineBasicBlock *BB) const {
1363 switch (MI.getOpcode()) {
1364 default:
1365 llvm_unreachable("Unexpected instr type to insert");
1366 case Mips::ATOMIC_LOAD_ADD_I8:
1367 return emitAtomicBinaryPartword(MI, BB, 1);
1368 case Mips::ATOMIC_LOAD_ADD_I16:
1369 return emitAtomicBinaryPartword(MI, BB, 2);
1370 case Mips::ATOMIC_LOAD_ADD_I32:
1371 return emitAtomicBinary(MI, BB);
1372 case Mips::ATOMIC_LOAD_ADD_I64:
1373 return emitAtomicBinary(MI, BB);
1374
1375 case Mips::ATOMIC_LOAD_AND_I8:
1376 return emitAtomicBinaryPartword(MI, BB, 1);
1377 case Mips::ATOMIC_LOAD_AND_I16:
1378 return emitAtomicBinaryPartword(MI, BB, 2);
1379 case Mips::ATOMIC_LOAD_AND_I32:
1380 return emitAtomicBinary(MI, BB);
1381 case Mips::ATOMIC_LOAD_AND_I64:
1382 return emitAtomicBinary(MI, BB);
1383
1384 case Mips::ATOMIC_LOAD_OR_I8:
1385 return emitAtomicBinaryPartword(MI, BB, 1);
1386 case Mips::ATOMIC_LOAD_OR_I16:
1387 return emitAtomicBinaryPartword(MI, BB, 2);
1388 case Mips::ATOMIC_LOAD_OR_I32:
1389 return emitAtomicBinary(MI, BB);
1390 case Mips::ATOMIC_LOAD_OR_I64:
1391 return emitAtomicBinary(MI, BB);
1392
1393 case Mips::ATOMIC_LOAD_XOR_I8:
1394 return emitAtomicBinaryPartword(MI, BB, 1);
1395 case Mips::ATOMIC_LOAD_XOR_I16:
1396 return emitAtomicBinaryPartword(MI, BB, 2);
1397 case Mips::ATOMIC_LOAD_XOR_I32:
1398 return emitAtomicBinary(MI, BB);
1399 case Mips::ATOMIC_LOAD_XOR_I64:
1400 return emitAtomicBinary(MI, BB);
1401
1402 case Mips::ATOMIC_LOAD_NAND_I8:
1403 return emitAtomicBinaryPartword(MI, BB, 1);
1404 case Mips::ATOMIC_LOAD_NAND_I16:
1405 return emitAtomicBinaryPartword(MI, BB, 2);
1406 case Mips::ATOMIC_LOAD_NAND_I32:
1407 return emitAtomicBinary(MI, BB);
1408 case Mips::ATOMIC_LOAD_NAND_I64:
1409 return emitAtomicBinary(MI, BB);
1410
1411 case Mips::ATOMIC_LOAD_SUB_I8:
1412 return emitAtomicBinaryPartword(MI, BB, 1);
1413 case Mips::ATOMIC_LOAD_SUB_I16:
1414 return emitAtomicBinaryPartword(MI, BB, 2);
1415 case Mips::ATOMIC_LOAD_SUB_I32:
1416 return emitAtomicBinary(MI, BB);
1417 case Mips::ATOMIC_LOAD_SUB_I64:
1418 return emitAtomicBinary(MI, BB);
1419
1420 case Mips::ATOMIC_SWAP_I8:
1421 return emitAtomicBinaryPartword(MI, BB, 1);
1422 case Mips::ATOMIC_SWAP_I16:
1423 return emitAtomicBinaryPartword(MI, BB, 2);
1424 case Mips::ATOMIC_SWAP_I32:
1425 return emitAtomicBinary(MI, BB);
1426 case Mips::ATOMIC_SWAP_I64:
1427 return emitAtomicBinary(MI, BB);
1428
1429 case Mips::ATOMIC_CMP_SWAP_I8:
1430 return emitAtomicCmpSwapPartword(MI, BB, 1);
1431 case Mips::ATOMIC_CMP_SWAP_I16:
1432 return emitAtomicCmpSwapPartword(MI, BB, 2);
1433 case Mips::ATOMIC_CMP_SWAP_I32:
1434 return emitAtomicCmpSwap(MI, BB);
1435 case Mips::ATOMIC_CMP_SWAP_I64:
1436 return emitAtomicCmpSwap(MI, BB);
1437
1438 case Mips::ATOMIC_LOAD_MIN_I8:
1439 return emitAtomicBinaryPartword(MI, BB, 1);
1440 case Mips::ATOMIC_LOAD_MIN_I16:
1441 return emitAtomicBinaryPartword(MI, BB, 2);
1442 case Mips::ATOMIC_LOAD_MIN_I32:
1443 return emitAtomicBinary(MI, BB);
1444 case Mips::ATOMIC_LOAD_MIN_I64:
1445 return emitAtomicBinary(MI, BB);
1446
1447 case Mips::ATOMIC_LOAD_MAX_I8:
1448 return emitAtomicBinaryPartword(MI, BB, 1);
1449 case Mips::ATOMIC_LOAD_MAX_I16:
1450 return emitAtomicBinaryPartword(MI, BB, 2);
1451 case Mips::ATOMIC_LOAD_MAX_I32:
1452 return emitAtomicBinary(MI, BB);
1453 case Mips::ATOMIC_LOAD_MAX_I64:
1454 return emitAtomicBinary(MI, BB);
1455
1456 case Mips::ATOMIC_LOAD_UMIN_I8:
1457 return emitAtomicBinaryPartword(MI, BB, 1);
1458 case Mips::ATOMIC_LOAD_UMIN_I16:
1459 return emitAtomicBinaryPartword(MI, BB, 2);
1460 case Mips::ATOMIC_LOAD_UMIN_I32:
1461 return emitAtomicBinary(MI, BB);
1462 case Mips::ATOMIC_LOAD_UMIN_I64:
1463 return emitAtomicBinary(MI, BB);
1464
1465 case Mips::ATOMIC_LOAD_UMAX_I8:
1466 return emitAtomicBinaryPartword(MI, BB, 1);
1467 case Mips::ATOMIC_LOAD_UMAX_I16:
1468 return emitAtomicBinaryPartword(MI, BB, 2);
1469 case Mips::ATOMIC_LOAD_UMAX_I32:
1470 return emitAtomicBinary(MI, BB);
1471 case Mips::ATOMIC_LOAD_UMAX_I64:
1472 return emitAtomicBinary(MI, BB);
1473
1474 case Mips::PseudoSDIV:
1475 case Mips::PseudoUDIV:
1476 case Mips::DIV:
1477 case Mips::DIVU:
1478 case Mips::MOD:
1479 case Mips::MODU: {
1480 const DivByZeroTrapKind TrapKind = !Subtarget.hasMips2()
1483 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false,
1484 TrapKind);
1485 }
1486 case Mips::SDIV_MM_Pseudo:
1487 case Mips::UDIV_MM_Pseudo:
1488 case Mips::SDIV_MM:
1489 case Mips::UDIV_MM:
1490 case Mips::DIV_MMR6:
1491 case Mips::DIVU_MMR6:
1492 case Mips::MOD_MMR6:
1493 case Mips::MODU_MMR6:
1494 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false,
1496 case Mips::PseudoDSDIV:
1497 case Mips::PseudoDUDIV:
1498 case Mips::DDIV:
1499 case Mips::DDIVU:
1500 case Mips::DMOD:
1501 case Mips::DMODU:
1502 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), true,
1504
1505 case Mips::PseudoSELECT_I:
1506 case Mips::PseudoSELECT_I64:
1507 case Mips::PseudoSELECT_S:
1508 case Mips::PseudoSELECT_D32:
1509 case Mips::PseudoSELECT_D64:
1510 return emitPseudoSELECT(MI, BB, false, Mips::BNE);
1511 case Mips::PseudoSELECTFP_F_I:
1512 case Mips::PseudoSELECTFP_F_I64:
1513 case Mips::PseudoSELECTFP_F_S:
1514 case Mips::PseudoSELECTFP_F_D32:
1515 case Mips::PseudoSELECTFP_F_D64:
1516 return emitPseudoSELECT(MI, BB, true, Mips::BC1F);
1517 case Mips::PseudoSELECTFP_T_I:
1518 case Mips::PseudoSELECTFP_T_I64:
1519 case Mips::PseudoSELECTFP_T_S:
1520 case Mips::PseudoSELECTFP_T_D32:
1521 case Mips::PseudoSELECTFP_T_D64:
1522 return emitPseudoSELECT(MI, BB, true, Mips::BC1T);
1523 case Mips::PseudoD_SELECT_I:
1524 case Mips::PseudoD_SELECT_I64:
1525 return emitPseudoD_SELECT(MI, BB);
1526 case Mips::LDR_W:
1527 return emitLDR_W(MI, BB);
1528 case Mips::LDR_D:
1529 return emitLDR_D(MI, BB);
1530 case Mips::STR_W:
1531 return emitSTR_W(MI, BB);
1532 case Mips::STR_D:
1533 return emitSTR_D(MI, BB);
1534 }
1535}
1536
1537// This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1538// Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1540MipsTargetLowering::emitAtomicBinary(MachineInstr &MI,
1541 MachineBasicBlock *BB) const {
1542
1543 MachineFunction *MF = BB->getParent();
1544 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1546 DebugLoc DL = MI.getDebugLoc();
1547
1548 unsigned AtomicOp;
1549 bool NeedsAdditionalReg = false;
1550 switch (MI.getOpcode()) {
1551 case Mips::ATOMIC_LOAD_ADD_I32:
1552 AtomicOp = Mips::ATOMIC_LOAD_ADD_I32_POSTRA;
1553 break;
1554 case Mips::ATOMIC_LOAD_SUB_I32:
1555 AtomicOp = Mips::ATOMIC_LOAD_SUB_I32_POSTRA;
1556 break;
1557 case Mips::ATOMIC_LOAD_AND_I32:
1558 AtomicOp = Mips::ATOMIC_LOAD_AND_I32_POSTRA;
1559 break;
1560 case Mips::ATOMIC_LOAD_OR_I32:
1561 AtomicOp = Mips::ATOMIC_LOAD_OR_I32_POSTRA;
1562 break;
1563 case Mips::ATOMIC_LOAD_XOR_I32:
1564 AtomicOp = Mips::ATOMIC_LOAD_XOR_I32_POSTRA;
1565 break;
1566 case Mips::ATOMIC_LOAD_NAND_I32:
1567 AtomicOp = Mips::ATOMIC_LOAD_NAND_I32_POSTRA;
1568 break;
1569 case Mips::ATOMIC_SWAP_I32:
1570 AtomicOp = Mips::ATOMIC_SWAP_I32_POSTRA;
1571 break;
1572 case Mips::ATOMIC_LOAD_ADD_I64:
1573 AtomicOp = Mips::ATOMIC_LOAD_ADD_I64_POSTRA;
1574 break;
1575 case Mips::ATOMIC_LOAD_SUB_I64:
1576 AtomicOp = Mips::ATOMIC_LOAD_SUB_I64_POSTRA;
1577 break;
1578 case Mips::ATOMIC_LOAD_AND_I64:
1579 AtomicOp = Mips::ATOMIC_LOAD_AND_I64_POSTRA;
1580 break;
1581 case Mips::ATOMIC_LOAD_OR_I64:
1582 AtomicOp = Mips::ATOMIC_LOAD_OR_I64_POSTRA;
1583 break;
1584 case Mips::ATOMIC_LOAD_XOR_I64:
1585 AtomicOp = Mips::ATOMIC_LOAD_XOR_I64_POSTRA;
1586 break;
1587 case Mips::ATOMIC_LOAD_NAND_I64:
1588 AtomicOp = Mips::ATOMIC_LOAD_NAND_I64_POSTRA;
1589 break;
1590 case Mips::ATOMIC_SWAP_I64:
1591 AtomicOp = Mips::ATOMIC_SWAP_I64_POSTRA;
1592 break;
1593 case Mips::ATOMIC_LOAD_MIN_I32:
1594 AtomicOp = Mips::ATOMIC_LOAD_MIN_I32_POSTRA;
1595 NeedsAdditionalReg = true;
1596 break;
1597 case Mips::ATOMIC_LOAD_MAX_I32:
1598 AtomicOp = Mips::ATOMIC_LOAD_MAX_I32_POSTRA;
1599 NeedsAdditionalReg = true;
1600 break;
1601 case Mips::ATOMIC_LOAD_UMIN_I32:
1602 AtomicOp = Mips::ATOMIC_LOAD_UMIN_I32_POSTRA;
1603 NeedsAdditionalReg = true;
1604 break;
1605 case Mips::ATOMIC_LOAD_UMAX_I32:
1606 AtomicOp = Mips::ATOMIC_LOAD_UMAX_I32_POSTRA;
1607 NeedsAdditionalReg = true;
1608 break;
1609 case Mips::ATOMIC_LOAD_MIN_I64:
1610 AtomicOp = Mips::ATOMIC_LOAD_MIN_I64_POSTRA;
1611 NeedsAdditionalReg = true;
1612 break;
1613 case Mips::ATOMIC_LOAD_MAX_I64:
1614 AtomicOp = Mips::ATOMIC_LOAD_MAX_I64_POSTRA;
1615 NeedsAdditionalReg = true;
1616 break;
1617 case Mips::ATOMIC_LOAD_UMIN_I64:
1618 AtomicOp = Mips::ATOMIC_LOAD_UMIN_I64_POSTRA;
1619 NeedsAdditionalReg = true;
1620 break;
1621 case Mips::ATOMIC_LOAD_UMAX_I64:
1622 AtomicOp = Mips::ATOMIC_LOAD_UMAX_I64_POSTRA;
1623 NeedsAdditionalReg = true;
1624 break;
1625 default:
1626 llvm_unreachable("Unknown pseudo atomic for replacement!");
1627 }
1628
1629 Register OldVal = MI.getOperand(0).getReg();
1630 Register Ptr = MI.getOperand(1).getReg();
1631 Register Incr = MI.getOperand(2).getReg();
1632 Register Scratch = RegInfo.createVirtualRegister(RegInfo.getRegClass(OldVal));
1633
1635
1636 // The scratch registers here with the EarlyClobber | Define | Implicit
1637 // flags is used to persuade the register allocator and the machine
1638 // verifier to accept the usage of this register. This has to be a real
1639 // register which has an UNDEF value but is dead after the instruction which
1640 // is unique among the registers chosen for the instruction.
1641
1642 // The EarlyClobber flag has the semantic properties that the operand it is
1643 // attached to is clobbered before the rest of the inputs are read. Hence it
1644 // must be unique among the operands to the instruction.
1645 // The Define flag is needed to coerce the machine verifier that an Undef
1646 // value isn't a problem.
1647 // The Dead flag is needed as the value in scratch isn't used by any other
1648 // instruction. Kill isn't used as Dead is more precise.
1649 // The implicit flag is here due to the interaction between the other flags
1650 // and the machine verifier.
1651
1652 // For correctness purpose, a new pseudo is introduced here. We need this
1653 // new pseudo, so that FastRegisterAllocator does not see an ll/sc sequence
1654 // that is spread over >1 basic blocks. A register allocator which
1655 // introduces (or any codegen infact) a store, can violate the expectations
1656 // of the hardware.
1657 //
1658 // An atomic read-modify-write sequence starts with a linked load
1659 // instruction and ends with a store conditional instruction. The atomic
1660 // read-modify-write sequence fails if any of the following conditions
1661 // occur between the execution of ll and sc:
1662 // * A coherent store is completed by another process or coherent I/O
1663 // module into the block of synchronizable physical memory containing
1664 // the word. The size and alignment of the block is
1665 // implementation-dependent.
1666 // * A coherent store is executed between an LL and SC sequence on the
1667 // same processor to the block of synchornizable physical memory
1668 // containing the word.
1669 //
1670
1671 Register PtrCopy = RegInfo.createVirtualRegister(RegInfo.getRegClass(Ptr));
1672 Register IncrCopy = RegInfo.createVirtualRegister(RegInfo.getRegClass(Incr));
1673
1674 BuildMI(*BB, II, DL, TII->get(Mips::COPY), IncrCopy).addReg(Incr);
1675 BuildMI(*BB, II, DL, TII->get(Mips::COPY), PtrCopy).addReg(Ptr);
1676
1678 BuildMI(*BB, II, DL, TII->get(AtomicOp))
1680 .addReg(PtrCopy)
1681 .addReg(IncrCopy)
1684 if (NeedsAdditionalReg) {
1685 Register Scratch2 =
1686 RegInfo.createVirtualRegister(RegInfo.getRegClass(OldVal));
1689 }
1690
1691 MI.eraseFromParent();
1692
1693 return BB;
1694}
1695
1696MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1697 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1698 unsigned SrcReg) const {
1699 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1700 const DebugLoc &DL = MI.getDebugLoc();
1701
1702 if (Subtarget.hasMips32r2() && Size == 1) {
1703 BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1704 return BB;
1705 }
1706
1707 if (Subtarget.hasMips32r2() && Size == 2) {
1708 BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1709 return BB;
1710 }
1711
1712 MachineFunction *MF = BB->getParent();
1713 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1714 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1715 Register ScrReg = RegInfo.createVirtualRegister(RC);
1716
1717 assert(Size < 32);
1718 int64_t ShiftImm = 32 - (Size * 8);
1719
1720 BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1721 BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1722
1723 return BB;
1724}
1725
1726MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1727 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size) const {
1728 assert((Size == 1 || Size == 2) &&
1729 "Unsupported size for EmitAtomicBinaryPartial.");
1730
1731 MachineFunction *MF = BB->getParent();
1732 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1733 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1734 const bool ArePtrs64bit = ABI.ArePtrs64bit();
1735 const TargetRegisterClass *RCp =
1736 getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32);
1737 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1738 DebugLoc DL = MI.getDebugLoc();
1739
1740 Register Dest = MI.getOperand(0).getReg();
1741 Register Ptr = MI.getOperand(1).getReg();
1742 Register Incr = MI.getOperand(2).getReg();
1743
1744 Register AlignedAddr = RegInfo.createVirtualRegister(RCp);
1745 Register ShiftAmt = RegInfo.createVirtualRegister(RC);
1746 Register Mask = RegInfo.createVirtualRegister(RC);
1747 Register Mask2 = RegInfo.createVirtualRegister(RC);
1748 Register Incr2 = RegInfo.createVirtualRegister(RC);
1749 Register MaskLSB2 = RegInfo.createVirtualRegister(RCp);
1750 Register PtrLSB2 = RegInfo.createVirtualRegister(RC);
1751 Register MaskUpper = RegInfo.createVirtualRegister(RC);
1752 Register Scratch = RegInfo.createVirtualRegister(RC);
1753 Register Scratch2 = RegInfo.createVirtualRegister(RC);
1754 Register Scratch3 = RegInfo.createVirtualRegister(RC);
1755
1756 unsigned AtomicOp = 0;
1757 bool NeedsAdditionalReg = false;
1758 switch (MI.getOpcode()) {
1759 case Mips::ATOMIC_LOAD_NAND_I8:
1760 AtomicOp = Mips::ATOMIC_LOAD_NAND_I8_POSTRA;
1761 break;
1762 case Mips::ATOMIC_LOAD_NAND_I16:
1763 AtomicOp = Mips::ATOMIC_LOAD_NAND_I16_POSTRA;
1764 break;
1765 case Mips::ATOMIC_SWAP_I8:
1766 AtomicOp = Mips::ATOMIC_SWAP_I8_POSTRA;
1767 break;
1768 case Mips::ATOMIC_SWAP_I16:
1769 AtomicOp = Mips::ATOMIC_SWAP_I16_POSTRA;
1770 break;
1771 case Mips::ATOMIC_LOAD_ADD_I8:
1772 AtomicOp = Mips::ATOMIC_LOAD_ADD_I8_POSTRA;
1773 break;
1774 case Mips::ATOMIC_LOAD_ADD_I16:
1775 AtomicOp = Mips::ATOMIC_LOAD_ADD_I16_POSTRA;
1776 break;
1777 case Mips::ATOMIC_LOAD_SUB_I8:
1778 AtomicOp = Mips::ATOMIC_LOAD_SUB_I8_POSTRA;
1779 break;
1780 case Mips::ATOMIC_LOAD_SUB_I16:
1781 AtomicOp = Mips::ATOMIC_LOAD_SUB_I16_POSTRA;
1782 break;
1783 case Mips::ATOMIC_LOAD_AND_I8:
1784 AtomicOp = Mips::ATOMIC_LOAD_AND_I8_POSTRA;
1785 break;
1786 case Mips::ATOMIC_LOAD_AND_I16:
1787 AtomicOp = Mips::ATOMIC_LOAD_AND_I16_POSTRA;
1788 break;
1789 case Mips::ATOMIC_LOAD_OR_I8:
1790 AtomicOp = Mips::ATOMIC_LOAD_OR_I8_POSTRA;
1791 break;
1792 case Mips::ATOMIC_LOAD_OR_I16:
1793 AtomicOp = Mips::ATOMIC_LOAD_OR_I16_POSTRA;
1794 break;
1795 case Mips::ATOMIC_LOAD_XOR_I8:
1796 AtomicOp = Mips::ATOMIC_LOAD_XOR_I8_POSTRA;
1797 break;
1798 case Mips::ATOMIC_LOAD_XOR_I16:
1799 AtomicOp = Mips::ATOMIC_LOAD_XOR_I16_POSTRA;
1800 break;
1801 case Mips::ATOMIC_LOAD_MIN_I8:
1802 AtomicOp = Mips::ATOMIC_LOAD_MIN_I8_POSTRA;
1803 NeedsAdditionalReg = true;
1804 break;
1805 case Mips::ATOMIC_LOAD_MIN_I16:
1806 AtomicOp = Mips::ATOMIC_LOAD_MIN_I16_POSTRA;
1807 NeedsAdditionalReg = true;
1808 break;
1809 case Mips::ATOMIC_LOAD_MAX_I8:
1810 AtomicOp = Mips::ATOMIC_LOAD_MAX_I8_POSTRA;
1811 NeedsAdditionalReg = true;
1812 break;
1813 case Mips::ATOMIC_LOAD_MAX_I16:
1814 AtomicOp = Mips::ATOMIC_LOAD_MAX_I16_POSTRA;
1815 NeedsAdditionalReg = true;
1816 break;
1817 case Mips::ATOMIC_LOAD_UMIN_I8:
1818 AtomicOp = Mips::ATOMIC_LOAD_UMIN_I8_POSTRA;
1819 NeedsAdditionalReg = true;
1820 break;
1821 case Mips::ATOMIC_LOAD_UMIN_I16:
1822 AtomicOp = Mips::ATOMIC_LOAD_UMIN_I16_POSTRA;
1823 NeedsAdditionalReg = true;
1824 break;
1825 case Mips::ATOMIC_LOAD_UMAX_I8:
1826 AtomicOp = Mips::ATOMIC_LOAD_UMAX_I8_POSTRA;
1827 NeedsAdditionalReg = true;
1828 break;
1829 case Mips::ATOMIC_LOAD_UMAX_I16:
1830 AtomicOp = Mips::ATOMIC_LOAD_UMAX_I16_POSTRA;
1831 NeedsAdditionalReg = true;
1832 break;
1833 default:
1834 llvm_unreachable("Unknown subword atomic pseudo for expansion!");
1835 }
1836
1837 // insert new blocks after the current block
1838 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1839 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1841 MF->insert(It, exitMBB);
1842
1843 // Transfer the remainder of BB and its successor edges to exitMBB.
1844 exitMBB->splice(exitMBB->begin(), BB,
1845 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1847
1849
1850 // thisMBB:
1851 // addiu masklsb2,$0,-4 # 0xfffffffc
1852 // and alignedaddr,ptr,masklsb2
1853 // andi ptrlsb2,ptr,3
1854 // sll shiftamt,ptrlsb2,3
1855 // ori maskupper,$0,255 # 0xff
1856 // sll mask,maskupper,shiftamt
1857 // nor mask2,$0,mask
1858 // sll incr2,incr,shiftamt
1859
1860 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1861 BuildMI(BB, DL, TII->get(ABI.GetPtrAddiuOp()), MaskLSB2)
1862 .addReg(ABI.GetNullPtr()).addImm(-4);
1863 BuildMI(BB, DL, TII->get(ABI.GetPtrAndOp()), AlignedAddr)
1864 .addReg(Ptr).addReg(MaskLSB2);
1865 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2)
1866 .addReg(Ptr, {}, ArePtrs64bit ? Mips::sub_32 : 0)
1867 .addImm(3);
1868 if (Subtarget.isLittle()) {
1869 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1870 } else {
1871 Register Off = RegInfo.createVirtualRegister(RC);
1872 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1873 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1874 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1875 }
1876 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1877 .addReg(Mips::ZERO).addImm(MaskImm);
1878 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1879 .addReg(MaskUpper).addReg(ShiftAmt);
1880 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1881 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1882
1883
1884 // The purposes of the flags on the scratch registers is explained in
1885 // emitAtomicBinary. In summary, we need a scratch register which is going to
1886 // be undef, that is unique among registers chosen for the instruction.
1887
1888 MachineInstrBuilder MIB =
1889 BuildMI(BB, DL, TII->get(AtomicOp))
1891 .addReg(AlignedAddr)
1892 .addReg(Incr2)
1893 .addReg(Mask)
1894 .addReg(Mask2)
1895 .addReg(ShiftAmt)
1902 if (NeedsAdditionalReg) {
1903 Register Scratch4 = RegInfo.createVirtualRegister(RC);
1906 }
1907
1908 MI.eraseFromParent(); // The instruction is gone now.
1909
1910 return exitMBB;
1911}
1912
1913// Lower atomic compare and swap to a pseudo instruction, taking care to
1914// define a scratch register for the pseudo instruction's expansion. The
1915// instruction is expanded after the register allocator as to prevent
1916// the insertion of stores between the linked load and the store conditional.
1917
1919MipsTargetLowering::emitAtomicCmpSwap(MachineInstr &MI,
1920 MachineBasicBlock *BB) const {
1921
1922 assert((MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32 ||
1923 MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I64) &&
1924 "Unsupported atomic pseudo for EmitAtomicCmpSwap.");
1925
1926 const unsigned Size = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32 ? 4 : 8;
1927
1928 MachineFunction *MF = BB->getParent();
1929 MachineRegisterInfo &MRI = MF->getRegInfo();
1931 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1932 DebugLoc DL = MI.getDebugLoc();
1933
1934 unsigned AtomicOp = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32
1935 ? Mips::ATOMIC_CMP_SWAP_I32_POSTRA
1936 : Mips::ATOMIC_CMP_SWAP_I64_POSTRA;
1937 Register Dest = MI.getOperand(0).getReg();
1938 Register Ptr = MI.getOperand(1).getReg();
1939 Register OldVal = MI.getOperand(2).getReg();
1940 Register NewVal = MI.getOperand(3).getReg();
1941
1942 Register Scratch = MRI.createVirtualRegister(RC);
1944
1945 // We need to create copies of the various registers and kill them at the
1946 // atomic pseudo. If the copies are not made, when the atomic is expanded
1947 // after fast register allocation, the spills will end up outside of the
1948 // blocks that their values are defined in, causing livein errors.
1949
1950 Register PtrCopy = MRI.createVirtualRegister(MRI.getRegClass(Ptr));
1951 Register OldValCopy = MRI.createVirtualRegister(MRI.getRegClass(OldVal));
1952 Register NewValCopy = MRI.createVirtualRegister(MRI.getRegClass(NewVal));
1953
1954 BuildMI(*BB, II, DL, TII->get(Mips::COPY), PtrCopy).addReg(Ptr);
1955 BuildMI(*BB, II, DL, TII->get(Mips::COPY), OldValCopy).addReg(OldVal);
1956 BuildMI(*BB, II, DL, TII->get(Mips::COPY), NewValCopy).addReg(NewVal);
1957
1958 // The purposes of the flags on the scratch registers is explained in
1959 // emitAtomicBinary. In summary, we need a scratch register which is going to
1960 // be undef, that is unique among registers chosen for the instruction.
1961
1962 BuildMI(*BB, II, DL, TII->get(AtomicOp))
1964 .addReg(PtrCopy, RegState::Kill)
1965 .addReg(OldValCopy, RegState::Kill)
1966 .addReg(NewValCopy, RegState::Kill)
1969
1970 MI.eraseFromParent(); // The instruction is gone now.
1971
1972 return BB;
1973}
1974
1975MachineBasicBlock *MipsTargetLowering::emitAtomicCmpSwapPartword(
1976 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size) const {
1977 assert((Size == 1 || Size == 2) &&
1978 "Unsupported size for EmitAtomicCmpSwapPartial.");
1979
1980 MachineFunction *MF = BB->getParent();
1981 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1982 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1983 const bool ArePtrs64bit = ABI.ArePtrs64bit();
1984 const TargetRegisterClass *RCp =
1985 getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32);
1986 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1987 DebugLoc DL = MI.getDebugLoc();
1988
1989 Register Dest = MI.getOperand(0).getReg();
1990 Register Ptr = MI.getOperand(1).getReg();
1991 Register CmpVal = MI.getOperand(2).getReg();
1992 Register NewVal = MI.getOperand(3).getReg();
1993
1994 Register AlignedAddr = RegInfo.createVirtualRegister(RCp);
1995 Register ShiftAmt = RegInfo.createVirtualRegister(RC);
1996 Register Mask = RegInfo.createVirtualRegister(RC);
1997 Register Mask2 = RegInfo.createVirtualRegister(RC);
1998 Register ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1999 Register ShiftedNewVal = RegInfo.createVirtualRegister(RC);
2000 Register MaskLSB2 = RegInfo.createVirtualRegister(RCp);
2001 Register PtrLSB2 = RegInfo.createVirtualRegister(RC);
2002 Register MaskUpper = RegInfo.createVirtualRegister(RC);
2003 Register MaskedCmpVal = RegInfo.createVirtualRegister(RC);
2004 Register MaskedNewVal = RegInfo.createVirtualRegister(RC);
2005 unsigned AtomicOp = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I8
2006 ? Mips::ATOMIC_CMP_SWAP_I8_POSTRA
2007 : Mips::ATOMIC_CMP_SWAP_I16_POSTRA;
2008
2009 // The scratch registers here with the EarlyClobber | Define | Dead | Implicit
2010 // flags are used to coerce the register allocator and the machine verifier to
2011 // accept the usage of these registers.
2012 // The EarlyClobber flag has the semantic properties that the operand it is
2013 // attached to is clobbered before the rest of the inputs are read. Hence it
2014 // must be unique among the operands to the instruction.
2015 // The Define flag is needed to coerce the machine verifier that an Undef
2016 // value isn't a problem.
2017 // The Dead flag is needed as the value in scratch isn't used by any other
2018 // instruction. Kill isn't used as Dead is more precise.
2019 Register Scratch = RegInfo.createVirtualRegister(RC);
2020 Register Scratch2 = RegInfo.createVirtualRegister(RC);
2021
2022 // insert new blocks after the current block
2023 const BasicBlock *LLVM_BB = BB->getBasicBlock();
2024 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
2026 MF->insert(It, exitMBB);
2027
2028 // Transfer the remainder of BB and its successor edges to exitMBB.
2029 exitMBB->splice(exitMBB->begin(), BB,
2030 std::next(MachineBasicBlock::iterator(MI)), BB->end());
2032
2034
2035 // thisMBB:
2036 // addiu masklsb2,$0,-4 # 0xfffffffc
2037 // and alignedaddr,ptr,masklsb2
2038 // andi ptrlsb2,ptr,3
2039 // xori ptrlsb2,ptrlsb2,3 # Only for BE
2040 // sll shiftamt,ptrlsb2,3
2041 // ori maskupper,$0,255 # 0xff
2042 // sll mask,maskupper,shiftamt
2043 // nor mask2,$0,mask
2044 // andi maskedcmpval,cmpval,255
2045 // sll shiftedcmpval,maskedcmpval,shiftamt
2046 // andi maskednewval,newval,255
2047 // sll shiftednewval,maskednewval,shiftamt
2048 int64_t MaskImm = (Size == 1) ? 255 : 65535;
2049 BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::DADDiu : Mips::ADDiu), MaskLSB2)
2050 .addReg(ABI.GetNullPtr()).addImm(-4);
2051 BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::AND64 : Mips::AND), AlignedAddr)
2052 .addReg(Ptr).addReg(MaskLSB2);
2053 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2)
2054 .addReg(Ptr, {}, ArePtrs64bit ? Mips::sub_32 : 0)
2055 .addImm(3);
2056 if (Subtarget.isLittle()) {
2057 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
2058 } else {
2059 Register Off = RegInfo.createVirtualRegister(RC);
2060 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
2061 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
2062 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
2063 }
2064 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
2065 .addReg(Mips::ZERO).addImm(MaskImm);
2066 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
2067 .addReg(MaskUpper).addReg(ShiftAmt);
2068 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
2069 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
2070 .addReg(CmpVal).addImm(MaskImm);
2071 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
2072 .addReg(MaskedCmpVal).addReg(ShiftAmt);
2073 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
2074 .addReg(NewVal).addImm(MaskImm);
2075 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
2076 .addReg(MaskedNewVal).addReg(ShiftAmt);
2077
2078 // The purposes of the flags on the scratch registers are explained in
2079 // emitAtomicBinary. In summary, we need a scratch register which is going to
2080 // be undef, that is unique among the register chosen for the instruction.
2081
2082 BuildMI(BB, DL, TII->get(AtomicOp))
2084 .addReg(AlignedAddr)
2085 .addReg(Mask)
2086 .addReg(ShiftedCmpVal)
2087 .addReg(Mask2)
2088 .addReg(ShiftedNewVal)
2089 .addReg(ShiftAmt)
2094
2095 MI.eraseFromParent(); // The instruction is gone now.
2096
2097 return exitMBB;
2098}
2099
2100SDValue MipsTargetLowering::lowerREADCYCLECOUNTER(SDValue Op,
2101 SelectionDAG &DAG) const {
2103 SDLoc DL(Op);
2105 unsigned RdhwrOpc, DestReg;
2106 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2107
2108 if (PtrVT == MVT::i64) {
2109 RdhwrOpc = Mips::RDHWR64;
2110 DestReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
2111 SDNode *Rdhwr = DAG.getMachineNode(RdhwrOpc, DL, MVT::i64, MVT::Glue,
2112 DAG.getRegister(Mips::HWR2, MVT::i32),
2113 DAG.getTargetConstant(0, DL, MVT::i32));
2114 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, DestReg,
2115 SDValue(Rdhwr, 0), SDValue(Rdhwr, 1));
2116 SDValue ResNode =
2117 DAG.getCopyFromReg(Chain, DL, DestReg, MVT::i64, Chain.getValue(1));
2118 Results.push_back(ResNode);
2119 Results.push_back(ResNode.getValue(1));
2120 } else {
2121 RdhwrOpc = Mips::RDHWR;
2122 DestReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
2123 SDNode *Rdhwr = DAG.getMachineNode(RdhwrOpc, DL, MVT::i32, MVT::Glue,
2124 DAG.getRegister(Mips::HWR2, MVT::i32),
2125 DAG.getTargetConstant(0, DL, MVT::i32));
2126 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, DestReg,
2127 SDValue(Rdhwr, 0), SDValue(Rdhwr, 1));
2128 SDValue ResNode =
2129 DAG.getCopyFromReg(Chain, DL, DestReg, MVT::i32, Chain.getValue(1));
2130 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResNode,
2131 DAG.getConstant(0, DL, MVT::i32)));
2132 Results.push_back(ResNode.getValue(1));
2133 }
2134
2135 return DAG.getMergeValues(Results, DL);
2136}
2137
2138SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
2139 // The first operand is the chain, the second is the condition, the third is
2140 // the block to branch to if the condition is true.
2141 SDValue Chain = Op.getOperand(0);
2142 SDValue Dest = Op.getOperand(2);
2143 SDLoc DL(Op);
2144
2145 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
2146 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
2147
2148 // Return if flag is not set by a floating point comparison.
2149 if (CondRes.getOpcode() != MipsISD::FPCmp)
2150 return Op;
2151
2152 SDValue CCNode = CondRes.getOperand(2);
2155 SDValue BrCode = DAG.getConstant(Opc, DL, MVT::i32);
2156 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
2157 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
2158 FCC0, Dest, CondRes);
2159}
2160
2161SDValue MipsTargetLowering::
2162lowerSELECT(SDValue Op, SelectionDAG &DAG) const
2163{
2164 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
2165 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
2166
2167 // Return if flag is not set by a floating point comparison.
2168 if (Cond.getOpcode() != MipsISD::FPCmp)
2169 return Op;
2170
2171 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
2172 SDLoc(Op));
2173}
2174
2175SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2176 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
2177 SDValue Cond = createFPCmp(DAG, Op);
2178
2179 assert(Cond.getOpcode() == MipsISD::FPCmp &&
2180 "Floating point operand expected.");
2181
2182 SDLoc DL(Op);
2183 SDValue True = DAG.getConstant(1, DL, MVT::i32);
2184 SDValue False = DAG.getConstant(0, DL, MVT::i32);
2185
2186 return createCMovFP(DAG, Cond, True, False, DL);
2187}
2188
2189SDValue MipsTargetLowering::lowerFSETCC(SDValue Op, SelectionDAG &DAG) const {
2190 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
2191
2192 SDLoc DL(Op);
2193 SDValue Chain = Op.getOperand(0);
2194 SDValue LHS = Op.getOperand(1);
2195 SDValue RHS = Op.getOperand(2);
2196 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get();
2197
2198 SDValue Cond = DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
2199 DAG.getConstant(condCodeToFCC(CC), DL, MVT::i32));
2200 SDValue True = DAG.getConstant(1, DL, MVT::i32);
2201 SDValue False = DAG.getConstant(0, DL, MVT::i32);
2202 SDValue CMovFP = createCMovFP(DAG, Cond, True, False, DL);
2203
2204 return DAG.getMergeValues({CMovFP, Chain}, DL);
2205}
2206
2207SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
2208 SelectionDAG &DAG) const {
2209 EVT Ty = Op.getValueType();
2210 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
2211 const GlobalValue *GV = N->getGlobal();
2212
2213 if (GV->hasDLLImportStorageClass()) {
2214 assert(Subtarget.isTargetWindows() &&
2215 "Windows is the only supported COFF target");
2216 return getDllimportVariable(
2217 N, SDLoc(N), Ty, DAG, DAG.getEntryNode(),
2219 }
2220
2221 if (!isPositionIndependent()) {
2222 const MipsTargetObjectFile *TLOF =
2223 static_cast<const MipsTargetObjectFile *>(
2225 const GlobalObject *GO = GV->getAliaseeObject();
2226 if (Subtarget.useSmallSection() && GO && TLOF->IsGlobalInSmallSection(GO))
2227 // %gp_rel relocation
2228 return getAddrGPRel(N, SDLoc(N), Ty, DAG, ABI.IsN64());
2229
2230 // %hi/%lo relocation
2231 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2232 // %highest/%higher/%hi/%lo relocation
2233 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2234 }
2235
2236 // Every other architecture would use shouldAssumeDSOLocal in here, but
2237 // mips is special.
2238 // * In PIC code mips requires got loads even for local statics!
2239 // * To save on got entries, for local statics the got entry contains the
2240 // page and an additional add instruction takes care of the low bits.
2241 // * It is legal to access a hidden symbol with a non hidden undefined,
2242 // so one cannot guarantee that all access to a hidden symbol will know
2243 // it is hidden.
2244 // * Mips linkers don't support creating a page and a full got entry for
2245 // the same symbol.
2246 // * Given all that, we have to use a full got entry for hidden symbols :-(
2247 if (GV->hasLocalLinkage())
2248 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2249
2250 if (Subtarget.useXGOT())
2251 return getAddrGlobalLargeGOT(
2252 N, SDLoc(N), Ty, DAG, MipsII::MO_GOT_HI16, MipsII::MO_GOT_LO16,
2253 DAG.getEntryNode(),
2255
2256 return getAddrGlobal(
2257 N, SDLoc(N), Ty, DAG,
2258 (ABI.IsN32() || ABI.IsN64()) ? MipsII::MO_GOT_DISP : MipsII::MO_GOT,
2260}
2261
2262SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
2263 SelectionDAG &DAG) const {
2264 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
2265 EVT Ty = Op.getValueType();
2266
2267 if (!isPositionIndependent())
2268 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2269 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2270
2271 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2272}
2273
2274SDValue MipsTargetLowering::
2275lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
2276{
2277 // If the relocation model is PIC, use the General Dynamic TLS Model or
2278 // Local Dynamic TLS model, otherwise use the Initial Exec or
2279 // Local Exec TLS Model.
2280
2281 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2282 if (DAG.getTarget().useEmulatedTLS())
2283 return LowerToTLSEmulatedModel(GA, DAG);
2284
2285 SDLoc DL(GA);
2286 const GlobalValue *GV = GA->getGlobal();
2287 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2288
2290
2291 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
2292 // General Dynamic and Local Dynamic TLS Model.
2293 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
2294 : MipsII::MO_TLSGD;
2295
2296 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
2297 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
2298 getGlobalReg(DAG, PtrVT), TGA);
2299 unsigned PtrSize = PtrVT.getSizeInBits();
2300 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
2301
2302 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
2303
2305 Args.emplace_back(Argument, PtrTy);
2306
2307 TargetLowering::CallLoweringInfo CLI(DAG);
2308 CLI.setDebugLoc(DL)
2309 .setChain(DAG.getEntryNode())
2310 .setLibCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args));
2311 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2312
2313 SDValue Ret = CallResult.first;
2314
2315 if (model != TLSModel::LocalDynamic)
2316 return Ret;
2317
2318 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2320 SDValue Hi = DAG.getNode(MipsISD::TlsHi, DL, PtrVT, TGAHi);
2321 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2323 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
2324 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
2325 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
2326 }
2327
2328 SDValue Offset;
2329 if (model == TLSModel::InitialExec) {
2330 // Initial Exec TLS Model
2331 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2333 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
2334 TGA);
2335 Offset =
2336 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), TGA, MachinePointerInfo());
2337 } else {
2338 // Local Exec TLS Model
2339 assert(model == TLSModel::LocalExec);
2340 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2342 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2344 SDValue Hi = DAG.getNode(MipsISD::TlsHi, DL, PtrVT, TGAHi);
2345 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
2346 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2347 }
2348
2349 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
2350 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
2351}
2352
2353SDValue MipsTargetLowering::
2354lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
2355{
2356 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
2357 EVT Ty = Op.getValueType();
2358
2359 if (!isPositionIndependent())
2360 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2361 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2362
2363 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2364}
2365
2366SDValue MipsTargetLowering::
2367lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
2368{
2369 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
2370 EVT Ty = Op.getValueType();
2371
2372 if (!isPositionIndependent()) {
2373 const MipsTargetObjectFile *TLOF =
2374 static_cast<const MipsTargetObjectFile *>(
2376
2377 if (TLOF->IsConstantInSmallSection(DAG.getDataLayout(), N->getConstVal(),
2379 // %gp_rel relocation
2380 return getAddrGPRel(N, SDLoc(N), Ty, DAG, ABI.IsN64());
2381
2382 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2383 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2384 }
2385
2386 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2387}
2388
2389SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2391 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2392
2393 SDLoc DL(Op);
2394 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2396
2397 // vastart just stores the address of the VarArgsFrameIndex slot into the
2398 // memory location argument.
2399 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2400 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
2401 MachinePointerInfo(SV));
2402}
2403
2404SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2405 SDNode *Node = Op.getNode();
2406 EVT VT = Node->getValueType(0);
2407 SDValue Chain = Node->getOperand(0);
2408 SDValue VAListPtr = Node->getOperand(1);
2409 const Align Align =
2410 llvm::MaybeAlign(Node->getConstantOperandVal(3)).valueOrOne();
2411 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2412 SDLoc DL(Node);
2413 unsigned ArgSlotSizeInBytes = (ABI.IsN32() || ABI.IsN64()) ? 8 : 4;
2414
2415 SDValue VAListLoad = DAG.getLoad(getPointerTy(DAG.getDataLayout()), DL, Chain,
2416 VAListPtr, MachinePointerInfo(SV));
2417 SDValue VAList = VAListLoad;
2418
2419 // Re-align the pointer if necessary.
2420 // It should only ever be necessary for 64-bit types on O32 since the minimum
2421 // argument alignment is the same as the maximum type alignment for N32/N64.
2422 //
2423 // FIXME: We currently align too often. The code generator doesn't notice
2424 // when the pointer is still aligned from the last va_arg (or pair of
2425 // va_args for the i64 on O32 case).
2426 if (Align > getMinStackArgumentAlignment()) {
2427 VAList = DAG.getNode(
2428 ISD::ADD, DL, VAList.getValueType(), VAList,
2429 DAG.getConstant(Align.value() - 1, DL, VAList.getValueType()));
2430
2431 VAList = DAG.getNode(ISD::AND, DL, VAList.getValueType(), VAList,
2432 DAG.getSignedConstant(-(int64_t)Align.value(), DL,
2433 VAList.getValueType()));
2434 }
2435
2436 // Increment the pointer, VAList, to the next vaarg.
2437 auto &TD = DAG.getDataLayout();
2438 unsigned ArgSizeInBytes =
2440 SDValue Tmp3 =
2441 DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
2442 DAG.getConstant(alignTo(ArgSizeInBytes, ArgSlotSizeInBytes),
2443 DL, VAList.getValueType()));
2444 // Store the incremented VAList to the legalized pointer
2445 Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
2446 MachinePointerInfo(SV));
2447
2448 // In big-endian mode we must adjust the pointer when the load size is smaller
2449 // than the argument slot size. We must also reduce the known alignment to
2450 // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
2451 // the correct half of the slot, and reduce the alignment from 8 (slot
2452 // alignment) down to 4 (type alignment).
2453 if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
2454 unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
2455 VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
2456 DAG.getIntPtrConstant(Adjustment, DL));
2457 }
2458 // Load the actual argument out of the pointer VAList
2459 return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo());
2460}
2461
2463 bool HasExtractInsert) {
2464 EVT TyX = Op.getOperand(0).getValueType();
2465 EVT TyY = Op.getOperand(1).getValueType();
2466 SDLoc DL(Op);
2467 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
2468 SDValue Const31 = DAG.getConstant(31, DL, MVT::i32);
2469 SDValue Res;
2470
2471 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2472 // to i32.
2473 SDValue X = (TyX == MVT::f32) ?
2474 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2475 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2476 Const1);
2477 SDValue Y = (TyY == MVT::f32) ?
2478 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
2479 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
2480 Const1);
2481
2482 if (HasExtractInsert) {
2483 // ext E, Y, 31, 1 ; extract bit31 of Y
2484 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
2485 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
2486 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
2487 } else {
2488 // sll SllX, X, 1
2489 // srl SrlX, SllX, 1
2490 // srl SrlY, Y, 31
2491 // sll SllY, SrlX, 31
2492 // or Or, SrlX, SllY
2493 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2494 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2495 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
2496 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
2497 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
2498 }
2499
2500 if (TyX == MVT::f32)
2501 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
2502
2503 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2504 Op.getOperand(0),
2505 DAG.getConstant(0, DL, MVT::i32));
2506 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2507}
2508
2510 bool HasExtractInsert) {
2511 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
2512 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
2513 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
2514 SDLoc DL(Op);
2515 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
2516
2517 // Bitcast to integer nodes.
2518 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
2519 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
2520
2521 if (HasExtractInsert) {
2522 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
2523 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
2524 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
2525 DAG.getConstant(WidthY - 1, DL, MVT::i32), Const1);
2526
2527 if (WidthX > WidthY)
2528 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
2529 else if (WidthY > WidthX)
2530 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
2531
2532 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
2533 DAG.getConstant(WidthX - 1, DL, MVT::i32), Const1,
2534 X);
2535 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
2536 }
2537
2538 // (d)sll SllX, X, 1
2539 // (d)srl SrlX, SllX, 1
2540 // (d)srl SrlY, Y, width(Y)-1
2541 // (d)sll SllY, SrlX, width(Y)-1
2542 // or Or, SrlX, SllY
2543 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
2544 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
2545 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
2546 DAG.getConstant(WidthY - 1, DL, MVT::i32));
2547
2548 if (WidthX > WidthY)
2549 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
2550 else if (WidthY > WidthX)
2551 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
2552
2553 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
2554 DAG.getConstant(WidthX - 1, DL, MVT::i32));
2555 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
2556 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2557}
2558
2559SDValue
2560MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2561 if (Subtarget.isGP64bit())
2562 return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
2563
2564 return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
2565}
2566
2567SDValue MipsTargetLowering::lowerFABS32(SDValue Op, SelectionDAG &DAG,
2568 bool HasExtractInsert) const {
2569 SDLoc DL(Op);
2570 SDValue Res, Const1 = DAG.getConstant(1, DL, MVT::i32);
2571
2572 if (Op->getFlags().hasNoNaNs() || Subtarget.inAbs2008Mode())
2573 return DAG.getNode(MipsISD::FAbs, DL, Op.getValueType(), Op.getOperand(0));
2574
2575 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2576 // to i32.
2577 SDValue X = (Op.getValueType() == MVT::f32)
2578 ? DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0))
2579 : DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2580 Op.getOperand(0), Const1);
2581
2582 // Clear MSB.
2583 if (HasExtractInsert)
2584 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
2585 DAG.getRegister(Mips::ZERO, MVT::i32),
2586 DAG.getConstant(31, DL, MVT::i32), Const1, X);
2587 else {
2588 // TODO: Provide DAG patterns which transform (and x, cst)
2589 // back to a (shl (srl x (clz cst)) (clz cst)) sequence.
2590 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2591 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2592 }
2593
2594 if (Op.getValueType() == MVT::f32)
2595 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
2596
2597 // FIXME: For mips32r2, the sequence of (BuildPairF64 (ins (ExtractElementF64
2598 // Op 1), $zero, 31 1) (ExtractElementF64 Op 0)) and the Op has one use, we
2599 // should be able to drop the usage of mfc1/mtc1 and rewrite the register in
2600 // place.
2601 SDValue LowX =
2602 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2603 DAG.getConstant(0, DL, MVT::i32));
2604 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2605}
2606
2607SDValue MipsTargetLowering::lowerFABS64(SDValue Op, SelectionDAG &DAG,
2608 bool HasExtractInsert) const {
2609 SDLoc DL(Op);
2610 SDValue Res, Const1 = DAG.getConstant(1, DL, MVT::i32);
2611
2612 if (Op->getFlags().hasNoNaNs() || Subtarget.inAbs2008Mode())
2613 return DAG.getNode(MipsISD::FAbs, DL, Op.getValueType(), Op.getOperand(0));
2614
2615 // Bitcast to integer node.
2616 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
2617
2618 // Clear MSB.
2619 if (HasExtractInsert)
2620 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
2621 DAG.getRegister(Mips::ZERO_64, MVT::i64),
2622 DAG.getConstant(63, DL, MVT::i32), Const1, X);
2623 else {
2624 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
2625 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
2626 }
2627
2628 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
2629}
2630
2631SDValue MipsTargetLowering::lowerFABS(SDValue Op, SelectionDAG &DAG) const {
2632 if ((ABI.IsN32() || ABI.IsN64()) && (Op.getValueType() == MVT::f64))
2633 return lowerFABS64(Op, DAG, Subtarget.hasExtractInsert());
2634
2635 return lowerFABS32(Op, DAG, Subtarget.hasExtractInsert());
2636}
2637
2638SDValue MipsTargetLowering::lowerFCANONICALIZE(SDValue Op,
2639 SelectionDAG &DAG) const {
2640 SDLoc DL(Op);
2641 EVT VT = Op.getValueType();
2642 SDValue Operand = Op.getOperand(0);
2643 SDNodeFlags Flags = Op->getFlags();
2644
2645 if (Flags.hasNoNaNs() || DAG.isKnownNeverNaN(Operand))
2646 return Operand;
2647
2648 SDValue Quiet = DAG.getNode(ISD::FADD, DL, VT, Operand, Operand);
2649 return DAG.getSelectCC(DL, Operand, Operand, Quiet, Operand, ISD::SETUO);
2650}
2651
2652SDValue MipsTargetLowering::
2653lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2654 // check the depth
2655 if (Op.getConstantOperandVal(0) != 0) {
2656 DAG.getContext()->emitError(
2657 "return address can be determined only for current frame");
2658 return SDValue();
2659 }
2660
2661 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2662 MFI.setFrameAddressIsTaken(true);
2663 EVT VT = Op.getValueType();
2664 SDLoc DL(Op);
2665 SDValue FrameAddr = DAG.getCopyFromReg(
2666 DAG.getEntryNode(), DL, ABI.IsN64() ? Mips::FP_64 : Mips::FP, VT);
2667 return FrameAddr;
2668}
2669
2670SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
2671 SelectionDAG &DAG) const {
2672 // check the depth
2673 if (Op.getConstantOperandVal(0) != 0) {
2674 DAG.getContext()->emitError(
2675 "return address can be determined only for current frame");
2676 return SDValue();
2677 }
2678
2680 MachineFrameInfo &MFI = MF.getFrameInfo();
2681 MVT VT = Op.getSimpleValueType();
2682 unsigned RA = ABI.IsN64() ? Mips::RA_64 : Mips::RA;
2683 MFI.setReturnAddressIsTaken(true);
2684
2685 // Return RA, which contains the return address. Mark it an implicit live-in.
2687 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
2688}
2689
2690// An EH_RETURN is the result of lowering llvm.eh.return which in turn is
2691// generated from __builtin_eh_return (offset, handler)
2692// The effect of this is to adjust the stack pointer by "offset"
2693// and then branch to "handler".
2694SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
2695 const {
2697 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2698
2699 MipsFI->setCallsEhReturn();
2700 SDValue Chain = Op.getOperand(0);
2701 SDValue Offset = Op.getOperand(1);
2702 SDValue Handler = Op.getOperand(2);
2703 SDLoc DL(Op);
2704 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2705
2706 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
2707 // EH_RETURN nodes, so that instructions are emitted back-to-back.
2708 unsigned OffsetReg = ABI.getReturnRegPtr(1);
2709 unsigned AddrReg = ABI.getReturnRegPtr(0);
2710 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
2711 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
2712 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
2713 DAG.getRegister(OffsetReg, Ty),
2714 DAG.getRegister(AddrReg, getPointerTy(MF.getDataLayout())),
2715 Chain.getValue(1));
2716}
2717
2718SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
2719 SelectionDAG &DAG) const {
2720 // FIXME: Need pseudo-fence for 'singlethread' fences
2721 // FIXME: Set SType for weaker fences where supported/appropriate.
2722 unsigned SType = 0;
2723 SDLoc DL(Op);
2724 SyncScope::ID FenceSSID =
2725 static_cast<SyncScope::ID>(Op.getConstantOperandVal(2));
2726
2727 if (Subtarget.hasMips2() && FenceSSID == SyncScope::System)
2728 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
2729 DAG.getTargetConstant(SType, DL, MVT::i32));
2730
2731 // singlethread fences only synchronize with signal handlers on the same
2732 // thread and thus only need to preserve instruction order, not actually
2733 // enforce memory ordering.
2734 if ((Subtarget.hasMips1() && !Subtarget.hasMips2()) ||
2735 FenceSSID == SyncScope::SingleThread) {
2736 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
2737 return DAG.getNode(ISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
2738 }
2739
2740 return Op;
2741}
2742
2743SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
2744 SelectionDAG &DAG) const {
2745 SDLoc DL(Op);
2746 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2747
2748 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2749 SDValue Shamt = Op.getOperand(2);
2750 // if shamt < (VT.bits):
2751 // lo = (shl lo, shamt)
2752 // hi = (or (shl hi, shamt) (srl (srl lo, 1), (xor shamt, (VT.bits-1))))
2753 // else:
2754 // lo = 0
2755 // hi = (shl lo, shamt[4:0])
2756 SDValue Not =
2757 DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2758 DAG.getConstant(VT.getSizeInBits() - 1, DL, MVT::i32));
2759 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
2760 DAG.getConstant(1, DL, VT));
2761 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, Not);
2762 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
2763 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2764 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
2765 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2766 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2767 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2768 DAG.getConstant(0, DL, VT), ShiftLeftLo);
2769 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftLeftLo, Or);
2770
2771 SDValue Ops[2] = {Lo, Hi};
2772 return DAG.getMergeValues(Ops, DL);
2773}
2774
2775SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2776 bool IsSRA) const {
2777 SDLoc DL(Op);
2778 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2779 SDValue Shamt = Op.getOperand(2);
2780 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2781
2782 // if shamt < (VT.bits):
2783 // lo = (or (shl (shl hi, 1), (xor shamt, (VT.bits-1))) (srl lo, shamt))
2784 // if isSRA:
2785 // hi = (sra hi, shamt)
2786 // else:
2787 // hi = (srl hi, shamt)
2788 // else:
2789 // if isSRA:
2790 // lo = (sra hi, shamt[4:0])
2791 // hi = (sra hi, 31)
2792 // else:
2793 // lo = (srl hi, shamt[4:0])
2794 // hi = 0
2795 SDValue Not =
2796 DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2797 DAG.getConstant(VT.getSizeInBits() - 1, DL, MVT::i32));
2798 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
2799 DAG.getConstant(1, DL, VT));
2800 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, ShiftLeft1Hi, Not);
2801 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
2802 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2803 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL,
2804 DL, VT, Hi, Shamt);
2805 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2806 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2807 SDValue Ext = DAG.getNode(ISD::SRA, DL, VT, Hi,
2808 DAG.getConstant(VT.getSizeInBits() - 1, DL, VT));
2809
2810 if (!(Subtarget.hasMips4() || Subtarget.hasMips32())) {
2811 SDVTList VTList = DAG.getVTList(VT, VT);
2812 return DAG.getNode(Subtarget.isGP64bit() ? MipsISD::DOUBLE_SELECT_I64
2814 DL, VTList, Cond, ShiftRightHi,
2815 IsSRA ? Ext : DAG.getConstant(0, DL, VT), Or,
2816 ShiftRightHi);
2817 }
2818
2819 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftRightHi, Or);
2820 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2821 IsSRA ? Ext : DAG.getConstant(0, DL, VT), ShiftRightHi);
2822
2823 SDValue Ops[2] = {Lo, Hi};
2824 return DAG.getMergeValues(Ops, DL);
2825}
2826
2828 SDValue Chain, SDValue Src, unsigned Offset) {
2829 SDValue Ptr = LD->getBasePtr();
2830 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2831 EVT BasePtrVT = Ptr.getValueType();
2832 SDLoc DL(LD);
2833 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2834
2835 if (Offset)
2836 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2837 DAG.getConstant(Offset, DL, BasePtrVT));
2838
2839 SDValue Ops[] = { Chain, Ptr, Src };
2840 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2841 LD->getMemOperand());
2842}
2843
2844// Expand an unaligned 32 or 64-bit integer load node.
2847 EVT MemVT = LD->getMemoryVT();
2848
2849 if (Subtarget.systemSupportsUnalignedAccess())
2850 return Op;
2851
2852 // Return if load is aligned or if MemVT is neither i32 nor i64.
2853 if ((LD->getAlign().value() >= (MemVT.getSizeInBits() / 8)) ||
2854 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2855 return SDValue();
2856
2857 bool IsLittle = Subtarget.isLittle();
2858 EVT VT = Op.getValueType();
2859 ISD::LoadExtType ExtType = LD->getExtensionType();
2860 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2861
2862 assert((VT == MVT::i32) || (VT == MVT::i64));
2863
2864 // Expand
2865 // (set dst, (i64 (load baseptr)))
2866 // to
2867 // (set tmp, (ldl (add baseptr, 7), undef))
2868 // (set dst, (ldr baseptr, tmp))
2869 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2870 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2871 IsLittle ? 7 : 0);
2872 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2873 IsLittle ? 0 : 7);
2874 }
2875
2876 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2877 IsLittle ? 3 : 0);
2878 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2879 IsLittle ? 0 : 3);
2880
2881 // Expand
2882 // (set dst, (i32 (load baseptr))) or
2883 // (set dst, (i64 (sextload baseptr))) or
2884 // (set dst, (i64 (extload baseptr)))
2885 // to
2886 // (set tmp, (lwl (add baseptr, 3), undef))
2887 // (set dst, (lwr baseptr, tmp))
2888 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2889 (ExtType == ISD::EXTLOAD))
2890 return LWR;
2891
2892 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2893
2894 // Expand
2895 // (set dst, (i64 (zextload baseptr)))
2896 // to
2897 // (set tmp0, (lwl (add baseptr, 3), undef))
2898 // (set tmp1, (lwr baseptr, tmp0))
2899 // (set tmp2, (shl tmp1, 32))
2900 // (set dst, (srl tmp2, 32))
2901 SDLoc DL(LD);
2902 SDValue Const32 = DAG.getConstant(32, DL, MVT::i32);
2903 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2904 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2905 SDValue Ops[] = { SRL, LWR.getValue(1) };
2906 return DAG.getMergeValues(Ops, DL);
2907}
2908
2910 SDValue Chain, unsigned Offset) {
2911 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2912 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2913 SDLoc DL(SD);
2914 SDVTList VTList = DAG.getVTList(MVT::Other);
2915
2916 if (Offset)
2917 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2918 DAG.getConstant(Offset, DL, BasePtrVT));
2919
2920 SDValue Ops[] = { Chain, Value, Ptr };
2921 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2922 SD->getMemOperand());
2923}
2924
2925// Expand an unaligned 32 or 64-bit integer store node.
2927 bool IsLittle) {
2928 SDValue Value = SD->getValue(), Chain = SD->getChain();
2929 EVT VT = Value.getValueType();
2930
2931 // Expand
2932 // (store val, baseptr) or
2933 // (truncstore val, baseptr)
2934 // to
2935 // (swl val, (add baseptr, 3))
2936 // (swr val, baseptr)
2937 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2938 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2939 IsLittle ? 3 : 0);
2940 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2941 }
2942
2943 assert(VT == MVT::i64);
2944
2945 // Expand
2946 // (store val, baseptr)
2947 // to
2948 // (sdl val, (add baseptr, 7))
2949 // (sdr val, baseptr)
2950 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2951 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2952}
2953
2954// Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2956 bool SingleFloat) {
2957 SDValue Val = SD->getValue();
2958
2959 if (Val.getOpcode() != ISD::FP_TO_SINT ||
2960 (Val.getValueSizeInBits() > 32 && SingleFloat))
2961 return SDValue();
2962
2964 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2965 Val.getOperand(0));
2966 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2967 SD->getPointerInfo(), SD->getAlign(),
2968 SD->getMemOperand()->getFlags());
2969}
2970
2973 EVT MemVT = SD->getMemoryVT();
2974
2975 // Lower unaligned integer stores.
2976 if (!Subtarget.systemSupportsUnalignedAccess() &&
2977 (SD->getAlign().value() < (MemVT.getSizeInBits() / 8)) &&
2978 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2979 return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
2980
2981 return lowerFP_TO_SINT_STORE(SD, DAG, Subtarget.isSingleFloat());
2982}
2983
2984SDValue MipsTargetLowering::lowerEH_DWARF_CFA(SDValue Op,
2985 SelectionDAG &DAG) const {
2986
2987 // Return a fixed StackObject with offset 0 which points to the old stack
2988 // pointer.
2990 EVT ValTy = Op->getValueType(0);
2991 int FI = MFI.CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2992 return DAG.getFrameIndex(FI, ValTy);
2993}
2994
2995SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2996 SelectionDAG &DAG) const {
2997 if (Op.getValueSizeInBits() > 32 && Subtarget.isSingleFloat())
2998 return SDValue();
2999
3000 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
3001 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
3002 Op.getOperand(0));
3003 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
3004}
3005
3006SDValue MipsTargetLowering::lowerSTRICT_FP_TO_INT(SDValue Op,
3007 SelectionDAG &DAG) const {
3008 assert(Op->isStrictFPOpcode());
3009 SDValue SrcVal = Op.getOperand(1);
3010 SDLoc Loc(Op);
3011
3012 SDValue Result =
3015 Loc, Op.getValueType(), SrcVal);
3016
3017 return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc);
3018}
3019
3021 static const MCPhysReg RCRegs[] = {Mips::FCR31};
3022 return RCRegs;
3023}
3024
3025//===----------------------------------------------------------------------===//
3026// Calling Convention Implementation
3027//===----------------------------------------------------------------------===//
3028
3029//===----------------------------------------------------------------------===//
3030// TODO: Implement a generic logic using tblgen that can support this.
3031// Mips O32 ABI rules:
3032// ---
3033// i32 - Passed in A0, A1, A2, A3 and stack
3034// f32 - Only passed in f32 registers if no int reg has been used yet to hold
3035// an argument. Otherwise, passed in A1, A2, A3 and stack.
3036// f64 - Only passed in two aliased f32 registers if no int reg has been used
3037// yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
3038// not used, it must be shadowed. If only A3 is available, shadow it and
3039// go to stack.
3040// vXiX - Received as scalarized i32s, passed in A0 - A3 and the stack.
3041// vXf32 - Passed in either a pair of registers {A0, A1}, {A2, A3} or {A0 - A3}
3042// with the remainder spilled to the stack.
3043// vXf64 - Passed in either {A0, A1, A2, A3} or {A2, A3} and in both cases
3044// spilling the remainder to the stack.
3045//
3046// For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
3047//===----------------------------------------------------------------------===//
3048
3049static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
3050 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
3051 Type *OrigTy, CCState &State,
3052 ArrayRef<MCPhysReg> F64Regs) {
3053 const MipsSubtarget &Subtarget = static_cast<const MipsSubtarget &>(
3054 State.getMachineFunction().getSubtarget());
3055
3056 const MipsABIInfo &ABI = Subtarget.getABI();
3057 ArrayRef<MCPhysReg> IntRegs = ABI.getArgRegs(false);
3058
3059 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
3060
3061 const MCPhysReg FloatVectorIntRegs[] = {IntRegs[0], IntRegs[2]};
3062
3063 // Do not process byval args here.
3064 if (ArgFlags.isByVal())
3065 return true;
3066
3067 // Promote i8 and i16
3068 if (ArgFlags.isInReg() && !Subtarget.isLittle()) {
3069 if (LocVT == MVT::i8 || LocVT == MVT::i16 || LocVT == MVT::i32) {
3070 LocVT = MVT::i32;
3071 if (ArgFlags.isSExt())
3072 LocInfo = CCValAssign::SExtUpper;
3073 else if (ArgFlags.isZExt())
3074 LocInfo = CCValAssign::ZExtUpper;
3075 else
3076 LocInfo = CCValAssign::AExtUpper;
3077 }
3078 }
3079
3080 // Promote i8 and i16
3081 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
3082 LocVT = MVT::i32;
3083 if (ArgFlags.isSExt())
3084 LocInfo = CCValAssign::SExt;
3085 else if (ArgFlags.isZExt())
3086 LocInfo = CCValAssign::ZExt;
3087 else
3088 LocInfo = CCValAssign::AExt;
3089 }
3090
3091 unsigned Reg;
3092
3093 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
3094 // is true: function is vararg, argument is 3rd or higher, there is previous
3095 // argument which is not f32 or f64.
3096 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1 ||
3097 State.getFirstUnallocated(F32Regs) != ValNo;
3098 Align OrigAlign = ArgFlags.getNonZeroOrigAlign();
3099 bool isI64 = (ValVT == MVT::i32 && OrigAlign == Align(8));
3100 bool isVectorFloat = OrigTy->isVectorTy() && OrigTy->isFPOrFPVectorTy();
3101
3102 // The MIPS vector ABI for floats passes them in a pair of registers
3103 if (ValVT == MVT::i32 && isVectorFloat) {
3104 // This is the start of an vector that was scalarized into an unknown number
3105 // of components. It doesn't matter how many there are. Allocate one of the
3106 // notional 8 byte aligned registers which map onto the argument stack, and
3107 // shadow the register lost to alignment requirements.
3108 if (ArgFlags.isSplit()) {
3109 Reg = State.AllocateReg(FloatVectorIntRegs);
3110 if (Reg == Mips::A2)
3111 State.AllocateReg(Mips::A1);
3112 else if (Reg == 0)
3113 State.AllocateReg(Mips::A3);
3114 } else {
3115 // If we're an intermediate component of the split, we can just attempt to
3116 // allocate a register directly.
3117 Reg = State.AllocateReg(IntRegs);
3118 }
3119 } else if (ValVT == MVT::i32 ||
3120 (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
3121 Reg = State.AllocateReg(IntRegs);
3122 // If this is the first part of an i64 arg,
3123 // the allocated register must be either A0 or A2.
3124 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
3125 Reg = State.AllocateReg(IntRegs);
3126 LocVT = MVT::i32;
3127 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
3128 // Allocate int register and shadow next int register. If first
3129 // available register is Mips::A1 or Mips::A3, shadow it too.
3130 Reg = State.AllocateReg(IntRegs);
3131 if (Reg == Mips::A1 || Reg == Mips::A3)
3132 Reg = State.AllocateReg(IntRegs);
3133
3134 if (Reg) {
3135 LocVT = MVT::i32;
3136
3137 State.addLoc(
3138 CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
3139 MCRegister HiReg = State.AllocateReg(IntRegs);
3140 assert(HiReg);
3141 State.addLoc(
3142 CCValAssign::getCustomReg(ValNo, ValVT, HiReg, LocVT, LocInfo));
3143 return false;
3144 }
3145 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
3146 // we are guaranteed to find an available float register
3147 if (ValVT == MVT::f32) {
3148 Reg = State.AllocateReg(F32Regs);
3149 // Shadow int register
3150 State.AllocateReg(IntRegs);
3151 } else {
3152 Reg = State.AllocateReg(F64Regs);
3153 // Shadow int registers
3154 MCRegister Reg2 = State.AllocateReg(IntRegs);
3155 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
3156 State.AllocateReg(IntRegs);
3157 State.AllocateReg(IntRegs);
3158 }
3159 } else
3160 llvm_unreachable("Cannot handle this ValVT.");
3161
3162 if (!Reg) {
3163 unsigned Offset = State.AllocateStack(ValVT.getStoreSize(), OrigAlign);
3164 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
3165 } else
3166 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
3167
3168 return false;
3169}
3170
3171static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT, MVT LocVT,
3172 CCValAssign::LocInfo LocInfo,
3173 ISD::ArgFlagsTy ArgFlags, Type *OrigTy,
3174 CCState &State) {
3175 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
3176
3177 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, OrigTy, State,
3178 F64Regs);
3179}
3180
3181static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT, MVT LocVT,
3182 CCValAssign::LocInfo LocInfo,
3183 ISD::ArgFlagsTy ArgFlags, Type *OrigTy,
3184 CCState &State) {
3185 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
3186
3187 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, OrigTy, State,
3188 F64Regs);
3189}
3190
3191[[maybe_unused]] static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
3192 CCValAssign::LocInfo LocInfo,
3193 ISD::ArgFlagsTy ArgFlags, Type *OrigTy,
3194 CCState &State);
3195
3196#define GET_CALLING_CONV_IMPL
3197#include "MipsGenCallingConv.inc"
3198
3200 return CC_Mips_FixedArg;
3201 }
3202
3204 return RetCC_Mips;
3205 }
3206//===----------------------------------------------------------------------===//
3207// Call Calling Convention Implementation
3208//===----------------------------------------------------------------------===//
3209
3210SDValue MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
3211 SDValue Chain, SDValue Arg,
3212 const SDLoc &DL, bool IsTailCall,
3213 SelectionDAG &DAG) const {
3214 if (!IsTailCall) {
3215 SDValue PtrOff =
3216 DAG.getNode(ISD::ADD, DL, getPointerTy(DAG.getDataLayout()), StackPtr,
3218 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo());
3219 }
3220
3222 int FI = MFI.CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
3223 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3224 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(), MaybeAlign(),
3226}
3227
3230 std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
3231 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
3232 bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
3233 SDValue Chain) const {
3234 // Insert node "GP copy globalreg" before call to function.
3235 //
3236 // R_MIPS_CALL* operators (emitted when non-internal functions are called
3237 // in PIC mode) allow symbols to be resolved via lazy binding.
3238 // The lazy binding stub requires GP to point to the GOT.
3239 // Note that we don't need GP to point to the GOT for indirect calls
3240 // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
3241 // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
3242 // used for the function (that is, Mips linker doesn't generate lazy binding
3243 // stub for a function whose address is taken in the program).
3244 if (IsPICCall && !InternalLinkage && IsCallReloc) {
3245 unsigned GPReg = ABI.IsN64() ? Mips::GP_64 : Mips::GP;
3246 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
3247 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
3248 }
3249
3250 // Build a sequence of copy-to-reg nodes chained together with token
3251 // chain and flag operands which copy the outgoing args into registers.
3252 // The InGlue in necessary since all emitted instructions must be
3253 // stuck together.
3254 SDValue InGlue;
3255
3256 for (auto &R : RegsToPass) {
3257 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, R.first, R.second, InGlue);
3258 InGlue = Chain.getValue(1);
3259 }
3260
3261 // Add argument registers to the end of the list so that they are
3262 // known live into the call.
3263 for (auto &R : RegsToPass)
3264 Ops.push_back(CLI.DAG.getRegister(R.first, R.second.getValueType()));
3265
3266 // Add a register mask operand representing the call-preserved registers.
3267 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
3268 const uint32_t *Mask =
3269 TRI->getCallPreservedMask(CLI.DAG.getMachineFunction(), CLI.CallConv);
3270 assert(Mask && "Missing call preserved mask for calling convention");
3271 if (Subtarget.inMips16HardFloat()) {
3273 StringRef Sym = G->getGlobal()->getName();
3274 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3275 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
3277 }
3278 }
3279 }
3280 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
3281
3282 if (InGlue.getNode())
3283 Ops.push_back(InGlue);
3284}
3285
3287 SDNode *Node) const {
3288 switch (MI.getOpcode()) {
3289 default:
3290 return;
3291 case Mips::JALR:
3292 case Mips::JALRPseudo:
3293 case Mips::JALR64:
3294 case Mips::JALR64Pseudo:
3295 case Mips::JALR16_MM:
3296 case Mips::JALRC16_MMR6:
3297 case Mips::TAILCALLREG:
3298 case Mips::TAILCALLREG64:
3299 case Mips::TAILCALLR6REG:
3300 case Mips::TAILCALL64R6REG:
3301 case Mips::TAILCALLREG_MM:
3302 case Mips::TAILCALLREG_MMR6: {
3303 if (!EmitJalrReloc ||
3304 Subtarget.inMips16Mode() ||
3306 Node->getNumOperands() < 1 ||
3307 Node->getOperand(0).getNumOperands() < 2) {
3308 return;
3309 }
3310 // We are after the callee address, set by LowerCall().
3311 // If added to MI, asm printer will emit .reloc R_MIPS_JALR for the
3312 // symbol.
3313 const SDValue TargetAddr = Node->getOperand(0).getOperand(1);
3314 StringRef Sym;
3315 if (const GlobalAddressSDNode *G =
3317 // We must not emit the R_MIPS_JALR relocation against data symbols
3318 // since this will cause run-time crashes if the linker replaces the
3319 // call instruction with a relative branch to the data symbol.
3320 if (!isa<Function>(G->getGlobal())) {
3321 LLVM_DEBUG(dbgs() << "Not adding R_MIPS_JALR against data symbol "
3322 << G->getGlobal()->getName() << "\n");
3323 return;
3324 }
3325 Sym = G->getGlobal()->getName();
3326 }
3327 else if (const ExternalSymbolSDNode *ES =
3329 Sym = ES->getSymbol();
3330 }
3331
3332 if (Sym.empty())
3333 return;
3334
3335 MachineFunction *MF = MI.getParent()->getParent();
3336 MCSymbol *S = MF->getContext().getOrCreateSymbol(Sym);
3337 LLVM_DEBUG(dbgs() << "Adding R_MIPS_JALR against " << Sym << "\n");
3339 }
3340 }
3341}
3342
3343/// LowerCall - functions arguments are copied from virtual regs to
3344/// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
3345SDValue
3346MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3347 SmallVectorImpl<SDValue> &InVals) const {
3348 SelectionDAG &DAG = CLI.DAG;
3349 SDLoc DL = CLI.DL;
3351 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3353 SDValue Chain = CLI.Chain;
3354 SDValue Callee = CLI.Callee;
3355 bool &IsTailCall = CLI.IsTailCall;
3356 CallingConv::ID CallConv = CLI.CallConv;
3357 bool IsVarArg = CLI.IsVarArg;
3358 const CallBase *CB = CLI.CB;
3359
3361 MachineFrameInfo &MFI = MF.getFrameInfo();
3363 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
3364 bool IsPIC = isPositionIndependent();
3365
3366 // Analyze operands of the call, assigning locations to each operand.
3368 MipsCCState CCInfo(
3369 CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(),
3371
3372 const ExternalSymbolSDNode *ES =
3374
3375 // There is one case where CALLSEQ_START..CALLSEQ_END can be nested, which
3376 // is during the lowering of a call with a byval argument which produces
3377 // a call to memcpy. For the O32 case, this causes the caller to allocate
3378 // stack space for the reserved argument area for the callee, then recursively
3379 // again for the memcpy call. In the NEWABI case, this doesn't occur as those
3380 // ABIs mandate that the callee allocates the reserved argument area. We do
3381 // still produce nested CALLSEQ_START..CALLSEQ_END with zero space though.
3382 //
3383 // If the callee has a byval argument and memcpy is used, we are mandated
3384 // to already have produced a reserved argument area for the callee for O32.
3385 // Therefore, the reserved argument area can be reused for both calls.
3386 //
3387 // Other cases of calling memcpy cannot have a chain with a CALLSEQ_START
3388 // present, as we have yet to hook that node onto the chain.
3389 //
3390 // Hence, the CALLSEQ_START and CALLSEQ_END nodes can be eliminated in this
3391 // case. GCC does a similar trick, in that wherever possible, it calculates
3392 // the maximum out going argument area (including the reserved area), and
3393 // preallocates the stack space on entrance to the caller.
3394 //
3395 // FIXME: We should do the same for efficiency and space.
3396
3397 // Note: The check on the calling convention below must match
3398 // MipsABIInfo::GetCalleeAllocdArgSizeInBytes().
3399 bool MemcpyInByVal = ES && StringRef(ES->getSymbol()) == "memcpy" &&
3400 CallConv != CallingConv::Fast &&
3401 Chain.getOpcode() == ISD::CALLSEQ_START;
3402
3403 // Allocate the reserved argument area. It seems strange to do this from the
3404 // caller side but removing it breaks the frame size calculation.
3405 unsigned ReservedArgArea =
3406 MemcpyInByVal ? 0 : ABI.GetCalleeAllocdArgSizeInBytes(CallConv);
3407 CCInfo.AllocateStack(ReservedArgArea, Align(1));
3408
3409 CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
3410
3411 // Get a count of how many bytes are to be pushed on the stack.
3412 unsigned StackSize = CCInfo.getStackSize();
3413
3414 // Call site info for function parameters tracking and call base type info.
3416 // Set type id for call site info.
3417 setTypeIdForCallsiteInfo(CB, MF, CSInfo);
3418
3419 // Check if it's really possible to do a tail call.
3420 // For non-musttail calls, restrict to functions that won't require $gp
3421 // restoration. In PIC mode, calling external functions via tail call can
3422 // cause issues with $gp register handling (see D24763).
3423 bool IsMustTail = CLI.CB && CLI.CB->isMustTailCall();
3424 bool CalleeIsLocal = true;
3426 const GlobalValue *GV = G->getGlobal();
3427 bool HasLocalLinkage = GV->hasLocalLinkage() || GV->hasPrivateLinkage();
3428 bool HasHiddenVisibility =
3430 if (GV->isDeclarationForLinker())
3431 CalleeIsLocal = HasLocalLinkage || HasHiddenVisibility;
3432 else
3433 CalleeIsLocal = GV->isDSOLocal();
3434 }
3435
3436 if (IsTailCall) {
3437 if (!UseMipsTailCalls) {
3438 IsTailCall = false;
3439 if (IsMustTail)
3440 report_fatal_error("failed to perform tail call elimination on a call "
3441 "site marked musttail");
3442 } else {
3443 bool Eligible = isEligibleForTailCallOptimization(
3444 CCInfo, StackSize, *MF.getInfo<MipsFunctionInfo>());
3445 if (!Eligible || !CalleeIsLocal) {
3446 IsTailCall = false;
3447 if (IsMustTail)
3449 "failed to perform tail call elimination on a call "
3450 "site marked musttail");
3451 }
3452 }
3453 }
3454
3455 if (IsTailCall)
3456 ++NumTailCalls;
3457
3458 // Chain is the output chain of the last Load/Store or CopyToReg node.
3459 // ByValChain is the output chain of the last Memcpy node created for copying
3460 // byval arguments to the stack.
3461 unsigned StackAlignment = TFL->getStackAlignment();
3462 StackSize = alignTo(StackSize, StackAlignment);
3463
3464 if (!(IsTailCall || MemcpyInByVal))
3465 Chain = DAG.getCALLSEQ_START(Chain, StackSize, 0, DL);
3466
3467 SDValue StackPtr =
3468 DAG.getCopyFromReg(Chain, DL, ABI.IsN64() ? Mips::SP_64 : Mips::SP,
3470 std::deque<std::pair<unsigned, SDValue>> RegsToPass;
3471 SmallVector<SDValue, 8> MemOpChains;
3472
3473 CCInfo.rewindByValRegsInfo();
3474
3475 // Walk the register/memloc assignments, inserting copies/loads.
3476 for (unsigned i = 0, e = ArgLocs.size(), OutIdx = 0; i != e; ++i, ++OutIdx) {
3477 SDValue Arg = OutVals[OutIdx];
3478 CCValAssign &VA = ArgLocs[i];
3479 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
3480 ISD::ArgFlagsTy Flags = Outs[OutIdx].Flags;
3481 bool UseUpperBits = false;
3482
3483 // ByVal Arg.
3484 if (Flags.isByVal()) {
3485 unsigned FirstByValReg, LastByValReg;
3486 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
3487 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
3488
3489 assert(Flags.getByValSize() &&
3490 "ByVal args of size 0 should have been ignored by front-end.");
3491 assert(ByValIdx < CCInfo.getInRegsParamsCount());
3492 assert(!IsTailCall &&
3493 "Do not tail-call optimize if there is a byval argument.");
3494 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
3495 FirstByValReg, LastByValReg, Flags, Subtarget.isLittle(),
3496 VA);
3497 CCInfo.nextInRegsParam();
3498 continue;
3499 }
3500
3501 // Promote the value if needed.
3502 switch (VA.getLocInfo()) {
3503 default:
3504 llvm_unreachable("Unknown loc info!");
3505 case CCValAssign::Full:
3506 if (VA.isRegLoc()) {
3507 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
3508 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
3509 (ValVT == MVT::i64 && LocVT == MVT::f64))
3510 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
3511 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
3512 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
3513 Arg, DAG.getConstant(0, DL, MVT::i32));
3514 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
3515 Arg, DAG.getConstant(1, DL, MVT::i32));
3516 if (!Subtarget.isLittle())
3517 std::swap(Lo, Hi);
3518
3519 assert(VA.needsCustom());
3520
3521 Register LocRegLo = VA.getLocReg();
3522 Register LocRegHigh = ArgLocs[++i].getLocReg();
3523 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
3524 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
3525 continue;
3526 }
3527 }
3528 break;
3529 case CCValAssign::BCvt:
3530 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
3531 break;
3533 UseUpperBits = true;
3534 [[fallthrough]];
3535 case CCValAssign::SExt:
3536 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
3537 break;
3539 UseUpperBits = true;
3540 [[fallthrough]];
3541 case CCValAssign::ZExt:
3542 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
3543 break;
3545 UseUpperBits = true;
3546 [[fallthrough]];
3547 case CCValAssign::AExt:
3548 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
3549 break;
3550 }
3551
3552 if (UseUpperBits) {
3553 unsigned ValSizeInBits = Outs[OutIdx].ArgVT.getSizeInBits();
3554 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3555 Arg = DAG.getNode(
3556 ISD::SHL, DL, VA.getLocVT(), Arg,
3557 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3558 }
3559
3560 // Arguments that can be passed on register must be kept at
3561 // RegsToPass vector
3562 if (VA.isRegLoc()) {
3563 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3564
3565 // If the parameter is passed through reg $D, which splits into
3566 // two physical registers, avoid creating call site info.
3567 if (Mips::AFGR64RegClass.contains(VA.getLocReg()))
3568 continue;
3569
3570 // Collect CSInfo about which register passes which parameter.
3571 const TargetOptions &Options = DAG.getTarget().Options;
3572 if (Options.EmitCallSiteInfo)
3573 CSInfo.ArgRegPairs.emplace_back(VA.getLocReg(), i);
3574
3575 continue;
3576 }
3577
3578 // Register can't get to this point...
3579 assert(VA.isMemLoc());
3580
3581 // emit ISD::STORE whichs stores the
3582 // parameter value to a stack Location
3583 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
3584 Chain, Arg, DL, IsTailCall, DAG));
3585 }
3586
3587 // Transform all store nodes into one single node because all store
3588 // nodes are independent of each other.
3589 if (!MemOpChains.empty())
3590 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3591
3592 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3593 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3594 // node so that legalize doesn't hack it.
3595
3596 EVT Ty = Callee.getValueType();
3597 bool GlobalOrExternal = false, IsCallReloc = false;
3598
3599 // The long-calls feature is ignored in case of PIC.
3600 // While we do not support -mshared / -mno-shared properly,
3601 // ignore long-calls in case of -mabicalls too.
3602 if (!Subtarget.isABICalls() && !IsPIC) {
3603 // If the function should be called using "long call",
3604 // get its address into a register to prevent using
3605 // of the `jal` instruction for the direct call.
3606 if (auto *N = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3607 if (Subtarget.useLongCalls())
3608 Callee = Subtarget.hasSym32()
3609 ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
3610 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
3611 } else if (auto *N = dyn_cast<GlobalAddressSDNode>(Callee)) {
3612 bool UseLongCalls = Subtarget.useLongCalls();
3613 // If the function has long-call/far/near attribute
3614 // it overrides command line switch pased to the backend.
3615 if (auto *F = dyn_cast<Function>(N->getGlobal())) {
3616 if (F->hasFnAttribute("long-call"))
3617 UseLongCalls = true;
3618 else if (F->hasFnAttribute("short-call"))
3619 UseLongCalls = false;
3620 }
3621 if (UseLongCalls)
3622 Callee = Subtarget.hasSym32()
3623 ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
3624 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
3625 }
3626 }
3627
3628 bool InternalLinkage = false;
3629 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3630 if (Subtarget.isTargetCOFF() &&
3631 G->getGlobal()->hasDLLImportStorageClass()) {
3632 assert(Subtarget.isTargetWindows() &&
3633 "Windows is the only supported COFF target");
3634 auto PtrInfo = MachinePointerInfo();
3635 Callee = DAG.getLoad(Ty, DL, Chain,
3636 getDllimportSymbol(G, SDLoc(G), Ty, DAG), PtrInfo);
3637 } else if (IsPIC) {
3638 const GlobalValue *Val = G->getGlobal();
3639 InternalLinkage = Val->hasInternalLinkage();
3640
3641 if (InternalLinkage)
3642 Callee = getAddrLocal(G, DL, Ty, DAG, ABI.IsN32() || ABI.IsN64());
3643 else if (Subtarget.useXGOT()) {
3645 MipsII::MO_CALL_LO16, Chain,
3646 FuncInfo->callPtrInfo(MF, Val));
3647 IsCallReloc = true;
3648 } else {
3649 Callee = getAddrGlobal(G, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
3650 FuncInfo->callPtrInfo(MF, Val));
3651 IsCallReloc = true;
3652 }
3653 } else
3654 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL,
3655 getPointerTy(DAG.getDataLayout()), 0,
3657 GlobalOrExternal = true;
3658 }
3659 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3660 const char *Sym = S->getSymbol();
3661
3662 if (!IsPIC) // static
3665 else if (Subtarget.useXGOT()) {
3667 MipsII::MO_CALL_LO16, Chain,
3668 FuncInfo->callPtrInfo(MF, Sym));
3669 IsCallReloc = true;
3670 } else { // PIC
3671 Callee = getAddrGlobal(S, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
3672 FuncInfo->callPtrInfo(MF, Sym));
3673 IsCallReloc = true;
3674 }
3675
3676 GlobalOrExternal = true;
3677 }
3678
3679 SmallVector<SDValue, 8> Ops(1, Chain);
3680 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3681
3682 getOpndList(Ops, RegsToPass, IsPIC, GlobalOrExternal, InternalLinkage,
3683 IsCallReloc, CLI, Callee, Chain);
3684
3685 if (IsTailCall) {
3687 SDValue Ret = DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
3688 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
3689 return Ret;
3690 }
3691
3692 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
3693 SDValue InGlue = Chain.getValue(1);
3694
3695 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
3696
3697 // Create the CALLSEQ_END node in the case of where it is not a call to
3698 // memcpy.
3699 if (!(MemcpyInByVal)) {
3700 Chain = DAG.getCALLSEQ_END(Chain, StackSize, 0, InGlue, DL);
3701 InGlue = Chain.getValue(1);
3702 }
3703
3704 // Handle result values, copying them out of physregs into vregs that we
3705 // return.
3706 return LowerCallResult(Chain, InGlue, CallConv, IsVarArg, Ins, DL, DAG,
3707 InVals, CLI);
3708}
3709
3710/// LowerCallResult - Lower the result values of a call into the
3711/// appropriate copies out of appropriate physical registers.
3712SDValue MipsTargetLowering::LowerCallResult(
3713 SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool IsVarArg,
3714 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3717 // Assign locations to each value returned by this call.
3719 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
3720 *DAG.getContext());
3721
3722 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
3723
3724 // Copy all of the result registers out of their specified physreg.
3725 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3726 CCValAssign &VA = RVLocs[i];
3727 assert(VA.isRegLoc() && "Can only return in registers!");
3728
3729 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
3730 RVLocs[i].getLocVT(), InGlue);
3731 Chain = Val.getValue(1);
3732 InGlue = Val.getValue(2);
3733
3734 if (VA.isUpperBitsInLoc()) {
3735 unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
3736 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3737 unsigned Shift =
3739 Val = DAG.getNode(
3740 Shift, DL, VA.getLocVT(), Val,
3741 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3742 }
3743
3744 switch (VA.getLocInfo()) {
3745 default:
3746 llvm_unreachable("Unknown loc info!");
3747 case CCValAssign::Full:
3748 break;
3749 case CCValAssign::BCvt:
3750 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3751 break;
3752 case CCValAssign::AExt:
3754 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3755 break;
3756 case CCValAssign::ZExt:
3758 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
3759 DAG.getValueType(VA.getValVT()));
3760 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3761 break;
3762 case CCValAssign::SExt:
3764 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
3765 DAG.getValueType(VA.getValVT()));
3766 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3767 break;
3768 }
3769
3770 InVals.push_back(Val);
3771 }
3772
3773 return Chain;
3774}
3775
3777 EVT ArgVT, const SDLoc &DL,
3778 SelectionDAG &DAG) {
3779 MVT LocVT = VA.getLocVT();
3780 EVT ValVT = VA.getValVT();
3781
3782 // Shift into the upper bits if necessary.
3783 switch (VA.getLocInfo()) {
3784 default:
3785 break;
3789 unsigned ValSizeInBits = ArgVT.getSizeInBits();
3790 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3791 unsigned Opcode =
3793 Val = DAG.getNode(
3794 Opcode, DL, VA.getLocVT(), Val,
3795 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3796 break;
3797 }
3798 }
3799
3800 // If this is an value smaller than the argument slot size (32-bit for O32,
3801 // 64-bit for N32/N64), it has been promoted in some way to the argument slot
3802 // size. Extract the value and insert any appropriate assertions regarding
3803 // sign/zero extension.
3804 switch (VA.getLocInfo()) {
3805 default:
3806 llvm_unreachable("Unknown loc info!");
3807 case CCValAssign::Full:
3808 break;
3810 case CCValAssign::AExt:
3811 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3812 break;
3814 case CCValAssign::SExt:
3815 Val = DAG.getNode(ISD::AssertSext, DL, LocVT, Val, DAG.getValueType(ValVT));
3816 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3817 break;
3819 case CCValAssign::ZExt:
3820 Val = DAG.getNode(ISD::AssertZext, DL, LocVT, Val, DAG.getValueType(ValVT));
3821 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3822 break;
3823 case CCValAssign::BCvt:
3824 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
3825 break;
3826 }
3827
3828 return Val;
3829}
3830
3831//===----------------------------------------------------------------------===//
3832// Formal Arguments Calling Convention Implementation
3833//===----------------------------------------------------------------------===//
3834/// LowerFormalArguments - transform physical registers into virtual registers
3835/// and generate load operations for arguments places on the stack.
3836SDValue MipsTargetLowering::LowerFormalArguments(
3837 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
3838 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3839 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3841 MachineFrameInfo &MFI = MF.getFrameInfo();
3842 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3843
3844 MipsFI->setVarArgsFrameIndex(0);
3845
3846 // Used with vargs to acumulate store chains.
3847 std::vector<SDValue> OutChains;
3848
3849 // Assign locations to all of the incoming arguments.
3851 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3852 *DAG.getContext());
3853 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), Align(1));
3855 Function::const_arg_iterator FuncArg = Func.arg_begin();
3856
3857 if (Func.hasFnAttribute("interrupt") && !Func.arg_empty())
3859 "Functions with the interrupt attribute cannot have arguments!");
3860
3861 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg);
3862 MipsFI->setFormalArgInfo(CCInfo.getStackSize(),
3863 CCInfo.getInRegsParamsCount() > 0);
3864
3865 unsigned CurArgIdx = 0;
3866 CCInfo.rewindByValRegsInfo();
3867
3868 for (unsigned i = 0, e = ArgLocs.size(), InsIdx = 0; i != e; ++i, ++InsIdx) {
3869 CCValAssign &VA = ArgLocs[i];
3870 if (Ins[InsIdx].isOrigArg()) {
3871 std::advance(FuncArg, Ins[InsIdx].getOrigArgIndex() - CurArgIdx);
3872 CurArgIdx = Ins[InsIdx].getOrigArgIndex();
3873 }
3874 EVT ValVT = VA.getValVT();
3875 ISD::ArgFlagsTy Flags = Ins[InsIdx].Flags;
3876 bool IsRegLoc = VA.isRegLoc();
3877
3878 if (Flags.isByVal()) {
3879 assert(Ins[InsIdx].isOrigArg() && "Byval arguments cannot be implicit");
3880 unsigned FirstByValReg, LastByValReg;
3881 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
3882 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
3883
3884 assert(Flags.getByValSize() &&
3885 "ByVal args of size 0 should have been ignored by front-end.");
3886 assert(ByValIdx < CCInfo.getInRegsParamsCount());
3887 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
3888 FirstByValReg, LastByValReg, VA, CCInfo);
3889 CCInfo.nextInRegsParam();
3890 continue;
3891 }
3892
3893 // Arguments stored on registers
3894 if (IsRegLoc) {
3895 MVT RegVT = VA.getLocVT();
3896 Register ArgReg = VA.getLocReg();
3897 const TargetRegisterClass *RC = getRegClassFor(RegVT);
3898
3899 // Transform the arguments stored on
3900 // physical registers into virtual ones
3901 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3902 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3903
3904 ArgValue =
3905 UnpackFromArgumentSlot(ArgValue, VA, Ins[InsIdx].ArgVT, DL, DAG);
3906
3907 // Handle floating point arguments passed in integer registers and
3908 // long double arguments passed in floating point registers.
3909 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3910 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
3911 (RegVT == MVT::f64 && ValVT == MVT::i64))
3912 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
3913 else if (ABI.IsO32() && RegVT == MVT::i32 &&
3914 ValVT == MVT::f64) {
3915 assert(VA.needsCustom() && "Expected custom argument for f64 split");
3916 CCValAssign &NextVA = ArgLocs[++i];
3917 unsigned Reg2 =
3918 addLiveIn(DAG.getMachineFunction(), NextVA.getLocReg(), RC);
3919 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
3920 if (!Subtarget.isLittle())
3921 std::swap(ArgValue, ArgValue2);
3922 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
3923 ArgValue, ArgValue2);
3924 }
3925
3926 InVals.push_back(ArgValue);
3927 } else { // VA.isRegLoc()
3928 MVT LocVT = VA.getLocVT();
3929
3930 assert(!VA.needsCustom() && "unexpected custom memory argument");
3931
3932 // Only arguments pased on the stack should make it here.
3933 assert(VA.isMemLoc());
3934
3935 // The stack pointer offset is relative to the caller stack frame.
3936 int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8,
3937 VA.getLocMemOffset(), true);
3938
3939 // Create load nodes to retrieve arguments from the stack
3940 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3941 SDValue ArgValue = DAG.getLoad(
3942 LocVT, DL, Chain, FIN,
3944 OutChains.push_back(ArgValue.getValue(1));
3945
3946 ArgValue =
3947 UnpackFromArgumentSlot(ArgValue, VA, Ins[InsIdx].ArgVT, DL, DAG);
3948
3949 InVals.push_back(ArgValue);
3950 }
3951 }
3952
3953 for (unsigned i = 0, e = ArgLocs.size(), InsIdx = 0; i != e; ++i, ++InsIdx) {
3954
3955 if (ArgLocs[i].needsCustom()) {
3956 ++i;
3957 continue;
3958 }
3959
3960 // The mips ABIs for returning structs by value requires that we copy
3961 // the sret argument into $v0 for the return. Save the argument into
3962 // a virtual register so that we can access it from the return points.
3963 if (Ins[InsIdx].Flags.isSRet()) {
3964 unsigned Reg = MipsFI->getSRetReturnReg();
3965 if (!Reg) {
3967 getRegClassFor(ABI.IsN64() ? MVT::i64 : MVT::i32));
3968 MipsFI->setSRetReturnReg(Reg);
3969 }
3970 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
3971 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3972 break;
3973 }
3974 }
3975
3976 if (IsVarArg)
3977 writeVarArgRegs(OutChains, Chain, DL, DAG, CCInfo);
3978
3979 // All stores are grouped in one node to allow the matching between
3980 // the size of Ins and InVals. This only happens when on varg functions
3981 if (!OutChains.empty()) {
3982 OutChains.push_back(Chain);
3983 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
3984 }
3985
3986 return Chain;
3987}
3988
3989//===----------------------------------------------------------------------===//
3990// Return Value Calling Convention Implementation
3991//===----------------------------------------------------------------------===//
3992
3993bool
3994MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3995 MachineFunction &MF, bool IsVarArg,
3997 LLVMContext &Context, const Type *RetTy) const {
3999 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
4000 return CCInfo.CheckReturn(Outs, RetCC_Mips);
4001}
4002
4003bool MipsTargetLowering::shouldSignExtendTypeInLibCall(Type *Ty,
4004 bool IsSigned) const {
4005 if ((ABI.IsN32() || ABI.IsN64()) && Ty->isIntegerTy(32))
4006 return true;
4007
4008 return IsSigned;
4009}
4010
4011SDValue
4012MipsTargetLowering::LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
4013 const SDLoc &DL,
4014 SelectionDAG &DAG) const {
4016 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
4017
4018 MipsFI->setISR();
4019
4020 return DAG.getNode(MipsISD::ERet, DL, MVT::Other, RetOps);
4021}
4022
4023SDValue
4024MipsTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
4025 bool IsVarArg,
4027 const SmallVectorImpl<SDValue> &OutVals,
4028 const SDLoc &DL, SelectionDAG &DAG) const {
4029 // CCValAssign - represent the assignment of
4030 // the return value to a location
4033
4034 // CCState - Info about the registers and stack slot.
4035 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
4036
4037 // Analyze return values.
4038 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
4039
4040 SDValue Glue;
4041 SmallVector<SDValue, 4> RetOps(1, Chain);
4042
4043 // Copy the result values into the output registers.
4044 for (unsigned i = 0; i != RVLocs.size(); ++i) {
4045 SDValue Val = OutVals[i];
4046 CCValAssign &VA = RVLocs[i];
4047 assert(VA.isRegLoc() && "Can only return in registers!");
4048 bool UseUpperBits = false;
4049
4050 switch (VA.getLocInfo()) {
4051 default:
4052 llvm_unreachable("Unknown loc info!");
4053 case CCValAssign::Full:
4054 break;
4055 case CCValAssign::BCvt:
4056 Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
4057 break;
4059 UseUpperBits = true;
4060 [[fallthrough]];
4061 case CCValAssign::AExt:
4062 Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
4063 break;
4065 UseUpperBits = true;
4066 [[fallthrough]];
4067 case CCValAssign::ZExt:
4068 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
4069 break;
4071 UseUpperBits = true;
4072 [[fallthrough]];
4073 case CCValAssign::SExt:
4074 Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
4075 break;
4076 }
4077
4078 if (UseUpperBits) {
4079 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
4080 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
4081 Val = DAG.getNode(
4082 ISD::SHL, DL, VA.getLocVT(), Val,
4083 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
4084 }
4085
4086 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
4087
4088 // Guarantee that all emitted copies are stuck together with flags.
4089 Glue = Chain.getValue(1);
4090 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4091 }
4092
4093 // The mips ABIs for returning structs by value requires that we copy
4094 // the sret argument into $v0 for the return. We saved the argument into
4095 // a virtual register in the entry block, so now we copy the value out
4096 // and into $v0.
4097 if (MF.getFunction().hasStructRetAttr()) {
4098 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
4099 unsigned Reg = MipsFI->getSRetReturnReg();
4100
4101 if (!Reg)
4102 llvm_unreachable("sret virtual register not created in the entry block");
4103 SDValue Val =
4104 DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(DAG.getDataLayout()));
4105 unsigned V0 = ABI.getReturnRegPtr(0);
4106
4107 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Glue);
4108 Glue = Chain.getValue(1);
4109 RetOps.push_back(DAG.getRegister(V0, getPointerTy(DAG.getDataLayout())));
4110 }
4111
4112 RetOps[0] = Chain; // Update chain.
4113
4114 // Add the glue if we have it.
4115 if (Glue.getNode())
4116 RetOps.push_back(Glue);
4117
4118 // ISRs must use "eret".
4119 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt"))
4120 return LowerInterruptReturn(RetOps, DL, DAG);
4121
4122 // Standard return on Mips is a "jr $ra"
4123 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
4124}
4125
4126//===----------------------------------------------------------------------===//
4127// Mips Inline Assembly Support
4128//===----------------------------------------------------------------------===//
4129
4130/// getConstraintType - Given a constraint letter, return the type of
4131/// constraint it is for this target.
4133MipsTargetLowering::getConstraintType(StringRef Constraint) const {
4134 // Mips specific constraints
4135 // GCC config/mips/constraints.md
4136 //
4137 // 'd' : An address register. Equivalent to r
4138 // unless generating MIPS16 code.
4139 // 'y' : Equivalent to r; retained for
4140 // backwards compatibility.
4141 // 'c' : A register suitable for use in an indirect
4142 // jump. This will always be $25 for -mabicalls.
4143 // 'l' : The lo register. 1 word storage.
4144 // 'x' : The hilo register pair. Double word storage.
4145 if (Constraint.size() == 1) {
4146 switch (Constraint[0]) {
4147 default : break;
4148 case 'd':
4149 case 'y':
4150 case 'f':
4151 case 'c':
4152 case 'l':
4153 case 'x':
4154 return C_RegisterClass;
4155 case 'R':
4156 return C_Memory;
4157 }
4158 }
4159
4160 if (Constraint == "ZC")
4161 return C_Memory;
4162
4163 return TargetLowering::getConstraintType(Constraint);
4164}
4165
4166/// Examine constraint type and operand type and determine a weight value.
4167/// This object must already have been set up with the operand type
4168/// and the current alternative constraint selected.
4170MipsTargetLowering::getSingleConstraintMatchWeight(
4171 AsmOperandInfo &info, const char *constraint) const {
4173 Value *CallOperandVal = info.CallOperandVal;
4174 // If we don't have a value, we can't do a match,
4175 // but allow it at the lowest weight.
4176 if (!CallOperandVal)
4177 return CW_Default;
4178 Type *type = CallOperandVal->getType();
4179 // Look at the constraint type.
4180 switch (*constraint) {
4181 default:
4183 break;
4184 case 'd':
4185 case 'y':
4186 if (type->isIntegerTy())
4187 weight = CW_Register;
4188 break;
4189 case 'f': // FPU or MSA register
4190 if (Subtarget.hasMSA() && type->isVectorTy() &&
4191 type->getPrimitiveSizeInBits().getFixedValue() == 128)
4192 weight = CW_Register;
4193 else if (type->isFloatTy())
4194 weight = CW_Register;
4195 break;
4196 case 'c': // $25 for indirect jumps
4197 case 'l': // lo register
4198 case 'x': // hilo register pair
4199 if (type->isIntegerTy())
4200 weight = CW_SpecificReg;
4201 break;
4202 case 'I': // signed 16 bit immediate
4203 case 'J': // integer zero
4204 case 'K': // unsigned 16 bit immediate
4205 case 'L': // signed 32 bit immediate where lower 16 bits are 0
4206 case 'N': // immediate in the range of -65535 to -1 (inclusive)
4207 case 'O': // signed 15 bit immediate (+- 16383)
4208 case 'P': // immediate in the range of 65535 to 1 (inclusive)
4209 if (isa<ConstantInt>(CallOperandVal))
4210 weight = CW_Constant;
4211 break;
4212 case 'R':
4213 weight = CW_Memory;
4214 break;
4215 }
4216 return weight;
4217}
4218
4219/// This is a helper function to parse a physical register string and split it
4220/// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
4221/// that is returned indicates whether parsing was successful. The second flag
4222/// is true if the numeric part exists.
4223static std::pair<bool, bool> parsePhysicalReg(StringRef C, StringRef &Prefix,
4224 unsigned long long &Reg) {
4225 if (C.front() != '{' || C.back() != '}')
4226 return std::make_pair(false, false);
4227
4228 // Search for the first numeric character.
4229 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
4230 I = std::find_if(B, E, isdigit);
4231
4232 Prefix = StringRef(B, I - B);
4233
4234 // The second flag is set to false if no numeric characters were found.
4235 if (I == E)
4236 return std::make_pair(true, false);
4237
4238 // Parse the numeric characters.
4239 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
4240 true);
4241}
4242
4244 ISD::NodeType) const {
4245 bool Cond = !Subtarget.isABI_O32() && VT.getSizeInBits() == 32;
4246 EVT MinVT = getRegisterType(Context, Cond ? MVT::i64 : MVT::i32);
4247 return VT.bitsLT(MinVT) ? MinVT : VT;
4248}
4249
4250std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
4251parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
4252 const TargetRegisterInfo *TRI =
4254 const TargetRegisterClass *RC;
4255 StringRef Prefix;
4256 unsigned long long Reg;
4257
4258 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
4259
4260 if (!R.first)
4261 return std::make_pair(0U, nullptr);
4262
4263 for (unsigned RegClassID : {Mips::HI32RegClassID, Mips::LO32RegClassID}) {
4265 Prefix, *TRI, RegClassID, Mips::RegAliasName)) {
4266 // No numeric characters follow a hi/lo register name.
4267 if (R.second)
4268 return std::make_pair(0U, nullptr);
4269 return std::make_pair(NamedReg.id(), TRI->getRegClass(RegClassID));
4270 }
4271 }
4272
4273 if (Prefix.starts_with("$msa")) {
4274 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
4275
4276 // No numeric characters follow the name.
4277 if (R.second)
4278 return std::make_pair(0U, nullptr);
4279
4280 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
4282 Prefix.drop_front(), *TRI, Mips::MSACtrlRegClassID, Mips::RegAliasName);
4283 if (!Reg)
4284 return std::make_pair(0U, nullptr);
4285
4286 return std::make_pair(Reg, RC);
4287 }
4288
4289 if (!R.second)
4290 return std::make_pair(0U, nullptr);
4291
4292 if (Prefix == "$f") { // Parse $f0-$f31.
4293 // If the targets is single float only, always select 32-bit registers,
4294 // otherwise if the size of FP registers is 64-bit or Reg is an even number,
4295 // select the 64-bit register class. Otherwise, select the 32-bit register
4296 // class.
4297 if (VT == MVT::Other) {
4298 if (Subtarget.isSingleFloat())
4299 VT = MVT::f32;
4300 else
4301 VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
4302 }
4303
4304 RC = getRegClassFor(VT);
4305
4306 if (RC == &Mips::AFGR64RegClass) {
4307 assert(Reg % 2 == 0);
4308 Reg >>= 1;
4309 }
4310 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
4311 RC = TRI->getRegClass(Mips::FCCRegClassID);
4312 else if (Prefix == "$w") { // Parse $w0-$w31.
4313 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
4314 } else { // Parse $0-$31.
4315 assert(Prefix == "$");
4316 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
4317 }
4318
4319 assert(Reg < RC->getNumRegs());
4320 return std::make_pair(*(RC->begin() + Reg), RC);
4321}
4322
4323/// Given a register class constraint, like 'r', if this corresponds directly
4324/// to an LLVM register class, return a register of 0 and the register class
4325/// pointer.
4326std::pair<unsigned, const TargetRegisterClass *>
4327MipsTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
4328 StringRef Constraint,
4329 MVT VT) const {
4330 if (Constraint.size() == 1) {
4331 switch (Constraint[0]) {
4332 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
4333 case 'y': // Same as 'r'. Exists for compatibility.
4334 case 'r':
4335 if ((VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8 ||
4336 VT == MVT::i1) ||
4337 (VT == MVT::f32 && Subtarget.useSoftFloat())) {
4338 if (Subtarget.inMips16Mode())
4339 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
4340 return std::make_pair(0U, &Mips::GPR32RegClass);
4341 }
4342 if ((VT == MVT::i64 || (VT == MVT::f64 && Subtarget.useSoftFloat()) ||
4343 (VT == MVT::f64 && Subtarget.isSingleFloat())) &&
4344 !Subtarget.isGP64bit())
4345 return std::make_pair(0U, &Mips::GPR32RegClass);
4346 if ((VT == MVT::i64 || (VT == MVT::f64 && Subtarget.useSoftFloat()) ||
4347 (VT == MVT::f64 && Subtarget.isSingleFloat())) &&
4348 Subtarget.isGP64bit())
4349 return std::make_pair(0U, &Mips::GPR64RegClass);
4350 // This will generate an error message
4351 return std::make_pair(0U, nullptr);
4352 case 'f': // FPU or MSA register
4353 if (VT == MVT::v16i8)
4354 return std::make_pair(0U, &Mips::MSA128BRegClass);
4355 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
4356 return std::make_pair(0U, &Mips::MSA128HRegClass);
4357 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
4358 return std::make_pair(0U, &Mips::MSA128WRegClass);
4359 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
4360 return std::make_pair(0U, &Mips::MSA128DRegClass);
4361 else if (VT == MVT::f32)
4362 return std::make_pair(0U, &Mips::FGR32RegClass);
4363 else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
4364 if (Subtarget.isFP64bit())
4365 return std::make_pair(0U, &Mips::FGR64RegClass);
4366 return std::make_pair(0U, &Mips::AFGR64RegClass);
4367 }
4368 break;
4369 case 'c': // register suitable for indirect jump
4370 if (VT == MVT::i32)
4371 return std::make_pair(ABI.getTempReg(9, false).id(),
4372 &Mips::GPR32RegClass);
4373 if (VT == MVT::i64)
4374 return std::make_pair(ABI.getTempReg(9, true).id(),
4375 &Mips::GPR64RegClass);
4376 // This will generate an error message
4377 return std::make_pair(0U, nullptr);
4378 case 'l': // use the `lo` register to store values
4379 // that are no bigger than a word
4380 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8)
4381 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
4382 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
4383 case 'x': // use the concatenated `hi` and `lo` registers
4384 // to store doubleword values
4385 // Fixme: Not triggering the use of both hi and low
4386 // This will generate an error message
4387 return std::make_pair(0U, nullptr);
4388 }
4389 }
4390
4391 if (!Constraint.empty()) {
4392 std::pair<unsigned, const TargetRegisterClass *> R;
4393 R = parseRegForInlineAsmConstraint(Constraint, VT);
4394
4395 if (R.second)
4396 return R;
4397 }
4398
4399 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4400}
4401
4402/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4403/// vector. If it is invalid, don't add anything to Ops.
4404void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
4405 StringRef Constraint,
4406 std::vector<SDValue> &Ops,
4407 SelectionDAG &DAG) const {
4408 SDLoc DL(Op);
4409 SDValue Result;
4410
4411 // Only support length 1 constraints for now.
4412 if (Constraint.size() > 1)
4413 return;
4414
4415 char ConstraintLetter = Constraint[0];
4416 switch (ConstraintLetter) {
4417 default: break; // This will fall through to the generic implementation
4418 case 'I': // Signed 16 bit constant
4419 // If this fails, the parent routine will give an error
4420 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4421 EVT Type = Op.getValueType();
4422 int64_t Val = C->getSExtValue();
4423 if (isInt<16>(Val)) {
4425 break;
4426 }
4427 }
4428 return;
4429 case 'J': // integer zero
4430 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4431 EVT Type = Op.getValueType();
4432 int64_t Val = C->getZExtValue();
4433 if (Val == 0) {
4434 Result = DAG.getTargetConstant(0, DL, Type);
4435 break;
4436 }
4437 }
4438 return;
4439 case 'K': // unsigned 16 bit immediate
4440 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4441 EVT Type = Op.getValueType();
4442 uint64_t Val = C->getZExtValue();
4443 if (isUInt<16>(Val)) {
4444 Result = DAG.getTargetConstant(Val, DL, Type);
4445 break;
4446 }
4447 }
4448 return;
4449 case 'L': // signed 32 bit immediate where lower 16 bits are 0
4450 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4451 EVT Type = Op.getValueType();
4452 int64_t Val = C->getSExtValue();
4453 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
4455 break;
4456 }
4457 }
4458 return;
4459 case 'N': // immediate in the range of -65535 to -1 (inclusive)
4460 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4461 EVT Type = Op.getValueType();
4462 int64_t Val = C->getSExtValue();
4463 if ((Val >= -65535) && (Val <= -1)) {
4465 break;
4466 }
4467 }
4468 return;
4469 case 'O': // signed 15 bit immediate
4470 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4471 EVT Type = Op.getValueType();
4472 int64_t Val = C->getSExtValue();
4473 if ((isInt<15>(Val))) {
4475 break;
4476 }
4477 }
4478 return;
4479 case 'P': // immediate in the range of 1 to 65535 (inclusive)
4480 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4481 EVT Type = Op.getValueType();
4482 int64_t Val = C->getSExtValue();
4483 if ((Val <= 65535) && (Val >= 1)) {
4484 Result = DAG.getTargetConstant(Val, DL, Type);
4485 break;
4486 }
4487 }
4488 return;
4489 }
4490
4491 if (Result.getNode()) {
4492 Ops.push_back(Result);
4493 return;
4494 }
4495
4497}
4498
4499bool MipsTargetLowering::isLegalAddressingMode(const DataLayout &DL,
4500 const AddrMode &AM, Type *Ty,
4501 unsigned AS,
4502 Instruction *I) const {
4503 // No global is ever allowed as a base.
4504 if (AM.BaseGV)
4505 return false;
4506
4507 switch (AM.Scale) {
4508 case 0: // "r+i" or just "i", depending on HasBaseReg.
4509 break;
4510 case 1:
4511 if (!AM.HasBaseReg) // allow "r+i".
4512 break;
4513 return false; // disallow "r+r" or "r+r+i".
4514 default:
4515 return false;
4516 }
4517
4518 return true;
4519}
4520
4521bool
4522MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4523 // The Mips target isn't yet aware of offsets.
4524 return false;
4525}
4526
4527EVT MipsTargetLowering::getOptimalMemOpType(
4528 LLVMContext &Context, const MemOp &Op,
4529 const AttributeList &FuncAttributes) const {
4530 if (Subtarget.hasMips64())
4531 return MVT::i64;
4532
4533 return MVT::i32;
4534}
4535
4536bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
4537 bool ForCodeSize) const {
4538 if (VT != MVT::f32 && VT != MVT::f64)
4539 return false;
4540 if (Imm.isNegZero())
4541 return false;
4542 return Imm.isZero();
4543}
4544
4545bool MipsTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
4546 return isInt<16>(Imm);
4547}
4548
4549bool MipsTargetLowering::isLegalAddImmediate(int64_t Imm) const {
4550 return isInt<16>(Imm);
4551}
4552
4554 if (!isPositionIndependent())
4556 if (ABI.IsN64())
4559}
4560
4561SDValue MipsTargetLowering::getPICJumpTableRelocBase(SDValue Table,
4562 SelectionDAG &DAG) const {
4563 if (!isPositionIndependent())
4564 return Table;
4566}
4567
4569 return Subtarget.useSoftFloat();
4570}
4571
4572void MipsTargetLowering::copyByValRegs(
4573 SDValue Chain, const SDLoc &DL, std::vector<SDValue> &OutChains,
4574 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
4575 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
4576 unsigned FirstReg, unsigned LastReg, const CCValAssign &VA,
4577 MipsCCState &State) const {
4579 MachineFrameInfo &MFI = MF.getFrameInfo();
4580 unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
4581 unsigned NumRegs = LastReg - FirstReg;
4582 unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
4583 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
4584 int FrameObjOffset;
4585 ArrayRef<MCPhysReg> ByValArgRegs = ABI.GetByValArgRegs();
4586
4587 if (RegAreaSize)
4588 FrameObjOffset =
4589 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
4590 (int)((ByValArgRegs.size() - FirstReg) * GPRSizeInBytes);
4591 else
4592 FrameObjOffset = VA.getLocMemOffset();
4593
4594 // Create frame object.
4595 EVT PtrTy = getPointerTy(DAG.getDataLayout());
4596 // Make the fixed object stored to mutable so that the load instructions
4597 // referencing it have their memory dependencies added.
4598 // Set the frame object as isAliased which clears the underlying objects
4599 // vector in ScheduleDAGInstrs::buildSchedGraph() resulting in addition of all
4600 // stores as dependencies for loads referencing this fixed object.
4601 int FI = MFI.CreateFixedObject(FrameObjSize, FrameObjOffset, false, true);
4602 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4603 InVals.push_back(FIN);
4604
4605 if (!NumRegs)
4606 return;
4607
4608 // Copy arg registers.
4609 MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
4610 const TargetRegisterClass *RC = getRegClassFor(RegTy);
4611
4612 for (unsigned I = 0; I < NumRegs; ++I) {
4613 unsigned ArgReg = ByValArgRegs[FirstReg + I];
4614 unsigned VReg = addLiveIn(MF, ArgReg, RC);
4615 unsigned Offset = I * GPRSizeInBytes;
4616 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
4617 DAG.getConstant(Offset, DL, PtrTy));
4618 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
4619 StorePtr, MachinePointerInfo(FuncArg, Offset));
4620 OutChains.push_back(Store);
4621 }
4622}
4623
4624// Copy byVal arg to registers and stack.
4625void MipsTargetLowering::passByValArg(
4626 SDValue Chain, const SDLoc &DL,
4627 std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
4628 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
4629 MachineFrameInfo &MFI, SelectionDAG &DAG, SDValue Arg, unsigned FirstReg,
4630 unsigned LastReg, const ISD::ArgFlagsTy &Flags, bool isLittle,
4631 const CCValAssign &VA) const {
4632 unsigned ByValSizeInBytes = Flags.getByValSize();
4633 unsigned OffsetInBytes = 0; // From beginning of struct
4634 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4636 std::min(Flags.getNonZeroByValAlign(), Align(RegSizeInBytes));
4637 EVT PtrTy = getPointerTy(DAG.getDataLayout()),
4638 RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
4639 unsigned NumRegs = LastReg - FirstReg;
4640
4641 if (NumRegs) {
4642 ArrayRef<MCPhysReg> ArgRegs = ABI.GetByValArgRegs();
4643 bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
4644 unsigned I = 0;
4645
4646 // Copy words to registers.
4647 for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
4648 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4649 DAG.getConstant(OffsetInBytes, DL, PtrTy));
4650 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
4651 MachinePointerInfo(), Alignment);
4652 MemOpChains.push_back(LoadVal.getValue(1));
4653 unsigned ArgReg = ArgRegs[FirstReg + I];
4654 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
4655 }
4656
4657 // Return if the struct has been fully copied.
4658 if (ByValSizeInBytes == OffsetInBytes)
4659 return;
4660
4661 // Copy the remainder of the byval argument with sub-word loads and shifts.
4662 if (LeftoverBytes) {
4663 SDValue Val;
4664
4665 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
4666 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
4667 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
4668
4669 if (RemainingSizeInBytes < LoadSizeInBytes)
4670 continue;
4671
4672 // Load subword.
4673 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4674 DAG.getConstant(OffsetInBytes, DL,
4675 PtrTy));
4676 SDValue LoadVal = DAG.getExtLoad(
4677 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
4678 MVT::getIntegerVT(LoadSizeInBytes * 8), Alignment);
4679 MemOpChains.push_back(LoadVal.getValue(1));
4680
4681 // Shift the loaded value.
4682 unsigned Shamt;
4683
4684 if (isLittle)
4685 Shamt = TotalBytesLoaded * 8;
4686 else
4687 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
4688
4689 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
4690 DAG.getConstant(Shamt, DL, MVT::i32));
4691
4692 if (Val.getNode())
4693 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
4694 else
4695 Val = Shift;
4696
4697 OffsetInBytes += LoadSizeInBytes;
4698 TotalBytesLoaded += LoadSizeInBytes;
4699 Alignment = std::min(Alignment, Align(LoadSizeInBytes));
4700 }
4701
4702 unsigned ArgReg = ArgRegs[FirstReg + I];
4703 RegsToPass.push_back(std::make_pair(ArgReg, Val));
4704 return;
4705 }
4706 }
4707
4708 // Copy remainder of byval arg to it with memcpy.
4709 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
4710 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4711 DAG.getConstant(OffsetInBytes, DL, PtrTy));
4712 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
4714 Chain = DAG.getMemcpy(
4715 Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, DL, PtrTy), Alignment,
4716 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
4717 /*CI=*/nullptr, std::nullopt, MachinePointerInfo(), MachinePointerInfo());
4718 MemOpChains.push_back(Chain);
4719}
4720
4721void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
4722 SDValue Chain, const SDLoc &DL,
4723 SelectionDAG &DAG,
4724 CCState &State) const {
4725 ArrayRef<MCPhysReg> ArgRegs = ABI.getVarArgRegs(Subtarget.isGP64bit());
4726 unsigned Idx = State.getFirstUnallocated(ArgRegs);
4727 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4728 MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
4729 const TargetRegisterClass *RC = getRegClassFor(RegTy);
4731 MachineFrameInfo &MFI = MF.getFrameInfo();
4732 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
4733
4734 // Offset of the first variable argument from stack pointer.
4735 int VaArgOffset;
4736
4737 if (ArgRegs.size() == Idx)
4738 VaArgOffset = alignTo(State.getStackSize(), RegSizeInBytes);
4739 else {
4740 VaArgOffset =
4741 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
4742 (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
4743 }
4744
4745 // Record the frame index of the first variable argument
4746 // which is a value necessary to VASTART.
4747 int FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
4748 MipsFI->setVarArgsFrameIndex(FI);
4749
4750 // Copy the integer registers that have not been used for argument passing
4751 // to the argument register save area. For O32, the save area is allocated
4752 // in the caller's stack frame, while for N32/64, it is allocated in the
4753 // callee's stack frame.
4754 for (unsigned I = Idx; I < ArgRegs.size();
4755 ++I, VaArgOffset += RegSizeInBytes) {
4756 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
4757 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
4758 FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
4759 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4760 SDValue Store =
4761 DAG.getStore(Chain, DL, ArgValue, PtrOff, MachinePointerInfo());
4762 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
4763 (Value *)nullptr);
4764 OutChains.push_back(Store);
4765 }
4766}
4767
4769 Align Alignment) const {
4770 const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
4771
4772 assert(Size && "Byval argument's size shouldn't be 0.");
4773
4774 Alignment = std::min(Alignment, TFL->getStackAlign());
4775
4776 unsigned FirstReg = 0;
4777 unsigned NumRegs = 0;
4778
4779 if (State->getCallingConv() != CallingConv::Fast) {
4780 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4781 ArrayRef<MCPhysReg> IntArgRegs = ABI.GetByValArgRegs();
4782 // FIXME: The O32 case actually describes no shadow registers.
4783 const MCPhysReg *ShadowRegs =
4784 ABI.IsO32() ? IntArgRegs.data() : Mips64DPRegs;
4785
4786 // We used to check the size as well but we can't do that anymore since
4787 // CCState::HandleByVal() rounds up the size after calling this function.
4788 assert(
4789 Alignment >= Align(RegSizeInBytes) &&
4790 "Byval argument's alignment should be a multiple of RegSizeInBytes.");
4791
4792 FirstReg = State->getFirstUnallocated(IntArgRegs);
4793
4794 // If Alignment > RegSizeInBytes, the first arg register must be even.
4795 // FIXME: This condition happens to do the right thing but it's not the
4796 // right way to test it. We want to check that the stack frame offset
4797 // of the register is aligned.
4798 if ((Alignment > RegSizeInBytes) && (FirstReg % 2)) {
4799 State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
4800 ++FirstReg;
4801 }
4802
4803 // Mark the registers allocated.
4804 Size = alignTo(Size, RegSizeInBytes);
4805 for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
4806 Size -= RegSizeInBytes, ++I, ++NumRegs)
4807 State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
4808 }
4809
4810 State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);
4811}
4812
4813MachineBasicBlock *MipsTargetLowering::emitPseudoSELECT(MachineInstr &MI,
4815 bool isFPCmp,
4816 unsigned Opc) const {
4818 "Subtarget already supports SELECT nodes with the use of"
4819 "conditional-move instructions.");
4820
4821 const TargetInstrInfo *TII =
4823 DebugLoc DL = MI.getDebugLoc();
4824
4825 // To "insert" a SELECT instruction, we actually have to insert the
4826 // diamond control-flow pattern. The incoming instruction knows the
4827 // destination vreg to set, the condition code register to branch on, the
4828 // true/false values to select between, and a branch opcode to use.
4829 const BasicBlock *LLVM_BB = BB->getBasicBlock();
4831
4832 // thisMBB:
4833 // ...
4834 // TrueVal = ...
4835 // setcc r1, r2, r3
4836 // bNE r1, r0, copy1MBB
4837 // fallthrough --> copy0MBB
4838 MachineBasicBlock *thisMBB = BB;
4839 MachineFunction *F = BB->getParent();
4840 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
4841 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
4842 F->insert(It, copy0MBB);
4843 F->insert(It, sinkMBB);
4844
4845 // Transfer the remainder of BB and its successor edges to sinkMBB.
4846 sinkMBB->splice(sinkMBB->begin(), BB,
4847 std::next(MachineBasicBlock::iterator(MI)), BB->end());
4849
4850 // Next, add the true and fallthrough blocks as its successors.
4851 BB->addSuccessor(copy0MBB);
4852 BB->addSuccessor(sinkMBB);
4853
4854 if (isFPCmp) {
4855 // bc1[tf] cc, sinkMBB
4856 BuildMI(BB, DL, TII->get(Opc))
4857 .addReg(MI.getOperand(1).getReg())
4858 .addMBB(sinkMBB);
4859 } else {
4860 // bne rs, $0, sinkMBB
4861 BuildMI(BB, DL, TII->get(Opc))
4862 .addReg(MI.getOperand(1).getReg())
4863 .addReg(Mips::ZERO)
4864 .addMBB(sinkMBB);
4865 }
4866
4867 // copy0MBB:
4868 // %FalseValue = ...
4869 // # fallthrough to sinkMBB
4870 BB = copy0MBB;
4871
4872 // Update machine-CFG edges
4873 BB->addSuccessor(sinkMBB);
4874
4875 // sinkMBB:
4876 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
4877 // ...
4878 BB = sinkMBB;
4879
4880 BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(0).getReg())
4881 .addReg(MI.getOperand(2).getReg())
4882 .addMBB(thisMBB)
4883 .addReg(MI.getOperand(3).getReg())
4884 .addMBB(copy0MBB);
4885
4886 MI.eraseFromParent(); // The pseudo instruction is gone now.
4887
4888 return BB;
4889}
4890
4892MipsTargetLowering::emitPseudoD_SELECT(MachineInstr &MI,
4893 MachineBasicBlock *BB) const {
4894 assert(!(Subtarget.hasMips4() || Subtarget.hasMips32()) &&
4895 "Subtarget already supports SELECT nodes with the use of"
4896 "conditional-move instructions.");
4897
4898 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
4899 DebugLoc DL = MI.getDebugLoc();
4900
4901 // D_SELECT substitutes two SELECT nodes that goes one after another and
4902 // have the same condition operand. On machines which don't have
4903 // conditional-move instruction, it reduces unnecessary branch instructions
4904 // which are result of using two diamond patterns that are result of two
4905 // SELECT pseudo instructions.
4906 const BasicBlock *LLVM_BB = BB->getBasicBlock();
4908
4909 // thisMBB:
4910 // ...
4911 // TrueVal = ...
4912 // setcc r1, r2, r3
4913 // bNE r1, r0, copy1MBB
4914 // fallthrough --> copy0MBB
4915 MachineBasicBlock *thisMBB = BB;
4916 MachineFunction *F = BB->getParent();
4917 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
4918 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
4919 F->insert(It, copy0MBB);
4920 F->insert(It, sinkMBB);
4921
4922 // Transfer the remainder of BB and its successor edges to sinkMBB.
4923 sinkMBB->splice(sinkMBB->begin(), BB,
4924 std::next(MachineBasicBlock::iterator(MI)), BB->end());
4926
4927 // Next, add the true and fallthrough blocks as its successors.
4928 BB->addSuccessor(copy0MBB);
4929 BB->addSuccessor(sinkMBB);
4930
4931 // bne rs, $0, sinkMBB
4932 BuildMI(BB, DL, TII->get(Mips::BNE))
4933 .addReg(MI.getOperand(2).getReg())
4934 .addReg(Mips::ZERO)
4935 .addMBB(sinkMBB);
4936
4937 // copy0MBB:
4938 // %FalseValue = ...
4939 // # fallthrough to sinkMBB
4940 BB = copy0MBB;
4941
4942 // Update machine-CFG edges
4943 BB->addSuccessor(sinkMBB);
4944
4945 // sinkMBB:
4946 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
4947 // ...
4948 BB = sinkMBB;
4949
4950 // Use two PHI nodes to select two reults
4951 BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(0).getReg())
4952 .addReg(MI.getOperand(3).getReg())
4953 .addMBB(thisMBB)
4954 .addReg(MI.getOperand(5).getReg())
4955 .addMBB(copy0MBB);
4956 BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(1).getReg())
4957 .addReg(MI.getOperand(4).getReg())
4958 .addMBB(thisMBB)
4959 .addReg(MI.getOperand(6).getReg())
4960 .addMBB(copy0MBB);
4961
4962 MI.eraseFromParent(); // The pseudo instruction is gone now.
4963
4964 return BB;
4965}
4966
4969 const MachineFunction &MF) const {
4970 StringRef Name(RegName);
4971 Name.consume_front("$");
4972
4973 unsigned RegIdx;
4974 if (Name.getAsInteger(10, RegIdx)) {
4975 std::string LowerName = Name.lower();
4976 const MCRegisterInfo &MRI = *MF.getContext().getRegisterInfo();
4977 int Index =
4978 MIPS_MC::getCPURegisterIndex(LowerName, MRI, ABI.getRegAltNameIndex());
4979 if (Index < 0)
4981 Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
4982 RegIdx = Index;
4983 }
4984
4985 if (RegIdx < 32) {
4986 const MCRegisterInfo *MRI = MF.getContext().getRegisterInfo();
4987 unsigned RegClassID = Mips::GPR32RegClassID;
4988 if (VT.isValid()) {
4989 if (VT.getSizeInBits() == 64) {
4990 if (!Subtarget.isGP64bit())
4991 report_fatal_error("64-bit registers not supported on 32-bit target");
4992 RegClassID = Mips::GPR64RegClassID;
4993 } else if (VT.getSizeInBits() == 32) {
4994 RegClassID = Mips::GPR32RegClassID;
4995 } else {
4996 report_fatal_error(Twine("Invalid register \"" + StringRef(RegName) +
4997 "\" for " + Twine(VT.getSizeInBits()) +
4998 "-bit type."));
4999 }
5000 } else if (Subtarget.isGP64bit()) {
5001 RegClassID = Mips::GPR64RegClassID;
5002 }
5003 const MCRegisterClass &RC = MRI->getRegClass(RegClassID);
5004 Register Reg = RC.getRegister(RegIdx);
5005 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
5006 if (!ReservedRegs.test(Reg))
5007 reportFatalUsageError(Twine("Trying to obtain non-reserved register \"" +
5008 StringRef(RegName) + "\"."));
5009 return Reg;
5010 }
5011
5013 Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
5014}
5015
5016MachineBasicBlock *MipsTargetLowering::emitLDR_W(MachineInstr &MI,
5017 MachineBasicBlock *BB) const {
5018 MachineFunction *MF = BB->getParent();
5019 MachineRegisterInfo &MRI = MF->getRegInfo();
5021 const bool IsLittle = Subtarget.isLittle();
5022 DebugLoc DL = MI.getDebugLoc();
5023
5024 Register Dest = MI.getOperand(0).getReg();
5025 Register Address = MI.getOperand(1).getReg();
5026 unsigned Imm = MI.getOperand(2).getImm();
5027
5029
5031 // Mips release 6 can load from adress that is not naturally-aligned.
5032 Register Temp = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5033 BuildMI(*BB, I, DL, TII->get(Mips::LW))
5034 .addDef(Temp)
5035 .addUse(Address)
5036 .addImm(Imm);
5037 BuildMI(*BB, I, DL, TII->get(Mips::FILL_W)).addDef(Dest).addUse(Temp);
5038 } else {
5039 // Mips release 5 needs to use instructions that can load from an unaligned
5040 // memory address.
5041 Register LoadHalf = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5042 Register LoadFull = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5043 Register Undef = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5044 BuildMI(*BB, I, DL, TII->get(Mips::IMPLICIT_DEF)).addDef(Undef);
5045 BuildMI(*BB, I, DL, TII->get(Mips::LWR))
5046 .addDef(LoadHalf)
5047 .addUse(Address)
5048 .addImm(Imm + (IsLittle ? 0 : 3))
5049 .addUse(Undef);
5050 BuildMI(*BB, I, DL, TII->get(Mips::LWL))
5051 .addDef(LoadFull)
5052 .addUse(Address)
5053 .addImm(Imm + (IsLittle ? 3 : 0))
5054 .addUse(LoadHalf);
5055 BuildMI(*BB, I, DL, TII->get(Mips::FILL_W)).addDef(Dest).addUse(LoadFull);
5056 }
5057
5058 MI.eraseFromParent();
5059 return BB;
5060}
5061
5062MachineBasicBlock *MipsTargetLowering::emitLDR_D(MachineInstr &MI,
5063 MachineBasicBlock *BB) const {
5064 MachineFunction *MF = BB->getParent();
5065 MachineRegisterInfo &MRI = MF->getRegInfo();
5066 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
5067 const bool IsLittle = Subtarget.isLittle();
5068 DebugLoc DL = MI.getDebugLoc();
5069
5070 Register Dest = MI.getOperand(0).getReg();
5071 Register Address = MI.getOperand(1).getReg();
5072 unsigned Imm = MI.getOperand(2).getImm();
5073
5075
5076 if (Subtarget.hasMips32r6() || Subtarget.hasMips64r6()) {
5077 // Mips release 6 can load from adress that is not naturally-aligned.
5078 if (Subtarget.isGP64bit()) {
5079 Register Temp = MRI.createVirtualRegister(&Mips::GPR64RegClass);
5080 BuildMI(*BB, I, DL, TII->get(Mips::LD))
5081 .addDef(Temp)
5082 .addUse(Address)
5083 .addImm(Imm);
5084 BuildMI(*BB, I, DL, TII->get(Mips::FILL_D)).addDef(Dest).addUse(Temp);
5085 } else {
5086 Register Wtemp = MRI.createVirtualRegister(&Mips::MSA128WRegClass);
5087 Register Lo = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5088 Register Hi = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5089 BuildMI(*BB, I, DL, TII->get(Mips::LW))
5090 .addDef(Lo)
5091 .addUse(Address)
5092 .addImm(Imm + (IsLittle ? 0 : 4));
5093 BuildMI(*BB, I, DL, TII->get(Mips::LW))
5094 .addDef(Hi)
5095 .addUse(Address)
5096 .addImm(Imm + (IsLittle ? 4 : 0));
5097 BuildMI(*BB, I, DL, TII->get(Mips::FILL_W)).addDef(Wtemp).addUse(Lo);
5098 BuildMI(*BB, I, DL, TII->get(Mips::INSERT_W), Dest)
5099 .addUse(Wtemp)
5100 .addUse(Hi)
5101 .addImm(1);
5102 }
5103 } else {
5104 // Mips release 5 needs to use instructions that can load from an unaligned
5105 // memory address.
5106 Register LoHalf = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5107 Register LoFull = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5108 Register LoUndef = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5109 Register HiHalf = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5110 Register HiFull = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5111 Register HiUndef = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5112 Register Wtemp = MRI.createVirtualRegister(&Mips::MSA128WRegClass);
5113 BuildMI(*BB, I, DL, TII->get(Mips::IMPLICIT_DEF)).addDef(LoUndef);
5114 BuildMI(*BB, I, DL, TII->get(Mips::LWR))
5115 .addDef(LoHalf)
5116 .addUse(Address)
5117 .addImm(Imm + (IsLittle ? 0 : 7))
5118 .addUse(LoUndef);
5119 BuildMI(*BB, I, DL, TII->get(Mips::LWL))
5120 .addDef(LoFull)
5121 .addUse(Address)
5122 .addImm(Imm + (IsLittle ? 3 : 4))
5123 .addUse(LoHalf);
5124 BuildMI(*BB, I, DL, TII->get(Mips::IMPLICIT_DEF)).addDef(HiUndef);
5125 BuildMI(*BB, I, DL, TII->get(Mips::LWR))
5126 .addDef(HiHalf)
5127 .addUse(Address)
5128 .addImm(Imm + (IsLittle ? 4 : 3))
5129 .addUse(HiUndef);
5130 BuildMI(*BB, I, DL, TII->get(Mips::LWL))
5131 .addDef(HiFull)
5132 .addUse(Address)
5133 .addImm(Imm + (IsLittle ? 7 : 0))
5134 .addUse(HiHalf);
5135 BuildMI(*BB, I, DL, TII->get(Mips::FILL_W)).addDef(Wtemp).addUse(LoFull);
5136 BuildMI(*BB, I, DL, TII->get(Mips::INSERT_W), Dest)
5137 .addUse(Wtemp)
5138 .addUse(HiFull)
5139 .addImm(1);
5140 }
5141
5142 MI.eraseFromParent();
5143 return BB;
5144}
5145
5146MachineBasicBlock *MipsTargetLowering::emitSTR_W(MachineInstr &MI,
5147 MachineBasicBlock *BB) const {
5148 MachineFunction *MF = BB->getParent();
5149 MachineRegisterInfo &MRI = MF->getRegInfo();
5150 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
5151 const bool IsLittle = Subtarget.isLittle();
5152 DebugLoc DL = MI.getDebugLoc();
5153
5154 Register StoreVal = MI.getOperand(0).getReg();
5155 Register Address = MI.getOperand(1).getReg();
5156 unsigned Imm = MI.getOperand(2).getImm();
5157
5159
5160 if (Subtarget.hasMips32r6() || Subtarget.hasMips64r6()) {
5161 // Mips release 6 can store to adress that is not naturally-aligned.
5162 Register BitcastW = MRI.createVirtualRegister(&Mips::MSA128WRegClass);
5163 Register Tmp = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5164 BuildMI(*BB, I, DL, TII->get(Mips::COPY)).addDef(BitcastW).addUse(StoreVal);
5165 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W))
5166 .addDef(Tmp)
5167 .addUse(BitcastW)
5168 .addImm(0);
5169 BuildMI(*BB, I, DL, TII->get(Mips::SW))
5170 .addUse(Tmp)
5171 .addUse(Address)
5172 .addImm(Imm);
5173 } else {
5174 // Mips release 5 needs to use instructions that can store to an unaligned
5175 // memory address.
5176 Register Tmp = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5177 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W))
5178 .addDef(Tmp)
5179 .addUse(StoreVal)
5180 .addImm(0);
5181 BuildMI(*BB, I, DL, TII->get(Mips::SWR))
5182 .addUse(Tmp)
5183 .addUse(Address)
5184 .addImm(Imm + (IsLittle ? 0 : 3));
5185 BuildMI(*BB, I, DL, TII->get(Mips::SWL))
5186 .addUse(Tmp)
5187 .addUse(Address)
5188 .addImm(Imm + (IsLittle ? 3 : 0));
5189 }
5190
5191 MI.eraseFromParent();
5192
5193 return BB;
5194}
5195
5196MachineBasicBlock *MipsTargetLowering::emitSTR_D(MachineInstr &MI,
5197 MachineBasicBlock *BB) const {
5198 MachineFunction *MF = BB->getParent();
5199 MachineRegisterInfo &MRI = MF->getRegInfo();
5200 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
5201 const bool IsLittle = Subtarget.isLittle();
5202 DebugLoc DL = MI.getDebugLoc();
5203
5204 Register StoreVal = MI.getOperand(0).getReg();
5205 Register Address = MI.getOperand(1).getReg();
5206 unsigned Imm = MI.getOperand(2).getImm();
5207
5209
5210 if (Subtarget.hasMips32r6() || Subtarget.hasMips64r6()) {
5211 // Mips release 6 can store to adress that is not naturally-aligned.
5212 if (Subtarget.isGP64bit()) {
5213 Register BitcastD = MRI.createVirtualRegister(&Mips::MSA128DRegClass);
5214 Register Lo = MRI.createVirtualRegister(&Mips::GPR64RegClass);
5215 BuildMI(*BB, I, DL, TII->get(Mips::COPY))
5216 .addDef(BitcastD)
5217 .addUse(StoreVal);
5218 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_D))
5219 .addDef(Lo)
5220 .addUse(BitcastD)
5221 .addImm(0);
5222 BuildMI(*BB, I, DL, TII->get(Mips::SD))
5223 .addUse(Lo)
5224 .addUse(Address)
5225 .addImm(Imm);
5226 } else {
5227 Register BitcastW = MRI.createVirtualRegister(&Mips::MSA128WRegClass);
5228 Register Lo = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5229 Register Hi = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5230 BuildMI(*BB, I, DL, TII->get(Mips::COPY))
5231 .addDef(BitcastW)
5232 .addUse(StoreVal);
5233 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W))
5234 .addDef(Lo)
5235 .addUse(BitcastW)
5236 .addImm(0);
5237 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W))
5238 .addDef(Hi)
5239 .addUse(BitcastW)
5240 .addImm(1);
5241 BuildMI(*BB, I, DL, TII->get(Mips::SW))
5242 .addUse(Lo)
5243 .addUse(Address)
5244 .addImm(Imm + (IsLittle ? 0 : 4));
5245 BuildMI(*BB, I, DL, TII->get(Mips::SW))
5246 .addUse(Hi)
5247 .addUse(Address)
5248 .addImm(Imm + (IsLittle ? 4 : 0));
5249 }
5250 } else {
5251 // Mips release 5 needs to use instructions that can store to an unaligned
5252 // memory address.
5253 Register Bitcast = MRI.createVirtualRegister(&Mips::MSA128WRegClass);
5254 Register Lo = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5255 Register Hi = MRI.createVirtualRegister(&Mips::GPR32RegClass);
5256 BuildMI(*BB, I, DL, TII->get(Mips::COPY)).addDef(Bitcast).addUse(StoreVal);
5257 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W))
5258 .addDef(Lo)
5259 .addUse(Bitcast)
5260 .addImm(0);
5261 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W))
5262 .addDef(Hi)
5263 .addUse(Bitcast)
5264 .addImm(1);
5265 BuildMI(*BB, I, DL, TII->get(Mips::SWR))
5266 .addUse(Lo)
5267 .addUse(Address)
5268 .addImm(Imm + (IsLittle ? 0 : 3));
5269 BuildMI(*BB, I, DL, TII->get(Mips::SWL))
5270 .addUse(Lo)
5271 .addUse(Address)
5272 .addImm(Imm + (IsLittle ? 3 : 0));
5273 BuildMI(*BB, I, DL, TII->get(Mips::SWR))
5274 .addUse(Hi)
5275 .addUse(Address)
5276 .addImm(Imm + (IsLittle ? 4 : 7));
5277 BuildMI(*BB, I, DL, TII->get(Mips::SWL))
5278 .addUse(Hi)
5279 .addUse(Address)
5280 .addImm(Imm + (IsLittle ? 7 : 4));
5281 }
5282
5283 MI.eraseFromParent();
5284 return BB;
5285}
static SDValue performSHLCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, SelectionDAG &DAG)
If the operand is a bitwise AND with a constant RHS, and the shift has a constant RHS and is the only...
static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI)
static SDValue performANDCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned Imm
unsigned uint64_t
This file declares a class to represent arbitrary precision floating point values and provide a varie...
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis Results
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define RegName(no)
static LVOptions Options
Definition LVOptions.cpp:25
lazy value info
static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
static MachineBasicBlock * insertDivByZeroTrap(MachineInstr &MI, MachineBasicBlock *MBB)
static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const LoongArchSubtarget &Subtarget)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
cl::opt< bool > EmitJalrReloc
cl::opt< bool > NoZeroDivCheck
static bool CC_Mips(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
static SDValue performMADD_MSUBCombine(SDNode *ROOTNode, SelectionDAG &CurDAG, const MipsSubtarget &Subtarget)
static bool invertFPCondCodeUser(Mips::CondCode CC)
This function returns true if the floating point conditional branches and conditional moves which use...
static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State, ArrayRef< MCPhysReg > F64Regs)
static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG, bool SingleFloat)
static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const MipsSubtarget &Subtarget)
static const MCPhysReg Mips64DPRegs[8]
static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG, bool IsLittle)
static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD, SDValue Chain, unsigned Offset)
static unsigned addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
static std::pair< bool, bool > parsePhysicalReg(StringRef C, StringRef &Prefix, unsigned long long &Reg)
This is a helper function to parse a physical register string and split it into non-numeric and numer...
static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD, SDValue Chain, SDValue Src, unsigned Offset)
static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasExtractInsert)
static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op)
static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasExtractInsert)
DivByZeroTrapKind
static SDValue performSignExtendCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const MipsSubtarget &Subtarget)
static SDValue performCMovFPCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const MipsSubtarget &Subtarget)
static SDValue UnpackFromArgumentSlot(SDValue Val, const CCValAssign &VA, EVT ArgVT, const SDLoc &DL, SelectionDAG &DAG)
static Mips::CondCode condCodeToFCC(ISD::CondCode CC)
static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True, SDValue False, const SDLoc &DL)
static cl::opt< bool > UseMipsTailCalls("mips-tail-calls", cl::Hidden, cl::desc("MIPS: permit tail calls."), cl::init(false))
uint64_t IntrinsicInst * II
const SmallVectorImpl< MachineOperand > & Cond
SI optimize exec mask operations pre RA
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:484
This file defines the SmallVector class.
static const MCPhysReg IntRegs[32]
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static const MCPhysReg F32Regs[64]
Value * RHS
Value * LHS
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
const T * data() const
Definition ArrayRef.h:138
LLVM Basic Block Representation.
Definition BasicBlock.h:62
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:482
static constexpr BranchProbability getOne()
CCState - This class holds information needed while lowering arguments and return values.
unsigned getFirstUnallocated(ArrayRef< MCPhysReg > Regs) const
getFirstUnallocated - Return the index of the first unallocated register in the set,...
CallingConv::ID getCallingConv() const
uint64_t getStackSize() const
Returns the size of the currently allocated portion of the stack.
CCValAssign - Represent assignment of one arg/retval to a location.
Register getLocReg() const
LocInfo getLocInfo() const
static CCValAssign getReg(unsigned ValNo, MVT ValVT, MCRegister Reg, MVT LocVT, LocInfo HTP, bool IsCustom=false)
static CCValAssign getCustomReg(unsigned ValNo, MVT ValVT, MCRegister Reg, MVT LocVT, LocInfo HTP)
bool isUpperBitsInLoc() const
static CCValAssign getMem(unsigned ValNo, MVT ValVT, int64_t Offset, MVT LocVT, LocInfo HTP, bool IsCustom=false)
bool needsCustom() const
int64_t getLocMemOffset() const
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
LLVM_ABI bool isMustTailCall() const
Tests if this call site must be tail call optimized.
uint64_t getZExtValue() const
int64_t getSExtValue() const
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
LLVM_ABI TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
A debug info location.
Definition DebugLoc.h:126
const char * getSymbol() const
This is a fast-path instruction selection class that generates poor code and doesn't support illegal ...
Definition FastISel.h:67
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
bool hasStructRetAttr() const
Determine if the function returns a structure through first or second pointer argument.
Definition Function.h:673
const Argument * const_arg_iterator
Definition Function.h:74
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:730
const GlobalValue * getGlobal() const
bool isDSOLocal() const
bool hasLocalLinkage() const
bool hasPrivateLinkage() const
bool hasHiddenVisibility() const
bool hasDLLImportStorageClass() const
bool isDeclarationForLinker() const
LLVM_ABI const GlobalObject * getAliaseeObject() const
Definition Globals.cpp:521
bool hasInternalLinkage() const
bool hasProtectedVisibility() const
constexpr bool isValid() const
constexpr TypeSize getSizeInBits() const
Returns the total size of the type. Must only be called on sized types.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
LLVM_ABI void emitError(const Instruction *I, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
Tracks which library functions to use for a particular subtarget or function.
This class is used to represent ISD::LOAD nodes.
const MCRegisterInfo * getRegisterInfo() const
Definition MCContext.h:411
LLVM_ABI MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
MCRegisterClass - Base class of TargetRegisterClass.
MCRegister getRegister(unsigned i) const
getRegister - Return the specified register in the class.
iterator begin() const
begin/end - Return all of the registers in this class.
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
const MCRegisterClass & getRegClass(unsigned i) const
Returns the register class associated with the enumeration value.
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
Machine Value Type.
static auto integer_valuetypes()
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
static MVT getVectorVT(MVT VT, unsigned NumElements)
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
bool isValid() const
Return true if this is a valid simple valuetype.
static MVT getIntegerVT(unsigned BitWidth)
static auto fp_valuetypes()
static auto fp_fixedlen_vector_valuetypes()
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
LLVM_ABI int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool IsImmutable, bool isAliased=false)
Create a new object at a fixed location on the stack.
void setFrameAddressIsTaken(bool T)
void setHasTailCall(bool V=true)
void setReturnAddressIsTaken(bool s)
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MCContext & getContext() const
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
Register addLiveIn(MCRegister PReg, const TargetRegisterClass *RC)
addLiveIn - Add the specified physical register as a live-in value and create a corresponding virtual...
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & addUse(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
Representation of each machine instruction.
const MachineOperand & getOperand(unsigned i) const
@ EK_GPRel32BlockAddress
EK_GPRel32BlockAddress - Each entry is an address of block, encoded with a relocation as gp-relative,...
@ EK_BlockAddress
EK_BlockAddress - Each entry is a plain address of block, e.g.: .word LBB123.
@ EK_GPRel64BlockAddress
EK_GPRel64BlockAddress - Each entry is an address of block, encoded with a relocation as gp-relative,...
@ MOVolatile
The memory access is volatile.
Flags getFlags() const
Return the raw flags of the source value,.
MachineOperand class - Representation of each machine instruction operand.
void setSubReg(unsigned subReg)
static MachineOperand CreateMCSymbol(MCSymbol *Sym, unsigned TargetFlags=0)
void setIsKill(bool Val=true)
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
void addLiveIn(MCRegister Reg, Register vreg=Register())
addLiveIn - Add the specified register as a live-in.
Align getAlign() const
MachineMemOperand * getMemOperand() const
Return the unique MachineMemOperand object describing the memory reference performed by operation.
const MachinePointerInfo & getPointerInfo() const
const SDValue & getChain() const
EVT getMemoryVT() const
Return the type of the in-memory value.
static SpecialCallingConvType getSpecialCallingConvForCallee(const SDNode *Callee, const MipsSubtarget &Subtarget)
Determine the SpecialCallingConvType for the given callee.
MipsFunctionInfo - This class is derived from MachineFunction private Mips target-specific informatio...
void setVarArgsFrameIndex(int Index)
unsigned getSRetReturnReg() const
MachinePointerInfo callPtrInfo(MachineFunction &MF, const char *ES)
Create a MachinePointerInfo that has an ExternalSymbolPseudoSourceValue object representing a GOT ent...
Register getGlobalBaseReg(MachineFunction &MF)
void setSRetReturnReg(unsigned Reg)
void setFormalArgInfo(unsigned Size, bool HasByval)
static const uint32_t * getMips16RetHelperMask()
bool hasMips32r6() const
bool hasMips4() const
bool hasMips64r2() const
bool isLittle() const
const MipsInstrInfo * getInstrInfo() const override
bool hasMips64r6() const
bool inMips16Mode() const
bool hasMips64() const
bool hasMips32() const
const MipsRegisterInfo * getRegisterInfo() const override
bool hasCnMips() const
bool isGP64bit() const
bool hasExtractInsert() const
Features related to the presence of specific instructions.
bool isSingleFloat() const
const MipsABIInfo & getABI() const
const TargetFrameLowering * getFrameLowering() const override
MVT getRegisterTypeForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const override
Return the register type for a given MVT, ensuring vectors are treated as a series of gpr sized integ...
bool hasBitTest(SDValue X, SDValue Y) const override
Return true if the target has a bit-test instruction: (X & (1 << Y)) ==/!= 0 This knowledge can be us...
static const MipsTargetLowering * create(const MipsTargetMachine &TM, const MipsSubtarget &STI)
SDValue getAddrGPRel(NodeTy *N, const SDLoc &DL, EVT Ty, SelectionDAG &DAG, bool IsN64) const
unsigned getVectorTypeBreakdownForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT, unsigned &NumIntermediates, MVT &RegisterVT) const override
Break down vectors to the correct number of gpr sized integers.
Register getRegisterByName(const char *RegName, LLT VT, const MachineFunction &MF) const override
Return the register ID of the name passed in.
SDValue getAddrNonPICSym64(NodeTy *N, const SDLoc &DL, EVT Ty, SelectionDAG &DAG) const
EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context, EVT VT) const override
getSetCCResultType - get the ISD::SETCC result ValueType
SDValue getAddrGlobal(NodeTy *N, const SDLoc &DL, EVT Ty, SelectionDAG &DAG, unsigned Flag, SDValue Chain, const MachinePointerInfo &PtrInfo) const
MipsTargetLowering(const MipsTargetMachine &TM, const MipsSubtarget &STI)
const MipsABIInfo & ABI
SDValue getAddrGlobalLargeGOT(NodeTy *N, const SDLoc &DL, EVT Ty, SelectionDAG &DAG, unsigned HiFlag, unsigned LoFlag, SDValue Chain, const MachinePointerInfo &PtrInfo) const
SDValue getDllimportVariable(NodeTy *N, const SDLoc &DL, EVT Ty, SelectionDAG &DAG, SDValue Chain, const MachinePointerInfo &PtrInfo) const
bool shouldFoldConstantShiftPairToMask(const SDNode *N) const override
Return true if it is profitable to fold a pair of shifts into a mask.
SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const override
This method will be invoked for all target nodes and for any target-independent nodes that the target...
CCAssignFn * CCAssignFnForReturn() const
void ReplaceNodeResults(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const override
ReplaceNodeResults - Replace the results of node with an illegal result type with new values built ou...
MachineBasicBlock * EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *MBB) const override
This method should be implemented by targets that mark instructions with the 'usesCustomInserter' fla...
SDValue getDllimportSymbol(NodeTy *N, const SDLoc &DL, EVT Ty, SelectionDAG &DAG) const
CCAssignFn * CCAssignFnForCall() const
unsigned getNumRegistersForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const override
Return the number of registers for a given MVT, ensuring vectors are treated as a series of gpr sized...
SDValue getAddrNonPIC(NodeTy *N, const SDLoc &DL, EVT Ty, SelectionDAG &DAG) const
SDValue lowerSTORE(SDValue Op, SelectionDAG &DAG) const
FastISel * createFastISel(FunctionLoweringInfo &funcInfo, const TargetLibraryInfo *libInfo, const LibcallLoweringInfo *libcallLowering) const override
createFastISel - This method returns a target specific FastISel object, or null if the target does no...
void AdjustInstrPostInstrSelection(MachineInstr &MI, SDNode *Node) const override
This method should be implemented by targets that mark instructions with the 'hasPostISelHook' flag.
virtual void getOpndList(SmallVectorImpl< SDValue > &Ops, std::deque< std::pair< unsigned, SDValue > > &RegsToPass, bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage, bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const
This function fills Ops, which is the list of operands that will later be used when a function call n...
EVT getTypeForExtReturn(LLVMContext &Context, EVT VT, ISD::NodeType) const override
Return the type that should be used to zero or sign extend a zeroext/signext integer return value.
bool isCheapToSpeculateCtlz(Type *Ty) const override
Return true if it is cheap to speculate a call to intrinsic ctlz.
SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const override
LowerOperation - Provide custom lowering hooks for some operations.
bool isCheapToSpeculateCttz(Type *Ty) const override
Return true if it is cheap to speculate a call to intrinsic cttz.
SDValue getAddrLocal(NodeTy *N, const SDLoc &DL, EVT Ty, SelectionDAG &DAG, bool IsN32OrN64) const
SDValue getGlobalReg(SelectionDAG &DAG, EVT Ty) const
const MipsSubtarget & Subtarget
void HandleByVal(CCState *, unsigned &, Align) const override
Target-specific cleanup for formal ByVal parameters.
SDValue lowerLOAD(SDValue Op, SelectionDAG &DAG) const
bool IsConstantInSmallSection(const DataLayout &DL, const Constant *CN, const Function *F) const
Return true if this constant should be placed into small data section.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
Represents one node in the SelectionDAG.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
uint64_t getAsZExtVal() const
Helper method returns the zero-extended integer value of a ConstantSDNode.
const SDValue & getOperand(unsigned Num) const
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
SDNode * getNode() const
get the SDNode which holds the desired result
bool hasOneUse() const
Return true if there is exactly one node using value ResNo of Node, in exactly one operand.
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
const SDValue & getOperand(unsigned i) const
unsigned getOpcode() const
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
SDValue getTargetGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, unsigned TargetFlags=0)
SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, Register Reg, SDValue N)
LLVM_ABI SDValue getMergeValues(ArrayRef< SDValue > Ops, const SDLoc &dl)
Create a MERGE_VALUES node from the given operands.
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_ABI MachineSDNode * getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT)
These are used for target selectors to create a new node with specified return type(s),...
LLVM_ABI SDValue getRegister(Register Reg, EVT VT)
SDValue getGLOBAL_OFFSET_TABLE(EVT VT)
Return a GLOBAL_OFFSET_TABLE node. This does not have a useful SDLoc.
LLVM_ABI SDValue getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef< SDValue > Ops, EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags Flags=MachineMemOperand::MOLoad|MachineMemOperand::MOStore, LocationSize Size=LocationSize::precise(0), const AAMDNodes &AAInfo=AAMDNodes())
Creates a MemIntrinsicNode that may produce a result and takes a list of operands.
SDValue getSetCC(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS, ISD::CondCode Cond, SDValue Chain=SDValue(), bool IsSignaling=false, SDNodeFlags Flags={})
Helper function to make it easier to build SetCC's if you just have an ISD::CondCode instead of an SD...
LLVM_ABI SDValue getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline, const CallInst *CI, std::optional< bool > OverrideTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo=AAMDNodes(), BatchAAResults *BatchAA=nullptr)
SDValue getTargetJumpTable(int JTI, EVT VT, unsigned TargetFlags=0)
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
SDValue getCALLSEQ_END(SDValue Chain, SDValue Op1, SDValue Op2, SDValue InGlue, const SDLoc &DL)
Return a new CALLSEQ_END node, which always must have a glue result (to ensure it's not CSE'd).
SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, Register Reg, EVT VT)
const DataLayout & getDataLayout() const
LLVM_ABI SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Helper function to build ISD::STORE nodes.
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
SDValue getSignedTargetConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
SDValue getCALLSEQ_START(SDValue Chain, uint64_t InSize, uint64_t OutSize, const SDLoc &DL)
Return a new CALLSEQ_START node, that starts new call frame, in which InSize bytes are set up inside ...
SDValue getSelectCC(const SDLoc &DL, SDValue LHS, SDValue RHS, SDValue True, SDValue False, ISD::CondCode Cond, SDNodeFlags Flags=SDNodeFlags())
Helper function to make it easier to build SelectCC's if you just have an ISD::CondCode instead of an...
LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Loads are not normal binary operators: their result type is not determined by their operands,...
LLVM_ABI SDValue getExternalSymbol(const char *Sym, EVT VT)
const TargetMachine & getTarget() const
LLVM_ABI SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI SDValue getValueType(EVT)
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
LLVM_ABI bool isKnownNeverNaN(SDValue Op, const APInt &DemandedElts, bool SNaN=false, unsigned Depth=0) const
Test whether the given SDValue (or all elements of it, if it is a vector) is known to never be NaN in...
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
SDValue getTargetBlockAddress(const BlockAddress *BA, EVT VT, int64_t Offset=0, unsigned TargetFlags=0)
LLVM_ABI void ReplaceAllUsesOfValueWith(SDValue From, SDValue To)
Replace any uses of From with To, leaving uses of other values produced by From.getNode() alone.
MachineFunction & getMachineFunction() const
LLVM_ABI SDValue getFrameIndex(int FI, EVT VT, bool isTarget=false)
LLVM_ABI SDValue getRegisterMask(const uint32_t *RegMask)
void addCallSiteInfo(const SDNode *Node, CallSiteInfo &&CallInfo)
Set CallSiteInfo to be associated with Node.
LLVMContext * getContext() const
LLVM_ABI SDValue getTargetExternalSymbol(const char *Sym, EVT VT, unsigned TargetFlags=0)
SDValue getTargetConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offset=0, unsigned TargetFlags=0)
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
LLVM_ABI std::pair< SDValue, SDValue > SplitScalar(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the scalar node with EXTRACT_ELEMENT using the provided VTs and return the low/high part.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class is used to represent ISD::STORE nodes.
const SDValue & getBasePtr() const
const SDValue & getValue() const
bool isTruncatingStore() const
Return true if the op does a truncation before store.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
const char * const_iterator
Definition StringRef.h:61
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
Information about stack frame layout on the target.
unsigned getStackAlignment() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
Align getStackAlign() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
TargetInstrInfo - Interface to description of machine instruction set.
Provides information about what library functions are available for the current target.
void setBooleanVectorContents(BooleanContent Ty)
Specify how the target extends the result of a vector boolean value from a vector of i1 to a wider ty...
void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action)
Indicate that the specified operation does not work with the specified type and indicate what to do a...
virtual const TargetRegisterClass * getRegClassFor(MVT VT, bool isDivergent=false) const
Return the register class that should be used for the specified value type.
void setMinStackArgumentAlignment(Align Alignment)
Set the minimum stack alignment of an argument.
const TargetMachine & getTargetMachine() const
MVT getRegisterType(LLVMContext &Context, EVT VT) const
Return the type of registers that this ValueType will eventually require.
virtual unsigned getNumRegisters(LLVMContext &Context, EVT VT, std::optional< MVT > RegisterVT=std::nullopt) const
Return the number of registers that this ValueType will eventually require.
void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits)
Set the maximum atomic operation size supported by the backend.
void setMinFunctionAlignment(Align Alignment)
Set the target's minimum function alignment.
void setBooleanContents(BooleanContent Ty)
Specify how the target extends the result of integer and floating point boolean values from i1 to a w...
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
void setTruncStoreAction(MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified truncating store does not work with the specified type and indicate what ...
void setStackPointerRegisterToSaveRestore(Register R)
If set to a physical register, this specifies the register that llvm.savestack/llvm....
void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT)
If Opc/OrigVT is specified as being promoted, the promotion code defaults to trying a larger integer/...
void setTargetDAGCombine(ArrayRef< ISD::NodeType > NTs)
Targets should invoke this method for each target independent node that they want to provide a custom...
virtual bool useSoftFloat() const
Align getMinStackArgumentAlignment() const
Return the minimum stack alignment of an argument.
void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified load with extension does not work with the specified type and indicate wh...
std::vector< ArgListEntry > ArgListTy
unsigned MaxStoresPerMemcpy
Specify maximum number of store instructions per memcpy call.
virtual ConstraintType getConstraintType(StringRef Constraint) const
Given a constraint, return the type of constraint it is for this target.
virtual SDValue LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, SelectionDAG &DAG) const
Lower TLS global address SDNode for target independent emulated TLS model.
std::pair< SDValue, SDValue > LowerCallTo(CallLoweringInfo &CLI) const
This function lowers an abstract call to a function into an actual call.
bool isPositionIndependent() const
virtual ConstraintWeight getSingleConstraintMatchWeight(AsmOperandInfo &info, const char *constraint) const
Examine constraint string and operand type and determine a weight value.
virtual std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const
Given a physical register constraint (e.g.
TargetLowering(const TargetLowering &)=delete
virtual ArrayRef< MCPhysReg > getRoundingControlRegisters() const
Returns a 0 terminated array of rounding control registers that can be attached into strict FP call.
virtual void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const
Lower the specified operand into the Ops vector.
virtual unsigned getJumpTableEncoding() const
Return the entry encoding for a jump table in the current function.
virtual void LowerOperationWrapper(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const
This callback is invoked by the type legalizer to legalize nodes with an illegal operand type but leg...
void setTypeIdForCallsiteInfo(const CallBase *CB, MachineFunction &MF, MachineFunction::CallSiteInfo &CSInfo) const
TLSModel::Model getTLSModel(const GlobalValue *GV) const
Returns the TLS model which should be used for the given global variable.
bool useEmulatedTLS() const
Returns true if this target uses emulated TLS.
virtual TargetLoweringObjectFile * getObjFileLowering() const
TargetOptions Options
unsigned EnableFastISel
EnableFastISel - This flag enables fast-path instruction selection which trades away generated code q...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:222
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition ISDOpcodes.h:41
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:835
@ STACKRESTORE
STACKRESTORE has two operands, an input chain and a pointer to restore to it returns an output chain.
@ STACKSAVE
STACKSAVE - STACKSAVE has one operand, an input chain.
@ STRICT_FSETCC
STRICT_FSETCC/STRICT_FSETCCS - Constrained versions of SETCC, used for floating-point operands only.
Definition ISDOpcodes.h:514
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:795
@ VAEND
VAEND, VASTART - VAEND and VASTART have three operands: an input chain, pointer, and a SRCVALUE.
@ ATOMIC_STORE
OUTCHAIN = ATOMIC_STORE(INCHAIN, val, ptr) This corresponds to "store atomic" instruction.
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:264
@ LOAD
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:869
@ FMA
FMA - Perform a * b + c with no intermediate rounding step.
Definition ISDOpcodes.h:521
@ GlobalAddress
Definition ISDOpcodes.h:88
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:418
@ MEMBARRIER
MEMBARRIER - Compiler barrier only; generate a no-op.
@ ATOMIC_FENCE
OUTCHAIN = ATOMIC_FENCE(INCHAIN, ordering, scope) This corresponds to the fence instruction.
@ SDIVREM
SDIVREM/UDIVREM - Divide two integers and produce both a quotient and remainder result.
Definition ISDOpcodes.h:280
@ FP16_TO_FP
FP16_TO_FP, FP_TO_FP16 - These operators are used to perform promotions and truncation for half-preci...
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
@ BUILD_PAIR
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition ISDOpcodes.h:254
@ GlobalTLSAddress
Definition ISDOpcodes.h:89
@ EH_RETURN
OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER) - This node represents 'eh_return' gcc dwarf builtin,...
Definition ISDOpcodes.h:156
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:860
@ TargetJumpTable
Definition ISDOpcodes.h:188
@ FSINCOS
FSINCOS - Compute both fsin and fcos as a single operation.
@ BR_CC
BR_CC - Conditional branch.
@ BR_JT
BR_JT - Jumptable branch.
@ FCANONICALIZE
Returns platform specific canonical encoding of a floating point number.
Definition ISDOpcodes.h:544
@ IS_FPCLASS
Performs a check of floating point class property, defined by IEEE-754.
Definition ISDOpcodes.h:551
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:812
@ ATOMIC_LOAD
Val, OUTCHAIN = ATOMIC_LOAD(INCHAIN, ptr) This corresponds to "load atomic" instruction.
@ VACOPY
VACOPY - VACOPY has 5 operands: an input chain, a destination pointer, a source pointer,...
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:777
@ FMINNUM_IEEE
FMINNUM_IEEE/FMAXNUM_IEEE - Perform floating-point minimumNumber or maximumNumber on two values,...
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:866
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:827
@ FMINNUM
FMINNUM/FMAXNUM - Perform floating-point minimum maximum on two values, following IEEE-754 definition...
@ DYNAMIC_STACKALLOC
DYNAMIC_STACKALLOC - Allocate some number of bytes on the stack aligned to a specified boundary.
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:904
@ EH_DWARF_CFA
EH_DWARF_CFA - This node represents the pointer to the DWARF Canonical Frame Address (CFA),...
Definition ISDOpcodes.h:150
@ FRAMEADDR
FRAMEADDR, RETURNADDR - These nodes represent llvm.frameaddress and llvm.returnaddress on the DAG.
Definition ISDOpcodes.h:110
@ STRICT_FP_TO_UINT
Definition ISDOpcodes.h:481
@ STRICT_FP_TO_SINT
STRICT_FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:480
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:942
@ READCYCLECOUNTER
READCYCLECOUNTER - This corresponds to the readcyclecounter intrinsic.
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:747
@ TRAP
TRAP - Trapping instruction.
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:53
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:872
@ VAARG
VAARG - VAARG has four operands: an input chain, a pointer, a SRCVALUE, and the alignment.
@ BRCOND
BRCOND - Conditional branch.
@ SHL_PARTS
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations.
Definition ISDOpcodes.h:849
@ AssertSext
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition ISDOpcodes.h:62
@ FCOPYSIGN
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition ISDOpcodes.h:537
@ CALLSEQ_START
CALLSEQ_START/CALLSEQ_END - These operators mark the beginning and end of a call sequence,...
LLVM_ABI CondCode getSetCCInverse(CondCode Operation, EVT Type)
Return the operation corresponding to !(X op Y), where 'op' is a valid SetCC operation.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
@ Bitcast
Perform the operation on a different, but equivalently sized type.
@ MO_TLSGD
On a symbol operand, this indicates that the immediate is the offset to the slot in GOT which stores ...
Flag
These should be considered private to the implementation of the MCInstrDesc class.
MCRegister matchRegisterName(StringRef Name, const MCRegisterInfo &MRI, unsigned RegClassID, unsigned AltIdx)
Match a symbolic name in RegClassID, or return an invalid register.
int getCPURegisterIndex(StringRef Name, const MCRegisterInfo &MRI, unsigned AltIdx, bool *IsDeprecated=nullptr)
Return a GPR name's hardware index, or -1 if unknown.
FastISel * createFastISel(FunctionLoweringInfo &funcInfo, const TargetLibraryInfo *libInfo, const LibcallLoweringInfo *libcallLowering)
Not(const Pred &P) -> Not< Pred >
@ SingleThread
Synchronized with respect to signal handlers executing in the same thread.
Definition LLVMContext.h:55
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:58
initializer< Ty > init(const Ty &Val)
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
@ Implicit
Not emitted register (e.g. carry, or temporary result).
@ Dead
Unused definition.
@ Kill
The last use of a register.
@ Undef
Value of the register doesn't matter.
@ EarlyClobber
Register definition happens before uses.
@ Define
Register definition.
constexpr RegState getKillRegState(bool B)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
bool CCAssignFn(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
CCAssignFn - This function assigns a location for Val, updating State to reflect the change.
@ Store
The extracted value is stored (ExtractElement only).
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
constexpr bool isShiftedMask_64(uint64_t Value)
Return true if the argument contains a non-empty sequence of ones with the remainder zero (64 bit ver...
Definition MathExtras.h:274
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
@ Other
Any other memory.
Definition ModRef.h:68
@ AfterLegalizeDAG
Definition DAGCombine.h:19
const MipsTargetLowering * createMips16TargetLowering(const MipsTargetMachine &TM, const MipsSubtarget &STI)
Create MipsTargetLowering objects.
@ Or
Bitwise or logical OR of integers.
@ Add
Sum of integers.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
const MipsTargetLowering * createMipsSETargetLowering(const MipsTargetMachine &TM, const MipsSubtarget &STI)
LLVM_ABI bool getAsUnsignedInteger(StringRef Str, unsigned Radix, unsigned long long &Result)
Helper functions for StringRef::getAsInteger.
constexpr T maskTrailingOnes(unsigned N)
Create a bitmask with the N right-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:78
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77
Extended Value Type.
Definition ValueTypes.h:35
EVT changeVectorElementTypeToInteger() const
Return a vector with the same number of elements as this vector, but with the element type converted ...
Definition ValueTypes.h:90
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:323
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:396
bool isPow2VectorType() const
Returns true if the given vector is a power of 2.
Definition ValueTypes.h:501
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:339
static EVT getFloatingPointVT(unsigned BitWidth)
Returns the EVT that represents a floating-point type with the given number of bits.
Definition ValueTypes.h:55
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:176
LLVM_ABI Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
bool isRound() const
Return true if the size is a power-of-two number of bytes.
Definition ValueTypes.h:271
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:351
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:359
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:160
Align getNonZeroOrigAlign() const
SmallVector< ArgRegPair, 1 > ArgRegPairs
Vector of call argument and its forwarding register.
This class contains a discriminated union of information about pointers in memory operands,...
static LLVM_ABI MachinePointerInfo getGOT(MachineFunction &MF)
Return a MachinePointerInfo record that refers to a GOT entry.
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:106
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
This structure contains all information that is necessary for lowering calls.
SmallVector< ISD::InputArg, 32 > Ins
SmallVector< ISD::OutputArg, 32 > Outs