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