Move TargetData to DataLayout.
[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 "MSP430MachineFunctionInfo.h"
19 #include "MSP430TargetMachine.h"
20 #include "MSP430Subtarget.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/Intrinsics.h"
24 #include "llvm/CallingConv.h"
25 #include "llvm/GlobalVariable.h"
26 #include "llvm/GlobalAlias.h"
27 #include "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/SelectionDAGISel.h"
33 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
34 #include "llvm/CodeGen/ValueTypes.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/raw_ostream.h"
39 using namespace llvm;
40
41 typedef enum {
42   NoHWMult,
43   HWMultIntr,
44   HWMultNoIntr
45 } HWMultUseMode;
46
47 static cl::opt<HWMultUseMode>
48 HWMultMode("msp430-hwmult-mode",
49            cl::desc("Hardware multiplier use mode"),
50            cl::init(HWMultNoIntr),
51            cl::values(
52              clEnumValN(NoHWMult, "no",
53                 "Do not use hardware multiplier"),
54              clEnumValN(HWMultIntr, "interrupts",
55                 "Assume hardware multiplier can be used inside interrupts"),
56              clEnumValN(HWMultNoIntr, "use",
57                 "Assume hardware multiplier cannot be used inside interrupts"),
58              clEnumValEnd));
59
60 MSP430TargetLowering::MSP430TargetLowering(MSP430TargetMachine &tm) :
61   TargetLowering(tm, new TargetLoweringObjectFileELF()),
62   Subtarget(*tm.getSubtargetImpl()) {
63
64   TD = getDataLayout();
65
66   // Set up the register classes.
67   addRegisterClass(MVT::i8,  &MSP430::GR8RegClass);
68   addRegisterClass(MVT::i16, &MSP430::GR16RegClass);
69
70   // Compute derived properties from the register classes
71   computeRegisterProperties();
72
73   // Provide all sorts of operation actions
74
75   // Division is expensive
76   setIntDivIsCheap(false);
77
78   setStackPointerRegisterToSaveRestore(MSP430::SPW);
79   setBooleanContents(ZeroOrOneBooleanContent);
80   setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
81
82   // We have post-incremented loads / stores.
83   setIndexedLoadAction(ISD::POST_INC, MVT::i8, Legal);
84   setIndexedLoadAction(ISD::POST_INC, MVT::i16, Legal);
85
86   setLoadExtAction(ISD::EXTLOAD,  MVT::i1,  Promote);
87   setLoadExtAction(ISD::SEXTLOAD, MVT::i1,  Promote);
88   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
89   setLoadExtAction(ISD::SEXTLOAD, MVT::i8,  Expand);
90   setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Expand);
91
92   // We don't have any truncstores
93   setTruncStoreAction(MVT::i16, MVT::i8, Expand);
94
95   setOperationAction(ISD::SRA,              MVT::i8,    Custom);
96   setOperationAction(ISD::SHL,              MVT::i8,    Custom);
97   setOperationAction(ISD::SRL,              MVT::i8,    Custom);
98   setOperationAction(ISD::SRA,              MVT::i16,   Custom);
99   setOperationAction(ISD::SHL,              MVT::i16,   Custom);
100   setOperationAction(ISD::SRL,              MVT::i16,   Custom);
101   setOperationAction(ISD::ROTL,             MVT::i8,    Expand);
102   setOperationAction(ISD::ROTR,             MVT::i8,    Expand);
103   setOperationAction(ISD::ROTL,             MVT::i16,   Expand);
104   setOperationAction(ISD::ROTR,             MVT::i16,   Expand);
105   setOperationAction(ISD::GlobalAddress,    MVT::i16,   Custom);
106   setOperationAction(ISD::ExternalSymbol,   MVT::i16,   Custom);
107   setOperationAction(ISD::BlockAddress,     MVT::i16,   Custom);
108   setOperationAction(ISD::BR_JT,            MVT::Other, Expand);
109   setOperationAction(ISD::BR_CC,            MVT::i8,    Custom);
110   setOperationAction(ISD::BR_CC,            MVT::i16,   Custom);
111   setOperationAction(ISD::BRCOND,           MVT::Other, Expand);
112   setOperationAction(ISD::SETCC,            MVT::i8,    Custom);
113   setOperationAction(ISD::SETCC,            MVT::i16,   Custom);
114   setOperationAction(ISD::SELECT,           MVT::i8,    Expand);
115   setOperationAction(ISD::SELECT,           MVT::i16,   Expand);
116   setOperationAction(ISD::SELECT_CC,        MVT::i8,    Custom);
117   setOperationAction(ISD::SELECT_CC,        MVT::i16,   Custom);
118   setOperationAction(ISD::SIGN_EXTEND,      MVT::i16,   Custom);
119   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i8, Expand);
120   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i16, Expand);
121
122   setOperationAction(ISD::CTTZ,             MVT::i8,    Expand);
123   setOperationAction(ISD::CTTZ,             MVT::i16,   Expand);
124   setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::i8,    Expand);
125   setOperationAction(ISD::CTTZ_ZERO_UNDEF,  MVT::i16,   Expand);
126   setOperationAction(ISD::CTLZ,             MVT::i8,    Expand);
127   setOperationAction(ISD::CTLZ,             MVT::i16,   Expand);
128   setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::i8,    Expand);
129   setOperationAction(ISD::CTLZ_ZERO_UNDEF,  MVT::i16,   Expand);
130   setOperationAction(ISD::CTPOP,            MVT::i8,    Expand);
131   setOperationAction(ISD::CTPOP,            MVT::i16,   Expand);
132
133   setOperationAction(ISD::SHL_PARTS,        MVT::i8,    Expand);
134   setOperationAction(ISD::SHL_PARTS,        MVT::i16,   Expand);
135   setOperationAction(ISD::SRL_PARTS,        MVT::i8,    Expand);
136   setOperationAction(ISD::SRL_PARTS,        MVT::i16,   Expand);
137   setOperationAction(ISD::SRA_PARTS,        MVT::i8,    Expand);
138   setOperationAction(ISD::SRA_PARTS,        MVT::i16,   Expand);
139
140   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1,   Expand);
141
142   // FIXME: Implement efficiently multiplication by a constant
143   setOperationAction(ISD::MUL,              MVT::i8,    Expand);
144   setOperationAction(ISD::MULHS,            MVT::i8,    Expand);
145   setOperationAction(ISD::MULHU,            MVT::i8,    Expand);
146   setOperationAction(ISD::SMUL_LOHI,        MVT::i8,    Expand);
147   setOperationAction(ISD::UMUL_LOHI,        MVT::i8,    Expand);
148   setOperationAction(ISD::MUL,              MVT::i16,   Expand);
149   setOperationAction(ISD::MULHS,            MVT::i16,   Expand);
150   setOperationAction(ISD::MULHU,            MVT::i16,   Expand);
151   setOperationAction(ISD::SMUL_LOHI,        MVT::i16,   Expand);
152   setOperationAction(ISD::UMUL_LOHI,        MVT::i16,   Expand);
153
154   setOperationAction(ISD::UDIV,             MVT::i8,    Expand);
155   setOperationAction(ISD::UDIVREM,          MVT::i8,    Expand);
156   setOperationAction(ISD::UREM,             MVT::i8,    Expand);
157   setOperationAction(ISD::SDIV,             MVT::i8,    Expand);
158   setOperationAction(ISD::SDIVREM,          MVT::i8,    Expand);
159   setOperationAction(ISD::SREM,             MVT::i8,    Expand);
160   setOperationAction(ISD::UDIV,             MVT::i16,   Expand);
161   setOperationAction(ISD::UDIVREM,          MVT::i16,   Expand);
162   setOperationAction(ISD::UREM,             MVT::i16,   Expand);
163   setOperationAction(ISD::SDIV,             MVT::i16,   Expand);
164   setOperationAction(ISD::SDIVREM,          MVT::i16,   Expand);
165   setOperationAction(ISD::SREM,             MVT::i16,   Expand);
166
167   // Libcalls names.
168   if (HWMultMode == HWMultIntr) {
169     setLibcallName(RTLIB::MUL_I8,  "__mulqi3hw");
170     setLibcallName(RTLIB::MUL_I16, "__mulhi3hw");
171   } else if (HWMultMode == HWMultNoIntr) {
172     setLibcallName(RTLIB::MUL_I8,  "__mulqi3hw_noint");
173     setLibcallName(RTLIB::MUL_I16, "__mulhi3hw_noint");
174   }
175
176   setMinFunctionAlignment(1);
177   setPrefFunctionAlignment(2);
178 }
179
180 SDValue MSP430TargetLowering::LowerOperation(SDValue Op,
181                                              SelectionDAG &DAG) const {
182   switch (Op.getOpcode()) {
183   case ISD::SHL: // FALLTHROUGH
184   case ISD::SRL:
185   case ISD::SRA:              return LowerShifts(Op, DAG);
186   case ISD::GlobalAddress:    return LowerGlobalAddress(Op, DAG);
187   case ISD::BlockAddress:     return LowerBlockAddress(Op, DAG);
188   case ISD::ExternalSymbol:   return LowerExternalSymbol(Op, DAG);
189   case ISD::SETCC:            return LowerSETCC(Op, DAG);
190   case ISD::BR_CC:            return LowerBR_CC(Op, DAG);
191   case ISD::SELECT_CC:        return LowerSELECT_CC(Op, DAG);
192   case ISD::SIGN_EXTEND:      return LowerSIGN_EXTEND(Op, DAG);
193   case ISD::RETURNADDR:       return LowerRETURNADDR(Op, DAG);
194   case ISD::FRAMEADDR:        return LowerFRAMEADDR(Op, DAG);
195   default:
196     llvm_unreachable("unimplemented operand");
197   }
198 }
199
200 //===----------------------------------------------------------------------===//
201 //                       MSP430 Inline Assembly Support
202 //===----------------------------------------------------------------------===//
203
204 /// getConstraintType - Given a constraint letter, return the type of
205 /// constraint it is for this target.
206 TargetLowering::ConstraintType
207 MSP430TargetLowering::getConstraintType(const std::string &Constraint) const {
208   if (Constraint.size() == 1) {
209     switch (Constraint[0]) {
210     case 'r':
211       return C_RegisterClass;
212     default:
213       break;
214     }
215   }
216   return TargetLowering::getConstraintType(Constraint);
217 }
218
219 std::pair<unsigned, const TargetRegisterClass*>
220 MSP430TargetLowering::
221 getRegForInlineAsmConstraint(const std::string &Constraint,
222                              EVT VT) const {
223   if (Constraint.size() == 1) {
224     // GCC Constraint Letters
225     switch (Constraint[0]) {
226     default: break;
227     case 'r':   // GENERAL_REGS
228       if (VT == MVT::i8)
229         return std::make_pair(0U, &MSP430::GR8RegClass);
230
231       return std::make_pair(0U, &MSP430::GR16RegClass);
232     }
233   }
234
235   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
236 }
237
238 //===----------------------------------------------------------------------===//
239 //                      Calling Convention Implementation
240 //===----------------------------------------------------------------------===//
241
242 #include "MSP430GenCallingConv.inc"
243
244 SDValue
245 MSP430TargetLowering::LowerFormalArguments(SDValue Chain,
246                                            CallingConv::ID CallConv,
247                                            bool isVarArg,
248                                            const SmallVectorImpl<ISD::InputArg>
249                                              &Ins,
250                                            DebugLoc dl,
251                                            SelectionDAG &DAG,
252                                            SmallVectorImpl<SDValue> &InVals)
253                                              const {
254
255   switch (CallConv) {
256   default:
257     llvm_unreachable("Unsupported calling convention");
258   case CallingConv::C:
259   case CallingConv::Fast:
260     return LowerCCCArguments(Chain, CallConv, isVarArg, Ins, dl, DAG, InVals);
261   case CallingConv::MSP430_INTR:
262     if (Ins.empty())
263       return Chain;
264     report_fatal_error("ISRs cannot have arguments");
265   }
266 }
267
268 SDValue
269 MSP430TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
270                                 SmallVectorImpl<SDValue> &InVals) const {
271   SelectionDAG &DAG                     = CLI.DAG;
272   DebugLoc &dl                          = CLI.DL;
273   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
274   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
275   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
276   SDValue Chain                         = CLI.Chain;
277   SDValue Callee                        = CLI.Callee;
278   bool &isTailCall                      = CLI.IsTailCall;
279   CallingConv::ID CallConv              = CLI.CallConv;
280   bool isVarArg                         = CLI.IsVarArg;
281
282   // MSP430 target does not yet support tail call optimization.
283   isTailCall = false;
284
285   switch (CallConv) {
286   default:
287     llvm_unreachable("Unsupported calling convention");
288   case CallingConv::Fast:
289   case CallingConv::C:
290     return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
291                           Outs, OutVals, Ins, dl, DAG, InVals);
292   case CallingConv::MSP430_INTR:
293     report_fatal_error("ISRs cannot be called directly");
294   }
295 }
296
297 /// LowerCCCArguments - transform physical registers into virtual registers and
298 /// generate load operations for arguments places on the stack.
299 // FIXME: struct return stuff
300 // FIXME: varargs
301 SDValue
302 MSP430TargetLowering::LowerCCCArguments(SDValue Chain,
303                                         CallingConv::ID CallConv,
304                                         bool isVarArg,
305                                         const SmallVectorImpl<ISD::InputArg>
306                                           &Ins,
307                                         DebugLoc dl,
308                                         SelectionDAG &DAG,
309                                         SmallVectorImpl<SDValue> &InVals)
310                                           const {
311   MachineFunction &MF = DAG.getMachineFunction();
312   MachineFrameInfo *MFI = MF.getFrameInfo();
313   MachineRegisterInfo &RegInfo = MF.getRegInfo();
314
315   // Assign locations to all of the incoming arguments.
316   SmallVector<CCValAssign, 16> ArgLocs;
317   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
318                  getTargetMachine(), ArgLocs, *DAG.getContext());
319   CCInfo.AnalyzeFormalArguments(Ins, CC_MSP430);
320
321   assert(!isVarArg && "Varargs not supported yet");
322
323   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
324     CCValAssign &VA = ArgLocs[i];
325     if (VA.isRegLoc()) {
326       // Arguments passed in registers
327       EVT RegVT = VA.getLocVT();
328       switch (RegVT.getSimpleVT().SimpleTy) {
329       default:
330         {
331 #ifndef NDEBUG
332           errs() << "LowerFormalArguments Unhandled argument type: "
333                << RegVT.getSimpleVT().SimpleTy << "\n";
334 #endif
335           llvm_unreachable(0);
336         }
337       case MVT::i16:
338         unsigned VReg = RegInfo.createVirtualRegister(&MSP430::GR16RegClass);
339         RegInfo.addLiveIn(VA.getLocReg(), VReg);
340         SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
341
342         // If this is an 8-bit value, it is really passed promoted to 16
343         // bits. Insert an assert[sz]ext to capture this, then truncate to the
344         // right size.
345         if (VA.getLocInfo() == CCValAssign::SExt)
346           ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
347                                  DAG.getValueType(VA.getValVT()));
348         else if (VA.getLocInfo() == CCValAssign::ZExt)
349           ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
350                                  DAG.getValueType(VA.getValVT()));
351
352         if (VA.getLocInfo() != CCValAssign::Full)
353           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
354
355         InVals.push_back(ArgValue);
356       }
357     } else {
358       // Sanity check
359       assert(VA.isMemLoc());
360       // Load the argument to a virtual register
361       unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
362       if (ObjSize > 2) {
363         errs() << "LowerFormalArguments Unhandled argument type: "
364              << EVT(VA.getLocVT()).getEVTString()
365              << "\n";
366       }
367       // Create the frame index object for this incoming parameter...
368       int FI = MFI->CreateFixedObject(ObjSize, VA.getLocMemOffset(), true);
369
370       // Create the SelectionDAG nodes corresponding to a load
371       //from this parameter
372       SDValue FIN = DAG.getFrameIndex(FI, MVT::i16);
373       InVals.push_back(DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
374                                    MachinePointerInfo::getFixedStack(FI),
375                                    false, false, false, 0));
376     }
377   }
378
379   return Chain;
380 }
381
382 SDValue
383 MSP430TargetLowering::LowerReturn(SDValue Chain,
384                                   CallingConv::ID CallConv, bool isVarArg,
385                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
386                                   const SmallVectorImpl<SDValue> &OutVals,
387                                   DebugLoc dl, SelectionDAG &DAG) const {
388
389   // CCValAssign - represent the assignment of the return value to a location
390   SmallVector<CCValAssign, 16> RVLocs;
391
392   // ISRs cannot return any value.
393   if (CallConv == CallingConv::MSP430_INTR && !Outs.empty())
394     report_fatal_error("ISRs cannot return any value");
395
396   // CCState - Info about the registers and stack slot.
397   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
398                  getTargetMachine(), RVLocs, *DAG.getContext());
399
400   // Analize return values.
401   CCInfo.AnalyzeReturn(Outs, RetCC_MSP430);
402
403   // If this is the first return lowered for this function, add the regs to the
404   // liveout set for the function.
405   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
406     for (unsigned i = 0; i != RVLocs.size(); ++i)
407       if (RVLocs[i].isRegLoc())
408         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
409   }
410
411   SDValue Flag;
412
413   // Copy the result values into the output registers.
414   for (unsigned i = 0; i != RVLocs.size(); ++i) {
415     CCValAssign &VA = RVLocs[i];
416     assert(VA.isRegLoc() && "Can only return in registers!");
417
418     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
419                              OutVals[i], Flag);
420
421     // Guarantee that all emitted copies are stuck together,
422     // avoiding something bad.
423     Flag = Chain.getValue(1);
424   }
425
426   unsigned Opc = (CallConv == CallingConv::MSP430_INTR ?
427                   MSP430ISD::RETI_FLAG : MSP430ISD::RET_FLAG);
428
429   if (Flag.getNode())
430     return DAG.getNode(Opc, dl, MVT::Other, Chain, Flag);
431
432   // Return Void
433   return DAG.getNode(Opc, dl, MVT::Other, Chain);
434 }
435
436 /// LowerCCCCallTo - functions arguments are copied from virtual regs to
437 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
438 /// TODO: sret.
439 SDValue
440 MSP430TargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
441                                      CallingConv::ID CallConv, bool isVarArg,
442                                      bool isTailCall,
443                                      const SmallVectorImpl<ISD::OutputArg>
444                                        &Outs,
445                                      const SmallVectorImpl<SDValue> &OutVals,
446                                      const SmallVectorImpl<ISD::InputArg> &Ins,
447                                      DebugLoc dl, SelectionDAG &DAG,
448                                      SmallVectorImpl<SDValue> &InVals) const {
449   // Analyze operands of the call, assigning locations to each operand.
450   SmallVector<CCValAssign, 16> ArgLocs;
451   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
452                  getTargetMachine(), ArgLocs, *DAG.getContext());
453
454   CCInfo.AnalyzeCallOperands(Outs, CC_MSP430);
455
456   // Get a count of how many bytes are to be pushed on the stack.
457   unsigned NumBytes = CCInfo.getNextStackOffset();
458
459   Chain = DAG.getCALLSEQ_START(Chain ,DAG.getConstant(NumBytes,
460                                                       getPointerTy(), true));
461
462   SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
463   SmallVector<SDValue, 12> MemOpChains;
464   SDValue StackPtr;
465
466   // Walk the register/memloc assignments, inserting copies/loads.
467   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
468     CCValAssign &VA = ArgLocs[i];
469
470     SDValue Arg = OutVals[i];
471
472     // Promote the value if needed.
473     switch (VA.getLocInfo()) {
474       default: llvm_unreachable("Unknown loc info!");
475       case CCValAssign::Full: break;
476       case CCValAssign::SExt:
477         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
478         break;
479       case CCValAssign::ZExt:
480         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
481         break;
482       case CCValAssign::AExt:
483         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
484         break;
485     }
486
487     // Arguments that can be passed on register must be kept at RegsToPass
488     // vector
489     if (VA.isRegLoc()) {
490       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
491     } else {
492       assert(VA.isMemLoc());
493
494       if (StackPtr.getNode() == 0)
495         StackPtr = DAG.getCopyFromReg(Chain, dl, MSP430::SPW, getPointerTy());
496
497       SDValue PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(),
498                                    StackPtr,
499                                    DAG.getIntPtrConstant(VA.getLocMemOffset()));
500
501
502       MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
503                                          MachinePointerInfo(),false, false, 0));
504     }
505   }
506
507   // Transform all store nodes into one single node because all store nodes are
508   // independent of each other.
509   if (!MemOpChains.empty())
510     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
511                         &MemOpChains[0], MemOpChains.size());
512
513   // Build a sequence of copy-to-reg nodes chained together with token chain and
514   // flag operands which copy the outgoing args into registers.  The InFlag in
515   // necessary since all emitted instructions must be stuck together.
516   SDValue InFlag;
517   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
518     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
519                              RegsToPass[i].second, InFlag);
520     InFlag = Chain.getValue(1);
521   }
522
523   // If the callee is a GlobalAddress node (quite common, every direct call is)
524   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
525   // Likewise ExternalSymbol -> TargetExternalSymbol.
526   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
527     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i16);
528   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
529     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i16);
530
531   // Returns a chain & a flag for retval copy to use.
532   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
533   SmallVector<SDValue, 8> Ops;
534   Ops.push_back(Chain);
535   Ops.push_back(Callee);
536
537   // Add argument registers to the end of the list so that they are
538   // known live into the call.
539   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
540     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
541                                   RegsToPass[i].second.getValueType()));
542
543   if (InFlag.getNode())
544     Ops.push_back(InFlag);
545
546   Chain = DAG.getNode(MSP430ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
547   InFlag = Chain.getValue(1);
548
549   // Create the CALLSEQ_END node.
550   Chain = DAG.getCALLSEQ_END(Chain,
551                              DAG.getConstant(NumBytes, getPointerTy(), true),
552                              DAG.getConstant(0, getPointerTy(), true),
553                              InFlag);
554   InFlag = Chain.getValue(1);
555
556   // Handle result values, copying them out of physregs into vregs that we
557   // return.
558   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl,
559                          DAG, InVals);
560 }
561
562 /// LowerCallResult - Lower the result values of a call into the
563 /// appropriate copies out of appropriate physical registers.
564 ///
565 SDValue
566 MSP430TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
567                                       CallingConv::ID CallConv, bool isVarArg,
568                                       const SmallVectorImpl<ISD::InputArg> &Ins,
569                                       DebugLoc dl, SelectionDAG &DAG,
570                                       SmallVectorImpl<SDValue> &InVals) const {
571
572   // Assign locations to each value returned by this call.
573   SmallVector<CCValAssign, 16> RVLocs;
574   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
575                  getTargetMachine(), RVLocs, *DAG.getContext());
576
577   CCInfo.AnalyzeCallResult(Ins, RetCC_MSP430);
578
579   // Copy all of the result registers out of their specified physreg.
580   for (unsigned i = 0; i != RVLocs.size(); ++i) {
581     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
582                                RVLocs[i].getValVT(), InFlag).getValue(1);
583     InFlag = Chain.getValue(2);
584     InVals.push_back(Chain.getValue(0));
585   }
586
587   return Chain;
588 }
589
590 SDValue MSP430TargetLowering::LowerShifts(SDValue Op,
591                                           SelectionDAG &DAG) const {
592   unsigned Opc = Op.getOpcode();
593   SDNode* N = Op.getNode();
594   EVT VT = Op.getValueType();
595   DebugLoc dl = N->getDebugLoc();
596
597   // Expand non-constant shifts to loops:
598   if (!isa<ConstantSDNode>(N->getOperand(1)))
599     switch (Opc) {
600     default: llvm_unreachable("Invalid shift opcode!");
601     case ISD::SHL:
602       return DAG.getNode(MSP430ISD::SHL, dl,
603                          VT, N->getOperand(0), N->getOperand(1));
604     case ISD::SRA:
605       return DAG.getNode(MSP430ISD::SRA, dl,
606                          VT, N->getOperand(0), N->getOperand(1));
607     case ISD::SRL:
608       return DAG.getNode(MSP430ISD::SRL, dl,
609                          VT, N->getOperand(0), N->getOperand(1));
610     }
611
612   uint64_t ShiftAmount = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
613
614   // Expand the stuff into sequence of shifts.
615   // FIXME: for some shift amounts this might be done better!
616   // E.g.: foo >> (8 + N) => sxt(swpb(foo)) >> N
617   SDValue Victim = N->getOperand(0);
618
619   if (Opc == ISD::SRL && ShiftAmount) {
620     // Emit a special goodness here:
621     // srl A, 1 => clrc; rrc A
622     Victim = DAG.getNode(MSP430ISD::RRC, dl, VT, Victim);
623     ShiftAmount -= 1;
624   }
625
626   while (ShiftAmount--)
627     Victim = DAG.getNode((Opc == ISD::SHL ? MSP430ISD::RLA : MSP430ISD::RRA),
628                          dl, VT, Victim);
629
630   return Victim;
631 }
632
633 SDValue MSP430TargetLowering::LowerGlobalAddress(SDValue Op,
634                                                  SelectionDAG &DAG) const {
635   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
636   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
637
638   // Create the TargetGlobalAddress node, folding in the constant offset.
639   SDValue Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
640                                               getPointerTy(), Offset);
641   return DAG.getNode(MSP430ISD::Wrapper, Op.getDebugLoc(),
642                      getPointerTy(), Result);
643 }
644
645 SDValue MSP430TargetLowering::LowerExternalSymbol(SDValue Op,
646                                                   SelectionDAG &DAG) const {
647   DebugLoc dl = Op.getDebugLoc();
648   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
649   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
650
651   return DAG.getNode(MSP430ISD::Wrapper, dl, getPointerTy(), Result);
652 }
653
654 SDValue MSP430TargetLowering::LowerBlockAddress(SDValue Op,
655                                                 SelectionDAG &DAG) const {
656   DebugLoc dl = Op.getDebugLoc();
657   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
658   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy());
659
660   return DAG.getNode(MSP430ISD::Wrapper, dl, getPointerTy(), Result);
661 }
662
663 static SDValue EmitCMP(SDValue &LHS, SDValue &RHS, SDValue &TargetCC,
664                        ISD::CondCode CC,
665                        DebugLoc dl, SelectionDAG &DAG) {
666   // FIXME: Handle bittests someday
667   assert(!LHS.getValueType().isFloatingPoint() && "We don't handle FP yet");
668
669   // FIXME: Handle jump negative someday
670   MSP430CC::CondCodes TCC = MSP430CC::COND_INVALID;
671   switch (CC) {
672   default: llvm_unreachable("Invalid integer condition!");
673   case ISD::SETEQ:
674     TCC = MSP430CC::COND_E;     // aka COND_Z
675     // Minor optimization: if LHS is a constant, swap operands, then the
676     // constant can be folded into comparison.
677     if (LHS.getOpcode() == ISD::Constant)
678       std::swap(LHS, RHS);
679     break;
680   case ISD::SETNE:
681     TCC = MSP430CC::COND_NE;    // aka COND_NZ
682     // Minor optimization: if LHS is a constant, swap operands, then the
683     // constant can be folded into comparison.
684     if (LHS.getOpcode() == ISD::Constant)
685       std::swap(LHS, RHS);
686     break;
687   case ISD::SETULE:
688     std::swap(LHS, RHS);        // FALLTHROUGH
689   case ISD::SETUGE:
690     // Turn lhs u>= rhs with lhs constant into rhs u< lhs+1, this allows us to
691     // fold constant into instruction.
692     if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
693       LHS = RHS;
694       RHS = DAG.getConstant(C->getSExtValue() + 1, C->getValueType(0));
695       TCC = MSP430CC::COND_LO;
696       break;
697     }
698     TCC = MSP430CC::COND_HS;    // aka COND_C
699     break;
700   case ISD::SETUGT:
701     std::swap(LHS, RHS);        // FALLTHROUGH
702   case ISD::SETULT:
703     // Turn lhs u< rhs with lhs constant into rhs u>= lhs+1, this allows us to
704     // fold constant into instruction.
705     if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
706       LHS = RHS;
707       RHS = DAG.getConstant(C->getSExtValue() + 1, C->getValueType(0));
708       TCC = MSP430CC::COND_HS;
709       break;
710     }
711     TCC = MSP430CC::COND_LO;    // aka COND_NC
712     break;
713   case ISD::SETLE:
714     std::swap(LHS, RHS);        // FALLTHROUGH
715   case ISD::SETGE:
716     // Turn lhs >= rhs with lhs constant into rhs < lhs+1, this allows us to
717     // fold constant into instruction.
718     if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
719       LHS = RHS;
720       RHS = DAG.getConstant(C->getSExtValue() + 1, C->getValueType(0));
721       TCC = MSP430CC::COND_L;
722       break;
723     }
724     TCC = MSP430CC::COND_GE;
725     break;
726   case ISD::SETGT:
727     std::swap(LHS, RHS);        // FALLTHROUGH
728   case ISD::SETLT:
729     // Turn lhs < rhs with lhs constant into rhs >= lhs+1, this allows us to
730     // fold constant into instruction.
731     if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
732       LHS = RHS;
733       RHS = DAG.getConstant(C->getSExtValue() + 1, C->getValueType(0));
734       TCC = MSP430CC::COND_GE;
735       break;
736     }
737     TCC = MSP430CC::COND_L;
738     break;
739   }
740
741   TargetCC = DAG.getConstant(TCC, MVT::i8);
742   return DAG.getNode(MSP430ISD::CMP, dl, MVT::Glue, LHS, RHS);
743 }
744
745
746 SDValue MSP430TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
747   SDValue Chain = Op.getOperand(0);
748   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
749   SDValue LHS   = Op.getOperand(2);
750   SDValue RHS   = Op.getOperand(3);
751   SDValue Dest  = Op.getOperand(4);
752   DebugLoc dl   = Op.getDebugLoc();
753
754   SDValue TargetCC;
755   SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
756
757   return DAG.getNode(MSP430ISD::BR_CC, dl, Op.getValueType(),
758                      Chain, Dest, TargetCC, Flag);
759 }
760
761 SDValue MSP430TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
762   SDValue LHS   = Op.getOperand(0);
763   SDValue RHS   = Op.getOperand(1);
764   DebugLoc dl   = Op.getDebugLoc();
765
766   // If we are doing an AND and testing against zero, then the CMP
767   // will not be generated.  The AND (or BIT) will generate the condition codes,
768   // but they are different from CMP.
769   // FIXME: since we're doing a post-processing, use a pseudoinstr here, so
770   // lowering & isel wouldn't diverge.
771   bool andCC = false;
772   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
773     if (RHSC->isNullValue() && LHS.hasOneUse() &&
774         (LHS.getOpcode() == ISD::AND ||
775          (LHS.getOpcode() == ISD::TRUNCATE &&
776           LHS.getOperand(0).getOpcode() == ISD::AND))) {
777       andCC = true;
778     }
779   }
780   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
781   SDValue TargetCC;
782   SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
783
784   // Get the condition codes directly from the status register, if its easy.
785   // Otherwise a branch will be generated.  Note that the AND and BIT
786   // instructions generate different flags than CMP, the carry bit can be used
787   // for NE/EQ.
788   bool Invert = false;
789   bool Shift = false;
790   bool Convert = true;
791   switch (cast<ConstantSDNode>(TargetCC)->getZExtValue()) {
792    default:
793     Convert = false;
794     break;
795    case MSP430CC::COND_HS:
796      // Res = SRW & 1, no processing is required
797      break;
798    case MSP430CC::COND_LO:
799      // Res = ~(SRW & 1)
800      Invert = true;
801      break;
802    case MSP430CC::COND_NE:
803      if (andCC) {
804        // C = ~Z, thus Res = SRW & 1, no processing is required
805      } else {
806        // Res = ~((SRW >> 1) & 1)
807        Shift = true;
808        Invert = true;
809      }
810      break;
811    case MSP430CC::COND_E:
812      Shift = true;
813      // C = ~Z for AND instruction, thus we can put Res = ~(SRW & 1), however,
814      // Res = (SRW >> 1) & 1 is 1 word shorter.
815      break;
816   }
817   EVT VT = Op.getValueType();
818   SDValue One  = DAG.getConstant(1, VT);
819   if (Convert) {
820     SDValue SR = DAG.getCopyFromReg(DAG.getEntryNode(), dl, MSP430::SRW,
821                                     MVT::i16, Flag);
822     if (Shift)
823       // FIXME: somewhere this is turned into a SRL, lower it MSP specific?
824       SR = DAG.getNode(ISD::SRA, dl, MVT::i16, SR, One);
825     SR = DAG.getNode(ISD::AND, dl, MVT::i16, SR, One);
826     if (Invert)
827       SR = DAG.getNode(ISD::XOR, dl, MVT::i16, SR, One);
828     return SR;
829   } else {
830     SDValue Zero = DAG.getConstant(0, VT);
831     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
832     SmallVector<SDValue, 4> Ops;
833     Ops.push_back(One);
834     Ops.push_back(Zero);
835     Ops.push_back(TargetCC);
836     Ops.push_back(Flag);
837     return DAG.getNode(MSP430ISD::SELECT_CC, dl, VTs, &Ops[0], Ops.size());
838   }
839 }
840
841 SDValue MSP430TargetLowering::LowerSELECT_CC(SDValue Op,
842                                              SelectionDAG &DAG) const {
843   SDValue LHS    = Op.getOperand(0);
844   SDValue RHS    = Op.getOperand(1);
845   SDValue TrueV  = Op.getOperand(2);
846   SDValue FalseV = Op.getOperand(3);
847   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
848   DebugLoc dl    = Op.getDebugLoc();
849
850   SDValue TargetCC;
851   SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
852
853   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
854   SmallVector<SDValue, 4> Ops;
855   Ops.push_back(TrueV);
856   Ops.push_back(FalseV);
857   Ops.push_back(TargetCC);
858   Ops.push_back(Flag);
859
860   return DAG.getNode(MSP430ISD::SELECT_CC, dl, VTs, &Ops[0], Ops.size());
861 }
862
863 SDValue MSP430TargetLowering::LowerSIGN_EXTEND(SDValue Op,
864                                                SelectionDAG &DAG) const {
865   SDValue Val = Op.getOperand(0);
866   EVT VT      = Op.getValueType();
867   DebugLoc dl = Op.getDebugLoc();
868
869   assert(VT == MVT::i16 && "Only support i16 for now!");
870
871   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT,
872                      DAG.getNode(ISD::ANY_EXTEND, dl, VT, Val),
873                      DAG.getValueType(Val.getValueType()));
874 }
875
876 SDValue
877 MSP430TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
878   MachineFunction &MF = DAG.getMachineFunction();
879   MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
880   int ReturnAddrIndex = FuncInfo->getRAIndex();
881
882   if (ReturnAddrIndex == 0) {
883     // Set up a frame object for the return address.
884     uint64_t SlotSize = TD->getPointerSize();
885     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
886                                                            true);
887     FuncInfo->setRAIndex(ReturnAddrIndex);
888   }
889
890   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
891 }
892
893 SDValue MSP430TargetLowering::LowerRETURNADDR(SDValue Op,
894                                               SelectionDAG &DAG) const {
895   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
896   MFI->setReturnAddressIsTaken(true);
897
898   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
899   DebugLoc dl = Op.getDebugLoc();
900
901   if (Depth > 0) {
902     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
903     SDValue Offset =
904       DAG.getConstant(TD->getPointerSize(), MVT::i16);
905     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
906                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
907                                    FrameAddr, Offset),
908                        MachinePointerInfo(), false, false, false, 0);
909   }
910
911   // Just load the return address.
912   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
913   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
914                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
915 }
916
917 SDValue MSP430TargetLowering::LowerFRAMEADDR(SDValue Op,
918                                              SelectionDAG &DAG) const {
919   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
920   MFI->setFrameAddressIsTaken(true);
921
922   EVT VT = Op.getValueType();
923   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
924   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
925   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
926                                          MSP430::FPW, VT);
927   while (Depth--)
928     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
929                             MachinePointerInfo(),
930                             false, false, false, 0);
931   return FrameAddr;
932 }
933
934 /// getPostIndexedAddressParts - returns true by value, base pointer and
935 /// offset pointer and addressing mode by reference if this node can be
936 /// combined with a load / store to form a post-indexed load / store.
937 bool MSP430TargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
938                                                       SDValue &Base,
939                                                       SDValue &Offset,
940                                                       ISD::MemIndexedMode &AM,
941                                                       SelectionDAG &DAG) const {
942
943   LoadSDNode *LD = cast<LoadSDNode>(N);
944   if (LD->getExtensionType() != ISD::NON_EXTLOAD)
945     return false;
946
947   EVT VT = LD->getMemoryVT();
948   if (VT != MVT::i8 && VT != MVT::i16)
949     return false;
950
951   if (Op->getOpcode() != ISD::ADD)
952     return false;
953
954   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
955     uint64_t RHSC = RHS->getZExtValue();
956     if ((VT == MVT::i16 && RHSC != 2) ||
957         (VT == MVT::i8 && RHSC != 1))
958       return false;
959
960     Base = Op->getOperand(0);
961     Offset = DAG.getConstant(RHSC, VT);
962     AM = ISD::POST_INC;
963     return true;
964   }
965
966   return false;
967 }
968
969
970 const char *MSP430TargetLowering::getTargetNodeName(unsigned Opcode) const {
971   switch (Opcode) {
972   default: return NULL;
973   case MSP430ISD::RET_FLAG:           return "MSP430ISD::RET_FLAG";
974   case MSP430ISD::RETI_FLAG:          return "MSP430ISD::RETI_FLAG";
975   case MSP430ISD::RRA:                return "MSP430ISD::RRA";
976   case MSP430ISD::RLA:                return "MSP430ISD::RLA";
977   case MSP430ISD::RRC:                return "MSP430ISD::RRC";
978   case MSP430ISD::CALL:               return "MSP430ISD::CALL";
979   case MSP430ISD::Wrapper:            return "MSP430ISD::Wrapper";
980   case MSP430ISD::BR_CC:              return "MSP430ISD::BR_CC";
981   case MSP430ISD::CMP:                return "MSP430ISD::CMP";
982   case MSP430ISD::SELECT_CC:          return "MSP430ISD::SELECT_CC";
983   case MSP430ISD::SHL:                return "MSP430ISD::SHL";
984   case MSP430ISD::SRA:                return "MSP430ISD::SRA";
985   }
986 }
987
988 bool MSP430TargetLowering::isTruncateFree(Type *Ty1,
989                                           Type *Ty2) const {
990   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
991     return false;
992
993   return (Ty1->getPrimitiveSizeInBits() > Ty2->getPrimitiveSizeInBits());
994 }
995
996 bool MSP430TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
997   if (!VT1.isInteger() || !VT2.isInteger())
998     return false;
999
1000   return (VT1.getSizeInBits() > VT2.getSizeInBits());
1001 }
1002
1003 bool MSP430TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
1004   // MSP430 implicitly zero-extends 8-bit results in 16-bit registers.
1005   return 0 && Ty1->isIntegerTy(8) && Ty2->isIntegerTy(16);
1006 }
1007
1008 bool MSP430TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
1009   // MSP430 implicitly zero-extends 8-bit results in 16-bit registers.
1010   return 0 && VT1 == MVT::i8 && VT2 == MVT::i16;
1011 }
1012
1013 //===----------------------------------------------------------------------===//
1014 //  Other Lowering Code
1015 //===----------------------------------------------------------------------===//
1016
1017 MachineBasicBlock*
1018 MSP430TargetLowering::EmitShiftInstr(MachineInstr *MI,
1019                                      MachineBasicBlock *BB) const {
1020   MachineFunction *F = BB->getParent();
1021   MachineRegisterInfo &RI = F->getRegInfo();
1022   DebugLoc dl = MI->getDebugLoc();
1023   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1024
1025   unsigned Opc;
1026   const TargetRegisterClass * RC;
1027   switch (MI->getOpcode()) {
1028   default: llvm_unreachable("Invalid shift opcode!");
1029   case MSP430::Shl8:
1030    Opc = MSP430::SHL8r1;
1031    RC = &MSP430::GR8RegClass;
1032    break;
1033   case MSP430::Shl16:
1034    Opc = MSP430::SHL16r1;
1035    RC = &MSP430::GR16RegClass;
1036    break;
1037   case MSP430::Sra8:
1038    Opc = MSP430::SAR8r1;
1039    RC = &MSP430::GR8RegClass;
1040    break;
1041   case MSP430::Sra16:
1042    Opc = MSP430::SAR16r1;
1043    RC = &MSP430::GR16RegClass;
1044    break;
1045   case MSP430::Srl8:
1046    Opc = MSP430::SAR8r1c;
1047    RC = &MSP430::GR8RegClass;
1048    break;
1049   case MSP430::Srl16:
1050    Opc = MSP430::SAR16r1c;
1051    RC = &MSP430::GR16RegClass;
1052    break;
1053   }
1054
1055   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1056   MachineFunction::iterator I = BB;
1057   ++I;
1058
1059   // Create loop block
1060   MachineBasicBlock *LoopBB = F->CreateMachineBasicBlock(LLVM_BB);
1061   MachineBasicBlock *RemBB  = F->CreateMachineBasicBlock(LLVM_BB);
1062
1063   F->insert(I, LoopBB);
1064   F->insert(I, RemBB);
1065
1066   // Update machine-CFG edges by transferring all successors of the current
1067   // block to the block containing instructions after shift.
1068   RemBB->splice(RemBB->begin(), BB,
1069                 llvm::next(MachineBasicBlock::iterator(MI)),
1070                 BB->end());
1071   RemBB->transferSuccessorsAndUpdatePHIs(BB);
1072
1073   // Add adges BB => LoopBB => RemBB, BB => RemBB, LoopBB => LoopBB
1074   BB->addSuccessor(LoopBB);
1075   BB->addSuccessor(RemBB);
1076   LoopBB->addSuccessor(RemBB);
1077   LoopBB->addSuccessor(LoopBB);
1078
1079   unsigned ShiftAmtReg = RI.createVirtualRegister(&MSP430::GR8RegClass);
1080   unsigned ShiftAmtReg2 = RI.createVirtualRegister(&MSP430::GR8RegClass);
1081   unsigned ShiftReg = RI.createVirtualRegister(RC);
1082   unsigned ShiftReg2 = RI.createVirtualRegister(RC);
1083   unsigned ShiftAmtSrcReg = MI->getOperand(2).getReg();
1084   unsigned SrcReg = MI->getOperand(1).getReg();
1085   unsigned DstReg = MI->getOperand(0).getReg();
1086
1087   // BB:
1088   // cmp 0, N
1089   // je RemBB
1090   BuildMI(BB, dl, TII.get(MSP430::CMP8ri))
1091     .addReg(ShiftAmtSrcReg).addImm(0);
1092   BuildMI(BB, dl, TII.get(MSP430::JCC))
1093     .addMBB(RemBB)
1094     .addImm(MSP430CC::COND_E);
1095
1096   // LoopBB:
1097   // ShiftReg = phi [%SrcReg, BB], [%ShiftReg2, LoopBB]
1098   // ShiftAmt = phi [%N, BB],      [%ShiftAmt2, LoopBB]
1099   // ShiftReg2 = shift ShiftReg
1100   // ShiftAmt2 = ShiftAmt - 1;
1101   BuildMI(LoopBB, dl, TII.get(MSP430::PHI), ShiftReg)
1102     .addReg(SrcReg).addMBB(BB)
1103     .addReg(ShiftReg2).addMBB(LoopBB);
1104   BuildMI(LoopBB, dl, TII.get(MSP430::PHI), ShiftAmtReg)
1105     .addReg(ShiftAmtSrcReg).addMBB(BB)
1106     .addReg(ShiftAmtReg2).addMBB(LoopBB);
1107   BuildMI(LoopBB, dl, TII.get(Opc), ShiftReg2)
1108     .addReg(ShiftReg);
1109   BuildMI(LoopBB, dl, TII.get(MSP430::SUB8ri), ShiftAmtReg2)
1110     .addReg(ShiftAmtReg).addImm(1);
1111   BuildMI(LoopBB, dl, TII.get(MSP430::JCC))
1112     .addMBB(LoopBB)
1113     .addImm(MSP430CC::COND_NE);
1114
1115   // RemBB:
1116   // DestReg = phi [%SrcReg, BB], [%ShiftReg, LoopBB]
1117   BuildMI(*RemBB, RemBB->begin(), dl, TII.get(MSP430::PHI), DstReg)
1118     .addReg(SrcReg).addMBB(BB)
1119     .addReg(ShiftReg2).addMBB(LoopBB);
1120
1121   MI->eraseFromParent();   // The pseudo instruction is gone now.
1122   return RemBB;
1123 }
1124
1125 MachineBasicBlock*
1126 MSP430TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1127                                                   MachineBasicBlock *BB) const {
1128   unsigned Opc = MI->getOpcode();
1129
1130   if (Opc == MSP430::Shl8 || Opc == MSP430::Shl16 ||
1131       Opc == MSP430::Sra8 || Opc == MSP430::Sra16 ||
1132       Opc == MSP430::Srl8 || Opc == MSP430::Srl16)
1133     return EmitShiftInstr(MI, BB);
1134
1135   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1136   DebugLoc dl = MI->getDebugLoc();
1137
1138   assert((Opc == MSP430::Select16 || Opc == MSP430::Select8) &&
1139          "Unexpected instr type to insert");
1140
1141   // To "insert" a SELECT instruction, we actually have to insert the diamond
1142   // control-flow pattern.  The incoming instruction knows the destination vreg
1143   // to set, the condition code register to branch on, the true/false values to
1144   // select between, and a branch opcode to use.
1145   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1146   MachineFunction::iterator I = BB;
1147   ++I;
1148
1149   //  thisMBB:
1150   //  ...
1151   //   TrueVal = ...
1152   //   cmpTY ccX, r1, r2
1153   //   jCC copy1MBB
1154   //   fallthrough --> copy0MBB
1155   MachineBasicBlock *thisMBB = BB;
1156   MachineFunction *F = BB->getParent();
1157   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1158   MachineBasicBlock *copy1MBB = F->CreateMachineBasicBlock(LLVM_BB);
1159   F->insert(I, copy0MBB);
1160   F->insert(I, copy1MBB);
1161   // Update machine-CFG edges by transferring all successors of the current
1162   // block to the new block which will contain the Phi node for the select.
1163   copy1MBB->splice(copy1MBB->begin(), BB,
1164                    llvm::next(MachineBasicBlock::iterator(MI)),
1165                    BB->end());
1166   copy1MBB->transferSuccessorsAndUpdatePHIs(BB);
1167   // Next, add the true and fallthrough blocks as its successors.
1168   BB->addSuccessor(copy0MBB);
1169   BB->addSuccessor(copy1MBB);
1170
1171   BuildMI(BB, dl, TII.get(MSP430::JCC))
1172     .addMBB(copy1MBB)
1173     .addImm(MI->getOperand(3).getImm());
1174
1175   //  copy0MBB:
1176   //   %FalseValue = ...
1177   //   # fallthrough to copy1MBB
1178   BB = copy0MBB;
1179
1180   // Update machine-CFG edges
1181   BB->addSuccessor(copy1MBB);
1182
1183   //  copy1MBB:
1184   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1185   //  ...
1186   BB = copy1MBB;
1187   BuildMI(*BB, BB->begin(), dl, TII.get(MSP430::PHI),
1188           MI->getOperand(0).getReg())
1189     .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
1190     .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
1191
1192   MI->eraseFromParent();   // The pseudo instruction is gone now.
1193   return BB;
1194 }