1 //===-- MSP430ISelLowering.cpp - MSP430 DAG Lowering Implementation  ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the MSP430TargetLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "MSP430ISelLowering.h"
15 #include "MSP430.h"
16 #include "MSP430MachineFunctionInfo.h"
17 #include "MSP430Subtarget.h"
18 #include "MSP430TargetMachine.h"
19 #include "llvm/CodeGen/CallingConvLower.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/SelectionDAGISel.h"
25 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
26 #include "llvm/CodeGen/ValueTypes.h"
27 #include "llvm/IR/CallingConv.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/GlobalAlias.h"
31 #include "llvm/IR/GlobalVariable.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
37 using namespace llvm;
38 
39 #define DEBUG_TYPE "msp430-lower"
40 
41 typedef enum {
42   NoHWMult,
43   HWMultIntr,
44   HWMultNoIntr
45 } HWMultUseMode;
46 
47 static cl::opt<HWMultUseMode>
48 HWMultMode("msp430-hwmult-mode", cl::Hidden,
49            cl::desc("Hardware multiplier use mode"),
50            cl::init(HWMultNoIntr),
51            cl::values(
52              clEnumValN(NoHWMult, "no",
53                 "Do not use hardware multiplier"),
54              clEnumValN(HWMultIntr, "interrupts",
55                 "Assume hardware multiplier can be used inside interrupts"),
56              clEnumValN(HWMultNoIntr, "use",
57                 "Assume hardware multiplier cannot be used inside interrupts")));
58 
59 MSP430TargetLowering::MSP430TargetLowering(const TargetMachine &TM,
60                                            const MSP430Subtarget &STI)
61     : TargetLowering(TM) {
62 
63   // Set up the register classes.
64   addRegisterClass(MVT::i8,  &MSP430::GR8RegClass);
65   addRegisterClass(MVT::i16, &MSP430::GR16RegClass);
66 
67   // Compute derived properties from the register classes
68   computeRegisterProperties(STI.getRegisterInfo());
69 
70   // Provide all sorts of operation actions
71   setStackPointerRegisterToSaveRestore(MSP430::SP);
72   setBooleanContents(ZeroOrOneBooleanContent);
73   setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
74 
75   // We have post-incremented loads / stores.
76   setIndexedLoadAction(ISD::POST_INC, MVT::i8, Legal);
77   setIndexedLoadAction(ISD::POST_INC, MVT::i16, Legal);
78 
79   for (MVT VT : MVT::integer_valuetypes()) {
80     setLoadExtAction(ISD::EXTLOAD,  VT, MVT::i1,  Promote);
81     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1,  Promote);
82     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1,  Promote);
83     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8,  Expand);
84     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i16, Expand);
85   }
86 
87   // We don't have any truncstores
88   setTruncStoreAction(MVT::i16, MVT::i8, Expand);
89 
90   setOperationAction(ISD::SRA,              MVT::i8,    Custom);
91   setOperationAction(ISD::SHL,              MVT::i8,    Custom);
92   setOperationAction(ISD::SRL,              MVT::i8,    Custom);
93   setOperationAction(ISD::SRA,              MVT::i16,   Custom);
94   setOperationAction(ISD::SHL,              MVT::i16,   Custom);
95   setOperationAction(ISD::SRL,              MVT::i16,   Custom);
96   setOperationAction(ISD::ROTL,             MVT::i8,    Expand);
97   setOperationAction(ISD::ROTR,             MVT::i8,    Expand);
98   setOperationAction(ISD::ROTL,             MVT::i16,   Expand);
99   setOperationAction(ISD::ROTR,             MVT::i16,   Expand);
100   setOperationAction(ISD::GlobalAddress,    MVT::i16,   Custom);
101   setOperationAction(ISD::ExternalSymbol,   MVT::i16,   Custom);
102   setOperationAction(ISD::BlockAddress,     MVT::i16,   Custom);
103   setOperationAction(ISD::BR_JT,            MVT::Other, Expand);
104   setOperationAction(ISD::BR_CC,            MVT::i8,    Custom);
105   setOperationAction(ISD::BR_CC,            MVT::i16,   Custom);
106   setOperationAction(ISD::BRCOND,           MVT::Other, Expand);
107   setOperationAction(ISD::SETCC,            MVT::i8,    Custom);
108   setOperationAction(ISD::SETCC,            MVT::i16,   Custom);
109   setOperationAction(ISD::SELECT,           MVT::i8,    Expand);
110   setOperationAction(ISD::SELECT,           MVT::i16,   Expand);
111   setOperationAction(ISD::SELECT_CC,        MVT::i8,    Custom);
112   setOperationAction(ISD::SELECT_CC,        MVT::i16,   Custom);
113   setOperationAction(ISD::SIGN_EXTEND,      MVT::i16,   Custom);
114   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i8, Expand);
115   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i16, Expand);
116 
117   setOperationAction(ISD::CTTZ,             MVT::i8,    Expand);
118   setOperationAction(ISD::CTTZ,             MVT::i16,   Expand);
119   setOperationAction(ISD::CTLZ,             MVT::i8,    Expand);
120   setOperationAction(ISD::CTLZ,             MVT::i16,   Expand);
121   setOperationAction(ISD::CTPOP,            MVT::i8,    Expand);
122   setOperationAction(ISD::CTPOP,            MVT::i16,   Expand);
123 
124   setOperationAction(ISD::SHL_PARTS,        MVT::i8,    Expand);
125   setOperationAction(ISD::SHL_PARTS,        MVT::i16,   Expand);
126   setOperationAction(ISD::SRL_PARTS,        MVT::i8,    Expand);
127   setOperationAction(ISD::SRL_PARTS,        MVT::i16,   Expand);
128   setOperationAction(ISD::SRA_PARTS,        MVT::i8,    Expand);
129   setOperationAction(ISD::SRA_PARTS,        MVT::i16,   Expand);
130 
131   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1,   Expand);
132 
133   // FIXME: Implement efficiently multiplication by a constant
134   setOperationAction(ISD::MUL,              MVT::i8,    Expand);
135   setOperationAction(ISD::MULHS,            MVT::i8,    Expand);
136   setOperationAction(ISD::MULHU,            MVT::i8,    Expand);
137   setOperationAction(ISD::SMUL_LOHI,        MVT::i8,    Expand);
138   setOperationAction(ISD::UMUL_LOHI,        MVT::i8,    Expand);
139   setOperationAction(ISD::MUL,              MVT::i16,   Expand);
140   setOperationAction(ISD::MULHS,            MVT::i16,   Expand);
141   setOperationAction(ISD::MULHU,            MVT::i16,   Expand);
142   setOperationAction(ISD::SMUL_LOHI,        MVT::i16,   Expand);
143   setOperationAction(ISD::UMUL_LOHI,        MVT::i16,   Expand);
144 
145   setOperationAction(ISD::UDIV,             MVT::i8,    Expand);
146   setOperationAction(ISD::UDIVREM,          MVT::i8,    Expand);
147   setOperationAction(ISD::UREM,             MVT::i8,    Expand);
148   setOperationAction(ISD::SDIV,             MVT::i8,    Expand);
149   setOperationAction(ISD::SDIVREM,          MVT::i8,    Expand);
150   setOperationAction(ISD::SREM,             MVT::i8,    Expand);
151   setOperationAction(ISD::UDIV,             MVT::i16,   Expand);
152   setOperationAction(ISD::UDIVREM,          MVT::i16,   Expand);
153   setOperationAction(ISD::UREM,             MVT::i16,   Expand);
154   setOperationAction(ISD::SDIV,             MVT::i16,   Expand);
155   setOperationAction(ISD::SDIVREM,          MVT::i16,   Expand);
156   setOperationAction(ISD::SREM,             MVT::i16,   Expand);
157 
158   // varargs support
159   setOperationAction(ISD::VASTART,          MVT::Other, Custom);
160   setOperationAction(ISD::VAARG,            MVT::Other, Expand);
161   setOperationAction(ISD::VAEND,            MVT::Other, Expand);
162   setOperationAction(ISD::VACOPY,           MVT::Other, Expand);
163   setOperationAction(ISD::JumpTable,        MVT::i16,   Custom);
164 
165   // Libcalls names.
166   if (HWMultMode == HWMultIntr) {
167     setLibcallName(RTLIB::MUL_I8,  "__mulqi3hw");
168     setLibcallName(RTLIB::MUL_I16, "__mulhi3hw");
169   } else if (HWMultMode == HWMultNoIntr) {
170     setLibcallName(RTLIB::MUL_I8,  "__mulqi3hw_noint");
171     setLibcallName(RTLIB::MUL_I16, "__mulhi3hw_noint");
172   }
173 
174   setMinFunctionAlignment(1);
175   setPrefFunctionAlignment(2);
176 }
177 
178 SDValue MSP430TargetLowering::LowerOperation(SDValue Op,
179                                              SelectionDAG &DAG) const {
180   switch (Op.getOpcode()) {
181   case ISD::SHL: // FALLTHROUGH
182   case ISD::SRL:
183   case ISD::SRA:              return LowerShifts(Op, DAG);
184   case ISD::GlobalAddress:    return LowerGlobalAddress(Op, DAG);
185   case ISD::BlockAddress:     return LowerBlockAddress(Op, DAG);
186   case ISD::ExternalSymbol:   return LowerExternalSymbol(Op, DAG);
187   case ISD::SETCC:            return LowerSETCC(Op, DAG);
188   case ISD::BR_CC:            return LowerBR_CC(Op, DAG);
189   case ISD::SELECT_CC:        return LowerSELECT_CC(Op, DAG);
190   case ISD::SIGN_EXTEND:      return LowerSIGN_EXTEND(Op, DAG);
191   case ISD::RETURNADDR:       return LowerRETURNADDR(Op, DAG);
192   case ISD::FRAMEADDR:        return LowerFRAMEADDR(Op, DAG);
193   case ISD::VASTART:          return LowerVASTART(Op, DAG);
194   case ISD::JumpTable:        return LowerJumpTable(Op, DAG);
195   default:
196     llvm_unreachable("unimplemented operand");
197   }
198 }
199 
200 //===----------------------------------------------------------------------===//
201 //                       MSP430 Inline Assembly Support
202 //===----------------------------------------------------------------------===//
203 
204 /// getConstraintType - Given a constraint letter, return the type of
205 /// constraint it is for this target.
206 TargetLowering::ConstraintType
207 MSP430TargetLowering::getConstraintType(StringRef Constraint) const {
208   if (Constraint.size() == 1) {
209     switch (Constraint[0]) {
210     case 'r':
211       return C_RegisterClass;
212     default:
213       break;
214     }
215   }
216   return TargetLowering::getConstraintType(Constraint);
217 }
218 
219 std::pair<unsigned, const TargetRegisterClass *>
220 MSP430TargetLowering::getRegForInlineAsmConstraint(
221     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
222   if (Constraint.size() == 1) {
223     // GCC Constraint Letters
224     switch (Constraint[0]) {
225     default: break;
226     case 'r':   // GENERAL_REGS
227       if (VT == MVT::i8)
228         return std::make_pair(0U, &MSP430::GR8RegClass);
229 
230       return std::make_pair(0U, &MSP430::GR16RegClass);
231     }
232   }
233 
234   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
235 }
236 
237 //===----------------------------------------------------------------------===//
238 //                      Calling Convention Implementation
239 //===----------------------------------------------------------------------===//
240 
241 #include "MSP430GenCallingConv.inc"
242 
243 /// For each argument in a function store the number of pieces it is composed
244 /// of.
245 template<typename ArgT>
246 static void ParseFunctionArgs(const SmallVectorImpl<ArgT> &Args,
247                               SmallVectorImpl<unsigned> &Out) {
248   unsigned CurrentArgIndex;
249 
250   if (Args.empty())
251     return;
252 
253   CurrentArgIndex = Args[0].OrigArgIndex;
254   Out.push_back(0);
255 
256   for (auto &Arg : Args) {
257     if (CurrentArgIndex == Arg.OrigArgIndex) {
258       Out.back() += 1;
259     } else {
260       Out.push_back(1);
261       CurrentArgIndex = Arg.OrigArgIndex;
262     }
263   }
264 }
265 
266 static void AnalyzeVarArgs(CCState &State,
267                            const SmallVectorImpl<ISD::OutputArg> &Outs) {
268   State.AnalyzeCallOperands(Outs, CC_MSP430_AssignStack);
269 }
270 
271 static void AnalyzeVarArgs(CCState &State,
272                            const SmallVectorImpl<ISD::InputArg> &Ins) {
273   State.AnalyzeFormalArguments(Ins, CC_MSP430_AssignStack);
274 }
275 
276 /// Analyze incoming and outgoing function arguments. We need custom C++ code
277 /// to handle special constraints in the ABI like reversing the order of the
278 /// pieces of splitted arguments. In addition, all pieces of a certain argument
279 /// have to be passed either using registers or the stack but never mixing both.
280 template<typename ArgT>
281 static void AnalyzeArguments(CCState &State,
282                              SmallVectorImpl<CCValAssign> &ArgLocs,
283                              const SmallVectorImpl<ArgT> &Args) {
284   static const MCPhysReg RegList[] = {
285     MSP430::R12, MSP430::R13, MSP430::R14, MSP430::R15
286   };
287   static const unsigned NbRegs = array_lengthof(RegList);
288 
289   if (State.isVarArg()) {
290     AnalyzeVarArgs(State, Args);
291     return;
292   }
293 
294   SmallVector<unsigned, 4> ArgsParts;
295   ParseFunctionArgs(Args, ArgsParts);
296 
297   unsigned RegsLeft = NbRegs;
298   bool UsedStack = false;
299   unsigned ValNo = 0;
300 
301   for (unsigned i = 0, e = ArgsParts.size(); i != e; i++) {
302     MVT ArgVT = Args[ValNo].VT;
303     ISD::ArgFlagsTy ArgFlags = Args[ValNo].Flags;
304     MVT LocVT = ArgVT;
305     CCValAssign::LocInfo LocInfo = CCValAssign::Full;
306 
307     // Promote i8 to i16
308     if (LocVT == MVT::i8) {
309       LocVT = MVT::i16;
310       if (ArgFlags.isSExt())
311           LocInfo = CCValAssign::SExt;
312       else if (ArgFlags.isZExt())
313           LocInfo = CCValAssign::ZExt;
314       else
315           LocInfo = CCValAssign::AExt;
316     }
317 
318     // Handle byval arguments
319     if (ArgFlags.isByVal()) {
320       State.HandleByVal(ValNo++, ArgVT, LocVT, LocInfo, 2, 2, ArgFlags);
321       continue;
322     }
323 
324     unsigned Parts = ArgsParts[i];
325 
326     if (!UsedStack && Parts == 2 && RegsLeft == 1) {
327       // Special case for 32-bit register split, see EABI section 3.3.3
328       unsigned Reg = State.AllocateReg(RegList);
329       State.addLoc(CCValAssign::getReg(ValNo++, ArgVT, Reg, LocVT, LocInfo));
330       RegsLeft -= 1;
331 
332       UsedStack = true;
333       CC_MSP430_AssignStack(ValNo++, ArgVT, LocVT, LocInfo, ArgFlags, State);
334     } else if (Parts <= RegsLeft) {
335       for (unsigned j = 0; j < Parts; j++) {
336         unsigned Reg = State.AllocateReg(RegList);
337         State.addLoc(CCValAssign::getReg(ValNo++, ArgVT, Reg, LocVT, LocInfo));
338         RegsLeft--;
339       }
340     } else {
341       UsedStack = true;
342       for (unsigned j = 0; j < Parts; j++)
343         CC_MSP430_AssignStack(ValNo++, ArgVT, LocVT, LocInfo, ArgFlags, State);
344     }
345   }
346 }
347 
348 static void AnalyzeRetResult(CCState &State,
349                              const SmallVectorImpl<ISD::InputArg> &Ins) {
350   State.AnalyzeCallResult(Ins, RetCC_MSP430);
351 }
352 
353 static void AnalyzeRetResult(CCState &State,
354                              const SmallVectorImpl<ISD::OutputArg> &Outs) {
355   State.AnalyzeReturn(Outs, RetCC_MSP430);
356 }
357 
358 template<typename ArgT>
359 static void AnalyzeReturnValues(CCState &State,
360                                 SmallVectorImpl<CCValAssign> &RVLocs,
361                                 const SmallVectorImpl<ArgT> &Args) {
362   AnalyzeRetResult(State, Args);
363 }
364 
365 SDValue MSP430TargetLowering::LowerFormalArguments(
366     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
367     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
368     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
369 
370   switch (CallConv) {
371   default:
372     llvm_unreachable("Unsupported calling convention");
373   case CallingConv::C:
374   case CallingConv::Fast:
375     return LowerCCCArguments(Chain, CallConv, isVarArg, Ins, dl, DAG, InVals);
376   case CallingConv::MSP430_INTR:
377     if (Ins.empty())
378       return Chain;
379     report_fatal_error("ISRs cannot have arguments");
380   }
381 }
382 
383 SDValue
384 MSP430TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
385                                 SmallVectorImpl<SDValue> &InVals) const {
386   SelectionDAG &DAG                     = CLI.DAG;
387   SDLoc &dl                             = CLI.DL;
388   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
389   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
390   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
391   SDValue Chain                         = CLI.Chain;
392   SDValue Callee                        = CLI.Callee;
393   bool &isTailCall                      = CLI.IsTailCall;
394   CallingConv::ID CallConv              = CLI.CallConv;
395   bool isVarArg                         = CLI.IsVarArg;
396 
397   // MSP430 target does not yet support tail call optimization.
398   isTailCall = false;
399 
400   switch (CallConv) {
401   default:
402     llvm_unreachable("Unsupported calling convention");
403   case CallingConv::Fast:
404   case CallingConv::C:
405     return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
406                           Outs, OutVals, Ins, dl, DAG, InVals);
407   case CallingConv::MSP430_INTR:
408     report_fatal_error("ISRs cannot be called directly");
409   }
410 }
411 
412 /// LowerCCCArguments - transform physical registers into virtual registers and
413 /// generate load operations for arguments places on the stack.
414 // FIXME: struct return stuff
415 SDValue MSP430TargetLowering::LowerCCCArguments(
416     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
417     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
418     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
419   MachineFunction &MF = DAG.getMachineFunction();
420   MachineFrameInfo &MFI = MF.getFrameInfo();
421   MachineRegisterInfo &RegInfo = MF.getRegInfo();
422   MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
423 
424   // Assign locations to all of the incoming arguments.
425   SmallVector<CCValAssign, 16> ArgLocs;
426   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
427                  *DAG.getContext());
428   AnalyzeArguments(CCInfo, ArgLocs, Ins);
429 
430   // Create frame index for the start of the first vararg value
431   if (isVarArg) {
432     unsigned Offset = CCInfo.getNextStackOffset();
433     FuncInfo->setVarArgsFrameIndex(MFI.CreateFixedObject(1, Offset, true));
434   }
435 
436   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
437     CCValAssign &VA = ArgLocs[i];
438     if (VA.isRegLoc()) {
439       // Arguments passed in registers
440       EVT RegVT = VA.getLocVT();
441       switch (RegVT.getSimpleVT().SimpleTy) {
442       default:
443         {
444 #ifndef NDEBUG
445           errs() << "LowerFormalArguments Unhandled argument type: "
446                << RegVT.getEVTString() << "\n";
447 #endif
448           llvm_unreachable(nullptr);
449         }
450       case MVT::i16:
451         unsigned VReg = RegInfo.createVirtualRegister(&MSP430::GR16RegClass);
452         RegInfo.addLiveIn(VA.getLocReg(), VReg);
453         SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
454 
455         // If this is an 8-bit value, it is really passed promoted to 16
456         // bits. Insert an assert[sz]ext to capture this, then truncate to the
457         // right size.
458         if (VA.getLocInfo() == CCValAssign::SExt)
459           ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
460                                  DAG.getValueType(VA.getValVT()));
461         else if (VA.getLocInfo() == CCValAssign::ZExt)
462           ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
463                                  DAG.getValueType(VA.getValVT()));
464 
465         if (VA.getLocInfo() != CCValAssign::Full)
466           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
467 
468         InVals.push_back(ArgValue);
469       }
470     } else {
471       // Sanity check
472       assert(VA.isMemLoc());
473 
474       SDValue InVal;
475       ISD::ArgFlagsTy Flags = Ins[i].Flags;
476 
477       if (Flags.isByVal()) {
478         int FI = MFI.CreateFixedObject(Flags.getByValSize(),
479                                        VA.getLocMemOffset(), true);
480         InVal = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
481       } else {
482         // Load the argument to a virtual register
483         unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
484         if (ObjSize > 2) {
485             errs() << "LowerFormalArguments Unhandled argument type: "
486                 << EVT(VA.getLocVT()).getEVTString()
487                 << "\n";
488         }
489         // Create the frame index object for this incoming parameter...
490         int FI = MFI.CreateFixedObject(ObjSize, VA.getLocMemOffset(), true);
491 
492         // Create the SelectionDAG nodes corresponding to a load
493         //from this parameter
494         SDValue FIN = DAG.getFrameIndex(FI, MVT::i16);
495         InVal = DAG.getLoad(
496             VA.getLocVT(), dl, Chain, FIN,
497             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
498       }
499 
500       InVals.push_back(InVal);
501     }
502   }
503 
504   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
505     if (Ins[i].Flags.isSRet()) {
506       unsigned Reg = FuncInfo->getSRetReturnReg();
507       if (!Reg) {
508         Reg = MF.getRegInfo().createVirtualRegister(
509             getRegClassFor(MVT::i16));
510         FuncInfo->setSRetReturnReg(Reg);
511       }
512       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
513       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
514     }
515   }
516 
517   return Chain;
518 }
519 
520 bool
521 MSP430TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
522                                      MachineFunction &MF,
523                                      bool IsVarArg,
524                                      const SmallVectorImpl<ISD::OutputArg> &Outs,
525                                      LLVMContext &Context) const {
526   SmallVector<CCValAssign, 16> RVLocs;
527   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
528   return CCInfo.CheckReturn(Outs, RetCC_MSP430);
529 }
530 
531 SDValue
532 MSP430TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
533                                   bool isVarArg,
534                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
535                                   const SmallVectorImpl<SDValue> &OutVals,
536                                   const SDLoc &dl, SelectionDAG &DAG) const {
537 
538   MachineFunction &MF = DAG.getMachineFunction();
539 
540   // CCValAssign - represent the assignment of the return value to a location
541   SmallVector<CCValAssign, 16> RVLocs;
542 
543   // ISRs cannot return any value.
544   if (CallConv == CallingConv::MSP430_INTR && !Outs.empty())
545     report_fatal_error("ISRs cannot return any value");
546 
547   // CCState - Info about the registers and stack slot.
548   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
549                  *DAG.getContext());
550 
551   // Analize return values.
552   AnalyzeReturnValues(CCInfo, RVLocs, Outs);
553 
554   SDValue Flag;
555   SmallVector<SDValue, 4> RetOps(1, Chain);
556 
557   // Copy the result values into the output registers.
558   for (unsigned i = 0; i != RVLocs.size(); ++i) {
559     CCValAssign &VA = RVLocs[i];
560     assert(VA.isRegLoc() && "Can only return in registers!");
561 
562     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
563                              OutVals[i], Flag);
564 
565     // Guarantee that all emitted copies are stuck together,
566     // avoiding something bad.
567     Flag = Chain.getValue(1);
568     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
569   }
570 
571   if (MF.getFunction()->hasStructRetAttr()) {
572     MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
573     unsigned Reg = FuncInfo->getSRetReturnReg();
574 
575     if (!Reg)
576       llvm_unreachable("sret virtual register not created in entry block");
577 
578     SDValue Val =
579       DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy(DAG.getDataLayout()));
580     unsigned R12 = MSP430::R12;
581 
582     Chain = DAG.getCopyToReg(Chain, dl, R12, Val, Flag);
583     Flag = Chain.getValue(1);
584     RetOps.push_back(DAG.getRegister(R12, getPointerTy(DAG.getDataLayout())));
585   }
586 
587   unsigned Opc = (CallConv == CallingConv::MSP430_INTR ?
588                   MSP430ISD::RETI_FLAG : MSP430ISD::RET_FLAG);
589 
590   RetOps[0] = Chain;  // Update chain.
591 
592   // Add the flag if we have it.
593   if (Flag.getNode())
594     RetOps.push_back(Flag);
595 
596   return DAG.getNode(Opc, dl, MVT::Other, RetOps);
597 }
598 
599 /// LowerCCCCallTo - functions arguments are copied from virtual regs to
600 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
601 // TODO: sret.
602 SDValue MSP430TargetLowering::LowerCCCCallTo(
603     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
604     bool isTailCall, const SmallVectorImpl<ISD::OutputArg> &Outs,
605     const SmallVectorImpl<SDValue> &OutVals,
606     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
607     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
608   // Analyze operands of the call, assigning locations to each operand.
609   SmallVector<CCValAssign, 16> ArgLocs;
610   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
611                  *DAG.getContext());
612   AnalyzeArguments(CCInfo, ArgLocs, Outs);
613 
614   // Get a count of how many bytes are to be pushed on the stack.
615   unsigned NumBytes = CCInfo.getNextStackOffset();
616   auto PtrVT = getPointerTy(DAG.getDataLayout());
617 
618   Chain = DAG.getCALLSEQ_START(Chain,
619                                DAG.getConstant(NumBytes, dl, PtrVT, true), dl);
620 
621   SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
622   SmallVector<SDValue, 12> MemOpChains;
623   SDValue StackPtr;
624 
625   // Walk the register/memloc assignments, inserting copies/loads.
626   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
627     CCValAssign &VA = ArgLocs[i];
628 
629     SDValue Arg = OutVals[i];
630 
631     // Promote the value if needed.
632     switch (VA.getLocInfo()) {
633       default: llvm_unreachable("Unknown loc info!");
634       case CCValAssign::Full: break;
635       case CCValAssign::SExt:
636         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
637         break;
638       case CCValAssign::ZExt:
639         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
640         break;
641       case CCValAssign::AExt:
642         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
643         break;
644     }
645 
646     // Arguments that can be passed on register must be kept at RegsToPass
647     // vector
648     if (VA.isRegLoc()) {
649       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
650     } else {
651       assert(VA.isMemLoc());
652 
653       if (!StackPtr.getNode())
654         StackPtr = DAG.getCopyFromReg(Chain, dl, MSP430::SP, PtrVT);
655 
656       SDValue PtrOff =
657           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
658                       DAG.getIntPtrConstant(VA.getLocMemOffset(), dl));
659 
660       SDValue MemOp;
661       ISD::ArgFlagsTy Flags = Outs[i].Flags;
662 
663       if (Flags.isByVal()) {
664         SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i16);
665         MemOp = DAG.getMemcpy(Chain, dl, PtrOff, Arg, SizeNode,
666                               Flags.getByValAlign(),
667                               /*isVolatile*/false,
668                               /*AlwaysInline=*/true,
669                               /*isTailCall=*/false,
670                               MachinePointerInfo(),
671                               MachinePointerInfo());
672       } else {
673         MemOp = DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
674       }
675 
676       MemOpChains.push_back(MemOp);
677     }
678   }
679 
680   // Transform all store nodes into one single node because all store nodes are
681   // independent of each other.
682   if (!MemOpChains.empty())
683     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
684 
685   // Build a sequence of copy-to-reg nodes chained together with token chain and
686   // flag operands which copy the outgoing args into registers.  The InFlag in
687   // necessary since all emitted instructions must be stuck together.
688   SDValue InFlag;
689   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
690     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
691                              RegsToPass[i].second, InFlag);
692     InFlag = Chain.getValue(1);
693   }
694 
695   // If the callee is a GlobalAddress node (quite common, every direct call is)
696   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
697   // Likewise ExternalSymbol -> TargetExternalSymbol.
698   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
699     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i16);
700   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
701     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i16);
702 
703   // Returns a chain & a flag for retval copy to use.
704   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
705   SmallVector<SDValue, 8> Ops;
706   Ops.push_back(Chain);
707   Ops.push_back(Callee);
708 
709   // Add argument registers to the end of the list so that they are
710   // known live into the call.
711   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
712     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
713                                   RegsToPass[i].second.getValueType()));
714 
715   if (InFlag.getNode())
716     Ops.push_back(InFlag);
717 
718   Chain = DAG.getNode(MSP430ISD::CALL, dl, NodeTys, Ops);
719   InFlag = Chain.getValue(1);
720 
721   // Create the CALLSEQ_END node.
722   Chain = DAG.getCALLSEQ_END(Chain, DAG.getConstant(NumBytes, dl, PtrVT, true),
723                              DAG.getConstant(0, dl, PtrVT, true), InFlag, dl);
724   InFlag = Chain.getValue(1);
725 
726   // Handle result values, copying them out of physregs into vregs that we
727   // return.
728   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl,
729                          DAG, InVals);
730 }
731 
732 /// LowerCallResult - Lower the result values of a call into the
733 /// appropriate copies out of appropriate physical registers.
734 ///
735 SDValue MSP430TargetLowering::LowerCallResult(
736     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
737     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
738     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
739 
740   // Assign locations to each value returned by this call.
741   SmallVector<CCValAssign, 16> RVLocs;
742   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
743                  *DAG.getContext());
744 
745   AnalyzeReturnValues(CCInfo, RVLocs, Ins);
746 
747   // Copy all of the result registers out of their specified physreg.
748   for (unsigned i = 0; i != RVLocs.size(); ++i) {
749     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
750                                RVLocs[i].getValVT(), InFlag).getValue(1);
751     InFlag = Chain.getValue(2);
752     InVals.push_back(Chain.getValue(0));
753   }
754 
755   return Chain;
756 }
757 
758 SDValue MSP430TargetLowering::LowerShifts(SDValue Op,
759                                           SelectionDAG &DAG) const {
760   unsigned Opc = Op.getOpcode();
761   SDNode* N = Op.getNode();
762   EVT VT = Op.getValueType();
763   SDLoc dl(N);
764 
765   // Expand non-constant shifts to loops:
766   if (!isa<ConstantSDNode>(N->getOperand(1)))
767     switch (Opc) {
768     default: llvm_unreachable("Invalid shift opcode!");
769     case ISD::SHL:
770       return DAG.getNode(MSP430ISD::SHL, dl,
771                          VT, N->getOperand(0), N->getOperand(1));
772     case ISD::SRA:
773       return DAG.getNode(MSP430ISD::SRA, dl,
774                          VT, N->getOperand(0), N->getOperand(1));
775     case ISD::SRL:
776       return DAG.getNode(MSP430ISD::SRL, dl,
777                          VT, N->getOperand(0), N->getOperand(1));
778     }
779 
780   uint64_t ShiftAmount = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
781 
782   // Expand the stuff into sequence of shifts.
783   // FIXME: for some shift amounts this might be done better!
784   // E.g.: foo >> (8 + N) => sxt(swpb(foo)) >> N
785   SDValue Victim = N->getOperand(0);
786 
787   if (Opc == ISD::SRL && ShiftAmount) {
788     // Emit a special goodness here:
789     // srl A, 1 => clrc; rrc A
790     Victim = DAG.getNode(MSP430ISD::RRC, dl, VT, Victim);
791     ShiftAmount -= 1;
792   }
793 
794   while (ShiftAmount--)
795     Victim = DAG.getNode((Opc == ISD::SHL ? MSP430ISD::RLA : MSP430ISD::RRA),
796                          dl, VT, Victim);
797 
798   return Victim;
799 }
800 
801 SDValue MSP430TargetLowering::LowerGlobalAddress(SDValue Op,
802                                                  SelectionDAG &DAG) const {
803   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
804   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
805   auto PtrVT = getPointerTy(DAG.getDataLayout());
806 
807   // Create the TargetGlobalAddress node, folding in the constant offset.
808   SDValue Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op), PtrVT, Offset);
809   return DAG.getNode(MSP430ISD::Wrapper, SDLoc(Op), PtrVT, Result);
810 }
811 
812 SDValue MSP430TargetLowering::LowerExternalSymbol(SDValue Op,
813                                                   SelectionDAG &DAG) const {
814   SDLoc dl(Op);
815   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
816   auto PtrVT = getPointerTy(DAG.getDataLayout());
817   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT);
818 
819   return DAG.getNode(MSP430ISD::Wrapper, dl, PtrVT, Result);
820 }
821 
822 SDValue MSP430TargetLowering::LowerBlockAddress(SDValue Op,
823                                                 SelectionDAG &DAG) const {
824   SDLoc dl(Op);
825   auto PtrVT = getPointerTy(DAG.getDataLayout());
826   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
827   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT);
828 
829   return DAG.getNode(MSP430ISD::Wrapper, dl, PtrVT, Result);
830 }
831 
832 static SDValue EmitCMP(SDValue &LHS, SDValue &RHS, SDValue &TargetCC,
833                        ISD::CondCode CC, const SDLoc &dl, SelectionDAG &DAG) {
834   // FIXME: Handle bittests someday
835   assert(!LHS.getValueType().isFloatingPoint() && "We don't handle FP yet");
836 
837   // FIXME: Handle jump negative someday
838   MSP430CC::CondCodes TCC = MSP430CC::COND_INVALID;
839   switch (CC) {
840   default: llvm_unreachable("Invalid integer condition!");
841   case ISD::SETEQ:
842     TCC = MSP430CC::COND_E;     // aka COND_Z
843     // Minor optimization: if LHS is a constant, swap operands, then the
844     // constant can be folded into comparison.
845     if (LHS.getOpcode() == ISD::Constant)
846       std::swap(LHS, RHS);
847     break;
848   case ISD::SETNE:
849     TCC = MSP430CC::COND_NE;    // aka COND_NZ
850     // Minor optimization: if LHS is a constant, swap operands, then the
851     // constant can be folded into comparison.
852     if (LHS.getOpcode() == ISD::Constant)
853       std::swap(LHS, RHS);
854     break;
855   case ISD::SETULE:
856     std::swap(LHS, RHS);
857     LLVM_FALLTHROUGH;
858   case ISD::SETUGE:
859     // Turn lhs u>= rhs with lhs constant into rhs u< lhs+1, this allows us to
860     // fold constant into instruction.
861     if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
862       LHS = RHS;
863       RHS = DAG.getConstant(C->getSExtValue() + 1, dl, C->getValueType(0));
864       TCC = MSP430CC::COND_LO;
865       break;
866     }
867     TCC = MSP430CC::COND_HS;    // aka COND_C
868     break;
869   case ISD::SETUGT:
870     std::swap(LHS, RHS);
871     LLVM_FALLTHROUGH;
872   case ISD::SETULT:
873     // Turn lhs u< rhs with lhs constant into rhs u>= lhs+1, this allows us to
874     // fold constant into instruction.
875     if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
876       LHS = RHS;
877       RHS = DAG.getConstant(C->getSExtValue() + 1, dl, C->getValueType(0));
878       TCC = MSP430CC::COND_HS;
879       break;
880     }
881     TCC = MSP430CC::COND_LO;    // aka COND_NC
882     break;
883   case ISD::SETLE:
884     std::swap(LHS, RHS);
885     LLVM_FALLTHROUGH;
886   case ISD::SETGE:
887     // Turn lhs >= rhs with lhs constant into rhs < lhs+1, this allows us to
888     // fold constant into instruction.
889     if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
890       LHS = RHS;
891       RHS = DAG.getConstant(C->getSExtValue() + 1, dl, C->getValueType(0));
892       TCC = MSP430CC::COND_L;
893       break;
894     }
895     TCC = MSP430CC::COND_GE;
896     break;
897   case ISD::SETGT:
898     std::swap(LHS, RHS);
899     LLVM_FALLTHROUGH;
900   case ISD::SETLT:
901     // Turn lhs < rhs with lhs constant into rhs >= lhs+1, this allows us to
902     // fold constant into instruction.
903     if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
904       LHS = RHS;
905       RHS = DAG.getConstant(C->getSExtValue() + 1, dl, C->getValueType(0));
906       TCC = MSP430CC::COND_GE;
907       break;
908     }
909     TCC = MSP430CC::COND_L;
910     break;
911   }
912 
913   TargetCC = DAG.getConstant(TCC, dl, MVT::i8);
914   return DAG.getNode(MSP430ISD::CMP, dl, MVT::Glue, LHS, RHS);
915 }
916 
917 
918 SDValue MSP430TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
919   SDValue Chain = Op.getOperand(0);
920   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
921   SDValue LHS   = Op.getOperand(2);
922   SDValue RHS   = Op.getOperand(3);
923   SDValue Dest  = Op.getOperand(4);
924   SDLoc dl  (Op);
925 
926   SDValue TargetCC;
927   SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
928 
929   return DAG.getNode(MSP430ISD::BR_CC, dl, Op.getValueType(),
930                      Chain, Dest, TargetCC, Flag);
931 }
932 
933 SDValue MSP430TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
934   SDValue LHS   = Op.getOperand(0);
935   SDValue RHS   = Op.getOperand(1);
936   SDLoc dl  (Op);
937 
938   // If we are doing an AND and testing against zero, then the CMP
939   // will not be generated.  The AND (or BIT) will generate the condition codes,
940   // but they are different from CMP.
941   // FIXME: since we're doing a post-processing, use a pseudoinstr here, so
942   // lowering & isel wouldn't diverge.
943   bool andCC = false;
944   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
945     if (RHSC->isNullValue() && LHS.hasOneUse() &&
946         (LHS.getOpcode() == ISD::AND ||
947          (LHS.getOpcode() == ISD::TRUNCATE &&
948           LHS.getOperand(0).getOpcode() == ISD::AND))) {
949       andCC = true;
950     }
951   }
952   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
953   SDValue TargetCC;
954   SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
955 
956   // Get the condition codes directly from the status register, if its easy.
957   // Otherwise a branch will be generated.  Note that the AND and BIT
958   // instructions generate different flags than CMP, the carry bit can be used
959   // for NE/EQ.
960   bool Invert = false;
961   bool Shift = false;
962   bool Convert = true;
963   switch (cast<ConstantSDNode>(TargetCC)->getZExtValue()) {
964    default:
965     Convert = false;
966     break;
967    case MSP430CC::COND_HS:
968      // Res = SR & 1, no processing is required
969      break;
970    case MSP430CC::COND_LO:
971      // Res = ~(SR & 1)
972      Invert = true;
973      break;
974    case MSP430CC::COND_NE:
975      if (andCC) {
976        // C = ~Z, thus Res = SR & 1, no processing is required
977      } else {
978        // Res = ~((SR >> 1) & 1)
979        Shift = true;
980        Invert = true;
981      }
982      break;
983    case MSP430CC::COND_E:
984      Shift = true;
985      // C = ~Z for AND instruction, thus we can put Res = ~(SR & 1), however,
986      // Res = (SR >> 1) & 1 is 1 word shorter.
987      break;
988   }
989   EVT VT = Op.getValueType();
990   SDValue One  = DAG.getConstant(1, dl, VT);
991   if (Convert) {
992     SDValue SR = DAG.getCopyFromReg(DAG.getEntryNode(), dl, MSP430::SR,
993                                     MVT::i16, Flag);
994     if (Shift)
995       // FIXME: somewhere this is turned into a SRL, lower it MSP specific?
996       SR = DAG.getNode(ISD::SRA, dl, MVT::i16, SR, One);
997     SR = DAG.getNode(ISD::AND, dl, MVT::i16, SR, One);
998     if (Invert)
999       SR = DAG.getNode(ISD::XOR, dl, MVT::i16, SR, One);
1000     return SR;
1001   } else {
1002     SDValue Zero = DAG.getConstant(0, dl, VT);
1003     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
1004     SDValue Ops[] = {One, Zero, TargetCC, Flag};
1005     return DAG.getNode(MSP430ISD::SELECT_CC, dl, VTs, Ops);
1006   }
1007 }
1008 
1009 SDValue MSP430TargetLowering::LowerSELECT_CC(SDValue Op,
1010                                              SelectionDAG &DAG) const {
1011   SDValue LHS    = Op.getOperand(0);
1012   SDValue RHS    = Op.getOperand(1);
1013   SDValue TrueV  = Op.getOperand(2);
1014   SDValue FalseV = Op.getOperand(3);
1015   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1016   SDLoc dl   (Op);
1017 
1018   SDValue TargetCC;
1019   SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
1020 
1021   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
1022   SDValue Ops[] = {TrueV, FalseV, TargetCC, Flag};
1023 
1024   return DAG.getNode(MSP430ISD::SELECT_CC, dl, VTs, Ops);
1025 }
1026 
1027 SDValue MSP430TargetLowering::LowerSIGN_EXTEND(SDValue Op,
1028                                                SelectionDAG &DAG) const {
1029   SDValue Val = Op.getOperand(0);
1030   EVT VT      = Op.getValueType();
1031   SDLoc dl(Op);
1032 
1033   assert(VT == MVT::i16 && "Only support i16 for now!");
1034 
1035   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT,
1036                      DAG.getNode(ISD::ANY_EXTEND, dl, VT, Val),
1037                      DAG.getValueType(Val.getValueType()));
1038 }
1039 
1040 SDValue
1041 MSP430TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
1042   MachineFunction &MF = DAG.getMachineFunction();
1043   MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
1044   int ReturnAddrIndex = FuncInfo->getRAIndex();
1045   auto PtrVT = getPointerTy(MF.getDataLayout());
1046 
1047   if (ReturnAddrIndex == 0) {
1048     // Set up a frame object for the return address.
1049     uint64_t SlotSize = MF.getDataLayout().getPointerSize();
1050     ReturnAddrIndex = MF.getFrameInfo().CreateFixedObject(SlotSize, -SlotSize,
1051                                                            true);
1052     FuncInfo->setRAIndex(ReturnAddrIndex);
1053   }
1054 
1055   return DAG.getFrameIndex(ReturnAddrIndex, PtrVT);
1056 }
1057 
1058 SDValue MSP430TargetLowering::LowerRETURNADDR(SDValue Op,
1059                                               SelectionDAG &DAG) const {
1060   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
1061   MFI.setReturnAddressIsTaken(true);
1062 
1063   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1064     return SDValue();
1065 
1066   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1067   SDLoc dl(Op);
1068   auto PtrVT = getPointerTy(DAG.getDataLayout());
1069 
1070   if (Depth > 0) {
1071     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
1072     SDValue Offset =
1073         DAG.getConstant(DAG.getDataLayout().getPointerSize(), dl, MVT::i16);
1074     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
1075                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
1076                        MachinePointerInfo());
1077   }
1078 
1079   // Just load the return address.
1080   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
1081   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
1082                      MachinePointerInfo());
1083 }
1084 
1085 SDValue MSP430TargetLowering::LowerFRAMEADDR(SDValue Op,
1086                                              SelectionDAG &DAG) const {
1087   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
1088   MFI.setFrameAddressIsTaken(true);
1089 
1090   EVT VT = Op.getValueType();
1091   SDLoc dl(Op);  // FIXME probably not meaningful
1092   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1093   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
1094                                          MSP430::FP, VT);
1095   while (Depth--)
1096     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
1097                             MachinePointerInfo());
1098   return FrameAddr;
1099 }
1100 
1101 SDValue MSP430TargetLowering::LowerVASTART(SDValue Op,
1102                                            SelectionDAG &DAG) const {
1103   MachineFunction &MF = DAG.getMachineFunction();
1104   MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
1105   auto PtrVT = getPointerTy(DAG.getDataLayout());
1106 
1107   // Frame index of first vararg argument
1108   SDValue FrameIndex =
1109       DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1110   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1111 
1112   // Create a store of the frame index to the location operand
1113   return DAG.getStore(Op.getOperand(0), SDLoc(Op), FrameIndex, Op.getOperand(1),
1114                       MachinePointerInfo(SV));
1115 }
1116 
1117 SDValue MSP430TargetLowering::LowerJumpTable(SDValue Op,
1118                                              SelectionDAG &DAG) const {
1119     JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1120     auto PtrVT = getPointerTy(DAG.getDataLayout());
1121     SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1122     return DAG.getNode(MSP430ISD::Wrapper, SDLoc(JT), PtrVT, Result);
1123 }
1124 
1125 /// getPostIndexedAddressParts - returns true by value, base pointer and
1126 /// offset pointer and addressing mode by reference if this node can be
1127 /// combined with a load / store to form a post-indexed load / store.
1128 bool MSP430TargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
1129                                                       SDValue &Base,
1130                                                       SDValue &Offset,
1131                                                       ISD::MemIndexedMode &AM,
1132                                                       SelectionDAG &DAG) const {
1133 
1134   LoadSDNode *LD = cast<LoadSDNode>(N);
1135   if (LD->getExtensionType() != ISD::NON_EXTLOAD)
1136     return false;
1137 
1138   EVT VT = LD->getMemoryVT();
1139   if (VT != MVT::i8 && VT != MVT::i16)
1140     return false;
1141 
1142   if (Op->getOpcode() != ISD::ADD)
1143     return false;
1144 
1145   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
1146     uint64_t RHSC = RHS->getZExtValue();
1147     if ((VT == MVT::i16 && RHSC != 2) ||
1148         (VT == MVT::i8 && RHSC != 1))
1149       return false;
1150 
1151     Base = Op->getOperand(0);
1152     Offset = DAG.getConstant(RHSC, SDLoc(N), VT);
1153     AM = ISD::POST_INC;
1154     return true;
1155   }
1156 
1157   return false;
1158 }
1159 
1160 
1161 const char *MSP430TargetLowering::getTargetNodeName(unsigned Opcode) const {
1162   switch ((MSP430ISD::NodeType)Opcode) {
1163   case MSP430ISD::FIRST_NUMBER:       break;
1164   case MSP430ISD::RET_FLAG:           return "MSP430ISD::RET_FLAG";
1165   case MSP430ISD::RETI_FLAG:          return "MSP430ISD::RETI_FLAG";
1166   case MSP430ISD::RRA:                return "MSP430ISD::RRA";
1167   case MSP430ISD::RLA:                return "MSP430ISD::RLA";
1168   case MSP430ISD::RRC:                return "MSP430ISD::RRC";
1169   case MSP430ISD::CALL:               return "MSP430ISD::CALL";
1170   case MSP430ISD::Wrapper:            return "MSP430ISD::Wrapper";
1171   case MSP430ISD::BR_CC:              return "MSP430ISD::BR_CC";
1172   case MSP430ISD::CMP:                return "MSP430ISD::CMP";
1173   case MSP430ISD::SETCC:              return "MSP430ISD::SETCC";
1174   case MSP430ISD::SELECT_CC:          return "MSP430ISD::SELECT_CC";
1175   case MSP430ISD::SHL:                return "MSP430ISD::SHL";
1176   case MSP430ISD::SRA:                return "MSP430ISD::SRA";
1177   case MSP430ISD::SRL:                return "MSP430ISD::SRL";
1178   }
1179   return nullptr;
1180 }
1181 
1182 bool MSP430TargetLowering::isTruncateFree(Type *Ty1,
1183                                           Type *Ty2) const {
1184   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
1185     return false;
1186 
1187   return (Ty1->getPrimitiveSizeInBits() > Ty2->getPrimitiveSizeInBits());
1188 }
1189 
1190 bool MSP430TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
1191   if (!VT1.isInteger() || !VT2.isInteger())
1192     return false;
1193 
1194   return (VT1.getSizeInBits() > VT2.getSizeInBits());
1195 }
1196 
1197 bool MSP430TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
1198   // MSP430 implicitly zero-extends 8-bit results in 16-bit registers.
1199   return 0 && Ty1->isIntegerTy(8) && Ty2->isIntegerTy(16);
1200 }
1201 
1202 bool MSP430TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
1203   // MSP430 implicitly zero-extends 8-bit results in 16-bit registers.
1204   return 0 && VT1 == MVT::i8 && VT2 == MVT::i16;
1205 }
1206 
1207 bool MSP430TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1208   return isZExtFree(Val.getValueType(), VT2);
1209 }
1210 
1211 //===----------------------------------------------------------------------===//
1212 //  Other Lowering Code
1213 //===----------------------------------------------------------------------===//
1214 
1215 MachineBasicBlock *
1216 MSP430TargetLowering::EmitShiftInstr(MachineInstr &MI,
1217                                      MachineBasicBlock *BB) const {
1218   MachineFunction *F = BB->getParent();
1219   MachineRegisterInfo &RI = F->getRegInfo();
1220   DebugLoc dl = MI.getDebugLoc();
1221   const TargetInstrInfo &TII = *F->getSubtarget().getInstrInfo();
1222 
1223   unsigned Opc;
1224   const TargetRegisterClass * RC;
1225   switch (MI.getOpcode()) {
1226   default: llvm_unreachable("Invalid shift opcode!");
1227   case MSP430::Shl8:
1228    Opc = MSP430::SHL8r1;
1229    RC = &MSP430::GR8RegClass;
1230    break;
1231   case MSP430::Shl16:
1232    Opc = MSP430::SHL16r1;
1233    RC = &MSP430::GR16RegClass;
1234    break;
1235   case MSP430::Sra8:
1236    Opc = MSP430::SAR8r1;
1237    RC = &MSP430::GR8RegClass;
1238    break;
1239   case MSP430::Sra16:
1240    Opc = MSP430::SAR16r1;
1241    RC = &MSP430::GR16RegClass;
1242    break;
1243   case MSP430::Srl8:
1244    Opc = MSP430::SAR8r1c;
1245    RC = &MSP430::GR8RegClass;
1246    break;
1247   case MSP430::Srl16:
1248    Opc = MSP430::SAR16r1c;
1249    RC = &MSP430::GR16RegClass;
1250    break;
1251   }
1252 
1253   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1254   MachineFunction::iterator I = ++BB->getIterator();
1255 
1256   // Create loop block
1257   MachineBasicBlock *LoopBB = F->CreateMachineBasicBlock(LLVM_BB);
1258   MachineBasicBlock *RemBB  = F->CreateMachineBasicBlock(LLVM_BB);
1259 
1260   F->insert(I, LoopBB);
1261   F->insert(I, RemBB);
1262 
1263   // Update machine-CFG edges by transferring all successors of the current
1264   // block to the block containing instructions after shift.
1265   RemBB->splice(RemBB->begin(), BB, std::next(MachineBasicBlock::iterator(MI)),
1266                 BB->end());
1267   RemBB->transferSuccessorsAndUpdatePHIs(BB);
1268 
1269   // Add edges BB => LoopBB => RemBB, BB => RemBB, LoopBB => LoopBB
1270   BB->addSuccessor(LoopBB);
1271   BB->addSuccessor(RemBB);
1272   LoopBB->addSuccessor(RemBB);
1273   LoopBB->addSuccessor(LoopBB);
1274 
1275   unsigned ShiftAmtReg = RI.createVirtualRegister(&MSP430::GR8RegClass);
1276   unsigned ShiftAmtReg2 = RI.createVirtualRegister(&MSP430::GR8RegClass);
1277   unsigned ShiftReg = RI.createVirtualRegister(RC);
1278   unsigned ShiftReg2 = RI.createVirtualRegister(RC);
1279   unsigned ShiftAmtSrcReg = MI.getOperand(2).getReg();
1280   unsigned SrcReg = MI.getOperand(1).getReg();
1281   unsigned DstReg = MI.getOperand(0).getReg();
1282 
1283   // BB:
1284   // cmp 0, N
1285   // je RemBB
1286   BuildMI(BB, dl, TII.get(MSP430::CMP8ri))
1287     .addReg(ShiftAmtSrcReg).addImm(0);
1288   BuildMI(BB, dl, TII.get(MSP430::JCC))
1289     .addMBB(RemBB)
1290     .addImm(MSP430CC::COND_E);
1291 
1292   // LoopBB:
1293   // ShiftReg = phi [%SrcReg, BB], [%ShiftReg2, LoopBB]
1294   // ShiftAmt = phi [%N, BB],      [%ShiftAmt2, LoopBB]
1295   // ShiftReg2 = shift ShiftReg
1296   // ShiftAmt2 = ShiftAmt - 1;
1297   BuildMI(LoopBB, dl, TII.get(MSP430::PHI), ShiftReg)
1298     .addReg(SrcReg).addMBB(BB)
1299     .addReg(ShiftReg2).addMBB(LoopBB);
1300   BuildMI(LoopBB, dl, TII.get(MSP430::PHI), ShiftAmtReg)
1301     .addReg(ShiftAmtSrcReg).addMBB(BB)
1302     .addReg(ShiftAmtReg2).addMBB(LoopBB);
1303   BuildMI(LoopBB, dl, TII.get(Opc), ShiftReg2)
1304     .addReg(ShiftReg);
1305   BuildMI(LoopBB, dl, TII.get(MSP430::SUB8ri), ShiftAmtReg2)
1306     .addReg(ShiftAmtReg).addImm(1);
1307   BuildMI(LoopBB, dl, TII.get(MSP430::JCC))
1308     .addMBB(LoopBB)
1309     .addImm(MSP430CC::COND_NE);
1310 
1311   // RemBB:
1312   // DestReg = phi [%SrcReg, BB], [%ShiftReg, LoopBB]
1313   BuildMI(*RemBB, RemBB->begin(), dl, TII.get(MSP430::PHI), DstReg)
1314     .addReg(SrcReg).addMBB(BB)
1315     .addReg(ShiftReg2).addMBB(LoopBB);
1316 
1317   MI.eraseFromParent(); // The pseudo instruction is gone now.
1318   return RemBB;
1319 }
1320 
1321 MachineBasicBlock *
1322 MSP430TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
1323                                                   MachineBasicBlock *BB) const {
1324   unsigned Opc = MI.getOpcode();
1325 
1326   if (Opc == MSP430::Shl8 || Opc == MSP430::Shl16 ||
1327       Opc == MSP430::Sra8 || Opc == MSP430::Sra16 ||
1328       Opc == MSP430::Srl8 || Opc == MSP430::Srl16)
1329     return EmitShiftInstr(MI, BB);
1330 
1331   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
1332   DebugLoc dl = MI.getDebugLoc();
1333 
1334   assert((Opc == MSP430::Select16 || Opc == MSP430::Select8) &&
1335          "Unexpected instr type to insert");
1336 
1337   // To "insert" a SELECT instruction, we actually have to insert the diamond
1338   // control-flow pattern.  The incoming instruction knows the destination vreg
1339   // to set, the condition code register to branch on, the true/false values to
1340   // select between, and a branch opcode to use.
1341   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1342   MachineFunction::iterator I = ++BB->getIterator();
1343 
1344   //  thisMBB:
1345   //  ...
1346   //   TrueVal = ...
1347   //   cmpTY ccX, r1, r2
1348   //   jCC copy1MBB
1349   //   fallthrough --> copy0MBB
1350   MachineBasicBlock *thisMBB = BB;
1351   MachineFunction *F = BB->getParent();
1352   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1353   MachineBasicBlock *copy1MBB = F->CreateMachineBasicBlock(LLVM_BB);
1354   F->insert(I, copy0MBB);
1355   F->insert(I, copy1MBB);
1356   // Update machine-CFG edges by transferring all successors of the current
1357   // block to the new block which will contain the Phi node for the select.
1358   copy1MBB->splice(copy1MBB->begin(), BB,
1359                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
1360   copy1MBB->transferSuccessorsAndUpdatePHIs(BB);
1361   // Next, add the true and fallthrough blocks as its successors.
1362   BB->addSuccessor(copy0MBB);
1363   BB->addSuccessor(copy1MBB);
1364 
1365   BuildMI(BB, dl, TII.get(MSP430::JCC))
1366       .addMBB(copy1MBB)
1367       .addImm(MI.getOperand(3).getImm());
1368 
1369   //  copy0MBB:
1370   //   %FalseValue = ...
1371   //   # fallthrough to copy1MBB
1372   BB = copy0MBB;
1373 
1374   // Update machine-CFG edges
1375   BB->addSuccessor(copy1MBB);
1376 
1377   //  copy1MBB:
1378   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1379   //  ...
1380   BB = copy1MBB;
1381   BuildMI(*BB, BB->begin(), dl, TII.get(MSP430::PHI), MI.getOperand(0).getReg())
1382       .addReg(MI.getOperand(2).getReg())
1383       .addMBB(copy0MBB)
1384       .addReg(MI.getOperand(1).getReg())
1385       .addMBB(thisMBB);
1386 
1387   MI.eraseFromParent(); // The pseudo instruction is gone now.
1388   return BB;
1389 }
1390