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 default : return NULL;
58 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
59 : TargetLowering(XTM, new XCoreTargetObjectFile()),
61 Subtarget(*XTM.getSubtargetImpl()) {
63 // Set up the register classes.
64 addRegisterClass(MVT::i32, XCore::GRRegsRegisterClass);
66 // Compute derived properties from the register classes
67 computeRegisterProperties();
69 // Division is expensive
70 setIntDivIsCheap(false);
72 setShiftAmountType(MVT::i32);
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 setOperationAction(ISD::ADD, MVT::i64, Custom);
93 setOperationAction(ISD::SUB, MVT::i64, Custom);
94 setOperationAction(ISD::MULHS, MVT::i32, Expand);
95 setOperationAction(ISD::MULHU, MVT::i32, Expand);
96 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
97 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
98 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
101 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
102 setOperationAction(ISD::ROTL , MVT::i32, Expand);
103 setOperationAction(ISD::ROTR , MVT::i32, Expand);
105 setOperationAction(ISD::TRAP, MVT::Other, Legal);
107 // Expand jump tables for now
108 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
109 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
111 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
113 // Thread Local Storage
114 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
116 // Conversion of i64 -> double produces constantpool nodes
117 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
120 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
121 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
122 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
124 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
125 setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
127 // Custom expand misaligned loads / stores.
128 setOperationAction(ISD::LOAD, MVT::i32, Custom);
129 setOperationAction(ISD::STORE, MVT::i32, Custom);
132 setOperationAction(ISD::VAEND, MVT::Other, Expand);
133 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
134 setOperationAction(ISD::VAARG, MVT::Other, Custom);
135 setOperationAction(ISD::VASTART, MVT::Other, Custom);
138 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
139 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
140 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
143 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
144 setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
146 maxStoresPerMemset = 4;
147 maxStoresPerMemmove = maxStoresPerMemcpy = 2;
149 // We have target-specific dag combine patterns for the following nodes:
150 setTargetDAGCombine(ISD::STORE);
153 SDValue XCoreTargetLowering::
154 LowerOperation(SDValue Op, SelectionDAG &DAG) {
155 switch (Op.getOpcode())
157 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
158 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
159 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
160 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
161 case ISD::LOAD: return LowerLOAD(Op, DAG);
162 case ISD::STORE: return LowerSTORE(Op, DAG);
163 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
164 case ISD::VAARG: return LowerVAARG(Op, DAG);
165 case ISD::VASTART: return LowerVASTART(Op, DAG);
166 // FIXME: Remove these when LegalizeDAGTypes lands.
168 case ISD::SUB: return ExpandADDSUB(Op.getNode(), DAG);
169 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
171 llvm_unreachable("unimplemented operand");
176 /// ReplaceNodeResults - Replace the results of node with an illegal result
177 /// type with new values built out of custom code.
178 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
179 SmallVectorImpl<SDValue>&Results,
181 switch (N->getOpcode()) {
183 llvm_unreachable("Don't know how to custom expand this!");
187 Results.push_back(ExpandADDSUB(N, DAG));
192 /// getFunctionAlignment - Return the Log2 alignment of this function.
193 unsigned XCoreTargetLowering::
194 getFunctionAlignment(const Function *) const {
198 //===----------------------------------------------------------------------===//
199 // Misc Lower Operation implementation
200 //===----------------------------------------------------------------------===//
202 SDValue XCoreTargetLowering::
203 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG)
205 DebugLoc dl = Op.getDebugLoc();
206 SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i32, Op.getOperand(2),
207 Op.getOperand(3), Op.getOperand(4));
208 return DAG.getNode(ISD::SELECT, dl, MVT::i32, Cond, Op.getOperand(0),
212 SDValue XCoreTargetLowering::
213 getGlobalAddressWrapper(SDValue GA, GlobalValue *GV, SelectionDAG &DAG)
215 // FIXME there is no actual debug info here
216 DebugLoc dl = GA.getDebugLoc();
217 if (isa<Function>(GV)) {
218 return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
220 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
222 // If GV is an alias then use the aliasee to determine constness
223 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
224 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
226 bool isConst = GVar && GVar->isConstant();
228 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
230 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
233 SDValue XCoreTargetLowering::
234 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG)
236 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
237 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
238 // If it's a debug information descriptor, don't mess with it.
239 if (DAG.isVerifiedDebugInfoDesc(Op))
241 return getGlobalAddressWrapper(GA, GV, DAG);
244 static inline SDValue BuildGetId(SelectionDAG &DAG, DebugLoc dl) {
245 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
246 DAG.getConstant(Intrinsic::xcore_getid, MVT::i32));
249 static inline bool isZeroLengthArray(const Type *Ty) {
250 const ArrayType *AT = dyn_cast_or_null<ArrayType>(Ty);
251 return AT && (AT->getNumElements() == 0);
254 SDValue XCoreTargetLowering::
255 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG)
257 // FIXME there isn't really debug info here
258 DebugLoc dl = Op.getDebugLoc();
259 // transform to label + getid() * size
260 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
261 SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
262 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
264 // If GV is an alias then use the aliasee to determine size
265 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
266 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
269 llvm_unreachable("Thread local object not a GlobalVariable?");
272 const Type *Ty = cast<PointerType>(GV->getType())->getElementType();
273 if (!Ty->isSized() || isZeroLengthArray(Ty)) {
275 errs() << "Size of thread local object " << GVar->getName()
280 SDValue base = getGlobalAddressWrapper(GA, GV, DAG);
281 const TargetData *TD = TM.getTargetData();
282 unsigned Size = TD->getTypeAllocSize(Ty);
283 SDValue offset = DAG.getNode(ISD::MUL, dl, MVT::i32, BuildGetId(DAG, dl),
284 DAG.getConstant(Size, MVT::i32));
285 return DAG.getNode(ISD::ADD, dl, MVT::i32, base, offset);
288 SDValue XCoreTargetLowering::
289 LowerConstantPool(SDValue Op, SelectionDAG &DAG)
291 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
292 // FIXME there isn't really debug info here
293 DebugLoc dl = CP->getDebugLoc();
294 EVT PtrVT = Op.getValueType();
296 if (CP->isMachineConstantPoolEntry()) {
297 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
300 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
303 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
306 SDValue XCoreTargetLowering::
307 LowerJumpTable(SDValue Op, SelectionDAG &DAG)
309 // FIXME there isn't really debug info here
310 DebugLoc dl = Op.getDebugLoc();
311 EVT PtrVT = Op.getValueType();
312 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
313 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
314 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, JTI);
318 IsWordAlignedBasePlusConstantOffset(SDValue Addr, SDValue &AlignedBase,
321 if (Addr.getOpcode() != ISD::ADD) {
324 ConstantSDNode *CN = 0;
325 if (!(CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
328 int64_t off = CN->getSExtValue();
329 const SDValue &Base = Addr.getOperand(0);
330 const SDValue *Root = &Base;
331 if (Base.getOpcode() == ISD::ADD &&
332 Base.getOperand(1).getOpcode() == ISD::SHL) {
333 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Base.getOperand(1)
335 if (CN && (CN->getSExtValue() >= 2)) {
336 Root = &Base.getOperand(0);
339 if (isa<FrameIndexSDNode>(*Root)) {
340 // All frame indicies are word aligned
345 if (Root->getOpcode() == XCoreISD::DPRelativeWrapper ||
346 Root->getOpcode() == XCoreISD::CPRelativeWrapper) {
347 // All dp / cp relative addresses are word aligned
355 SDValue XCoreTargetLowering::
356 LowerLOAD(SDValue Op, SelectionDAG &DAG)
358 LoadSDNode *LD = cast<LoadSDNode>(Op);
359 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
360 "Unexpected extension type");
361 assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
362 if (allowsUnalignedMemoryAccesses(LD->getMemoryVT())) {
365 unsigned ABIAlignment = getTargetData()->
366 getABITypeAlignment(LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
367 // Leave aligned load alone.
368 if (LD->getAlignment() >= ABIAlignment) {
371 SDValue Chain = LD->getChain();
372 SDValue BasePtr = LD->getBasePtr();
373 DebugLoc dl = Op.getDebugLoc();
377 if (!LD->isVolatile() &&
378 IsWordAlignedBasePlusConstantOffset(BasePtr, Base, Offset)) {
379 if (Offset % 4 == 0) {
380 // We've managed to infer better alignment information than the load
381 // already has. Use an aligned load.
382 return DAG.getLoad(getPointerTy(), dl, Chain, BasePtr, NULL, 4);
385 // ldw low, base[offset >> 2]
386 // ldw high, base[(offset >> 2) + 1]
387 // shr low_shifted, low, (offset & 0x3) * 8
388 // shl high_shifted, high, 32 - (offset & 0x3) * 8
389 // or result, low_shifted, high_shifted
390 SDValue LowOffset = DAG.getConstant(Offset & ~0x3, MVT::i32);
391 SDValue HighOffset = DAG.getConstant((Offset & ~0x3) + 4, MVT::i32);
392 SDValue LowShift = DAG.getConstant((Offset & 0x3) * 8, MVT::i32);
393 SDValue HighShift = DAG.getConstant(32 - (Offset & 0x3) * 8, MVT::i32);
395 SDValue LowAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Base, LowOffset);
396 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Base, HighOffset);
398 SDValue Low = DAG.getLoad(getPointerTy(), dl, Chain,
400 SDValue High = DAG.getLoad(getPointerTy(), dl, Chain,
402 SDValue LowShifted = DAG.getNode(ISD::SRL, dl, MVT::i32, Low, LowShift);
403 SDValue HighShifted = DAG.getNode(ISD::SHL, dl, MVT::i32, High, HighShift);
404 SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, LowShifted, HighShifted);
405 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Low.getValue(1),
407 SDValue Ops[] = { Result, Chain };
408 return DAG.getMergeValues(Ops, 2, dl);
411 if (LD->getAlignment() == 2) {
412 int SVOffset = LD->getSrcValueOffset();
413 SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
414 BasePtr, LD->getSrcValue(), SVOffset, MVT::i16,
415 LD->isVolatile(), 2);
416 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
417 DAG.getConstant(2, MVT::i32));
418 SDValue High = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::i32, Chain,
419 HighAddr, LD->getSrcValue(), SVOffset + 2,
420 MVT::i16, LD->isVolatile(), 2);
421 SDValue HighShifted = DAG.getNode(ISD::SHL, dl, MVT::i32, High,
422 DAG.getConstant(16, MVT::i32));
423 SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, Low, HighShifted);
424 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Low.getValue(1),
426 SDValue Ops[] = { Result, Chain };
427 return DAG.getMergeValues(Ops, 2, dl);
430 // Lower to a call to __misaligned_load(BasePtr).
431 const Type *IntPtrTy = getTargetData()->getIntPtrType(*DAG.getContext());
432 TargetLowering::ArgListTy Args;
433 TargetLowering::ArgListEntry Entry;
436 Entry.Node = BasePtr;
437 Args.push_back(Entry);
439 std::pair<SDValue, SDValue> CallResult =
440 LowerCallTo(Chain, IntPtrTy, false, false,
441 false, false, 0, CallingConv::C, false,
442 /*isReturnValueUsed=*/true,
443 DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
447 { CallResult.first, CallResult.second };
449 return DAG.getMergeValues(Ops, 2, dl);
452 SDValue XCoreTargetLowering::
453 LowerSTORE(SDValue Op, SelectionDAG &DAG)
455 StoreSDNode *ST = cast<StoreSDNode>(Op);
456 assert(!ST->isTruncatingStore() && "Unexpected store type");
457 assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
458 if (allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
461 unsigned ABIAlignment = getTargetData()->
462 getABITypeAlignment(ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
463 // Leave aligned store alone.
464 if (ST->getAlignment() >= ABIAlignment) {
467 SDValue Chain = ST->getChain();
468 SDValue BasePtr = ST->getBasePtr();
469 SDValue Value = ST->getValue();
470 DebugLoc dl = Op.getDebugLoc();
472 if (ST->getAlignment() == 2) {
473 int SVOffset = ST->getSrcValueOffset();
475 SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
476 DAG.getConstant(16, MVT::i32));
477 SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
478 ST->getSrcValue(), SVOffset, MVT::i16,
479 ST->isVolatile(), 2);
480 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
481 DAG.getConstant(2, MVT::i32));
482 SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
483 ST->getSrcValue(), SVOffset + 2,
484 MVT::i16, ST->isVolatile(), 2);
485 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
488 // Lower to a call to __misaligned_store(BasePtr, Value).
489 const Type *IntPtrTy = getTargetData()->getIntPtrType(*DAG.getContext());
490 TargetLowering::ArgListTy Args;
491 TargetLowering::ArgListEntry Entry;
494 Entry.Node = BasePtr;
495 Args.push_back(Entry);
498 Args.push_back(Entry);
500 std::pair<SDValue, SDValue> CallResult =
501 LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()), false, false,
502 false, false, 0, CallingConv::C, false,
503 /*isReturnValueUsed=*/true,
504 DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
507 return CallResult.second;
510 SDValue XCoreTargetLowering::
511 ExpandADDSUB(SDNode *N, SelectionDAG &DAG)
513 assert(N->getValueType(0) == MVT::i64 &&
514 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
515 "Unknown operand to lower!");
516 DebugLoc dl = N->getDebugLoc();
518 // Extract components
519 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
520 N->getOperand(0), DAG.getConstant(0, MVT::i32));
521 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
522 N->getOperand(0), DAG.getConstant(1, MVT::i32));
523 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
524 N->getOperand(1), DAG.getConstant(0, MVT::i32));
525 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
526 N->getOperand(1), DAG.getConstant(1, MVT::i32));
529 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
531 SDValue Zero = DAG.getConstant(0, MVT::i32);
532 SDValue Carry = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
534 SDValue Lo(Carry.getNode(), 1);
536 SDValue Ignored = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
538 SDValue Hi(Ignored.getNode(), 1);
540 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
543 SDValue XCoreTargetLowering::
544 LowerVAARG(SDValue Op, SelectionDAG &DAG)
546 llvm_unreachable("unimplemented");
547 // FIX Arguments passed by reference need a extra dereference.
548 SDNode *Node = Op.getNode();
549 DebugLoc dl = Node->getDebugLoc();
550 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
551 EVT VT = Node->getValueType(0);
552 SDValue VAList = DAG.getLoad(getPointerTy(), dl, Node->getOperand(0),
553 Node->getOperand(1), V, 0);
554 // Increment the pointer, VAList, to the next vararg
555 SDValue Tmp3 = DAG.getNode(ISD::ADD, dl, getPointerTy(), VAList,
556 DAG.getConstant(VT.getSizeInBits(),
558 // Store the incremented VAList to the legalized pointer
559 Tmp3 = DAG.getStore(VAList.getValue(1), dl, Tmp3, Node->getOperand(1), V, 0);
560 // Load the actual argument out of the pointer VAList
561 return DAG.getLoad(VT, dl, Tmp3, VAList, NULL, 0);
564 SDValue XCoreTargetLowering::
565 LowerVASTART(SDValue Op, SelectionDAG &DAG)
567 DebugLoc dl = Op.getDebugLoc();
568 // vastart stores the address of the VarArgsFrameIndex slot into the
569 // memory location argument
570 MachineFunction &MF = DAG.getMachineFunction();
571 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
572 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
573 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
574 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1), SV, 0);
577 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
578 DebugLoc dl = Op.getDebugLoc();
579 // Depths > 0 not supported yet!
580 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
583 MachineFunction &MF = DAG.getMachineFunction();
584 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
585 return DAG.getCopyFromReg(DAG.getEntryNode(), dl,
586 RegInfo->getFrameRegister(MF), MVT::i32);
589 //===----------------------------------------------------------------------===//
590 // Calling Convention Implementation
591 //===----------------------------------------------------------------------===//
593 #include "XCoreGenCallingConv.inc"
595 //===----------------------------------------------------------------------===//
596 // Call Calling Convention Implementation
597 //===----------------------------------------------------------------------===//
599 /// XCore call implementation
601 XCoreTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
602 CallingConv::ID CallConv, bool isVarArg,
604 const SmallVectorImpl<ISD::OutputArg> &Outs,
605 const SmallVectorImpl<ISD::InputArg> &Ins,
606 DebugLoc dl, SelectionDAG &DAG,
607 SmallVectorImpl<SDValue> &InVals) {
609 // For now, only CallingConv::C implemented
613 llvm_unreachable("Unsupported calling convention");
614 case CallingConv::Fast:
616 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
617 Outs, Ins, dl, DAG, InVals);
621 /// LowerCCCCallTo - functions arguments are copied from virtual
622 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
623 /// CALLSEQ_END are emitted.
624 /// TODO: isTailCall, sret.
626 XCoreTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
627 CallingConv::ID CallConv, bool isVarArg,
629 const SmallVectorImpl<ISD::OutputArg> &Outs,
630 const SmallVectorImpl<ISD::InputArg> &Ins,
631 DebugLoc dl, SelectionDAG &DAG,
632 SmallVectorImpl<SDValue> &InVals) {
634 // Analyze operands of the call, assigning locations to each operand.
635 SmallVector<CCValAssign, 16> ArgLocs;
636 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
637 ArgLocs, *DAG.getContext());
639 // The ABI dictates there should be one stack slot available to the callee
640 // on function entry (for saving lr).
641 CCInfo.AllocateStack(4, 4);
643 CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
645 // Get a count of how many bytes are to be pushed on the stack.
646 unsigned NumBytes = CCInfo.getNextStackOffset();
648 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
649 getPointerTy(), true));
651 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
652 SmallVector<SDValue, 12> MemOpChains;
654 // Walk the register/memloc assignments, inserting copies/loads.
655 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
656 CCValAssign &VA = ArgLocs[i];
657 SDValue Arg = Outs[i].Val;
659 // Promote the value if needed.
660 switch (VA.getLocInfo()) {
661 default: llvm_unreachable("Unknown loc info!");
662 case CCValAssign::Full: break;
663 case CCValAssign::SExt:
664 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
666 case CCValAssign::ZExt:
667 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
669 case CCValAssign::AExt:
670 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
674 // Arguments that can be passed on register must be kept at
677 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
679 assert(VA.isMemLoc());
681 int Offset = VA.getLocMemOffset();
683 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
685 DAG.getConstant(Offset/4, MVT::i32)));
689 // Transform all store nodes into one single node because
690 // all store nodes are independent of each other.
691 if (!MemOpChains.empty())
692 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
693 &MemOpChains[0], MemOpChains.size());
695 // Build a sequence of copy-to-reg nodes chained together with token
696 // chain and flag operands which copy the outgoing args into registers.
697 // The InFlag in necessary since all emited instructions must be
700 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
701 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
702 RegsToPass[i].second, InFlag);
703 InFlag = Chain.getValue(1);
706 // If the callee is a GlobalAddress node (quite common, every direct call is)
707 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
708 // Likewise ExternalSymbol -> TargetExternalSymbol.
709 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
710 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32);
711 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
712 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
714 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
715 // = Chain, Callee, Reg#1, Reg#2, ...
717 // Returns a chain & a flag for retval copy to use.
718 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
719 SmallVector<SDValue, 8> Ops;
720 Ops.push_back(Chain);
721 Ops.push_back(Callee);
723 // Add argument registers to the end of the list so that they are
724 // known live into the call.
725 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
726 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
727 RegsToPass[i].second.getValueType()));
729 if (InFlag.getNode())
730 Ops.push_back(InFlag);
732 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, &Ops[0], Ops.size());
733 InFlag = Chain.getValue(1);
735 // Create the CALLSEQ_END node.
736 Chain = DAG.getCALLSEQ_END(Chain,
737 DAG.getConstant(NumBytes, getPointerTy(), true),
738 DAG.getConstant(0, getPointerTy(), true),
740 InFlag = Chain.getValue(1);
742 // Handle result values, copying them out of physregs into vregs that we
744 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
745 Ins, dl, DAG, InVals);
748 /// LowerCallResult - Lower the result values of a call into the
749 /// appropriate copies out of appropriate physical registers.
751 XCoreTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
752 CallingConv::ID CallConv, bool isVarArg,
753 const SmallVectorImpl<ISD::InputArg> &Ins,
754 DebugLoc dl, SelectionDAG &DAG,
755 SmallVectorImpl<SDValue> &InVals) {
757 // Assign locations to each value returned by this call.
758 SmallVector<CCValAssign, 16> RVLocs;
759 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
760 RVLocs, *DAG.getContext());
762 CCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
764 // Copy all of the result registers out of their specified physreg.
765 for (unsigned i = 0; i != RVLocs.size(); ++i) {
766 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
767 RVLocs[i].getValVT(), InFlag).getValue(1);
768 InFlag = Chain.getValue(2);
769 InVals.push_back(Chain.getValue(0));
775 //===----------------------------------------------------------------------===//
776 // Formal Arguments Calling Convention Implementation
777 //===----------------------------------------------------------------------===//
779 /// XCore formal arguments implementation
781 XCoreTargetLowering::LowerFormalArguments(SDValue Chain,
782 CallingConv::ID CallConv,
784 const SmallVectorImpl<ISD::InputArg> &Ins,
787 SmallVectorImpl<SDValue> &InVals) {
791 llvm_unreachable("Unsupported calling convention");
793 case CallingConv::Fast:
794 return LowerCCCArguments(Chain, CallConv, isVarArg,
795 Ins, dl, DAG, InVals);
799 /// LowerCCCArguments - transform physical registers into
800 /// virtual registers and generate load operations for
801 /// arguments places on the stack.
804 XCoreTargetLowering::LowerCCCArguments(SDValue Chain,
805 CallingConv::ID CallConv,
807 const SmallVectorImpl<ISD::InputArg>
811 SmallVectorImpl<SDValue> &InVals) {
812 MachineFunction &MF = DAG.getMachineFunction();
813 MachineFrameInfo *MFI = MF.getFrameInfo();
814 MachineRegisterInfo &RegInfo = MF.getRegInfo();
816 // Assign locations to all of the incoming arguments.
817 SmallVector<CCValAssign, 16> ArgLocs;
818 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
819 ArgLocs, *DAG.getContext());
821 CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
823 unsigned StackSlotSize = XCoreFrameInfo::stackSlotSize();
825 unsigned LRSaveSize = StackSlotSize;
827 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
829 CCValAssign &VA = ArgLocs[i];
832 // Arguments passed in registers
833 EVT RegVT = VA.getLocVT();
834 switch (RegVT.getSimpleVT().SimpleTy) {
838 errs() << "LowerFormalArguments Unhandled argument type: "
839 << RegVT.getSimpleVT().SimpleTy << "\n";
844 unsigned VReg = RegInfo.createVirtualRegister(
845 XCore::GRRegsRegisterClass);
846 RegInfo.addLiveIn(VA.getLocReg(), VReg);
847 InVals.push_back(DAG.getCopyFromReg(Chain, dl, VReg, RegVT));
851 assert(VA.isMemLoc());
852 // Load the argument to a virtual register
853 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
854 if (ObjSize > StackSlotSize) {
855 errs() << "LowerFormalArguments Unhandled argument type: "
856 << (unsigned)VA.getLocVT().getSimpleVT().SimpleTy
859 // Create the frame index object for this incoming parameter...
860 int FI = MFI->CreateFixedObject(ObjSize,
861 LRSaveSize + VA.getLocMemOffset());
863 // Create the SelectionDAG nodes corresponding to a load
864 //from this parameter
865 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
866 InVals.push_back(DAG.getLoad(VA.getLocVT(), dl, Chain, FIN, NULL, 0));
871 /* Argument registers */
872 static const unsigned ArgRegs[] = {
873 XCore::R0, XCore::R1, XCore::R2, XCore::R3
875 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
876 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
877 array_lengthof(ArgRegs));
878 if (FirstVAReg < array_lengthof(ArgRegs)) {
879 SmallVector<SDValue, 4> MemOps;
881 // Save remaining registers, storing higher register numbers at a higher
883 for (unsigned i = array_lengthof(ArgRegs) - 1; i >= FirstVAReg; --i) {
884 // Create a stack slot
885 int FI = MFI->CreateFixedObject(4, offset);
886 if (i == FirstVAReg) {
887 XFI->setVarArgsFrameIndex(FI);
889 offset -= StackSlotSize;
890 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
891 // Move argument from phys reg -> virt reg
892 unsigned VReg = RegInfo.createVirtualRegister(
893 XCore::GRRegsRegisterClass);
894 RegInfo.addLiveIn(ArgRegs[i], VReg);
895 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
896 // Move argument from virt reg -> stack
897 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
898 MemOps.push_back(Store);
901 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
902 &MemOps[0], MemOps.size());
904 // This will point to the next argument passed via stack.
905 XFI->setVarArgsFrameIndex(
906 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset()));
913 //===----------------------------------------------------------------------===//
914 // Return Value Calling Convention Implementation
915 //===----------------------------------------------------------------------===//
918 XCoreTargetLowering::LowerReturn(SDValue Chain,
919 CallingConv::ID CallConv, bool isVarArg,
920 const SmallVectorImpl<ISD::OutputArg> &Outs,
921 DebugLoc dl, SelectionDAG &DAG) {
923 // CCValAssign - represent the assignment of
924 // the return value to a location
925 SmallVector<CCValAssign, 16> RVLocs;
927 // CCState - Info about the registers and stack slot.
928 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
929 RVLocs, *DAG.getContext());
931 // Analize return values.
932 CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
934 // If this is the first return lowered for this function, add
935 // the regs to the liveout set for the function.
936 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
937 for (unsigned i = 0; i != RVLocs.size(); ++i)
938 if (RVLocs[i].isRegLoc())
939 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
944 // Copy the result values into the output registers.
945 for (unsigned i = 0; i != RVLocs.size(); ++i) {
946 CCValAssign &VA = RVLocs[i];
947 assert(VA.isRegLoc() && "Can only return in registers!");
949 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
952 // guarantee that all emitted copies are
953 // stuck together, avoiding something bad
954 Flag = Chain.getValue(1);
957 // Return on XCore is always a "retsp 0"
959 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
960 Chain, DAG.getConstant(0, MVT::i32), Flag);
962 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
963 Chain, DAG.getConstant(0, MVT::i32));
966 //===----------------------------------------------------------------------===//
967 // Other Lowering Code
968 //===----------------------------------------------------------------------===//
971 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
972 MachineBasicBlock *BB,
973 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
974 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
975 DebugLoc dl = MI->getDebugLoc();
976 assert((MI->getOpcode() == XCore::SELECT_CC) &&
977 "Unexpected instr type to insert");
979 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
980 // control-flow pattern. The incoming instruction knows the destination vreg
981 // to set, the condition code register to branch on, the true/false values to
982 // select between, and a branch opcode to use.
983 const BasicBlock *LLVM_BB = BB->getBasicBlock();
984 MachineFunction::iterator It = BB;
992 // fallthrough --> copy0MBB
993 MachineBasicBlock *thisMBB = BB;
994 MachineFunction *F = BB->getParent();
995 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
996 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
997 BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
998 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
999 F->insert(It, copy0MBB);
1000 F->insert(It, sinkMBB);
1001 // Update machine-CFG edges by first adding all successors of the current
1002 // block to the new block which will contain the Phi node for the select.
1003 // Also inform sdisel of the edge changes.
1004 for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
1005 E = BB->succ_end(); I != E; ++I) {
1006 EM->insert(std::make_pair(*I, sinkMBB));
1007 sinkMBB->addSuccessor(*I);
1009 // Next, remove all successors of the current block, and add the true
1010 // and fallthrough blocks as its successors.
1011 while (!BB->succ_empty())
1012 BB->removeSuccessor(BB->succ_begin());
1013 // Next, add the true and fallthrough blocks as its successors.
1014 BB->addSuccessor(copy0MBB);
1015 BB->addSuccessor(sinkMBB);
1018 // %FalseValue = ...
1019 // # fallthrough to sinkMBB
1022 // Update machine-CFG edges
1023 BB->addSuccessor(sinkMBB);
1026 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1029 BuildMI(BB, dl, TII.get(XCore::PHI), MI->getOperand(0).getReg())
1030 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1031 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1033 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
1037 //===----------------------------------------------------------------------===//
1038 // Target Optimization Hooks
1039 //===----------------------------------------------------------------------===//
1041 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1042 DAGCombinerInfo &DCI) const {
1043 SelectionDAG &DAG = DCI.DAG;
1044 DebugLoc dl = N->getDebugLoc();
1045 switch (N->getOpcode()) {
1048 // Replace unaligned store of unaligned load with memmove.
1049 StoreSDNode *ST = cast<StoreSDNode>(N);
1050 if (!DCI.isBeforeLegalize() ||
1051 allowsUnalignedMemoryAccesses(ST->getMemoryVT()) ||
1052 ST->isVolatile() || ST->isIndexed()) {
1055 SDValue Chain = ST->getChain();
1057 unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1058 if (StoreBits % 8) {
1061 unsigned ABIAlignment = getTargetData()->getABITypeAlignment(
1062 ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1063 unsigned Alignment = ST->getAlignment();
1064 if (Alignment >= ABIAlignment) {
1068 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1069 if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1070 LD->getAlignment() == Alignment &&
1071 !LD->isVolatile() && !LD->isIndexed() &&
1072 Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1073 return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1075 DAG.getConstant(StoreBits/8, MVT::i32),
1076 Alignment, ST->getSrcValue(),
1077 ST->getSrcValueOffset(), LD->getSrcValue(),
1078 LD->getSrcValueOffset());
1087 //===----------------------------------------------------------------------===//
1088 // Addressing mode description hooks
1089 //===----------------------------------------------------------------------===//
1091 static inline bool isImmUs(int64_t val)
1093 return (val >= 0 && val <= 11);
1096 static inline bool isImmUs2(int64_t val)
1098 return (val%2 == 0 && isImmUs(val/2));
1101 static inline bool isImmUs4(int64_t val)
1103 return (val%4 == 0 && isImmUs(val/4));
1106 /// isLegalAddressingMode - Return true if the addressing mode represented
1107 /// by AM is legal for this target, for a load/store of the specified type.
1109 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1110 const Type *Ty) const {
1111 // Be conservative with void
1112 // FIXME: Can we be more aggressive?
1113 if (Ty->getTypeID() == Type::VoidTyID)
1116 const TargetData *TD = TM.getTargetData();
1117 unsigned Size = TD->getTypeAllocSize(Ty);
1119 return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1126 if (AM.Scale == 0) {
1127 return isImmUs(AM.BaseOffs);
1130 return AM.Scale == 1 && AM.BaseOffs == 0;
1134 if (AM.Scale == 0) {
1135 return isImmUs2(AM.BaseOffs);
1138 return AM.Scale == 2 && AM.BaseOffs == 0;
1141 if (AM.Scale == 0) {
1142 return isImmUs4(AM.BaseOffs);
1145 return AM.Scale == 4 && AM.BaseOffs == 0;
1151 //===----------------------------------------------------------------------===//
1152 // XCore Inline Assembly Support
1153 //===----------------------------------------------------------------------===//
1155 std::vector<unsigned> XCoreTargetLowering::
1156 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1159 if (Constraint.size() != 1)
1160 return std::vector<unsigned>();
1162 switch (Constraint[0]) {
1165 return make_vector<unsigned>(XCore::R0, XCore::R1, XCore::R2,
1166 XCore::R3, XCore::R4, XCore::R5,
1167 XCore::R6, XCore::R7, XCore::R8,
1168 XCore::R9, XCore::R10, XCore::R11, 0);
1171 return std::vector<unsigned>();