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