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