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);
135 // Custom expand misaligned loads / stores.
136 setOperationAction(ISD::LOAD, MVT::i32, Custom);
137 setOperationAction(ISD::STORE, MVT::i32, Custom);
140 setOperationAction(ISD::VAEND, MVT::Other, Expand);
141 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
142 setOperationAction(ISD::VAARG, MVT::Other, Custom);
143 setOperationAction(ISD::VASTART, MVT::Other, Custom);
146 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
147 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
148 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
151 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
152 setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
154 maxStoresPerMemset = 4;
155 maxStoresPerMemmove = maxStoresPerMemcpy = 2;
158 SDValue XCoreTargetLowering::
159 LowerOperation(SDValue Op, SelectionDAG &DAG) {
160 switch (Op.getOpcode())
162 case ISD::CALL: return LowerCALL(Op, DAG);
163 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
164 case ISD::RET: return LowerRET(Op, DAG);
165 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
166 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
167 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
168 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
169 case ISD::LOAD: return LowerLOAD(Op, DAG);
170 case ISD::STORE: return LowerSTORE(Op, DAG);
171 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
172 case ISD::VAARG: return LowerVAARG(Op, DAG);
173 case ISD::VASTART: return LowerVASTART(Op, DAG);
174 // FIXME: Remove these when LegalizeDAGTypes lands.
176 case ISD::SUB: return ExpandADDSUB(Op.getNode(), DAG);
177 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
179 llvm_unreachable("unimplemented operand");
184 /// ReplaceNodeResults - Replace the results of node with an illegal result
185 /// type with new values built out of custom code.
186 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
187 SmallVectorImpl<SDValue>&Results,
189 switch (N->getOpcode()) {
191 llvm_unreachable("Don't know how to custom expand this!");
195 Results.push_back(ExpandADDSUB(N, DAG));
200 /// getFunctionAlignment - Return the Log2 alignment of this function.
201 unsigned XCoreTargetLowering::
202 getFunctionAlignment(const Function *) const {
206 //===----------------------------------------------------------------------===//
207 // Misc Lower Operation implementation
208 //===----------------------------------------------------------------------===//
210 SDValue XCoreTargetLowering::
211 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG)
213 DebugLoc dl = Op.getDebugLoc();
214 SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i32, Op.getOperand(2),
215 Op.getOperand(3), Op.getOperand(4));
216 return DAG.getNode(ISD::SELECT, dl, MVT::i32, Cond, Op.getOperand(0),
220 SDValue XCoreTargetLowering::
221 getGlobalAddressWrapper(SDValue GA, GlobalValue *GV, SelectionDAG &DAG)
223 // FIXME there is no actual debug info here
224 DebugLoc dl = GA.getDebugLoc();
225 if (isa<Function>(GV)) {
226 return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
227 } else if (!Subtarget.isXS1A()) {
228 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
230 // If GV is an alias then use the aliasee to determine constness
231 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
232 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
234 bool isConst = GVar && GVar->isConstant();
236 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
239 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
242 SDValue XCoreTargetLowering::
243 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG)
245 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
246 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
247 // If it's a debug information descriptor, don't mess with it.
248 if (DAG.isVerifiedDebugInfoDesc(Op))
250 return getGlobalAddressWrapper(GA, GV, DAG);
253 static inline SDValue BuildGetId(SelectionDAG &DAG, DebugLoc dl) {
254 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
255 DAG.getConstant(Intrinsic::xcore_getid, MVT::i32));
258 static inline bool isZeroLengthArray(const Type *Ty) {
259 const ArrayType *AT = dyn_cast_or_null<ArrayType>(Ty);
260 return AT && (AT->getNumElements() == 0);
263 SDValue XCoreTargetLowering::
264 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG)
266 // FIXME there isn't really debug info here
267 DebugLoc dl = Op.getDebugLoc();
268 // transform to label + getid() * size
269 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
270 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
271 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
273 // If GV is an alias then use the aliasee to determine size
274 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
275 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
278 llvm_unreachable("Thread local object not a GlobalVariable?");
281 const Type *Ty = cast<PointerType>(GV->getType())->getElementType();
282 if (!Ty->isSized() || isZeroLengthArray(Ty)) {
284 cerr << "Size of thread local object " << GVar->getName()
289 SDValue base = getGlobalAddressWrapper(GA, GV, DAG);
290 const TargetData *TD = TM.getTargetData();
291 unsigned Size = TD->getTypeAllocSize(Ty);
292 SDValue offset = DAG.getNode(ISD::MUL, dl, MVT::i32, BuildGetId(DAG, dl),
293 DAG.getConstant(Size, MVT::i32));
294 return DAG.getNode(ISD::ADD, dl, MVT::i32, base, offset);
297 SDValue XCoreTargetLowering::
298 LowerConstantPool(SDValue Op, SelectionDAG &DAG)
300 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
301 // FIXME there isn't really debug info here
302 DebugLoc dl = CP->getDebugLoc();
303 if (Subtarget.isXS1A()) {
304 llvm_unreachable("Lowering of constant pool unimplemented");
307 MVT PtrVT = Op.getValueType();
309 if (CP->isMachineConstantPoolEntry()) {
310 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
313 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
316 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
320 SDValue XCoreTargetLowering::
321 LowerJumpTable(SDValue Op, SelectionDAG &DAG)
323 // FIXME there isn't really debug info here
324 DebugLoc dl = Op.getDebugLoc();
325 MVT PtrVT = Op.getValueType();
326 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
327 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
328 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, JTI);
332 IsWordAlignedBasePlusConstantOffset(SDValue Addr, SDValue &AlignedBase,
335 if (Addr.getOpcode() != ISD::ADD) {
338 ConstantSDNode *CN = 0;
339 if (!(CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
342 int64_t off = CN->getSExtValue();
343 const SDValue &Base = Addr.getOperand(0);
344 const SDValue *Root = &Base;
345 if (Base.getOpcode() == ISD::ADD &&
346 Base.getOperand(1).getOpcode() == ISD::SHL) {
347 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Base.getOperand(1)
349 if (CN && (CN->getSExtValue() >= 2)) {
350 Root = &Base.getOperand(0);
353 if (isa<FrameIndexSDNode>(*Root)) {
354 // All frame indicies are word aligned
359 if (Root->getOpcode() == XCoreISD::DPRelativeWrapper ||
360 Root->getOpcode() == XCoreISD::CPRelativeWrapper) {
361 // All dp / cp relative addresses are word aligned
369 SDValue XCoreTargetLowering::
370 LowerLOAD(SDValue Op, SelectionDAG &DAG)
372 LoadSDNode *LD = cast<LoadSDNode>(Op);
373 assert(LD->getExtensionType() == ISD::NON_EXTLOAD && "Unexpected extension type");
374 assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load MVT");
375 if (allowsUnalignedMemoryAccesses()) {
378 unsigned ABIAlignment = getTargetData()->
379 getABITypeAlignment(LD->getMemoryVT().getTypeForMVT(*DAG.getContext()));
380 // Leave aligned load alone.
381 if (LD->getAlignment() >= ABIAlignment) {
384 SDValue Chain = LD->getChain();
385 SDValue BasePtr = LD->getBasePtr();
386 DebugLoc dl = Op.getDebugLoc();
390 if (!LD->isVolatile() &&
391 IsWordAlignedBasePlusConstantOffset(BasePtr, Base, Offset)) {
392 if (Offset % 4 == 0) {
393 // We've managed to infer better alignment information than the load
394 // already has. Use an aligned load.
395 return DAG.getLoad(getPointerTy(), dl, Chain, BasePtr, NULL, 4);
398 // ldw low, base[offset >> 2]
399 // ldw high, base[(offset >> 2) + 1]
400 // shr low_shifted, low, (offset & 0x3) * 8
401 // shl high_shifted, high, 32 - (offset & 0x3) * 8
402 // or result, low_shifted, high_shifted
403 SDValue LowOffset = DAG.getConstant(Offset & ~0x3, MVT::i32);
404 SDValue HighOffset = DAG.getConstant((Offset & ~0x3) + 4, MVT::i32);
405 SDValue LowShift = DAG.getConstant((Offset & 0x3) * 8, MVT::i32);
406 SDValue HighShift = DAG.getConstant(32 - (Offset & 0x3) * 8, MVT::i32);
408 SDValue LowAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Base, LowOffset);
409 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Base, HighOffset);
411 SDValue Low = DAG.getLoad(getPointerTy(), dl, Chain,
413 SDValue High = DAG.getLoad(getPointerTy(), dl, Chain,
415 SDValue LowShifted = DAG.getNode(ISD::SRL, dl, MVT::i32, Low, LowShift);
416 SDValue HighShifted = DAG.getNode(ISD::SHL, dl, MVT::i32, High, HighShift);
417 SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, LowShifted, HighShifted);
418 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Low.getValue(1),
420 SDValue Ops[] = { Result, Chain };
421 return DAG.getMergeValues(Ops, 2, dl);
424 if (LD->getAlignment() == 2) {
425 int SVOffset = LD->getSrcValueOffset();
426 SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
427 BasePtr, LD->getSrcValue(), SVOffset, MVT::i16,
428 LD->isVolatile(), 2);
429 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
430 DAG.getConstant(2, MVT::i32));
431 SDValue High = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::i32, Chain,
432 HighAddr, LD->getSrcValue(), SVOffset + 2,
433 MVT::i16, LD->isVolatile(), 2);
434 SDValue HighShifted = DAG.getNode(ISD::SHL, dl, MVT::i32, High,
435 DAG.getConstant(16, MVT::i32));
436 SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, Low, HighShifted);
437 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Low.getValue(1),
439 SDValue Ops[] = { Result, Chain };
440 return DAG.getMergeValues(Ops, 2, dl);
443 // Lower to a call to __misaligned_load(BasePtr).
444 const Type *IntPtrTy = getTargetData()->getIntPtrType();
445 TargetLowering::ArgListTy Args;
446 TargetLowering::ArgListEntry Entry;
449 Entry.Node = BasePtr;
450 Args.push_back(Entry);
452 std::pair<SDValue, SDValue> CallResult =
453 LowerCallTo(Chain, IntPtrTy, false, false,
454 false, false, 0, CallingConv::C, false,
455 DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
459 { CallResult.first, CallResult.second };
461 return DAG.getMergeValues(Ops, 2, dl);
464 SDValue XCoreTargetLowering::
465 LowerSTORE(SDValue Op, SelectionDAG &DAG)
467 StoreSDNode *ST = cast<StoreSDNode>(Op);
468 assert(!ST->isTruncatingStore() && "Unexpected store type");
469 assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store MVT");
470 if (allowsUnalignedMemoryAccesses()) {
473 unsigned ABIAlignment = getTargetData()->
474 getABITypeAlignment(ST->getMemoryVT().getTypeForMVT(*DAG.getContext()));
475 // Leave aligned store alone.
476 if (ST->getAlignment() >= ABIAlignment) {
479 SDValue Chain = ST->getChain();
480 SDValue BasePtr = ST->getBasePtr();
481 SDValue Value = ST->getValue();
482 DebugLoc dl = Op.getDebugLoc();
484 if (ST->getAlignment() == 2) {
485 int SVOffset = ST->getSrcValueOffset();
487 SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
488 DAG.getConstant(16, MVT::i32));
489 SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
490 ST->getSrcValue(), SVOffset, MVT::i16,
491 ST->isVolatile(), 2);
492 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
493 DAG.getConstant(2, MVT::i32));
494 SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
495 ST->getSrcValue(), SVOffset + 2,
496 MVT::i16, ST->isVolatile(), 2);
497 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
500 // Lower to a call to __misaligned_store(BasePtr, Value).
501 const Type *IntPtrTy = getTargetData()->getIntPtrType();
502 TargetLowering::ArgListTy Args;
503 TargetLowering::ArgListEntry Entry;
506 Entry.Node = BasePtr;
507 Args.push_back(Entry);
510 Args.push_back(Entry);
512 std::pair<SDValue, SDValue> CallResult =
513 LowerCallTo(Chain, Type::VoidTy, false, false,
514 false, false, 0, CallingConv::C, false,
515 DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
518 return CallResult.second;
521 SDValue XCoreTargetLowering::
522 ExpandADDSUB(SDNode *N, SelectionDAG &DAG)
524 assert(N->getValueType(0) == MVT::i64 &&
525 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
526 "Unknown operand to lower!");
527 assert(!Subtarget.isXS1A() && "Cannot custom lower ADD/SUB on xs1a");
528 DebugLoc dl = N->getDebugLoc();
530 // Extract components
531 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
532 N->getOperand(0), DAG.getConstant(0, MVT::i32));
533 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
534 N->getOperand(0), DAG.getConstant(1, MVT::i32));
535 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
536 N->getOperand(1), DAG.getConstant(0, MVT::i32));
537 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
538 N->getOperand(1), DAG.getConstant(1, MVT::i32));
541 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
543 SDValue Zero = DAG.getConstant(0, MVT::i32);
544 SDValue Carry = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
546 SDValue Lo(Carry.getNode(), 1);
548 SDValue Ignored = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
550 SDValue Hi(Ignored.getNode(), 1);
552 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
555 SDValue XCoreTargetLowering::
556 LowerVAARG(SDValue Op, SelectionDAG &DAG)
558 llvm_unreachable("unimplemented");
559 // FIX Arguments passed by reference need a extra dereference.
560 SDNode *Node = Op.getNode();
561 DebugLoc dl = Node->getDebugLoc();
562 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
563 MVT VT = Node->getValueType(0);
564 SDValue VAList = DAG.getLoad(getPointerTy(), dl, Node->getOperand(0),
565 Node->getOperand(1), V, 0);
566 // Increment the pointer, VAList, to the next vararg
567 SDValue Tmp3 = DAG.getNode(ISD::ADD, dl, getPointerTy(), VAList,
568 DAG.getConstant(VT.getSizeInBits(),
570 // Store the incremented VAList to the legalized pointer
571 Tmp3 = DAG.getStore(VAList.getValue(1), dl, Tmp3, Node->getOperand(1), V, 0);
572 // Load the actual argument out of the pointer VAList
573 return DAG.getLoad(VT, dl, Tmp3, VAList, NULL, 0);
576 SDValue XCoreTargetLowering::
577 LowerVASTART(SDValue Op, SelectionDAG &DAG)
579 DebugLoc dl = Op.getDebugLoc();
580 // vastart stores the address of the VarArgsFrameIndex slot into the
581 // memory location argument
582 MachineFunction &MF = DAG.getMachineFunction();
583 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
584 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
585 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
586 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1), SV, 0);
589 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
590 DebugLoc dl = Op.getDebugLoc();
591 // Depths > 0 not supported yet!
592 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
595 MachineFunction &MF = DAG.getMachineFunction();
596 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
597 return DAG.getCopyFromReg(DAG.getEntryNode(), dl,
598 RegInfo->getFrameRegister(MF), MVT::i32);
601 //===----------------------------------------------------------------------===//
602 // Calling Convention Implementation
604 // The lower operations present on calling convention works on this order:
605 // LowerCALL (virt regs --> phys regs, virt regs --> stack)
606 // LowerFORMAL_ARGUMENTS (phys --> virt regs, stack --> virt regs)
607 // LowerRET (virt regs --> phys regs)
608 // LowerCALL (phys regs --> virt regs)
610 //===----------------------------------------------------------------------===//
612 #include "XCoreGenCallingConv.inc"
614 //===----------------------------------------------------------------------===//
615 // CALL Calling Convention Implementation
616 //===----------------------------------------------------------------------===//
618 /// XCore custom CALL implementation
619 SDValue XCoreTargetLowering::
620 LowerCALL(SDValue Op, SelectionDAG &DAG)
622 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
623 unsigned CallingConv = TheCall->getCallingConv();
624 // For now, only CallingConv::C implemented
628 llvm_unreachable("Unsupported calling convention");
629 case CallingConv::Fast:
631 return LowerCCCCallTo(Op, DAG, CallingConv);
635 /// LowerCCCCallTo - functions arguments are copied from virtual
636 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
637 /// CALLSEQ_END are emitted.
638 /// TODO: isTailCall, sret.
639 SDValue XCoreTargetLowering::
640 LowerCCCCallTo(SDValue Op, SelectionDAG &DAG, unsigned CC)
642 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
643 SDValue Chain = TheCall->getChain();
644 SDValue Callee = TheCall->getCallee();
645 bool isVarArg = TheCall->isVarArg();
646 DebugLoc dl = Op.getDebugLoc();
648 // Analyze operands of the call, assigning locations to each operand.
649 SmallVector<CCValAssign, 16> ArgLocs;
650 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs, DAG.getContext());
652 // The ABI dictates there should be one stack slot available to the callee
653 // on function entry (for saving lr).
654 CCInfo.AllocateStack(4, 4);
656 CCInfo.AnalyzeCallOperands(TheCall, CC_XCore);
658 // Get a count of how many bytes are to be pushed on the stack.
659 unsigned NumBytes = CCInfo.getNextStackOffset();
661 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
662 getPointerTy(), true));
664 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
665 SmallVector<SDValue, 12> MemOpChains;
667 // Walk the register/memloc assignments, inserting copies/loads.
668 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
669 CCValAssign &VA = ArgLocs[i];
671 // Arguments start after the 5 first operands of ISD::CALL
672 SDValue Arg = TheCall->getArg(i);
674 // Promote the value if needed.
675 switch (VA.getLocInfo()) {
676 default: llvm_unreachable("Unknown loc info!");
677 case CCValAssign::Full: break;
678 case CCValAssign::SExt:
679 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
681 case CCValAssign::ZExt:
682 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
684 case CCValAssign::AExt:
685 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
689 // Arguments that can be passed on register must be kept at
692 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
694 assert(VA.isMemLoc());
696 int Offset = VA.getLocMemOffset();
698 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
700 DAG.getConstant(Offset/4, MVT::i32)));
704 // Transform all store nodes into one single node because
705 // all store nodes are independent of each other.
706 if (!MemOpChains.empty())
707 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
708 &MemOpChains[0], MemOpChains.size());
710 // Build a sequence of copy-to-reg nodes chained together with token
711 // chain and flag operands which copy the outgoing args into registers.
712 // The InFlag in necessary since all emited instructions must be
715 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
716 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
717 RegsToPass[i].second, InFlag);
718 InFlag = Chain.getValue(1);
721 // If the callee is a GlobalAddress node (quite common, every direct call is)
722 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
723 // Likewise ExternalSymbol -> TargetExternalSymbol.
724 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
725 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32);
726 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
727 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
729 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
730 // = Chain, Callee, Reg#1, Reg#2, ...
732 // Returns a chain & a flag for retval copy to use.
733 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
734 SmallVector<SDValue, 8> Ops;
735 Ops.push_back(Chain);
736 Ops.push_back(Callee);
738 // Add argument registers to the end of the list so that they are
739 // known live into the call.
740 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
741 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
742 RegsToPass[i].second.getValueType()));
744 if (InFlag.getNode())
745 Ops.push_back(InFlag);
747 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, &Ops[0], Ops.size());
748 InFlag = Chain.getValue(1);
750 // Create the CALLSEQ_END node.
751 Chain = DAG.getCALLSEQ_END(Chain,
752 DAG.getConstant(NumBytes, getPointerTy(), true),
753 DAG.getConstant(0, getPointerTy(), true),
755 InFlag = Chain.getValue(1);
757 // Handle result values, copying them out of physregs into vregs that we
759 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
763 /// LowerCallResult - Lower the result values of an ISD::CALL into the
764 /// appropriate copies out of appropriate physical registers. This assumes that
765 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
766 /// being lowered. Returns a SDNode with the same number of values as the
768 SDNode *XCoreTargetLowering::
769 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
770 unsigned CallingConv, SelectionDAG &DAG) {
771 bool isVarArg = TheCall->isVarArg();
772 DebugLoc dl = TheCall->getDebugLoc();
774 // Assign locations to each value returned by this call.
775 SmallVector<CCValAssign, 16> RVLocs;
776 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(),
777 RVLocs, DAG.getContext());
779 CCInfo.AnalyzeCallResult(TheCall, RetCC_XCore);
780 SmallVector<SDValue, 8> ResultVals;
782 // Copy all of the result registers out of their specified physreg.
783 for (unsigned i = 0; i != RVLocs.size(); ++i) {
784 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
785 RVLocs[i].getValVT(), InFlag).getValue(1);
786 InFlag = Chain.getValue(2);
787 ResultVals.push_back(Chain.getValue(0));
790 ResultVals.push_back(Chain);
792 // Merge everything together with a MERGE_VALUES node.
793 return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
794 &ResultVals[0], ResultVals.size()).getNode();
797 //===----------------------------------------------------------------------===//
798 // FORMAL_ARGUMENTS Calling Convention Implementation
799 //===----------------------------------------------------------------------===//
801 /// XCore custom FORMAL_ARGUMENTS implementation
802 SDValue XCoreTargetLowering::
803 LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG)
805 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
809 llvm_unreachable("Unsupported calling convention");
811 case CallingConv::Fast:
812 return LowerCCCArguments(Op, DAG);
816 /// LowerCCCArguments - transform physical registers into
817 /// virtual registers and generate load operations for
818 /// arguments places on the stack.
820 SDValue XCoreTargetLowering::
821 LowerCCCArguments(SDValue Op, SelectionDAG &DAG)
823 MachineFunction &MF = DAG.getMachineFunction();
824 MachineFrameInfo *MFI = MF.getFrameInfo();
825 MachineRegisterInfo &RegInfo = MF.getRegInfo();
826 SDValue Root = Op.getOperand(0);
827 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
828 unsigned CC = MF.getFunction()->getCallingConv();
829 DebugLoc dl = Op.getDebugLoc();
831 // Assign locations to all of the incoming arguments.
832 SmallVector<CCValAssign, 16> ArgLocs;
833 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs, DAG.getContext());
835 CCInfo.AnalyzeFormalArguments(Op.getNode(), CC_XCore);
837 unsigned StackSlotSize = XCoreFrameInfo::stackSlotSize();
839 SmallVector<SDValue, 16> ArgValues;
841 unsigned LRSaveSize = StackSlotSize;
843 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
845 CCValAssign &VA = ArgLocs[i];
848 // Arguments passed in registers
849 MVT RegVT = VA.getLocVT();
850 switch (RegVT.getSimpleVT()) {
854 cerr << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
855 << RegVT.getSimpleVT() << "\n";
860 unsigned VReg = RegInfo.createVirtualRegister(
861 XCore::GRRegsRegisterClass);
862 RegInfo.addLiveIn(VA.getLocReg(), VReg);
863 ArgValues.push_back(DAG.getCopyFromReg(Root, dl, VReg, RegVT));
867 assert(VA.isMemLoc());
868 // Load the argument to a virtual register
869 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
870 if (ObjSize > StackSlotSize) {
871 cerr << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
872 << VA.getLocVT().getSimpleVT()
875 // Create the frame index object for this incoming parameter...
876 int FI = MFI->CreateFixedObject(ObjSize,
877 LRSaveSize + VA.getLocMemOffset());
879 // Create the SelectionDAG nodes corresponding to a load
880 //from this parameter
881 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
882 ArgValues.push_back(DAG.getLoad(VA.getLocVT(), dl, Root, FIN, NULL, 0));
887 /* Argument registers */
888 static const unsigned ArgRegs[] = {
889 XCore::R0, XCore::R1, XCore::R2, XCore::R3
891 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
892 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
893 array_lengthof(ArgRegs));
894 if (FirstVAReg < array_lengthof(ArgRegs)) {
895 SmallVector<SDValue, 4> MemOps;
897 // Save remaining registers, storing higher register numbers at a higher
899 for (unsigned i = array_lengthof(ArgRegs) - 1; i >= FirstVAReg; --i) {
900 // Create a stack slot
901 int FI = MFI->CreateFixedObject(4, offset);
902 if (i == FirstVAReg) {
903 XFI->setVarArgsFrameIndex(FI);
905 offset -= StackSlotSize;
906 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
907 // Move argument from phys reg -> virt reg
908 unsigned VReg = RegInfo.createVirtualRegister(
909 XCore::GRRegsRegisterClass);
910 RegInfo.addLiveIn(ArgRegs[i], VReg);
911 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::i32);
912 // Move argument from virt reg -> stack
913 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
914 MemOps.push_back(Store);
917 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
918 &MemOps[0], MemOps.size());
920 // This will point to the next argument passed via stack.
921 XFI->setVarArgsFrameIndex(
922 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset()));
926 ArgValues.push_back(Root);
928 // Return the new list of results.
929 std::vector<MVT> RetVT(Op.getNode()->value_begin(),
930 Op.getNode()->value_end());
931 return DAG.getNode(ISD::MERGE_VALUES, dl, RetVT,
932 &ArgValues[0], ArgValues.size());
935 //===----------------------------------------------------------------------===//
936 // Return Value Calling Convention Implementation
937 //===----------------------------------------------------------------------===//
939 SDValue XCoreTargetLowering::
940 LowerRET(SDValue Op, SelectionDAG &DAG)
942 // CCValAssign - represent the assignment of
943 // the return value to a location
944 SmallVector<CCValAssign, 16> RVLocs;
945 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
946 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
947 DebugLoc dl = Op.getDebugLoc();
949 // CCState - Info about the registers and stack slot.
950 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs, DAG.getContext());
952 // Analize return values of ISD::RET
953 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_XCore);
955 // If this is the first return lowered for this function, add
956 // the regs to the liveout set for the function.
957 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
958 for (unsigned i = 0; i != RVLocs.size(); ++i)
959 if (RVLocs[i].isRegLoc())
960 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
963 // The chain is always operand #0
964 SDValue Chain = Op.getOperand(0);
967 // Copy the result values into the output registers.
968 for (unsigned i = 0; i != RVLocs.size(); ++i) {
969 CCValAssign &VA = RVLocs[i];
970 assert(VA.isRegLoc() && "Can only return in registers!");
972 // ISD::RET => ret chain, (regnum1,val1), ...
973 // So i*2+1 index only the regnums
974 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
975 Op.getOperand(i*2+1), Flag);
977 // guarantee that all emitted copies are
978 // stuck together, avoiding something bad
979 Flag = Chain.getValue(1);
982 // Return on XCore is always a "retsp 0"
984 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
985 Chain, DAG.getConstant(0, MVT::i32), Flag);
987 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
988 Chain, DAG.getConstant(0, MVT::i32));
991 //===----------------------------------------------------------------------===//
992 // Other Lowering Code
993 //===----------------------------------------------------------------------===//
996 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
997 MachineBasicBlock *BB) const {
998 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
999 DebugLoc dl = MI->getDebugLoc();
1000 assert((MI->getOpcode() == XCore::SELECT_CC) &&
1001 "Unexpected instr type to insert");
1003 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1004 // control-flow pattern. The incoming instruction knows the destination vreg
1005 // to set, the condition code register to branch on, the true/false values to
1006 // select between, and a branch opcode to use.
1007 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1008 MachineFunction::iterator It = BB;
1014 // cmpTY ccX, r1, r2
1016 // fallthrough --> copy0MBB
1017 MachineBasicBlock *thisMBB = BB;
1018 MachineFunction *F = BB->getParent();
1019 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1020 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1021 BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1022 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1023 F->insert(It, copy0MBB);
1024 F->insert(It, sinkMBB);
1025 // Update machine-CFG edges by transferring all successors of the current
1026 // block to the new block which will contain the Phi node for the select.
1027 sinkMBB->transferSuccessors(BB);
1028 // Next, add the true and fallthrough blocks as its successors.
1029 BB->addSuccessor(copy0MBB);
1030 BB->addSuccessor(sinkMBB);
1033 // %FalseValue = ...
1034 // # fallthrough to sinkMBB
1037 // Update machine-CFG edges
1038 BB->addSuccessor(sinkMBB);
1041 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1044 BuildMI(BB, dl, TII.get(XCore::PHI), MI->getOperand(0).getReg())
1045 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1046 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1048 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
1052 //===----------------------------------------------------------------------===//
1053 // Addressing mode description hooks
1054 //===----------------------------------------------------------------------===//
1056 static inline bool isImmUs(int64_t val)
1058 return (val >= 0 && val <= 11);
1061 static inline bool isImmUs2(int64_t val)
1063 return (val%2 == 0 && isImmUs(val/2));
1066 static inline bool isImmUs4(int64_t val)
1068 return (val%4 == 0 && isImmUs(val/4));
1071 /// isLegalAddressingMode - Return true if the addressing mode represented
1072 /// by AM is legal for this target, for a load/store of the specified type.
1074 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1075 const Type *Ty) const {
1076 const TargetData *TD = TM.getTargetData();
1077 unsigned Size = TD->getTypeAllocSize(Ty);
1079 return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1086 if (AM.Scale == 0) {
1087 return isImmUs(AM.BaseOffs);
1090 return AM.Scale == 1 && AM.BaseOffs == 0;
1094 if (AM.Scale == 0) {
1095 return isImmUs2(AM.BaseOffs);
1098 return AM.Scale == 2 && AM.BaseOffs == 0;
1101 if (AM.Scale == 0) {
1102 return isImmUs4(AM.BaseOffs);
1105 return AM.Scale == 4 && AM.BaseOffs == 0;
1111 //===----------------------------------------------------------------------===//
1112 // XCore Inline Assembly Support
1113 //===----------------------------------------------------------------------===//
1115 std::vector<unsigned> XCoreTargetLowering::
1116 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1119 if (Constraint.size() != 1)
1120 return std::vector<unsigned>();
1122 switch (Constraint[0]) {
1125 return make_vector<unsigned>(XCore::R0, XCore::R1, XCore::R2,
1126 XCore::R3, XCore::R4, XCore::R5,
1127 XCore::R6, XCore::R7, XCore::R8,
1128 XCore::R9, XCore::R10, XCore::R11, 0);
1131 return std::vector<unsigned>();