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/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/SelectionDAGISel.h"
35 #include "llvm/CodeGen/ValueTypes.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/ADT/VectorExtras.h"
44 const char *XCoreTargetLowering::
45 getTargetNodeName(unsigned Opcode) const
49 case XCoreISD::BL : return "XCoreISD::BL";
50 case XCoreISD::PCRelativeWrapper : return "XCoreISD::PCRelativeWrapper";
51 case XCoreISD::DPRelativeWrapper : return "XCoreISD::DPRelativeWrapper";
52 case XCoreISD::CPRelativeWrapper : return "XCoreISD::CPRelativeWrapper";
53 case XCoreISD::STWSP : return "XCoreISD::STWSP";
54 case XCoreISD::RETSP : return "XCoreISD::RETSP";
55 case XCoreISD::LADD : return "XCoreISD::LADD";
56 case XCoreISD::LSUB : return "XCoreISD::LSUB";
57 case XCoreISD::LMUL : return "XCoreISD::LMUL";
58 case XCoreISD::MACCU : return "XCoreISD::MACCU";
59 case XCoreISD::MACCS : return "XCoreISD::MACCS";
60 case XCoreISD::BR_JT : return "XCoreISD::BR_JT";
61 case XCoreISD::BR_JT32 : return "XCoreISD::BR_JT32";
62 default : return NULL;
66 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
67 : TargetLowering(XTM, new XCoreTargetObjectFile()),
69 Subtarget(*XTM.getSubtargetImpl()) {
71 // Set up the register classes.
72 addRegisterClass(MVT::i32, XCore::GRRegsRegisterClass);
74 // Compute derived properties from the register classes
75 computeRegisterProperties();
77 // Division is expensive
78 setIntDivIsCheap(false);
80 setShiftAmountType(MVT::i32);
81 setStackPointerRegisterToSaveRestore(XCore::SP);
83 setSchedulingPreference(Sched::RegPressure);
85 // Use i32 for setcc operations results (slt, sgt, ...).
86 setBooleanContents(ZeroOrOneBooleanContent);
88 // XCore does not have the NodeTypes below.
89 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
90 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
91 setOperationAction(ISD::ADDC, MVT::i32, Expand);
92 setOperationAction(ISD::ADDE, MVT::i32, Expand);
93 setOperationAction(ISD::SUBC, MVT::i32, Expand);
94 setOperationAction(ISD::SUBE, MVT::i32, Expand);
96 // Stop the combiner recombining select and set_cc
97 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
100 setOperationAction(ISD::ADD, MVT::i64, Custom);
101 setOperationAction(ISD::SUB, MVT::i64, Custom);
102 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
103 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
104 setOperationAction(ISD::MULHS, MVT::i32, Expand);
105 setOperationAction(ISD::MULHU, MVT::i32, Expand);
106 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
107 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
108 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
111 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
112 setOperationAction(ISD::ROTL , MVT::i32, Expand);
113 setOperationAction(ISD::ROTR , MVT::i32, Expand);
115 setOperationAction(ISD::TRAP, MVT::Other, Legal);
118 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
120 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
121 setOperationAction(ISD::BlockAddress, MVT::i32 , Custom);
123 // Thread Local Storage
124 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
126 // Conversion of i64 -> double produces constantpool nodes
127 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
130 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
131 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
132 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
134 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
135 setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
137 // Custom expand misaligned loads / stores.
138 setOperationAction(ISD::LOAD, MVT::i32, Custom);
139 setOperationAction(ISD::STORE, MVT::i32, Custom);
142 setOperationAction(ISD::VAEND, MVT::Other, Expand);
143 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
144 setOperationAction(ISD::VAARG, MVT::Other, Custom);
145 setOperationAction(ISD::VASTART, MVT::Other, Custom);
148 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
149 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
150 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
152 maxStoresPerMemset = 4;
153 maxStoresPerMemmove = maxStoresPerMemcpy = 2;
155 // We have target-specific dag combine patterns for the following nodes:
156 setTargetDAGCombine(ISD::STORE);
157 setTargetDAGCombine(ISD::ADD);
160 SDValue XCoreTargetLowering::
161 LowerOperation(SDValue Op, SelectionDAG &DAG) const {
162 switch (Op.getOpcode())
164 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
165 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
166 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
167 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
168 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
169 case ISD::LOAD: return LowerLOAD(Op, DAG);
170 case ISD::STORE: return LowerSTORE(Op, DAG);
171 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
172 case ISD::VAARG: return LowerVAARG(Op, DAG);
173 case ISD::VASTART: return LowerVASTART(Op, DAG);
174 case ISD::SMUL_LOHI: return LowerSMUL_LOHI(Op, DAG);
175 case ISD::UMUL_LOHI: return LowerUMUL_LOHI(Op, DAG);
176 // FIXME: Remove these when LegalizeDAGTypes lands.
178 case ISD::SUB: return ExpandADDSUB(Op.getNode(), DAG);
179 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
181 llvm_unreachable("unimplemented operand");
186 /// ReplaceNodeResults - Replace the results of node with an illegal result
187 /// type with new values built out of custom code.
188 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
189 SmallVectorImpl<SDValue>&Results,
190 SelectionDAG &DAG) const {
191 switch (N->getOpcode()) {
193 llvm_unreachable("Don't know how to custom expand this!");
197 Results.push_back(ExpandADDSUB(N, DAG));
202 /// getFunctionAlignment - Return the Log2 alignment of this function.
203 unsigned XCoreTargetLowering::
204 getFunctionAlignment(const Function *) const {
208 //===----------------------------------------------------------------------===//
209 // Misc Lower Operation implementation
210 //===----------------------------------------------------------------------===//
212 SDValue XCoreTargetLowering::
213 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
215 DebugLoc dl = Op.getDebugLoc();
216 SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i32, Op.getOperand(2),
217 Op.getOperand(3), Op.getOperand(4));
218 return DAG.getNode(ISD::SELECT, dl, MVT::i32, Cond, Op.getOperand(0),
222 SDValue XCoreTargetLowering::
223 getGlobalAddressWrapper(SDValue GA, const GlobalValue *GV,
224 SelectionDAG &DAG) const
226 // FIXME there is no actual debug info here
227 DebugLoc dl = GA.getDebugLoc();
228 if (isa<Function>(GV)) {
229 return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
231 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
233 // If GV is an alias then use the aliasee to determine constness
234 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
235 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
237 bool isConst = GVar && GVar->isConstant();
239 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
241 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
244 SDValue XCoreTargetLowering::
245 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const
247 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
248 SDValue GA = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(), MVT::i32);
249 // If it's a debug information descriptor, don't mess with it.
250 if (DAG.isVerifiedDebugInfoDesc(Op))
252 return getGlobalAddressWrapper(GA, GV, DAG);
255 static inline SDValue BuildGetId(SelectionDAG &DAG, DebugLoc dl) {
256 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
257 DAG.getConstant(Intrinsic::xcore_getid, MVT::i32));
260 static inline bool isZeroLengthArray(const Type *Ty) {
261 const ArrayType *AT = dyn_cast_or_null<ArrayType>(Ty);
262 return AT && (AT->getNumElements() == 0);
265 SDValue XCoreTargetLowering::
266 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
268 // FIXME there isn't really debug info here
269 DebugLoc dl = Op.getDebugLoc();
270 // transform to label + getid() * size
271 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
272 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32);
273 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
275 // If GV is an alias then use the aliasee to determine size
276 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
277 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
280 llvm_unreachable("Thread local object not a GlobalVariable?");
283 const Type *Ty = cast<PointerType>(GV->getType())->getElementType();
284 if (!Ty->isSized() || isZeroLengthArray(Ty)) {
286 errs() << "Size of thread local object " << GVar->getName()
291 SDValue base = getGlobalAddressWrapper(GA, GV, DAG);
292 const TargetData *TD = TM.getTargetData();
293 unsigned Size = TD->getTypeAllocSize(Ty);
294 SDValue offset = DAG.getNode(ISD::MUL, dl, MVT::i32, BuildGetId(DAG, dl),
295 DAG.getConstant(Size, MVT::i32));
296 return DAG.getNode(ISD::ADD, dl, MVT::i32, base, offset);
299 SDValue XCoreTargetLowering::
300 LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const
302 DebugLoc DL = Op.getDebugLoc();
304 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
305 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(), /*isTarget=*/true);
307 return DAG.getNode(XCoreISD::PCRelativeWrapper, DL, getPointerTy(), Result);
310 SDValue XCoreTargetLowering::
311 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
313 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
314 // FIXME there isn't really debug info here
315 DebugLoc dl = CP->getDebugLoc();
316 EVT PtrVT = Op.getValueType();
318 if (CP->isMachineConstantPoolEntry()) {
319 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
322 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
325 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
328 unsigned XCoreTargetLowering::getJumpTableEncoding() const {
329 return MachineJumpTableInfo::EK_Inline;
332 SDValue XCoreTargetLowering::
333 LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
335 SDValue Chain = Op.getOperand(0);
336 SDValue Table = Op.getOperand(1);
337 SDValue Index = Op.getOperand(2);
338 DebugLoc dl = Op.getDebugLoc();
339 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
340 unsigned JTI = JT->getIndex();
341 MachineFunction &MF = DAG.getMachineFunction();
342 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
343 SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
345 unsigned NumEntries = MJTI->getJumpTables()[JTI].MBBs.size();
346 if (NumEntries <= 32) {
347 return DAG.getNode(XCoreISD::BR_JT, dl, MVT::Other, Chain, TargetJT, Index);
349 assert((NumEntries >> 31) == 0);
350 SDValue ScaledIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
351 DAG.getConstant(1, MVT::i32));
352 return DAG.getNode(XCoreISD::BR_JT32, dl, MVT::Other, Chain, TargetJT,
357 IsWordAlignedBasePlusConstantOffset(SDValue Addr, SDValue &AlignedBase,
360 if (Addr.getOpcode() != ISD::ADD) {
363 ConstantSDNode *CN = 0;
364 if (!(CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
367 int64_t off = CN->getSExtValue();
368 const SDValue &Base = Addr.getOperand(0);
369 const SDValue *Root = &Base;
370 if (Base.getOpcode() == ISD::ADD &&
371 Base.getOperand(1).getOpcode() == ISD::SHL) {
372 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Base.getOperand(1)
374 if (CN && (CN->getSExtValue() >= 2)) {
375 Root = &Base.getOperand(0);
378 if (isa<FrameIndexSDNode>(*Root)) {
379 // All frame indicies are word aligned
384 if (Root->getOpcode() == XCoreISD::DPRelativeWrapper ||
385 Root->getOpcode() == XCoreISD::CPRelativeWrapper) {
386 // All dp / cp relative addresses are word aligned
394 SDValue XCoreTargetLowering::
395 LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
396 LoadSDNode *LD = cast<LoadSDNode>(Op);
397 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
398 "Unexpected extension type");
399 assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
400 if (allowsUnalignedMemoryAccesses(LD->getMemoryVT()))
403 unsigned ABIAlignment = getTargetData()->
404 getABITypeAlignment(LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
405 // Leave aligned load alone.
406 if (LD->getAlignment() >= ABIAlignment)
409 SDValue Chain = LD->getChain();
410 SDValue BasePtr = LD->getBasePtr();
411 DebugLoc DL = Op.getDebugLoc();
415 if (!LD->isVolatile() &&
416 IsWordAlignedBasePlusConstantOffset(BasePtr, Base, Offset)) {
417 if (Offset % 4 == 0) {
418 // We've managed to infer better alignment information than the load
419 // already has. Use an aligned load.
421 return DAG.getLoad(getPointerTy(), DL, Chain, BasePtr,
422 MachinePointerInfo(),
426 // ldw low, base[offset >> 2]
427 // ldw high, base[(offset >> 2) + 1]
428 // shr low_shifted, low, (offset & 0x3) * 8
429 // shl high_shifted, high, 32 - (offset & 0x3) * 8
430 // or result, low_shifted, high_shifted
431 SDValue LowOffset = DAG.getConstant(Offset & ~0x3, MVT::i32);
432 SDValue HighOffset = DAG.getConstant((Offset & ~0x3) + 4, MVT::i32);
433 SDValue LowShift = DAG.getConstant((Offset & 0x3) * 8, MVT::i32);
434 SDValue HighShift = DAG.getConstant(32 - (Offset & 0x3) * 8, MVT::i32);
436 SDValue LowAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base, LowOffset);
437 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base, HighOffset);
439 SDValue Low = DAG.getLoad(getPointerTy(), DL, Chain,
440 LowAddr, MachinePointerInfo(), false, false, 0);
441 SDValue High = DAG.getLoad(getPointerTy(), DL, Chain,
442 HighAddr, MachinePointerInfo(), false, false, 0);
443 SDValue LowShifted = DAG.getNode(ISD::SRL, DL, MVT::i32, Low, LowShift);
444 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High, HighShift);
445 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, LowShifted, HighShifted);
446 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
448 SDValue Ops[] = { Result, Chain };
449 return DAG.getMergeValues(Ops, 2, DL);
452 if (LD->getAlignment() == 2) {
453 SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, MVT::i32, DL, Chain,
454 BasePtr, LD->getPointerInfo(), MVT::i16,
455 LD->isVolatile(), LD->isNonTemporal(), 2);
456 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
457 DAG.getConstant(2, MVT::i32));
458 SDValue High = DAG.getExtLoad(ISD::EXTLOAD, MVT::i32, DL, Chain,
460 LD->getPointerInfo().getWithOffset(2),
461 MVT::i16, LD->isVolatile(),
462 LD->isNonTemporal(), 2);
463 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High,
464 DAG.getConstant(16, MVT::i32));
465 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Low, HighShifted);
466 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
468 SDValue Ops[] = { Result, Chain };
469 return DAG.getMergeValues(Ops, 2, DL);
472 // Lower to a call to __misaligned_load(BasePtr).
473 const Type *IntPtrTy = getTargetData()->getIntPtrType(*DAG.getContext());
474 TargetLowering::ArgListTy Args;
475 TargetLowering::ArgListEntry Entry;
478 Entry.Node = BasePtr;
479 Args.push_back(Entry);
481 std::pair<SDValue, SDValue> CallResult =
482 LowerCallTo(Chain, IntPtrTy, false, false,
483 false, false, 0, CallingConv::C, false,
484 /*isReturnValueUsed=*/true,
485 DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
489 { CallResult.first, CallResult.second };
491 return DAG.getMergeValues(Ops, 2, DL);
494 SDValue XCoreTargetLowering::
495 LowerSTORE(SDValue Op, SelectionDAG &DAG) const
497 StoreSDNode *ST = cast<StoreSDNode>(Op);
498 assert(!ST->isTruncatingStore() && "Unexpected store type");
499 assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
500 if (allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
503 unsigned ABIAlignment = getTargetData()->
504 getABITypeAlignment(ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
505 // Leave aligned store alone.
506 if (ST->getAlignment() >= ABIAlignment) {
509 SDValue Chain = ST->getChain();
510 SDValue BasePtr = ST->getBasePtr();
511 SDValue Value = ST->getValue();
512 DebugLoc dl = Op.getDebugLoc();
514 if (ST->getAlignment() == 2) {
516 SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
517 DAG.getConstant(16, MVT::i32));
518 SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
519 ST->getPointerInfo(), MVT::i16,
520 ST->isVolatile(), ST->isNonTemporal(),
522 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
523 DAG.getConstant(2, MVT::i32));
524 SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
525 ST->getPointerInfo().getWithOffset(2),
526 MVT::i16, ST->isVolatile(),
527 ST->isNonTemporal(), 2);
528 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
531 // Lower to a call to __misaligned_store(BasePtr, Value).
532 const Type *IntPtrTy = getTargetData()->getIntPtrType(*DAG.getContext());
533 TargetLowering::ArgListTy Args;
534 TargetLowering::ArgListEntry Entry;
537 Entry.Node = BasePtr;
538 Args.push_back(Entry);
541 Args.push_back(Entry);
543 std::pair<SDValue, SDValue> CallResult =
544 LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()), false, false,
545 false, false, 0, CallingConv::C, false,
546 /*isReturnValueUsed=*/true,
547 DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
550 return CallResult.second;
553 SDValue XCoreTargetLowering::
554 LowerSMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
556 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::SMUL_LOHI &&
557 "Unexpected operand to lower!");
558 DebugLoc dl = Op.getDebugLoc();
559 SDValue LHS = Op.getOperand(0);
560 SDValue RHS = Op.getOperand(1);
561 SDValue Zero = DAG.getConstant(0, MVT::i32);
562 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
563 DAG.getVTList(MVT::i32, MVT::i32), Zero, Zero,
565 SDValue Lo(Hi.getNode(), 1);
566 SDValue Ops[] = { Lo, Hi };
567 return DAG.getMergeValues(Ops, 2, dl);
570 SDValue XCoreTargetLowering::
571 LowerUMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
573 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::UMUL_LOHI &&
574 "Unexpected operand to lower!");
575 DebugLoc dl = Op.getDebugLoc();
576 SDValue LHS = Op.getOperand(0);
577 SDValue RHS = Op.getOperand(1);
578 SDValue Zero = DAG.getConstant(0, MVT::i32);
579 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
580 DAG.getVTList(MVT::i32, MVT::i32), LHS, RHS,
582 SDValue Lo(Hi.getNode(), 1);
583 SDValue Ops[] = { Lo, Hi };
584 return DAG.getMergeValues(Ops, 2, dl);
587 /// isADDADDMUL - Return whether Op is in a form that is equivalent to
588 /// add(add(mul(x,y),a),b). If requireIntermediatesHaveOneUse is true then
589 /// each intermediate result in the calculation must also have a single use.
590 /// If the Op is in the correct form the constituent parts are written to Mul0,
591 /// Mul1, Addend0 and Addend1.
593 isADDADDMUL(SDValue Op, SDValue &Mul0, SDValue &Mul1, SDValue &Addend0,
594 SDValue &Addend1, bool requireIntermediatesHaveOneUse)
596 if (Op.getOpcode() != ISD::ADD)
598 SDValue N0 = Op.getOperand(0);
599 SDValue N1 = Op.getOperand(1);
602 if (N0.getOpcode() == ISD::ADD) {
605 } else if (N1.getOpcode() == ISD::ADD) {
611 if (requireIntermediatesHaveOneUse && !AddOp.hasOneUse())
613 if (OtherOp.getOpcode() == ISD::MUL) {
614 // add(add(a,b),mul(x,y))
615 if (requireIntermediatesHaveOneUse && !OtherOp.hasOneUse())
617 Mul0 = OtherOp.getOperand(0);
618 Mul1 = OtherOp.getOperand(1);
619 Addend0 = AddOp.getOperand(0);
620 Addend1 = AddOp.getOperand(1);
623 if (AddOp.getOperand(0).getOpcode() == ISD::MUL) {
624 // add(add(mul(x,y),a),b)
625 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(0).hasOneUse())
627 Mul0 = AddOp.getOperand(0).getOperand(0);
628 Mul1 = AddOp.getOperand(0).getOperand(1);
629 Addend0 = AddOp.getOperand(1);
633 if (AddOp.getOperand(1).getOpcode() == ISD::MUL) {
634 // add(add(a,mul(x,y)),b)
635 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(1).hasOneUse())
637 Mul0 = AddOp.getOperand(1).getOperand(0);
638 Mul1 = AddOp.getOperand(1).getOperand(1);
639 Addend0 = AddOp.getOperand(0);
646 SDValue XCoreTargetLowering::
647 TryExpandADDWithMul(SDNode *N, SelectionDAG &DAG) const
651 if (N->getOperand(0).getOpcode() == ISD::MUL) {
652 Mul = N->getOperand(0);
653 Other = N->getOperand(1);
654 } else if (N->getOperand(1).getOpcode() == ISD::MUL) {
655 Mul = N->getOperand(1);
656 Other = N->getOperand(0);
660 DebugLoc dl = N->getDebugLoc();
661 SDValue LL, RL, AddendL, AddendH;
662 LL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
663 Mul.getOperand(0), DAG.getConstant(0, MVT::i32));
664 RL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
665 Mul.getOperand(1), DAG.getConstant(0, MVT::i32));
666 AddendL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
667 Other, DAG.getConstant(0, MVT::i32));
668 AddendH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
669 Other, DAG.getConstant(1, MVT::i32));
670 APInt HighMask = APInt::getHighBitsSet(64, 32);
671 unsigned LHSSB = DAG.ComputeNumSignBits(Mul.getOperand(0));
672 unsigned RHSSB = DAG.ComputeNumSignBits(Mul.getOperand(1));
673 if (DAG.MaskedValueIsZero(Mul.getOperand(0), HighMask) &&
674 DAG.MaskedValueIsZero(Mul.getOperand(1), HighMask)) {
675 // The inputs are both zero-extended.
676 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
677 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
679 SDValue Lo(Hi.getNode(), 1);
680 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
682 if (LHSSB > 32 && RHSSB > 32) {
683 // The inputs are both sign-extended.
684 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
685 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
687 SDValue Lo(Hi.getNode(), 1);
688 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
691 LH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
692 Mul.getOperand(0), DAG.getConstant(1, MVT::i32));
693 RH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
694 Mul.getOperand(1), DAG.getConstant(1, MVT::i32));
695 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
696 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
698 SDValue Lo(Hi.getNode(), 1);
699 RH = DAG.getNode(ISD::MUL, dl, MVT::i32, LL, RH);
700 LH = DAG.getNode(ISD::MUL, dl, MVT::i32, LH, RL);
701 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, RH);
702 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, LH);
703 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
706 SDValue XCoreTargetLowering::
707 ExpandADDSUB(SDNode *N, SelectionDAG &DAG) const
709 assert(N->getValueType(0) == MVT::i64 &&
710 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
711 "Unknown operand to lower!");
713 if (N->getOpcode() == ISD::ADD) {
714 SDValue Result = TryExpandADDWithMul(N, DAG);
715 if (Result.getNode() != 0)
719 DebugLoc dl = N->getDebugLoc();
721 // Extract components
722 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
723 N->getOperand(0), DAG.getConstant(0, MVT::i32));
724 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
725 N->getOperand(0), DAG.getConstant(1, MVT::i32));
726 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
727 N->getOperand(1), DAG.getConstant(0, MVT::i32));
728 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
729 N->getOperand(1), DAG.getConstant(1, MVT::i32));
732 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
734 SDValue Zero = DAG.getConstant(0, MVT::i32);
735 SDValue Carry = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
737 SDValue Lo(Carry.getNode(), 1);
739 SDValue Ignored = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
741 SDValue Hi(Ignored.getNode(), 1);
743 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
746 SDValue XCoreTargetLowering::
747 LowerVAARG(SDValue Op, SelectionDAG &DAG) const
749 llvm_unreachable("unimplemented");
750 // FIX Arguments passed by reference need a extra dereference.
751 SDNode *Node = Op.getNode();
752 DebugLoc dl = Node->getDebugLoc();
753 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
754 EVT VT = Node->getValueType(0);
755 SDValue VAList = DAG.getLoad(getPointerTy(), dl, Node->getOperand(0),
756 Node->getOperand(1), MachinePointerInfo(V),
758 // Increment the pointer, VAList, to the next vararg
759 SDValue Tmp3 = DAG.getNode(ISD::ADD, dl, getPointerTy(), VAList,
760 DAG.getConstant(VT.getSizeInBits(),
762 // Store the incremented VAList to the legalized pointer
763 Tmp3 = DAG.getStore(VAList.getValue(1), dl, Tmp3, Node->getOperand(1),
764 MachinePointerInfo(V), false, false, 0);
765 // Load the actual argument out of the pointer VAList
766 return DAG.getLoad(VT, dl, Tmp3, VAList, MachinePointerInfo(),
770 SDValue XCoreTargetLowering::
771 LowerVASTART(SDValue Op, SelectionDAG &DAG) const
773 DebugLoc dl = Op.getDebugLoc();
774 // vastart stores the address of the VarArgsFrameIndex slot into the
775 // memory location argument
776 MachineFunction &MF = DAG.getMachineFunction();
777 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
778 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
779 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1),
780 MachinePointerInfo(), false, false, 0);
783 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op,
784 SelectionDAG &DAG) const {
785 DebugLoc dl = Op.getDebugLoc();
786 // Depths > 0 not supported yet!
787 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
790 MachineFunction &MF = DAG.getMachineFunction();
791 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
792 return DAG.getCopyFromReg(DAG.getEntryNode(), dl,
793 RegInfo->getFrameRegister(MF), MVT::i32);
796 //===----------------------------------------------------------------------===//
797 // Calling Convention Implementation
798 //===----------------------------------------------------------------------===//
800 #include "XCoreGenCallingConv.inc"
802 //===----------------------------------------------------------------------===//
803 // Call Calling Convention Implementation
804 //===----------------------------------------------------------------------===//
806 /// XCore call implementation
808 XCoreTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
809 CallingConv::ID CallConv, bool isVarArg,
811 const SmallVectorImpl<ISD::OutputArg> &Outs,
812 const SmallVectorImpl<SDValue> &OutVals,
813 const SmallVectorImpl<ISD::InputArg> &Ins,
814 DebugLoc dl, SelectionDAG &DAG,
815 SmallVectorImpl<SDValue> &InVals) const {
816 // XCore target does not yet support tail call optimization.
819 // For now, only CallingConv::C implemented
823 llvm_unreachable("Unsupported calling convention");
824 case CallingConv::Fast:
826 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
827 Outs, OutVals, Ins, dl, DAG, InVals);
831 /// LowerCCCCallTo - functions arguments are copied from virtual
832 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
833 /// CALLSEQ_END are emitted.
834 /// TODO: isTailCall, sret.
836 XCoreTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
837 CallingConv::ID CallConv, bool isVarArg,
839 const SmallVectorImpl<ISD::OutputArg> &Outs,
840 const SmallVectorImpl<SDValue> &OutVals,
841 const SmallVectorImpl<ISD::InputArg> &Ins,
842 DebugLoc dl, SelectionDAG &DAG,
843 SmallVectorImpl<SDValue> &InVals) const {
845 // Analyze operands of the call, assigning locations to each operand.
846 SmallVector<CCValAssign, 16> ArgLocs;
847 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
848 ArgLocs, *DAG.getContext());
850 // The ABI dictates there should be one stack slot available to the callee
851 // on function entry (for saving lr).
852 CCInfo.AllocateStack(4, 4);
854 CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
856 // Get a count of how many bytes are to be pushed on the stack.
857 unsigned NumBytes = CCInfo.getNextStackOffset();
859 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
860 getPointerTy(), true));
862 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
863 SmallVector<SDValue, 12> MemOpChains;
865 // Walk the register/memloc assignments, inserting copies/loads.
866 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
867 CCValAssign &VA = ArgLocs[i];
868 SDValue Arg = OutVals[i];
870 // Promote the value if needed.
871 switch (VA.getLocInfo()) {
872 default: llvm_unreachable("Unknown loc info!");
873 case CCValAssign::Full: break;
874 case CCValAssign::SExt:
875 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
877 case CCValAssign::ZExt:
878 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
880 case CCValAssign::AExt:
881 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
885 // Arguments that can be passed on register must be kept at
888 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
890 assert(VA.isMemLoc());
892 int Offset = VA.getLocMemOffset();
894 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
896 DAG.getConstant(Offset/4, MVT::i32)));
900 // Transform all store nodes into one single node because
901 // all store nodes are independent of each other.
902 if (!MemOpChains.empty())
903 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
904 &MemOpChains[0], MemOpChains.size());
906 // Build a sequence of copy-to-reg nodes chained together with token
907 // chain and flag operands which copy the outgoing args into registers.
908 // The InFlag in necessary since all emited instructions must be
911 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
912 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
913 RegsToPass[i].second, InFlag);
914 InFlag = Chain.getValue(1);
917 // If the callee is a GlobalAddress node (quite common, every direct call is)
918 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
919 // Likewise ExternalSymbol -> TargetExternalSymbol.
920 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
921 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
922 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
923 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
925 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
926 // = Chain, Callee, Reg#1, Reg#2, ...
928 // Returns a chain & a flag for retval copy to use.
929 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
930 SmallVector<SDValue, 8> Ops;
931 Ops.push_back(Chain);
932 Ops.push_back(Callee);
934 // Add argument registers to the end of the list so that they are
935 // known live into the call.
936 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
937 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
938 RegsToPass[i].second.getValueType()));
940 if (InFlag.getNode())
941 Ops.push_back(InFlag);
943 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, &Ops[0], Ops.size());
944 InFlag = Chain.getValue(1);
946 // Create the CALLSEQ_END node.
947 Chain = DAG.getCALLSEQ_END(Chain,
948 DAG.getConstant(NumBytes, getPointerTy(), true),
949 DAG.getConstant(0, getPointerTy(), true),
951 InFlag = Chain.getValue(1);
953 // Handle result values, copying them out of physregs into vregs that we
955 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
956 Ins, dl, DAG, InVals);
959 /// LowerCallResult - Lower the result values of a call into the
960 /// appropriate copies out of appropriate physical registers.
962 XCoreTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
963 CallingConv::ID CallConv, bool isVarArg,
964 const SmallVectorImpl<ISD::InputArg> &Ins,
965 DebugLoc dl, SelectionDAG &DAG,
966 SmallVectorImpl<SDValue> &InVals) const {
968 // Assign locations to each value returned by this call.
969 SmallVector<CCValAssign, 16> RVLocs;
970 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
971 RVLocs, *DAG.getContext());
973 CCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
975 // Copy all of the result registers out of their specified physreg.
976 for (unsigned i = 0; i != RVLocs.size(); ++i) {
977 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
978 RVLocs[i].getValVT(), InFlag).getValue(1);
979 InFlag = Chain.getValue(2);
980 InVals.push_back(Chain.getValue(0));
986 //===----------------------------------------------------------------------===//
987 // Formal Arguments Calling Convention Implementation
988 //===----------------------------------------------------------------------===//
990 /// XCore formal arguments implementation
992 XCoreTargetLowering::LowerFormalArguments(SDValue Chain,
993 CallingConv::ID CallConv,
995 const SmallVectorImpl<ISD::InputArg> &Ins,
998 SmallVectorImpl<SDValue> &InVals)
1003 llvm_unreachable("Unsupported calling convention");
1004 case CallingConv::C:
1005 case CallingConv::Fast:
1006 return LowerCCCArguments(Chain, CallConv, isVarArg,
1007 Ins, dl, DAG, InVals);
1011 /// LowerCCCArguments - transform physical registers into
1012 /// virtual registers and generate load operations for
1013 /// arguments places on the stack.
1016 XCoreTargetLowering::LowerCCCArguments(SDValue Chain,
1017 CallingConv::ID CallConv,
1019 const SmallVectorImpl<ISD::InputArg>
1023 SmallVectorImpl<SDValue> &InVals) const {
1024 MachineFunction &MF = DAG.getMachineFunction();
1025 MachineFrameInfo *MFI = MF.getFrameInfo();
1026 MachineRegisterInfo &RegInfo = MF.getRegInfo();
1028 // Assign locations to all of the incoming arguments.
1029 SmallVector<CCValAssign, 16> ArgLocs;
1030 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1031 ArgLocs, *DAG.getContext());
1033 CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
1035 unsigned StackSlotSize = XCoreFrameInfo::stackSlotSize();
1037 unsigned LRSaveSize = StackSlotSize;
1039 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1041 CCValAssign &VA = ArgLocs[i];
1043 if (VA.isRegLoc()) {
1044 // Arguments passed in registers
1045 EVT RegVT = VA.getLocVT();
1046 switch (RegVT.getSimpleVT().SimpleTy) {
1050 errs() << "LowerFormalArguments Unhandled argument type: "
1051 << RegVT.getSimpleVT().SimpleTy << "\n";
1053 llvm_unreachable(0);
1056 unsigned VReg = RegInfo.createVirtualRegister(
1057 XCore::GRRegsRegisterClass);
1058 RegInfo.addLiveIn(VA.getLocReg(), VReg);
1059 InVals.push_back(DAG.getCopyFromReg(Chain, dl, VReg, RegVT));
1063 assert(VA.isMemLoc());
1064 // Load the argument to a virtual register
1065 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
1066 if (ObjSize > StackSlotSize) {
1067 errs() << "LowerFormalArguments Unhandled argument type: "
1068 << EVT(VA.getLocVT()).getEVTString()
1071 // Create the frame index object for this incoming parameter...
1072 int FI = MFI->CreateFixedObject(ObjSize,
1073 LRSaveSize + VA.getLocMemOffset(),
1076 // Create the SelectionDAG nodes corresponding to a load
1077 //from this parameter
1078 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1079 InVals.push_back(DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
1080 MachinePointerInfo::getFixedStack(FI),
1086 /* Argument registers */
1087 static const unsigned ArgRegs[] = {
1088 XCore::R0, XCore::R1, XCore::R2, XCore::R3
1090 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1091 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
1092 array_lengthof(ArgRegs));
1093 if (FirstVAReg < array_lengthof(ArgRegs)) {
1094 SmallVector<SDValue, 4> MemOps;
1096 // Save remaining registers, storing higher register numbers at a higher
1098 for (unsigned i = array_lengthof(ArgRegs) - 1; i >= FirstVAReg; --i) {
1099 // Create a stack slot
1100 int FI = MFI->CreateFixedObject(4, offset, true);
1101 if (i == FirstVAReg) {
1102 XFI->setVarArgsFrameIndex(FI);
1104 offset -= StackSlotSize;
1105 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1106 // Move argument from phys reg -> virt reg
1107 unsigned VReg = RegInfo.createVirtualRegister(
1108 XCore::GRRegsRegisterClass);
1109 RegInfo.addLiveIn(ArgRegs[i], VReg);
1110 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1111 // Move argument from virt reg -> stack
1112 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
1113 MachinePointerInfo(), false, false, 0);
1114 MemOps.push_back(Store);
1116 if (!MemOps.empty())
1117 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1118 &MemOps[0], MemOps.size());
1120 // This will point to the next argument passed via stack.
1121 XFI->setVarArgsFrameIndex(
1122 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset(),
1130 //===----------------------------------------------------------------------===//
1131 // Return Value Calling Convention Implementation
1132 //===----------------------------------------------------------------------===//
1134 bool XCoreTargetLowering::
1135 CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1136 const SmallVectorImpl<ISD::OutputArg> &Outs,
1137 LLVMContext &Context) const {
1138 SmallVector<CCValAssign, 16> RVLocs;
1139 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1141 return CCInfo.CheckReturn(Outs, RetCC_XCore);
1145 XCoreTargetLowering::LowerReturn(SDValue Chain,
1146 CallingConv::ID CallConv, bool isVarArg,
1147 const SmallVectorImpl<ISD::OutputArg> &Outs,
1148 const SmallVectorImpl<SDValue> &OutVals,
1149 DebugLoc dl, SelectionDAG &DAG) const {
1151 // CCValAssign - represent the assignment of
1152 // the return value to a location
1153 SmallVector<CCValAssign, 16> RVLocs;
1155 // CCState - Info about the registers and stack slot.
1156 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1157 RVLocs, *DAG.getContext());
1159 // Analize return values.
1160 CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
1162 // If this is the first return lowered for this function, add
1163 // the regs to the liveout set for the function.
1164 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1165 for (unsigned i = 0; i != RVLocs.size(); ++i)
1166 if (RVLocs[i].isRegLoc())
1167 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1172 // Copy the result values into the output registers.
1173 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1174 CCValAssign &VA = RVLocs[i];
1175 assert(VA.isRegLoc() && "Can only return in registers!");
1177 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1180 // guarantee that all emitted copies are
1181 // stuck together, avoiding something bad
1182 Flag = Chain.getValue(1);
1185 // Return on XCore is always a "retsp 0"
1187 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
1188 Chain, DAG.getConstant(0, MVT::i32), Flag);
1190 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
1191 Chain, DAG.getConstant(0, MVT::i32));
1194 //===----------------------------------------------------------------------===//
1195 // Other Lowering Code
1196 //===----------------------------------------------------------------------===//
1199 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1200 MachineBasicBlock *BB) const {
1201 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1202 DebugLoc dl = MI->getDebugLoc();
1203 assert((MI->getOpcode() == XCore::SELECT_CC) &&
1204 "Unexpected instr type to insert");
1206 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1207 // control-flow pattern. The incoming instruction knows the destination vreg
1208 // to set, the condition code register to branch on, the true/false values to
1209 // select between, and a branch opcode to use.
1210 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1211 MachineFunction::iterator It = BB;
1217 // cmpTY ccX, r1, r2
1219 // fallthrough --> copy0MBB
1220 MachineBasicBlock *thisMBB = BB;
1221 MachineFunction *F = BB->getParent();
1222 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1223 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1224 F->insert(It, copy0MBB);
1225 F->insert(It, sinkMBB);
1227 // Transfer the remainder of BB and its successor edges to sinkMBB.
1228 sinkMBB->splice(sinkMBB->begin(), BB,
1229 llvm::next(MachineBasicBlock::iterator(MI)),
1231 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1233 // Next, add the true and fallthrough blocks as its successors.
1234 BB->addSuccessor(copy0MBB);
1235 BB->addSuccessor(sinkMBB);
1237 BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1238 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1241 // %FalseValue = ...
1242 // # fallthrough to sinkMBB
1245 // Update machine-CFG edges
1246 BB->addSuccessor(sinkMBB);
1249 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1252 BuildMI(*BB, BB->begin(), dl,
1253 TII.get(XCore::PHI), MI->getOperand(0).getReg())
1254 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1255 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1257 MI->eraseFromParent(); // The pseudo instruction is gone now.
1261 //===----------------------------------------------------------------------===//
1262 // Target Optimization Hooks
1263 //===----------------------------------------------------------------------===//
1265 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1266 DAGCombinerInfo &DCI) const {
1267 SelectionDAG &DAG = DCI.DAG;
1268 DebugLoc dl = N->getDebugLoc();
1269 switch (N->getOpcode()) {
1271 case XCoreISD::LADD: {
1272 SDValue N0 = N->getOperand(0);
1273 SDValue N1 = N->getOperand(1);
1274 SDValue N2 = N->getOperand(2);
1275 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1276 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1277 EVT VT = N0.getValueType();
1279 // canonicalize constant to RHS
1281 return DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N1, N0, N2);
1283 // fold (ladd 0, 0, x) -> 0, x & 1
1284 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1285 SDValue Carry = DAG.getConstant(0, VT);
1286 SDValue Result = DAG.getNode(ISD::AND, dl, VT, N2,
1287 DAG.getConstant(1, VT));
1288 SDValue Ops [] = { Carry, Result };
1289 return DAG.getMergeValues(Ops, 2, dl);
1292 // fold (ladd x, 0, y) -> 0, add x, y iff carry is unused and y has only the
1294 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 0)) {
1295 APInt KnownZero, KnownOne;
1296 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1297 VT.getSizeInBits() - 1);
1298 DAG.ComputeMaskedBits(N2, Mask, KnownZero, KnownOne);
1299 if (KnownZero == Mask) {
1300 SDValue Carry = DAG.getConstant(0, VT);
1301 SDValue Result = DAG.getNode(ISD::ADD, dl, VT, N0, N2);
1302 SDValue Ops [] = { Carry, Result };
1303 return DAG.getMergeValues(Ops, 2, dl);
1308 case XCoreISD::LSUB: {
1309 SDValue N0 = N->getOperand(0);
1310 SDValue N1 = N->getOperand(1);
1311 SDValue N2 = N->getOperand(2);
1312 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1313 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1314 EVT VT = N0.getValueType();
1316 // fold (lsub 0, 0, x) -> x, -x iff x has only the low bit set
1317 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1318 APInt KnownZero, KnownOne;
1319 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1320 VT.getSizeInBits() - 1);
1321 DAG.ComputeMaskedBits(N2, Mask, KnownZero, KnownOne);
1322 if (KnownZero == Mask) {
1323 SDValue Borrow = N2;
1324 SDValue Result = DAG.getNode(ISD::SUB, dl, VT,
1325 DAG.getConstant(0, VT), N2);
1326 SDValue Ops [] = { Borrow, Result };
1327 return DAG.getMergeValues(Ops, 2, dl);
1331 // fold (lsub x, 0, y) -> 0, sub x, y iff borrow is unused and y has only the
1333 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 0)) {
1334 APInt KnownZero, KnownOne;
1335 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1336 VT.getSizeInBits() - 1);
1337 DAG.ComputeMaskedBits(N2, Mask, KnownZero, KnownOne);
1338 if (KnownZero == Mask) {
1339 SDValue Borrow = DAG.getConstant(0, VT);
1340 SDValue Result = DAG.getNode(ISD::SUB, dl, VT, N0, N2);
1341 SDValue Ops [] = { Borrow, Result };
1342 return DAG.getMergeValues(Ops, 2, dl);
1347 case XCoreISD::LMUL: {
1348 SDValue N0 = N->getOperand(0);
1349 SDValue N1 = N->getOperand(1);
1350 SDValue N2 = N->getOperand(2);
1351 SDValue N3 = N->getOperand(3);
1352 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1353 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1354 EVT VT = N0.getValueType();
1355 // Canonicalize multiplicative constant to RHS. If both multiplicative
1356 // operands are constant canonicalize smallest to RHS.
1357 if ((N0C && !N1C) ||
1358 (N0C && N1C && N0C->getZExtValue() < N1C->getZExtValue()))
1359 return DAG.getNode(XCoreISD::LMUL, dl, DAG.getVTList(VT, VT), N1, N0, N2, N3);
1362 if (N1C && N1C->isNullValue()) {
1363 // If the high result is unused fold to add(a, b)
1364 if (N->hasNUsesOfValue(0, 0)) {
1365 SDValue Lo = DAG.getNode(ISD::ADD, dl, VT, N2, N3);
1366 SDValue Ops [] = { Lo, Lo };
1367 return DAG.getMergeValues(Ops, 2, dl);
1369 // Otherwise fold to ladd(a, b, 0)
1370 return DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N2, N3, N1);
1375 // Fold 32 bit expressions such as add(add(mul(x,y),a),b) ->
1376 // lmul(x, y, a, b). The high result of lmul will be ignored.
1377 // This is only profitable if the intermediate results are unused
1379 SDValue Mul0, Mul1, Addend0, Addend1;
1380 if (N->getValueType(0) == MVT::i32 &&
1381 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, true)) {
1382 SDValue Ignored = DAG.getNode(XCoreISD::LMUL, dl,
1383 DAG.getVTList(MVT::i32, MVT::i32), Mul0,
1384 Mul1, Addend0, Addend1);
1385 SDValue Result(Ignored.getNode(), 1);
1388 APInt HighMask = APInt::getHighBitsSet(64, 32);
1389 // Fold 64 bit expression such as add(add(mul(x,y),a),b) ->
1390 // lmul(x, y, a, b) if all operands are zero-extended. We do this
1391 // before type legalization as it is messy to match the operands after
1393 if (N->getValueType(0) == MVT::i64 &&
1394 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, false) &&
1395 DAG.MaskedValueIsZero(Mul0, HighMask) &&
1396 DAG.MaskedValueIsZero(Mul1, HighMask) &&
1397 DAG.MaskedValueIsZero(Addend0, HighMask) &&
1398 DAG.MaskedValueIsZero(Addend1, HighMask)) {
1399 SDValue Mul0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1400 Mul0, DAG.getConstant(0, MVT::i32));
1401 SDValue Mul1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1402 Mul1, DAG.getConstant(0, MVT::i32));
1403 SDValue Addend0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1404 Addend0, DAG.getConstant(0, MVT::i32));
1405 SDValue Addend1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1406 Addend1, DAG.getConstant(0, MVT::i32));
1407 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
1408 DAG.getVTList(MVT::i32, MVT::i32), Mul0L, Mul1L,
1409 Addend0L, Addend1L);
1410 SDValue Lo(Hi.getNode(), 1);
1411 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
1416 // Replace unaligned store of unaligned load with memmove.
1417 StoreSDNode *ST = cast<StoreSDNode>(N);
1418 if (!DCI.isBeforeLegalize() ||
1419 allowsUnalignedMemoryAccesses(ST->getMemoryVT()) ||
1420 ST->isVolatile() || ST->isIndexed()) {
1423 SDValue Chain = ST->getChain();
1425 unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1426 if (StoreBits % 8) {
1429 unsigned ABIAlignment = getTargetData()->getABITypeAlignment(
1430 ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1431 unsigned Alignment = ST->getAlignment();
1432 if (Alignment >= ABIAlignment) {
1436 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1437 if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1438 LD->getAlignment() == Alignment &&
1439 !LD->isVolatile() && !LD->isIndexed() &&
1440 Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1441 return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1443 DAG.getConstant(StoreBits/8, MVT::i32),
1444 Alignment, false, ST->getPointerInfo(),
1445 LD->getPointerInfo());
1454 void XCoreTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
1458 const SelectionDAG &DAG,
1459 unsigned Depth) const {
1460 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
1461 switch (Op.getOpcode()) {
1463 case XCoreISD::LADD:
1464 case XCoreISD::LSUB:
1465 if (Op.getResNo() == 0) {
1466 // Top bits of carry / borrow are clear.
1467 KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
1468 Mask.getBitWidth() - 1);
1475 //===----------------------------------------------------------------------===//
1476 // Addressing mode description hooks
1477 //===----------------------------------------------------------------------===//
1479 static inline bool isImmUs(int64_t val)
1481 return (val >= 0 && val <= 11);
1484 static inline bool isImmUs2(int64_t val)
1486 return (val%2 == 0 && isImmUs(val/2));
1489 static inline bool isImmUs4(int64_t val)
1491 return (val%4 == 0 && isImmUs(val/4));
1494 /// isLegalAddressingMode - Return true if the addressing mode represented
1495 /// by AM is legal for this target, for a load/store of the specified type.
1497 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1498 const Type *Ty) const {
1499 if (Ty->getTypeID() == Type::VoidTyID)
1500 return AM.Scale == 0 && isImmUs(AM.BaseOffs) && isImmUs4(AM.BaseOffs);
1502 const TargetData *TD = TM.getTargetData();
1503 unsigned Size = TD->getTypeAllocSize(Ty);
1505 return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1512 if (AM.Scale == 0) {
1513 return isImmUs(AM.BaseOffs);
1516 return AM.Scale == 1 && AM.BaseOffs == 0;
1520 if (AM.Scale == 0) {
1521 return isImmUs2(AM.BaseOffs);
1524 return AM.Scale == 2 && AM.BaseOffs == 0;
1527 if (AM.Scale == 0) {
1528 return isImmUs4(AM.BaseOffs);
1531 return AM.Scale == 4 && AM.BaseOffs == 0;
1537 //===----------------------------------------------------------------------===//
1538 // XCore Inline Assembly Support
1539 //===----------------------------------------------------------------------===//
1541 std::vector<unsigned> XCoreTargetLowering::
1542 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1545 if (Constraint.size() != 1)
1546 return std::vector<unsigned>();
1548 switch (Constraint[0]) {
1551 return make_vector<unsigned>(XCore::R0, XCore::R1, XCore::R2,
1552 XCore::R3, XCore::R4, XCore::R5,
1553 XCore::R6, XCore::R7, XCore::R8,
1554 XCore::R9, XCore::R10, XCore::R11, 0);
1557 return std::vector<unsigned>();