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"
18 #include "XCoreMachineFunctionInfo.h"
19 #include "XCoreSubtarget.h"
20 #include "XCoreTargetMachine.h"
21 #include "XCoreTargetObjectFile.h"
22 #include "llvm/CodeGen/CallingConvLower.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineJumpTableInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/SelectionDAGISel.h"
29 #include "llvm/CodeGen/ValueTypes.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/GlobalAlias.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/raw_ostream.h"
41 const char *XCoreTargetLowering::
42 getTargetNodeName(unsigned Opcode) const
46 case XCoreISD::BL : return "XCoreISD::BL";
47 case XCoreISD::PCRelativeWrapper : return "XCoreISD::PCRelativeWrapper";
48 case XCoreISD::DPRelativeWrapper : return "XCoreISD::DPRelativeWrapper";
49 case XCoreISD::CPRelativeWrapper : return "XCoreISD::CPRelativeWrapper";
50 case XCoreISD::STWSP : return "XCoreISD::STWSP";
51 case XCoreISD::RETSP : return "XCoreISD::RETSP";
52 case XCoreISD::LADD : return "XCoreISD::LADD";
53 case XCoreISD::LSUB : return "XCoreISD::LSUB";
54 case XCoreISD::LMUL : return "XCoreISD::LMUL";
55 case XCoreISD::MACCU : return "XCoreISD::MACCU";
56 case XCoreISD::MACCS : return "XCoreISD::MACCS";
57 case XCoreISD::CRC8 : return "XCoreISD::CRC8";
58 case XCoreISD::BR_JT : return "XCoreISD::BR_JT";
59 case XCoreISD::BR_JT32 : return "XCoreISD::BR_JT32";
60 default : return NULL;
64 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
65 : TargetLowering(XTM, new XCoreTargetObjectFile()),
67 Subtarget(*XTM.getSubtargetImpl()) {
69 // Set up the register classes.
70 addRegisterClass(MVT::i32, &XCore::GRRegsRegClass);
72 // Compute derived properties from the register classes
73 computeRegisterProperties();
75 // Division is expensive
76 setIntDivIsCheap(false);
78 setStackPointerRegisterToSaveRestore(XCore::SP);
80 setSchedulingPreference(Sched::RegPressure);
82 // Use i32 for setcc operations results (slt, sgt, ...).
83 setBooleanContents(ZeroOrOneBooleanContent);
84 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
86 // XCore does not have the NodeTypes below.
87 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
88 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
89 setOperationAction(ISD::ADDC, MVT::i32, Expand);
90 setOperationAction(ISD::ADDE, MVT::i32, Expand);
91 setOperationAction(ISD::SUBC, MVT::i32, Expand);
92 setOperationAction(ISD::SUBE, MVT::i32, Expand);
94 // Stop the combiner recombining select and set_cc
95 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
98 setOperationAction(ISD::ADD, MVT::i64, Custom);
99 setOperationAction(ISD::SUB, MVT::i64, Custom);
100 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
101 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
102 setOperationAction(ISD::MULHS, MVT::i32, Expand);
103 setOperationAction(ISD::MULHU, MVT::i32, Expand);
104 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
105 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
106 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
109 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
110 setOperationAction(ISD::ROTL , MVT::i32, Expand);
111 setOperationAction(ISD::ROTR , MVT::i32, Expand);
112 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
113 setOperationAction(ISD::CTLZ_ZERO_UNDEF, 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 // TRAMPOLINE is custom lowered.
153 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
154 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
156 // We want to custom lower some of our intrinsics.
157 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
159 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 4;
160 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize
161 = MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 2;
163 // We have target-specific dag combine patterns for the following nodes:
164 setTargetDAGCombine(ISD::STORE);
165 setTargetDAGCombine(ISD::ADD);
167 setMinFunctionAlignment(1);
170 SDValue XCoreTargetLowering::
171 LowerOperation(SDValue Op, SelectionDAG &DAG) const {
172 switch (Op.getOpcode())
174 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
175 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
176 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
177 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
178 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
179 case ISD::LOAD: return LowerLOAD(Op, DAG);
180 case ISD::STORE: return LowerSTORE(Op, DAG);
181 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
182 case ISD::VAARG: return LowerVAARG(Op, DAG);
183 case ISD::VASTART: return LowerVASTART(Op, DAG);
184 case ISD::SMUL_LOHI: return LowerSMUL_LOHI(Op, DAG);
185 case ISD::UMUL_LOHI: return LowerUMUL_LOHI(Op, DAG);
186 // FIXME: Remove these when LegalizeDAGTypes lands.
188 case ISD::SUB: return ExpandADDSUB(Op.getNode(), DAG);
189 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
190 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
191 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
192 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
194 llvm_unreachable("unimplemented operand");
198 /// ReplaceNodeResults - Replace the results of node with an illegal result
199 /// type with new values built out of custom code.
200 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
201 SmallVectorImpl<SDValue>&Results,
202 SelectionDAG &DAG) const {
203 switch (N->getOpcode()) {
205 llvm_unreachable("Don't know how to custom expand this!");
208 Results.push_back(ExpandADDSUB(N, DAG));
213 //===----------------------------------------------------------------------===//
214 // Misc Lower Operation implementation
215 //===----------------------------------------------------------------------===//
217 SDValue XCoreTargetLowering::
218 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
220 DebugLoc dl = Op.getDebugLoc();
221 SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i32, Op.getOperand(2),
222 Op.getOperand(3), Op.getOperand(4));
223 return DAG.getNode(ISD::SELECT, dl, MVT::i32, Cond, Op.getOperand(0),
227 SDValue XCoreTargetLowering::
228 getGlobalAddressWrapper(SDValue GA, const GlobalValue *GV,
229 SelectionDAG &DAG) const
231 // FIXME there is no actual debug info here
232 DebugLoc dl = GA.getDebugLoc();
233 const GlobalValue *UnderlyingGV = GV;
234 // If GV is an alias then use the aliasee to determine the wrapper type
235 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
236 UnderlyingGV = GA->resolveAliasedGlobal();
237 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(UnderlyingGV)) {
238 if (GVar->isConstant())
239 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
240 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
242 return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
245 SDValue XCoreTargetLowering::
246 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const
248 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
249 SDValue GA = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(), MVT::i32);
250 return getGlobalAddressWrapper(GA, GV, DAG);
253 static inline SDValue BuildGetId(SelectionDAG &DAG, DebugLoc dl) {
254 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
255 DAG.getConstant(Intrinsic::xcore_getid, MVT::i32));
258 static inline bool isZeroLengthArray(Type *Ty) {
259 ArrayType *AT = dyn_cast_or_null<ArrayType>(Ty);
260 return AT && (AT->getNumElements() == 0);
263 SDValue XCoreTargetLowering::
264 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
266 // FIXME there isn't really debug info here
267 DebugLoc dl = Op.getDebugLoc();
268 // transform to label + getid() * size
269 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
270 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32);
271 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
273 // If GV is an alias then use the aliasee to determine size
274 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
275 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
278 llvm_unreachable("Thread local object not a GlobalVariable?");
280 Type *Ty = cast<PointerType>(GV->getType())->getElementType();
281 if (!Ty->isSized() || isZeroLengthArray(Ty)) {
283 errs() << "Size of thread local object " << GVar->getName()
288 SDValue base = getGlobalAddressWrapper(GA, GV, DAG);
289 const DataLayout *TD = TM.getDataLayout();
290 unsigned Size = TD->getTypeAllocSize(Ty);
291 SDValue offset = DAG.getNode(ISD::MUL, dl, MVT::i32, BuildGetId(DAG, dl),
292 DAG.getConstant(Size, MVT::i32));
293 return DAG.getNode(ISD::ADD, dl, MVT::i32, base, offset);
296 SDValue XCoreTargetLowering::
297 LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const
299 DebugLoc DL = Op.getDebugLoc();
301 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
302 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy());
304 return DAG.getNode(XCoreISD::PCRelativeWrapper, DL, getPointerTy(), Result);
307 SDValue XCoreTargetLowering::
308 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
310 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
311 // FIXME there isn't really debug info here
312 DebugLoc dl = CP->getDebugLoc();
313 EVT PtrVT = Op.getValueType();
315 if (CP->isMachineConstantPoolEntry()) {
316 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
319 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
322 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
325 unsigned XCoreTargetLowering::getJumpTableEncoding() const {
326 return MachineJumpTableInfo::EK_Inline;
329 SDValue XCoreTargetLowering::
330 LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
332 SDValue Chain = Op.getOperand(0);
333 SDValue Table = Op.getOperand(1);
334 SDValue Index = Op.getOperand(2);
335 DebugLoc dl = Op.getDebugLoc();
336 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
337 unsigned JTI = JT->getIndex();
338 MachineFunction &MF = DAG.getMachineFunction();
339 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
340 SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
342 unsigned NumEntries = MJTI->getJumpTables()[JTI].MBBs.size();
343 if (NumEntries <= 32) {
344 return DAG.getNode(XCoreISD::BR_JT, dl, MVT::Other, Chain, TargetJT, Index);
346 assert((NumEntries >> 31) == 0);
347 SDValue ScaledIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
348 DAG.getConstant(1, MVT::i32));
349 return DAG.getNode(XCoreISD::BR_JT32, dl, MVT::Other, Chain, TargetJT,
354 IsWordAlignedBasePlusConstantOffset(SDValue Addr, SDValue &AlignedBase,
357 if (Addr.getOpcode() != ISD::ADD) {
360 ConstantSDNode *CN = 0;
361 if (!(CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
364 int64_t off = CN->getSExtValue();
365 const SDValue &Base = Addr.getOperand(0);
366 const SDValue *Root = &Base;
367 if (Base.getOpcode() == ISD::ADD &&
368 Base.getOperand(1).getOpcode() == ISD::SHL) {
369 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Base.getOperand(1)
371 if (CN && (CN->getSExtValue() >= 2)) {
372 Root = &Base.getOperand(0);
375 if (isa<FrameIndexSDNode>(*Root)) {
376 // All frame indicies are word aligned
381 if (Root->getOpcode() == XCoreISD::DPRelativeWrapper ||
382 Root->getOpcode() == XCoreISD::CPRelativeWrapper) {
383 // All dp / cp relative addresses are word aligned
388 // Check for an aligned global variable.
389 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(*Root)) {
390 const GlobalValue *GV = GA->getGlobal();
391 if (GA->getOffset() == 0 && GV->getAlignment() >= 4) {
400 SDValue XCoreTargetLowering::
401 LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
402 LoadSDNode *LD = cast<LoadSDNode>(Op);
403 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
404 "Unexpected extension type");
405 assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
406 if (allowsUnalignedMemoryAccesses(LD->getMemoryVT()))
409 unsigned ABIAlignment = getDataLayout()->
410 getABITypeAlignment(LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
411 // Leave aligned load alone.
412 if (LD->getAlignment() >= ABIAlignment)
415 SDValue Chain = LD->getChain();
416 SDValue BasePtr = LD->getBasePtr();
417 DebugLoc DL = Op.getDebugLoc();
421 if (!LD->isVolatile() &&
422 IsWordAlignedBasePlusConstantOffset(BasePtr, Base, Offset)) {
423 if (Offset % 4 == 0) {
424 // We've managed to infer better alignment information than the load
425 // already has. Use an aligned load.
427 return DAG.getLoad(getPointerTy(), DL, Chain, BasePtr,
428 MachinePointerInfo(),
429 false, false, false, 0);
432 // ldw low, base[offset >> 2]
433 // ldw high, base[(offset >> 2) + 1]
434 // shr low_shifted, low, (offset & 0x3) * 8
435 // shl high_shifted, high, 32 - (offset & 0x3) * 8
436 // or result, low_shifted, high_shifted
437 SDValue LowOffset = DAG.getConstant(Offset & ~0x3, MVT::i32);
438 SDValue HighOffset = DAG.getConstant((Offset & ~0x3) + 4, MVT::i32);
439 SDValue LowShift = DAG.getConstant((Offset & 0x3) * 8, MVT::i32);
440 SDValue HighShift = DAG.getConstant(32 - (Offset & 0x3) * 8, MVT::i32);
442 SDValue LowAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base, LowOffset);
443 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base, HighOffset);
445 SDValue Low = DAG.getLoad(getPointerTy(), DL, Chain,
446 LowAddr, MachinePointerInfo(),
447 false, false, false, 0);
448 SDValue High = DAG.getLoad(getPointerTy(), DL, Chain,
449 HighAddr, MachinePointerInfo(),
450 false, false, false, 0);
451 SDValue LowShifted = DAG.getNode(ISD::SRL, DL, MVT::i32, Low, LowShift);
452 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High, HighShift);
453 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, LowShifted, HighShifted);
454 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
456 SDValue Ops[] = { Result, Chain };
457 return DAG.getMergeValues(Ops, 2, DL);
460 if (LD->getAlignment() == 2) {
461 SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, DL, MVT::i32, Chain,
462 BasePtr, LD->getPointerInfo(), MVT::i16,
463 LD->isVolatile(), LD->isNonTemporal(), 2);
464 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
465 DAG.getConstant(2, MVT::i32));
466 SDValue High = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
468 LD->getPointerInfo().getWithOffset(2),
469 MVT::i16, LD->isVolatile(),
470 LD->isNonTemporal(), 2);
471 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High,
472 DAG.getConstant(16, MVT::i32));
473 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Low, HighShifted);
474 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
476 SDValue Ops[] = { Result, Chain };
477 return DAG.getMergeValues(Ops, 2, DL);
480 // Lower to a call to __misaligned_load(BasePtr).
481 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
482 TargetLowering::ArgListTy Args;
483 TargetLowering::ArgListEntry Entry;
486 Entry.Node = BasePtr;
487 Args.push_back(Entry);
489 TargetLowering::CallLoweringInfo CLI(Chain, IntPtrTy, false, false,
490 false, false, 0, CallingConv::C, /*isTailCall=*/false,
491 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
492 DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
494 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
497 { CallResult.first, CallResult.second };
499 return DAG.getMergeValues(Ops, 2, DL);
502 SDValue XCoreTargetLowering::
503 LowerSTORE(SDValue Op, SelectionDAG &DAG) const
505 StoreSDNode *ST = cast<StoreSDNode>(Op);
506 assert(!ST->isTruncatingStore() && "Unexpected store type");
507 assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
508 if (allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
511 unsigned ABIAlignment = getDataLayout()->
512 getABITypeAlignment(ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
513 // Leave aligned store alone.
514 if (ST->getAlignment() >= ABIAlignment) {
517 SDValue Chain = ST->getChain();
518 SDValue BasePtr = ST->getBasePtr();
519 SDValue Value = ST->getValue();
520 DebugLoc dl = Op.getDebugLoc();
522 if (ST->getAlignment() == 2) {
524 SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
525 DAG.getConstant(16, MVT::i32));
526 SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
527 ST->getPointerInfo(), MVT::i16,
528 ST->isVolatile(), ST->isNonTemporal(),
530 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
531 DAG.getConstant(2, MVT::i32));
532 SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
533 ST->getPointerInfo().getWithOffset(2),
534 MVT::i16, ST->isVolatile(),
535 ST->isNonTemporal(), 2);
536 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
539 // Lower to a call to __misaligned_store(BasePtr, Value).
540 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
541 TargetLowering::ArgListTy Args;
542 TargetLowering::ArgListEntry Entry;
545 Entry.Node = BasePtr;
546 Args.push_back(Entry);
549 Args.push_back(Entry);
551 TargetLowering::CallLoweringInfo CLI(Chain,
552 Type::getVoidTy(*DAG.getContext()), false, false,
553 false, false, 0, CallingConv::C, /*isTailCall=*/false,
554 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
555 DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
557 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
559 return CallResult.second;
562 SDValue XCoreTargetLowering::
563 LowerSMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
565 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::SMUL_LOHI &&
566 "Unexpected operand to lower!");
567 DebugLoc dl = Op.getDebugLoc();
568 SDValue LHS = Op.getOperand(0);
569 SDValue RHS = Op.getOperand(1);
570 SDValue Zero = DAG.getConstant(0, MVT::i32);
571 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
572 DAG.getVTList(MVT::i32, MVT::i32), Zero, Zero,
574 SDValue Lo(Hi.getNode(), 1);
575 SDValue Ops[] = { Lo, Hi };
576 return DAG.getMergeValues(Ops, 2, dl);
579 SDValue XCoreTargetLowering::
580 LowerUMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
582 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::UMUL_LOHI &&
583 "Unexpected operand to lower!");
584 DebugLoc dl = Op.getDebugLoc();
585 SDValue LHS = Op.getOperand(0);
586 SDValue RHS = Op.getOperand(1);
587 SDValue Zero = DAG.getConstant(0, MVT::i32);
588 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
589 DAG.getVTList(MVT::i32, MVT::i32), LHS, RHS,
591 SDValue Lo(Hi.getNode(), 1);
592 SDValue Ops[] = { Lo, Hi };
593 return DAG.getMergeValues(Ops, 2, dl);
596 /// isADDADDMUL - Return whether Op is in a form that is equivalent to
597 /// add(add(mul(x,y),a),b). If requireIntermediatesHaveOneUse is true then
598 /// each intermediate result in the calculation must also have a single use.
599 /// If the Op is in the correct form the constituent parts are written to Mul0,
600 /// Mul1, Addend0 and Addend1.
602 isADDADDMUL(SDValue Op, SDValue &Mul0, SDValue &Mul1, SDValue &Addend0,
603 SDValue &Addend1, bool requireIntermediatesHaveOneUse)
605 if (Op.getOpcode() != ISD::ADD)
607 SDValue N0 = Op.getOperand(0);
608 SDValue N1 = Op.getOperand(1);
611 if (N0.getOpcode() == ISD::ADD) {
614 } else if (N1.getOpcode() == ISD::ADD) {
620 if (requireIntermediatesHaveOneUse && !AddOp.hasOneUse())
622 if (OtherOp.getOpcode() == ISD::MUL) {
623 // add(add(a,b),mul(x,y))
624 if (requireIntermediatesHaveOneUse && !OtherOp.hasOneUse())
626 Mul0 = OtherOp.getOperand(0);
627 Mul1 = OtherOp.getOperand(1);
628 Addend0 = AddOp.getOperand(0);
629 Addend1 = AddOp.getOperand(1);
632 if (AddOp.getOperand(0).getOpcode() == ISD::MUL) {
633 // add(add(mul(x,y),a),b)
634 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(0).hasOneUse())
636 Mul0 = AddOp.getOperand(0).getOperand(0);
637 Mul1 = AddOp.getOperand(0).getOperand(1);
638 Addend0 = AddOp.getOperand(1);
642 if (AddOp.getOperand(1).getOpcode() == ISD::MUL) {
643 // add(add(a,mul(x,y)),b)
644 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(1).hasOneUse())
646 Mul0 = AddOp.getOperand(1).getOperand(0);
647 Mul1 = AddOp.getOperand(1).getOperand(1);
648 Addend0 = AddOp.getOperand(0);
655 SDValue XCoreTargetLowering::
656 TryExpandADDWithMul(SDNode *N, SelectionDAG &DAG) const
660 if (N->getOperand(0).getOpcode() == ISD::MUL) {
661 Mul = N->getOperand(0);
662 Other = N->getOperand(1);
663 } else if (N->getOperand(1).getOpcode() == ISD::MUL) {
664 Mul = N->getOperand(1);
665 Other = N->getOperand(0);
669 DebugLoc dl = N->getDebugLoc();
670 SDValue LL, RL, AddendL, AddendH;
671 LL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
672 Mul.getOperand(0), DAG.getConstant(0, MVT::i32));
673 RL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
674 Mul.getOperand(1), DAG.getConstant(0, MVT::i32));
675 AddendL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
676 Other, DAG.getConstant(0, MVT::i32));
677 AddendH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
678 Other, DAG.getConstant(1, MVT::i32));
679 APInt HighMask = APInt::getHighBitsSet(64, 32);
680 unsigned LHSSB = DAG.ComputeNumSignBits(Mul.getOperand(0));
681 unsigned RHSSB = DAG.ComputeNumSignBits(Mul.getOperand(1));
682 if (DAG.MaskedValueIsZero(Mul.getOperand(0), HighMask) &&
683 DAG.MaskedValueIsZero(Mul.getOperand(1), HighMask)) {
684 // The inputs are both zero-extended.
685 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
686 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
688 SDValue Lo(Hi.getNode(), 1);
689 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
691 if (LHSSB > 32 && RHSSB > 32) {
692 // The inputs are both sign-extended.
693 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
694 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
696 SDValue Lo(Hi.getNode(), 1);
697 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
700 LH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
701 Mul.getOperand(0), DAG.getConstant(1, MVT::i32));
702 RH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
703 Mul.getOperand(1), DAG.getConstant(1, MVT::i32));
704 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
705 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
707 SDValue Lo(Hi.getNode(), 1);
708 RH = DAG.getNode(ISD::MUL, dl, MVT::i32, LL, RH);
709 LH = DAG.getNode(ISD::MUL, dl, MVT::i32, LH, RL);
710 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, RH);
711 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, LH);
712 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
715 SDValue XCoreTargetLowering::
716 ExpandADDSUB(SDNode *N, SelectionDAG &DAG) const
718 assert(N->getValueType(0) == MVT::i64 &&
719 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
720 "Unknown operand to lower!");
722 if (N->getOpcode() == ISD::ADD) {
723 SDValue Result = TryExpandADDWithMul(N, DAG);
724 if (Result.getNode() != 0)
728 DebugLoc dl = N->getDebugLoc();
730 // Extract components
731 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
732 N->getOperand(0), DAG.getConstant(0, MVT::i32));
733 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
734 N->getOperand(0), DAG.getConstant(1, MVT::i32));
735 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
736 N->getOperand(1), DAG.getConstant(0, MVT::i32));
737 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
738 N->getOperand(1), DAG.getConstant(1, MVT::i32));
741 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
743 SDValue Zero = DAG.getConstant(0, MVT::i32);
744 SDValue Lo = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
746 SDValue Carry(Lo.getNode(), 1);
748 SDValue Hi = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
750 SDValue Ignored(Hi.getNode(), 1);
752 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
755 SDValue XCoreTargetLowering::
756 LowerVAARG(SDValue Op, SelectionDAG &DAG) const
758 llvm_unreachable("unimplemented");
759 // FIXME Arguments passed by reference need a extra dereference.
760 SDNode *Node = Op.getNode();
761 DebugLoc dl = Node->getDebugLoc();
762 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
763 EVT VT = Node->getValueType(0);
764 SDValue VAList = DAG.getLoad(getPointerTy(), dl, Node->getOperand(0),
765 Node->getOperand(1), MachinePointerInfo(V),
766 false, false, false, 0);
767 // Increment the pointer, VAList, to the next vararg
768 SDValue Tmp3 = DAG.getNode(ISD::ADD, dl, getPointerTy(), VAList,
769 DAG.getConstant(VT.getSizeInBits(),
771 // Store the incremented VAList to the legalized pointer
772 Tmp3 = DAG.getStore(VAList.getValue(1), dl, Tmp3, Node->getOperand(1),
773 MachinePointerInfo(V), false, false, 0);
774 // Load the actual argument out of the pointer VAList
775 return DAG.getLoad(VT, dl, Tmp3, VAList, MachinePointerInfo(),
776 false, false, false, 0);
779 SDValue XCoreTargetLowering::
780 LowerVASTART(SDValue Op, SelectionDAG &DAG) const
782 DebugLoc dl = Op.getDebugLoc();
783 // vastart stores the address of the VarArgsFrameIndex slot into the
784 // memory location argument
785 MachineFunction &MF = DAG.getMachineFunction();
786 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
787 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
788 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1),
789 MachinePointerInfo(), false, false, 0);
792 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op,
793 SelectionDAG &DAG) const {
794 DebugLoc dl = Op.getDebugLoc();
795 // Depths > 0 not supported yet!
796 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
799 MachineFunction &MF = DAG.getMachineFunction();
800 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
801 return DAG.getCopyFromReg(DAG.getEntryNode(), dl,
802 RegInfo->getFrameRegister(MF), MVT::i32);
805 SDValue XCoreTargetLowering::
806 LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
807 return Op.getOperand(0);
810 SDValue XCoreTargetLowering::
811 LowerINIT_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
812 SDValue Chain = Op.getOperand(0);
813 SDValue Trmp = Op.getOperand(1); // trampoline
814 SDValue FPtr = Op.getOperand(2); // nested function
815 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
817 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
820 // LDAPF_u10 r11, nest
821 // LDW_2rus r11, r11[0]
822 // STWSP_ru6 r11, sp[0]
823 // LDAPF_u10 r11, fptr
824 // LDW_2rus r11, r11[0]
830 SDValue OutChains[5];
834 DebugLoc dl = Op.getDebugLoc();
835 OutChains[0] = DAG.getStore(Chain, dl, DAG.getConstant(0x0a3cd805, MVT::i32),
836 Addr, MachinePointerInfo(TrmpAddr), false, false,
839 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
840 DAG.getConstant(4, MVT::i32));
841 OutChains[1] = DAG.getStore(Chain, dl, DAG.getConstant(0xd80456c0, MVT::i32),
842 Addr, MachinePointerInfo(TrmpAddr, 4), false,
845 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
846 DAG.getConstant(8, MVT::i32));
847 OutChains[2] = DAG.getStore(Chain, dl, DAG.getConstant(0x27fb0a3c, MVT::i32),
848 Addr, MachinePointerInfo(TrmpAddr, 8), false,
851 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
852 DAG.getConstant(12, MVT::i32));
853 OutChains[3] = DAG.getStore(Chain, dl, Nest, Addr,
854 MachinePointerInfo(TrmpAddr, 12), false, false,
857 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
858 DAG.getConstant(16, MVT::i32));
859 OutChains[4] = DAG.getStore(Chain, dl, FPtr, Addr,
860 MachinePointerInfo(TrmpAddr, 16), false, false,
863 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 5);
866 SDValue XCoreTargetLowering::
867 LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
868 DebugLoc DL = Op.getDebugLoc();
869 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
871 case Intrinsic::xcore_crc8:
872 EVT VT = Op.getValueType();
874 DAG.getNode(XCoreISD::CRC8, DL, DAG.getVTList(VT, VT),
875 Op.getOperand(1), Op.getOperand(2) , Op.getOperand(3));
876 SDValue Crc(Data.getNode(), 1);
877 SDValue Results[] = { Crc, Data };
878 return DAG.getMergeValues(Results, 2, DL);
883 //===----------------------------------------------------------------------===//
884 // Calling Convention Implementation
885 //===----------------------------------------------------------------------===//
887 #include "XCoreGenCallingConv.inc"
889 //===----------------------------------------------------------------------===//
890 // Call Calling Convention Implementation
891 //===----------------------------------------------------------------------===//
893 /// XCore call implementation
895 XCoreTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
896 SmallVectorImpl<SDValue> &InVals) const {
897 SelectionDAG &DAG = CLI.DAG;
898 DebugLoc &dl = CLI.DL;
899 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
900 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
901 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
902 SDValue Chain = CLI.Chain;
903 SDValue Callee = CLI.Callee;
904 bool &isTailCall = CLI.IsTailCall;
905 CallingConv::ID CallConv = CLI.CallConv;
906 bool isVarArg = CLI.IsVarArg;
908 // XCore target does not yet support tail call optimization.
911 // For now, only CallingConv::C implemented
915 llvm_unreachable("Unsupported calling convention");
916 case CallingConv::Fast:
918 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
919 Outs, OutVals, Ins, dl, DAG, InVals);
923 /// LowerCCCCallTo - functions arguments are copied from virtual
924 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
925 /// CALLSEQ_END are emitted.
926 /// TODO: isTailCall, sret.
928 XCoreTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
929 CallingConv::ID CallConv, bool isVarArg,
931 const SmallVectorImpl<ISD::OutputArg> &Outs,
932 const SmallVectorImpl<SDValue> &OutVals,
933 const SmallVectorImpl<ISD::InputArg> &Ins,
934 DebugLoc dl, SelectionDAG &DAG,
935 SmallVectorImpl<SDValue> &InVals) const {
937 // Analyze operands of the call, assigning locations to each operand.
938 SmallVector<CCValAssign, 16> ArgLocs;
939 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
940 getTargetMachine(), ArgLocs, *DAG.getContext());
942 // The ABI dictates there should be one stack slot available to the callee
943 // on function entry (for saving lr).
944 CCInfo.AllocateStack(4, 4);
946 CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
948 // Get a count of how many bytes are to be pushed on the stack.
949 unsigned NumBytes = CCInfo.getNextStackOffset();
951 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
952 getPointerTy(), true));
954 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
955 SmallVector<SDValue, 12> MemOpChains;
957 // Walk the register/memloc assignments, inserting copies/loads.
958 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
959 CCValAssign &VA = ArgLocs[i];
960 SDValue Arg = OutVals[i];
962 // Promote the value if needed.
963 switch (VA.getLocInfo()) {
964 default: llvm_unreachable("Unknown loc info!");
965 case CCValAssign::Full: break;
966 case CCValAssign::SExt:
967 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
969 case CCValAssign::ZExt:
970 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
972 case CCValAssign::AExt:
973 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
977 // Arguments that can be passed on register must be kept at
980 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
982 assert(VA.isMemLoc());
984 int Offset = VA.getLocMemOffset();
986 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
988 DAG.getConstant(Offset/4, MVT::i32)));
992 // Transform all store nodes into one single node because
993 // all store nodes are independent of each other.
994 if (!MemOpChains.empty())
995 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
996 &MemOpChains[0], MemOpChains.size());
998 // Build a sequence of copy-to-reg nodes chained together with token
999 // chain and flag operands which copy the outgoing args into registers.
1000 // The InFlag in necessary since all emitted instructions must be
1003 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1004 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1005 RegsToPass[i].second, InFlag);
1006 InFlag = Chain.getValue(1);
1009 // If the callee is a GlobalAddress node (quite common, every direct call is)
1010 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1011 // Likewise ExternalSymbol -> TargetExternalSymbol.
1012 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1013 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
1014 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
1015 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
1017 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
1018 // = Chain, Callee, Reg#1, Reg#2, ...
1020 // Returns a chain & a flag for retval copy to use.
1021 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1022 SmallVector<SDValue, 8> Ops;
1023 Ops.push_back(Chain);
1024 Ops.push_back(Callee);
1026 // Add argument registers to the end of the list so that they are
1027 // known live into the call.
1028 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1029 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1030 RegsToPass[i].second.getValueType()));
1032 if (InFlag.getNode())
1033 Ops.push_back(InFlag);
1035 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, &Ops[0], Ops.size());
1036 InFlag = Chain.getValue(1);
1038 // Create the CALLSEQ_END node.
1039 Chain = DAG.getCALLSEQ_END(Chain,
1040 DAG.getConstant(NumBytes, getPointerTy(), true),
1041 DAG.getConstant(0, getPointerTy(), true),
1043 InFlag = Chain.getValue(1);
1045 // Handle result values, copying them out of physregs into vregs that we
1047 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
1048 Ins, dl, DAG, InVals);
1051 /// LowerCallResult - Lower the result values of a call into the
1052 /// appropriate copies out of appropriate physical registers.
1054 XCoreTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1055 CallingConv::ID CallConv, bool isVarArg,
1056 const SmallVectorImpl<ISD::InputArg> &Ins,
1057 DebugLoc dl, SelectionDAG &DAG,
1058 SmallVectorImpl<SDValue> &InVals) const {
1060 // Assign locations to each value returned by this call.
1061 SmallVector<CCValAssign, 16> RVLocs;
1062 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1063 getTargetMachine(), RVLocs, *DAG.getContext());
1065 CCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
1067 // Copy all of the result registers out of their specified physreg.
1068 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1069 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
1070 RVLocs[i].getValVT(), InFlag).getValue(1);
1071 InFlag = Chain.getValue(2);
1072 InVals.push_back(Chain.getValue(0));
1078 //===----------------------------------------------------------------------===//
1079 // Formal Arguments Calling Convention Implementation
1080 //===----------------------------------------------------------------------===//
1082 /// XCore formal arguments implementation
1084 XCoreTargetLowering::LowerFormalArguments(SDValue Chain,
1085 CallingConv::ID CallConv,
1087 const SmallVectorImpl<ISD::InputArg> &Ins,
1090 SmallVectorImpl<SDValue> &InVals)
1095 llvm_unreachable("Unsupported calling convention");
1096 case CallingConv::C:
1097 case CallingConv::Fast:
1098 return LowerCCCArguments(Chain, CallConv, isVarArg,
1099 Ins, dl, DAG, InVals);
1103 /// LowerCCCArguments - transform physical registers into
1104 /// virtual registers and generate load operations for
1105 /// arguments places on the stack.
1108 XCoreTargetLowering::LowerCCCArguments(SDValue Chain,
1109 CallingConv::ID CallConv,
1111 const SmallVectorImpl<ISD::InputArg>
1115 SmallVectorImpl<SDValue> &InVals) const {
1116 MachineFunction &MF = DAG.getMachineFunction();
1117 MachineFrameInfo *MFI = MF.getFrameInfo();
1118 MachineRegisterInfo &RegInfo = MF.getRegInfo();
1120 // Assign locations to all of the incoming arguments.
1121 SmallVector<CCValAssign, 16> ArgLocs;
1122 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1123 getTargetMachine(), ArgLocs, *DAG.getContext());
1125 CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
1127 unsigned StackSlotSize = XCoreFrameLowering::stackSlotSize();
1129 unsigned LRSaveSize = StackSlotSize;
1131 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1133 CCValAssign &VA = ArgLocs[i];
1135 if (VA.isRegLoc()) {
1136 // Arguments passed in registers
1137 EVT RegVT = VA.getLocVT();
1138 switch (RegVT.getSimpleVT().SimpleTy) {
1142 errs() << "LowerFormalArguments Unhandled argument type: "
1143 << RegVT.getSimpleVT().SimpleTy << "\n";
1145 llvm_unreachable(0);
1148 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1149 RegInfo.addLiveIn(VA.getLocReg(), VReg);
1150 InVals.push_back(DAG.getCopyFromReg(Chain, dl, VReg, RegVT));
1154 assert(VA.isMemLoc());
1155 // Load the argument to a virtual register
1156 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
1157 if (ObjSize > StackSlotSize) {
1158 errs() << "LowerFormalArguments Unhandled argument type: "
1159 << EVT(VA.getLocVT()).getEVTString()
1162 // Create the frame index object for this incoming parameter...
1163 int FI = MFI->CreateFixedObject(ObjSize,
1164 LRSaveSize + VA.getLocMemOffset(),
1167 // Create the SelectionDAG nodes corresponding to a load
1168 //from this parameter
1169 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1170 InVals.push_back(DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
1171 MachinePointerInfo::getFixedStack(FI),
1172 false, false, false, 0));
1177 /* Argument registers */
1178 static const uint16_t ArgRegs[] = {
1179 XCore::R0, XCore::R1, XCore::R2, XCore::R3
1181 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1182 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
1183 array_lengthof(ArgRegs));
1184 if (FirstVAReg < array_lengthof(ArgRegs)) {
1185 SmallVector<SDValue, 4> MemOps;
1187 // Save remaining registers, storing higher register numbers at a higher
1189 for (int i = array_lengthof(ArgRegs) - 1; i >= (int)FirstVAReg; --i) {
1190 // Create a stack slot
1191 int FI = MFI->CreateFixedObject(4, offset, true);
1192 if (i == (int)FirstVAReg) {
1193 XFI->setVarArgsFrameIndex(FI);
1195 offset -= StackSlotSize;
1196 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1197 // Move argument from phys reg -> virt reg
1198 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1199 RegInfo.addLiveIn(ArgRegs[i], VReg);
1200 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1201 // Move argument from virt reg -> stack
1202 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
1203 MachinePointerInfo(), false, false, 0);
1204 MemOps.push_back(Store);
1206 if (!MemOps.empty())
1207 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1208 &MemOps[0], MemOps.size());
1210 // This will point to the next argument passed via stack.
1211 XFI->setVarArgsFrameIndex(
1212 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset(),
1220 //===----------------------------------------------------------------------===//
1221 // Return Value Calling Convention Implementation
1222 //===----------------------------------------------------------------------===//
1224 bool XCoreTargetLowering::
1225 CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF,
1227 const SmallVectorImpl<ISD::OutputArg> &Outs,
1228 LLVMContext &Context) const {
1229 SmallVector<CCValAssign, 16> RVLocs;
1230 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
1231 return CCInfo.CheckReturn(Outs, RetCC_XCore);
1235 XCoreTargetLowering::LowerReturn(SDValue Chain,
1236 CallingConv::ID CallConv, bool isVarArg,
1237 const SmallVectorImpl<ISD::OutputArg> &Outs,
1238 const SmallVectorImpl<SDValue> &OutVals,
1239 DebugLoc dl, SelectionDAG &DAG) const {
1241 // CCValAssign - represent the assignment of
1242 // the return value to a location
1243 SmallVector<CCValAssign, 16> RVLocs;
1245 // CCState - Info about the registers and stack slot.
1246 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1247 getTargetMachine(), RVLocs, *DAG.getContext());
1249 // Analyze return values.
1250 CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
1253 SmallVector<SDValue, 4> RetOps(1, Chain);
1255 // Return on XCore is always a "retsp 0"
1256 RetOps.push_back(DAG.getConstant(0, MVT::i32));
1258 // Copy the result values into the output registers.
1259 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1260 CCValAssign &VA = RVLocs[i];
1261 assert(VA.isRegLoc() && "Can only return in registers!");
1263 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1266 // guarantee that all emitted copies are
1267 // stuck together, avoiding something bad
1268 Flag = Chain.getValue(1);
1269 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1272 RetOps[0] = Chain; // Update chain.
1274 // Add the flag if we have it.
1276 RetOps.push_back(Flag);
1278 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
1279 &RetOps[0], RetOps.size());
1282 //===----------------------------------------------------------------------===//
1283 // Other Lowering Code
1284 //===----------------------------------------------------------------------===//
1287 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1288 MachineBasicBlock *BB) const {
1289 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1290 DebugLoc dl = MI->getDebugLoc();
1291 assert((MI->getOpcode() == XCore::SELECT_CC) &&
1292 "Unexpected instr type to insert");
1294 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1295 // control-flow pattern. The incoming instruction knows the destination vreg
1296 // to set, the condition code register to branch on, the true/false values to
1297 // select between, and a branch opcode to use.
1298 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1299 MachineFunction::iterator It = BB;
1305 // cmpTY ccX, r1, r2
1307 // fallthrough --> copy0MBB
1308 MachineBasicBlock *thisMBB = BB;
1309 MachineFunction *F = BB->getParent();
1310 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1311 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1312 F->insert(It, copy0MBB);
1313 F->insert(It, sinkMBB);
1315 // Transfer the remainder of BB and its successor edges to sinkMBB.
1316 sinkMBB->splice(sinkMBB->begin(), BB,
1317 llvm::next(MachineBasicBlock::iterator(MI)),
1319 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1321 // Next, add the true and fallthrough blocks as its successors.
1322 BB->addSuccessor(copy0MBB);
1323 BB->addSuccessor(sinkMBB);
1325 BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1326 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1329 // %FalseValue = ...
1330 // # fallthrough to sinkMBB
1333 // Update machine-CFG edges
1334 BB->addSuccessor(sinkMBB);
1337 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1340 BuildMI(*BB, BB->begin(), dl,
1341 TII.get(XCore::PHI), MI->getOperand(0).getReg())
1342 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1343 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1345 MI->eraseFromParent(); // The pseudo instruction is gone now.
1349 //===----------------------------------------------------------------------===//
1350 // Target Optimization Hooks
1351 //===----------------------------------------------------------------------===//
1353 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1354 DAGCombinerInfo &DCI) const {
1355 SelectionDAG &DAG = DCI.DAG;
1356 DebugLoc dl = N->getDebugLoc();
1357 switch (N->getOpcode()) {
1359 case XCoreISD::LADD: {
1360 SDValue N0 = N->getOperand(0);
1361 SDValue N1 = N->getOperand(1);
1362 SDValue N2 = N->getOperand(2);
1363 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1364 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1365 EVT VT = N0.getValueType();
1367 // canonicalize constant to RHS
1369 return DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N1, N0, N2);
1371 // fold (ladd 0, 0, x) -> 0, x & 1
1372 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1373 SDValue Carry = DAG.getConstant(0, VT);
1374 SDValue Result = DAG.getNode(ISD::AND, dl, VT, N2,
1375 DAG.getConstant(1, VT));
1376 SDValue Ops[] = { Result, Carry };
1377 return DAG.getMergeValues(Ops, 2, dl);
1380 // fold (ladd x, 0, y) -> 0, add x, y iff carry is unused and y has only the
1382 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1383 APInt KnownZero, KnownOne;
1384 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1385 VT.getSizeInBits() - 1);
1386 DAG.ComputeMaskedBits(N2, KnownZero, KnownOne);
1387 if ((KnownZero & Mask) == Mask) {
1388 SDValue Carry = DAG.getConstant(0, VT);
1389 SDValue Result = DAG.getNode(ISD::ADD, dl, VT, N0, N2);
1390 SDValue Ops[] = { Result, Carry };
1391 return DAG.getMergeValues(Ops, 2, dl);
1396 case XCoreISD::LSUB: {
1397 SDValue N0 = N->getOperand(0);
1398 SDValue N1 = N->getOperand(1);
1399 SDValue N2 = N->getOperand(2);
1400 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1401 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1402 EVT VT = N0.getValueType();
1404 // fold (lsub 0, 0, x) -> x, -x iff x has only the low bit set
1405 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1406 APInt KnownZero, KnownOne;
1407 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1408 VT.getSizeInBits() - 1);
1409 DAG.ComputeMaskedBits(N2, KnownZero, KnownOne);
1410 if ((KnownZero & Mask) == Mask) {
1411 SDValue Borrow = N2;
1412 SDValue Result = DAG.getNode(ISD::SUB, dl, VT,
1413 DAG.getConstant(0, VT), N2);
1414 SDValue Ops[] = { Result, Borrow };
1415 return DAG.getMergeValues(Ops, 2, dl);
1419 // fold (lsub x, 0, y) -> 0, sub x, y iff borrow is unused and y has only the
1421 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1422 APInt KnownZero, KnownOne;
1423 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1424 VT.getSizeInBits() - 1);
1425 DAG.ComputeMaskedBits(N2, KnownZero, KnownOne);
1426 if ((KnownZero & Mask) == Mask) {
1427 SDValue Borrow = DAG.getConstant(0, VT);
1428 SDValue Result = DAG.getNode(ISD::SUB, dl, VT, N0, N2);
1429 SDValue Ops[] = { Result, Borrow };
1430 return DAG.getMergeValues(Ops, 2, dl);
1435 case XCoreISD::LMUL: {
1436 SDValue N0 = N->getOperand(0);
1437 SDValue N1 = N->getOperand(1);
1438 SDValue N2 = N->getOperand(2);
1439 SDValue N3 = N->getOperand(3);
1440 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1441 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1442 EVT VT = N0.getValueType();
1443 // Canonicalize multiplicative constant to RHS. If both multiplicative
1444 // operands are constant canonicalize smallest to RHS.
1445 if ((N0C && !N1C) ||
1446 (N0C && N1C && N0C->getZExtValue() < N1C->getZExtValue()))
1447 return DAG.getNode(XCoreISD::LMUL, dl, DAG.getVTList(VT, VT),
1451 if (N1C && N1C->isNullValue()) {
1452 // If the high result is unused fold to add(a, b)
1453 if (N->hasNUsesOfValue(0, 0)) {
1454 SDValue Lo = DAG.getNode(ISD::ADD, dl, VT, N2, N3);
1455 SDValue Ops[] = { Lo, Lo };
1456 return DAG.getMergeValues(Ops, 2, dl);
1458 // Otherwise fold to ladd(a, b, 0)
1460 DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N2, N3, N1);
1461 SDValue Carry(Result.getNode(), 1);
1462 SDValue Ops[] = { Carry, Result };
1463 return DAG.getMergeValues(Ops, 2, dl);
1468 // Fold 32 bit expressions such as add(add(mul(x,y),a),b) ->
1469 // lmul(x, y, a, b). The high result of lmul will be ignored.
1470 // This is only profitable if the intermediate results are unused
1472 SDValue Mul0, Mul1, Addend0, Addend1;
1473 if (N->getValueType(0) == MVT::i32 &&
1474 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, true)) {
1475 SDValue Ignored = DAG.getNode(XCoreISD::LMUL, dl,
1476 DAG.getVTList(MVT::i32, MVT::i32), Mul0,
1477 Mul1, Addend0, Addend1);
1478 SDValue Result(Ignored.getNode(), 1);
1481 APInt HighMask = APInt::getHighBitsSet(64, 32);
1482 // Fold 64 bit expression such as add(add(mul(x,y),a),b) ->
1483 // lmul(x, y, a, b) if all operands are zero-extended. We do this
1484 // before type legalization as it is messy to match the operands after
1486 if (N->getValueType(0) == MVT::i64 &&
1487 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, false) &&
1488 DAG.MaskedValueIsZero(Mul0, HighMask) &&
1489 DAG.MaskedValueIsZero(Mul1, HighMask) &&
1490 DAG.MaskedValueIsZero(Addend0, HighMask) &&
1491 DAG.MaskedValueIsZero(Addend1, HighMask)) {
1492 SDValue Mul0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1493 Mul0, DAG.getConstant(0, MVT::i32));
1494 SDValue Mul1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1495 Mul1, DAG.getConstant(0, MVT::i32));
1496 SDValue Addend0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1497 Addend0, DAG.getConstant(0, MVT::i32));
1498 SDValue Addend1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1499 Addend1, DAG.getConstant(0, MVT::i32));
1500 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
1501 DAG.getVTList(MVT::i32, MVT::i32), Mul0L, Mul1L,
1502 Addend0L, Addend1L);
1503 SDValue Lo(Hi.getNode(), 1);
1504 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
1509 // Replace unaligned store of unaligned load with memmove.
1510 StoreSDNode *ST = cast<StoreSDNode>(N);
1511 if (!DCI.isBeforeLegalize() ||
1512 allowsUnalignedMemoryAccesses(ST->getMemoryVT()) ||
1513 ST->isVolatile() || ST->isIndexed()) {
1516 SDValue Chain = ST->getChain();
1518 unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1519 if (StoreBits % 8) {
1522 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(
1523 ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1524 unsigned Alignment = ST->getAlignment();
1525 if (Alignment >= ABIAlignment) {
1529 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1530 if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1531 LD->getAlignment() == Alignment &&
1532 !LD->isVolatile() && !LD->isIndexed() &&
1533 Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1534 return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1536 DAG.getConstant(StoreBits/8, MVT::i32),
1537 Alignment, false, ST->getPointerInfo(),
1538 LD->getPointerInfo());
1547 void XCoreTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
1550 const SelectionDAG &DAG,
1551 unsigned Depth) const {
1552 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
1553 switch (Op.getOpcode()) {
1555 case XCoreISD::LADD:
1556 case XCoreISD::LSUB:
1557 if (Op.getResNo() == 1) {
1558 // Top bits of carry / borrow are clear.
1559 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1560 KnownZero.getBitWidth() - 1);
1566 //===----------------------------------------------------------------------===//
1567 // Addressing mode description hooks
1568 //===----------------------------------------------------------------------===//
1570 static inline bool isImmUs(int64_t val)
1572 return (val >= 0 && val <= 11);
1575 static inline bool isImmUs2(int64_t val)
1577 return (val%2 == 0 && isImmUs(val/2));
1580 static inline bool isImmUs4(int64_t val)
1582 return (val%4 == 0 && isImmUs(val/4));
1585 /// isLegalAddressingMode - Return true if the addressing mode represented
1586 /// by AM is legal for this target, for a load/store of the specified type.
1588 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1590 if (Ty->getTypeID() == Type::VoidTyID)
1591 return AM.Scale == 0 && isImmUs(AM.BaseOffs) && isImmUs4(AM.BaseOffs);
1593 const DataLayout *TD = TM.getDataLayout();
1594 unsigned Size = TD->getTypeAllocSize(Ty);
1596 return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1603 if (AM.Scale == 0) {
1604 return isImmUs(AM.BaseOffs);
1607 return AM.Scale == 1 && AM.BaseOffs == 0;
1611 if (AM.Scale == 0) {
1612 return isImmUs2(AM.BaseOffs);
1615 return AM.Scale == 2 && AM.BaseOffs == 0;
1618 if (AM.Scale == 0) {
1619 return isImmUs4(AM.BaseOffs);
1622 return AM.Scale == 4 && AM.BaseOffs == 0;
1626 //===----------------------------------------------------------------------===//
1627 // XCore Inline Assembly Support
1628 //===----------------------------------------------------------------------===//
1630 std::pair<unsigned, const TargetRegisterClass*>
1631 XCoreTargetLowering::
1632 getRegForInlineAsmConstraint(const std::string &Constraint,
1634 if (Constraint.size() == 1) {
1635 switch (Constraint[0]) {
1638 return std::make_pair(0U, &XCore::GRRegsRegClass);
1641 // Use the default implementation in TargetLowering to convert the register
1642 // constraint into a member of a register class.
1643 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);