1 //===-- SparcISelDAGToDAG.cpp - A dag to dag inst selector for Sparc ------===//
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 SPARC target.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "SparcTargetMachine.h"
14 #include "llvm/CodeGen/MachineRegisterInfo.h"
15 #include "llvm/CodeGen/SelectionDAGISel.h"
16 #include "llvm/IR/Intrinsics.h"
17 #include "llvm/Support/Debug.h"
18 #include "llvm/Support/ErrorHandling.h"
19 #include "llvm/Support/raw_ostream.h"
20 using namespace llvm;
21 
22 //===----------------------------------------------------------------------===//
23 // Instruction Selector Implementation
24 //===----------------------------------------------------------------------===//
25 
26 //===--------------------------------------------------------------------===//
27 /// SparcDAGToDAGISel - SPARC specific code to select SPARC machine
28 /// instructions for SelectionDAG operations.
29 ///
30 namespace {
31 class SparcDAGToDAGISel : public SelectionDAGISel {
32   /// Subtarget - Keep a pointer to the Sparc Subtarget around so that we can
33   /// make the right decision when generating code for different targets.
34   const SparcSubtarget *Subtarget = nullptr;
35 public:
36   explicit SparcDAGToDAGISel(SparcTargetMachine &tm) : SelectionDAGISel(tm) {}
37 
38   bool runOnMachineFunction(MachineFunction &MF) override {
39     Subtarget = &MF.getSubtarget<SparcSubtarget>();
40     return SelectionDAGISel::runOnMachineFunction(MF);
41   }
42 
43   void Select(SDNode *N) override;
44 
45   // Complex Pattern Selectors.
46   bool SelectADDRrr(SDValue N, SDValue &R1, SDValue &R2);
47   bool SelectADDRri(SDValue N, SDValue &Base, SDValue &Offset);
48 
49   /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
50   /// inline asm expressions.
51   bool SelectInlineAsmMemoryOperand(const SDValue &Op,
52                                     unsigned ConstraintID,
53                                     std::vector<SDValue> &OutOps) override;
54 
55   StringRef getPassName() const override {
56     return "SPARC DAG->DAG Pattern Instruction Selection";
57   }
58 
59   // Include the pieces autogenerated from the target description.
60 #include "SparcGenDAGISel.inc"
61 
62 private:
63   SDNode* getGlobalBaseReg();
64   bool tryInlineAsm(SDNode *N);
65 };
66 }  // end anonymous namespace
67 
68 SDNode* SparcDAGToDAGISel::getGlobalBaseReg() {
69   Register GlobalBaseReg = Subtarget->getInstrInfo()->getGlobalBaseReg(MF);
70   return CurDAG->getRegister(GlobalBaseReg,
71                              TLI->getPointerTy(CurDAG->getDataLayout()))
72       .getNode();
73 }
74 
75 bool SparcDAGToDAGISel::SelectADDRri(SDValue Addr,
76                                      SDValue &Base, SDValue &Offset) {
77   if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
78     Base = CurDAG->getTargetFrameIndex(
79         FIN->getIndex(), TLI->getPointerTy(CurDAG->getDataLayout()));
80     Offset = CurDAG->getTargetConstant(0, SDLoc(Addr), MVT::i32);
81     return true;
82   }
83   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
84       Addr.getOpcode() == ISD::TargetGlobalAddress ||
85       Addr.getOpcode() == ISD::TargetGlobalTLSAddress)
86     return false;  // direct calls.
87 
88   if (Addr.getOpcode() == ISD::ADD) {
89     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1))) {
90       if (isInt<13>(CN->getSExtValue())) {
91         if (FrameIndexSDNode *FIN =
92                 dyn_cast<FrameIndexSDNode>(Addr.getOperand(0))) {
93           // Constant offset from frame ref.
94           Base = CurDAG->getTargetFrameIndex(
95               FIN->getIndex(), TLI->getPointerTy(CurDAG->getDataLayout()));
96         } else {
97           Base = Addr.getOperand(0);
98         }
99         Offset = CurDAG->getTargetConstant(CN->getZExtValue(), SDLoc(Addr),
100                                            MVT::i32);
101         return true;
102       }
103     }
104     if (Addr.getOperand(0).getOpcode() == SPISD::Lo) {
105       Base = Addr.getOperand(1);
106       Offset = Addr.getOperand(0).getOperand(0);
107       return true;
108     }
109     if (Addr.getOperand(1).getOpcode() == SPISD::Lo) {
110       Base = Addr.getOperand(0);
111       Offset = Addr.getOperand(1).getOperand(0);
112       return true;
113     }
114   }
115   Base = Addr;
116   Offset = CurDAG->getTargetConstant(0, SDLoc(Addr), MVT::i32);
117   return true;
118 }
119 
120 bool SparcDAGToDAGISel::SelectADDRrr(SDValue Addr, SDValue &R1, SDValue &R2) {
121   if (Addr.getOpcode() == ISD::FrameIndex) return false;
122   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
123       Addr.getOpcode() == ISD::TargetGlobalAddress ||
124       Addr.getOpcode() == ISD::TargetGlobalTLSAddress)
125     return false;  // direct calls.
126 
127   if (Addr.getOpcode() == ISD::ADD) {
128     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))
129       if (isInt<13>(CN->getSExtValue()))
130         return false;  // Let the reg+imm pattern catch this!
131     if (Addr.getOperand(0).getOpcode() == SPISD::Lo ||
132         Addr.getOperand(1).getOpcode() == SPISD::Lo)
133       return false;  // Let the reg+imm pattern catch this!
134     R1 = Addr.getOperand(0);
135     R2 = Addr.getOperand(1);
136     return true;
137   }
138 
139   R1 = Addr;
140   R2 = CurDAG->getRegister(SP::G0, TLI->getPointerTy(CurDAG->getDataLayout()));
141   return true;
142 }
143 
144 
145 // Re-assemble i64 arguments split up in SelectionDAGBuilder's
146 // visitInlineAsm / GetRegistersForValue functions.
147 //
148 // Note: This function was copied from, and is essentially identical
149 // to ARMISelDAGToDAG::SelectInlineAsm. It is very unfortunate that
150 // such hacking-up is necessary; a rethink of how inline asm operands
151 // are handled may be in order to make doing this more sane.
152 //
153 // TODO: fix inline asm support so I can simply tell it that 'i64'
154 // inputs to asm need to be allocated to the IntPair register type,
155 // and have that work. Then, delete this function.
156 bool SparcDAGToDAGISel::tryInlineAsm(SDNode *N){
157   std::vector<SDValue> AsmNodeOperands;
158   unsigned Flag, Kind;
159   bool Changed = false;
160   unsigned NumOps = N->getNumOperands();
161 
162   // Normally, i64 data is bounded to two arbitrary GPRs for "%r"
163   // constraint.  However, some instructions (e.g. ldd/std) require
164   // (even/even+1) GPRs.
165 
166   // So, here, we check for this case, and mutate the inlineasm to use
167   // a single IntPair register instead, which guarantees such even/odd
168   // placement.
169 
170   SDLoc dl(N);
171   SDValue Glue = N->getGluedNode() ? N->getOperand(NumOps - 1) : SDValue();
172 
173   SmallVector<bool, 8> OpChanged;
174   // Glue node will be appended late.
175   for(unsigned i = 0, e = N->getGluedNode() ? NumOps - 1 : NumOps; i < e; ++i) {
176     SDValue op = N->getOperand(i);
177     AsmNodeOperands.push_back(op);
178 
179     if (i < InlineAsm::Op_FirstOperand)
180       continue;
181 
182     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(i))) {
183       Flag = C->getZExtValue();
184       Kind = InlineAsm::getKind(Flag);
185     }
186     else
187       continue;
188 
189     // Immediate operands to inline asm in the SelectionDAG are modeled with
190     // two operands. The first is a constant of value InlineAsm::Kind_Imm, and
191     // the second is a constant with the value of the immediate. If we get here
192     // and we have a Kind_Imm, skip the next operand, and continue.
193     if (Kind == InlineAsm::Kind_Imm) {
194       SDValue op = N->getOperand(++i);
195       AsmNodeOperands.push_back(op);
196       continue;
197     }
198 
199     unsigned NumRegs = InlineAsm::getNumOperandRegisters(Flag);
200     if (NumRegs)
201       OpChanged.push_back(false);
202 
203     unsigned DefIdx = 0;
204     bool IsTiedToChangedOp = false;
205     // If it's a use that is tied with a previous def, it has no
206     // reg class constraint.
207     if (Changed && InlineAsm::isUseOperandTiedToDef(Flag, DefIdx))
208       IsTiedToChangedOp = OpChanged[DefIdx];
209 
210     if (Kind != InlineAsm::Kind_RegUse && Kind != InlineAsm::Kind_RegDef
211         && Kind != InlineAsm::Kind_RegDefEarlyClobber)
212       continue;
213 
214     unsigned RC;
215     bool HasRC = InlineAsm::hasRegClassConstraint(Flag, RC);
216     if ((!IsTiedToChangedOp && (!HasRC || RC != SP::IntRegsRegClassID))
217         || NumRegs != 2)
218       continue;
219 
220     assert((i+2 < NumOps) && "Invalid number of operands in inline asm");
221     SDValue V0 = N->getOperand(i+1);
222     SDValue V1 = N->getOperand(i+2);
223     Register Reg0 = cast<RegisterSDNode>(V0)->getReg();
224     Register Reg1 = cast<RegisterSDNode>(V1)->getReg();
225     SDValue PairedReg;
226     MachineRegisterInfo &MRI = MF->getRegInfo();
227 
228     if (Kind == InlineAsm::Kind_RegDef ||
229         Kind == InlineAsm::Kind_RegDefEarlyClobber) {
230       // Replace the two GPRs with 1 GPRPair and copy values from GPRPair to
231       // the original GPRs.
232 
233       Register GPVR = MRI.createVirtualRegister(&SP::IntPairRegClass);
234       PairedReg = CurDAG->getRegister(GPVR, MVT::v2i32);
235       SDValue Chain = SDValue(N,0);
236 
237       SDNode *GU = N->getGluedUser();
238       SDValue RegCopy = CurDAG->getCopyFromReg(Chain, dl, GPVR, MVT::v2i32,
239                                                Chain.getValue(1));
240 
241       // Extract values from a GPRPair reg and copy to the original GPR reg.
242       SDValue Sub0 = CurDAG->getTargetExtractSubreg(SP::sub_even, dl, MVT::i32,
243                                                     RegCopy);
244       SDValue Sub1 = CurDAG->getTargetExtractSubreg(SP::sub_odd, dl, MVT::i32,
245                                                     RegCopy);
246       SDValue T0 = CurDAG->getCopyToReg(Sub0, dl, Reg0, Sub0,
247                                         RegCopy.getValue(1));
248       SDValue T1 = CurDAG->getCopyToReg(Sub1, dl, Reg1, Sub1, T0.getValue(1));
249 
250       // Update the original glue user.
251       std::vector<SDValue> Ops(GU->op_begin(), GU->op_end()-1);
252       Ops.push_back(T1.getValue(1));
253       CurDAG->UpdateNodeOperands(GU, Ops);
254     }
255     else {
256       // For Kind  == InlineAsm::Kind_RegUse, we first copy two GPRs into a
257       // GPRPair and then pass the GPRPair to the inline asm.
258       SDValue Chain = AsmNodeOperands[InlineAsm::Op_InputChain];
259 
260       // As REG_SEQ doesn't take RegisterSDNode, we copy them first.
261       SDValue T0 = CurDAG->getCopyFromReg(Chain, dl, Reg0, MVT::i32,
262                                           Chain.getValue(1));
263       SDValue T1 = CurDAG->getCopyFromReg(Chain, dl, Reg1, MVT::i32,
264                                           T0.getValue(1));
265       SDValue Pair = SDValue(
266           CurDAG->getMachineNode(
267               TargetOpcode::REG_SEQUENCE, dl, MVT::v2i32,
268               {
269                   CurDAG->getTargetConstant(SP::IntPairRegClassID, dl,
270                                             MVT::i32),
271                   T0,
272                   CurDAG->getTargetConstant(SP::sub_even, dl, MVT::i32),
273                   T1,
274                   CurDAG->getTargetConstant(SP::sub_odd, dl, MVT::i32),
275               }),
276           0);
277 
278       // Copy REG_SEQ into a GPRPair-typed VR and replace the original two
279       // i32 VRs of inline asm with it.
280       Register GPVR = MRI.createVirtualRegister(&SP::IntPairRegClass);
281       PairedReg = CurDAG->getRegister(GPVR, MVT::v2i32);
282       Chain = CurDAG->getCopyToReg(T1, dl, GPVR, Pair, T1.getValue(1));
283 
284       AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
285       Glue = Chain.getValue(1);
286     }
287 
288     Changed = true;
289 
290     if(PairedReg.getNode()) {
291       OpChanged[OpChanged.size() -1 ] = true;
292       Flag = InlineAsm::getFlagWord(Kind, 1 /* RegNum*/);
293       if (IsTiedToChangedOp)
294         Flag = InlineAsm::getFlagWordForMatchingOp(Flag, DefIdx);
295       else
296         Flag = InlineAsm::getFlagWordForRegClass(Flag, SP::IntPairRegClassID);
297       // Replace the current flag.
298       AsmNodeOperands[AsmNodeOperands.size() -1] = CurDAG->getTargetConstant(
299           Flag, dl, MVT::i32);
300       // Add the new register node and skip the original two GPRs.
301       AsmNodeOperands.push_back(PairedReg);
302       // Skip the next two GPRs.
303       i += 2;
304     }
305   }
306 
307   if (Glue.getNode())
308     AsmNodeOperands.push_back(Glue);
309   if (!Changed)
310     return false;
311 
312   SelectInlineAsmMemoryOperands(AsmNodeOperands, SDLoc(N));
313 
314   SDValue New = CurDAG->getNode(N->getOpcode(), SDLoc(N),
315       CurDAG->getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
316   New->setNodeId(-1);
317   ReplaceNode(N, New.getNode());
318   return true;
319 }
320 
321 void SparcDAGToDAGISel::Select(SDNode *N) {
322   SDLoc dl(N);
323   if (N->isMachineOpcode()) {
324     N->setNodeId(-1);
325     return;   // Already selected.
326   }
327 
328   switch (N->getOpcode()) {
329   default: break;
330   case ISD::INLINEASM:
331   case ISD::INLINEASM_BR: {
332     if (tryInlineAsm(N))
333       return;
334     break;
335   }
336   case SPISD::GLOBAL_BASE_REG:
337     ReplaceNode(N, getGlobalBaseReg());
338     return;
339 
340   case ISD::SDIV:
341   case ISD::UDIV: {
342     // sdivx / udivx handle 64-bit divides.
343     if (N->getValueType(0) == MVT::i64)
344       break;
345     // FIXME: should use a custom expander to expose the SRA to the dag.
346     SDValue DivLHS = N->getOperand(0);
347     SDValue DivRHS = N->getOperand(1);
348 
349     // Set the Y register to the high-part.
350     SDValue TopPart;
351     if (N->getOpcode() == ISD::SDIV) {
352       TopPart = SDValue(CurDAG->getMachineNode(SP::SRAri, dl, MVT::i32, DivLHS,
353                                    CurDAG->getTargetConstant(31, dl, MVT::i32)),
354                         0);
355     } else {
356       TopPart = CurDAG->getRegister(SP::G0, MVT::i32);
357     }
358     TopPart = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, SP::Y, TopPart,
359                                    SDValue())
360                   .getValue(1);
361 
362     // FIXME: Handle div by immediate.
363     unsigned Opcode = N->getOpcode() == ISD::SDIV ? SP::SDIVrr : SP::UDIVrr;
364     CurDAG->SelectNodeTo(N, Opcode, MVT::i32, DivLHS, DivRHS, TopPart);
365     return;
366   }
367   }
368 
369   SelectCode(N);
370 }
371 
372 
373 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
374 /// inline asm expressions.
375 bool
376 SparcDAGToDAGISel::SelectInlineAsmMemoryOperand(const SDValue &Op,
377                                                 unsigned ConstraintID,
378                                                 std::vector<SDValue> &OutOps) {
379   SDValue Op0, Op1;
380   switch (ConstraintID) {
381   default: return true;
382   case InlineAsm::Constraint_o:
383   case InlineAsm::Constraint_m: // memory
384    if (!SelectADDRrr(Op, Op0, Op1))
385      SelectADDRri(Op, Op0, Op1);
386    break;
387   }
388 
389   OutOps.push_back(Op0);
390   OutOps.push_back(Op1);
391   return false;
392 }
393 
394 /// createSparcISelDag - This pass converts a legalized DAG into a
395 /// SPARC-specific DAG, ready for instruction scheduling.
396 ///
397 FunctionPass *llvm::createSparcISelDag(SparcTargetMachine &TM) {
398   return new SparcDAGToDAGISel(TM);
399 }
400