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