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 "XCoreTargetObjectFile.h"
20 #include "XCoreTargetMachine.h"
21 #include "XCoreSubtarget.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/CallingConv.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/GlobalAlias.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/SelectionDAGISel.h"
34 #include "llvm/CodeGen/ValueTypes.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/ADT/VectorExtras.h"
43 const char *XCoreTargetLowering::
44 getTargetNodeName(unsigned Opcode) const
48 case XCoreISD::BL : return "XCoreISD::BL";
49 case XCoreISD::PCRelativeWrapper : return "XCoreISD::PCRelativeWrapper";
50 case XCoreISD::DPRelativeWrapper : return "XCoreISD::DPRelativeWrapper";
51 case XCoreISD::CPRelativeWrapper : return "XCoreISD::CPRelativeWrapper";
52 case XCoreISD::STWSP : return "XCoreISD::STWSP";
53 case XCoreISD::RETSP : return "XCoreISD::RETSP";
54 case XCoreISD::LADD : return "XCoreISD::LADD";
55 case XCoreISD::LSUB : return "XCoreISD::LSUB";
56 default : return NULL;
60 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
61 : TargetLowering(XTM, new XCoreTargetObjectFile()),
63 Subtarget(*XTM.getSubtargetImpl()) {
65 // Set up the register classes.
66 addRegisterClass(MVT::i32, XCore::GRRegsRegisterClass);
68 // Compute derived properties from the register classes
69 computeRegisterProperties();
71 // Division is expensive
72 setIntDivIsCheap(false);
74 setShiftAmountType(MVT::i32);
75 setStackPointerRegisterToSaveRestore(XCore::SP);
77 setSchedulingPreference(SchedulingForRegPressure);
79 // Use i32 for setcc operations results (slt, sgt, ...).
80 setBooleanContents(ZeroOrOneBooleanContent);
82 // XCore does not have the NodeTypes below.
83 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
84 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
85 setOperationAction(ISD::ADDC, MVT::i32, Expand);
86 setOperationAction(ISD::ADDE, MVT::i32, Expand);
87 setOperationAction(ISD::SUBC, MVT::i32, Expand);
88 setOperationAction(ISD::SUBE, MVT::i32, Expand);
90 // Stop the combiner recombining select and set_cc
91 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
94 setOperationAction(ISD::ADD, MVT::i64, Custom);
95 setOperationAction(ISD::SUB, MVT::i64, Custom);
96 setOperationAction(ISD::MULHS, MVT::i32, Expand);
97 setOperationAction(ISD::MULHU, MVT::i32, Expand);
98 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
99 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
100 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
103 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
104 setOperationAction(ISD::ROTL , MVT::i32, Expand);
105 setOperationAction(ISD::ROTR , MVT::i32, Expand);
107 setOperationAction(ISD::TRAP, MVT::Other, Legal);
109 // Expand jump tables for now
110 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
111 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
113 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
114 setOperationAction(ISD::BlockAddress, MVT::i32 , Custom);
116 // Thread Local Storage
117 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
119 // Conversion of i64 -> double produces constantpool nodes
120 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
123 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
124 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
125 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
127 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
128 setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
130 // Custom expand misaligned loads / stores.
131 setOperationAction(ISD::LOAD, MVT::i32, Custom);
132 setOperationAction(ISD::STORE, MVT::i32, Custom);
135 setOperationAction(ISD::VAEND, MVT::Other, Expand);
136 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
137 setOperationAction(ISD::VAARG, MVT::Other, Custom);
138 setOperationAction(ISD::VASTART, MVT::Other, Custom);
141 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
142 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
143 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
146 setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
148 maxStoresPerMemset = 4;
149 maxStoresPerMemmove = maxStoresPerMemcpy = 2;
151 // We have target-specific dag combine patterns for the following nodes:
152 setTargetDAGCombine(ISD::STORE);
155 SDValue XCoreTargetLowering::
156 LowerOperation(SDValue Op, SelectionDAG &DAG) {
157 switch (Op.getOpcode())
159 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
160 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
161 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
162 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
163 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
164 case ISD::LOAD: return LowerLOAD(Op, DAG);
165 case ISD::STORE: return LowerSTORE(Op, DAG);
166 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
167 case ISD::VAARG: return LowerVAARG(Op, DAG);
168 case ISD::VASTART: return LowerVASTART(Op, DAG);
169 // FIXME: Remove these when LegalizeDAGTypes lands.
171 case ISD::SUB: return ExpandADDSUB(Op.getNode(), DAG);
172 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
174 llvm_unreachable("unimplemented operand");
179 /// ReplaceNodeResults - Replace the results of node with an illegal result
180 /// type with new values built out of custom code.
181 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
182 SmallVectorImpl<SDValue>&Results,
184 switch (N->getOpcode()) {
186 llvm_unreachable("Don't know how to custom expand this!");
190 Results.push_back(ExpandADDSUB(N, DAG));
195 /// getFunctionAlignment - Return the Log2 alignment of this function.
196 unsigned XCoreTargetLowering::
197 getFunctionAlignment(const Function *) const {
201 //===----------------------------------------------------------------------===//
202 // Misc Lower Operation implementation
203 //===----------------------------------------------------------------------===//
205 SDValue XCoreTargetLowering::
206 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG)
208 DebugLoc dl = Op.getDebugLoc();
209 SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i32, Op.getOperand(2),
210 Op.getOperand(3), Op.getOperand(4));
211 return DAG.getNode(ISD::SELECT, dl, MVT::i32, Cond, Op.getOperand(0),
215 SDValue XCoreTargetLowering::
216 getGlobalAddressWrapper(SDValue GA, GlobalValue *GV, SelectionDAG &DAG)
218 // FIXME there is no actual debug info here
219 DebugLoc dl = GA.getDebugLoc();
220 if (isa<Function>(GV)) {
221 return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
223 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
225 // If GV is an alias then use the aliasee to determine constness
226 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
227 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
229 bool isConst = GVar && GVar->isConstant();
231 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
233 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
236 SDValue XCoreTargetLowering::
237 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG)
239 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
240 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
241 // If it's a debug information descriptor, don't mess with it.
242 if (DAG.isVerifiedDebugInfoDesc(Op))
244 return getGlobalAddressWrapper(GA, GV, DAG);
247 static inline SDValue BuildGetId(SelectionDAG &DAG, DebugLoc dl) {
248 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
249 DAG.getConstant(Intrinsic::xcore_getid, MVT::i32));
252 static inline bool isZeroLengthArray(const Type *Ty) {
253 const ArrayType *AT = dyn_cast_or_null<ArrayType>(Ty);
254 return AT && (AT->getNumElements() == 0);
257 SDValue XCoreTargetLowering::
258 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG)
260 // FIXME there isn't really debug info here
261 DebugLoc dl = Op.getDebugLoc();
262 // transform to label + getid() * size
263 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
264 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
265 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
267 // If GV is an alias then use the aliasee to determine size
268 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
269 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
272 llvm_unreachable("Thread local object not a GlobalVariable?");
275 const Type *Ty = cast<PointerType>(GV->getType())->getElementType();
276 if (!Ty->isSized() || isZeroLengthArray(Ty)) {
278 errs() << "Size of thread local object " << GVar->getName()
283 SDValue base = getGlobalAddressWrapper(GA, GV, DAG);
284 const TargetData *TD = TM.getTargetData();
285 unsigned Size = TD->getTypeAllocSize(Ty);
286 SDValue offset = DAG.getNode(ISD::MUL, dl, MVT::i32, BuildGetId(DAG, dl),
287 DAG.getConstant(Size, MVT::i32));
288 return DAG.getNode(ISD::ADD, dl, MVT::i32, base, offset);
291 SDValue XCoreTargetLowering::
292 LowerBlockAddress(SDValue Op, SelectionDAG &DAG)
294 DebugLoc DL = Op.getDebugLoc();
296 BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
297 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(), /*isTarget=*/true);
299 return DAG.getNode(XCoreISD::PCRelativeWrapper, DL, getPointerTy(), Result);
302 SDValue XCoreTargetLowering::
303 LowerConstantPool(SDValue Op, SelectionDAG &DAG)
305 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
306 // FIXME there isn't really debug info here
307 DebugLoc dl = CP->getDebugLoc();
308 EVT PtrVT = Op.getValueType();
310 if (CP->isMachineConstantPoolEntry()) {
311 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
314 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
317 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 EVT 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 &&
374 "Unexpected extension type");
375 assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
376 if (allowsUnalignedMemoryAccesses(LD->getMemoryVT())) {
379 unsigned ABIAlignment = getTargetData()->
380 getABITypeAlignment(LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
381 // Leave aligned load alone.
382 if (LD->getAlignment() >= ABIAlignment) {
385 SDValue Chain = LD->getChain();
386 SDValue BasePtr = LD->getBasePtr();
387 DebugLoc dl = Op.getDebugLoc();
391 if (!LD->isVolatile() &&
392 IsWordAlignedBasePlusConstantOffset(BasePtr, Base, Offset)) {
393 if (Offset % 4 == 0) {
394 // We've managed to infer better alignment information than the load
395 // already has. Use an aligned load.
396 return DAG.getLoad(getPointerTy(), dl, Chain, BasePtr, NULL, 4);
399 // ldw low, base[offset >> 2]
400 // ldw high, base[(offset >> 2) + 1]
401 // shr low_shifted, low, (offset & 0x3) * 8
402 // shl high_shifted, high, 32 - (offset & 0x3) * 8
403 // or result, low_shifted, high_shifted
404 SDValue LowOffset = DAG.getConstant(Offset & ~0x3, MVT::i32);
405 SDValue HighOffset = DAG.getConstant((Offset & ~0x3) + 4, MVT::i32);
406 SDValue LowShift = DAG.getConstant((Offset & 0x3) * 8, MVT::i32);
407 SDValue HighShift = DAG.getConstant(32 - (Offset & 0x3) * 8, MVT::i32);
409 SDValue LowAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Base, LowOffset);
410 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Base, HighOffset);
412 SDValue Low = DAG.getLoad(getPointerTy(), dl, Chain,
414 SDValue High = DAG.getLoad(getPointerTy(), dl, Chain,
416 SDValue LowShifted = DAG.getNode(ISD::SRL, dl, MVT::i32, Low, LowShift);
417 SDValue HighShifted = DAG.getNode(ISD::SHL, dl, MVT::i32, High, HighShift);
418 SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, LowShifted, HighShifted);
419 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Low.getValue(1),
421 SDValue Ops[] = { Result, Chain };
422 return DAG.getMergeValues(Ops, 2, dl);
425 if (LD->getAlignment() == 2) {
426 int SVOffset = LD->getSrcValueOffset();
427 SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
428 BasePtr, LD->getSrcValue(), SVOffset, MVT::i16,
429 LD->isVolatile(), 2);
430 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
431 DAG.getConstant(2, MVT::i32));
432 SDValue High = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::i32, Chain,
433 HighAddr, LD->getSrcValue(), SVOffset + 2,
434 MVT::i16, LD->isVolatile(), 2);
435 SDValue HighShifted = DAG.getNode(ISD::SHL, dl, MVT::i32, High,
436 DAG.getConstant(16, MVT::i32));
437 SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, Low, HighShifted);
438 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Low.getValue(1),
440 SDValue Ops[] = { Result, Chain };
441 return DAG.getMergeValues(Ops, 2, dl);
444 // Lower to a call to __misaligned_load(BasePtr).
445 const Type *IntPtrTy = getTargetData()->getIntPtrType(*DAG.getContext());
446 TargetLowering::ArgListTy Args;
447 TargetLowering::ArgListEntry Entry;
450 Entry.Node = BasePtr;
451 Args.push_back(Entry);
453 std::pair<SDValue, SDValue> CallResult =
454 LowerCallTo(Chain, IntPtrTy, false, false,
455 false, false, 0, CallingConv::C, false,
456 /*isReturnValueUsed=*/true,
457 DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
461 { CallResult.first, CallResult.second };
463 return DAG.getMergeValues(Ops, 2, dl);
466 SDValue XCoreTargetLowering::
467 LowerSTORE(SDValue Op, SelectionDAG &DAG)
469 StoreSDNode *ST = cast<StoreSDNode>(Op);
470 assert(!ST->isTruncatingStore() && "Unexpected store type");
471 assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
472 if (allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
475 unsigned ABIAlignment = getTargetData()->
476 getABITypeAlignment(ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
477 // Leave aligned store alone.
478 if (ST->getAlignment() >= ABIAlignment) {
481 SDValue Chain = ST->getChain();
482 SDValue BasePtr = ST->getBasePtr();
483 SDValue Value = ST->getValue();
484 DebugLoc dl = Op.getDebugLoc();
486 if (ST->getAlignment() == 2) {
487 int SVOffset = ST->getSrcValueOffset();
489 SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
490 DAG.getConstant(16, MVT::i32));
491 SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
492 ST->getSrcValue(), SVOffset, MVT::i16,
493 ST->isVolatile(), 2);
494 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
495 DAG.getConstant(2, MVT::i32));
496 SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
497 ST->getSrcValue(), SVOffset + 2,
498 MVT::i16, ST->isVolatile(), 2);
499 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
502 // Lower to a call to __misaligned_store(BasePtr, Value).
503 const Type *IntPtrTy = getTargetData()->getIntPtrType(*DAG.getContext());
504 TargetLowering::ArgListTy Args;
505 TargetLowering::ArgListEntry Entry;
508 Entry.Node = BasePtr;
509 Args.push_back(Entry);
512 Args.push_back(Entry);
514 std::pair<SDValue, SDValue> CallResult =
515 LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()), false, false,
516 false, false, 0, CallingConv::C, false,
517 /*isReturnValueUsed=*/true,
518 DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
521 return CallResult.second;
524 SDValue XCoreTargetLowering::
525 ExpandADDSUB(SDNode *N, SelectionDAG &DAG)
527 assert(N->getValueType(0) == MVT::i64 &&
528 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
529 "Unknown operand to lower!");
530 DebugLoc dl = N->getDebugLoc();
532 // Extract components
533 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
534 N->getOperand(0), DAG.getConstant(0, MVT::i32));
535 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
536 N->getOperand(0), DAG.getConstant(1, MVT::i32));
537 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
538 N->getOperand(1), DAG.getConstant(0, MVT::i32));
539 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
540 N->getOperand(1), DAG.getConstant(1, MVT::i32));
543 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
545 SDValue Zero = DAG.getConstant(0, MVT::i32);
546 SDValue Carry = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
548 SDValue Lo(Carry.getNode(), 1);
550 SDValue Ignored = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
552 SDValue Hi(Ignored.getNode(), 1);
554 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
557 SDValue XCoreTargetLowering::
558 LowerVAARG(SDValue Op, SelectionDAG &DAG)
560 llvm_unreachable("unimplemented");
561 // FIX Arguments passed by reference need a extra dereference.
562 SDNode *Node = Op.getNode();
563 DebugLoc dl = Node->getDebugLoc();
564 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
565 EVT VT = Node->getValueType(0);
566 SDValue VAList = DAG.getLoad(getPointerTy(), dl, Node->getOperand(0),
567 Node->getOperand(1), V, 0);
568 // Increment the pointer, VAList, to the next vararg
569 SDValue Tmp3 = DAG.getNode(ISD::ADD, dl, getPointerTy(), VAList,
570 DAG.getConstant(VT.getSizeInBits(),
572 // Store the incremented VAList to the legalized pointer
573 Tmp3 = DAG.getStore(VAList.getValue(1), dl, Tmp3, Node->getOperand(1), V, 0);
574 // Load the actual argument out of the pointer VAList
575 return DAG.getLoad(VT, dl, Tmp3, VAList, NULL, 0);
578 SDValue XCoreTargetLowering::
579 LowerVASTART(SDValue Op, SelectionDAG &DAG)
581 DebugLoc dl = Op.getDebugLoc();
582 // vastart stores the address of the VarArgsFrameIndex slot into the
583 // memory location argument
584 MachineFunction &MF = DAG.getMachineFunction();
585 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
586 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
587 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
588 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1), SV, 0);
591 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
592 DebugLoc dl = Op.getDebugLoc();
593 // Depths > 0 not supported yet!
594 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
597 MachineFunction &MF = DAG.getMachineFunction();
598 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
599 return DAG.getCopyFromReg(DAG.getEntryNode(), dl,
600 RegInfo->getFrameRegister(MF), MVT::i32);
603 //===----------------------------------------------------------------------===//
604 // Calling Convention Implementation
605 //===----------------------------------------------------------------------===//
607 #include "XCoreGenCallingConv.inc"
609 //===----------------------------------------------------------------------===//
610 // Call Calling Convention Implementation
611 //===----------------------------------------------------------------------===//
613 /// XCore call implementation
615 XCoreTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
616 CallingConv::ID CallConv, bool isVarArg,
618 const SmallVectorImpl<ISD::OutputArg> &Outs,
619 const SmallVectorImpl<ISD::InputArg> &Ins,
620 DebugLoc dl, SelectionDAG &DAG,
621 SmallVectorImpl<SDValue> &InVals) {
623 // For now, only CallingConv::C implemented
627 llvm_unreachable("Unsupported calling convention");
628 case CallingConv::Fast:
630 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
631 Outs, Ins, dl, DAG, InVals);
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.
640 XCoreTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
641 CallingConv::ID CallConv, bool isVarArg,
643 const SmallVectorImpl<ISD::OutputArg> &Outs,
644 const SmallVectorImpl<ISD::InputArg> &Ins,
645 DebugLoc dl, SelectionDAG &DAG,
646 SmallVectorImpl<SDValue> &InVals) {
648 // Analyze operands of the call, assigning locations to each operand.
649 SmallVector<CCValAssign, 16> ArgLocs;
650 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
651 ArgLocs, *DAG.getContext());
653 // The ABI dictates there should be one stack slot available to the callee
654 // on function entry (for saving lr).
655 CCInfo.AllocateStack(4, 4);
657 CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
659 // Get a count of how many bytes are to be pushed on the stack.
660 unsigned NumBytes = CCInfo.getNextStackOffset();
662 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
663 getPointerTy(), true));
665 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
666 SmallVector<SDValue, 12> MemOpChains;
668 // Walk the register/memloc assignments, inserting copies/loads.
669 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
670 CCValAssign &VA = ArgLocs[i];
671 SDValue Arg = Outs[i].Val;
673 // Promote the value if needed.
674 switch (VA.getLocInfo()) {
675 default: llvm_unreachable("Unknown loc info!");
676 case CCValAssign::Full: break;
677 case CCValAssign::SExt:
678 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
680 case CCValAssign::ZExt:
681 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
683 case CCValAssign::AExt:
684 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
688 // Arguments that can be passed on register must be kept at
691 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
693 assert(VA.isMemLoc());
695 int Offset = VA.getLocMemOffset();
697 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
699 DAG.getConstant(Offset/4, MVT::i32)));
703 // Transform all store nodes into one single node because
704 // all store nodes are independent of each other.
705 if (!MemOpChains.empty())
706 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
707 &MemOpChains[0], MemOpChains.size());
709 // Build a sequence of copy-to-reg nodes chained together with token
710 // chain and flag operands which copy the outgoing args into registers.
711 // The InFlag in necessary since all emited instructions must be
714 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
715 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
716 RegsToPass[i].second, InFlag);
717 InFlag = Chain.getValue(1);
720 // If the callee is a GlobalAddress node (quite common, every direct call is)
721 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
722 // Likewise ExternalSymbol -> TargetExternalSymbol.
723 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
724 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32);
725 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
726 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
728 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
729 // = Chain, Callee, Reg#1, Reg#2, ...
731 // Returns a chain & a flag for retval copy to use.
732 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
733 SmallVector<SDValue, 8> Ops;
734 Ops.push_back(Chain);
735 Ops.push_back(Callee);
737 // Add argument registers to the end of the list so that they are
738 // known live into the call.
739 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
740 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
741 RegsToPass[i].second.getValueType()));
743 if (InFlag.getNode())
744 Ops.push_back(InFlag);
746 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, &Ops[0], Ops.size());
747 InFlag = Chain.getValue(1);
749 // Create the CALLSEQ_END node.
750 Chain = DAG.getCALLSEQ_END(Chain,
751 DAG.getConstant(NumBytes, getPointerTy(), true),
752 DAG.getConstant(0, getPointerTy(), true),
754 InFlag = Chain.getValue(1);
756 // Handle result values, copying them out of physregs into vregs that we
758 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
759 Ins, dl, DAG, InVals);
762 /// LowerCallResult - Lower the result values of a call into the
763 /// appropriate copies out of appropriate physical registers.
765 XCoreTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
766 CallingConv::ID CallConv, bool isVarArg,
767 const SmallVectorImpl<ISD::InputArg> &Ins,
768 DebugLoc dl, SelectionDAG &DAG,
769 SmallVectorImpl<SDValue> &InVals) {
771 // Assign locations to each value returned by this call.
772 SmallVector<CCValAssign, 16> RVLocs;
773 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
774 RVLocs, *DAG.getContext());
776 CCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
778 // Copy all of the result registers out of their specified physreg.
779 for (unsigned i = 0; i != RVLocs.size(); ++i) {
780 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
781 RVLocs[i].getValVT(), InFlag).getValue(1);
782 InFlag = Chain.getValue(2);
783 InVals.push_back(Chain.getValue(0));
789 //===----------------------------------------------------------------------===//
790 // Formal Arguments Calling Convention Implementation
791 //===----------------------------------------------------------------------===//
793 /// XCore formal arguments implementation
795 XCoreTargetLowering::LowerFormalArguments(SDValue Chain,
796 CallingConv::ID CallConv,
798 const SmallVectorImpl<ISD::InputArg> &Ins,
801 SmallVectorImpl<SDValue> &InVals) {
805 llvm_unreachable("Unsupported calling convention");
807 case CallingConv::Fast:
808 return LowerCCCArguments(Chain, CallConv, isVarArg,
809 Ins, dl, DAG, InVals);
813 /// LowerCCCArguments - transform physical registers into
814 /// virtual registers and generate load operations for
815 /// arguments places on the stack.
818 XCoreTargetLowering::LowerCCCArguments(SDValue Chain,
819 CallingConv::ID CallConv,
821 const SmallVectorImpl<ISD::InputArg>
825 SmallVectorImpl<SDValue> &InVals) {
826 MachineFunction &MF = DAG.getMachineFunction();
827 MachineFrameInfo *MFI = MF.getFrameInfo();
828 MachineRegisterInfo &RegInfo = MF.getRegInfo();
830 // Assign locations to all of the incoming arguments.
831 SmallVector<CCValAssign, 16> ArgLocs;
832 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
833 ArgLocs, *DAG.getContext());
835 CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
837 unsigned StackSlotSize = XCoreFrameInfo::stackSlotSize();
839 unsigned LRSaveSize = StackSlotSize;
841 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
843 CCValAssign &VA = ArgLocs[i];
846 // Arguments passed in registers
847 EVT RegVT = VA.getLocVT();
848 switch (RegVT.getSimpleVT().SimpleTy) {
852 errs() << "LowerFormalArguments Unhandled argument type: "
853 << RegVT.getSimpleVT().SimpleTy << "\n";
858 unsigned VReg = RegInfo.createVirtualRegister(
859 XCore::GRRegsRegisterClass);
860 RegInfo.addLiveIn(VA.getLocReg(), VReg);
861 InVals.push_back(DAG.getCopyFromReg(Chain, dl, VReg, RegVT));
865 assert(VA.isMemLoc());
866 // Load the argument to a virtual register
867 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
868 if (ObjSize > StackSlotSize) {
869 errs() << "LowerFormalArguments Unhandled argument type: "
870 << (unsigned)VA.getLocVT().getSimpleVT().SimpleTy
873 // Create the frame index object for this incoming parameter...
874 int FI = MFI->CreateFixedObject(ObjSize,
875 LRSaveSize + VA.getLocMemOffset(),
878 // Create the SelectionDAG nodes corresponding to a load
879 //from this parameter
880 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
881 InVals.push_back(DAG.getLoad(VA.getLocVT(), dl, Chain, FIN, NULL, 0));
886 /* Argument registers */
887 static const unsigned ArgRegs[] = {
888 XCore::R0, XCore::R1, XCore::R2, XCore::R3
890 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
891 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
892 array_lengthof(ArgRegs));
893 if (FirstVAReg < array_lengthof(ArgRegs)) {
894 SmallVector<SDValue, 4> MemOps;
896 // Save remaining registers, storing higher register numbers at a higher
898 for (unsigned i = array_lengthof(ArgRegs) - 1; i >= FirstVAReg; --i) {
899 // Create a stack slot
900 int FI = MFI->CreateFixedObject(4, offset, true, false);
901 if (i == FirstVAReg) {
902 XFI->setVarArgsFrameIndex(FI);
904 offset -= StackSlotSize;
905 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
906 // Move argument from phys reg -> virt reg
907 unsigned VReg = RegInfo.createVirtualRegister(
908 XCore::GRRegsRegisterClass);
909 RegInfo.addLiveIn(ArgRegs[i], VReg);
910 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
911 // Move argument from virt reg -> stack
912 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
913 MemOps.push_back(Store);
916 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
917 &MemOps[0], MemOps.size());
919 // This will point to the next argument passed via stack.
920 XFI->setVarArgsFrameIndex(
921 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset(),
929 //===----------------------------------------------------------------------===//
930 // Return Value Calling Convention Implementation
931 //===----------------------------------------------------------------------===//
933 bool XCoreTargetLowering::
934 CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
935 const SmallVectorImpl<EVT> &OutTys,
936 const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
938 SmallVector<CCValAssign, 16> RVLocs;
939 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
940 RVLocs, *DAG.getContext());
941 return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_XCore);
945 XCoreTargetLowering::LowerReturn(SDValue Chain,
946 CallingConv::ID CallConv, bool isVarArg,
947 const SmallVectorImpl<ISD::OutputArg> &Outs,
948 DebugLoc dl, SelectionDAG &DAG) {
950 // CCValAssign - represent the assignment of
951 // the return value to a location
952 SmallVector<CCValAssign, 16> RVLocs;
954 // CCState - Info about the registers and stack slot.
955 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
956 RVLocs, *DAG.getContext());
958 // Analize return values.
959 CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
961 // If this is the first return lowered for this function, add
962 // the regs to the liveout set for the function.
963 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
964 for (unsigned i = 0; i != RVLocs.size(); ++i)
965 if (RVLocs[i].isRegLoc())
966 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
971 // Copy the result values into the output registers.
972 for (unsigned i = 0; i != RVLocs.size(); ++i) {
973 CCValAssign &VA = RVLocs[i];
974 assert(VA.isRegLoc() && "Can only return in registers!");
976 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
979 // guarantee that all emitted copies are
980 // stuck together, avoiding something bad
981 Flag = Chain.getValue(1);
984 // Return on XCore is always a "retsp 0"
986 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
987 Chain, DAG.getConstant(0, MVT::i32), Flag);
989 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
990 Chain, DAG.getConstant(0, MVT::i32));
993 //===----------------------------------------------------------------------===//
994 // Other Lowering Code
995 //===----------------------------------------------------------------------===//
998 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
999 MachineBasicBlock *BB,
1000 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
1001 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1002 DebugLoc dl = MI->getDebugLoc();
1003 assert((MI->getOpcode() == XCore::SELECT_CC) &&
1004 "Unexpected instr type to insert");
1006 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1007 // control-flow pattern. The incoming instruction knows the destination vreg
1008 // to set, the condition code register to branch on, the true/false values to
1009 // select between, and a branch opcode to use.
1010 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1011 MachineFunction::iterator It = BB;
1017 // cmpTY ccX, r1, r2
1019 // fallthrough --> copy0MBB
1020 MachineBasicBlock *thisMBB = BB;
1021 MachineFunction *F = BB->getParent();
1022 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1023 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1024 BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1025 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1026 F->insert(It, copy0MBB);
1027 F->insert(It, sinkMBB);
1028 // Update machine-CFG edges by first adding all successors of the current
1029 // block to the new block which will contain the Phi node for the select.
1030 // Also inform sdisel of the edge changes.
1031 for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
1032 E = BB->succ_end(); I != E; ++I) {
1033 EM->insert(std::make_pair(*I, sinkMBB));
1034 sinkMBB->addSuccessor(*I);
1036 // Next, remove all successors of the current block, and add the true
1037 // and fallthrough blocks as its successors.
1038 while (!BB->succ_empty())
1039 BB->removeSuccessor(BB->succ_begin());
1040 // Next, add the true and fallthrough blocks as its successors.
1041 BB->addSuccessor(copy0MBB);
1042 BB->addSuccessor(sinkMBB);
1045 // %FalseValue = ...
1046 // # fallthrough to sinkMBB
1049 // Update machine-CFG edges
1050 BB->addSuccessor(sinkMBB);
1053 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1056 BuildMI(BB, dl, TII.get(XCore::PHI), MI->getOperand(0).getReg())
1057 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1058 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1060 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
1064 //===----------------------------------------------------------------------===//
1065 // Target Optimization Hooks
1066 //===----------------------------------------------------------------------===//
1068 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1069 DAGCombinerInfo &DCI) const {
1070 SelectionDAG &DAG = DCI.DAG;
1071 DebugLoc dl = N->getDebugLoc();
1072 switch (N->getOpcode()) {
1075 // Replace unaligned store of unaligned load with memmove.
1076 StoreSDNode *ST = cast<StoreSDNode>(N);
1077 if (!DCI.isBeforeLegalize() ||
1078 allowsUnalignedMemoryAccesses(ST->getMemoryVT()) ||
1079 ST->isVolatile() || ST->isIndexed()) {
1082 SDValue Chain = ST->getChain();
1084 unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1085 if (StoreBits % 8) {
1088 unsigned ABIAlignment = getTargetData()->getABITypeAlignment(
1089 ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1090 unsigned Alignment = ST->getAlignment();
1091 if (Alignment >= ABIAlignment) {
1095 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1096 if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1097 LD->getAlignment() == Alignment &&
1098 !LD->isVolatile() && !LD->isIndexed() &&
1099 Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1100 return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1102 DAG.getConstant(StoreBits/8, MVT::i32),
1103 Alignment, ST->getSrcValue(),
1104 ST->getSrcValueOffset(), LD->getSrcValue(),
1105 LD->getSrcValueOffset());
1114 //===----------------------------------------------------------------------===//
1115 // Addressing mode description hooks
1116 //===----------------------------------------------------------------------===//
1118 static inline bool isImmUs(int64_t val)
1120 return (val >= 0 && val <= 11);
1123 static inline bool isImmUs2(int64_t val)
1125 return (val%2 == 0 && isImmUs(val/2));
1128 static inline bool isImmUs4(int64_t val)
1130 return (val%4 == 0 && isImmUs(val/4));
1133 /// isLegalAddressingMode - Return true if the addressing mode represented
1134 /// by AM is legal for this target, for a load/store of the specified type.
1136 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1137 const Type *Ty) const {
1138 // Be conservative with void
1139 // FIXME: Can we be more aggressive?
1140 if (Ty->getTypeID() == Type::VoidTyID)
1143 const TargetData *TD = TM.getTargetData();
1144 unsigned Size = TD->getTypeAllocSize(Ty);
1146 return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1153 if (AM.Scale == 0) {
1154 return isImmUs(AM.BaseOffs);
1157 return AM.Scale == 1 && AM.BaseOffs == 0;
1161 if (AM.Scale == 0) {
1162 return isImmUs2(AM.BaseOffs);
1165 return AM.Scale == 2 && AM.BaseOffs == 0;
1168 if (AM.Scale == 0) {
1169 return isImmUs4(AM.BaseOffs);
1172 return AM.Scale == 4 && AM.BaseOffs == 0;
1178 //===----------------------------------------------------------------------===//
1179 // XCore Inline Assembly Support
1180 //===----------------------------------------------------------------------===//
1182 std::vector<unsigned> XCoreTargetLowering::
1183 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1186 if (Constraint.size() != 1)
1187 return std::vector<unsigned>();
1189 switch (Constraint[0]) {
1192 return make_vector<unsigned>(XCore::R0, XCore::R1, XCore::R2,
1193 XCore::R3, XCore::R4, XCore::R5,
1194 XCore::R6, XCore::R7, XCore::R8,
1195 XCore::R9, XCore::R10, XCore::R11, 0);
1198 return std::vector<unsigned>();