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 #define DEBUG_TYPE "msp430-lower"
16 #include "MSP430ISelLowering.h"
18 #include "MSP430TargetMachine.h"
19 #include "MSP430Subtarget.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Function.h"
22 #include "llvm/Intrinsics.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/PseudoSourceValue.h"
32 #include "llvm/CodeGen/SelectionDAGISel.h"
33 #include "llvm/CodeGen/ValueTypes.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/ADT/VectorExtras.h"
38 MSP430TargetLowering::MSP430TargetLowering(MSP430TargetMachine &tm) :
39 TargetLowering(tm), Subtarget(*tm.getSubtargetImpl()), TM(tm) {
41 // Set up the register classes.
42 addRegisterClass(MVT::i8, MSP430::GR8RegisterClass);
43 addRegisterClass(MVT::i16, MSP430::GR16RegisterClass);
45 // Compute derived properties from the register classes
46 computeRegisterProperties();
48 // Provide all sorts of operation actions
50 // Division is expensive
51 setIntDivIsCheap(false);
53 // Even if we have only 1 bit shift here, we can perform
54 // shifts of the whole bitwidth 1 bit per step.
55 setShiftAmountType(MVT::i8);
57 setStackPointerRegisterToSaveRestore(MSP430::SPW);
58 setBooleanContents(ZeroOrOneBooleanContent);
59 setSchedulingPreference(SchedulingForLatency);
61 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
62 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
63 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
64 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
65 setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Expand);
67 // We don't have any truncstores
68 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
70 setOperationAction(ISD::SRA, MVT::i16, Custom);
71 setOperationAction(ISD::RET, MVT::Other, Custom);
72 setOperationAction(ISD::GlobalAddress, MVT::i16, Custom);
73 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
74 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
75 setOperationAction(ISD::SETCC, MVT::i8 , Custom);
76 setOperationAction(ISD::SETCC, MVT::i16 , Custom);
79 SDValue MSP430TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
80 switch (Op.getOpcode()) {
81 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
82 case ISD::SRA: return LowerShifts(Op, DAG);
83 case ISD::RET: return LowerRET(Op, DAG);
84 case ISD::CALL: return LowerCALL(Op, DAG);
85 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
86 case ISD::SETCC: return LowerSETCC(Op, DAG);
87 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
89 assert(0 && "unimplemented operand");
94 //===----------------------------------------------------------------------===//
95 // Calling Convention Implementation
96 //===----------------------------------------------------------------------===//
98 #include "MSP430GenCallingConv.inc"
100 SDValue MSP430TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op,
102 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
105 assert(0 && "Unsupported calling convention");
107 case CallingConv::Fast:
108 return LowerCCCArguments(Op, DAG);
112 SDValue MSP430TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
113 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
114 unsigned CallingConv = TheCall->getCallingConv();
115 switch (CallingConv) {
117 assert(0 && "Unsupported calling convention");
118 case CallingConv::Fast:
120 return LowerCCCCallTo(Op, DAG, CallingConv);
124 /// LowerCCCArguments - transform physical registers into virtual registers and
125 /// generate load operations for arguments places on the stack.
126 // FIXME: struct return stuff
128 SDValue MSP430TargetLowering::LowerCCCArguments(SDValue Op,
130 MachineFunction &MF = DAG.getMachineFunction();
131 MachineFrameInfo *MFI = MF.getFrameInfo();
132 MachineRegisterInfo &RegInfo = MF.getRegInfo();
133 SDValue Root = Op.getOperand(0);
134 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
135 unsigned CC = MF.getFunction()->getCallingConv();
136 DebugLoc dl = Op.getDebugLoc();
138 // Assign locations to all of the incoming arguments.
139 SmallVector<CCValAssign, 16> ArgLocs;
140 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
141 CCInfo.AnalyzeFormalArguments(Op.getNode(), CC_MSP430);
143 assert(!isVarArg && "Varargs not supported yet");
145 SmallVector<SDValue, 16> ArgValues;
146 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
147 CCValAssign &VA = ArgLocs[i];
149 // Arguments passed in registers
150 MVT RegVT = VA.getLocVT();
151 switch (RegVT.getSimpleVT()) {
153 cerr << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
154 << RegVT.getSimpleVT()
159 RegInfo.createVirtualRegister(MSP430::GR16RegisterClass);
160 RegInfo.addLiveIn(VA.getLocReg(), VReg);
161 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, VReg, RegVT);
163 // If this is an 8-bit value, it is really passed promoted to 16
164 // bits. Insert an assert[sz]ext to capture this, then truncate to the
166 if (VA.getLocInfo() == CCValAssign::SExt)
167 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
168 DAG.getValueType(VA.getValVT()));
169 else if (VA.getLocInfo() == CCValAssign::ZExt)
170 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
171 DAG.getValueType(VA.getValVT()));
173 if (VA.getLocInfo() != CCValAssign::Full)
174 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
176 ArgValues.push_back(ArgValue);
180 assert(VA.isMemLoc());
181 // Load the argument to a virtual register
182 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
184 cerr << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
185 << VA.getLocVT().getSimpleVT()
188 // Create the frame index object for this incoming parameter...
189 int FI = MFI->CreateFixedObject(ObjSize, VA.getLocMemOffset());
191 // Create the SelectionDAG nodes corresponding to a load
192 //from this parameter
193 SDValue FIN = DAG.getFrameIndex(FI, MVT::i16);
194 ArgValues.push_back(DAG.getLoad(VA.getLocVT(), dl, Root, FIN,
195 PseudoSourceValue::getFixedStack(FI), 0));
199 ArgValues.push_back(Root);
201 // Return the new list of results.
202 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
203 &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
206 SDValue MSP430TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
207 // CCValAssign - represent the assignment of the return value to a location
208 SmallVector<CCValAssign, 16> RVLocs;
209 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
210 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
211 DebugLoc dl = Op.getDebugLoc();
213 // CCState - Info about the registers and stack slot.
214 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
216 // Analize return values of ISD::RET
217 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_MSP430);
219 // If this is the first return lowered for this function, add the regs to the
220 // liveout set for the function.
221 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
222 for (unsigned i = 0; i != RVLocs.size(); ++i)
223 if (RVLocs[i].isRegLoc())
224 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
227 // The chain is always operand #0
228 SDValue Chain = Op.getOperand(0);
231 // Copy the result values into the output registers.
232 for (unsigned i = 0; i != RVLocs.size(); ++i) {
233 CCValAssign &VA = RVLocs[i];
234 assert(VA.isRegLoc() && "Can only return in registers!");
236 // ISD::RET => ret chain, (regnum1,val1), ...
237 // So i*2+1 index only the regnums
238 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
239 Op.getOperand(i*2+1), Flag);
241 // Guarantee that all emitted copies are stuck together,
242 // avoiding something bad.
243 Flag = Chain.getValue(1);
247 return DAG.getNode(MSP430ISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
250 return DAG.getNode(MSP430ISD::RET_FLAG, dl, MVT::Other, Chain);
253 /// LowerCCCCallTo - functions arguments are copied from virtual regs to
254 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
256 SDValue MSP430TargetLowering::LowerCCCCallTo(SDValue Op, SelectionDAG &DAG,
258 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
259 SDValue Chain = TheCall->getChain();
260 SDValue Callee = TheCall->getCallee();
261 bool isVarArg = TheCall->isVarArg();
262 DebugLoc dl = Op.getDebugLoc();
264 // Analyze operands of the call, assigning locations to each operand.
265 SmallVector<CCValAssign, 16> ArgLocs;
266 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
268 CCInfo.AnalyzeCallOperands(TheCall, CC_MSP430);
270 // Get a count of how many bytes are to be pushed on the stack.
271 unsigned NumBytes = CCInfo.getNextStackOffset();
273 Chain = DAG.getCALLSEQ_START(Chain ,DAG.getConstant(NumBytes,
274 getPointerTy(), true));
276 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
277 SmallVector<SDValue, 12> MemOpChains;
280 // Walk the register/memloc assignments, inserting copies/loads.
281 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
282 CCValAssign &VA = ArgLocs[i];
284 // Arguments start after the 5 first operands of ISD::CALL
285 SDValue Arg = TheCall->getArg(i);
287 // Promote the value if needed.
288 switch (VA.getLocInfo()) {
289 default: assert(0 && "Unknown loc info!");
290 case CCValAssign::Full: break;
291 case CCValAssign::SExt:
292 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
294 case CCValAssign::ZExt:
295 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
297 case CCValAssign::AExt:
298 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
302 // Arguments that can be passed on register must be kept at RegsToPass
305 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
307 assert(VA.isMemLoc());
309 if (StackPtr.getNode() == 0)
310 StackPtr = DAG.getCopyFromReg(Chain, dl, MSP430::SPW, getPointerTy());
312 SDValue PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(),
314 DAG.getIntPtrConstant(VA.getLocMemOffset()));
317 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
318 PseudoSourceValue::getStack(),
319 VA.getLocMemOffset()));
323 // Transform all store nodes into one single node because all store nodes are
324 // independent of each other.
325 if (!MemOpChains.empty())
326 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
327 &MemOpChains[0], MemOpChains.size());
329 // Build a sequence of copy-to-reg nodes chained together with token chain and
330 // flag operands which copy the outgoing args into registers. The InFlag in
331 // necessary since all emited instructions must be stuck together.
333 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
334 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
335 RegsToPass[i].second, InFlag);
336 InFlag = Chain.getValue(1);
339 // If the callee is a GlobalAddress node (quite common, every direct call is)
340 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
341 // Likewise ExternalSymbol -> TargetExternalSymbol.
342 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
343 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i16);
344 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
345 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i16);
347 // Returns a chain & a flag for retval copy to use.
348 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
349 SmallVector<SDValue, 8> Ops;
350 Ops.push_back(Chain);
351 Ops.push_back(Callee);
353 // Add argument registers to the end of the list so that they are
354 // known live into the call.
355 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
356 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
357 RegsToPass[i].second.getValueType()));
359 if (InFlag.getNode())
360 Ops.push_back(InFlag);
362 Chain = DAG.getNode(MSP430ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
363 InFlag = Chain.getValue(1);
365 // Create the CALLSEQ_END node.
366 Chain = DAG.getCALLSEQ_END(Chain,
367 DAG.getConstant(NumBytes, getPointerTy(), true),
368 DAG.getConstant(0, getPointerTy(), true),
370 InFlag = Chain.getValue(1);
372 // Handle result values, copying them out of physregs into vregs that we
374 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
378 /// LowerCallResult - Lower the result values of an ISD::CALL into the
379 /// appropriate copies out of appropriate physical registers. This assumes that
380 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
381 /// being lowered. Returns a SDNode with the same number of values as the
384 MSP430TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
386 unsigned CallingConv,
388 bool isVarArg = TheCall->isVarArg();
389 DebugLoc dl = TheCall->getDebugLoc();
391 // Assign locations to each value returned by this call.
392 SmallVector<CCValAssign, 16> RVLocs;
393 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
395 CCInfo.AnalyzeCallResult(TheCall, RetCC_MSP430);
396 SmallVector<SDValue, 8> ResultVals;
398 // Copy all of the result registers out of their specified physreg.
399 for (unsigned i = 0; i != RVLocs.size(); ++i) {
400 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
401 RVLocs[i].getValVT(), InFlag).getValue(1);
402 InFlag = Chain.getValue(2);
403 ResultVals.push_back(Chain.getValue(0));
406 ResultVals.push_back(Chain);
408 // Merge everything together with a MERGE_VALUES node.
409 return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
410 &ResultVals[0], ResultVals.size()).getNode();
413 SDValue MSP430TargetLowering::LowerShifts(SDValue Op,
415 assert(Op.getOpcode() == ISD::SRA && "Only SRA is currently supported.");
416 SDNode* N = Op.getNode();
417 MVT VT = Op.getValueType();
418 DebugLoc dl = N->getDebugLoc();
420 // We currently only lower SRA of constant argument.
421 if (!isa<ConstantSDNode>(N->getOperand(1)))
424 uint64_t ShiftAmount = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
426 // Expand the stuff into sequence of shifts.
427 // FIXME: for some shift amounts this might be done better!
428 // E.g.: foo >> (8 + N) => sxt(swpb(foo)) >> N
429 SDValue Victim = N->getOperand(0);
430 while (ShiftAmount--)
431 Victim = DAG.getNode(MSP430ISD::RRA, dl, VT, Victim);
436 SDValue MSP430TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
437 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
438 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
440 // Create the TargetGlobalAddress node, folding in the constant offset.
441 SDValue Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
442 return DAG.getNode(MSP430ISD::Wrapper, Op.getDebugLoc(),
443 getPointerTy(), Result);
446 MVT MSP430TargetLowering::getSetCCResultType(MVT VT) const {
450 SDValue MSP430TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
451 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
452 SDValue LHS = Op.getOperand(0);
453 SDValue RHS = Op.getOperand(1);
454 DebugLoc dl = Op.getDebugLoc();
455 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
457 // FIXME: Handle bittests someday
458 assert(!LHS.getValueType().isFloatingPoint() && "We don't handle FP yet");
460 // FIXME: Handle jump negative someday
461 unsigned TargetCC = 0;
463 default: assert(0 && "Invalid integer condition!");
465 TargetCC = MSP430::COND_E; // aka COND_Z
468 TargetCC = MSP430::COND_NE; // aka COND_NZ
471 std::swap(LHS, RHS); // FALLTHROUGH
473 TargetCC = MSP430::COND_HS; // aka COND_C
476 std::swap(LHS, RHS); // FALLTHROUGH
478 TargetCC = MSP430::COND_LO; // aka COND_NC
481 std::swap(LHS, RHS); // FALLTHROUGH
483 TargetCC = MSP430::COND_GE;
486 std::swap(LHS, RHS); // FALLTHROUGH
488 TargetCC = MSP430::COND_L;
492 SDValue Cond = DAG.getNode(MSP430ISD::CMP, dl, MVT::i16, LHS, RHS);
493 return DAG.getNode(MSP430ISD::SETCC, dl, MVT::i8,
494 DAG.getConstant(TargetCC, MVT::i8), Cond);
497 SDValue MSP430TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
498 SDValue Chain = Op.getOperand(0);
499 SDValue Cond = Op.getOperand(1);
500 SDValue Dest = Op.getOperand(2);
501 DebugLoc dl = Op.getDebugLoc();
504 // Lower condition if not lowered yet
505 if (Cond.getOpcode() == ISD::SETCC)
506 Cond = LowerSETCC(Cond, DAG);
508 // If condition flag is set by a MSP430ISD::CMP, then use it as the condition
509 // setting operand in place of the MSP430ISD::SETCC.
510 if (Cond.getOpcode() == MSP430ISD::SETCC) {
511 CC = Cond.getOperand(0);
512 Cond = Cond.getOperand(1);
514 assert(0 && "Unimplemented condition!");
516 return DAG.getNode(MSP430ISD::BRCOND, dl, Op.getValueType(),
517 Chain, Dest, CC, Cond);
520 const char *MSP430TargetLowering::getTargetNodeName(unsigned Opcode) const {
522 default: return NULL;
523 case MSP430ISD::RET_FLAG: return "MSP430ISD::RET_FLAG";
524 case MSP430ISD::RRA: return "MSP430ISD::RRA";
525 case MSP430ISD::CALL: return "MSP430ISD::CALL";
526 case MSP430ISD::Wrapper: return "MSP430ISD::Wrapper";
527 case MSP430ISD::BRCOND: return "MSP430ISD::BRCOND";
528 case MSP430ISD::CMP: return "MSP430ISD::CMP";
529 case MSP430ISD::SETCC: return "MSP430ISD::SETCC";