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