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/Support/ErrorHandling.h"
36 #include "llvm/ADT/VectorExtras.h"
41 const char *XCoreTargetLowering::
42 getTargetNodeName(unsigned Opcode) const
46 case XCoreISD::BL : return "XCoreISD::BL";
47 case XCoreISD::PCRelativeWrapper : return "XCoreISD::PCRelativeWrapper";
48 case XCoreISD::DPRelativeWrapper : return "XCoreISD::DPRelativeWrapper";
49 case XCoreISD::CPRelativeWrapper : return "XCoreISD::CPRelativeWrapper";
50 case XCoreISD::STWSP : return "XCoreISD::STWSP";
51 case XCoreISD::RETSP : return "XCoreISD::RETSP";
52 default : return NULL;
56 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
57 : TargetLowering(XTM),
59 Subtarget(*XTM.getSubtargetImpl()) {
61 // Set up the register classes.
62 addRegisterClass(MVT::i32, XCore::GRRegsRegisterClass);
64 // Compute derived properties from the register classes
65 computeRegisterProperties();
67 // Division is expensive
68 setIntDivIsCheap(false);
70 setShiftAmountType(MVT::i32);
72 setShiftAmountFlavor(Extend);
73 setStackPointerRegisterToSaveRestore(XCore::SP);
75 setSchedulingPreference(SchedulingForRegPressure);
77 // Use i32 for setcc operations results (slt, sgt, ...).
78 setBooleanContents(ZeroOrOneBooleanContent);
80 // XCore does not have the NodeTypes below.
81 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
82 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
83 setOperationAction(ISD::ADDC, MVT::i32, Expand);
84 setOperationAction(ISD::ADDE, MVT::i32, Expand);
85 setOperationAction(ISD::SUBC, MVT::i32, Expand);
86 setOperationAction(ISD::SUBE, MVT::i32, Expand);
88 // Stop the combiner recombining select and set_cc
89 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
92 if (!Subtarget.isXS1A()) {
93 setOperationAction(ISD::ADD, MVT::i64, Custom);
94 setOperationAction(ISD::SUB, MVT::i64, Custom);
96 if (Subtarget.isXS1A()) {
97 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
99 setOperationAction(ISD::MULHS, MVT::i32, Expand);
100 setOperationAction(ISD::MULHU, MVT::i32, Expand);
101 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
102 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
103 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
106 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
107 setOperationAction(ISD::ROTL , MVT::i32, Expand);
108 setOperationAction(ISD::ROTR , MVT::i32, Expand);
110 setOperationAction(ISD::TRAP, MVT::Other, Legal);
112 // Expand jump tables for now
113 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
114 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
116 // RET must be custom lowered, to meet ABI requirements
117 setOperationAction(ISD::RET, MVT::Other, Custom);
119 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
121 // Thread Local Storage
122 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
124 // Conversion of i64 -> double produces constantpool nodes
125 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
128 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
129 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
130 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
132 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
133 setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
136 setOperationAction(ISD::VAEND, MVT::Other, Expand);
137 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
138 setOperationAction(ISD::VAARG, MVT::Other, Custom);
139 setOperationAction(ISD::VASTART, MVT::Other, Custom);
142 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
143 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
144 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
147 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
148 setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
151 SDValue XCoreTargetLowering::
152 LowerOperation(SDValue Op, SelectionDAG &DAG) {
153 switch (Op.getOpcode())
155 case ISD::CALL: return LowerCALL(Op, DAG);
156 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
157 case ISD::RET: return LowerRET(Op, DAG);
158 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
159 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
160 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
161 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
162 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
163 case ISD::VAARG: return LowerVAARG(Op, DAG);
164 case ISD::VASTART: return LowerVASTART(Op, DAG);
165 // FIXME: Remove these when LegalizeDAGTypes lands.
167 case ISD::SUB: return ExpandADDSUB(Op.getNode(), DAG);
168 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
170 llvm_unreachable("unimplemented operand");
175 /// ReplaceNodeResults - Replace the results of node with an illegal result
176 /// type with new values built out of custom code.
177 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
178 SmallVectorImpl<SDValue>&Results,
180 switch (N->getOpcode()) {
182 llvm_unreachable("Don't know how to custom expand this!");
186 Results.push_back(ExpandADDSUB(N, DAG));
191 /// getFunctionAlignment - Return the Log2 alignment of this function.
192 unsigned XCoreTargetLowering::
193 getFunctionAlignment(const Function *) const {
197 //===----------------------------------------------------------------------===//
198 // Misc Lower Operation implementation
199 //===----------------------------------------------------------------------===//
201 SDValue XCoreTargetLowering::
202 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG)
204 DebugLoc dl = Op.getDebugLoc();
205 SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i32, Op.getOperand(2),
206 Op.getOperand(3), Op.getOperand(4));
207 return DAG.getNode(ISD::SELECT, dl, MVT::i32, Cond, Op.getOperand(0),
211 SDValue XCoreTargetLowering::
212 getGlobalAddressWrapper(SDValue GA, GlobalValue *GV, SelectionDAG &DAG)
214 // FIXME there is no actual debug info here
215 DebugLoc dl = GA.getDebugLoc();
216 if (isa<Function>(GV)) {
217 return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
218 } else if (!Subtarget.isXS1A()) {
219 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
221 // If GV is an alias then use the aliasee to determine constness
222 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
223 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
225 bool isConst = GVar && GVar->isConstant();
227 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
230 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
233 SDValue XCoreTargetLowering::
234 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG)
236 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
237 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
238 // If it's a debug information descriptor, don't mess with it.
239 if (DAG.isVerifiedDebugInfoDesc(Op))
241 return getGlobalAddressWrapper(GA, GV, DAG);
244 static inline SDValue BuildGetId(SelectionDAG &DAG, DebugLoc dl) {
245 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
246 DAG.getConstant(Intrinsic::xcore_getid, MVT::i32));
249 static inline bool isZeroLengthArray(const Type *Ty) {
250 const ArrayType *AT = dyn_cast_or_null<ArrayType>(Ty);
251 return AT && (AT->getNumElements() == 0);
254 SDValue XCoreTargetLowering::
255 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG)
257 // FIXME there isn't really debug info here
258 DebugLoc dl = Op.getDebugLoc();
259 // transform to label + getid() * size
260 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
261 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
262 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
264 // If GV is an alias then use the aliasee to determine size
265 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
266 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
269 llvm_unreachable("Thread local object not a GlobalVariable?");
272 const Type *Ty = cast<PointerType>(GV->getType())->getElementType();
273 if (!Ty->isSized() || isZeroLengthArray(Ty)) {
275 cerr << "Size of thread local object " << GVar->getName()
280 SDValue base = getGlobalAddressWrapper(GA, GV, DAG);
281 const TargetData *TD = TM.getTargetData();
282 unsigned Size = TD->getTypeAllocSize(Ty);
283 SDValue offset = DAG.getNode(ISD::MUL, dl, MVT::i32, BuildGetId(DAG, dl),
284 DAG.getConstant(Size, MVT::i32));
285 return DAG.getNode(ISD::ADD, dl, MVT::i32, base, offset);
288 SDValue XCoreTargetLowering::
289 LowerConstantPool(SDValue Op, SelectionDAG &DAG)
291 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
292 // FIXME there isn't really debug info here
293 DebugLoc dl = CP->getDebugLoc();
294 if (Subtarget.isXS1A()) {
295 llvm_unreachable("Lowering of constant pool unimplemented");
298 MVT PtrVT = Op.getValueType();
300 if (CP->isMachineConstantPoolEntry()) {
301 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
304 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
307 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
311 SDValue XCoreTargetLowering::
312 LowerJumpTable(SDValue Op, SelectionDAG &DAG)
314 // FIXME there isn't really debug info here
315 DebugLoc dl = Op.getDebugLoc();
316 MVT PtrVT = Op.getValueType();
317 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
318 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
319 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, JTI);
322 SDValue XCoreTargetLowering::
323 ExpandADDSUB(SDNode *N, SelectionDAG &DAG)
325 assert(N->getValueType(0) == MVT::i64 &&
326 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
327 "Unknown operand to lower!");
328 assert(!Subtarget.isXS1A() && "Cannot custom lower ADD/SUB on xs1a");
329 DebugLoc dl = N->getDebugLoc();
331 // Extract components
332 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
333 N->getOperand(0), DAG.getConstant(0, MVT::i32));
334 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
335 N->getOperand(0), DAG.getConstant(1, MVT::i32));
336 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
337 N->getOperand(1), DAG.getConstant(0, MVT::i32));
338 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
339 N->getOperand(1), DAG.getConstant(1, MVT::i32));
342 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
344 SDValue Zero = DAG.getConstant(0, MVT::i32);
345 SDValue Carry = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
347 SDValue Lo(Carry.getNode(), 1);
349 SDValue Ignored = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
351 SDValue Hi(Ignored.getNode(), 1);
353 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
356 SDValue XCoreTargetLowering::
357 LowerVAARG(SDValue Op, SelectionDAG &DAG)
359 llvm_unreachable("unimplemented");
360 // FIX Arguments passed by reference need a extra dereference.
361 SDNode *Node = Op.getNode();
362 DebugLoc dl = Node->getDebugLoc();
363 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
364 MVT VT = Node->getValueType(0);
365 SDValue VAList = DAG.getLoad(getPointerTy(), dl, Node->getOperand(0),
366 Node->getOperand(1), V, 0);
367 // Increment the pointer, VAList, to the next vararg
368 SDValue Tmp3 = DAG.getNode(ISD::ADD, dl, getPointerTy(), VAList,
369 DAG.getConstant(VT.getSizeInBits(),
371 // Store the incremented VAList to the legalized pointer
372 Tmp3 = DAG.getStore(VAList.getValue(1), dl, Tmp3, Node->getOperand(1), V, 0);
373 // Load the actual argument out of the pointer VAList
374 return DAG.getLoad(VT, dl, Tmp3, VAList, NULL, 0);
377 SDValue XCoreTargetLowering::
378 LowerVASTART(SDValue Op, SelectionDAG &DAG)
380 DebugLoc dl = Op.getDebugLoc();
381 // vastart stores the address of the VarArgsFrameIndex slot into the
382 // memory location argument
383 MachineFunction &MF = DAG.getMachineFunction();
384 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
385 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
386 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
387 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1), SV, 0);
390 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
391 DebugLoc dl = Op.getDebugLoc();
392 // Depths > 0 not supported yet!
393 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
396 MachineFunction &MF = DAG.getMachineFunction();
397 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
398 return DAG.getCopyFromReg(DAG.getEntryNode(), dl,
399 RegInfo->getFrameRegister(MF), MVT::i32);
402 //===----------------------------------------------------------------------===//
403 // Calling Convention Implementation
405 // The lower operations present on calling convention works on this order:
406 // LowerCALL (virt regs --> phys regs, virt regs --> stack)
407 // LowerFORMAL_ARGUMENTS (phys --> virt regs, stack --> virt regs)
408 // LowerRET (virt regs --> phys regs)
409 // LowerCALL (phys regs --> virt regs)
411 //===----------------------------------------------------------------------===//
413 #include "XCoreGenCallingConv.inc"
415 //===----------------------------------------------------------------------===//
416 // CALL Calling Convention Implementation
417 //===----------------------------------------------------------------------===//
419 /// XCore custom CALL implementation
420 SDValue XCoreTargetLowering::
421 LowerCALL(SDValue Op, SelectionDAG &DAG)
423 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
424 unsigned CallingConv = TheCall->getCallingConv();
425 // For now, only CallingConv::C implemented
429 llvm_unreachable("Unsupported calling convention");
430 case CallingConv::Fast:
432 return LowerCCCCallTo(Op, DAG, CallingConv);
436 /// LowerCCCCallTo - functions arguments are copied from virtual
437 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
438 /// CALLSEQ_END are emitted.
439 /// TODO: isTailCall, sret.
440 SDValue XCoreTargetLowering::
441 LowerCCCCallTo(SDValue Op, SelectionDAG &DAG, unsigned CC)
443 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
444 SDValue Chain = TheCall->getChain();
445 SDValue Callee = TheCall->getCallee();
446 bool isVarArg = TheCall->isVarArg();
447 DebugLoc dl = Op.getDebugLoc();
449 // Analyze operands of the call, assigning locations to each operand.
450 SmallVector<CCValAssign, 16> ArgLocs;
451 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs, DAG.getContext());
453 // The ABI dictates there should be one stack slot available to the callee
454 // on function entry (for saving lr).
455 CCInfo.AllocateStack(4, 4);
457 CCInfo.AnalyzeCallOperands(TheCall, CC_XCore);
459 // Get a count of how many bytes are to be pushed on the stack.
460 unsigned NumBytes = CCInfo.getNextStackOffset();
462 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
463 getPointerTy(), true));
465 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
466 SmallVector<SDValue, 12> MemOpChains;
468 // Walk the register/memloc assignments, inserting copies/loads.
469 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
470 CCValAssign &VA = ArgLocs[i];
472 // Arguments start after the 5 first operands of ISD::CALL
473 SDValue Arg = TheCall->getArg(i);
475 // Promote the value if needed.
476 switch (VA.getLocInfo()) {
477 default: llvm_unreachable("Unknown loc info!");
478 case CCValAssign::Full: break;
479 case CCValAssign::SExt:
480 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
482 case CCValAssign::ZExt:
483 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
485 case CCValAssign::AExt:
486 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
490 // Arguments that can be passed on register must be kept at
493 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
495 assert(VA.isMemLoc());
497 int Offset = VA.getLocMemOffset();
499 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
501 DAG.getConstant(Offset/4, MVT::i32)));
505 // Transform all store nodes into one single node because
506 // all store nodes are independent of each other.
507 if (!MemOpChains.empty())
508 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
509 &MemOpChains[0], MemOpChains.size());
511 // Build a sequence of copy-to-reg nodes chained together with token
512 // chain and flag operands which copy the outgoing args into registers.
513 // The InFlag in necessary since all emited instructions must be
516 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
517 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
518 RegsToPass[i].second, InFlag);
519 InFlag = Chain.getValue(1);
522 // If the callee is a GlobalAddress node (quite common, every direct call is)
523 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
524 // Likewise ExternalSymbol -> TargetExternalSymbol.
525 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
526 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32);
527 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
528 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
530 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
531 // = Chain, Callee, Reg#1, Reg#2, ...
533 // Returns a chain & a flag for retval copy to use.
534 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
535 SmallVector<SDValue, 8> Ops;
536 Ops.push_back(Chain);
537 Ops.push_back(Callee);
539 // Add argument registers to the end of the list so that they are
540 // known live into the call.
541 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
542 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
543 RegsToPass[i].second.getValueType()));
545 if (InFlag.getNode())
546 Ops.push_back(InFlag);
548 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, &Ops[0], Ops.size());
549 InFlag = Chain.getValue(1);
551 // Create the CALLSEQ_END node.
552 Chain = DAG.getCALLSEQ_END(Chain,
553 DAG.getConstant(NumBytes, getPointerTy(), true),
554 DAG.getConstant(0, getPointerTy(), true),
556 InFlag = Chain.getValue(1);
558 // Handle result values, copying them out of physregs into vregs that we
560 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
564 /// LowerCallResult - Lower the result values of an ISD::CALL into the
565 /// appropriate copies out of appropriate physical registers. This assumes that
566 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
567 /// being lowered. Returns a SDNode with the same number of values as the
569 SDNode *XCoreTargetLowering::
570 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
571 unsigned CallingConv, SelectionDAG &DAG) {
572 bool isVarArg = TheCall->isVarArg();
573 DebugLoc dl = TheCall->getDebugLoc();
575 // Assign locations to each value returned by this call.
576 SmallVector<CCValAssign, 16> RVLocs;
577 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(),
578 RVLocs, DAG.getContext());
580 CCInfo.AnalyzeCallResult(TheCall, RetCC_XCore);
581 SmallVector<SDValue, 8> ResultVals;
583 // Copy all of the result registers out of their specified physreg.
584 for (unsigned i = 0; i != RVLocs.size(); ++i) {
585 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
586 RVLocs[i].getValVT(), InFlag).getValue(1);
587 InFlag = Chain.getValue(2);
588 ResultVals.push_back(Chain.getValue(0));
591 ResultVals.push_back(Chain);
593 // Merge everything together with a MERGE_VALUES node.
594 return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
595 &ResultVals[0], ResultVals.size()).getNode();
598 //===----------------------------------------------------------------------===//
599 // FORMAL_ARGUMENTS Calling Convention Implementation
600 //===----------------------------------------------------------------------===//
602 /// XCore custom FORMAL_ARGUMENTS implementation
603 SDValue XCoreTargetLowering::
604 LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG)
606 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
610 llvm_unreachable("Unsupported calling convention");
612 case CallingConv::Fast:
613 return LowerCCCArguments(Op, DAG);
617 /// LowerCCCArguments - transform physical registers into
618 /// virtual registers and generate load operations for
619 /// arguments places on the stack.
621 SDValue XCoreTargetLowering::
622 LowerCCCArguments(SDValue Op, SelectionDAG &DAG)
624 MachineFunction &MF = DAG.getMachineFunction();
625 MachineFrameInfo *MFI = MF.getFrameInfo();
626 MachineRegisterInfo &RegInfo = MF.getRegInfo();
627 SDValue Root = Op.getOperand(0);
628 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
629 unsigned CC = MF.getFunction()->getCallingConv();
630 DebugLoc dl = Op.getDebugLoc();
632 // Assign locations to all of the incoming arguments.
633 SmallVector<CCValAssign, 16> ArgLocs;
634 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs, DAG.getContext());
636 CCInfo.AnalyzeFormalArguments(Op.getNode(), CC_XCore);
638 unsigned StackSlotSize = XCoreFrameInfo::stackSlotSize();
640 SmallVector<SDValue, 16> ArgValues;
642 unsigned LRSaveSize = StackSlotSize;
644 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
646 CCValAssign &VA = ArgLocs[i];
649 // Arguments passed in registers
650 MVT RegVT = VA.getLocVT();
651 switch (RegVT.getSimpleVT()) {
655 cerr << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
656 << RegVT.getSimpleVT() << "\n";
661 unsigned VReg = RegInfo.createVirtualRegister(
662 XCore::GRRegsRegisterClass);
663 RegInfo.addLiveIn(VA.getLocReg(), VReg);
664 ArgValues.push_back(DAG.getCopyFromReg(Root, dl, VReg, RegVT));
668 assert(VA.isMemLoc());
669 // Load the argument to a virtual register
670 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
671 if (ObjSize > StackSlotSize) {
672 cerr << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
673 << VA.getLocVT().getSimpleVT()
676 // Create the frame index object for this incoming parameter...
677 int FI = MFI->CreateFixedObject(ObjSize,
678 LRSaveSize + VA.getLocMemOffset());
680 // Create the SelectionDAG nodes corresponding to a load
681 //from this parameter
682 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
683 ArgValues.push_back(DAG.getLoad(VA.getLocVT(), dl, Root, FIN, NULL, 0));
688 /* Argument registers */
689 static const unsigned ArgRegs[] = {
690 XCore::R0, XCore::R1, XCore::R2, XCore::R3
692 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
693 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
694 array_lengthof(ArgRegs));
695 if (FirstVAReg < array_lengthof(ArgRegs)) {
696 SmallVector<SDValue, 4> MemOps;
698 // Save remaining registers, storing higher register numbers at a higher
700 for (unsigned i = array_lengthof(ArgRegs) - 1; i >= FirstVAReg; --i) {
701 // Create a stack slot
702 int FI = MFI->CreateFixedObject(4, offset);
703 if (i == FirstVAReg) {
704 XFI->setVarArgsFrameIndex(FI);
706 offset -= StackSlotSize;
707 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
708 // Move argument from phys reg -> virt reg
709 unsigned VReg = RegInfo.createVirtualRegister(
710 XCore::GRRegsRegisterClass);
711 RegInfo.addLiveIn(ArgRegs[i], VReg);
712 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::i32);
713 // Move argument from virt reg -> stack
714 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
715 MemOps.push_back(Store);
718 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
719 &MemOps[0], MemOps.size());
721 // This will point to the next argument passed via stack.
722 XFI->setVarArgsFrameIndex(
723 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset()));
727 ArgValues.push_back(Root);
729 // Return the new list of results.
730 std::vector<MVT> RetVT(Op.getNode()->value_begin(),
731 Op.getNode()->value_end());
732 return DAG.getNode(ISD::MERGE_VALUES, dl, RetVT,
733 &ArgValues[0], ArgValues.size());
736 //===----------------------------------------------------------------------===//
737 // Return Value Calling Convention Implementation
738 //===----------------------------------------------------------------------===//
740 SDValue XCoreTargetLowering::
741 LowerRET(SDValue Op, SelectionDAG &DAG)
743 // CCValAssign - represent the assignment of
744 // the return value to a location
745 SmallVector<CCValAssign, 16> RVLocs;
746 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
747 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
748 DebugLoc dl = Op.getDebugLoc();
750 // CCState - Info about the registers and stack slot.
751 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs, DAG.getContext());
753 // Analize return values of ISD::RET
754 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_XCore);
756 // If this is the first return lowered for this function, add
757 // the regs to the liveout set for the function.
758 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
759 for (unsigned i = 0; i != RVLocs.size(); ++i)
760 if (RVLocs[i].isRegLoc())
761 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
764 // The chain is always operand #0
765 SDValue Chain = Op.getOperand(0);
768 // Copy the result values into the output registers.
769 for (unsigned i = 0; i != RVLocs.size(); ++i) {
770 CCValAssign &VA = RVLocs[i];
771 assert(VA.isRegLoc() && "Can only return in registers!");
773 // ISD::RET => ret chain, (regnum1,val1), ...
774 // So i*2+1 index only the regnums
775 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
776 Op.getOperand(i*2+1), Flag);
778 // guarantee that all emitted copies are
779 // stuck together, avoiding something bad
780 Flag = Chain.getValue(1);
783 // Return on XCore is always a "retsp 0"
785 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
786 Chain, DAG.getConstant(0, MVT::i32), Flag);
788 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
789 Chain, DAG.getConstant(0, MVT::i32));
792 //===----------------------------------------------------------------------===//
793 // Other Lowering Code
794 //===----------------------------------------------------------------------===//
797 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
798 MachineBasicBlock *BB) const {
799 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
800 DebugLoc dl = MI->getDebugLoc();
801 assert((MI->getOpcode() == XCore::SELECT_CC) &&
802 "Unexpected instr type to insert");
804 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
805 // control-flow pattern. The incoming instruction knows the destination vreg
806 // to set, the condition code register to branch on, the true/false values to
807 // select between, and a branch opcode to use.
808 const BasicBlock *LLVM_BB = BB->getBasicBlock();
809 MachineFunction::iterator It = BB;
817 // fallthrough --> copy0MBB
818 MachineBasicBlock *thisMBB = BB;
819 MachineFunction *F = BB->getParent();
820 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
821 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
822 BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
823 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
824 F->insert(It, copy0MBB);
825 F->insert(It, sinkMBB);
826 // Update machine-CFG edges by transferring all successors of the current
827 // block to the new block which will contain the Phi node for the select.
828 sinkMBB->transferSuccessors(BB);
829 // Next, add the true and fallthrough blocks as its successors.
830 BB->addSuccessor(copy0MBB);
831 BB->addSuccessor(sinkMBB);
835 // # fallthrough to sinkMBB
838 // Update machine-CFG edges
839 BB->addSuccessor(sinkMBB);
842 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
845 BuildMI(BB, dl, TII.get(XCore::PHI), MI->getOperand(0).getReg())
846 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
847 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
849 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
853 //===----------------------------------------------------------------------===//
854 // Addressing mode description hooks
855 //===----------------------------------------------------------------------===//
857 static inline bool isImmUs(int64_t val)
859 return (val >= 0 && val <= 11);
862 static inline bool isImmUs2(int64_t val)
864 return (val%2 == 0 && isImmUs(val/2));
867 static inline bool isImmUs4(int64_t val)
869 return (val%4 == 0 && isImmUs(val/4));
872 /// isLegalAddressingMode - Return true if the addressing mode represented
873 /// by AM is legal for this target, for a load/store of the specified type.
875 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
876 const Type *Ty) const {
877 MVT VT = getValueType(Ty, true);
878 // Get expected value type after legalization
879 switch (VT.getSimpleVT()) {
880 // Legal load / stores
889 // Everything else is lowered to words
895 return VT == MVT::i32 && !AM.HasBaseReg && AM.Scale == 0 &&
899 switch (VT.getSimpleVT()) {
905 return isImmUs(AM.BaseOffs);
907 return AM.Scale == 1 && AM.BaseOffs == 0;
911 return isImmUs2(AM.BaseOffs);
913 return AM.Scale == 2 && AM.BaseOffs == 0;
917 return isImmUs4(AM.BaseOffs);
920 return AM.Scale == 4 && AM.BaseOffs == 0;
926 //===----------------------------------------------------------------------===//
927 // XCore Inline Assembly Support
928 //===----------------------------------------------------------------------===//
930 std::vector<unsigned> XCoreTargetLowering::
931 getRegClassForInlineAsmConstraint(const std::string &Constraint,
934 if (Constraint.size() != 1)
935 return std::vector<unsigned>();
937 switch (Constraint[0]) {
940 return make_vector<unsigned>(XCore::R0, XCore::R1, XCore::R2,
941 XCore::R3, XCore::R4, XCore::R5,
942 XCore::R6, XCore::R7, XCore::R8,
943 XCore::R9, XCore::R10, XCore::R11, 0);
946 return std::vector<unsigned>();