1 //===-- MSP430ISelLowering.cpp - MSP430 DAG Lowering Implementation ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the MSP430TargetLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "MSP430ISelLowering.h"
16 #include "MSP430MachineFunctionInfo.h"
17 #include "MSP430Subtarget.h"
18 #include "MSP430TargetMachine.h"
19 #include "llvm/CodeGen/CallingConvLower.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/SelectionDAGISel.h"
25 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
26 #include "llvm/CodeGen/ValueTypes.h"
27 #include "llvm/IR/CallingConv.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/GlobalAlias.h"
31 #include "llvm/IR/GlobalVariable.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
39 #define DEBUG_TYPE "msp430-lower"
47 static cl::opt<HWMultUseMode>
48 HWMultMode("msp430-hwmult-mode", cl::Hidden,
49 cl::desc("Hardware multiplier use mode"),
50 cl::init(HWMultNoIntr),
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"),
60 MSP430TargetLowering::MSP430TargetLowering(const TargetMachine &TM,
61 const MSP430Subtarget &STI)
62 : TargetLowering(TM) {
64 // Set up the register classes.
65 addRegisterClass(MVT::i8, &MSP430::GR8RegClass);
66 addRegisterClass(MVT::i16, &MSP430::GR16RegClass);
68 // Compute derived properties from the register classes
69 computeRegisterProperties(STI.getRegisterInfo());
71 // Provide all sorts of operation actions
73 // Division is expensive
74 setIntDivIsCheap(false);
76 setStackPointerRegisterToSaveRestore(MSP430::SP);
77 setBooleanContents(ZeroOrOneBooleanContent);
78 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
80 // We have post-incremented loads / stores.
81 setIndexedLoadAction(ISD::POST_INC, MVT::i8, Legal);
82 setIndexedLoadAction(ISD::POST_INC, MVT::i16, Legal);
84 for (MVT VT : MVT::integer_valuetypes()) {
85 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
86 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
87 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
88 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
89 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i16, Expand);
92 // We don't have any truncstores
93 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
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);
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);
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);
140 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
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);
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);
168 setOperationAction(ISD::VASTART, MVT::Other, Custom);
169 setOperationAction(ISD::VAARG, MVT::Other, Expand);
170 setOperationAction(ISD::VAEND, MVT::Other, Expand);
171 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
172 setOperationAction(ISD::JumpTable, MVT::i16, Custom);
175 if (HWMultMode == HWMultIntr) {
176 setLibcallName(RTLIB::MUL_I8, "__mulqi3hw");
177 setLibcallName(RTLIB::MUL_I16, "__mulhi3hw");
178 } else if (HWMultMode == HWMultNoIntr) {
179 setLibcallName(RTLIB::MUL_I8, "__mulqi3hw_noint");
180 setLibcallName(RTLIB::MUL_I16, "__mulhi3hw_noint");
183 setMinFunctionAlignment(1);
184 setPrefFunctionAlignment(2);
187 SDValue MSP430TargetLowering::LowerOperation(SDValue Op,
188 SelectionDAG &DAG) const {
189 switch (Op.getOpcode()) {
190 case ISD::SHL: // FALLTHROUGH
192 case ISD::SRA: return LowerShifts(Op, DAG);
193 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
194 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
195 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
196 case ISD::SETCC: return LowerSETCC(Op, DAG);
197 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
198 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
199 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
200 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
201 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
202 case ISD::VASTART: return LowerVASTART(Op, DAG);
203 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
205 llvm_unreachable("unimplemented operand");
209 //===----------------------------------------------------------------------===//
210 // MSP430 Inline Assembly Support
211 //===----------------------------------------------------------------------===//
213 /// getConstraintType - Given a constraint letter, return the type of
214 /// constraint it is for this target.
215 TargetLowering::ConstraintType
216 MSP430TargetLowering::getConstraintType(StringRef Constraint) const {
217 if (Constraint.size() == 1) {
218 switch (Constraint[0]) {
220 return C_RegisterClass;
225 return TargetLowering::getConstraintType(Constraint);
228 std::pair<unsigned, const TargetRegisterClass *>
229 MSP430TargetLowering::getRegForInlineAsmConstraint(
230 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
231 if (Constraint.size() == 1) {
232 // GCC Constraint Letters
233 switch (Constraint[0]) {
235 case 'r': // GENERAL_REGS
237 return std::make_pair(0U, &MSP430::GR8RegClass);
239 return std::make_pair(0U, &MSP430::GR16RegClass);
243 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
246 //===----------------------------------------------------------------------===//
247 // Calling Convention Implementation
248 //===----------------------------------------------------------------------===//
250 #include "MSP430GenCallingConv.inc"
252 /// For each argument in a function store the number of pieces it is composed
254 template<typename ArgT>
255 static void ParseFunctionArgs(const SmallVectorImpl<ArgT> &Args,
256 SmallVectorImpl<unsigned> &Out) {
257 unsigned CurrentArgIndex = ~0U;
258 for (unsigned i = 0, e = Args.size(); i != e; i++) {
259 if (CurrentArgIndex == Args[i].OrigArgIndex) {
268 static void AnalyzeVarArgs(CCState &State,
269 const SmallVectorImpl<ISD::OutputArg> &Outs) {
270 State.AnalyzeCallOperands(Outs, CC_MSP430_AssignStack);
273 static void AnalyzeVarArgs(CCState &State,
274 const SmallVectorImpl<ISD::InputArg> &Ins) {
275 State.AnalyzeFormalArguments(Ins, CC_MSP430_AssignStack);
278 /// Analyze incoming and outgoing function arguments. We need custom C++ code
279 /// to handle special constraints in the ABI like reversing the order of the
280 /// pieces of splitted arguments. In addition, all pieces of a certain argument
281 /// have to be passed either using registers or the stack but never mixing both.
282 template<typename ArgT>
283 static void AnalyzeArguments(CCState &State,
284 SmallVectorImpl<CCValAssign> &ArgLocs,
285 const SmallVectorImpl<ArgT> &Args) {
286 static const MCPhysReg RegList[] = {
287 MSP430::R15, MSP430::R14, MSP430::R13, MSP430::R12
289 static const unsigned NbRegs = array_lengthof(RegList);
291 if (State.isVarArg()) {
292 AnalyzeVarArgs(State, Args);
296 SmallVector<unsigned, 4> ArgsParts;
297 ParseFunctionArgs(Args, ArgsParts);
299 unsigned RegsLeft = NbRegs;
300 bool UseStack = false;
303 for (unsigned i = 0, e = ArgsParts.size(); i != e; i++) {
304 MVT ArgVT = Args[ValNo].VT;
305 ISD::ArgFlagsTy ArgFlags = Args[ValNo].Flags;
307 CCValAssign::LocInfo LocInfo = CCValAssign::Full;
310 if (LocVT == MVT::i8) {
312 if (ArgFlags.isSExt())
313 LocInfo = CCValAssign::SExt;
314 else if (ArgFlags.isZExt())
315 LocInfo = CCValAssign::ZExt;
317 LocInfo = CCValAssign::AExt;
320 // Handle byval arguments
321 if (ArgFlags.isByVal()) {
322 State.HandleByVal(ValNo++, ArgVT, LocVT, LocInfo, 2, 2, ArgFlags);
326 unsigned Parts = ArgsParts[i];
328 if (!UseStack && Parts <= RegsLeft) {
329 unsigned FirstVal = ValNo;
330 for (unsigned j = 0; j < Parts; j++) {
331 unsigned Reg = State.AllocateReg(RegList);
332 State.addLoc(CCValAssign::getReg(ValNo++, ArgVT, Reg, LocVT, LocInfo));
336 // Reverse the order of the pieces to agree with the "big endian" format
337 // required in the calling convention ABI.
338 SmallVectorImpl<CCValAssign>::iterator B = ArgLocs.begin() + FirstVal;
339 std::reverse(B, B + Parts);
342 for (unsigned j = 0; j < Parts; j++)
343 CC_MSP430_AssignStack(ValNo++, ArgVT, LocVT, LocInfo, ArgFlags, State);
348 static void AnalyzeRetResult(CCState &State,
349 const SmallVectorImpl<ISD::InputArg> &Ins) {
350 State.AnalyzeCallResult(Ins, RetCC_MSP430);
353 static void AnalyzeRetResult(CCState &State,
354 const SmallVectorImpl<ISD::OutputArg> &Outs) {
355 State.AnalyzeReturn(Outs, RetCC_MSP430);
358 template<typename ArgT>
359 static void AnalyzeReturnValues(CCState &State,
360 SmallVectorImpl<CCValAssign> &RVLocs,
361 const SmallVectorImpl<ArgT> &Args) {
362 AnalyzeRetResult(State, Args);
364 // Reverse splitted return values to get the "big endian" format required
365 // to agree with the calling convention ABI.
366 std::reverse(RVLocs.begin(), RVLocs.end());
370 MSP430TargetLowering::LowerFormalArguments(SDValue Chain,
371 CallingConv::ID CallConv,
373 const SmallVectorImpl<ISD::InputArg>
377 SmallVectorImpl<SDValue> &InVals)
382 llvm_unreachable("Unsupported calling convention");
384 case CallingConv::Fast:
385 return LowerCCCArguments(Chain, CallConv, isVarArg, Ins, dl, DAG, InVals);
386 case CallingConv::MSP430_INTR:
389 report_fatal_error("ISRs cannot have arguments");
394 MSP430TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
395 SmallVectorImpl<SDValue> &InVals) const {
396 SelectionDAG &DAG = CLI.DAG;
398 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
399 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
400 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
401 SDValue Chain = CLI.Chain;
402 SDValue Callee = CLI.Callee;
403 bool &isTailCall = CLI.IsTailCall;
404 CallingConv::ID CallConv = CLI.CallConv;
405 bool isVarArg = CLI.IsVarArg;
407 // MSP430 target does not yet support tail call optimization.
412 llvm_unreachable("Unsupported calling convention");
413 case CallingConv::Fast:
415 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
416 Outs, OutVals, Ins, dl, DAG, InVals);
417 case CallingConv::MSP430_INTR:
418 report_fatal_error("ISRs cannot be called directly");
422 /// LowerCCCArguments - transform physical registers into virtual registers and
423 /// generate load operations for arguments places on the stack.
424 // FIXME: struct return stuff
426 MSP430TargetLowering::LowerCCCArguments(SDValue Chain,
427 CallingConv::ID CallConv,
429 const SmallVectorImpl<ISD::InputArg>
433 SmallVectorImpl<SDValue> &InVals)
435 MachineFunction &MF = DAG.getMachineFunction();
436 MachineFrameInfo *MFI = MF.getFrameInfo();
437 MachineRegisterInfo &RegInfo = MF.getRegInfo();
438 MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
440 // Assign locations to all of the incoming arguments.
441 SmallVector<CCValAssign, 16> ArgLocs;
442 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
444 AnalyzeArguments(CCInfo, ArgLocs, Ins);
446 // Create frame index for the start of the first vararg value
448 unsigned Offset = CCInfo.getNextStackOffset();
449 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, Offset, true));
452 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
453 CCValAssign &VA = ArgLocs[i];
455 // Arguments passed in registers
456 EVT RegVT = VA.getLocVT();
457 switch (RegVT.getSimpleVT().SimpleTy) {
461 errs() << "LowerFormalArguments Unhandled argument type: "
462 << RegVT.getSimpleVT().SimpleTy << "\n";
464 llvm_unreachable(nullptr);
467 unsigned VReg = RegInfo.createVirtualRegister(&MSP430::GR16RegClass);
468 RegInfo.addLiveIn(VA.getLocReg(), VReg);
469 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
471 // If this is an 8-bit value, it is really passed promoted to 16
472 // bits. Insert an assert[sz]ext to capture this, then truncate to the
474 if (VA.getLocInfo() == CCValAssign::SExt)
475 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
476 DAG.getValueType(VA.getValVT()));
477 else if (VA.getLocInfo() == CCValAssign::ZExt)
478 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
479 DAG.getValueType(VA.getValVT()));
481 if (VA.getLocInfo() != CCValAssign::Full)
482 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
484 InVals.push_back(ArgValue);
488 assert(VA.isMemLoc());
491 ISD::ArgFlagsTy Flags = Ins[i].Flags;
493 if (Flags.isByVal()) {
494 int FI = MFI->CreateFixedObject(Flags.getByValSize(),
495 VA.getLocMemOffset(), true);
496 InVal = DAG.getFrameIndex(FI, getPointerTy());
498 // Load the argument to a virtual register
499 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
501 errs() << "LowerFormalArguments Unhandled argument type: "
502 << EVT(VA.getLocVT()).getEVTString()
505 // Create the frame index object for this incoming parameter...
506 int FI = MFI->CreateFixedObject(ObjSize, VA.getLocMemOffset(), true);
508 // Create the SelectionDAG nodes corresponding to a load
509 //from this parameter
510 SDValue FIN = DAG.getFrameIndex(FI, MVT::i16);
511 InVal = DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
512 MachinePointerInfo::getFixedStack(FI),
513 false, false, false, 0);
516 InVals.push_back(InVal);
524 MSP430TargetLowering::LowerReturn(SDValue Chain,
525 CallingConv::ID CallConv, bool isVarArg,
526 const SmallVectorImpl<ISD::OutputArg> &Outs,
527 const SmallVectorImpl<SDValue> &OutVals,
528 SDLoc dl, SelectionDAG &DAG) const {
530 // CCValAssign - represent the assignment of the return value to a location
531 SmallVector<CCValAssign, 16> RVLocs;
533 // ISRs cannot return any value.
534 if (CallConv == CallingConv::MSP430_INTR && !Outs.empty())
535 report_fatal_error("ISRs cannot return any value");
537 // CCState - Info about the registers and stack slot.
538 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
541 // Analize return values.
542 AnalyzeReturnValues(CCInfo, RVLocs, Outs);
545 SmallVector<SDValue, 4> RetOps(1, Chain);
547 // Copy the result values into the output registers.
548 for (unsigned i = 0; i != RVLocs.size(); ++i) {
549 CCValAssign &VA = RVLocs[i];
550 assert(VA.isRegLoc() && "Can only return in registers!");
552 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
555 // Guarantee that all emitted copies are stuck together,
556 // avoiding something bad.
557 Flag = Chain.getValue(1);
558 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
561 unsigned Opc = (CallConv == CallingConv::MSP430_INTR ?
562 MSP430ISD::RETI_FLAG : MSP430ISD::RET_FLAG);
564 RetOps[0] = Chain; // Update chain.
566 // Add the flag if we have it.
568 RetOps.push_back(Flag);
570 return DAG.getNode(Opc, dl, MVT::Other, RetOps);
573 /// LowerCCCCallTo - functions arguments are copied from virtual regs to
574 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
577 MSP430TargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
578 CallingConv::ID CallConv, bool isVarArg,
580 const SmallVectorImpl<ISD::OutputArg>
582 const SmallVectorImpl<SDValue> &OutVals,
583 const SmallVectorImpl<ISD::InputArg> &Ins,
584 SDLoc dl, SelectionDAG &DAG,
585 SmallVectorImpl<SDValue> &InVals) const {
586 // Analyze operands of the call, assigning locations to each operand.
587 SmallVector<CCValAssign, 16> ArgLocs;
588 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
590 AnalyzeArguments(CCInfo, ArgLocs, Outs);
592 // Get a count of how many bytes are to be pushed on the stack.
593 unsigned NumBytes = CCInfo.getNextStackOffset();
595 Chain = DAG.getCALLSEQ_START(Chain, DAG.getConstant(NumBytes, dl,
596 getPointerTy(), true),
599 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
600 SmallVector<SDValue, 12> MemOpChains;
603 // Walk the register/memloc assignments, inserting copies/loads.
604 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
605 CCValAssign &VA = ArgLocs[i];
607 SDValue Arg = OutVals[i];
609 // Promote the value if needed.
610 switch (VA.getLocInfo()) {
611 default: llvm_unreachable("Unknown loc info!");
612 case CCValAssign::Full: break;
613 case CCValAssign::SExt:
614 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
616 case CCValAssign::ZExt:
617 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
619 case CCValAssign::AExt:
620 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
624 // Arguments that can be passed on register must be kept at RegsToPass
627 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
629 assert(VA.isMemLoc());
631 if (!StackPtr.getNode())
632 StackPtr = DAG.getCopyFromReg(Chain, dl, MSP430::SP, getPointerTy());
634 SDValue PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(),
636 DAG.getIntPtrConstant(VA.getLocMemOffset(),
640 ISD::ArgFlagsTy Flags = Outs[i].Flags;
642 if (Flags.isByVal()) {
643 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i16);
644 MemOp = DAG.getMemcpy(Chain, dl, PtrOff, Arg, SizeNode,
645 Flags.getByValAlign(),
647 /*AlwaysInline=*/true,
648 /*isTailCall=*/false,
649 MachinePointerInfo(),
650 MachinePointerInfo());
652 MemOp = DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo(),
656 MemOpChains.push_back(MemOp);
660 // Transform all store nodes into one single node because all store nodes are
661 // independent of each other.
662 if (!MemOpChains.empty())
663 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
665 // Build a sequence of copy-to-reg nodes chained together with token chain and
666 // flag operands which copy the outgoing args into registers. The InFlag in
667 // necessary since all emitted instructions must be stuck together.
669 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
670 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
671 RegsToPass[i].second, InFlag);
672 InFlag = Chain.getValue(1);
675 // If the callee is a GlobalAddress node (quite common, every direct call is)
676 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
677 // Likewise ExternalSymbol -> TargetExternalSymbol.
678 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
679 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i16);
680 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
681 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i16);
683 // Returns a chain & a flag for retval copy to use.
684 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
685 SmallVector<SDValue, 8> Ops;
686 Ops.push_back(Chain);
687 Ops.push_back(Callee);
689 // Add argument registers to the end of the list so that they are
690 // known live into the call.
691 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
692 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
693 RegsToPass[i].second.getValueType()));
695 if (InFlag.getNode())
696 Ops.push_back(InFlag);
698 Chain = DAG.getNode(MSP430ISD::CALL, dl, NodeTys, Ops);
699 InFlag = Chain.getValue(1);
701 // Create the CALLSEQ_END node.
702 Chain = DAG.getCALLSEQ_END(Chain,
703 DAG.getConstant(NumBytes, dl, getPointerTy(),
705 DAG.getConstant(0, dl, getPointerTy(), true),
707 InFlag = Chain.getValue(1);
709 // Handle result values, copying them out of physregs into vregs that we
711 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl,
715 /// LowerCallResult - Lower the result values of a call into the
716 /// appropriate copies out of appropriate physical registers.
719 MSP430TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
720 CallingConv::ID CallConv, bool isVarArg,
721 const SmallVectorImpl<ISD::InputArg> &Ins,
722 SDLoc dl, SelectionDAG &DAG,
723 SmallVectorImpl<SDValue> &InVals) const {
725 // Assign locations to each value returned by this call.
726 SmallVector<CCValAssign, 16> RVLocs;
727 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
730 AnalyzeReturnValues(CCInfo, RVLocs, Ins);
732 // Copy all of the result registers out of their specified physreg.
733 for (unsigned i = 0; i != RVLocs.size(); ++i) {
734 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
735 RVLocs[i].getValVT(), InFlag).getValue(1);
736 InFlag = Chain.getValue(2);
737 InVals.push_back(Chain.getValue(0));
743 SDValue MSP430TargetLowering::LowerShifts(SDValue Op,
744 SelectionDAG &DAG) const {
745 unsigned Opc = Op.getOpcode();
746 SDNode* N = Op.getNode();
747 EVT VT = Op.getValueType();
750 // Expand non-constant shifts to loops:
751 if (!isa<ConstantSDNode>(N->getOperand(1)))
753 default: llvm_unreachable("Invalid shift opcode!");
755 return DAG.getNode(MSP430ISD::SHL, dl,
756 VT, N->getOperand(0), N->getOperand(1));
758 return DAG.getNode(MSP430ISD::SRA, dl,
759 VT, N->getOperand(0), N->getOperand(1));
761 return DAG.getNode(MSP430ISD::SRL, dl,
762 VT, N->getOperand(0), N->getOperand(1));
765 uint64_t ShiftAmount = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
767 // Expand the stuff into sequence of shifts.
768 // FIXME: for some shift amounts this might be done better!
769 // E.g.: foo >> (8 + N) => sxt(swpb(foo)) >> N
770 SDValue Victim = N->getOperand(0);
772 if (Opc == ISD::SRL && ShiftAmount) {
773 // Emit a special goodness here:
774 // srl A, 1 => clrc; rrc A
775 Victim = DAG.getNode(MSP430ISD::RRC, dl, VT, Victim);
779 while (ShiftAmount--)
780 Victim = DAG.getNode((Opc == ISD::SHL ? MSP430ISD::RLA : MSP430ISD::RRA),
786 SDValue MSP430TargetLowering::LowerGlobalAddress(SDValue Op,
787 SelectionDAG &DAG) const {
788 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
789 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
791 // Create the TargetGlobalAddress node, folding in the constant offset.
792 SDValue Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
793 getPointerTy(), Offset);
794 return DAG.getNode(MSP430ISD::Wrapper, SDLoc(Op),
795 getPointerTy(), Result);
798 SDValue MSP430TargetLowering::LowerExternalSymbol(SDValue Op,
799 SelectionDAG &DAG) const {
801 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
802 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
804 return DAG.getNode(MSP430ISD::Wrapper, dl, getPointerTy(), Result);
807 SDValue MSP430TargetLowering::LowerBlockAddress(SDValue Op,
808 SelectionDAG &DAG) const {
810 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
811 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy());
813 return DAG.getNode(MSP430ISD::Wrapper, dl, getPointerTy(), Result);
816 static SDValue EmitCMP(SDValue &LHS, SDValue &RHS, SDValue &TargetCC,
818 SDLoc dl, SelectionDAG &DAG) {
819 // FIXME: Handle bittests someday
820 assert(!LHS.getValueType().isFloatingPoint() && "We don't handle FP yet");
822 // FIXME: Handle jump negative someday
823 MSP430CC::CondCodes TCC = MSP430CC::COND_INVALID;
825 default: llvm_unreachable("Invalid integer condition!");
827 TCC = MSP430CC::COND_E; // aka COND_Z
828 // Minor optimization: if LHS is a constant, swap operands, then the
829 // constant can be folded into comparison.
830 if (LHS.getOpcode() == ISD::Constant)
834 TCC = MSP430CC::COND_NE; // aka COND_NZ
835 // Minor optimization: if LHS is a constant, swap operands, then the
836 // constant can be folded into comparison.
837 if (LHS.getOpcode() == ISD::Constant)
841 std::swap(LHS, RHS); // FALLTHROUGH
843 // Turn lhs u>= rhs with lhs constant into rhs u< lhs+1, this allows us to
844 // fold constant into instruction.
845 if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
847 RHS = DAG.getConstant(C->getSExtValue() + 1, dl, C->getValueType(0));
848 TCC = MSP430CC::COND_LO;
851 TCC = MSP430CC::COND_HS; // aka COND_C
854 std::swap(LHS, RHS); // FALLTHROUGH
856 // Turn lhs u< rhs with lhs constant into rhs u>= lhs+1, this allows us to
857 // fold constant into instruction.
858 if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
860 RHS = DAG.getConstant(C->getSExtValue() + 1, dl, C->getValueType(0));
861 TCC = MSP430CC::COND_HS;
864 TCC = MSP430CC::COND_LO; // aka COND_NC
867 std::swap(LHS, RHS); // FALLTHROUGH
869 // Turn lhs >= rhs with lhs constant into rhs < lhs+1, this allows us to
870 // fold constant into instruction.
871 if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
873 RHS = DAG.getConstant(C->getSExtValue() + 1, dl, C->getValueType(0));
874 TCC = MSP430CC::COND_L;
877 TCC = MSP430CC::COND_GE;
880 std::swap(LHS, RHS); // FALLTHROUGH
882 // Turn lhs < rhs with lhs constant into rhs >= lhs+1, this allows us to
883 // fold constant into instruction.
884 if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
886 RHS = DAG.getConstant(C->getSExtValue() + 1, dl, C->getValueType(0));
887 TCC = MSP430CC::COND_GE;
890 TCC = MSP430CC::COND_L;
894 TargetCC = DAG.getConstant(TCC, dl, MVT::i8);
895 return DAG.getNode(MSP430ISD::CMP, dl, MVT::Glue, LHS, RHS);
899 SDValue MSP430TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
900 SDValue Chain = Op.getOperand(0);
901 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
902 SDValue LHS = Op.getOperand(2);
903 SDValue RHS = Op.getOperand(3);
904 SDValue Dest = Op.getOperand(4);
908 SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
910 return DAG.getNode(MSP430ISD::BR_CC, dl, Op.getValueType(),
911 Chain, Dest, TargetCC, Flag);
914 SDValue MSP430TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
915 SDValue LHS = Op.getOperand(0);
916 SDValue RHS = Op.getOperand(1);
919 // If we are doing an AND and testing against zero, then the CMP
920 // will not be generated. The AND (or BIT) will generate the condition codes,
921 // but they are different from CMP.
922 // FIXME: since we're doing a post-processing, use a pseudoinstr here, so
923 // lowering & isel wouldn't diverge.
925 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
926 if (RHSC->isNullValue() && LHS.hasOneUse() &&
927 (LHS.getOpcode() == ISD::AND ||
928 (LHS.getOpcode() == ISD::TRUNCATE &&
929 LHS.getOperand(0).getOpcode() == ISD::AND))) {
933 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
935 SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
937 // Get the condition codes directly from the status register, if its easy.
938 // Otherwise a branch will be generated. Note that the AND and BIT
939 // instructions generate different flags than CMP, the carry bit can be used
944 switch (cast<ConstantSDNode>(TargetCC)->getZExtValue()) {
948 case MSP430CC::COND_HS:
949 // Res = SR & 1, no processing is required
951 case MSP430CC::COND_LO:
955 case MSP430CC::COND_NE:
957 // C = ~Z, thus Res = SR & 1, no processing is required
959 // Res = ~((SR >> 1) & 1)
964 case MSP430CC::COND_E:
966 // C = ~Z for AND instruction, thus we can put Res = ~(SR & 1), however,
967 // Res = (SR >> 1) & 1 is 1 word shorter.
970 EVT VT = Op.getValueType();
971 SDValue One = DAG.getConstant(1, dl, VT);
973 SDValue SR = DAG.getCopyFromReg(DAG.getEntryNode(), dl, MSP430::SR,
976 // FIXME: somewhere this is turned into a SRL, lower it MSP specific?
977 SR = DAG.getNode(ISD::SRA, dl, MVT::i16, SR, One);
978 SR = DAG.getNode(ISD::AND, dl, MVT::i16, SR, One);
980 SR = DAG.getNode(ISD::XOR, dl, MVT::i16, SR, One);
983 SDValue Zero = DAG.getConstant(0, dl, VT);
984 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
985 SDValue Ops[] = {One, Zero, TargetCC, Flag};
986 return DAG.getNode(MSP430ISD::SELECT_CC, dl, VTs, Ops);
990 SDValue MSP430TargetLowering::LowerSELECT_CC(SDValue Op,
991 SelectionDAG &DAG) const {
992 SDValue LHS = Op.getOperand(0);
993 SDValue RHS = Op.getOperand(1);
994 SDValue TrueV = Op.getOperand(2);
995 SDValue FalseV = Op.getOperand(3);
996 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1000 SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
1002 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
1003 SDValue Ops[] = {TrueV, FalseV, TargetCC, Flag};
1005 return DAG.getNode(MSP430ISD::SELECT_CC, dl, VTs, Ops);
1008 SDValue MSP430TargetLowering::LowerSIGN_EXTEND(SDValue Op,
1009 SelectionDAG &DAG) const {
1010 SDValue Val = Op.getOperand(0);
1011 EVT VT = Op.getValueType();
1014 assert(VT == MVT::i16 && "Only support i16 for now!");
1016 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT,
1017 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Val),
1018 DAG.getValueType(Val.getValueType()));
1022 MSP430TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
1023 MachineFunction &MF = DAG.getMachineFunction();
1024 MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
1025 int ReturnAddrIndex = FuncInfo->getRAIndex();
1027 if (ReturnAddrIndex == 0) {
1028 // Set up a frame object for the return address.
1029 uint64_t SlotSize = getDataLayout()->getPointerSize();
1030 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
1032 FuncInfo->setRAIndex(ReturnAddrIndex);
1035 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1038 SDValue MSP430TargetLowering::LowerRETURNADDR(SDValue Op,
1039 SelectionDAG &DAG) const {
1040 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1041 MFI->setReturnAddressIsTaken(true);
1043 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1046 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1050 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
1052 DAG.getConstant(getDataLayout()->getPointerSize(), dl, MVT::i16);
1053 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1054 DAG.getNode(ISD::ADD, dl, getPointerTy(),
1056 MachinePointerInfo(), false, false, false, 0);
1059 // Just load the return address.
1060 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
1061 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1062 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
1065 SDValue MSP430TargetLowering::LowerFRAMEADDR(SDValue Op,
1066 SelectionDAG &DAG) const {
1067 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1068 MFI->setFrameAddressIsTaken(true);
1070 EVT VT = Op.getValueType();
1071 SDLoc dl(Op); // FIXME probably not meaningful
1072 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1073 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
1076 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
1077 MachinePointerInfo(),
1078 false, false, false, 0);
1082 SDValue MSP430TargetLowering::LowerVASTART(SDValue Op,
1083 SelectionDAG &DAG) const {
1084 MachineFunction &MF = DAG.getMachineFunction();
1085 MSP430MachineFunctionInfo *FuncInfo = MF.getInfo<MSP430MachineFunctionInfo>();
1087 // Frame index of first vararg argument
1088 SDValue FrameIndex = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1090 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1092 // Create a store of the frame index to the location operand
1093 return DAG.getStore(Op.getOperand(0), SDLoc(Op), FrameIndex,
1094 Op.getOperand(1), MachinePointerInfo(SV),
1098 SDValue MSP430TargetLowering::LowerJumpTable(SDValue Op,
1099 SelectionDAG &DAG) const {
1100 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1101 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
1102 return DAG.getNode(MSP430ISD::Wrapper, SDLoc(JT),
1103 getPointerTy(), Result);
1106 /// getPostIndexedAddressParts - returns true by value, base pointer and
1107 /// offset pointer and addressing mode by reference if this node can be
1108 /// combined with a load / store to form a post-indexed load / store.
1109 bool MSP430TargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
1112 ISD::MemIndexedMode &AM,
1113 SelectionDAG &DAG) const {
1115 LoadSDNode *LD = cast<LoadSDNode>(N);
1116 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
1119 EVT VT = LD->getMemoryVT();
1120 if (VT != MVT::i8 && VT != MVT::i16)
1123 if (Op->getOpcode() != ISD::ADD)
1126 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
1127 uint64_t RHSC = RHS->getZExtValue();
1128 if ((VT == MVT::i16 && RHSC != 2) ||
1129 (VT == MVT::i8 && RHSC != 1))
1132 Base = Op->getOperand(0);
1133 Offset = DAG.getConstant(RHSC, SDLoc(N), VT);
1142 const char *MSP430TargetLowering::getTargetNodeName(unsigned Opcode) const {
1143 switch ((MSP430ISD::NodeType)Opcode) {
1144 case MSP430ISD::FIRST_NUMBER: break;
1145 case MSP430ISD::RET_FLAG: return "MSP430ISD::RET_FLAG";
1146 case MSP430ISD::RETI_FLAG: return "MSP430ISD::RETI_FLAG";
1147 case MSP430ISD::RRA: return "MSP430ISD::RRA";
1148 case MSP430ISD::RLA: return "MSP430ISD::RLA";
1149 case MSP430ISD::RRC: return "MSP430ISD::RRC";
1150 case MSP430ISD::CALL: return "MSP430ISD::CALL";
1151 case MSP430ISD::Wrapper: return "MSP430ISD::Wrapper";
1152 case MSP430ISD::BR_CC: return "MSP430ISD::BR_CC";
1153 case MSP430ISD::CMP: return "MSP430ISD::CMP";
1154 case MSP430ISD::SETCC: return "MSP430ISD::SETCC";
1155 case MSP430ISD::SELECT_CC: return "MSP430ISD::SELECT_CC";
1156 case MSP430ISD::SHL: return "MSP430ISD::SHL";
1157 case MSP430ISD::SRA: return "MSP430ISD::SRA";
1158 case MSP430ISD::SRL: return "MSP430ISD::SRL";
1163 bool MSP430TargetLowering::isTruncateFree(Type *Ty1,
1165 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
1168 return (Ty1->getPrimitiveSizeInBits() > Ty2->getPrimitiveSizeInBits());
1171 bool MSP430TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
1172 if (!VT1.isInteger() || !VT2.isInteger())
1175 return (VT1.getSizeInBits() > VT2.getSizeInBits());
1178 bool MSP430TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
1179 // MSP430 implicitly zero-extends 8-bit results in 16-bit registers.
1180 return 0 && Ty1->isIntegerTy(8) && Ty2->isIntegerTy(16);
1183 bool MSP430TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
1184 // MSP430 implicitly zero-extends 8-bit results in 16-bit registers.
1185 return 0 && VT1 == MVT::i8 && VT2 == MVT::i16;
1188 bool MSP430TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1189 return isZExtFree(Val.getValueType(), VT2);
1192 //===----------------------------------------------------------------------===//
1193 // Other Lowering Code
1194 //===----------------------------------------------------------------------===//
1197 MSP430TargetLowering::EmitShiftInstr(MachineInstr *MI,
1198 MachineBasicBlock *BB) const {
1199 MachineFunction *F = BB->getParent();
1200 MachineRegisterInfo &RI = F->getRegInfo();
1201 DebugLoc dl = MI->getDebugLoc();
1202 const TargetInstrInfo &TII = *F->getSubtarget().getInstrInfo();
1205 const TargetRegisterClass * RC;
1206 switch (MI->getOpcode()) {
1207 default: llvm_unreachable("Invalid shift opcode!");
1209 Opc = MSP430::SHL8r1;
1210 RC = &MSP430::GR8RegClass;
1213 Opc = MSP430::SHL16r1;
1214 RC = &MSP430::GR16RegClass;
1217 Opc = MSP430::SAR8r1;
1218 RC = &MSP430::GR8RegClass;
1221 Opc = MSP430::SAR16r1;
1222 RC = &MSP430::GR16RegClass;
1225 Opc = MSP430::SAR8r1c;
1226 RC = &MSP430::GR8RegClass;
1229 Opc = MSP430::SAR16r1c;
1230 RC = &MSP430::GR16RegClass;
1234 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1235 MachineFunction::iterator I = BB;
1238 // Create loop block
1239 MachineBasicBlock *LoopBB = F->CreateMachineBasicBlock(LLVM_BB);
1240 MachineBasicBlock *RemBB = F->CreateMachineBasicBlock(LLVM_BB);
1242 F->insert(I, LoopBB);
1243 F->insert(I, RemBB);
1245 // Update machine-CFG edges by transferring all successors of the current
1246 // block to the block containing instructions after shift.
1247 RemBB->splice(RemBB->begin(), BB, std::next(MachineBasicBlock::iterator(MI)),
1249 RemBB->transferSuccessorsAndUpdatePHIs(BB);
1251 // Add adges BB => LoopBB => RemBB, BB => RemBB, LoopBB => LoopBB
1252 BB->addSuccessor(LoopBB);
1253 BB->addSuccessor(RemBB);
1254 LoopBB->addSuccessor(RemBB);
1255 LoopBB->addSuccessor(LoopBB);
1257 unsigned ShiftAmtReg = RI.createVirtualRegister(&MSP430::GR8RegClass);
1258 unsigned ShiftAmtReg2 = RI.createVirtualRegister(&MSP430::GR8RegClass);
1259 unsigned ShiftReg = RI.createVirtualRegister(RC);
1260 unsigned ShiftReg2 = RI.createVirtualRegister(RC);
1261 unsigned ShiftAmtSrcReg = MI->getOperand(2).getReg();
1262 unsigned SrcReg = MI->getOperand(1).getReg();
1263 unsigned DstReg = MI->getOperand(0).getReg();
1268 BuildMI(BB, dl, TII.get(MSP430::CMP8ri))
1269 .addReg(ShiftAmtSrcReg).addImm(0);
1270 BuildMI(BB, dl, TII.get(MSP430::JCC))
1272 .addImm(MSP430CC::COND_E);
1275 // ShiftReg = phi [%SrcReg, BB], [%ShiftReg2, LoopBB]
1276 // ShiftAmt = phi [%N, BB], [%ShiftAmt2, LoopBB]
1277 // ShiftReg2 = shift ShiftReg
1278 // ShiftAmt2 = ShiftAmt - 1;
1279 BuildMI(LoopBB, dl, TII.get(MSP430::PHI), ShiftReg)
1280 .addReg(SrcReg).addMBB(BB)
1281 .addReg(ShiftReg2).addMBB(LoopBB);
1282 BuildMI(LoopBB, dl, TII.get(MSP430::PHI), ShiftAmtReg)
1283 .addReg(ShiftAmtSrcReg).addMBB(BB)
1284 .addReg(ShiftAmtReg2).addMBB(LoopBB);
1285 BuildMI(LoopBB, dl, TII.get(Opc), ShiftReg2)
1287 BuildMI(LoopBB, dl, TII.get(MSP430::SUB8ri), ShiftAmtReg2)
1288 .addReg(ShiftAmtReg).addImm(1);
1289 BuildMI(LoopBB, dl, TII.get(MSP430::JCC))
1291 .addImm(MSP430CC::COND_NE);
1294 // DestReg = phi [%SrcReg, BB], [%ShiftReg, LoopBB]
1295 BuildMI(*RemBB, RemBB->begin(), dl, TII.get(MSP430::PHI), DstReg)
1296 .addReg(SrcReg).addMBB(BB)
1297 .addReg(ShiftReg2).addMBB(LoopBB);
1299 MI->eraseFromParent(); // The pseudo instruction is gone now.
1304 MSP430TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1305 MachineBasicBlock *BB) const {
1306 unsigned Opc = MI->getOpcode();
1308 if (Opc == MSP430::Shl8 || Opc == MSP430::Shl16 ||
1309 Opc == MSP430::Sra8 || Opc == MSP430::Sra16 ||
1310 Opc == MSP430::Srl8 || Opc == MSP430::Srl16)
1311 return EmitShiftInstr(MI, BB);
1313 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
1314 DebugLoc dl = MI->getDebugLoc();
1316 assert((Opc == MSP430::Select16 || Opc == MSP430::Select8) &&
1317 "Unexpected instr type to insert");
1319 // To "insert" a SELECT instruction, we actually have to insert the diamond
1320 // control-flow pattern. The incoming instruction knows the destination vreg
1321 // to set, the condition code register to branch on, the true/false values to
1322 // select between, and a branch opcode to use.
1323 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1324 MachineFunction::iterator I = BB;
1330 // cmpTY ccX, r1, r2
1332 // fallthrough --> copy0MBB
1333 MachineBasicBlock *thisMBB = BB;
1334 MachineFunction *F = BB->getParent();
1335 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1336 MachineBasicBlock *copy1MBB = F->CreateMachineBasicBlock(LLVM_BB);
1337 F->insert(I, copy0MBB);
1338 F->insert(I, copy1MBB);
1339 // Update machine-CFG edges by transferring all successors of the current
1340 // block to the new block which will contain the Phi node for the select.
1341 copy1MBB->splice(copy1MBB->begin(), BB,
1342 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1343 copy1MBB->transferSuccessorsAndUpdatePHIs(BB);
1344 // Next, add the true and fallthrough blocks as its successors.
1345 BB->addSuccessor(copy0MBB);
1346 BB->addSuccessor(copy1MBB);
1348 BuildMI(BB, dl, TII.get(MSP430::JCC))
1350 .addImm(MI->getOperand(3).getImm());
1353 // %FalseValue = ...
1354 // # fallthrough to copy1MBB
1357 // Update machine-CFG edges
1358 BB->addSuccessor(copy1MBB);
1361 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1364 BuildMI(*BB, BB->begin(), dl, TII.get(MSP430::PHI),
1365 MI->getOperand(0).getReg())
1366 .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
1367 .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
1369 MI->eraseFromParent(); // The pseudo instruction is gone now.