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);
155 SDValue XCoreTargetLowering::
156 LowerOperation(SDValue Op, SelectionDAG &DAG) {
157 switch (Op.getOpcode())
159 case ISD::CALL: return LowerCALL(Op, DAG);
160 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
161 case ISD::RET: return LowerRET(Op, DAG);
162 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
163 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
164 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
165 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
166 case ISD::LOAD: return LowerLOAD(Op, DAG);
167 case ISD::STORE: return LowerSTORE(Op, DAG);
168 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
169 case ISD::VAARG: return LowerVAARG(Op, DAG);
170 case ISD::VASTART: return LowerVASTART(Op, DAG);
171 // FIXME: Remove these when LegalizeDAGTypes lands.
173 case ISD::SUB: return ExpandADDSUB(Op.getNode(), DAG);
174 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
176 llvm_unreachable("unimplemented operand");
181 /// ReplaceNodeResults - Replace the results of node with an illegal result
182 /// type with new values built out of custom code.
183 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
184 SmallVectorImpl<SDValue>&Results,
186 switch (N->getOpcode()) {
188 llvm_unreachable("Don't know how to custom expand this!");
192 Results.push_back(ExpandADDSUB(N, DAG));
197 /// getFunctionAlignment - Return the Log2 alignment of this function.
198 unsigned XCoreTargetLowering::
199 getFunctionAlignment(const Function *) const {
203 //===----------------------------------------------------------------------===//
204 // Misc Lower Operation implementation
205 //===----------------------------------------------------------------------===//
207 SDValue XCoreTargetLowering::
208 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG)
210 DebugLoc dl = Op.getDebugLoc();
211 SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i32, Op.getOperand(2),
212 Op.getOperand(3), Op.getOperand(4));
213 return DAG.getNode(ISD::SELECT, dl, MVT::i32, Cond, Op.getOperand(0),
217 SDValue XCoreTargetLowering::
218 getGlobalAddressWrapper(SDValue GA, GlobalValue *GV, SelectionDAG &DAG)
220 // FIXME there is no actual debug info here
221 DebugLoc dl = GA.getDebugLoc();
222 if (isa<Function>(GV)) {
223 return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
224 } else if (!Subtarget.isXS1A()) {
225 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
227 // If GV is an alias then use the aliasee to determine constness
228 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
229 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
231 bool isConst = GVar && GVar->isConstant();
233 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
236 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
239 SDValue XCoreTargetLowering::
240 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG)
242 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
243 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
244 // If it's a debug information descriptor, don't mess with it.
245 if (DAG.isVerifiedDebugInfoDesc(Op))
247 return getGlobalAddressWrapper(GA, GV, DAG);
250 static inline SDValue BuildGetId(SelectionDAG &DAG, DebugLoc dl) {
251 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
252 DAG.getConstant(Intrinsic::xcore_getid, MVT::i32));
255 static inline bool isZeroLengthArray(const Type *Ty) {
256 const ArrayType *AT = dyn_cast_or_null<ArrayType>(Ty);
257 return AT && (AT->getNumElements() == 0);
260 SDValue XCoreTargetLowering::
261 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG)
263 // FIXME there isn't really debug info here
264 DebugLoc dl = Op.getDebugLoc();
265 // transform to label + getid() * size
266 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
267 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
268 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
270 // If GV is an alias then use the aliasee to determine size
271 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
272 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
275 llvm_unreachable("Thread local object not a GlobalVariable?");
278 const Type *Ty = cast<PointerType>(GV->getType())->getElementType();
279 if (!Ty->isSized() || isZeroLengthArray(Ty)) {
281 cerr << "Size of thread local object " << GVar->getName()
286 SDValue base = getGlobalAddressWrapper(GA, GV, DAG);
287 const TargetData *TD = TM.getTargetData();
288 unsigned Size = TD->getTypeAllocSize(Ty);
289 SDValue offset = DAG.getNode(ISD::MUL, dl, MVT::i32, BuildGetId(DAG, dl),
290 DAG.getConstant(Size, MVT::i32));
291 return DAG.getNode(ISD::ADD, dl, MVT::i32, base, offset);
294 SDValue XCoreTargetLowering::
295 LowerConstantPool(SDValue Op, SelectionDAG &DAG)
297 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
298 // FIXME there isn't really debug info here
299 DebugLoc dl = CP->getDebugLoc();
300 if (Subtarget.isXS1A()) {
301 llvm_unreachable("Lowering of constant pool unimplemented");
304 MVT PtrVT = Op.getValueType();
306 if (CP->isMachineConstantPoolEntry()) {
307 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
310 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
313 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
317 SDValue XCoreTargetLowering::
318 LowerJumpTable(SDValue Op, SelectionDAG &DAG)
320 // FIXME there isn't really debug info here
321 DebugLoc dl = Op.getDebugLoc();
322 MVT PtrVT = Op.getValueType();
323 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
324 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
325 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, JTI);
329 IsWordAlignedBasePlusConstantOffset(SDValue Addr, SDValue &AlignedBase,
332 if (Addr.getOpcode() != ISD::ADD) {
335 ConstantSDNode *CN = 0;
336 if (!(CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
339 int64_t off = CN->getSExtValue();
340 const SDValue &Base = Addr.getOperand(0);
341 const SDValue *Root = &Base;
342 if (Base.getOpcode() == ISD::ADD &&
343 Base.getOperand(1).getOpcode() == ISD::SHL) {
344 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Base.getOperand(1)
346 if (CN && (CN->getSExtValue() >= 2)) {
347 Root = &Base.getOperand(0);
350 if (isa<FrameIndexSDNode>(*Root)) {
351 // All frame indicies are word aligned
356 if (Root->getOpcode() == XCoreISD::DPRelativeWrapper ||
357 Root->getOpcode() == XCoreISD::CPRelativeWrapper) {
358 // All dp / cp relative addresses are word aligned
366 SDValue XCoreTargetLowering::
367 LowerLOAD(SDValue Op, SelectionDAG &DAG)
369 LoadSDNode *LD = cast<LoadSDNode>(Op);
370 assert(LD->getExtensionType() == ISD::NON_EXTLOAD && "Unexpected extension type");
371 assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load MVT");
372 if (allowsUnalignedMemoryAccesses()) {
375 unsigned ABIAlignment = getTargetData()->
376 getABITypeAlignment(LD->getMemoryVT().getTypeForMVT(*DAG.getContext()));
377 // Leave aligned load alone.
378 if (LD->getAlignment() >= ABIAlignment) {
381 SDValue Chain = LD->getChain();
382 SDValue BasePtr = LD->getBasePtr();
383 DebugLoc dl = Op.getDebugLoc();
387 if (!LD->isVolatile() &&
388 IsWordAlignedBasePlusConstantOffset(BasePtr, Base, Offset)) {
389 if (Offset % 4 == 0) {
390 // We've managed to infer better alignment information than the load
391 // already has. Use an aligned load.
392 return DAG.getLoad(getPointerTy(), dl, Chain, BasePtr, NULL, 4);
395 // ldw low, base[offset >> 2]
396 // ldw high, base[(offset >> 2) + 1]
397 // shr low_shifted, low, (offset & 0x3) * 8
398 // shl high_shifted, high, 32 - (offset & 0x3) * 8
399 // or result, low_shifted, high_shifted
400 SDValue LowOffset = DAG.getConstant(Offset & ~0x3, MVT::i32);
401 SDValue HighOffset = DAG.getConstant((Offset & ~0x3) + 4, MVT::i32);
402 SDValue LowShift = DAG.getConstant((Offset & 0x3) * 8, MVT::i32);
403 SDValue HighShift = DAG.getConstant(32 - (Offset & 0x3) * 8, MVT::i32);
405 SDValue LowAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Base, LowOffset);
406 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Base, HighOffset);
408 SDValue Low = DAG.getLoad(getPointerTy(), dl, Chain,
410 SDValue High = DAG.getLoad(getPointerTy(), dl, Chain,
412 SDValue LowShifted = DAG.getNode(ISD::SRL, dl, MVT::i32, Low, LowShift);
413 SDValue HighShifted = DAG.getNode(ISD::SHL, dl, MVT::i32, High, HighShift);
414 SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, LowShifted, HighShifted);
415 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Low.getValue(1),
417 SDValue Ops[] = { Result, Chain };
418 return DAG.getMergeValues(Ops, 2, dl);
421 if (LD->getAlignment() == 2) {
422 int SVOffset = LD->getSrcValueOffset();
423 SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
424 BasePtr, LD->getSrcValue(), SVOffset, MVT::i16,
425 LD->isVolatile(), 2);
426 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
427 DAG.getConstant(1, MVT::i32));
428 SDValue High = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::i32, Chain,
429 HighAddr, LD->getSrcValue(), SVOffset + 2,
430 MVT::i16, LD->isVolatile(), 2);
431 SDValue HighShifted = DAG.getNode(ISD::SHL, dl, MVT::i32, High,
432 DAG.getConstant(16, MVT::i32));
433 SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, Low, HighShifted);
434 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Low.getValue(1),
436 SDValue Ops[] = { Result, Chain };
437 return DAG.getMergeValues(Ops, 2, dl);
440 // Lower to a call to __misaligned_load(BasePtr).
441 const Type *IntPtrTy = getTargetData()->getIntPtrType();
442 TargetLowering::ArgListTy Args;
443 TargetLowering::ArgListEntry Entry;
446 Entry.Node = BasePtr;
447 Args.push_back(Entry);
449 std::pair<SDValue, SDValue> CallResult =
450 LowerCallTo(Chain, IntPtrTy, false, false,
451 false, false, 0, CallingConv::C, false,
452 DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
456 { CallResult.first, CallResult.second };
458 return DAG.getMergeValues(Ops, 2, dl);
461 SDValue XCoreTargetLowering::
462 LowerSTORE(SDValue Op, SelectionDAG &DAG)
464 StoreSDNode *ST = cast<StoreSDNode>(Op);
465 assert(!ST->isTruncatingStore() && "Unexpected store type");
466 assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store MVT");
467 if (allowsUnalignedMemoryAccesses()) {
470 unsigned ABIAlignment = getTargetData()->
471 getABITypeAlignment(ST->getMemoryVT().getTypeForMVT(*DAG.getContext()));
472 // Leave aligned store alone.
473 if (ST->getAlignment() >= ABIAlignment) {
476 SDValue Chain = ST->getChain();
477 SDValue BasePtr = ST->getBasePtr();
478 SDValue Value = ST->getValue();
479 DebugLoc dl = Op.getDebugLoc();
481 if (ST->getAlignment() == 2) {
482 int SVOffset = ST->getSrcValueOffset();
484 SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
485 DAG.getConstant(16, MVT::i32));
486 SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
487 ST->getSrcValue(), SVOffset, MVT::i16,
488 ST->isVolatile(), 2);
489 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
490 DAG.getConstant(1, MVT::i32));
491 SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
492 ST->getSrcValue(), SVOffset + 2,
493 MVT::i16, ST->isVolatile(), 2);
494 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
497 // Lower to a call to __misaligned_store(BasePtr, Value).
498 const Type *IntPtrTy = getTargetData()->getIntPtrType();
499 TargetLowering::ArgListTy Args;
500 TargetLowering::ArgListEntry Entry;
503 Entry.Node = BasePtr;
504 Args.push_back(Entry);
507 Args.push_back(Entry);
509 std::pair<SDValue, SDValue> CallResult =
510 LowerCallTo(Chain, Type::VoidTy, false, false,
511 false, false, 0, CallingConv::C, false,
512 DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
515 return CallResult.second;
518 SDValue XCoreTargetLowering::
519 ExpandADDSUB(SDNode *N, SelectionDAG &DAG)
521 assert(N->getValueType(0) == MVT::i64 &&
522 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
523 "Unknown operand to lower!");
524 assert(!Subtarget.isXS1A() && "Cannot custom lower ADD/SUB on xs1a");
525 DebugLoc dl = N->getDebugLoc();
527 // Extract components
528 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
529 N->getOperand(0), DAG.getConstant(0, MVT::i32));
530 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
531 N->getOperand(0), DAG.getConstant(1, MVT::i32));
532 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
533 N->getOperand(1), DAG.getConstant(0, MVT::i32));
534 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
535 N->getOperand(1), DAG.getConstant(1, MVT::i32));
538 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
540 SDValue Zero = DAG.getConstant(0, MVT::i32);
541 SDValue Carry = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
543 SDValue Lo(Carry.getNode(), 1);
545 SDValue Ignored = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
547 SDValue Hi(Ignored.getNode(), 1);
549 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
552 SDValue XCoreTargetLowering::
553 LowerVAARG(SDValue Op, SelectionDAG &DAG)
555 llvm_unreachable("unimplemented");
556 // FIX Arguments passed by reference need a extra dereference.
557 SDNode *Node = Op.getNode();
558 DebugLoc dl = Node->getDebugLoc();
559 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
560 MVT VT = Node->getValueType(0);
561 SDValue VAList = DAG.getLoad(getPointerTy(), dl, Node->getOperand(0),
562 Node->getOperand(1), V, 0);
563 // Increment the pointer, VAList, to the next vararg
564 SDValue Tmp3 = DAG.getNode(ISD::ADD, dl, getPointerTy(), VAList,
565 DAG.getConstant(VT.getSizeInBits(),
567 // Store the incremented VAList to the legalized pointer
568 Tmp3 = DAG.getStore(VAList.getValue(1), dl, Tmp3, Node->getOperand(1), V, 0);
569 // Load the actual argument out of the pointer VAList
570 return DAG.getLoad(VT, dl, Tmp3, VAList, NULL, 0);
573 SDValue XCoreTargetLowering::
574 LowerVASTART(SDValue Op, SelectionDAG &DAG)
576 DebugLoc dl = Op.getDebugLoc();
577 // vastart stores the address of the VarArgsFrameIndex slot into the
578 // memory location argument
579 MachineFunction &MF = DAG.getMachineFunction();
580 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
581 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
582 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
583 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1), SV, 0);
586 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
587 DebugLoc dl = Op.getDebugLoc();
588 // Depths > 0 not supported yet!
589 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
592 MachineFunction &MF = DAG.getMachineFunction();
593 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
594 return DAG.getCopyFromReg(DAG.getEntryNode(), dl,
595 RegInfo->getFrameRegister(MF), MVT::i32);
598 //===----------------------------------------------------------------------===//
599 // Calling Convention Implementation
601 // The lower operations present on calling convention works on this order:
602 // LowerCALL (virt regs --> phys regs, virt regs --> stack)
603 // LowerFORMAL_ARGUMENTS (phys --> virt regs, stack --> virt regs)
604 // LowerRET (virt regs --> phys regs)
605 // LowerCALL (phys regs --> virt regs)
607 //===----------------------------------------------------------------------===//
609 #include "XCoreGenCallingConv.inc"
611 //===----------------------------------------------------------------------===//
612 // CALL Calling Convention Implementation
613 //===----------------------------------------------------------------------===//
615 /// XCore custom CALL implementation
616 SDValue XCoreTargetLowering::
617 LowerCALL(SDValue Op, SelectionDAG &DAG)
619 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
620 unsigned CallingConv = TheCall->getCallingConv();
621 // For now, only CallingConv::C implemented
625 llvm_unreachable("Unsupported calling convention");
626 case CallingConv::Fast:
628 return LowerCCCCallTo(Op, DAG, CallingConv);
632 /// LowerCCCCallTo - functions arguments are copied from virtual
633 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
634 /// CALLSEQ_END are emitted.
635 /// TODO: isTailCall, sret.
636 SDValue XCoreTargetLowering::
637 LowerCCCCallTo(SDValue Op, SelectionDAG &DAG, unsigned CC)
639 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
640 SDValue Chain = TheCall->getChain();
641 SDValue Callee = TheCall->getCallee();
642 bool isVarArg = TheCall->isVarArg();
643 DebugLoc dl = Op.getDebugLoc();
645 // Analyze operands of the call, assigning locations to each operand.
646 SmallVector<CCValAssign, 16> ArgLocs;
647 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs, DAG.getContext());
649 // The ABI dictates there should be one stack slot available to the callee
650 // on function entry (for saving lr).
651 CCInfo.AllocateStack(4, 4);
653 CCInfo.AnalyzeCallOperands(TheCall, CC_XCore);
655 // Get a count of how many bytes are to be pushed on the stack.
656 unsigned NumBytes = CCInfo.getNextStackOffset();
658 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
659 getPointerTy(), true));
661 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
662 SmallVector<SDValue, 12> MemOpChains;
664 // Walk the register/memloc assignments, inserting copies/loads.
665 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
666 CCValAssign &VA = ArgLocs[i];
668 // Arguments start after the 5 first operands of ISD::CALL
669 SDValue Arg = TheCall->getArg(i);
671 // Promote the value if needed.
672 switch (VA.getLocInfo()) {
673 default: llvm_unreachable("Unknown loc info!");
674 case CCValAssign::Full: break;
675 case CCValAssign::SExt:
676 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
678 case CCValAssign::ZExt:
679 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
681 case CCValAssign::AExt:
682 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
686 // Arguments that can be passed on register must be kept at
689 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
691 assert(VA.isMemLoc());
693 int Offset = VA.getLocMemOffset();
695 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
697 DAG.getConstant(Offset/4, MVT::i32)));
701 // Transform all store nodes into one single node because
702 // all store nodes are independent of each other.
703 if (!MemOpChains.empty())
704 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
705 &MemOpChains[0], MemOpChains.size());
707 // Build a sequence of copy-to-reg nodes chained together with token
708 // chain and flag operands which copy the outgoing args into registers.
709 // The InFlag in necessary since all emited instructions must be
712 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
713 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
714 RegsToPass[i].second, InFlag);
715 InFlag = Chain.getValue(1);
718 // If the callee is a GlobalAddress node (quite common, every direct call is)
719 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
720 // Likewise ExternalSymbol -> TargetExternalSymbol.
721 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
722 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32);
723 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
724 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
726 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
727 // = Chain, Callee, Reg#1, Reg#2, ...
729 // Returns a chain & a flag for retval copy to use.
730 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
731 SmallVector<SDValue, 8> Ops;
732 Ops.push_back(Chain);
733 Ops.push_back(Callee);
735 // Add argument registers to the end of the list so that they are
736 // known live into the call.
737 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
738 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
739 RegsToPass[i].second.getValueType()));
741 if (InFlag.getNode())
742 Ops.push_back(InFlag);
744 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, &Ops[0], Ops.size());
745 InFlag = Chain.getValue(1);
747 // Create the CALLSEQ_END node.
748 Chain = DAG.getCALLSEQ_END(Chain,
749 DAG.getConstant(NumBytes, getPointerTy(), true),
750 DAG.getConstant(0, getPointerTy(), true),
752 InFlag = Chain.getValue(1);
754 // Handle result values, copying them out of physregs into vregs that we
756 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
760 /// LowerCallResult - Lower the result values of an ISD::CALL into the
761 /// appropriate copies out of appropriate physical registers. This assumes that
762 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
763 /// being lowered. Returns a SDNode with the same number of values as the
765 SDNode *XCoreTargetLowering::
766 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
767 unsigned CallingConv, SelectionDAG &DAG) {
768 bool isVarArg = TheCall->isVarArg();
769 DebugLoc dl = TheCall->getDebugLoc();
771 // Assign locations to each value returned by this call.
772 SmallVector<CCValAssign, 16> RVLocs;
773 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(),
774 RVLocs, DAG.getContext());
776 CCInfo.AnalyzeCallResult(TheCall, RetCC_XCore);
777 SmallVector<SDValue, 8> ResultVals;
779 // Copy all of the result registers out of their specified physreg.
780 for (unsigned i = 0; i != RVLocs.size(); ++i) {
781 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
782 RVLocs[i].getValVT(), InFlag).getValue(1);
783 InFlag = Chain.getValue(2);
784 ResultVals.push_back(Chain.getValue(0));
787 ResultVals.push_back(Chain);
789 // Merge everything together with a MERGE_VALUES node.
790 return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
791 &ResultVals[0], ResultVals.size()).getNode();
794 //===----------------------------------------------------------------------===//
795 // FORMAL_ARGUMENTS Calling Convention Implementation
796 //===----------------------------------------------------------------------===//
798 /// XCore custom FORMAL_ARGUMENTS implementation
799 SDValue XCoreTargetLowering::
800 LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG)
802 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
806 llvm_unreachable("Unsupported calling convention");
808 case CallingConv::Fast:
809 return LowerCCCArguments(Op, DAG);
813 /// LowerCCCArguments - transform physical registers into
814 /// virtual registers and generate load operations for
815 /// arguments places on the stack.
817 SDValue XCoreTargetLowering::
818 LowerCCCArguments(SDValue Op, SelectionDAG &DAG)
820 MachineFunction &MF = DAG.getMachineFunction();
821 MachineFrameInfo *MFI = MF.getFrameInfo();
822 MachineRegisterInfo &RegInfo = MF.getRegInfo();
823 SDValue Root = Op.getOperand(0);
824 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
825 unsigned CC = MF.getFunction()->getCallingConv();
826 DebugLoc dl = Op.getDebugLoc();
828 // Assign locations to all of the incoming arguments.
829 SmallVector<CCValAssign, 16> ArgLocs;
830 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs, DAG.getContext());
832 CCInfo.AnalyzeFormalArguments(Op.getNode(), CC_XCore);
834 unsigned StackSlotSize = XCoreFrameInfo::stackSlotSize();
836 SmallVector<SDValue, 16> ArgValues;
838 unsigned LRSaveSize = StackSlotSize;
840 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
842 CCValAssign &VA = ArgLocs[i];
845 // Arguments passed in registers
846 MVT RegVT = VA.getLocVT();
847 switch (RegVT.getSimpleVT()) {
851 cerr << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
852 << RegVT.getSimpleVT() << "\n";
857 unsigned VReg = RegInfo.createVirtualRegister(
858 XCore::GRRegsRegisterClass);
859 RegInfo.addLiveIn(VA.getLocReg(), VReg);
860 ArgValues.push_back(DAG.getCopyFromReg(Root, dl, VReg, RegVT));
864 assert(VA.isMemLoc());
865 // Load the argument to a virtual register
866 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
867 if (ObjSize > StackSlotSize) {
868 cerr << "LowerFORMAL_ARGUMENTS Unhandled argument type: "
869 << VA.getLocVT().getSimpleVT()
872 // Create the frame index object for this incoming parameter...
873 int FI = MFI->CreateFixedObject(ObjSize,
874 LRSaveSize + VA.getLocMemOffset());
876 // Create the SelectionDAG nodes corresponding to a load
877 //from this parameter
878 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
879 ArgValues.push_back(DAG.getLoad(VA.getLocVT(), dl, Root, FIN, NULL, 0));
884 /* Argument registers */
885 static const unsigned ArgRegs[] = {
886 XCore::R0, XCore::R1, XCore::R2, XCore::R3
888 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
889 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
890 array_lengthof(ArgRegs));
891 if (FirstVAReg < array_lengthof(ArgRegs)) {
892 SmallVector<SDValue, 4> MemOps;
894 // Save remaining registers, storing higher register numbers at a higher
896 for (unsigned i = array_lengthof(ArgRegs) - 1; i >= FirstVAReg; --i) {
897 // Create a stack slot
898 int FI = MFI->CreateFixedObject(4, offset);
899 if (i == FirstVAReg) {
900 XFI->setVarArgsFrameIndex(FI);
902 offset -= StackSlotSize;
903 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
904 // Move argument from phys reg -> virt reg
905 unsigned VReg = RegInfo.createVirtualRegister(
906 XCore::GRRegsRegisterClass);
907 RegInfo.addLiveIn(ArgRegs[i], VReg);
908 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::i32);
909 // Move argument from virt reg -> stack
910 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
911 MemOps.push_back(Store);
914 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
915 &MemOps[0], MemOps.size());
917 // This will point to the next argument passed via stack.
918 XFI->setVarArgsFrameIndex(
919 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset()));
923 ArgValues.push_back(Root);
925 // Return the new list of results.
926 std::vector<MVT> RetVT(Op.getNode()->value_begin(),
927 Op.getNode()->value_end());
928 return DAG.getNode(ISD::MERGE_VALUES, dl, RetVT,
929 &ArgValues[0], ArgValues.size());
932 //===----------------------------------------------------------------------===//
933 // Return Value Calling Convention Implementation
934 //===----------------------------------------------------------------------===//
936 SDValue XCoreTargetLowering::
937 LowerRET(SDValue Op, SelectionDAG &DAG)
939 // CCValAssign - represent the assignment of
940 // the return value to a location
941 SmallVector<CCValAssign, 16> RVLocs;
942 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
943 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
944 DebugLoc dl = Op.getDebugLoc();
946 // CCState - Info about the registers and stack slot.
947 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs, DAG.getContext());
949 // Analize return values of ISD::RET
950 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_XCore);
952 // If this is the first return lowered for this function, add
953 // the regs to the liveout set for the function.
954 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
955 for (unsigned i = 0; i != RVLocs.size(); ++i)
956 if (RVLocs[i].isRegLoc())
957 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
960 // The chain is always operand #0
961 SDValue Chain = Op.getOperand(0);
964 // Copy the result values into the output registers.
965 for (unsigned i = 0; i != RVLocs.size(); ++i) {
966 CCValAssign &VA = RVLocs[i];
967 assert(VA.isRegLoc() && "Can only return in registers!");
969 // ISD::RET => ret chain, (regnum1,val1), ...
970 // So i*2+1 index only the regnums
971 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
972 Op.getOperand(i*2+1), Flag);
974 // guarantee that all emitted copies are
975 // stuck together, avoiding something bad
976 Flag = Chain.getValue(1);
979 // Return on XCore is always a "retsp 0"
981 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
982 Chain, DAG.getConstant(0, MVT::i32), Flag);
984 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
985 Chain, DAG.getConstant(0, MVT::i32));
988 //===----------------------------------------------------------------------===//
989 // Other Lowering Code
990 //===----------------------------------------------------------------------===//
993 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
994 MachineBasicBlock *BB) const {
995 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
996 DebugLoc dl = MI->getDebugLoc();
997 assert((MI->getOpcode() == XCore::SELECT_CC) &&
998 "Unexpected instr type to insert");
1000 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1001 // control-flow pattern. The incoming instruction knows the destination vreg
1002 // to set, the condition code register to branch on, the true/false values to
1003 // select between, and a branch opcode to use.
1004 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1005 MachineFunction::iterator It = BB;
1011 // cmpTY ccX, r1, r2
1013 // fallthrough --> copy0MBB
1014 MachineBasicBlock *thisMBB = BB;
1015 MachineFunction *F = BB->getParent();
1016 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1017 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1018 BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1019 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1020 F->insert(It, copy0MBB);
1021 F->insert(It, sinkMBB);
1022 // Update machine-CFG edges by transferring all successors of the current
1023 // block to the new block which will contain the Phi node for the select.
1024 sinkMBB->transferSuccessors(BB);
1025 // Next, add the true and fallthrough blocks as its successors.
1026 BB->addSuccessor(copy0MBB);
1027 BB->addSuccessor(sinkMBB);
1030 // %FalseValue = ...
1031 // # fallthrough to sinkMBB
1034 // Update machine-CFG edges
1035 BB->addSuccessor(sinkMBB);
1038 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1041 BuildMI(BB, dl, TII.get(XCore::PHI), MI->getOperand(0).getReg())
1042 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1043 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1045 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
1049 //===----------------------------------------------------------------------===//
1050 // Addressing mode description hooks
1051 //===----------------------------------------------------------------------===//
1053 static inline bool isImmUs(int64_t val)
1055 return (val >= 0 && val <= 11);
1058 static inline bool isImmUs2(int64_t val)
1060 return (val%2 == 0 && isImmUs(val/2));
1063 static inline bool isImmUs4(int64_t val)
1065 return (val%4 == 0 && isImmUs(val/4));
1068 /// isLegalAddressingMode - Return true if the addressing mode represented
1069 /// by AM is legal for this target, for a load/store of the specified type.
1071 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1072 const Type *Ty) const {
1073 const TargetData *TD = TM.getTargetData();
1074 unsigned Size = TD->getTypeAllocSize(Ty);
1076 return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1083 if (AM.Scale == 0) {
1084 return isImmUs(AM.BaseOffs);
1087 return AM.Scale == 1 && AM.BaseOffs == 0;
1091 if (AM.Scale == 0) {
1092 return isImmUs2(AM.BaseOffs);
1095 return AM.Scale == 2 && AM.BaseOffs == 0;
1098 if (AM.Scale == 0) {
1099 return isImmUs4(AM.BaseOffs);
1102 return AM.Scale == 4 && AM.BaseOffs == 0;
1108 //===----------------------------------------------------------------------===//
1109 // XCore Inline Assembly Support
1110 //===----------------------------------------------------------------------===//
1112 std::vector<unsigned> XCoreTargetLowering::
1113 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1116 if (Constraint.size() != 1)
1117 return std::vector<unsigned>();
1119 switch (Constraint[0]) {
1122 return make_vector<unsigned>(XCore::R0, XCore::R1, XCore::R2,
1123 XCore::R3, XCore::R4, XCore::R5,
1124 XCore::R6, XCore::R7, XCore::R8,
1125 XCore::R9, XCore::R10, XCore::R11, 0);
1128 return std::vector<unsigned>();