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