xref: /freebsd/contrib/llvm-project/llvm/lib/Target/MSP430/MSP430ISelDAGToDAG.cpp (revision d30a1689f5b37e78ea189232a8b94a7011dc0dc8)
1 //===-- MSP430ISelDAGToDAG.cpp - A dag to dag inst selector for MSP430 ----===//
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 MSP430 target.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "MSP430.h"
14 #include "MSP430TargetMachine.h"
15 #include "llvm/CodeGen/MachineFrameInfo.h"
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/CodeGen/MachineInstrBuilder.h"
18 #include "llvm/CodeGen/MachineRegisterInfo.h"
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/CodeGen/SelectionDAGISel.h"
21 #include "llvm/CodeGen/TargetLowering.h"
22 #include "llvm/Config/llvm-config.h"
23 #include "llvm/IR/CallingConv.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/Intrinsics.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/raw_ostream.h"
31 using namespace llvm;
32 
33 #define DEBUG_TYPE "msp430-isel"
34 
35 namespace {
36   struct MSP430ISelAddressMode {
37     enum {
38       RegBase,
39       FrameIndexBase
40     } BaseType = RegBase;
41 
42     struct {            // This is really a union, discriminated by BaseType!
43       SDValue Reg;
44       int FrameIndex = 0;
45     } Base;
46 
47     int16_t Disp = 0;
48     const GlobalValue *GV = nullptr;
49     const Constant *CP = nullptr;
50     const BlockAddress *BlockAddr = nullptr;
51     const char *ES = nullptr;
52     int JT = -1;
53     Align Alignment; // CP alignment.
54 
55     MSP430ISelAddressMode() = default;
56 
57     bool hasSymbolicDisplacement() const {
58       return GV != nullptr || CP != nullptr || ES != nullptr || JT != -1;
59     }
60 
61 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
62     LLVM_DUMP_METHOD void dump() {
63       errs() << "MSP430ISelAddressMode " << this << '\n';
64       if (BaseType == RegBase && Base.Reg.getNode() != nullptr) {
65         errs() << "Base.Reg ";
66         Base.Reg.getNode()->dump();
67       } else if (BaseType == FrameIndexBase) {
68         errs() << " Base.FrameIndex " << Base.FrameIndex << '\n';
69       }
70       errs() << " Disp " << Disp << '\n';
71       if (GV) {
72         errs() << "GV ";
73         GV->dump();
74       } else if (CP) {
75         errs() << " CP ";
76         CP->dump();
77         errs() << " Align" << Alignment.value() << '\n';
78       } else if (ES) {
79         errs() << "ES ";
80         errs() << ES << '\n';
81       } else if (JT != -1)
82         errs() << " JT" << JT << " Align" << Alignment.value() << '\n';
83     }
84 #endif
85   };
86 }
87 
88 /// MSP430DAGToDAGISel - MSP430 specific code to select MSP430 machine
89 /// instructions for SelectionDAG operations.
90 ///
91 namespace {
92   class MSP430DAGToDAGISel : public SelectionDAGISel {
93   public:
94     MSP430DAGToDAGISel(MSP430TargetMachine &TM, CodeGenOpt::Level OptLevel)
95         : SelectionDAGISel(TM, OptLevel) {}
96 
97   private:
98     StringRef getPassName() const override {
99       return "MSP430 DAG->DAG Pattern Instruction Selection";
100     }
101 
102     bool MatchAddress(SDValue N, MSP430ISelAddressMode &AM);
103     bool MatchWrapper(SDValue N, MSP430ISelAddressMode &AM);
104     bool MatchAddressBase(SDValue N, MSP430ISelAddressMode &AM);
105 
106     bool SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
107                                       std::vector<SDValue> &OutOps) override;
108 
109     // Include the pieces autogenerated from the target description.
110   #include "MSP430GenDAGISel.inc"
111 
112     // Main method to transform nodes into machine nodes.
113     void Select(SDNode *N) override;
114 
115     bool tryIndexedLoad(SDNode *Op);
116     bool tryIndexedBinOp(SDNode *Op, SDValue N1, SDValue N2, unsigned Opc8,
117                          unsigned Opc16);
118 
119     bool SelectAddr(SDValue Addr, SDValue &Base, SDValue &Disp);
120   };
121 }  // end anonymous namespace
122 
123 /// createMSP430ISelDag - This pass converts a legalized DAG into a
124 /// MSP430-specific DAG, ready for instruction scheduling.
125 ///
126 FunctionPass *llvm::createMSP430ISelDag(MSP430TargetMachine &TM,
127                                         CodeGenOpt::Level OptLevel) {
128   return new MSP430DAGToDAGISel(TM, OptLevel);
129 }
130 
131 
132 /// MatchWrapper - Try to match MSP430ISD::Wrapper node into an addressing mode.
133 /// These wrap things that will resolve down into a symbol reference.  If no
134 /// match is possible, this returns true, otherwise it returns false.
135 bool MSP430DAGToDAGISel::MatchWrapper(SDValue N, MSP430ISelAddressMode &AM) {
136   // If the addressing mode already has a symbol as the displacement, we can
137   // never match another symbol.
138   if (AM.hasSymbolicDisplacement())
139     return true;
140 
141   SDValue N0 = N.getOperand(0);
142 
143   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
144     AM.GV = G->getGlobal();
145     AM.Disp += G->getOffset();
146     //AM.SymbolFlags = G->getTargetFlags();
147   } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
148     AM.CP = CP->getConstVal();
149     AM.Alignment = CP->getAlign();
150     AM.Disp += CP->getOffset();
151     //AM.SymbolFlags = CP->getTargetFlags();
152   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
153     AM.ES = S->getSymbol();
154     //AM.SymbolFlags = S->getTargetFlags();
155   } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
156     AM.JT = J->getIndex();
157     //AM.SymbolFlags = J->getTargetFlags();
158   } else {
159     AM.BlockAddr = cast<BlockAddressSDNode>(N0)->getBlockAddress();
160     //AM.SymbolFlags = cast<BlockAddressSDNode>(N0)->getTargetFlags();
161   }
162   return false;
163 }
164 
165 /// MatchAddressBase - Helper for MatchAddress. Add the specified node to the
166 /// specified addressing mode without any further recursion.
167 bool MSP430DAGToDAGISel::MatchAddressBase(SDValue N, MSP430ISelAddressMode &AM) {
168   // Is the base register already occupied?
169   if (AM.BaseType != MSP430ISelAddressMode::RegBase || AM.Base.Reg.getNode()) {
170     // If so, we cannot select it.
171     return true;
172   }
173 
174   // Default, generate it as a register.
175   AM.BaseType = MSP430ISelAddressMode::RegBase;
176   AM.Base.Reg = N;
177   return false;
178 }
179 
180 bool MSP430DAGToDAGISel::MatchAddress(SDValue N, MSP430ISelAddressMode &AM) {
181   LLVM_DEBUG(errs() << "MatchAddress: "; AM.dump());
182 
183   switch (N.getOpcode()) {
184   default: break;
185   case ISD::Constant: {
186     uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
187     AM.Disp += Val;
188     return false;
189   }
190 
191   case MSP430ISD::Wrapper:
192     if (!MatchWrapper(N, AM))
193       return false;
194     break;
195 
196   case ISD::FrameIndex:
197     if (AM.BaseType == MSP430ISelAddressMode::RegBase
198         && AM.Base.Reg.getNode() == nullptr) {
199       AM.BaseType = MSP430ISelAddressMode::FrameIndexBase;
200       AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
201       return false;
202     }
203     break;
204 
205   case ISD::ADD: {
206     MSP430ISelAddressMode Backup = AM;
207     if (!MatchAddress(N.getNode()->getOperand(0), AM) &&
208         !MatchAddress(N.getNode()->getOperand(1), AM))
209       return false;
210     AM = Backup;
211     if (!MatchAddress(N.getNode()->getOperand(1), AM) &&
212         !MatchAddress(N.getNode()->getOperand(0), AM))
213       return false;
214     AM = Backup;
215 
216     break;
217   }
218 
219   case ISD::OR:
220     // Handle "X | C" as "X + C" iff X is known to have C bits clear.
221     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
222       MSP430ISelAddressMode Backup = AM;
223       uint64_t Offset = CN->getSExtValue();
224       // Start with the LHS as an addr mode.
225       if (!MatchAddress(N.getOperand(0), AM) &&
226           // Address could not have picked a GV address for the displacement.
227           AM.GV == nullptr &&
228           // Check to see if the LHS & C is zero.
229           CurDAG->MaskedValueIsZero(N.getOperand(0), CN->getAPIntValue())) {
230         AM.Disp += Offset;
231         return false;
232       }
233       AM = Backup;
234     }
235     break;
236   }
237 
238   return MatchAddressBase(N, AM);
239 }
240 
241 /// SelectAddr - returns true if it is able pattern match an addressing mode.
242 /// It returns the operands which make up the maximal addressing mode it can
243 /// match by reference.
244 bool MSP430DAGToDAGISel::SelectAddr(SDValue N,
245                                     SDValue &Base, SDValue &Disp) {
246   MSP430ISelAddressMode AM;
247 
248   if (MatchAddress(N, AM))
249     return false;
250 
251   if (AM.BaseType == MSP430ISelAddressMode::RegBase)
252     if (!AM.Base.Reg.getNode())
253       AM.Base.Reg = CurDAG->getRegister(MSP430::SR, MVT::i16);
254 
255   Base = (AM.BaseType == MSP430ISelAddressMode::FrameIndexBase)
256              ? CurDAG->getTargetFrameIndex(
257                    AM.Base.FrameIndex,
258                    getTargetLowering()->getPointerTy(CurDAG->getDataLayout()))
259              : AM.Base.Reg;
260 
261   if (AM.GV)
262     Disp = CurDAG->getTargetGlobalAddress(AM.GV, SDLoc(N),
263                                           MVT::i16, AM.Disp,
264                                           0/*AM.SymbolFlags*/);
265   else if (AM.CP)
266     Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i16, AM.Alignment, AM.Disp,
267                                          0 /*AM.SymbolFlags*/);
268   else if (AM.ES)
269     Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i16, 0/*AM.SymbolFlags*/);
270   else if (AM.JT != -1)
271     Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i16, 0/*AM.SymbolFlags*/);
272   else if (AM.BlockAddr)
273     Disp = CurDAG->getTargetBlockAddress(AM.BlockAddr, MVT::i32, 0,
274                                          0/*AM.SymbolFlags*/);
275   else
276     Disp = CurDAG->getTargetConstant(AM.Disp, SDLoc(N), MVT::i16);
277 
278   return true;
279 }
280 
281 bool MSP430DAGToDAGISel::
282 SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
283                              std::vector<SDValue> &OutOps) {
284   SDValue Op0, Op1;
285   switch (ConstraintID) {
286   default: return true;
287   case InlineAsm::Constraint_m: // memory
288     if (!SelectAddr(Op, Op0, Op1))
289       return true;
290     break;
291   }
292 
293   OutOps.push_back(Op0);
294   OutOps.push_back(Op1);
295   return false;
296 }
297 
298 static bool isValidIndexedLoad(const LoadSDNode *LD) {
299   ISD::MemIndexedMode AM = LD->getAddressingMode();
300   if (AM != ISD::POST_INC || LD->getExtensionType() != ISD::NON_EXTLOAD)
301     return false;
302 
303   EVT VT = LD->getMemoryVT();
304 
305   switch (VT.getSimpleVT().SimpleTy) {
306   case MVT::i8:
307     if (cast<ConstantSDNode>(LD->getOffset())->getZExtValue() != 1)
308       return false;
309 
310     break;
311   case MVT::i16:
312     if (cast<ConstantSDNode>(LD->getOffset())->getZExtValue() != 2)
313       return false;
314 
315     break;
316   default:
317     return false;
318   }
319 
320   return true;
321 }
322 
323 bool MSP430DAGToDAGISel::tryIndexedLoad(SDNode *N) {
324   LoadSDNode *LD = cast<LoadSDNode>(N);
325   if (!isValidIndexedLoad(LD))
326     return false;
327 
328   MVT VT = LD->getMemoryVT().getSimpleVT();
329 
330   unsigned Opcode = 0;
331   switch (VT.SimpleTy) {
332   case MVT::i8:
333     Opcode = MSP430::MOV8rp;
334     break;
335   case MVT::i16:
336     Opcode = MSP430::MOV16rp;
337     break;
338   default:
339     return false;
340   }
341 
342   ReplaceNode(N,
343               CurDAG->getMachineNode(Opcode, SDLoc(N), VT, MVT::i16, MVT::Other,
344                                      LD->getBasePtr(), LD->getChain()));
345   return true;
346 }
347 
348 bool MSP430DAGToDAGISel::tryIndexedBinOp(SDNode *Op, SDValue N1, SDValue N2,
349                                          unsigned Opc8, unsigned Opc16) {
350   if (N1.getOpcode() == ISD::LOAD &&
351       N1.hasOneUse() &&
352       IsLegalToFold(N1, Op, Op, OptLevel)) {
353     LoadSDNode *LD = cast<LoadSDNode>(N1);
354     if (!isValidIndexedLoad(LD))
355       return false;
356 
357     MVT VT = LD->getMemoryVT().getSimpleVT();
358     unsigned Opc = (VT == MVT::i16 ? Opc16 : Opc8);
359     MachineMemOperand *MemRef = cast<MemSDNode>(N1)->getMemOperand();
360     SDValue Ops0[] = { N2, LD->getBasePtr(), LD->getChain() };
361     SDNode *ResNode =
362       CurDAG->SelectNodeTo(Op, Opc, VT, MVT::i16, MVT::Other, Ops0);
363     CurDAG->setNodeMemRefs(cast<MachineSDNode>(ResNode), {MemRef});
364     // Transfer chain.
365     ReplaceUses(SDValue(N1.getNode(), 2), SDValue(ResNode, 2));
366     // Transfer writeback.
367     ReplaceUses(SDValue(N1.getNode(), 1), SDValue(ResNode, 1));
368     return true;
369   }
370 
371   return false;
372 }
373 
374 
375 void MSP430DAGToDAGISel::Select(SDNode *Node) {
376   SDLoc dl(Node);
377 
378   // If we have a custom node, we already have selected!
379   if (Node->isMachineOpcode()) {
380     LLVM_DEBUG(errs() << "== "; Node->dump(CurDAG); errs() << "\n");
381     Node->setNodeId(-1);
382     return;
383   }
384 
385   // Few custom selection stuff.
386   switch (Node->getOpcode()) {
387   default: break;
388   case ISD::FrameIndex: {
389     assert(Node->getValueType(0) == MVT::i16);
390     int FI = cast<FrameIndexSDNode>(Node)->getIndex();
391     SDValue TFI = CurDAG->getTargetFrameIndex(FI, MVT::i16);
392     if (Node->hasOneUse()) {
393       CurDAG->SelectNodeTo(Node, MSP430::ADDframe, MVT::i16, TFI,
394                            CurDAG->getTargetConstant(0, dl, MVT::i16));
395       return;
396     }
397     ReplaceNode(Node, CurDAG->getMachineNode(
398                           MSP430::ADDframe, dl, MVT::i16, TFI,
399                           CurDAG->getTargetConstant(0, dl, MVT::i16)));
400     return;
401   }
402   case ISD::LOAD:
403     if (tryIndexedLoad(Node))
404       return;
405     // Other cases are autogenerated.
406     break;
407   case ISD::ADD:
408     if (tryIndexedBinOp(Node, Node->getOperand(0), Node->getOperand(1),
409                         MSP430::ADD8rp, MSP430::ADD16rp))
410       return;
411     else if (tryIndexedBinOp(Node, Node->getOperand(1), Node->getOperand(0),
412                              MSP430::ADD8rp, MSP430::ADD16rp))
413       return;
414 
415     // Other cases are autogenerated.
416     break;
417   case ISD::SUB:
418     if (tryIndexedBinOp(Node, Node->getOperand(0), Node->getOperand(1),
419                         MSP430::SUB8rp, MSP430::SUB16rp))
420       return;
421 
422     // Other cases are autogenerated.
423     break;
424   case ISD::AND:
425     if (tryIndexedBinOp(Node, Node->getOperand(0), Node->getOperand(1),
426                         MSP430::AND8rp, MSP430::AND16rp))
427       return;
428     else if (tryIndexedBinOp(Node, Node->getOperand(1), Node->getOperand(0),
429                              MSP430::AND8rp, MSP430::AND16rp))
430       return;
431 
432     // Other cases are autogenerated.
433     break;
434   case ISD::OR:
435     if (tryIndexedBinOp(Node, Node->getOperand(0), Node->getOperand(1),
436                         MSP430::BIS8rp, MSP430::BIS16rp))
437       return;
438     else if (tryIndexedBinOp(Node, Node->getOperand(1), Node->getOperand(0),
439                              MSP430::BIS8rp, MSP430::BIS16rp))
440       return;
441 
442     // Other cases are autogenerated.
443     break;
444   case ISD::XOR:
445     if (tryIndexedBinOp(Node, Node->getOperand(0), Node->getOperand(1),
446                         MSP430::XOR8rp, MSP430::XOR16rp))
447       return;
448     else if (tryIndexedBinOp(Node, Node->getOperand(1), Node->getOperand(0),
449                              MSP430::XOR8rp, MSP430::XOR16rp))
450       return;
451 
452     // Other cases are autogenerated.
453     break;
454   }
455 
456   // Select the default instruction
457   SelectCode(Node);
458 }
459