1 //=- LoongArchISelDAGToDAG.cpp - A dag to dag inst selector for LoongArch -===//
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 an instruction selector for the LoongArch target.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "LoongArchISelDAGToDAG.h"
14 #include "MCTargetDesc/LoongArchMCTargetDesc.h"
15 #include "MCTargetDesc/LoongArchMatInt.h"
16 
17 using namespace llvm;
18 
19 #define DEBUG_TYPE "loongarch-isel"
20 
21 void LoongArchDAGToDAGISel::Select(SDNode *Node) {
22   // If we have a custom node, we have already selected.
23   if (Node->isMachineOpcode()) {
24     LLVM_DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << "\n");
25     Node->setNodeId(-1);
26     return;
27   }
28 
29   // Instruction Selection not handled by the auto-generated tablegen selection
30   // should be handled here.
31   unsigned Opcode = Node->getOpcode();
32   MVT GRLenVT = Subtarget->getGRLenVT();
33   SDLoc DL(Node);
34 
35   switch (Opcode) {
36   default:
37     break;
38   case ISD::Constant: {
39     int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();
40     SDNode *Result = nullptr;
41     SDValue SrcReg = CurDAG->getRegister(LoongArch::R0, GRLenVT);
42 
43     // The instructions in the sequence are handled here.
44     for (LoongArchMatInt::Inst &Inst : LoongArchMatInt::generateInstSeq(Imm)) {
45       SDValue SDImm = CurDAG->getTargetConstant(Inst.Imm, DL, GRLenVT);
46       if (Inst.Opc == LoongArch::LU12I_W)
47         Result = CurDAG->getMachineNode(LoongArch::LU12I_W, DL, GRLenVT, SDImm);
48       else
49         Result = CurDAG->getMachineNode(Inst.Opc, DL, GRLenVT, SrcReg, SDImm);
50       SrcReg = SDValue(Result, 0);
51     }
52 
53     ReplaceNode(Node, Result);
54     return;
55   }
56     // TODO: Add selection nodes needed later.
57   }
58 
59   // Select the default instruction.
60   SelectCode(Node);
61 }
62 // This pass converts a legalized DAG into a LoongArch-specific DAG, ready
63 // for instruction scheduling.
64 FunctionPass *llvm::createLoongArchISelDag(LoongArchTargetMachine &TM) {
65   return new LoongArchDAGToDAGISel(TM);
66 }
67