1 //===-- XCoreISelLowering.cpp - XCore 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 XCoreTargetLowering class.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "xcore-lower"
16 #include "XCoreISelLowering.h"
17 #include "XCoreMachineFunctionInfo.h"
19 #include "XCoreTargetMachine.h"
20 #include "XCoreSubtarget.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/ValueTypes.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/ADT/VectorExtras.h"
40 const char *XCoreTargetLowering::
41 getTargetNodeName(unsigned Opcode) const
45 case XCoreISD::BL : return "XCoreISD::BL";
46 case XCoreISD::PCRelativeWrapper : return "XCoreISD::PCRelativeWrapper";
47 case XCoreISD::DPRelativeWrapper : return "XCoreISD::DPRelativeWrapper";
48 case XCoreISD::CPRelativeWrapper : return "XCoreISD::CPRelativeWrapper";
49 case XCoreISD::STWSP : return "XCoreISD::STWSP";
50 case XCoreISD::RETSP : return "XCoreISD::RETSP";
51 default : return NULL;
55 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
56 : TargetLowering(XTM),
58 Subtarget(*XTM.getSubtargetImpl()) {
60 // Set up the register classes.
61 addRegisterClass(MVT::i32, XCore::GRRegsRegisterClass);
63 // Compute derived properties from the register classes
64 computeRegisterProperties();
66 // Division is expensive
67 setIntDivIsCheap(false);
69 setShiftAmountType(MVT::i32);
71 setShiftAmountFlavor(Extend);
72 setStackPointerRegisterToSaveRestore(XCore::SP);
74 setSchedulingPreference(SchedulingForRegPressure);
76 // Use i32 for setcc operations results (slt, sgt, ...).
77 setBooleanContents(ZeroOrOneBooleanContent);
79 // XCore does not have the NodeTypes below.
80 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
81 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
82 setOperationAction(ISD::ADDC, MVT::i32, Expand);
83 setOperationAction(ISD::ADDE, MVT::i32, Expand);
84 setOperationAction(ISD::SUBC, MVT::i32, Expand);
85 setOperationAction(ISD::SUBE, MVT::i32, Expand);
87 // Stop the combiner recombining select and set_cc
88 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
91 if (!Subtarget.isXS1A()) {
92 setOperationAction(ISD::ADD, MVT::i64, Custom);
93 setOperationAction(ISD::SUB, MVT::i64, Custom);
95 if (Subtarget.isXS1A()) {
96 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
98 setOperationAction(ISD::MULHS, MVT::i32, Expand);
99 setOperationAction(ISD::MULHU, MVT::i32, Expand);
100 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
101 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
102 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
105 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
106 setOperationAction(ISD::ROTL , MVT::i32, Expand);
107 setOperationAction(ISD::ROTR , MVT::i32, Expand);
109 setOperationAction(ISD::TRAP, MVT::Other, Legal);
111 // Expand jump tables for now
112 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
113 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
115 // RET must be custom lowered, to meet ABI requirements
116 setOperationAction(ISD::RET, MVT::Other, Custom);
118 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
120 // Thread Local Storage
121 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
123 // Conversion of i64 -> double produces constantpool nodes
124 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
127 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
128 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
129 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
131 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
132 setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
135 setOperationAction(ISD::VAEND, MVT::Other, Expand);
136 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
137 setOperationAction(ISD::VAARG, MVT::Other, Custom);
138 setOperationAction(ISD::VASTART, MVT::Other, Custom);
141 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
142 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
143 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
146 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
147 setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
150 SDValue XCoreTargetLowering::
151 LowerOperation(SDValue Op, SelectionDAG &DAG) {
152 switch (Op.getOpcode())
154 case ISD::CALL: return LowerCALL(Op, DAG);
155 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
156 case ISD::RET: return LowerRET(Op, DAG);
157 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
158 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
159 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
160 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
161 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
162 case ISD::VAARG: return LowerVAARG(Op, DAG);
163 case ISD::VASTART: return LowerVASTART(Op, DAG);
164 // FIXME: Remove these when LegalizeDAGTypes lands.
166 case ISD::SUB: return ExpandADDSUB(Op.getNode(), DAG);
167 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
169 assert(0 && "unimplemented operand");
174 /// ReplaceNodeResults - Replace the results of node with an illegal result
175 /// type with new values built out of custom code.
176 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
177 SmallVectorImpl<SDValue>&Results,
179 switch (N->getOpcode()) {
181 assert(0 && "Don't know how to custom expand this!");
185 Results.push_back(ExpandADDSUB(N, DAG));
190 /// getFunctionAlignment - Return the Log2 alignment of this function.
191 unsigned XCoreTargetLowering::
192 getFunctionAlignment(const Function *) const {
196 //===----------------------------------------------------------------------===//
197 // Misc Lower Operation implementation
198 //===----------------------------------------------------------------------===//
200 SDValue XCoreTargetLowering::
201 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG)
203 DebugLoc dl = Op.getDebugLoc();
204 SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i32, Op.getOperand(2),
205 Op.getOperand(3), Op.getOperand(4));
206 return DAG.getNode(ISD::SELECT, dl, MVT::i32, Cond, Op.getOperand(0),
210 SDValue XCoreTargetLowering::
211 getGlobalAddressWrapper(SDValue GA, GlobalValue *GV, SelectionDAG &DAG)
213 // FIXME there is no actual debug info here
214 DebugLoc dl = GA.getDebugLoc();
215 if (isa<Function>(GV)) {
216 return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
217 } else if (!Subtarget.isXS1A()) {
218 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
220 // If GV is an alias then use the aliasee to determine constness
221 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
222 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
224 bool isConst = GVar && GVar->isConstant();
226 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
229 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
232 SDValue XCoreTargetLowering::
233 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG)
235 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
236 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
237 // If it's a debug information descriptor, don't mess with it.
238 if (DAG.isVerifiedDebugInfoDesc(Op))
240 return getGlobalAddressWrapper(GA, GV, DAG);
243 static inline SDValue BuildGetId(SelectionDAG &DAG, DebugLoc dl) {
244 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
245 DAG.getConstant(Intrinsic::xcore_getid, MVT::i32));
248 static inline bool isZeroLengthArray(const Type *Ty) {
249 const ArrayType *AT = dyn_cast_or_null<ArrayType>(Ty);
250 return AT && (AT->getNumElements() == 0);
253 SDValue XCoreTargetLowering::
254 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG)
256 // FIXME there isn't really debug info here
257 DebugLoc dl = Op.getDebugLoc();
258 // transform to label + getid() * size
259 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
260 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
261 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
263 // If GV is an alias then use the aliasee to determine size
264 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
265 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
268 assert(0 && "Thread local object not a GlobalVariable?");
271 const Type *Ty = cast<PointerType>(GV->getType())->getElementType();
272 if (!Ty->isSized() || isZeroLengthArray(Ty)) {
273 llvm_report_error("Size of thread local object " + GVar->getName()
276 SDValue base = getGlobalAddressWrapper(GA, GV, DAG);
277 const TargetData *TD = TM.getTargetData();
278 unsigned Size = TD->getTypeAllocSize(Ty);
279 SDValue offset = DAG.getNode(ISD::MUL, dl, MVT::i32, BuildGetId(DAG, dl),
280 DAG.getConstant(Size, MVT::i32));
281 return DAG.getNode(ISD::ADD, dl, MVT::i32, base, offset);
284 SDValue XCoreTargetLowering::
285 LowerConstantPool(SDValue Op, SelectionDAG &DAG)
287 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
288 // FIXME there isn't really debug info here
289 DebugLoc dl = CP->getDebugLoc();
290 if (Subtarget.isXS1A()) {
291 assert(0 && "Lowering of constant pool unimplemented");
294 MVT PtrVT = Op.getValueType();
296 if (CP->isMachineConstantPoolEntry()) {
297 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
300 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
303 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
307 SDValue XCoreTargetLowering::
308 LowerJumpTable(SDValue Op, SelectionDAG &DAG)
310 // FIXME there isn't really debug info here
311 DebugLoc dl = Op.getDebugLoc();
312 MVT PtrVT = Op.getValueType();
313 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
314 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
315 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, JTI);
318 SDValue XCoreTargetLowering::
319 ExpandADDSUB(SDNode *N, SelectionDAG &DAG)
321 assert(N->getValueType(0) == MVT::i64 &&
322 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
323 "Unknown operand to lower!");
324 assert(!Subtarget.isXS1A() && "Cannot custom lower ADD/SUB on xs1a");
325 DebugLoc dl = N->getDebugLoc();
327 // Extract components
328 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
329 N->getOperand(0), DAG.getConstant(0, MVT::i32));
330 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
331 N->getOperand(0), DAG.getConstant(1, MVT::i32));
332 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
333 N->getOperand(1), DAG.getConstant(0, MVT::i32));
334 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
335 N->getOperand(1), DAG.getConstant(1, MVT::i32));
338 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
340 SDValue Zero = DAG.getConstant(0, MVT::i32);
341 SDValue Carry = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
343 SDValue Lo(Carry.getNode(), 1);
345 SDValue Ignored = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
347 SDValue Hi(Ignored.getNode(), 1);
349 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
352 SDValue XCoreTargetLowering::
353 LowerVAARG(SDValue Op, SelectionDAG &DAG)
355 assert(0 && "unimplemented");
356 // FIX Arguments passed by reference need a extra dereference.
357 SDNode *Node = Op.getNode();
358 DebugLoc dl = Node->getDebugLoc();
359 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
360 MVT VT = Node->getValueType(0);
361 SDValue VAList = DAG.getLoad(getPointerTy(), dl, Node->getOperand(0),
362 Node->getOperand(1), V, 0);
363 // Increment the pointer, VAList, to the next vararg
364 SDValue Tmp3 = DAG.getNode(ISD::ADD, dl, getPointerTy(), VAList,
365 DAG.getConstant(VT.getSizeInBits(),
367 // Store the incremented VAList to the legalized pointer
368 Tmp3 = DAG.getStore(VAList.getValue(1), dl, Tmp3, Node->getOperand(1), V, 0);
369 // Load the actual argument out of the pointer VAList
370 return DAG.getLoad(VT, dl, Tmp3, VAList, NULL, 0);
373 SDValue XCoreTargetLowering::
374 LowerVASTART(SDValue Op, SelectionDAG &DAG)
376 DebugLoc dl = Op.getDebugLoc();
377 // vastart stores the address of the VarArgsFrameIndex slot into the
378 // memory location argument
379 MachineFunction &MF = DAG.getMachineFunction();
380 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
381 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
382 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
383 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1), SV, 0);
386 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
387 DebugLoc dl = Op.getDebugLoc();
388 // Depths > 0 not supported yet!
389 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
392 MachineFunction &MF = DAG.getMachineFunction();
393 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
394 return DAG.getCopyFromReg(DAG.getEntryNode(), dl,
395 RegInfo->getFrameRegister(MF), MVT::i32);
398 //===----------------------------------------------------------------------===//
399 // Calling Convention Implementation
401 // The lower operations present on calling convention works on this order:
402 // LowerCALL (virt regs --> phys regs, virt regs --> stack)
403 // LowerFORMAL_ARGUMENTS (phys --> virt regs, stack --> virt regs)
404 // LowerRET (virt regs --> phys regs)
405 // LowerCALL (phys regs --> virt regs)
407 //===----------------------------------------------------------------------===//
409 #include "XCoreGenCallingConv.inc"
411 //===----------------------------------------------------------------------===//
412 // CALL Calling Convention Implementation
413 //===----------------------------------------------------------------------===//
415 /// XCore custom CALL implementation
416 SDValue XCoreTargetLowering::
417 LowerCALL(SDValue Op, SelectionDAG &DAG)
419 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
420 unsigned CallingConv = TheCall->getCallingConv();
421 // For now, only CallingConv::C implemented
425 assert(0 && "Unsupported calling convention");
426 case CallingConv::Fast:
428 return LowerCCCCallTo(Op, DAG, CallingConv);
432 /// LowerCCCCallTo - functions arguments are copied from virtual
433 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
434 /// CALLSEQ_END are emitted.
435 /// TODO: isTailCall, sret.
436 SDValue XCoreTargetLowering::
437 LowerCCCCallTo(SDValue Op, SelectionDAG &DAG, unsigned CC)
439 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
440 SDValue Chain = TheCall->getChain();
441 SDValue Callee = TheCall->getCallee();
442 bool isVarArg = TheCall->isVarArg();
443 DebugLoc dl = Op.getDebugLoc();
445 // Analyze operands of the call, assigning locations to each operand.
446 SmallVector<CCValAssign, 16> ArgLocs;
447 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
449 // The ABI dictates there should be one stack slot available to the callee
450 // on function entry (for saving lr).
451 CCInfo.AllocateStack(4, 4);
453 CCInfo.AnalyzeCallOperands(TheCall, CC_XCore);
455 // Get a count of how many bytes are to be pushed on the stack.
456 unsigned NumBytes = CCInfo.getNextStackOffset();
458 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
459 getPointerTy(), true));
461 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
462 SmallVector<SDValue, 12> MemOpChains;
464 // Walk the register/memloc assignments, inserting copies/loads.
465 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
466 CCValAssign &VA = ArgLocs[i];
468 // Arguments start after the 5 first operands of ISD::CALL
469 SDValue Arg = TheCall->getArg(i);
471 // Promote the value if needed.
472 switch (VA.getLocInfo()) {
473 default: assert(0 && "Unknown loc info!");
474 case CCValAssign::Full: break;
475 case CCValAssign::SExt:
476 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
478 case CCValAssign::ZExt:
479 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
481 case CCValAssign::AExt:
482 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
486 // Arguments that can be passed on register must be kept at
489 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
491 assert(VA.isMemLoc());
493 int Offset = VA.getLocMemOffset();
495 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
497 DAG.getConstant(Offset/4, MVT::i32)));
501 // Transform all store nodes into one single node because
502 // all store nodes are independent of each other.
503 if (!MemOpChains.empty())
504 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
505 &MemOpChains[0], MemOpChains.size());
507 // Build a sequence of copy-to-reg nodes chained together with token
508 // chain and flag operands which copy the outgoing args into registers.
509 // The InFlag in necessary since all emited instructions must be
512 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
513 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
514 RegsToPass[i].second, InFlag);
515 InFlag = Chain.getValue(1);
518 // If the callee is a GlobalAddress node (quite common, every direct call is)
519 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
520 // Likewise ExternalSymbol -> TargetExternalSymbol.
521 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
522 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32);
523 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
524 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
526 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
527 // = Chain, Callee, Reg#1, Reg#2, ...
529 // Returns a chain & a flag for retval copy to use.
530 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
531 SmallVector<SDValue, 8> Ops;
532 Ops.push_back(Chain);
533 Ops.push_back(Callee);
535 // Add argument registers to the end of the list so that they are
536 // known live into the call.
537 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
538 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
539 RegsToPass[i].second.getValueType()));
541 if (InFlag.getNode())
542 Ops.push_back(InFlag);
544 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, &Ops[0], Ops.size());
545 InFlag = Chain.getValue(1);
547 // Create the CALLSEQ_END node.
548 Chain = DAG.getCALLSEQ_END(Chain,
549 DAG.getConstant(NumBytes, getPointerTy(), true),
550 DAG.getConstant(0, getPointerTy(), true),
552 InFlag = Chain.getValue(1);
554 // Handle result values, copying them out of physregs into vregs that we
556 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
560 /// LowerCallResult - Lower the result values of an ISD::CALL into the
561 /// appropriate copies out of appropriate physical registers. This assumes that
562 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
563 /// being lowered. Returns a SDNode with the same number of values as the
565 SDNode *XCoreTargetLowering::
566 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
567 unsigned CallingConv, SelectionDAG &DAG) {
568 bool isVarArg = TheCall->isVarArg();
569 DebugLoc dl = TheCall->getDebugLoc();
571 // Assign locations to each value returned by this call.
572 SmallVector<CCValAssign, 16> RVLocs;
573 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
575 CCInfo.AnalyzeCallResult(TheCall, RetCC_XCore);
576 SmallVector<SDValue, 8> ResultVals;
578 // Copy all of the result registers out of their specified physreg.
579 for (unsigned i = 0; i != RVLocs.size(); ++i) {
580 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
581 RVLocs[i].getValVT(), InFlag).getValue(1);
582 InFlag = Chain.getValue(2);
583 ResultVals.push_back(Chain.getValue(0));
586 ResultVals.push_back(Chain);
588 // Merge everything together with a MERGE_VALUES node.
589 return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
590 &ResultVals[0], ResultVals.size()).getNode();
593 //===----------------------------------------------------------------------===//
594 // FORMAL_ARGUMENTS Calling Convention Implementation
595 //===----------------------------------------------------------------------===//
597 /// XCore custom FORMAL_ARGUMENTS implementation
598 SDValue XCoreTargetLowering::
599 LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG)
601 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
605 assert(0 && "Unsupported calling convention");
607 case CallingConv::Fast:
608 return LowerCCCArguments(Op, DAG);
612 /// LowerCCCArguments - transform physical registers into
613 /// virtual registers and generate load operations for
614 /// arguments places on the stack.
616 SDValue XCoreTargetLowering::
617 LowerCCCArguments(SDValue Op, SelectionDAG &DAG)
619 MachineFunction &MF = DAG.getMachineFunction();
620 MachineFrameInfo *MFI = MF.getFrameInfo();
621 MachineRegisterInfo &RegInfo = MF.getRegInfo();
622 SDValue Root = Op.getOperand(0);
623 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
624 unsigned CC = MF.getFunction()->getCallingConv();
625 DebugLoc dl = Op.getDebugLoc();
627 // Assign locations to all of the incoming arguments.
628 SmallVector<CCValAssign, 16> ArgLocs;
629 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
631 CCInfo.AnalyzeFormalArguments(Op.getNode(), CC_XCore);
633 unsigned StackSlotSize = XCoreFrameInfo::stackSlotSize();
635 SmallVector<SDValue, 16> ArgValues;
637 unsigned LRSaveSize = StackSlotSize;
639 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
641 CCValAssign &VA = ArgLocs[i];
644 // Arguments passed in registers
645 MVT RegVT = VA.getLocVT();
646 switch (RegVT.getSimpleVT()) {
650 raw_string_ostream Msg(msg);
651 Msg << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
652 << RegVT.getSimpleVT();
653 llvm_report_error(Msg.str());
656 unsigned VReg = RegInfo.createVirtualRegister(
657 XCore::GRRegsRegisterClass);
658 RegInfo.addLiveIn(VA.getLocReg(), VReg);
659 ArgValues.push_back(DAG.getCopyFromReg(Root, dl, VReg, RegVT));
663 assert(VA.isMemLoc());
664 // Load the argument to a virtual register
665 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
666 if (ObjSize > StackSlotSize) {
667 cerr << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
668 << VA.getLocVT().getSimpleVT()
671 // Create the frame index object for this incoming parameter...
672 int FI = MFI->CreateFixedObject(ObjSize,
673 LRSaveSize + VA.getLocMemOffset());
675 // Create the SelectionDAG nodes corresponding to a load
676 //from this parameter
677 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
678 ArgValues.push_back(DAG.getLoad(VA.getLocVT(), dl, Root, FIN, NULL, 0));
683 /* Argument registers */
684 static const unsigned ArgRegs[] = {
685 XCore::R0, XCore::R1, XCore::R2, XCore::R3
687 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
688 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
689 array_lengthof(ArgRegs));
690 if (FirstVAReg < array_lengthof(ArgRegs)) {
691 SmallVector<SDValue, 4> MemOps;
693 // Save remaining registers, storing higher register numbers at a higher
695 for (unsigned i = array_lengthof(ArgRegs) - 1; i >= FirstVAReg; --i) {
696 // Create a stack slot
697 int FI = MFI->CreateFixedObject(4, offset);
698 if (i == FirstVAReg) {
699 XFI->setVarArgsFrameIndex(FI);
701 offset -= StackSlotSize;
702 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
703 // Move argument from phys reg -> virt reg
704 unsigned VReg = RegInfo.createVirtualRegister(
705 XCore::GRRegsRegisterClass);
706 RegInfo.addLiveIn(ArgRegs[i], VReg);
707 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::i32);
708 // Move argument from virt reg -> stack
709 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
710 MemOps.push_back(Store);
713 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
714 &MemOps[0], MemOps.size());
716 // This will point to the next argument passed via stack.
717 XFI->setVarArgsFrameIndex(
718 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset()));
722 ArgValues.push_back(Root);
724 // Return the new list of results.
725 std::vector<MVT> RetVT(Op.getNode()->value_begin(),
726 Op.getNode()->value_end());
727 return DAG.getNode(ISD::MERGE_VALUES, dl, RetVT,
728 &ArgValues[0], ArgValues.size());
731 //===----------------------------------------------------------------------===//
732 // Return Value Calling Convention Implementation
733 //===----------------------------------------------------------------------===//
735 SDValue XCoreTargetLowering::
736 LowerRET(SDValue Op, SelectionDAG &DAG)
738 // CCValAssign - represent the assignment of
739 // the return value to a location
740 SmallVector<CCValAssign, 16> RVLocs;
741 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
742 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
743 DebugLoc dl = Op.getDebugLoc();
745 // CCState - Info about the registers and stack slot.
746 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
748 // Analize return values of ISD::RET
749 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_XCore);
751 // If this is the first return lowered for this function, add
752 // the regs to the liveout set for the function.
753 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
754 for (unsigned i = 0; i != RVLocs.size(); ++i)
755 if (RVLocs[i].isRegLoc())
756 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
759 // The chain is always operand #0
760 SDValue Chain = Op.getOperand(0);
763 // Copy the result values into the output registers.
764 for (unsigned i = 0; i != RVLocs.size(); ++i) {
765 CCValAssign &VA = RVLocs[i];
766 assert(VA.isRegLoc() && "Can only return in registers!");
768 // ISD::RET => ret chain, (regnum1,val1), ...
769 // So i*2+1 index only the regnums
770 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
771 Op.getOperand(i*2+1), Flag);
773 // guarantee that all emitted copies are
774 // stuck together, avoiding something bad
775 Flag = Chain.getValue(1);
778 // Return on XCore is always a "retsp 0"
780 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
781 Chain, DAG.getConstant(0, MVT::i32), Flag);
783 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
784 Chain, DAG.getConstant(0, MVT::i32));
787 //===----------------------------------------------------------------------===//
788 // Other Lowering Code
789 //===----------------------------------------------------------------------===//
792 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
793 MachineBasicBlock *BB) const {
794 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
795 DebugLoc dl = MI->getDebugLoc();
796 assert((MI->getOpcode() == XCore::SELECT_CC) &&
797 "Unexpected instr type to insert");
799 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
800 // control-flow pattern. The incoming instruction knows the destination vreg
801 // to set, the condition code register to branch on, the true/false values to
802 // select between, and a branch opcode to use.
803 const BasicBlock *LLVM_BB = BB->getBasicBlock();
804 MachineFunction::iterator It = BB;
812 // fallthrough --> copy0MBB
813 MachineBasicBlock *thisMBB = BB;
814 MachineFunction *F = BB->getParent();
815 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
816 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
817 BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
818 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
819 F->insert(It, copy0MBB);
820 F->insert(It, sinkMBB);
821 // Update machine-CFG edges by transferring all successors of the current
822 // block to the new block which will contain the Phi node for the select.
823 sinkMBB->transferSuccessors(BB);
824 // Next, add the true and fallthrough blocks as its successors.
825 BB->addSuccessor(copy0MBB);
826 BB->addSuccessor(sinkMBB);
830 // # fallthrough to sinkMBB
833 // Update machine-CFG edges
834 BB->addSuccessor(sinkMBB);
837 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
840 BuildMI(BB, dl, TII.get(XCore::PHI), MI->getOperand(0).getReg())
841 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
842 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
844 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
848 //===----------------------------------------------------------------------===//
849 // Addressing mode description hooks
850 //===----------------------------------------------------------------------===//
852 static inline bool isImmUs(int64_t val)
854 return (val >= 0 && val <= 11);
857 static inline bool isImmUs2(int64_t val)
859 return (val%2 == 0 && isImmUs(val/2));
862 static inline bool isImmUs4(int64_t val)
864 return (val%4 == 0 && isImmUs(val/4));
867 /// isLegalAddressingMode - Return true if the addressing mode represented
868 /// by AM is legal for this target, for a load/store of the specified type.
870 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
871 const Type *Ty) const {
872 MVT VT = getValueType(Ty, true);
873 // Get expected value type after legalization
874 switch (VT.getSimpleVT()) {
875 // Legal load / stores
884 // Everything else is lowered to words
890 return VT == MVT::i32 && !AM.HasBaseReg && AM.Scale == 0 &&
894 switch (VT.getSimpleVT()) {
900 return isImmUs(AM.BaseOffs);
902 return AM.Scale == 1 && AM.BaseOffs == 0;
906 return isImmUs2(AM.BaseOffs);
908 return AM.Scale == 2 && AM.BaseOffs == 0;
912 return isImmUs4(AM.BaseOffs);
915 return AM.Scale == 4 && AM.BaseOffs == 0;
921 //===----------------------------------------------------------------------===//
922 // XCore Inline Assembly Support
923 //===----------------------------------------------------------------------===//
925 std::vector<unsigned> XCoreTargetLowering::
926 getRegClassForInlineAsmConstraint(const std::string &Constraint,
929 if (Constraint.size() != 1)
930 return std::vector<unsigned>();
932 switch (Constraint[0]) {
935 return make_vector<unsigned>(XCore::R0, XCore::R1, XCore::R2,
936 XCore::R3, XCore::R4, XCore::R5,
937 XCore::R6, XCore::R7, XCore::R8,
938 XCore::R9, XCore::R10, XCore::R11, 0);
941 return std::vector<unsigned>();