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