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 #include "XCoreISelLowering.h"
16 #include "XCoreMachineFunctionInfo.h"
17 #include "XCoreSubtarget.h"
18 #include "XCoreTargetMachine.h"
19 #include "XCoreTargetObjectFile.h"
20 #include "llvm/CodeGen/CallingConvLower.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAGISel.h"
27 #include "llvm/CodeGen/ValueTypes.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GlobalAlias.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
42 #define DEBUG_TYPE "xcore-lower"
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::LDWSP : return "XCoreISD::LDWSP";
54 case XCoreISD::STWSP : return "XCoreISD::STWSP";
55 case XCoreISD::RETSP : return "XCoreISD::RETSP";
56 case XCoreISD::LADD : return "XCoreISD::LADD";
57 case XCoreISD::LSUB : return "XCoreISD::LSUB";
58 case XCoreISD::LMUL : return "XCoreISD::LMUL";
59 case XCoreISD::MACCU : return "XCoreISD::MACCU";
60 case XCoreISD::MACCS : return "XCoreISD::MACCS";
61 case XCoreISD::CRC8 : return "XCoreISD::CRC8";
62 case XCoreISD::BR_JT : return "XCoreISD::BR_JT";
63 case XCoreISD::BR_JT32 : return "XCoreISD::BR_JT32";
64 case XCoreISD::FRAME_TO_ARGS_OFFSET : return "XCoreISD::FRAME_TO_ARGS_OFFSET";
65 case XCoreISD::EH_RETURN : return "XCoreISD::EH_RETURN";
66 case XCoreISD::MEMBARRIER : return "XCoreISD::MEMBARRIER";
67 default : return nullptr;
71 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
72 : TargetLowering(XTM, new XCoreTargetObjectFile()),
74 Subtarget(*XTM.getSubtargetImpl()) {
76 // Set up the register classes.
77 addRegisterClass(MVT::i32, &XCore::GRRegsRegClass);
79 // Compute derived properties from the register classes
80 computeRegisterProperties();
82 // Division is expensive
83 setIntDivIsCheap(false);
85 setStackPointerRegisterToSaveRestore(XCore::SP);
87 setSchedulingPreference(Sched::Source);
89 // Use i32 for setcc operations results (slt, sgt, ...).
90 setBooleanContents(ZeroOrOneBooleanContent);
91 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
93 // XCore does not have the NodeTypes below.
94 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
95 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
96 setOperationAction(ISD::ADDC, MVT::i32, Expand);
97 setOperationAction(ISD::ADDE, MVT::i32, Expand);
98 setOperationAction(ISD::SUBC, MVT::i32, Expand);
99 setOperationAction(ISD::SUBE, MVT::i32, Expand);
102 setOperationAction(ISD::ADD, MVT::i64, Custom);
103 setOperationAction(ISD::SUB, MVT::i64, Custom);
104 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
105 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
106 setOperationAction(ISD::MULHS, MVT::i32, Expand);
107 setOperationAction(ISD::MULHU, MVT::i32, Expand);
108 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
109 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
110 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
113 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
114 setOperationAction(ISD::ROTL , MVT::i32, Expand);
115 setOperationAction(ISD::ROTR , MVT::i32, Expand);
116 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
117 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
119 setOperationAction(ISD::TRAP, MVT::Other, Legal);
122 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
124 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
125 setOperationAction(ISD::BlockAddress, MVT::i32 , Custom);
127 // Conversion of i64 -> double produces constantpool nodes
128 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
131 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
132 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
133 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
135 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
136 setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
138 // Custom expand misaligned loads / stores.
139 setOperationAction(ISD::LOAD, MVT::i32, Custom);
140 setOperationAction(ISD::STORE, MVT::i32, Custom);
143 setOperationAction(ISD::VAEND, MVT::Other, Expand);
144 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
145 setOperationAction(ISD::VAARG, MVT::Other, Custom);
146 setOperationAction(ISD::VASTART, MVT::Other, Custom);
149 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
150 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
151 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
153 // Exception handling
154 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
155 setExceptionPointerRegister(XCore::R0);
156 setExceptionSelectorRegister(XCore::R1);
157 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
160 // We request a fence for ATOMIC_* instructions, to reduce them to Monotonic.
161 // As we are always Sequential Consistent, an ATOMIC_FENCE becomes a no OP.
162 setInsertFencesForAtomic(true);
163 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
164 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
165 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
167 // TRAMPOLINE is custom lowered.
168 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
169 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
171 // We want to custom lower some of our intrinsics.
172 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
174 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 4;
175 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize
176 = MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 2;
178 // We have target-specific dag combine patterns for the following nodes:
179 setTargetDAGCombine(ISD::STORE);
180 setTargetDAGCombine(ISD::ADD);
181 setTargetDAGCombine(ISD::INTRINSIC_VOID);
182 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
184 setMinFunctionAlignment(1);
185 setPrefFunctionAlignment(2);
188 bool XCoreTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
189 if (Val.getOpcode() != ISD::LOAD)
192 EVT VT1 = Val.getValueType();
193 if (!VT1.isSimple() || !VT1.isInteger() ||
194 !VT2.isSimple() || !VT2.isInteger())
197 switch (VT1.getSimpleVT().SimpleTy) {
206 SDValue XCoreTargetLowering::
207 LowerOperation(SDValue Op, SelectionDAG &DAG) const {
208 switch (Op.getOpcode())
210 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
211 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
212 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
213 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
214 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
215 case ISD::LOAD: return LowerLOAD(Op, DAG);
216 case ISD::STORE: return LowerSTORE(Op, DAG);
217 case ISD::VAARG: return LowerVAARG(Op, DAG);
218 case ISD::VASTART: return LowerVASTART(Op, DAG);
219 case ISD::SMUL_LOHI: return LowerSMUL_LOHI(Op, DAG);
220 case ISD::UMUL_LOHI: return LowerUMUL_LOHI(Op, DAG);
221 // FIXME: Remove these when LegalizeDAGTypes lands.
223 case ISD::SUB: return ExpandADDSUB(Op.getNode(), DAG);
224 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
225 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
226 case ISD::FRAME_TO_ARGS_OFFSET: return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
227 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
228 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
229 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
230 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
231 case ISD::ATOMIC_LOAD: return LowerATOMIC_LOAD(Op, DAG);
232 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op, DAG);
234 llvm_unreachable("unimplemented operand");
238 /// ReplaceNodeResults - Replace the results of node with an illegal result
239 /// type with new values built out of custom code.
240 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
241 SmallVectorImpl<SDValue>&Results,
242 SelectionDAG &DAG) const {
243 switch (N->getOpcode()) {
245 llvm_unreachable("Don't know how to custom expand this!");
248 Results.push_back(ExpandADDSUB(N, DAG));
253 //===----------------------------------------------------------------------===//
254 // Misc Lower Operation implementation
255 //===----------------------------------------------------------------------===//
257 SDValue XCoreTargetLowering::getGlobalAddressWrapper(SDValue GA,
258 const GlobalValue *GV,
259 SelectionDAG &DAG) const {
260 // FIXME there is no actual debug info here
263 if (GV->getType()->getElementType()->isFunctionTy())
264 return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
266 const auto *GVar = dyn_cast<GlobalVariable>(GV);
267 if ((GV->hasSection() && StringRef(GV->getSection()).startswith(".cp.")) ||
268 (GVar && GVar->isConstant() && GV->hasLocalLinkage()))
269 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
271 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
274 static bool IsSmallObject(const GlobalValue *GV, const XCoreTargetLowering &XTL) {
275 if (XTL.getTargetMachine().getCodeModel() == CodeModel::Small)
278 Type *ObjType = GV->getType()->getPointerElementType();
279 if (!ObjType->isSized())
282 unsigned ObjSize = XTL.getDataLayout()->getTypeAllocSize(ObjType);
283 return ObjSize < CodeModelLargeSize && ObjSize != 0;
286 SDValue XCoreTargetLowering::
287 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const
289 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
290 const GlobalValue *GV = GN->getGlobal();
292 int64_t Offset = GN->getOffset();
293 if (IsSmallObject(GV, *this)) {
294 // We can only fold positive offsets that are a multiple of the word size.
295 int64_t FoldedOffset = std::max(Offset & ~3, (int64_t)0);
296 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, FoldedOffset);
297 GA = getGlobalAddressWrapper(GA, GV, DAG);
298 // Handle the rest of the offset.
299 if (Offset != FoldedOffset) {
300 SDValue Remaining = DAG.getConstant(Offset - FoldedOffset, MVT::i32);
301 GA = DAG.getNode(ISD::ADD, DL, MVT::i32, GA, Remaining);
305 // Ideally we would not fold in offset with an index <= 11.
306 Type *Ty = Type::getInt8PtrTy(*DAG.getContext());
307 Constant *GA = ConstantExpr::getBitCast(const_cast<GlobalValue*>(GV), Ty);
308 Ty = Type::getInt32Ty(*DAG.getContext());
309 Constant *Idx = ConstantInt::get(Ty, Offset);
310 Constant *GAI = ConstantExpr::getGetElementPtr(GA, Idx);
311 SDValue CP = DAG.getConstantPool(GAI, MVT::i32);
312 return DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), CP,
313 MachinePointerInfo(), false, false, false, 0);
317 SDValue XCoreTargetLowering::
318 LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const
322 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
323 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy());
325 return DAG.getNode(XCoreISD::PCRelativeWrapper, DL, getPointerTy(), Result);
328 SDValue XCoreTargetLowering::
329 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
331 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
332 // FIXME there isn't really debug info here
334 EVT PtrVT = Op.getValueType();
336 if (CP->isMachineConstantPoolEntry()) {
337 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
338 CP->getAlignment(), CP->getOffset());
340 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
341 CP->getAlignment(), CP->getOffset());
343 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
346 unsigned XCoreTargetLowering::getJumpTableEncoding() const {
347 return MachineJumpTableInfo::EK_Inline;
350 SDValue XCoreTargetLowering::
351 LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
353 SDValue Chain = Op.getOperand(0);
354 SDValue Table = Op.getOperand(1);
355 SDValue Index = Op.getOperand(2);
357 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
358 unsigned JTI = JT->getIndex();
359 MachineFunction &MF = DAG.getMachineFunction();
360 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
361 SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
363 unsigned NumEntries = MJTI->getJumpTables()[JTI].MBBs.size();
364 if (NumEntries <= 32) {
365 return DAG.getNode(XCoreISD::BR_JT, dl, MVT::Other, Chain, TargetJT, Index);
367 assert((NumEntries >> 31) == 0);
368 SDValue ScaledIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
369 DAG.getConstant(1, MVT::i32));
370 return DAG.getNode(XCoreISD::BR_JT32, dl, MVT::Other, Chain, TargetJT,
374 SDValue XCoreTargetLowering::
375 lowerLoadWordFromAlignedBasePlusOffset(SDLoc DL, SDValue Chain, SDValue Base,
376 int64_t Offset, SelectionDAG &DAG) const
378 if ((Offset & 0x3) == 0) {
379 return DAG.getLoad(getPointerTy(), DL, Chain, Base, MachinePointerInfo(),
380 false, false, false, 0);
382 // Lower to pair of consecutive word aligned loads plus some bit shifting.
383 int32_t HighOffset = RoundUpToAlignment(Offset, 4);
384 int32_t LowOffset = HighOffset - 4;
385 SDValue LowAddr, HighAddr;
386 if (GlobalAddressSDNode *GASD =
387 dyn_cast<GlobalAddressSDNode>(Base.getNode())) {
388 LowAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
390 HighAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
393 LowAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
394 DAG.getConstant(LowOffset, MVT::i32));
395 HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
396 DAG.getConstant(HighOffset, MVT::i32));
398 SDValue LowShift = DAG.getConstant((Offset - LowOffset) * 8, MVT::i32);
399 SDValue HighShift = DAG.getConstant((HighOffset - Offset) * 8, MVT::i32);
401 SDValue Low = DAG.getLoad(getPointerTy(), DL, Chain,
402 LowAddr, MachinePointerInfo(),
403 false, false, false, 0);
404 SDValue High = DAG.getLoad(getPointerTy(), DL, Chain,
405 HighAddr, MachinePointerInfo(),
406 false, false, false, 0);
407 SDValue LowShifted = DAG.getNode(ISD::SRL, DL, MVT::i32, Low, LowShift);
408 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High, HighShift);
409 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, LowShifted, HighShifted);
410 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
412 SDValue Ops[] = { Result, Chain };
413 return DAG.getMergeValues(Ops, DL);
416 static bool isWordAligned(SDValue Value, SelectionDAG &DAG)
418 APInt KnownZero, KnownOne;
419 DAG.computeKnownBits(Value, KnownZero, KnownOne);
420 return KnownZero.countTrailingOnes() >= 2;
423 SDValue XCoreTargetLowering::
424 LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
425 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
426 LoadSDNode *LD = cast<LoadSDNode>(Op);
427 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
428 "Unexpected extension type");
429 assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
430 if (allowsUnalignedMemoryAccesses(LD->getMemoryVT()))
433 unsigned ABIAlignment = getDataLayout()->
434 getABITypeAlignment(LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
435 // Leave aligned load alone.
436 if (LD->getAlignment() >= ABIAlignment)
439 SDValue Chain = LD->getChain();
440 SDValue BasePtr = LD->getBasePtr();
443 if (!LD->isVolatile()) {
444 const GlobalValue *GV;
446 if (DAG.isBaseWithConstantOffset(BasePtr) &&
447 isWordAligned(BasePtr->getOperand(0), DAG)) {
448 SDValue NewBasePtr = BasePtr->getOperand(0);
449 Offset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
450 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
453 if (TLI.isGAPlusOffset(BasePtr.getNode(), GV, Offset) &&
454 MinAlign(GV->getAlignment(), 4) == 4) {
455 SDValue NewBasePtr = DAG.getGlobalAddress(GV, DL,
456 BasePtr->getValueType(0));
457 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
462 if (LD->getAlignment() == 2) {
463 SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, DL, MVT::i32, Chain,
464 BasePtr, LD->getPointerInfo(), MVT::i16,
465 LD->isVolatile(), LD->isNonTemporal(), 2);
466 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
467 DAG.getConstant(2, MVT::i32));
468 SDValue High = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
470 LD->getPointerInfo().getWithOffset(2),
471 MVT::i16, LD->isVolatile(),
472 LD->isNonTemporal(), 2);
473 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High,
474 DAG.getConstant(16, MVT::i32));
475 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Low, HighShifted);
476 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
478 SDValue Ops[] = { Result, Chain };
479 return DAG.getMergeValues(Ops, DL);
482 // Lower to a call to __misaligned_load(BasePtr).
483 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
484 TargetLowering::ArgListTy Args;
485 TargetLowering::ArgListEntry Entry;
488 Entry.Node = BasePtr;
489 Args.push_back(Entry);
491 TargetLowering::CallLoweringInfo CLI(DAG);
492 CLI.setDebugLoc(DL).setChain(Chain)
493 .setCallee(CallingConv::C, IntPtrTy,
494 DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
497 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
498 SDValue Ops[] = { CallResult.first, CallResult.second };
499 return DAG.getMergeValues(Ops, 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();
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(DAG);
552 CLI.setDebugLoc(dl).setChain(Chain)
553 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
554 DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
557 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
558 return CallResult.second;
561 SDValue XCoreTargetLowering::
562 LowerSMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
564 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::SMUL_LOHI &&
565 "Unexpected operand to lower!");
567 SDValue LHS = Op.getOperand(0);
568 SDValue RHS = Op.getOperand(1);
569 SDValue Zero = DAG.getConstant(0, MVT::i32);
570 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
571 DAG.getVTList(MVT::i32, MVT::i32), Zero, Zero,
573 SDValue Lo(Hi.getNode(), 1);
574 SDValue Ops[] = { Lo, Hi };
575 return DAG.getMergeValues(Ops, dl);
578 SDValue XCoreTargetLowering::
579 LowerUMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
581 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::UMUL_LOHI &&
582 "Unexpected operand to lower!");
584 SDValue LHS = Op.getOperand(0);
585 SDValue RHS = Op.getOperand(1);
586 SDValue Zero = DAG.getConstant(0, MVT::i32);
587 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
588 DAG.getVTList(MVT::i32, MVT::i32), LHS, RHS,
590 SDValue Lo(Hi.getNode(), 1);
591 SDValue Ops[] = { Lo, Hi };
592 return DAG.getMergeValues(Ops, dl);
595 /// isADDADDMUL - Return whether Op is in a form that is equivalent to
596 /// add(add(mul(x,y),a),b). If requireIntermediatesHaveOneUse is true then
597 /// each intermediate result in the calculation must also have a single use.
598 /// If the Op is in the correct form the constituent parts are written to Mul0,
599 /// Mul1, Addend0 and Addend1.
601 isADDADDMUL(SDValue Op, SDValue &Mul0, SDValue &Mul1, SDValue &Addend0,
602 SDValue &Addend1, bool requireIntermediatesHaveOneUse)
604 if (Op.getOpcode() != ISD::ADD)
606 SDValue N0 = Op.getOperand(0);
607 SDValue N1 = Op.getOperand(1);
610 if (N0.getOpcode() == ISD::ADD) {
613 } else if (N1.getOpcode() == ISD::ADD) {
619 if (requireIntermediatesHaveOneUse && !AddOp.hasOneUse())
621 if (OtherOp.getOpcode() == ISD::MUL) {
622 // add(add(a,b),mul(x,y))
623 if (requireIntermediatesHaveOneUse && !OtherOp.hasOneUse())
625 Mul0 = OtherOp.getOperand(0);
626 Mul1 = OtherOp.getOperand(1);
627 Addend0 = AddOp.getOperand(0);
628 Addend1 = AddOp.getOperand(1);
631 if (AddOp.getOperand(0).getOpcode() == ISD::MUL) {
632 // add(add(mul(x,y),a),b)
633 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(0).hasOneUse())
635 Mul0 = AddOp.getOperand(0).getOperand(0);
636 Mul1 = AddOp.getOperand(0).getOperand(1);
637 Addend0 = AddOp.getOperand(1);
641 if (AddOp.getOperand(1).getOpcode() == ISD::MUL) {
642 // add(add(a,mul(x,y)),b)
643 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(1).hasOneUse())
645 Mul0 = AddOp.getOperand(1).getOperand(0);
646 Mul1 = AddOp.getOperand(1).getOperand(1);
647 Addend0 = AddOp.getOperand(0);
654 SDValue XCoreTargetLowering::
655 TryExpandADDWithMul(SDNode *N, SelectionDAG &DAG) const
659 if (N->getOperand(0).getOpcode() == ISD::MUL) {
660 Mul = N->getOperand(0);
661 Other = N->getOperand(1);
662 } else if (N->getOperand(1).getOpcode() == ISD::MUL) {
663 Mul = N->getOperand(1);
664 Other = N->getOperand(0);
669 SDValue LL, RL, AddendL, AddendH;
670 LL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
671 Mul.getOperand(0), DAG.getConstant(0, MVT::i32));
672 RL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
673 Mul.getOperand(1), DAG.getConstant(0, MVT::i32));
674 AddendL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
675 Other, DAG.getConstant(0, MVT::i32));
676 AddendH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
677 Other, DAG.getConstant(1, MVT::i32));
678 APInt HighMask = APInt::getHighBitsSet(64, 32);
679 unsigned LHSSB = DAG.ComputeNumSignBits(Mul.getOperand(0));
680 unsigned RHSSB = DAG.ComputeNumSignBits(Mul.getOperand(1));
681 if (DAG.MaskedValueIsZero(Mul.getOperand(0), HighMask) &&
682 DAG.MaskedValueIsZero(Mul.getOperand(1), HighMask)) {
683 // The inputs are both zero-extended.
684 SDValue Hi = DAG.getNode(XCoreISD::MACCU, 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);
690 if (LHSSB > 32 && RHSSB > 32) {
691 // The inputs are both sign-extended.
692 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
693 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
695 SDValue Lo(Hi.getNode(), 1);
696 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
699 LH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
700 Mul.getOperand(0), DAG.getConstant(1, MVT::i32));
701 RH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
702 Mul.getOperand(1), DAG.getConstant(1, MVT::i32));
703 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
704 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
706 SDValue Lo(Hi.getNode(), 1);
707 RH = DAG.getNode(ISD::MUL, dl, MVT::i32, LL, RH);
708 LH = DAG.getNode(ISD::MUL, dl, MVT::i32, LH, RL);
709 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, RH);
710 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, LH);
711 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
714 SDValue XCoreTargetLowering::
715 ExpandADDSUB(SDNode *N, SelectionDAG &DAG) const
717 assert(N->getValueType(0) == MVT::i64 &&
718 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
719 "Unknown operand to lower!");
721 if (N->getOpcode() == ISD::ADD) {
722 SDValue Result = TryExpandADDWithMul(N, DAG);
723 if (Result.getNode())
729 // Extract components
730 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
731 N->getOperand(0), DAG.getConstant(0, MVT::i32));
732 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
733 N->getOperand(0), DAG.getConstant(1, MVT::i32));
734 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
735 N->getOperand(1), DAG.getConstant(0, MVT::i32));
736 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
737 N->getOperand(1), DAG.getConstant(1, MVT::i32));
740 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
742 SDValue Zero = DAG.getConstant(0, MVT::i32);
743 SDValue Lo = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
745 SDValue Carry(Lo.getNode(), 1);
747 SDValue Hi = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
749 SDValue Ignored(Hi.getNode(), 1);
751 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
754 SDValue XCoreTargetLowering::
755 LowerVAARG(SDValue Op, SelectionDAG &DAG) const
757 // Whist llvm does not support aggregate varargs we can ignore
758 // the possibility of the ValueType being an implicit byVal vararg.
759 SDNode *Node = Op.getNode();
760 EVT VT = Node->getValueType(0); // not an aggregate
761 SDValue InChain = Node->getOperand(0);
762 SDValue VAListPtr = Node->getOperand(1);
763 EVT PtrVT = VAListPtr.getValueType();
764 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
766 SDValue VAList = DAG.getLoad(PtrVT, dl, InChain,
767 VAListPtr, MachinePointerInfo(SV),
768 false, false, false, 0);
769 // Increment the pointer, VAList, to the next vararg
770 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAList,
771 DAG.getIntPtrConstant(VT.getSizeInBits() / 8));
772 // Store the incremented VAList to the legalized pointer
773 InChain = DAG.getStore(VAList.getValue(1), dl, nextPtr, VAListPtr,
774 MachinePointerInfo(SV), false, false, 0);
775 // Load the actual argument out of the pointer VAList
776 return DAG.getLoad(VT, dl, InChain, VAList, MachinePointerInfo(),
777 false, false, false, 0);
780 SDValue XCoreTargetLowering::
781 LowerVASTART(SDValue Op, SelectionDAG &DAG) const
784 // vastart stores the address of the VarArgsFrameIndex slot into the
785 // memory location argument
786 MachineFunction &MF = DAG.getMachineFunction();
787 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
788 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
789 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1),
790 MachinePointerInfo(), false, false, 0);
793 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op,
794 SelectionDAG &DAG) const {
795 // This nodes represent llvm.frameaddress on the DAG.
796 // It takes one operand, the index of the frame address to return.
797 // An index of zero corresponds to the current function's frame address.
798 // An index of one to the parent's frame address, and so on.
799 // Depths > 0 not supported yet!
800 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
803 MachineFunction &MF = DAG.getMachineFunction();
804 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
805 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op),
806 RegInfo->getFrameRegister(MF), MVT::i32);
809 SDValue XCoreTargetLowering::
810 LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const {
811 // This nodes represent llvm.returnaddress on the DAG.
812 // It takes one operand, the index of the return address to return.
813 // An index of zero corresponds to the current function's return address.
814 // An index of one to the parent's return address, and so on.
815 // Depths > 0 not supported yet!
816 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
819 MachineFunction &MF = DAG.getMachineFunction();
820 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
821 int FI = XFI->createLRSpillSlot(MF);
822 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
823 return DAG.getLoad(getPointerTy(), SDLoc(Op), DAG.getEntryNode(), FIN,
824 MachinePointerInfo::getFixedStack(FI), false, false,
828 SDValue XCoreTargetLowering::
829 LowerFRAME_TO_ARGS_OFFSET(SDValue Op, SelectionDAG &DAG) const {
830 // This node represents offset from frame pointer to first on-stack argument.
831 // This is needed for correct stack adjustment during unwind.
832 // However, we don't know the offset until after the frame has be finalised.
833 // This is done during the XCoreFTAOElim pass.
834 return DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, SDLoc(Op), MVT::i32);
837 SDValue XCoreTargetLowering::
838 LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
839 // OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER)
840 // This node represents 'eh_return' gcc dwarf builtin, which is used to
841 // return from exception. The general meaning is: adjust stack by OFFSET and
842 // pass execution to HANDLER.
843 MachineFunction &MF = DAG.getMachineFunction();
844 SDValue Chain = Op.getOperand(0);
845 SDValue Offset = Op.getOperand(1);
846 SDValue Handler = Op.getOperand(2);
849 // Absolute SP = (FP + FrameToArgs) + Offset
850 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
851 SDValue Stack = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
852 RegInfo->getFrameRegister(MF), MVT::i32);
853 SDValue FrameToArgs = DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, dl,
855 Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, FrameToArgs);
856 Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, Offset);
858 // R0=ExceptionPointerRegister R1=ExceptionSelectorRegister
859 // which leaves 2 caller saved registers, R2 & R3 for us to use.
860 unsigned StackReg = XCore::R2;
861 unsigned HandlerReg = XCore::R3;
863 SDValue OutChains[] = {
864 DAG.getCopyToReg(Chain, dl, StackReg, Stack),
865 DAG.getCopyToReg(Chain, dl, HandlerReg, Handler)
868 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
870 return DAG.getNode(XCoreISD::EH_RETURN, dl, MVT::Other, Chain,
871 DAG.getRegister(StackReg, MVT::i32),
872 DAG.getRegister(HandlerReg, MVT::i32));
876 SDValue XCoreTargetLowering::
877 LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
878 return Op.getOperand(0);
881 SDValue XCoreTargetLowering::
882 LowerINIT_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
883 SDValue Chain = Op.getOperand(0);
884 SDValue Trmp = Op.getOperand(1); // trampoline
885 SDValue FPtr = Op.getOperand(2); // nested function
886 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
888 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
891 // LDAPF_u10 r11, nest
892 // LDW_2rus r11, r11[0]
893 // STWSP_ru6 r11, sp[0]
894 // LDAPF_u10 r11, fptr
895 // LDW_2rus r11, r11[0]
901 SDValue OutChains[5];
906 OutChains[0] = DAG.getStore(Chain, dl, DAG.getConstant(0x0a3cd805, MVT::i32),
907 Addr, MachinePointerInfo(TrmpAddr), false, false,
910 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
911 DAG.getConstant(4, MVT::i32));
912 OutChains[1] = DAG.getStore(Chain, dl, DAG.getConstant(0xd80456c0, MVT::i32),
913 Addr, MachinePointerInfo(TrmpAddr, 4), false,
916 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
917 DAG.getConstant(8, MVT::i32));
918 OutChains[2] = DAG.getStore(Chain, dl, DAG.getConstant(0x27fb0a3c, MVT::i32),
919 Addr, MachinePointerInfo(TrmpAddr, 8), false,
922 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
923 DAG.getConstant(12, MVT::i32));
924 OutChains[3] = DAG.getStore(Chain, dl, Nest, Addr,
925 MachinePointerInfo(TrmpAddr, 12), false, false,
928 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
929 DAG.getConstant(16, MVT::i32));
930 OutChains[4] = DAG.getStore(Chain, dl, FPtr, Addr,
931 MachinePointerInfo(TrmpAddr, 16), false, false,
934 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
937 SDValue XCoreTargetLowering::
938 LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
940 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
942 case Intrinsic::xcore_crc8:
943 EVT VT = Op.getValueType();
945 DAG.getNode(XCoreISD::CRC8, DL, DAG.getVTList(VT, VT),
946 Op.getOperand(1), Op.getOperand(2) , Op.getOperand(3));
947 SDValue Crc(Data.getNode(), 1);
948 SDValue Results[] = { Crc, Data };
949 return DAG.getMergeValues(Results, DL);
954 SDValue XCoreTargetLowering::
955 LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG) const {
957 return DAG.getNode(XCoreISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
960 SDValue XCoreTargetLowering::
961 LowerATOMIC_LOAD(SDValue Op, SelectionDAG &DAG) const {
962 AtomicSDNode *N = cast<AtomicSDNode>(Op);
963 assert(N->getOpcode() == ISD::ATOMIC_LOAD && "Bad Atomic OP");
964 assert(N->getOrdering() <= Monotonic &&
965 "setInsertFencesForAtomic(true) and yet greater than Monotonic");
966 if (N->getMemoryVT() == MVT::i32) {
967 if (N->getAlignment() < 4)
968 report_fatal_error("atomic load must be aligned");
969 return DAG.getLoad(getPointerTy(), SDLoc(Op), N->getChain(),
970 N->getBasePtr(), N->getPointerInfo(),
971 N->isVolatile(), N->isNonTemporal(),
972 N->isInvariant(), N->getAlignment(),
973 N->getTBAAInfo(), N->getRanges());
975 if (N->getMemoryVT() == MVT::i16) {
976 if (N->getAlignment() < 2)
977 report_fatal_error("atomic load must be aligned");
978 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
979 N->getBasePtr(), N->getPointerInfo(), MVT::i16,
980 N->isVolatile(), N->isNonTemporal(),
981 N->getAlignment(), N->getTBAAInfo());
983 if (N->getMemoryVT() == MVT::i8)
984 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
985 N->getBasePtr(), N->getPointerInfo(), MVT::i8,
986 N->isVolatile(), N->isNonTemporal(),
987 N->getAlignment(), N->getTBAAInfo());
991 SDValue XCoreTargetLowering::
992 LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) const {
993 AtomicSDNode *N = cast<AtomicSDNode>(Op);
994 assert(N->getOpcode() == ISD::ATOMIC_STORE && "Bad Atomic OP");
995 assert(N->getOrdering() <= Monotonic &&
996 "setInsertFencesForAtomic(true) and yet greater than Monotonic");
997 if (N->getMemoryVT() == MVT::i32) {
998 if (N->getAlignment() < 4)
999 report_fatal_error("atomic store must be aligned");
1000 return DAG.getStore(N->getChain(), SDLoc(Op), N->getVal(),
1001 N->getBasePtr(), N->getPointerInfo(),
1002 N->isVolatile(), N->isNonTemporal(),
1003 N->getAlignment(), N->getTBAAInfo());
1005 if (N->getMemoryVT() == MVT::i16) {
1006 if (N->getAlignment() < 2)
1007 report_fatal_error("atomic store must be aligned");
1008 return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1009 N->getBasePtr(), N->getPointerInfo(), MVT::i16,
1010 N->isVolatile(), N->isNonTemporal(),
1011 N->getAlignment(), N->getTBAAInfo());
1013 if (N->getMemoryVT() == MVT::i8)
1014 return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1015 N->getBasePtr(), N->getPointerInfo(), MVT::i8,
1016 N->isVolatile(), N->isNonTemporal(),
1017 N->getAlignment(), N->getTBAAInfo());
1021 //===----------------------------------------------------------------------===//
1022 // Calling Convention Implementation
1023 //===----------------------------------------------------------------------===//
1025 #include "XCoreGenCallingConv.inc"
1027 //===----------------------------------------------------------------------===//
1028 // Call Calling Convention Implementation
1029 //===----------------------------------------------------------------------===//
1031 /// XCore call implementation
1033 XCoreTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1034 SmallVectorImpl<SDValue> &InVals) const {
1035 SelectionDAG &DAG = CLI.DAG;
1037 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1038 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1039 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1040 SDValue Chain = CLI.Chain;
1041 SDValue Callee = CLI.Callee;
1042 bool &isTailCall = CLI.IsTailCall;
1043 CallingConv::ID CallConv = CLI.CallConv;
1044 bool isVarArg = CLI.IsVarArg;
1046 // XCore target does not yet support tail call optimization.
1049 // For now, only CallingConv::C implemented
1053 llvm_unreachable("Unsupported calling convention");
1054 case CallingConv::Fast:
1055 case CallingConv::C:
1056 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
1057 Outs, OutVals, Ins, dl, DAG, InVals);
1061 /// LowerCallResult - Lower the result values of a call into the
1062 /// appropriate copies out of appropriate physical registers / memory locations.
1064 LowerCallResult(SDValue Chain, SDValue InFlag,
1065 const SmallVectorImpl<CCValAssign> &RVLocs,
1066 SDLoc dl, SelectionDAG &DAG,
1067 SmallVectorImpl<SDValue> &InVals) {
1068 SmallVector<std::pair<int, unsigned>, 4> ResultMemLocs;
1069 // Copy results out of physical registers.
1070 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1071 const CCValAssign &VA = RVLocs[i];
1072 if (VA.isRegLoc()) {
1073 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getValVT(),
1074 InFlag).getValue(1);
1075 InFlag = Chain.getValue(2);
1076 InVals.push_back(Chain.getValue(0));
1078 assert(VA.isMemLoc());
1079 ResultMemLocs.push_back(std::make_pair(VA.getLocMemOffset(),
1081 // Reserve space for this result.
1082 InVals.push_back(SDValue());
1086 // Copy results out of memory.
1087 SmallVector<SDValue, 4> MemOpChains;
1088 for (unsigned i = 0, e = ResultMemLocs.size(); i != e; ++i) {
1089 int offset = ResultMemLocs[i].first;
1090 unsigned index = ResultMemLocs[i].second;
1091 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
1092 SDValue Ops[] = { Chain, DAG.getConstant(offset / 4, MVT::i32) };
1093 SDValue load = DAG.getNode(XCoreISD::LDWSP, dl, VTs, Ops);
1094 InVals[index] = load;
1095 MemOpChains.push_back(load.getValue(1));
1098 // Transform all loads nodes into one single node because
1099 // all load nodes are independent of each other.
1100 if (!MemOpChains.empty())
1101 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1106 /// LowerCCCCallTo - functions arguments are copied from virtual
1107 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
1108 /// CALLSEQ_END are emitted.
1109 /// TODO: isTailCall, sret.
1111 XCoreTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
1112 CallingConv::ID CallConv, bool isVarArg,
1114 const SmallVectorImpl<ISD::OutputArg> &Outs,
1115 const SmallVectorImpl<SDValue> &OutVals,
1116 const SmallVectorImpl<ISD::InputArg> &Ins,
1117 SDLoc dl, SelectionDAG &DAG,
1118 SmallVectorImpl<SDValue> &InVals) const {
1120 // Analyze operands of the call, assigning locations to each operand.
1121 SmallVector<CCValAssign, 16> ArgLocs;
1122 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1123 getTargetMachine(), ArgLocs, *DAG.getContext());
1125 // The ABI dictates there should be one stack slot available to the callee
1126 // on function entry (for saving lr).
1127 CCInfo.AllocateStack(4, 4);
1129 CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
1131 SmallVector<CCValAssign, 16> RVLocs;
1132 // Analyze return values to determine the number of bytes of stack required.
1133 CCState RetCCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1134 getTargetMachine(), RVLocs, *DAG.getContext());
1135 RetCCInfo.AllocateStack(CCInfo.getNextStackOffset(), 4);
1136 RetCCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
1138 // Get a count of how many bytes are to be pushed on the stack.
1139 unsigned NumBytes = RetCCInfo.getNextStackOffset();
1141 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
1142 getPointerTy(), true), dl);
1144 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
1145 SmallVector<SDValue, 12> MemOpChains;
1147 // Walk the register/memloc assignments, inserting copies/loads.
1148 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1149 CCValAssign &VA = ArgLocs[i];
1150 SDValue Arg = OutVals[i];
1152 // Promote the value if needed.
1153 switch (VA.getLocInfo()) {
1154 default: llvm_unreachable("Unknown loc info!");
1155 case CCValAssign::Full: break;
1156 case CCValAssign::SExt:
1157 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1159 case CCValAssign::ZExt:
1160 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1162 case CCValAssign::AExt:
1163 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1167 // Arguments that can be passed on register must be kept at
1168 // RegsToPass vector
1169 if (VA.isRegLoc()) {
1170 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1172 assert(VA.isMemLoc());
1174 int Offset = VA.getLocMemOffset();
1176 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
1178 DAG.getConstant(Offset/4, MVT::i32)));
1182 // Transform all store nodes into one single node because
1183 // all store nodes are independent of each other.
1184 if (!MemOpChains.empty())
1185 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1187 // Build a sequence of copy-to-reg nodes chained together with token
1188 // chain and flag operands which copy the outgoing args into registers.
1189 // The InFlag in necessary since all emitted instructions must be
1192 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1193 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1194 RegsToPass[i].second, InFlag);
1195 InFlag = Chain.getValue(1);
1198 // If the callee is a GlobalAddress node (quite common, every direct call is)
1199 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1200 // Likewise ExternalSymbol -> TargetExternalSymbol.
1201 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1202 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
1203 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
1204 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
1206 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
1207 // = Chain, Callee, Reg#1, Reg#2, ...
1209 // Returns a chain & a flag for retval copy to use.
1210 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1211 SmallVector<SDValue, 8> Ops;
1212 Ops.push_back(Chain);
1213 Ops.push_back(Callee);
1215 // Add argument registers to the end of the list so that they are
1216 // known live into the call.
1217 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1218 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1219 RegsToPass[i].second.getValueType()));
1221 if (InFlag.getNode())
1222 Ops.push_back(InFlag);
1224 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, Ops);
1225 InFlag = Chain.getValue(1);
1227 // Create the CALLSEQ_END node.
1228 Chain = DAG.getCALLSEQ_END(Chain,
1229 DAG.getConstant(NumBytes, getPointerTy(), true),
1230 DAG.getConstant(0, getPointerTy(), true),
1232 InFlag = Chain.getValue(1);
1234 // Handle result values, copying them out of physregs into vregs that we
1236 return LowerCallResult(Chain, InFlag, RVLocs, dl, DAG, InVals);
1239 //===----------------------------------------------------------------------===//
1240 // Formal Arguments Calling Convention Implementation
1241 //===----------------------------------------------------------------------===//
1244 struct ArgDataPair { SDValue SDV; ISD::ArgFlagsTy Flags; };
1247 /// XCore formal arguments implementation
1249 XCoreTargetLowering::LowerFormalArguments(SDValue Chain,
1250 CallingConv::ID CallConv,
1252 const SmallVectorImpl<ISD::InputArg> &Ins,
1255 SmallVectorImpl<SDValue> &InVals)
1260 llvm_unreachable("Unsupported calling convention");
1261 case CallingConv::C:
1262 case CallingConv::Fast:
1263 return LowerCCCArguments(Chain, CallConv, isVarArg,
1264 Ins, dl, DAG, InVals);
1268 /// LowerCCCArguments - transform physical registers into
1269 /// virtual registers and generate load operations for
1270 /// arguments places on the stack.
1273 XCoreTargetLowering::LowerCCCArguments(SDValue Chain,
1274 CallingConv::ID CallConv,
1276 const SmallVectorImpl<ISD::InputArg>
1280 SmallVectorImpl<SDValue> &InVals) const {
1281 MachineFunction &MF = DAG.getMachineFunction();
1282 MachineFrameInfo *MFI = MF.getFrameInfo();
1283 MachineRegisterInfo &RegInfo = MF.getRegInfo();
1284 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1286 // Assign locations to all of the incoming arguments.
1287 SmallVector<CCValAssign, 16> ArgLocs;
1288 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1289 getTargetMachine(), ArgLocs, *DAG.getContext());
1291 CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
1293 unsigned StackSlotSize = XCoreFrameLowering::stackSlotSize();
1295 unsigned LRSaveSize = StackSlotSize;
1298 XFI->setReturnStackOffset(CCInfo.getNextStackOffset() + LRSaveSize);
1300 // All getCopyFromReg ops must precede any getMemcpys to prevent the
1301 // scheduler clobbering a register before it has been copied.
1303 // 1. CopyFromReg (and load) arg & vararg registers.
1304 // 2. Chain CopyFromReg nodes into a TokenFactor.
1305 // 3. Memcpy 'byVal' args & push final InVals.
1306 // 4. Chain mem ops nodes into a TokenFactor.
1307 SmallVector<SDValue, 4> CFRegNode;
1308 SmallVector<ArgDataPair, 4> ArgData;
1309 SmallVector<SDValue, 4> MemOps;
1311 // 1a. CopyFromReg (and load) arg registers.
1312 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1314 CCValAssign &VA = ArgLocs[i];
1317 if (VA.isRegLoc()) {
1318 // Arguments passed in registers
1319 EVT RegVT = VA.getLocVT();
1320 switch (RegVT.getSimpleVT().SimpleTy) {
1324 errs() << "LowerFormalArguments Unhandled argument type: "
1325 << RegVT.getSimpleVT().SimpleTy << "\n";
1327 llvm_unreachable(nullptr);
1330 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1331 RegInfo.addLiveIn(VA.getLocReg(), VReg);
1332 ArgIn = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
1333 CFRegNode.push_back(ArgIn.getValue(ArgIn->getNumValues() - 1));
1337 assert(VA.isMemLoc());
1338 // Load the argument to a virtual register
1339 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
1340 if (ObjSize > StackSlotSize) {
1341 errs() << "LowerFormalArguments Unhandled argument type: "
1342 << EVT(VA.getLocVT()).getEVTString()
1345 // Create the frame index object for this incoming parameter...
1346 int FI = MFI->CreateFixedObject(ObjSize,
1347 LRSaveSize + VA.getLocMemOffset(),
1350 // Create the SelectionDAG nodes corresponding to a load
1351 //from this parameter
1352 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1353 ArgIn = DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
1354 MachinePointerInfo::getFixedStack(FI),
1355 false, false, false, 0);
1357 const ArgDataPair ADP = { ArgIn, Ins[i].Flags };
1358 ArgData.push_back(ADP);
1361 // 1b. CopyFromReg vararg registers.
1363 // Argument registers
1364 static const MCPhysReg ArgRegs[] = {
1365 XCore::R0, XCore::R1, XCore::R2, XCore::R3
1367 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1368 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
1369 array_lengthof(ArgRegs));
1370 if (FirstVAReg < array_lengthof(ArgRegs)) {
1372 // Save remaining registers, storing higher register numbers at a higher
1374 for (int i = array_lengthof(ArgRegs) - 1; i >= (int)FirstVAReg; --i) {
1375 // Create a stack slot
1376 int FI = MFI->CreateFixedObject(4, offset, true);
1377 if (i == (int)FirstVAReg) {
1378 XFI->setVarArgsFrameIndex(FI);
1380 offset -= StackSlotSize;
1381 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1382 // Move argument from phys reg -> virt reg
1383 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1384 RegInfo.addLiveIn(ArgRegs[i], VReg);
1385 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1386 CFRegNode.push_back(Val.getValue(Val->getNumValues() - 1));
1387 // Move argument from virt reg -> stack
1388 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
1389 MachinePointerInfo(), false, false, 0);
1390 MemOps.push_back(Store);
1393 // This will point to the next argument passed via stack.
1394 XFI->setVarArgsFrameIndex(
1395 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset(),
1400 // 2. chain CopyFromReg nodes into a TokenFactor.
1401 if (!CFRegNode.empty())
1402 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, CFRegNode);
1404 // 3. Memcpy 'byVal' args & push final InVals.
1405 // Aggregates passed "byVal" need to be copied by the callee.
1406 // The callee will use a pointer to this copy, rather than the original
1408 for (SmallVectorImpl<ArgDataPair>::const_iterator ArgDI = ArgData.begin(),
1409 ArgDE = ArgData.end();
1410 ArgDI != ArgDE; ++ArgDI) {
1411 if (ArgDI->Flags.isByVal() && ArgDI->Flags.getByValSize()) {
1412 unsigned Size = ArgDI->Flags.getByValSize();
1413 unsigned Align = std::max(StackSlotSize, ArgDI->Flags.getByValAlign());
1414 // Create a new object on the stack and copy the pointee into it.
1415 int FI = MFI->CreateStackObject(Size, Align, false);
1416 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1417 InVals.push_back(FIN);
1418 MemOps.push_back(DAG.getMemcpy(Chain, dl, FIN, ArgDI->SDV,
1419 DAG.getConstant(Size, MVT::i32),
1420 Align, false, false,
1421 MachinePointerInfo(),
1422 MachinePointerInfo()));
1424 InVals.push_back(ArgDI->SDV);
1428 // 4, chain mem ops nodes into a TokenFactor.
1429 if (!MemOps.empty()) {
1430 MemOps.push_back(Chain);
1431 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
1437 //===----------------------------------------------------------------------===//
1438 // Return Value Calling Convention Implementation
1439 //===----------------------------------------------------------------------===//
1441 bool XCoreTargetLowering::
1442 CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF,
1444 const SmallVectorImpl<ISD::OutputArg> &Outs,
1445 LLVMContext &Context) const {
1446 SmallVector<CCValAssign, 16> RVLocs;
1447 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
1448 if (!CCInfo.CheckReturn(Outs, RetCC_XCore))
1450 if (CCInfo.getNextStackOffset() != 0 && isVarArg)
1456 XCoreTargetLowering::LowerReturn(SDValue Chain,
1457 CallingConv::ID CallConv, bool isVarArg,
1458 const SmallVectorImpl<ISD::OutputArg> &Outs,
1459 const SmallVectorImpl<SDValue> &OutVals,
1460 SDLoc dl, SelectionDAG &DAG) const {
1462 XCoreFunctionInfo *XFI =
1463 DAG.getMachineFunction().getInfo<XCoreFunctionInfo>();
1464 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1466 // CCValAssign - represent the assignment of
1467 // the return value to a location
1468 SmallVector<CCValAssign, 16> RVLocs;
1470 // CCState - Info about the registers and stack slot.
1471 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1472 getTargetMachine(), RVLocs, *DAG.getContext());
1474 // Analyze return values.
1476 CCInfo.AllocateStack(XFI->getReturnStackOffset(), 4);
1478 CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
1481 SmallVector<SDValue, 4> RetOps(1, Chain);
1483 // Return on XCore is always a "retsp 0"
1484 RetOps.push_back(DAG.getConstant(0, MVT::i32));
1486 SmallVector<SDValue, 4> MemOpChains;
1487 // Handle return values that must be copied to memory.
1488 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1489 CCValAssign &VA = RVLocs[i];
1492 assert(VA.isMemLoc());
1494 report_fatal_error("Can't return value from vararg function in memory");
1497 int Offset = VA.getLocMemOffset();
1498 unsigned ObjSize = VA.getLocVT().getSizeInBits() / 8;
1499 // Create the frame index object for the memory location.
1500 int FI = MFI->CreateFixedObject(ObjSize, Offset, false);
1502 // Create a SelectionDAG node corresponding to a store
1503 // to this memory location.
1504 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1505 MemOpChains.push_back(DAG.getStore(Chain, dl, OutVals[i], FIN,
1506 MachinePointerInfo::getFixedStack(FI), false, false,
1510 // Transform all store nodes into one single node because
1511 // all stores are independent of each other.
1512 if (!MemOpChains.empty())
1513 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1515 // Now handle return values copied to registers.
1516 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1517 CCValAssign &VA = RVLocs[i];
1520 // Copy the result values into the output registers.
1521 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
1523 // guarantee that all emitted copies are
1524 // stuck together, avoiding something bad
1525 Flag = Chain.getValue(1);
1526 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1529 RetOps[0] = Chain; // Update chain.
1531 // Add the flag if we have it.
1533 RetOps.push_back(Flag);
1535 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other, RetOps);
1538 //===----------------------------------------------------------------------===//
1539 // Other Lowering Code
1540 //===----------------------------------------------------------------------===//
1543 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1544 MachineBasicBlock *BB) const {
1545 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1546 DebugLoc dl = MI->getDebugLoc();
1547 assert((MI->getOpcode() == XCore::SELECT_CC) &&
1548 "Unexpected instr type to insert");
1550 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1551 // control-flow pattern. The incoming instruction knows the destination vreg
1552 // to set, the condition code register to branch on, the true/false values to
1553 // select between, and a branch opcode to use.
1554 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1555 MachineFunction::iterator It = BB;
1561 // cmpTY ccX, r1, r2
1563 // fallthrough --> copy0MBB
1564 MachineBasicBlock *thisMBB = BB;
1565 MachineFunction *F = BB->getParent();
1566 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1567 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1568 F->insert(It, copy0MBB);
1569 F->insert(It, sinkMBB);
1571 // Transfer the remainder of BB and its successor edges to sinkMBB.
1572 sinkMBB->splice(sinkMBB->begin(), BB,
1573 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1574 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1576 // Next, add the true and fallthrough blocks as its successors.
1577 BB->addSuccessor(copy0MBB);
1578 BB->addSuccessor(sinkMBB);
1580 BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1581 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1584 // %FalseValue = ...
1585 // # fallthrough to sinkMBB
1588 // Update machine-CFG edges
1589 BB->addSuccessor(sinkMBB);
1592 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1595 BuildMI(*BB, BB->begin(), dl,
1596 TII.get(XCore::PHI), MI->getOperand(0).getReg())
1597 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1598 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1600 MI->eraseFromParent(); // The pseudo instruction is gone now.
1604 //===----------------------------------------------------------------------===//
1605 // Target Optimization Hooks
1606 //===----------------------------------------------------------------------===//
1608 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1609 DAGCombinerInfo &DCI) const {
1610 SelectionDAG &DAG = DCI.DAG;
1612 switch (N->getOpcode()) {
1614 case ISD::INTRINSIC_VOID:
1615 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
1616 case Intrinsic::xcore_outt:
1617 case Intrinsic::xcore_outct:
1618 case Intrinsic::xcore_chkct: {
1619 SDValue OutVal = N->getOperand(3);
1620 // These instructions ignore the high bits.
1621 if (OutVal.hasOneUse()) {
1622 unsigned BitWidth = OutVal.getValueSizeInBits();
1623 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8);
1624 APInt KnownZero, KnownOne;
1625 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1626 !DCI.isBeforeLegalizeOps());
1627 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1628 if (TLO.ShrinkDemandedConstant(OutVal, DemandedMask) ||
1629 TLI.SimplifyDemandedBits(OutVal, DemandedMask, KnownZero, KnownOne,
1631 DCI.CommitTargetLoweringOpt(TLO);
1635 case Intrinsic::xcore_setpt: {
1636 SDValue Time = N->getOperand(3);
1637 // This instruction ignores the high bits.
1638 if (Time.hasOneUse()) {
1639 unsigned BitWidth = Time.getValueSizeInBits();
1640 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
1641 APInt KnownZero, KnownOne;
1642 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1643 !DCI.isBeforeLegalizeOps());
1644 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1645 if (TLO.ShrinkDemandedConstant(Time, DemandedMask) ||
1646 TLI.SimplifyDemandedBits(Time, DemandedMask, KnownZero, KnownOne,
1648 DCI.CommitTargetLoweringOpt(TLO);
1654 case XCoreISD::LADD: {
1655 SDValue N0 = N->getOperand(0);
1656 SDValue N1 = N->getOperand(1);
1657 SDValue N2 = N->getOperand(2);
1658 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1659 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1660 EVT VT = N0.getValueType();
1662 // canonicalize constant to RHS
1664 return DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N1, N0, N2);
1666 // fold (ladd 0, 0, x) -> 0, x & 1
1667 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1668 SDValue Carry = DAG.getConstant(0, VT);
1669 SDValue Result = DAG.getNode(ISD::AND, dl, VT, N2,
1670 DAG.getConstant(1, VT));
1671 SDValue Ops[] = { Result, Carry };
1672 return DAG.getMergeValues(Ops, dl);
1675 // fold (ladd x, 0, y) -> 0, add x, y iff carry is unused and y has only the
1677 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1678 APInt KnownZero, KnownOne;
1679 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1680 VT.getSizeInBits() - 1);
1681 DAG.computeKnownBits(N2, KnownZero, KnownOne);
1682 if ((KnownZero & Mask) == Mask) {
1683 SDValue Carry = DAG.getConstant(0, VT);
1684 SDValue Result = DAG.getNode(ISD::ADD, dl, VT, N0, N2);
1685 SDValue Ops[] = { Result, Carry };
1686 return DAG.getMergeValues(Ops, dl);
1691 case XCoreISD::LSUB: {
1692 SDValue N0 = N->getOperand(0);
1693 SDValue N1 = N->getOperand(1);
1694 SDValue N2 = N->getOperand(2);
1695 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1696 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1697 EVT VT = N0.getValueType();
1699 // fold (lsub 0, 0, x) -> x, -x iff x has only the low bit set
1700 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1701 APInt KnownZero, KnownOne;
1702 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1703 VT.getSizeInBits() - 1);
1704 DAG.computeKnownBits(N2, KnownZero, KnownOne);
1705 if ((KnownZero & Mask) == Mask) {
1706 SDValue Borrow = N2;
1707 SDValue Result = DAG.getNode(ISD::SUB, dl, VT,
1708 DAG.getConstant(0, VT), N2);
1709 SDValue Ops[] = { Result, Borrow };
1710 return DAG.getMergeValues(Ops, dl);
1714 // fold (lsub x, 0, y) -> 0, sub x, y iff borrow is unused and y has only the
1716 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1717 APInt KnownZero, KnownOne;
1718 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1719 VT.getSizeInBits() - 1);
1720 DAG.computeKnownBits(N2, KnownZero, KnownOne);
1721 if ((KnownZero & Mask) == Mask) {
1722 SDValue Borrow = DAG.getConstant(0, VT);
1723 SDValue Result = DAG.getNode(ISD::SUB, dl, VT, N0, N2);
1724 SDValue Ops[] = { Result, Borrow };
1725 return DAG.getMergeValues(Ops, dl);
1730 case XCoreISD::LMUL: {
1731 SDValue N0 = N->getOperand(0);
1732 SDValue N1 = N->getOperand(1);
1733 SDValue N2 = N->getOperand(2);
1734 SDValue N3 = N->getOperand(3);
1735 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1736 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1737 EVT VT = N0.getValueType();
1738 // Canonicalize multiplicative constant to RHS. If both multiplicative
1739 // operands are constant canonicalize smallest to RHS.
1740 if ((N0C && !N1C) ||
1741 (N0C && N1C && N0C->getZExtValue() < N1C->getZExtValue()))
1742 return DAG.getNode(XCoreISD::LMUL, dl, DAG.getVTList(VT, VT),
1746 if (N1C && N1C->isNullValue()) {
1747 // If the high result is unused fold to add(a, b)
1748 if (N->hasNUsesOfValue(0, 0)) {
1749 SDValue Lo = DAG.getNode(ISD::ADD, dl, VT, N2, N3);
1750 SDValue Ops[] = { Lo, Lo };
1751 return DAG.getMergeValues(Ops, dl);
1753 // Otherwise fold to ladd(a, b, 0)
1755 DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N2, N3, N1);
1756 SDValue Carry(Result.getNode(), 1);
1757 SDValue Ops[] = { Carry, Result };
1758 return DAG.getMergeValues(Ops, dl);
1763 // Fold 32 bit expressions such as add(add(mul(x,y),a),b) ->
1764 // lmul(x, y, a, b). The high result of lmul will be ignored.
1765 // This is only profitable if the intermediate results are unused
1767 SDValue Mul0, Mul1, Addend0, Addend1;
1768 if (N->getValueType(0) == MVT::i32 &&
1769 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, true)) {
1770 SDValue Ignored = DAG.getNode(XCoreISD::LMUL, dl,
1771 DAG.getVTList(MVT::i32, MVT::i32), Mul0,
1772 Mul1, Addend0, Addend1);
1773 SDValue Result(Ignored.getNode(), 1);
1776 APInt HighMask = APInt::getHighBitsSet(64, 32);
1777 // Fold 64 bit expression such as add(add(mul(x,y),a),b) ->
1778 // lmul(x, y, a, b) if all operands are zero-extended. We do this
1779 // before type legalization as it is messy to match the operands after
1781 if (N->getValueType(0) == MVT::i64 &&
1782 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, false) &&
1783 DAG.MaskedValueIsZero(Mul0, HighMask) &&
1784 DAG.MaskedValueIsZero(Mul1, HighMask) &&
1785 DAG.MaskedValueIsZero(Addend0, HighMask) &&
1786 DAG.MaskedValueIsZero(Addend1, HighMask)) {
1787 SDValue Mul0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1788 Mul0, DAG.getConstant(0, MVT::i32));
1789 SDValue Mul1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1790 Mul1, DAG.getConstant(0, MVT::i32));
1791 SDValue Addend0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1792 Addend0, DAG.getConstant(0, MVT::i32));
1793 SDValue Addend1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1794 Addend1, DAG.getConstant(0, MVT::i32));
1795 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
1796 DAG.getVTList(MVT::i32, MVT::i32), Mul0L, Mul1L,
1797 Addend0L, Addend1L);
1798 SDValue Lo(Hi.getNode(), 1);
1799 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
1804 // Replace unaligned store of unaligned load with memmove.
1805 StoreSDNode *ST = cast<StoreSDNode>(N);
1806 if (!DCI.isBeforeLegalize() ||
1807 allowsUnalignedMemoryAccesses(ST->getMemoryVT()) ||
1808 ST->isVolatile() || ST->isIndexed()) {
1811 SDValue Chain = ST->getChain();
1813 unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1814 if (StoreBits % 8) {
1817 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(
1818 ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1819 unsigned Alignment = ST->getAlignment();
1820 if (Alignment >= ABIAlignment) {
1824 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1825 if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1826 LD->getAlignment() == Alignment &&
1827 !LD->isVolatile() && !LD->isIndexed() &&
1828 Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1829 return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1831 DAG.getConstant(StoreBits/8, MVT::i32),
1832 Alignment, false, ST->getPointerInfo(),
1833 LD->getPointerInfo());
1842 void XCoreTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
1845 const SelectionDAG &DAG,
1846 unsigned Depth) const {
1847 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
1848 switch (Op.getOpcode()) {
1850 case XCoreISD::LADD:
1851 case XCoreISD::LSUB:
1852 if (Op.getResNo() == 1) {
1853 // Top bits of carry / borrow are clear.
1854 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1855 KnownZero.getBitWidth() - 1);
1858 case ISD::INTRINSIC_W_CHAIN:
1860 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1862 case Intrinsic::xcore_getts:
1863 // High bits are known to be zero.
1864 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1865 KnownZero.getBitWidth() - 16);
1867 case Intrinsic::xcore_int:
1868 case Intrinsic::xcore_inct:
1869 // High bits are known to be zero.
1870 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1871 KnownZero.getBitWidth() - 8);
1873 case Intrinsic::xcore_testct:
1874 // Result is either 0 or 1.
1875 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1876 KnownZero.getBitWidth() - 1);
1878 case Intrinsic::xcore_testwct:
1879 // Result is in the range 0 - 4.
1880 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1881 KnownZero.getBitWidth() - 3);
1889 //===----------------------------------------------------------------------===//
1890 // Addressing mode description hooks
1891 //===----------------------------------------------------------------------===//
1893 static inline bool isImmUs(int64_t val)
1895 return (val >= 0 && val <= 11);
1898 static inline bool isImmUs2(int64_t val)
1900 return (val%2 == 0 && isImmUs(val/2));
1903 static inline bool isImmUs4(int64_t val)
1905 return (val%4 == 0 && isImmUs(val/4));
1908 /// isLegalAddressingMode - Return true if the addressing mode represented
1909 /// by AM is legal for this target, for a load/store of the specified type.
1911 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1913 if (Ty->getTypeID() == Type::VoidTyID)
1914 return AM.Scale == 0 && isImmUs(AM.BaseOffs) && isImmUs4(AM.BaseOffs);
1916 const DataLayout *TD = TM.getDataLayout();
1917 unsigned Size = TD->getTypeAllocSize(Ty);
1919 return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1926 if (AM.Scale == 0) {
1927 return isImmUs(AM.BaseOffs);
1930 return AM.Scale == 1 && AM.BaseOffs == 0;
1934 if (AM.Scale == 0) {
1935 return isImmUs2(AM.BaseOffs);
1938 return AM.Scale == 2 && AM.BaseOffs == 0;
1941 if (AM.Scale == 0) {
1942 return isImmUs4(AM.BaseOffs);
1945 return AM.Scale == 4 && AM.BaseOffs == 0;
1949 //===----------------------------------------------------------------------===//
1950 // XCore Inline Assembly Support
1951 //===----------------------------------------------------------------------===//
1953 std::pair<unsigned, const TargetRegisterClass*>
1954 XCoreTargetLowering::
1955 getRegForInlineAsmConstraint(const std::string &Constraint,
1957 if (Constraint.size() == 1) {
1958 switch (Constraint[0]) {
1961 return std::make_pair(0U, &XCore::GRRegsRegClass);
1964 // Use the default implementation in TargetLowering to convert the register
1965 // constraint into a member of a register class.
1966 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);