Initial codegen support for MSP430 ISRs
[oota-llvm.git] / lib / Target / MSP430 / MSP430ISelLowering.cpp
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 #define DEBUG_TYPE "msp430-lower"
15
16 #include "MSP430ISelLowering.h"
17 #include "MSP430.h"
18 #include "MSP430TargetMachine.h"
19 #include "MSP430Subtarget.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Function.h"
22 #include "llvm/Intrinsics.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/PseudoSourceValue.h"
32 #include "llvm/CodeGen/SelectionDAGISel.h"
33 #include "llvm/CodeGen/ValueTypes.h"
34 #include "llvm/Target/TargetLoweringObjectFile.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/ADT/VectorExtras.h"
40 using namespace llvm;
41
42 typedef enum {
43   NoHWMult,
44   HWMultIntr,
45   HWMultNoIntr
46 } HWMultUseMode;
47
48 static cl::opt<HWMultUseMode>
49 HWMultMode("msp430-hwmult-mode",
50            cl::desc("Hardware multiplier use mode"),
51            cl::init(HWMultNoIntr),
52            cl::values(
53              clEnumValN(NoHWMult, "no",
54                 "Do not use hardware multiplier"),
55              clEnumValN(HWMultIntr, "interrupts",
56                 "Assume hardware multiplier can be used inside interrupts"),
57              clEnumValN(HWMultNoIntr, "use",
58                 "Assume hardware multiplier cannot be used inside interrupts"),
59              clEnumValEnd));
60
61 MSP430TargetLowering::MSP430TargetLowering(MSP430TargetMachine &tm) :
62   TargetLowering(tm, new TargetLoweringObjectFileELF()),
63   Subtarget(*tm.getSubtargetImpl()), TM(tm) {
64
65   // Set up the register classes.
66   addRegisterClass(MVT::i8,  MSP430::GR8RegisterClass);
67   addRegisterClass(MVT::i16, MSP430::GR16RegisterClass);
68
69   // Compute derived properties from the register classes
70   computeRegisterProperties();
71
72   // Provide all sorts of operation actions
73
74   // Division is expensive
75   setIntDivIsCheap(false);
76
77   // Even if we have only 1 bit shift here, we can perform
78   // shifts of the whole bitwidth 1 bit per step.
79   setShiftAmountType(MVT::i8);
80
81   setStackPointerRegisterToSaveRestore(MSP430::SPW);
82   setBooleanContents(ZeroOrOneBooleanContent);
83   setSchedulingPreference(SchedulingForLatency);
84
85   // We have post-incremented loads / stores.
86   setIndexedLoadAction(ISD::POST_INC, MVT::i8, Legal);
87   setIndexedLoadAction(ISD::POST_INC, MVT::i16, Legal);
88
89   setLoadExtAction(ISD::EXTLOAD,  MVT::i1,  Promote);
90   setLoadExtAction(ISD::SEXTLOAD, MVT::i1,  Promote);
91   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
92   setLoadExtAction(ISD::SEXTLOAD, MVT::i8,  Expand);
93   setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Expand);
94
95   // We don't have any truncstores
96   setTruncStoreAction(MVT::i16, MVT::i8, Expand);
97
98   setOperationAction(ISD::SRA,              MVT::i8,    Custom);
99   setOperationAction(ISD::SHL,              MVT::i8,    Custom);
100   setOperationAction(ISD::SRL,              MVT::i8,    Custom);
101   setOperationAction(ISD::SRA,              MVT::i16,   Custom);
102   setOperationAction(ISD::SHL,              MVT::i16,   Custom);
103   setOperationAction(ISD::SRL,              MVT::i16,   Custom);
104   setOperationAction(ISD::ROTL,             MVT::i8,    Expand);
105   setOperationAction(ISD::ROTR,             MVT::i8,    Expand);
106   setOperationAction(ISD::ROTL,             MVT::i16,   Expand);
107   setOperationAction(ISD::ROTR,             MVT::i16,   Expand);
108   setOperationAction(ISD::GlobalAddress,    MVT::i16,   Custom);
109   setOperationAction(ISD::ExternalSymbol,   MVT::i16,   Custom);
110   setOperationAction(ISD::BR_JT,            MVT::Other, Expand);
111   setOperationAction(ISD::BRIND,            MVT::Other, Expand);
112   setOperationAction(ISD::BR_CC,            MVT::i8,    Custom);
113   setOperationAction(ISD::BR_CC,            MVT::i16,   Custom);
114   setOperationAction(ISD::BRCOND,           MVT::Other, Expand);
115   setOperationAction(ISD::SETCC,            MVT::i8,    Expand);
116   setOperationAction(ISD::SETCC,            MVT::i16,   Expand);
117   setOperationAction(ISD::SELECT,           MVT::i8,    Expand);
118   setOperationAction(ISD::SELECT,           MVT::i16,   Expand);
119   setOperationAction(ISD::SELECT_CC,        MVT::i8,    Custom);
120   setOperationAction(ISD::SELECT_CC,        MVT::i16,   Custom);
121   setOperationAction(ISD::SIGN_EXTEND,      MVT::i16,   Custom);
122   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i8, Expand);
123   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i16, Expand);
124
125   setOperationAction(ISD::CTTZ,             MVT::i8,    Expand);
126   setOperationAction(ISD::CTTZ,             MVT::i16,   Expand);
127   setOperationAction(ISD::CTLZ,             MVT::i8,    Expand);
128   setOperationAction(ISD::CTLZ,             MVT::i16,   Expand);
129   setOperationAction(ISD::CTPOP,            MVT::i8,    Expand);
130   setOperationAction(ISD::CTPOP,            MVT::i16,   Expand);
131
132   setOperationAction(ISD::SHL_PARTS,        MVT::i8,    Expand);
133   setOperationAction(ISD::SHL_PARTS,        MVT::i16,   Expand);
134   setOperationAction(ISD::SRL_PARTS,        MVT::i8,    Expand);
135   setOperationAction(ISD::SRL_PARTS,        MVT::i16,   Expand);
136   setOperationAction(ISD::SRA_PARTS,        MVT::i8,    Expand);
137   setOperationAction(ISD::SRA_PARTS,        MVT::i16,   Expand);
138
139   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1,   Expand);
140
141   // FIXME: Implement efficiently multiplication by a constant
142   setOperationAction(ISD::MUL,              MVT::i8,    Expand);
143   setOperationAction(ISD::MULHS,            MVT::i8,    Expand);
144   setOperationAction(ISD::MULHU,            MVT::i8,    Expand);
145   setOperationAction(ISD::SMUL_LOHI,        MVT::i8,    Expand);
146   setOperationAction(ISD::UMUL_LOHI,        MVT::i8,    Expand);
147   setOperationAction(ISD::MUL,              MVT::i16,   Expand);
148   setOperationAction(ISD::MULHS,            MVT::i16,   Expand);
149   setOperationAction(ISD::MULHU,            MVT::i16,   Expand);
150   setOperationAction(ISD::SMUL_LOHI,        MVT::i16,   Expand);
151   setOperationAction(ISD::UMUL_LOHI,        MVT::i16,   Expand);
152
153   setOperationAction(ISD::UDIV,             MVT::i8,    Expand);
154   setOperationAction(ISD::UDIVREM,          MVT::i8,    Expand);
155   setOperationAction(ISD::UREM,             MVT::i8,    Expand);
156   setOperationAction(ISD::SDIV,             MVT::i8,    Expand);
157   setOperationAction(ISD::SDIVREM,          MVT::i8,    Expand);
158   setOperationAction(ISD::SREM,             MVT::i8,    Expand);
159   setOperationAction(ISD::UDIV,             MVT::i16,   Expand);
160   setOperationAction(ISD::UDIVREM,          MVT::i16,   Expand);
161   setOperationAction(ISD::UREM,             MVT::i16,   Expand);
162   setOperationAction(ISD::SDIV,             MVT::i16,   Expand);
163   setOperationAction(ISD::SDIVREM,          MVT::i16,   Expand);
164   setOperationAction(ISD::SREM,             MVT::i16,   Expand);
165
166   // Libcalls names.
167   if (HWMultMode == HWMultIntr) {
168     setLibcallName(RTLIB::MUL_I8,  "__mulqi3hw");
169     setLibcallName(RTLIB::MUL_I16, "__mulhi3hw");
170   } else if (HWMultMode == HWMultNoIntr) {
171     setLibcallName(RTLIB::MUL_I8,  "__mulqi3hw_noint");
172     setLibcallName(RTLIB::MUL_I16, "__mulhi3hw_noint");
173   }
174 }
175
176 SDValue MSP430TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
177   switch (Op.getOpcode()) {
178   case ISD::SHL: // FALLTHROUGH
179   case ISD::SRL:
180   case ISD::SRA:              return LowerShifts(Op, DAG);
181   case ISD::GlobalAddress:    return LowerGlobalAddress(Op, DAG);
182   case ISD::ExternalSymbol:   return LowerExternalSymbol(Op, DAG);
183   case ISD::BR_CC:            return LowerBR_CC(Op, DAG);
184   case ISD::SELECT_CC:        return LowerSELECT_CC(Op, DAG);
185   case ISD::SIGN_EXTEND:      return LowerSIGN_EXTEND(Op, DAG);
186   default:
187     llvm_unreachable("unimplemented operand");
188     return SDValue();
189   }
190 }
191
192 /// getFunctionAlignment - Return the Log2 alignment of this function.
193 unsigned MSP430TargetLowering::getFunctionAlignment(const Function *F) const {
194   return F->hasFnAttr(Attribute::OptimizeForSize) ? 1 : 2;
195 }
196
197 //===----------------------------------------------------------------------===//
198 //                       MSP430 Inline Assembly Support
199 //===----------------------------------------------------------------------===//
200
201 /// getConstraintType - Given a constraint letter, return the type of
202 /// constraint it is for this target.
203 TargetLowering::ConstraintType
204 MSP430TargetLowering::getConstraintType(const std::string &Constraint) const {
205   if (Constraint.size() == 1) {
206     switch (Constraint[0]) {
207     case 'r':
208       return C_RegisterClass;
209     default:
210       break;
211     }
212   }
213   return TargetLowering::getConstraintType(Constraint);
214 }
215
216 std::pair<unsigned, const TargetRegisterClass*>
217 MSP430TargetLowering::
218 getRegForInlineAsmConstraint(const std::string &Constraint,
219                              EVT VT) const {
220   if (Constraint.size() == 1) {
221     // GCC Constraint Letters
222     switch (Constraint[0]) {
223     default: break;
224     case 'r':   // GENERAL_REGS
225       if (VT == MVT::i8)
226         return std::make_pair(0U, MSP430::GR8RegisterClass);
227
228       return std::make_pair(0U, MSP430::GR16RegisterClass);
229     }
230   }
231
232   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
233 }
234
235 //===----------------------------------------------------------------------===//
236 //                      Calling Convention Implementation
237 //===----------------------------------------------------------------------===//
238
239 #include "MSP430GenCallingConv.inc"
240
241 SDValue
242 MSP430TargetLowering::LowerFormalArguments(SDValue Chain,
243                                            CallingConv::ID CallConv,
244                                            bool isVarArg,
245                                            const SmallVectorImpl<ISD::InputArg>
246                                              &Ins,
247                                            DebugLoc dl,
248                                            SelectionDAG &DAG,
249                                            SmallVectorImpl<SDValue> &InVals) {
250
251   switch (CallConv) {
252   default:
253     llvm_unreachable("Unsupported calling convention");
254   case CallingConv::C:
255   case CallingConv::Fast:
256     return LowerCCCArguments(Chain, CallConv, isVarArg, Ins, dl, DAG, InVals);
257   case CallingConv::MSP430_INTR:
258    if (Ins.empty())
259      return Chain;
260    else {
261     llvm_report_error("ISRs cannot have arguments");
262     return SDValue();
263    }
264   }
265 }
266
267 SDValue
268 MSP430TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
269                                 CallingConv::ID CallConv, bool isVarArg,
270                                 bool isTailCall,
271                                 const SmallVectorImpl<ISD::OutputArg> &Outs,
272                                 const SmallVectorImpl<ISD::InputArg> &Ins,
273                                 DebugLoc dl, SelectionDAG &DAG,
274                                 SmallVectorImpl<SDValue> &InVals) {
275
276   switch (CallConv) {
277   default:
278     llvm_unreachable("Unsupported calling convention");
279   case CallingConv::Fast:
280   case CallingConv::C:
281     return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
282                           Outs, Ins, dl, DAG, InVals);
283   case CallingConv::MSP430_INTR:
284     llvm_report_error("ISRs cannot be called directly");
285     return SDValue();
286   }
287 }
288
289 /// LowerCCCArguments - transform physical registers into virtual registers and
290 /// generate load operations for arguments places on the stack.
291 // FIXME: struct return stuff
292 // FIXME: varargs
293 SDValue
294 MSP430TargetLowering::LowerCCCArguments(SDValue Chain,
295                                         CallingConv::ID CallConv,
296                                         bool isVarArg,
297                                         const SmallVectorImpl<ISD::InputArg>
298                                           &Ins,
299                                         DebugLoc dl,
300                                         SelectionDAG &DAG,
301                                         SmallVectorImpl<SDValue> &InVals) {
302   MachineFunction &MF = DAG.getMachineFunction();
303   MachineFrameInfo *MFI = MF.getFrameInfo();
304   MachineRegisterInfo &RegInfo = MF.getRegInfo();
305
306   // Assign locations to all of the incoming arguments.
307   SmallVector<CCValAssign, 16> ArgLocs;
308   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
309                  ArgLocs, *DAG.getContext());
310   CCInfo.AnalyzeFormalArguments(Ins, CC_MSP430);
311
312   assert(!isVarArg && "Varargs not supported yet");
313
314   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
315     CCValAssign &VA = ArgLocs[i];
316     if (VA.isRegLoc()) {
317       // Arguments passed in registers
318       EVT RegVT = VA.getLocVT();
319       switch (RegVT.getSimpleVT().SimpleTy) {
320       default: 
321         {
322 #ifndef NDEBUG
323           errs() << "LowerFormalArguments Unhandled argument type: "
324                << RegVT.getSimpleVT().SimpleTy << "\n";
325 #endif
326           llvm_unreachable(0);
327         }
328       case MVT::i16:
329         unsigned VReg =
330           RegInfo.createVirtualRegister(MSP430::GR16RegisterClass);
331         RegInfo.addLiveIn(VA.getLocReg(), VReg);
332         SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
333
334         // If this is an 8-bit value, it is really passed promoted to 16
335         // bits. Insert an assert[sz]ext to capture this, then truncate to the
336         // right size.
337         if (VA.getLocInfo() == CCValAssign::SExt)
338           ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
339                                  DAG.getValueType(VA.getValVT()));
340         else if (VA.getLocInfo() == CCValAssign::ZExt)
341           ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
342                                  DAG.getValueType(VA.getValVT()));
343
344         if (VA.getLocInfo() != CCValAssign::Full)
345           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
346
347         InVals.push_back(ArgValue);
348       }
349     } else {
350       // Sanity check
351       assert(VA.isMemLoc());
352       // Load the argument to a virtual register
353       unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
354       if (ObjSize > 2) {
355         errs() << "LowerFormalArguments Unhandled argument type: "
356              << VA.getLocVT().getSimpleVT().SimpleTy
357              << "\n";
358       }
359       // Create the frame index object for this incoming parameter...
360       int FI = MFI->CreateFixedObject(ObjSize, VA.getLocMemOffset(), true, false);
361
362       // Create the SelectionDAG nodes corresponding to a load
363       //from this parameter
364       SDValue FIN = DAG.getFrameIndex(FI, MVT::i16);
365       InVals.push_back(DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
366                                    PseudoSourceValue::getFixedStack(FI), 0));
367     }
368   }
369
370   return Chain;
371 }
372
373 SDValue
374 MSP430TargetLowering::LowerReturn(SDValue Chain,
375                                   CallingConv::ID CallConv, bool isVarArg,
376                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
377                                   DebugLoc dl, SelectionDAG &DAG) {
378
379   // CCValAssign - represent the assignment of the return value to a location
380   SmallVector<CCValAssign, 16> RVLocs;
381
382   // ISRs cannot return any value.
383   if (CallConv == CallingConv::MSP430_INTR && !Outs.empty()) {
384     llvm_report_error("ISRs cannot return any value");
385     return SDValue();
386   }
387
388   // CCState - Info about the registers and stack slot.
389   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
390                  RVLocs, *DAG.getContext());
391
392   // Analize return values.
393   CCInfo.AnalyzeReturn(Outs, RetCC_MSP430);
394
395   // If this is the first return lowered for this function, add the regs to the
396   // liveout set for the function.
397   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
398     for (unsigned i = 0; i != RVLocs.size(); ++i)
399       if (RVLocs[i].isRegLoc())
400         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
401   }
402
403   SDValue Flag;
404
405   // Copy the result values into the output registers.
406   for (unsigned i = 0; i != RVLocs.size(); ++i) {
407     CCValAssign &VA = RVLocs[i];
408     assert(VA.isRegLoc() && "Can only return in registers!");
409
410     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
411                              Outs[i].Val, Flag);
412
413     // Guarantee that all emitted copies are stuck together,
414     // avoiding something bad.
415     Flag = Chain.getValue(1);
416   }
417
418   unsigned Opc = (CallConv == CallingConv::MSP430_INTR ?
419                   MSP430ISD::RETI_FLAG : MSP430ISD::RET_FLAG);
420
421   if (Flag.getNode())
422     return DAG.getNode(Opc, dl, MVT::Other, Chain, Flag);
423
424   // Return Void
425   return DAG.getNode(Opc, dl, MVT::Other, Chain);
426 }
427
428 /// LowerCCCCallTo - functions arguments are copied from virtual regs to
429 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
430 /// TODO: sret.
431 SDValue
432 MSP430TargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
433                                      CallingConv::ID CallConv, bool isVarArg,
434                                      bool isTailCall,
435                                      const SmallVectorImpl<ISD::OutputArg>
436                                        &Outs,
437                                      const SmallVectorImpl<ISD::InputArg> &Ins,
438                                      DebugLoc dl, SelectionDAG &DAG,
439                                      SmallVectorImpl<SDValue> &InVals) {
440   // Analyze operands of the call, assigning locations to each operand.
441   SmallVector<CCValAssign, 16> ArgLocs;
442   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
443                  ArgLocs, *DAG.getContext());
444
445   CCInfo.AnalyzeCallOperands(Outs, CC_MSP430);
446
447   // Get a count of how many bytes are to be pushed on the stack.
448   unsigned NumBytes = CCInfo.getNextStackOffset();
449
450   Chain = DAG.getCALLSEQ_START(Chain ,DAG.getConstant(NumBytes,
451                                                       getPointerTy(), true));
452
453   SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
454   SmallVector<SDValue, 12> MemOpChains;
455   SDValue StackPtr;
456
457   // Walk the register/memloc assignments, inserting copies/loads.
458   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
459     CCValAssign &VA = ArgLocs[i];
460
461     SDValue Arg = Outs[i].Val;
462
463     // Promote the value if needed.
464     switch (VA.getLocInfo()) {
465       default: llvm_unreachable("Unknown loc info!");
466       case CCValAssign::Full: break;
467       case CCValAssign::SExt:
468         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
469         break;
470       case CCValAssign::ZExt:
471         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
472         break;
473       case CCValAssign::AExt:
474         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
475         break;
476     }
477
478     // Arguments that can be passed on register must be kept at RegsToPass
479     // vector
480     if (VA.isRegLoc()) {
481       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
482     } else {
483       assert(VA.isMemLoc());
484
485       if (StackPtr.getNode() == 0)
486         StackPtr = DAG.getCopyFromReg(Chain, dl, MSP430::SPW, getPointerTy());
487
488       SDValue PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(),
489                                    StackPtr,
490                                    DAG.getIntPtrConstant(VA.getLocMemOffset()));
491
492
493       MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
494                                          PseudoSourceValue::getStack(),
495                                          VA.getLocMemOffset()));
496     }
497   }
498
499   // Transform all store nodes into one single node because all store nodes are
500   // independent of each other.
501   if (!MemOpChains.empty())
502     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
503                         &MemOpChains[0], MemOpChains.size());
504
505   // Build a sequence of copy-to-reg nodes chained together with token chain and
506   // flag operands which copy the outgoing args into registers.  The InFlag in
507   // necessary since all emited instructions must be stuck together.
508   SDValue InFlag;
509   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
510     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
511                              RegsToPass[i].second, InFlag);
512     InFlag = Chain.getValue(1);
513   }
514
515   // If the callee is a GlobalAddress node (quite common, every direct call is)
516   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
517   // Likewise ExternalSymbol -> TargetExternalSymbol.
518   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
519     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i16);
520   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
521     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i16);
522
523   // Returns a chain & a flag for retval copy to use.
524   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
525   SmallVector<SDValue, 8> Ops;
526   Ops.push_back(Chain);
527   Ops.push_back(Callee);
528
529   // Add argument registers to the end of the list so that they are
530   // known live into the call.
531   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
532     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
533                                   RegsToPass[i].second.getValueType()));
534
535   if (InFlag.getNode())
536     Ops.push_back(InFlag);
537
538   Chain = DAG.getNode(MSP430ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
539   InFlag = Chain.getValue(1);
540
541   // Create the CALLSEQ_END node.
542   Chain = DAG.getCALLSEQ_END(Chain,
543                              DAG.getConstant(NumBytes, getPointerTy(), true),
544                              DAG.getConstant(0, getPointerTy(), true),
545                              InFlag);
546   InFlag = Chain.getValue(1);
547
548   // Handle result values, copying them out of physregs into vregs that we
549   // return.
550   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl,
551                          DAG, InVals);
552 }
553
554 /// LowerCallResult - Lower the result values of a call into the
555 /// appropriate copies out of appropriate physical registers.
556 ///
557 SDValue
558 MSP430TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
559                                       CallingConv::ID CallConv, bool isVarArg,
560                                       const SmallVectorImpl<ISD::InputArg> &Ins,
561                                       DebugLoc dl, SelectionDAG &DAG,
562                                       SmallVectorImpl<SDValue> &InVals) {
563
564   // Assign locations to each value returned by this call.
565   SmallVector<CCValAssign, 16> RVLocs;
566   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
567                  RVLocs, *DAG.getContext());
568
569   CCInfo.AnalyzeCallResult(Ins, RetCC_MSP430);
570
571   // Copy all of the result registers out of their specified physreg.
572   for (unsigned i = 0; i != RVLocs.size(); ++i) {
573     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
574                                RVLocs[i].getValVT(), InFlag).getValue(1);
575     InFlag = Chain.getValue(2);
576     InVals.push_back(Chain.getValue(0));
577   }
578
579   return Chain;
580 }
581
582 SDValue MSP430TargetLowering::LowerShifts(SDValue Op,
583                                           SelectionDAG &DAG) {
584   unsigned Opc = Op.getOpcode();
585   SDNode* N = Op.getNode();
586   EVT VT = Op.getValueType();
587   DebugLoc dl = N->getDebugLoc();
588
589   // We currently only lower shifts of constant argument.
590   if (!isa<ConstantSDNode>(N->getOperand(1)))
591     return SDValue();
592
593   uint64_t ShiftAmount = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
594
595   // Expand the stuff into sequence of shifts.
596   // FIXME: for some shift amounts this might be done better!
597   // E.g.: foo >> (8 + N) => sxt(swpb(foo)) >> N
598   SDValue Victim = N->getOperand(0);
599
600   if (Opc == ISD::SRL && ShiftAmount) {
601     // Emit a special goodness here:
602     // srl A, 1 => clrc; rrc A
603     Victim = DAG.getNode(MSP430ISD::RRC, dl, VT, Victim);
604     ShiftAmount -= 1;
605   }
606
607   while (ShiftAmount--)
608     Victim = DAG.getNode((Opc == ISD::SHL ? MSP430ISD::RLA : MSP430ISD::RRA),
609                          dl, VT, Victim);
610
611   return Victim;
612 }
613
614 SDValue MSP430TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
615   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
616   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
617
618   // Create the TargetGlobalAddress node, folding in the constant offset.
619   SDValue Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
620   return DAG.getNode(MSP430ISD::Wrapper, Op.getDebugLoc(),
621                      getPointerTy(), Result);
622 }
623
624 SDValue MSP430TargetLowering::LowerExternalSymbol(SDValue Op,
625                                                   SelectionDAG &DAG) {
626   DebugLoc dl = Op.getDebugLoc();
627   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
628   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
629
630   return DAG.getNode(MSP430ISD::Wrapper, dl, getPointerTy(), Result);;
631 }
632
633 static SDValue EmitCMP(SDValue &LHS, SDValue &RHS, SDValue &TargetCC,
634                        ISD::CondCode CC,
635                        DebugLoc dl, SelectionDAG &DAG) {
636   // FIXME: Handle bittests someday
637   assert(!LHS.getValueType().isFloatingPoint() && "We don't handle FP yet");
638
639   // FIXME: Handle jump negative someday
640   MSP430CC::CondCodes TCC = MSP430CC::COND_INVALID;
641   switch (CC) {
642   default: llvm_unreachable("Invalid integer condition!");
643   case ISD::SETEQ:
644     TCC = MSP430CC::COND_E;     // aka COND_Z
645     // Minor optimization: if RHS is a constant, swap operands, then the
646     // constant can be folded into comparison.
647     if (RHS.getOpcode() == ISD::Constant)
648       std::swap(LHS, RHS);
649     break;
650   case ISD::SETNE:
651     TCC = MSP430CC::COND_NE;    // aka COND_NZ
652     // Minor optimization: if RHS is a constant, swap operands, then the
653     // constant can be folded into comparison.
654     if (RHS.getOpcode() == ISD::Constant)
655       std::swap(LHS, RHS);
656     break;
657   case ISD::SETULE:
658     std::swap(LHS, RHS);        // FALLTHROUGH
659   case ISD::SETUGE:
660     TCC = MSP430CC::COND_HS;    // aka COND_C
661     break;
662   case ISD::SETUGT:
663     std::swap(LHS, RHS);        // FALLTHROUGH
664   case ISD::SETULT:
665     TCC = MSP430CC::COND_LO;    // aka COND_NC
666     break;
667   case ISD::SETLE:
668     std::swap(LHS, RHS);        // FALLTHROUGH
669   case ISD::SETGE:
670     TCC = MSP430CC::COND_GE;
671     break;
672   case ISD::SETGT:
673     std::swap(LHS, RHS);        // FALLTHROUGH
674   case ISD::SETLT:
675     TCC = MSP430CC::COND_L;
676     break;
677   }
678
679   TargetCC = DAG.getConstant(TCC, MVT::i8);
680   return DAG.getNode(MSP430ISD::CMP, dl, MVT::Flag, LHS, RHS);
681 }
682
683
684 SDValue MSP430TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) {
685   SDValue Chain = Op.getOperand(0);
686   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
687   SDValue LHS   = Op.getOperand(2);
688   SDValue RHS   = Op.getOperand(3);
689   SDValue Dest  = Op.getOperand(4);
690   DebugLoc dl   = Op.getDebugLoc();
691
692   SDValue TargetCC;
693   SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
694
695   return DAG.getNode(MSP430ISD::BR_CC, dl, Op.getValueType(),
696                      Chain, Dest, TargetCC, Flag);
697 }
698
699 SDValue MSP430TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) {
700   SDValue LHS    = Op.getOperand(0);
701   SDValue RHS    = Op.getOperand(1);
702   SDValue TrueV  = Op.getOperand(2);
703   SDValue FalseV = Op.getOperand(3);
704   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
705   DebugLoc dl    = Op.getDebugLoc();
706
707   SDValue TargetCC;
708   SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
709
710   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
711   SmallVector<SDValue, 4> Ops;
712   Ops.push_back(TrueV);
713   Ops.push_back(FalseV);
714   Ops.push_back(TargetCC);
715   Ops.push_back(Flag);
716
717   return DAG.getNode(MSP430ISD::SELECT_CC, dl, VTs, &Ops[0], Ops.size());
718 }
719
720 SDValue MSP430TargetLowering::LowerSIGN_EXTEND(SDValue Op,
721                                                SelectionDAG &DAG) {
722   SDValue Val = Op.getOperand(0);
723   EVT VT      = Op.getValueType();
724   DebugLoc dl = Op.getDebugLoc();
725
726   assert(VT == MVT::i16 && "Only support i16 for now!");
727
728   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT,
729                      DAG.getNode(ISD::ANY_EXTEND, dl, VT, Val),
730                      DAG.getValueType(Val.getValueType()));
731 }
732
733 /// getPostIndexedAddressParts - returns true by value, base pointer and
734 /// offset pointer and addressing mode by reference if this node can be
735 /// combined with a load / store to form a post-indexed load / store.
736 bool MSP430TargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
737                                                       SDValue &Base,
738                                                       SDValue &Offset,
739                                                       ISD::MemIndexedMode &AM,
740                                                       SelectionDAG &DAG) const {
741
742   LoadSDNode *LD = cast<LoadSDNode>(N);
743   if (LD->getExtensionType() != ISD::NON_EXTLOAD)
744     return false;
745
746   EVT VT = LD->getMemoryVT();
747   if (VT != MVT::i8 && VT != MVT::i16)
748     return false;
749
750   if (Op->getOpcode() != ISD::ADD)
751     return false;
752
753   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
754     uint64_t RHSC = RHS->getZExtValue();
755     if ((VT == MVT::i16 && RHSC != 2) ||
756         (VT == MVT::i8 && RHSC != 1))
757       return false;
758
759     Base = Op->getOperand(0);
760     Offset = DAG.getConstant(RHSC, VT);
761     AM = ISD::POST_INC;
762     return true;
763   }
764
765   return false;
766 }
767
768
769 const char *MSP430TargetLowering::getTargetNodeName(unsigned Opcode) const {
770   switch (Opcode) {
771   default: return NULL;
772   case MSP430ISD::RET_FLAG:           return "MSP430ISD::RET_FLAG";
773   case MSP430ISD::RRA:                return "MSP430ISD::RRA";
774   case MSP430ISD::RLA:                return "MSP430ISD::RLA";
775   case MSP430ISD::RRC:                return "MSP430ISD::RRC";
776   case MSP430ISD::CALL:               return "MSP430ISD::CALL";
777   case MSP430ISD::Wrapper:            return "MSP430ISD::Wrapper";
778   case MSP430ISD::BR_CC:              return "MSP430ISD::BR_CC";
779   case MSP430ISD::CMP:                return "MSP430ISD::CMP";
780   case MSP430ISD::SELECT_CC:          return "MSP430ISD::SELECT_CC";
781   }
782 }
783
784 //===----------------------------------------------------------------------===//
785 //  Other Lowering Code
786 //===----------------------------------------------------------------------===//
787
788 MachineBasicBlock*
789 MSP430TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
790                                                   MachineBasicBlock *BB,
791                    DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
792   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
793   DebugLoc dl = MI->getDebugLoc();
794   assert((MI->getOpcode() == MSP430::Select16 ||
795           MI->getOpcode() == MSP430::Select8) &&
796          "Unexpected instr type to insert");
797
798   // To "insert" a SELECT instruction, we actually have to insert the diamond
799   // control-flow pattern.  The incoming instruction knows the destination vreg
800   // to set, the condition code register to branch on, the true/false values to
801   // select between, and a branch opcode to use.
802   const BasicBlock *LLVM_BB = BB->getBasicBlock();
803   MachineFunction::iterator I = BB;
804   ++I;
805
806   //  thisMBB:
807   //  ...
808   //   TrueVal = ...
809   //   cmpTY ccX, r1, r2
810   //   jCC copy1MBB
811   //   fallthrough --> copy0MBB
812   MachineBasicBlock *thisMBB = BB;
813   MachineFunction *F = BB->getParent();
814   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
815   MachineBasicBlock *copy1MBB = F->CreateMachineBasicBlock(LLVM_BB);
816   BuildMI(BB, dl, TII.get(MSP430::JCC))
817     .addMBB(copy1MBB)
818     .addImm(MI->getOperand(3).getImm());
819   F->insert(I, copy0MBB);
820   F->insert(I, copy1MBB);
821   // Inform sdisel of the edge changes.
822   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(), 
823          SE = BB->succ_end(); SI != SE; ++SI)
824     EM->insert(std::make_pair(*SI, copy1MBB));
825   // Update machine-CFG edges by transferring all successors of the current
826   // block to the new block which will contain the Phi node for the select.
827   copy1MBB->transferSuccessors(BB);
828   // Next, add the true and fallthrough blocks as its successors.
829   BB->addSuccessor(copy0MBB);
830   BB->addSuccessor(copy1MBB);
831
832   //  copy0MBB:
833   //   %FalseValue = ...
834   //   # fallthrough to copy1MBB
835   BB = copy0MBB;
836
837   // Update machine-CFG edges
838   BB->addSuccessor(copy1MBB);
839
840   //  copy1MBB:
841   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
842   //  ...
843   BB = copy1MBB;
844   BuildMI(BB, dl, TII.get(MSP430::PHI),
845           MI->getOperand(0).getReg())
846     .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
847     .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
848
849   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
850   return BB;
851 }