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(const TargetMachine &TM)
72 : TargetLowering(TM, new XCoreTargetObjectFile()), TM(TM),
73 Subtarget(TM.getSubtarget<XCoreSubtarget>()) {
75 // Set up the register classes.
76 addRegisterClass(MVT::i32, &XCore::GRRegsRegClass);
78 // Compute derived properties from the register classes
79 computeRegisterProperties();
81 // Division is expensive
82 setIntDivIsCheap(false);
84 setStackPointerRegisterToSaveRestore(XCore::SP);
86 setSchedulingPreference(Sched::Source);
88 // Use i32 for setcc operations results (slt, sgt, ...).
89 setBooleanContents(ZeroOrOneBooleanContent);
90 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
92 // XCore does not have the NodeTypes below.
93 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
94 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
95 setOperationAction(ISD::ADDC, MVT::i32, Expand);
96 setOperationAction(ISD::ADDE, MVT::i32, Expand);
97 setOperationAction(ISD::SUBC, MVT::i32, Expand);
98 setOperationAction(ISD::SUBE, MVT::i32, Expand);
101 setOperationAction(ISD::ADD, MVT::i64, Custom);
102 setOperationAction(ISD::SUB, MVT::i64, Custom);
103 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
104 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
105 setOperationAction(ISD::MULHS, MVT::i32, Expand);
106 setOperationAction(ISD::MULHU, MVT::i32, Expand);
107 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
108 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
109 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
112 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
113 setOperationAction(ISD::ROTL , MVT::i32, Expand);
114 setOperationAction(ISD::ROTR , MVT::i32, Expand);
115 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
116 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
118 setOperationAction(ISD::TRAP, MVT::Other, Legal);
121 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
123 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
124 setOperationAction(ISD::BlockAddress, 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 // Exception handling
153 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
154 setExceptionPointerRegister(XCore::R0);
155 setExceptionSelectorRegister(XCore::R1);
156 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
159 // We request a fence for ATOMIC_* instructions, to reduce them to Monotonic.
160 // As we are always Sequential Consistent, an ATOMIC_FENCE becomes a no OP.
161 setInsertFencesForAtomic(true);
162 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
163 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
164 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
166 // TRAMPOLINE is custom lowered.
167 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
168 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
170 // We want to custom lower some of our intrinsics.
171 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
173 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 4;
174 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize
175 = MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 2;
177 // We have target-specific dag combine patterns for the following nodes:
178 setTargetDAGCombine(ISD::STORE);
179 setTargetDAGCombine(ISD::ADD);
180 setTargetDAGCombine(ISD::INTRINSIC_VOID);
181 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
183 setMinFunctionAlignment(1);
184 setPrefFunctionAlignment(2);
187 bool XCoreTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
188 if (Val.getOpcode() != ISD::LOAD)
191 EVT VT1 = Val.getValueType();
192 if (!VT1.isSimple() || !VT1.isInteger() ||
193 !VT2.isSimple() || !VT2.isInteger())
196 switch (VT1.getSimpleVT().SimpleTy) {
205 SDValue XCoreTargetLowering::
206 LowerOperation(SDValue Op, SelectionDAG &DAG) const {
207 switch (Op.getOpcode())
209 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
210 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
211 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
212 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
213 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
214 case ISD::LOAD: return LowerLOAD(Op, DAG);
215 case ISD::STORE: return LowerSTORE(Op, DAG);
216 case ISD::VAARG: return LowerVAARG(Op, DAG);
217 case ISD::VASTART: return LowerVASTART(Op, DAG);
218 case ISD::SMUL_LOHI: return LowerSMUL_LOHI(Op, DAG);
219 case ISD::UMUL_LOHI: return LowerUMUL_LOHI(Op, DAG);
220 // FIXME: Remove these when LegalizeDAGTypes lands.
222 case ISD::SUB: return ExpandADDSUB(Op.getNode(), DAG);
223 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
224 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
225 case ISD::FRAME_TO_ARGS_OFFSET: return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
226 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
227 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
228 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
229 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
230 case ISD::ATOMIC_LOAD: return LowerATOMIC_LOAD(Op, DAG);
231 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op, DAG);
233 llvm_unreachable("unimplemented operand");
237 /// ReplaceNodeResults - Replace the results of node with an illegal result
238 /// type with new values built out of custom code.
239 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
240 SmallVectorImpl<SDValue>&Results,
241 SelectionDAG &DAG) const {
242 switch (N->getOpcode()) {
244 llvm_unreachable("Don't know how to custom expand this!");
247 Results.push_back(ExpandADDSUB(N, DAG));
252 //===----------------------------------------------------------------------===//
253 // Misc Lower Operation implementation
254 //===----------------------------------------------------------------------===//
256 SDValue XCoreTargetLowering::getGlobalAddressWrapper(SDValue GA,
257 const GlobalValue *GV,
258 SelectionDAG &DAG) const {
259 // FIXME there is no actual debug info here
262 if (GV->getType()->getElementType()->isFunctionTy())
263 return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
265 const auto *GVar = dyn_cast<GlobalVariable>(GV);
266 if ((GV->hasSection() && StringRef(GV->getSection()).startswith(".cp.")) ||
267 (GVar && GVar->isConstant() && GV->hasLocalLinkage()))
268 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
270 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
273 static bool IsSmallObject(const GlobalValue *GV, const XCoreTargetLowering &XTL) {
274 if (XTL.getTargetMachine().getCodeModel() == CodeModel::Small)
277 Type *ObjType = GV->getType()->getPointerElementType();
278 if (!ObjType->isSized())
281 unsigned ObjSize = XTL.getDataLayout()->getTypeAllocSize(ObjType);
282 return ObjSize < CodeModelLargeSize && ObjSize != 0;
285 SDValue XCoreTargetLowering::
286 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const
288 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
289 const GlobalValue *GV = GN->getGlobal();
291 int64_t Offset = GN->getOffset();
292 if (IsSmallObject(GV, *this)) {
293 // We can only fold positive offsets that are a multiple of the word size.
294 int64_t FoldedOffset = std::max(Offset & ~3, (int64_t)0);
295 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, FoldedOffset);
296 GA = getGlobalAddressWrapper(GA, GV, DAG);
297 // Handle the rest of the offset.
298 if (Offset != FoldedOffset) {
299 SDValue Remaining = DAG.getConstant(Offset - FoldedOffset, MVT::i32);
300 GA = DAG.getNode(ISD::ADD, DL, MVT::i32, GA, Remaining);
304 // Ideally we would not fold in offset with an index <= 11.
305 Type *Ty = Type::getInt8PtrTy(*DAG.getContext());
306 Constant *GA = ConstantExpr::getBitCast(const_cast<GlobalValue*>(GV), Ty);
307 Ty = Type::getInt32Ty(*DAG.getContext());
308 Constant *Idx = ConstantInt::get(Ty, Offset);
309 Constant *GAI = ConstantExpr::getGetElementPtr(GA, Idx);
310 SDValue CP = DAG.getConstantPool(GAI, MVT::i32);
311 return DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), CP,
312 MachinePointerInfo(), false, false, false, 0);
316 SDValue XCoreTargetLowering::
317 LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const
321 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
322 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy());
324 return DAG.getNode(XCoreISD::PCRelativeWrapper, DL, getPointerTy(), Result);
327 SDValue XCoreTargetLowering::
328 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
330 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
331 // FIXME there isn't really debug info here
333 EVT PtrVT = Op.getValueType();
335 if (CP->isMachineConstantPoolEntry()) {
336 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
337 CP->getAlignment(), CP->getOffset());
339 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
340 CP->getAlignment(), CP->getOffset());
342 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
345 unsigned XCoreTargetLowering::getJumpTableEncoding() const {
346 return MachineJumpTableInfo::EK_Inline;
349 SDValue XCoreTargetLowering::
350 LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
352 SDValue Chain = Op.getOperand(0);
353 SDValue Table = Op.getOperand(1);
354 SDValue Index = Op.getOperand(2);
356 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
357 unsigned JTI = JT->getIndex();
358 MachineFunction &MF = DAG.getMachineFunction();
359 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
360 SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
362 unsigned NumEntries = MJTI->getJumpTables()[JTI].MBBs.size();
363 if (NumEntries <= 32) {
364 return DAG.getNode(XCoreISD::BR_JT, dl, MVT::Other, Chain, TargetJT, Index);
366 assert((NumEntries >> 31) == 0);
367 SDValue ScaledIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
368 DAG.getConstant(1, MVT::i32));
369 return DAG.getNode(XCoreISD::BR_JT32, dl, MVT::Other, Chain, TargetJT,
373 SDValue XCoreTargetLowering::
374 lowerLoadWordFromAlignedBasePlusOffset(SDLoc DL, SDValue Chain, SDValue Base,
375 int64_t Offset, SelectionDAG &DAG) const
377 if ((Offset & 0x3) == 0) {
378 return DAG.getLoad(getPointerTy(), DL, Chain, Base, MachinePointerInfo(),
379 false, false, false, 0);
381 // Lower to pair of consecutive word aligned loads plus some bit shifting.
382 int32_t HighOffset = RoundUpToAlignment(Offset, 4);
383 int32_t LowOffset = HighOffset - 4;
384 SDValue LowAddr, HighAddr;
385 if (GlobalAddressSDNode *GASD =
386 dyn_cast<GlobalAddressSDNode>(Base.getNode())) {
387 LowAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
389 HighAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
392 LowAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
393 DAG.getConstant(LowOffset, MVT::i32));
394 HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
395 DAG.getConstant(HighOffset, MVT::i32));
397 SDValue LowShift = DAG.getConstant((Offset - LowOffset) * 8, MVT::i32);
398 SDValue HighShift = DAG.getConstant((HighOffset - Offset) * 8, MVT::i32);
400 SDValue Low = DAG.getLoad(getPointerTy(), DL, Chain,
401 LowAddr, MachinePointerInfo(),
402 false, false, false, 0);
403 SDValue High = DAG.getLoad(getPointerTy(), DL, Chain,
404 HighAddr, MachinePointerInfo(),
405 false, false, false, 0);
406 SDValue LowShifted = DAG.getNode(ISD::SRL, DL, MVT::i32, Low, LowShift);
407 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High, HighShift);
408 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, LowShifted, HighShifted);
409 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
411 SDValue Ops[] = { Result, Chain };
412 return DAG.getMergeValues(Ops, DL);
415 static bool isWordAligned(SDValue Value, SelectionDAG &DAG)
417 APInt KnownZero, KnownOne;
418 DAG.computeKnownBits(Value, KnownZero, KnownOne);
419 return KnownZero.countTrailingOnes() >= 2;
422 SDValue XCoreTargetLowering::
423 LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
424 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
425 LoadSDNode *LD = cast<LoadSDNode>(Op);
426 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
427 "Unexpected extension type");
428 assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
429 if (allowsMisalignedMemoryAccesses(LD->getMemoryVT(),
430 LD->getAddressSpace(),
434 unsigned ABIAlignment = getDataLayout()->
435 getABITypeAlignment(LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
436 // Leave aligned load alone.
437 if (LD->getAlignment() >= ABIAlignment)
440 SDValue Chain = LD->getChain();
441 SDValue BasePtr = LD->getBasePtr();
444 if (!LD->isVolatile()) {
445 const GlobalValue *GV;
447 if (DAG.isBaseWithConstantOffset(BasePtr) &&
448 isWordAligned(BasePtr->getOperand(0), DAG)) {
449 SDValue NewBasePtr = BasePtr->getOperand(0);
450 Offset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
451 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
454 if (TLI.isGAPlusOffset(BasePtr.getNode(), GV, Offset) &&
455 MinAlign(GV->getAlignment(), 4) == 4) {
456 SDValue NewBasePtr = DAG.getGlobalAddress(GV, DL,
457 BasePtr->getValueType(0));
458 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
463 if (LD->getAlignment() == 2) {
464 SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, DL, MVT::i32, Chain,
465 BasePtr, LD->getPointerInfo(), MVT::i16,
466 LD->isVolatile(), LD->isNonTemporal(),
467 LD->isInvariant(), 2);
468 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
469 DAG.getConstant(2, MVT::i32));
470 SDValue High = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
472 LD->getPointerInfo().getWithOffset(2),
473 MVT::i16, LD->isVolatile(),
474 LD->isNonTemporal(), LD->isInvariant(), 2);
475 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High,
476 DAG.getConstant(16, MVT::i32));
477 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Low, HighShifted);
478 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
480 SDValue Ops[] = { Result, Chain };
481 return DAG.getMergeValues(Ops, DL);
484 // Lower to a call to __misaligned_load(BasePtr).
485 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
486 TargetLowering::ArgListTy Args;
487 TargetLowering::ArgListEntry Entry;
490 Entry.Node = BasePtr;
491 Args.push_back(Entry);
493 TargetLowering::CallLoweringInfo CLI(DAG);
494 CLI.setDebugLoc(DL).setChain(Chain)
495 .setCallee(CallingConv::C, IntPtrTy,
496 DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
499 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
500 SDValue Ops[] = { CallResult.first, CallResult.second };
501 return DAG.getMergeValues(Ops, DL);
504 SDValue XCoreTargetLowering::
505 LowerSTORE(SDValue Op, SelectionDAG &DAG) const
507 StoreSDNode *ST = cast<StoreSDNode>(Op);
508 assert(!ST->isTruncatingStore() && "Unexpected store type");
509 assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
510 if (allowsMisalignedMemoryAccesses(ST->getMemoryVT(),
511 ST->getAddressSpace(),
512 ST->getAlignment())) {
515 unsigned ABIAlignment = getDataLayout()->
516 getABITypeAlignment(ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
517 // Leave aligned store alone.
518 if (ST->getAlignment() >= ABIAlignment) {
521 SDValue Chain = ST->getChain();
522 SDValue BasePtr = ST->getBasePtr();
523 SDValue Value = ST->getValue();
526 if (ST->getAlignment() == 2) {
528 SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
529 DAG.getConstant(16, MVT::i32));
530 SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
531 ST->getPointerInfo(), MVT::i16,
532 ST->isVolatile(), ST->isNonTemporal(),
534 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
535 DAG.getConstant(2, MVT::i32));
536 SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
537 ST->getPointerInfo().getWithOffset(2),
538 MVT::i16, ST->isVolatile(),
539 ST->isNonTemporal(), 2);
540 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
543 // Lower to a call to __misaligned_store(BasePtr, Value).
544 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
545 TargetLowering::ArgListTy Args;
546 TargetLowering::ArgListEntry Entry;
549 Entry.Node = BasePtr;
550 Args.push_back(Entry);
553 Args.push_back(Entry);
555 TargetLowering::CallLoweringInfo CLI(DAG);
556 CLI.setDebugLoc(dl).setChain(Chain)
557 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
558 DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
561 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
562 return CallResult.second;
565 SDValue XCoreTargetLowering::
566 LowerSMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
568 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::SMUL_LOHI &&
569 "Unexpected operand to lower!");
571 SDValue LHS = Op.getOperand(0);
572 SDValue RHS = Op.getOperand(1);
573 SDValue Zero = DAG.getConstant(0, MVT::i32);
574 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
575 DAG.getVTList(MVT::i32, MVT::i32), Zero, Zero,
577 SDValue Lo(Hi.getNode(), 1);
578 SDValue Ops[] = { Lo, Hi };
579 return DAG.getMergeValues(Ops, dl);
582 SDValue XCoreTargetLowering::
583 LowerUMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
585 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::UMUL_LOHI &&
586 "Unexpected operand to lower!");
588 SDValue LHS = Op.getOperand(0);
589 SDValue RHS = Op.getOperand(1);
590 SDValue Zero = DAG.getConstant(0, MVT::i32);
591 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
592 DAG.getVTList(MVT::i32, MVT::i32), LHS, RHS,
594 SDValue Lo(Hi.getNode(), 1);
595 SDValue Ops[] = { Lo, Hi };
596 return DAG.getMergeValues(Ops, dl);
599 /// isADDADDMUL - Return whether Op is in a form that is equivalent to
600 /// add(add(mul(x,y),a),b). If requireIntermediatesHaveOneUse is true then
601 /// each intermediate result in the calculation must also have a single use.
602 /// If the Op is in the correct form the constituent parts are written to Mul0,
603 /// Mul1, Addend0 and Addend1.
605 isADDADDMUL(SDValue Op, SDValue &Mul0, SDValue &Mul1, SDValue &Addend0,
606 SDValue &Addend1, bool requireIntermediatesHaveOneUse)
608 if (Op.getOpcode() != ISD::ADD)
610 SDValue N0 = Op.getOperand(0);
611 SDValue N1 = Op.getOperand(1);
614 if (N0.getOpcode() == ISD::ADD) {
617 } else if (N1.getOpcode() == ISD::ADD) {
623 if (requireIntermediatesHaveOneUse && !AddOp.hasOneUse())
625 if (OtherOp.getOpcode() == ISD::MUL) {
626 // add(add(a,b),mul(x,y))
627 if (requireIntermediatesHaveOneUse && !OtherOp.hasOneUse())
629 Mul0 = OtherOp.getOperand(0);
630 Mul1 = OtherOp.getOperand(1);
631 Addend0 = AddOp.getOperand(0);
632 Addend1 = AddOp.getOperand(1);
635 if (AddOp.getOperand(0).getOpcode() == ISD::MUL) {
636 // add(add(mul(x,y),a),b)
637 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(0).hasOneUse())
639 Mul0 = AddOp.getOperand(0).getOperand(0);
640 Mul1 = AddOp.getOperand(0).getOperand(1);
641 Addend0 = AddOp.getOperand(1);
645 if (AddOp.getOperand(1).getOpcode() == ISD::MUL) {
646 // add(add(a,mul(x,y)),b)
647 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(1).hasOneUse())
649 Mul0 = AddOp.getOperand(1).getOperand(0);
650 Mul1 = AddOp.getOperand(1).getOperand(1);
651 Addend0 = AddOp.getOperand(0);
658 SDValue XCoreTargetLowering::
659 TryExpandADDWithMul(SDNode *N, SelectionDAG &DAG) const
663 if (N->getOperand(0).getOpcode() == ISD::MUL) {
664 Mul = N->getOperand(0);
665 Other = N->getOperand(1);
666 } else if (N->getOperand(1).getOpcode() == ISD::MUL) {
667 Mul = N->getOperand(1);
668 Other = N->getOperand(0);
673 SDValue LL, RL, AddendL, AddendH;
674 LL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
675 Mul.getOperand(0), DAG.getConstant(0, MVT::i32));
676 RL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
677 Mul.getOperand(1), DAG.getConstant(0, MVT::i32));
678 AddendL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
679 Other, DAG.getConstant(0, MVT::i32));
680 AddendH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
681 Other, DAG.getConstant(1, MVT::i32));
682 APInt HighMask = APInt::getHighBitsSet(64, 32);
683 unsigned LHSSB = DAG.ComputeNumSignBits(Mul.getOperand(0));
684 unsigned RHSSB = DAG.ComputeNumSignBits(Mul.getOperand(1));
685 if (DAG.MaskedValueIsZero(Mul.getOperand(0), HighMask) &&
686 DAG.MaskedValueIsZero(Mul.getOperand(1), HighMask)) {
687 // The inputs are both zero-extended.
688 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
689 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
691 SDValue Lo(Hi.getNode(), 1);
692 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
694 if (LHSSB > 32 && RHSSB > 32) {
695 // The inputs are both sign-extended.
696 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
697 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
699 SDValue Lo(Hi.getNode(), 1);
700 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
703 LH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
704 Mul.getOperand(0), DAG.getConstant(1, MVT::i32));
705 RH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
706 Mul.getOperand(1), DAG.getConstant(1, MVT::i32));
707 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
708 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
710 SDValue Lo(Hi.getNode(), 1);
711 RH = DAG.getNode(ISD::MUL, dl, MVT::i32, LL, RH);
712 LH = DAG.getNode(ISD::MUL, dl, MVT::i32, LH, RL);
713 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, RH);
714 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, LH);
715 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
718 SDValue XCoreTargetLowering::
719 ExpandADDSUB(SDNode *N, SelectionDAG &DAG) const
721 assert(N->getValueType(0) == MVT::i64 &&
722 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
723 "Unknown operand to lower!");
725 if (N->getOpcode() == ISD::ADD) {
726 SDValue Result = TryExpandADDWithMul(N, DAG);
727 if (Result.getNode())
733 // Extract components
734 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
735 N->getOperand(0), DAG.getConstant(0, MVT::i32));
736 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
737 N->getOperand(0), DAG.getConstant(1, MVT::i32));
738 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
739 N->getOperand(1), DAG.getConstant(0, MVT::i32));
740 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
741 N->getOperand(1), DAG.getConstant(1, MVT::i32));
744 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
746 SDValue Zero = DAG.getConstant(0, MVT::i32);
747 SDValue Lo = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
749 SDValue Carry(Lo.getNode(), 1);
751 SDValue Hi = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
753 SDValue Ignored(Hi.getNode(), 1);
755 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
758 SDValue XCoreTargetLowering::
759 LowerVAARG(SDValue Op, SelectionDAG &DAG) const
761 // Whist llvm does not support aggregate varargs we can ignore
762 // the possibility of the ValueType being an implicit byVal vararg.
763 SDNode *Node = Op.getNode();
764 EVT VT = Node->getValueType(0); // not an aggregate
765 SDValue InChain = Node->getOperand(0);
766 SDValue VAListPtr = Node->getOperand(1);
767 EVT PtrVT = VAListPtr.getValueType();
768 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
770 SDValue VAList = DAG.getLoad(PtrVT, dl, InChain,
771 VAListPtr, MachinePointerInfo(SV),
772 false, false, false, 0);
773 // Increment the pointer, VAList, to the next vararg
774 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAList,
775 DAG.getIntPtrConstant(VT.getSizeInBits() / 8));
776 // Store the incremented VAList to the legalized pointer
777 InChain = DAG.getStore(VAList.getValue(1), dl, nextPtr, VAListPtr,
778 MachinePointerInfo(SV), false, false, 0);
779 // Load the actual argument out of the pointer VAList
780 return DAG.getLoad(VT, dl, InChain, VAList, MachinePointerInfo(),
781 false, false, false, 0);
784 SDValue XCoreTargetLowering::
785 LowerVASTART(SDValue Op, SelectionDAG &DAG) const
788 // vastart stores the address of the VarArgsFrameIndex slot into the
789 // memory location argument
790 MachineFunction &MF = DAG.getMachineFunction();
791 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
792 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
793 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1),
794 MachinePointerInfo(), false, false, 0);
797 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op,
798 SelectionDAG &DAG) const {
799 // This nodes represent llvm.frameaddress on the DAG.
800 // It takes one operand, the index of the frame address to return.
801 // An index of zero corresponds to the current function's frame address.
802 // An index of one to the parent's frame address, and so on.
803 // Depths > 0 not supported yet!
804 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
807 MachineFunction &MF = DAG.getMachineFunction();
808 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
809 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op),
810 RegInfo->getFrameRegister(MF), MVT::i32);
813 SDValue XCoreTargetLowering::
814 LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const {
815 // This nodes represent llvm.returnaddress on the DAG.
816 // It takes one operand, the index of the return address to return.
817 // An index of zero corresponds to the current function's return address.
818 // An index of one to the parent's return address, and so on.
819 // Depths > 0 not supported yet!
820 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
823 MachineFunction &MF = DAG.getMachineFunction();
824 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
825 int FI = XFI->createLRSpillSlot(MF);
826 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
827 return DAG.getLoad(getPointerTy(), SDLoc(Op), DAG.getEntryNode(), FIN,
828 MachinePointerInfo::getFixedStack(FI), false, false,
832 SDValue XCoreTargetLowering::
833 LowerFRAME_TO_ARGS_OFFSET(SDValue Op, SelectionDAG &DAG) const {
834 // This node represents offset from frame pointer to first on-stack argument.
835 // This is needed for correct stack adjustment during unwind.
836 // However, we don't know the offset until after the frame has be finalised.
837 // This is done during the XCoreFTAOElim pass.
838 return DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, SDLoc(Op), MVT::i32);
841 SDValue XCoreTargetLowering::
842 LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
843 // OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER)
844 // This node represents 'eh_return' gcc dwarf builtin, which is used to
845 // return from exception. The general meaning is: adjust stack by OFFSET and
846 // pass execution to HANDLER.
847 MachineFunction &MF = DAG.getMachineFunction();
848 SDValue Chain = Op.getOperand(0);
849 SDValue Offset = Op.getOperand(1);
850 SDValue Handler = Op.getOperand(2);
853 // Absolute SP = (FP + FrameToArgs) + Offset
854 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
855 SDValue Stack = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
856 RegInfo->getFrameRegister(MF), MVT::i32);
857 SDValue FrameToArgs = DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, dl,
859 Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, FrameToArgs);
860 Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, Offset);
862 // R0=ExceptionPointerRegister R1=ExceptionSelectorRegister
863 // which leaves 2 caller saved registers, R2 & R3 for us to use.
864 unsigned StackReg = XCore::R2;
865 unsigned HandlerReg = XCore::R3;
867 SDValue OutChains[] = {
868 DAG.getCopyToReg(Chain, dl, StackReg, Stack),
869 DAG.getCopyToReg(Chain, dl, HandlerReg, Handler)
872 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
874 return DAG.getNode(XCoreISD::EH_RETURN, dl, MVT::Other, Chain,
875 DAG.getRegister(StackReg, MVT::i32),
876 DAG.getRegister(HandlerReg, MVT::i32));
880 SDValue XCoreTargetLowering::
881 LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
882 return Op.getOperand(0);
885 SDValue XCoreTargetLowering::
886 LowerINIT_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
887 SDValue Chain = Op.getOperand(0);
888 SDValue Trmp = Op.getOperand(1); // trampoline
889 SDValue FPtr = Op.getOperand(2); // nested function
890 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
892 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
895 // LDAPF_u10 r11, nest
896 // LDW_2rus r11, r11[0]
897 // STWSP_ru6 r11, sp[0]
898 // LDAPF_u10 r11, fptr
899 // LDW_2rus r11, r11[0]
905 SDValue OutChains[5];
910 OutChains[0] = DAG.getStore(Chain, dl, DAG.getConstant(0x0a3cd805, MVT::i32),
911 Addr, MachinePointerInfo(TrmpAddr), false, false,
914 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
915 DAG.getConstant(4, MVT::i32));
916 OutChains[1] = DAG.getStore(Chain, dl, DAG.getConstant(0xd80456c0, MVT::i32),
917 Addr, MachinePointerInfo(TrmpAddr, 4), false,
920 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
921 DAG.getConstant(8, MVT::i32));
922 OutChains[2] = DAG.getStore(Chain, dl, DAG.getConstant(0x27fb0a3c, MVT::i32),
923 Addr, MachinePointerInfo(TrmpAddr, 8), false,
926 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
927 DAG.getConstant(12, MVT::i32));
928 OutChains[3] = DAG.getStore(Chain, dl, Nest, Addr,
929 MachinePointerInfo(TrmpAddr, 12), false, false,
932 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
933 DAG.getConstant(16, MVT::i32));
934 OutChains[4] = DAG.getStore(Chain, dl, FPtr, Addr,
935 MachinePointerInfo(TrmpAddr, 16), false, false,
938 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
941 SDValue XCoreTargetLowering::
942 LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
944 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
946 case Intrinsic::xcore_crc8:
947 EVT VT = Op.getValueType();
949 DAG.getNode(XCoreISD::CRC8, DL, DAG.getVTList(VT, VT),
950 Op.getOperand(1), Op.getOperand(2) , Op.getOperand(3));
951 SDValue Crc(Data.getNode(), 1);
952 SDValue Results[] = { Crc, Data };
953 return DAG.getMergeValues(Results, DL);
958 SDValue XCoreTargetLowering::
959 LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG) const {
961 return DAG.getNode(XCoreISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
964 SDValue XCoreTargetLowering::
965 LowerATOMIC_LOAD(SDValue Op, SelectionDAG &DAG) const {
966 AtomicSDNode *N = cast<AtomicSDNode>(Op);
967 assert(N->getOpcode() == ISD::ATOMIC_LOAD && "Bad Atomic OP");
968 assert(N->getOrdering() <= Monotonic &&
969 "setInsertFencesForAtomic(true) and yet greater than Monotonic");
970 if (N->getMemoryVT() == MVT::i32) {
971 if (N->getAlignment() < 4)
972 report_fatal_error("atomic load must be aligned");
973 return DAG.getLoad(getPointerTy(), SDLoc(Op), N->getChain(),
974 N->getBasePtr(), N->getPointerInfo(),
975 N->isVolatile(), N->isNonTemporal(),
976 N->isInvariant(), N->getAlignment(),
977 N->getAAInfo(), N->getRanges());
979 if (N->getMemoryVT() == MVT::i16) {
980 if (N->getAlignment() < 2)
981 report_fatal_error("atomic load must be aligned");
982 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
983 N->getBasePtr(), N->getPointerInfo(), MVT::i16,
984 N->isVolatile(), N->isNonTemporal(),
985 N->isInvariant(), N->getAlignment(), N->getAAInfo());
987 if (N->getMemoryVT() == MVT::i8)
988 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
989 N->getBasePtr(), N->getPointerInfo(), MVT::i8,
990 N->isVolatile(), N->isNonTemporal(),
991 N->isInvariant(), N->getAlignment(), N->getAAInfo());
995 SDValue XCoreTargetLowering::
996 LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) const {
997 AtomicSDNode *N = cast<AtomicSDNode>(Op);
998 assert(N->getOpcode() == ISD::ATOMIC_STORE && "Bad Atomic OP");
999 assert(N->getOrdering() <= Monotonic &&
1000 "setInsertFencesForAtomic(true) and yet greater than Monotonic");
1001 if (N->getMemoryVT() == MVT::i32) {
1002 if (N->getAlignment() < 4)
1003 report_fatal_error("atomic store must be aligned");
1004 return DAG.getStore(N->getChain(), SDLoc(Op), N->getVal(),
1005 N->getBasePtr(), N->getPointerInfo(),
1006 N->isVolatile(), N->isNonTemporal(),
1007 N->getAlignment(), N->getAAInfo());
1009 if (N->getMemoryVT() == MVT::i16) {
1010 if (N->getAlignment() < 2)
1011 report_fatal_error("atomic store must be aligned");
1012 return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1013 N->getBasePtr(), N->getPointerInfo(), MVT::i16,
1014 N->isVolatile(), N->isNonTemporal(),
1015 N->getAlignment(), N->getAAInfo());
1017 if (N->getMemoryVT() == MVT::i8)
1018 return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1019 N->getBasePtr(), N->getPointerInfo(), MVT::i8,
1020 N->isVolatile(), N->isNonTemporal(),
1021 N->getAlignment(), N->getAAInfo());
1025 //===----------------------------------------------------------------------===//
1026 // Calling Convention Implementation
1027 //===----------------------------------------------------------------------===//
1029 #include "XCoreGenCallingConv.inc"
1031 //===----------------------------------------------------------------------===//
1032 // Call Calling Convention Implementation
1033 //===----------------------------------------------------------------------===//
1035 /// XCore call implementation
1037 XCoreTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1038 SmallVectorImpl<SDValue> &InVals) const {
1039 SelectionDAG &DAG = CLI.DAG;
1041 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1042 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1043 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1044 SDValue Chain = CLI.Chain;
1045 SDValue Callee = CLI.Callee;
1046 bool &isTailCall = CLI.IsTailCall;
1047 CallingConv::ID CallConv = CLI.CallConv;
1048 bool isVarArg = CLI.IsVarArg;
1050 // XCore target does not yet support tail call optimization.
1053 // For now, only CallingConv::C implemented
1057 llvm_unreachable("Unsupported calling convention");
1058 case CallingConv::Fast:
1059 case CallingConv::C:
1060 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
1061 Outs, OutVals, Ins, dl, DAG, InVals);
1065 /// LowerCallResult - Lower the result values of a call into the
1066 /// appropriate copies out of appropriate physical registers / memory locations.
1068 LowerCallResult(SDValue Chain, SDValue InFlag,
1069 const SmallVectorImpl<CCValAssign> &RVLocs,
1070 SDLoc dl, SelectionDAG &DAG,
1071 SmallVectorImpl<SDValue> &InVals) {
1072 SmallVector<std::pair<int, unsigned>, 4> ResultMemLocs;
1073 // Copy results out of physical registers.
1074 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1075 const CCValAssign &VA = RVLocs[i];
1076 if (VA.isRegLoc()) {
1077 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getValVT(),
1078 InFlag).getValue(1);
1079 InFlag = Chain.getValue(2);
1080 InVals.push_back(Chain.getValue(0));
1082 assert(VA.isMemLoc());
1083 ResultMemLocs.push_back(std::make_pair(VA.getLocMemOffset(),
1085 // Reserve space for this result.
1086 InVals.push_back(SDValue());
1090 // Copy results out of memory.
1091 SmallVector<SDValue, 4> MemOpChains;
1092 for (unsigned i = 0, e = ResultMemLocs.size(); i != e; ++i) {
1093 int offset = ResultMemLocs[i].first;
1094 unsigned index = ResultMemLocs[i].second;
1095 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
1096 SDValue Ops[] = { Chain, DAG.getConstant(offset / 4, MVT::i32) };
1097 SDValue load = DAG.getNode(XCoreISD::LDWSP, dl, VTs, Ops);
1098 InVals[index] = load;
1099 MemOpChains.push_back(load.getValue(1));
1102 // Transform all loads nodes into one single node because
1103 // all load nodes are independent of each other.
1104 if (!MemOpChains.empty())
1105 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1110 /// LowerCCCCallTo - functions arguments are copied from virtual
1111 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
1112 /// CALLSEQ_END are emitted.
1113 /// TODO: isTailCall, sret.
1115 XCoreTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
1116 CallingConv::ID CallConv, bool isVarArg,
1118 const SmallVectorImpl<ISD::OutputArg> &Outs,
1119 const SmallVectorImpl<SDValue> &OutVals,
1120 const SmallVectorImpl<ISD::InputArg> &Ins,
1121 SDLoc dl, SelectionDAG &DAG,
1122 SmallVectorImpl<SDValue> &InVals) const {
1124 // Analyze operands of the call, assigning locations to each operand.
1125 SmallVector<CCValAssign, 16> ArgLocs;
1126 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1127 getTargetMachine(), ArgLocs, *DAG.getContext());
1129 // The ABI dictates there should be one stack slot available to the callee
1130 // on function entry (for saving lr).
1131 CCInfo.AllocateStack(4, 4);
1133 CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
1135 SmallVector<CCValAssign, 16> RVLocs;
1136 // Analyze return values to determine the number of bytes of stack required.
1137 CCState RetCCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1138 getTargetMachine(), RVLocs, *DAG.getContext());
1139 RetCCInfo.AllocateStack(CCInfo.getNextStackOffset(), 4);
1140 RetCCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
1142 // Get a count of how many bytes are to be pushed on the stack.
1143 unsigned NumBytes = RetCCInfo.getNextStackOffset();
1145 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
1146 getPointerTy(), true), dl);
1148 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
1149 SmallVector<SDValue, 12> MemOpChains;
1151 // Walk the register/memloc assignments, inserting copies/loads.
1152 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1153 CCValAssign &VA = ArgLocs[i];
1154 SDValue Arg = OutVals[i];
1156 // Promote the value if needed.
1157 switch (VA.getLocInfo()) {
1158 default: llvm_unreachable("Unknown loc info!");
1159 case CCValAssign::Full: break;
1160 case CCValAssign::SExt:
1161 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1163 case CCValAssign::ZExt:
1164 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1166 case CCValAssign::AExt:
1167 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1171 // Arguments that can be passed on register must be kept at
1172 // RegsToPass vector
1173 if (VA.isRegLoc()) {
1174 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1176 assert(VA.isMemLoc());
1178 int Offset = VA.getLocMemOffset();
1180 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
1182 DAG.getConstant(Offset/4, MVT::i32)));
1186 // Transform all store nodes into one single node because
1187 // all store nodes are independent of each other.
1188 if (!MemOpChains.empty())
1189 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1191 // Build a sequence of copy-to-reg nodes chained together with token
1192 // chain and flag operands which copy the outgoing args into registers.
1193 // The InFlag in necessary since all emitted instructions must be
1196 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1197 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1198 RegsToPass[i].second, InFlag);
1199 InFlag = Chain.getValue(1);
1202 // If the callee is a GlobalAddress node (quite common, every direct call is)
1203 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1204 // Likewise ExternalSymbol -> TargetExternalSymbol.
1205 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1206 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
1207 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
1208 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
1210 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
1211 // = Chain, Callee, Reg#1, Reg#2, ...
1213 // Returns a chain & a flag for retval copy to use.
1214 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1215 SmallVector<SDValue, 8> Ops;
1216 Ops.push_back(Chain);
1217 Ops.push_back(Callee);
1219 // Add argument registers to the end of the list so that they are
1220 // known live into the call.
1221 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1222 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1223 RegsToPass[i].second.getValueType()));
1225 if (InFlag.getNode())
1226 Ops.push_back(InFlag);
1228 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, Ops);
1229 InFlag = Chain.getValue(1);
1231 // Create the CALLSEQ_END node.
1232 Chain = DAG.getCALLSEQ_END(Chain,
1233 DAG.getConstant(NumBytes, getPointerTy(), true),
1234 DAG.getConstant(0, getPointerTy(), true),
1236 InFlag = Chain.getValue(1);
1238 // Handle result values, copying them out of physregs into vregs that we
1240 return LowerCallResult(Chain, InFlag, RVLocs, dl, DAG, InVals);
1243 //===----------------------------------------------------------------------===//
1244 // Formal Arguments Calling Convention Implementation
1245 //===----------------------------------------------------------------------===//
1248 struct ArgDataPair { SDValue SDV; ISD::ArgFlagsTy Flags; };
1251 /// XCore formal arguments implementation
1253 XCoreTargetLowering::LowerFormalArguments(SDValue Chain,
1254 CallingConv::ID CallConv,
1256 const SmallVectorImpl<ISD::InputArg> &Ins,
1259 SmallVectorImpl<SDValue> &InVals)
1264 llvm_unreachable("Unsupported calling convention");
1265 case CallingConv::C:
1266 case CallingConv::Fast:
1267 return LowerCCCArguments(Chain, CallConv, isVarArg,
1268 Ins, dl, DAG, InVals);
1272 /// LowerCCCArguments - transform physical registers into
1273 /// virtual registers and generate load operations for
1274 /// arguments places on the stack.
1277 XCoreTargetLowering::LowerCCCArguments(SDValue Chain,
1278 CallingConv::ID CallConv,
1280 const SmallVectorImpl<ISD::InputArg>
1284 SmallVectorImpl<SDValue> &InVals) const {
1285 MachineFunction &MF = DAG.getMachineFunction();
1286 MachineFrameInfo *MFI = MF.getFrameInfo();
1287 MachineRegisterInfo &RegInfo = MF.getRegInfo();
1288 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1290 // Assign locations to all of the incoming arguments.
1291 SmallVector<CCValAssign, 16> ArgLocs;
1292 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1293 getTargetMachine(), ArgLocs, *DAG.getContext());
1295 CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
1297 unsigned StackSlotSize = XCoreFrameLowering::stackSlotSize();
1299 unsigned LRSaveSize = StackSlotSize;
1302 XFI->setReturnStackOffset(CCInfo.getNextStackOffset() + LRSaveSize);
1304 // All getCopyFromReg ops must precede any getMemcpys to prevent the
1305 // scheduler clobbering a register before it has been copied.
1307 // 1. CopyFromReg (and load) arg & vararg registers.
1308 // 2. Chain CopyFromReg nodes into a TokenFactor.
1309 // 3. Memcpy 'byVal' args & push final InVals.
1310 // 4. Chain mem ops nodes into a TokenFactor.
1311 SmallVector<SDValue, 4> CFRegNode;
1312 SmallVector<ArgDataPair, 4> ArgData;
1313 SmallVector<SDValue, 4> MemOps;
1315 // 1a. CopyFromReg (and load) arg registers.
1316 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1318 CCValAssign &VA = ArgLocs[i];
1321 if (VA.isRegLoc()) {
1322 // Arguments passed in registers
1323 EVT RegVT = VA.getLocVT();
1324 switch (RegVT.getSimpleVT().SimpleTy) {
1328 errs() << "LowerFormalArguments Unhandled argument type: "
1329 << RegVT.getSimpleVT().SimpleTy << "\n";
1331 llvm_unreachable(nullptr);
1334 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1335 RegInfo.addLiveIn(VA.getLocReg(), VReg);
1336 ArgIn = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
1337 CFRegNode.push_back(ArgIn.getValue(ArgIn->getNumValues() - 1));
1341 assert(VA.isMemLoc());
1342 // Load the argument to a virtual register
1343 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
1344 if (ObjSize > StackSlotSize) {
1345 errs() << "LowerFormalArguments Unhandled argument type: "
1346 << EVT(VA.getLocVT()).getEVTString()
1349 // Create the frame index object for this incoming parameter...
1350 int FI = MFI->CreateFixedObject(ObjSize,
1351 LRSaveSize + VA.getLocMemOffset(),
1354 // Create the SelectionDAG nodes corresponding to a load
1355 //from this parameter
1356 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1357 ArgIn = DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
1358 MachinePointerInfo::getFixedStack(FI),
1359 false, false, false, 0);
1361 const ArgDataPair ADP = { ArgIn, Ins[i].Flags };
1362 ArgData.push_back(ADP);
1365 // 1b. CopyFromReg vararg registers.
1367 // Argument registers
1368 static const MCPhysReg ArgRegs[] = {
1369 XCore::R0, XCore::R1, XCore::R2, XCore::R3
1371 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1372 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
1373 array_lengthof(ArgRegs));
1374 if (FirstVAReg < array_lengthof(ArgRegs)) {
1376 // Save remaining registers, storing higher register numbers at a higher
1378 for (int i = array_lengthof(ArgRegs) - 1; i >= (int)FirstVAReg; --i) {
1379 // Create a stack slot
1380 int FI = MFI->CreateFixedObject(4, offset, true);
1381 if (i == (int)FirstVAReg) {
1382 XFI->setVarArgsFrameIndex(FI);
1384 offset -= StackSlotSize;
1385 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1386 // Move argument from phys reg -> virt reg
1387 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1388 RegInfo.addLiveIn(ArgRegs[i], VReg);
1389 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1390 CFRegNode.push_back(Val.getValue(Val->getNumValues() - 1));
1391 // Move argument from virt reg -> stack
1392 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
1393 MachinePointerInfo(), false, false, 0);
1394 MemOps.push_back(Store);
1397 // This will point to the next argument passed via stack.
1398 XFI->setVarArgsFrameIndex(
1399 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset(),
1404 // 2. chain CopyFromReg nodes into a TokenFactor.
1405 if (!CFRegNode.empty())
1406 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, CFRegNode);
1408 // 3. Memcpy 'byVal' args & push final InVals.
1409 // Aggregates passed "byVal" need to be copied by the callee.
1410 // The callee will use a pointer to this copy, rather than the original
1412 for (SmallVectorImpl<ArgDataPair>::const_iterator ArgDI = ArgData.begin(),
1413 ArgDE = ArgData.end();
1414 ArgDI != ArgDE; ++ArgDI) {
1415 if (ArgDI->Flags.isByVal() && ArgDI->Flags.getByValSize()) {
1416 unsigned Size = ArgDI->Flags.getByValSize();
1417 unsigned Align = std::max(StackSlotSize, ArgDI->Flags.getByValAlign());
1418 // Create a new object on the stack and copy the pointee into it.
1419 int FI = MFI->CreateStackObject(Size, Align, false);
1420 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1421 InVals.push_back(FIN);
1422 MemOps.push_back(DAG.getMemcpy(Chain, dl, FIN, ArgDI->SDV,
1423 DAG.getConstant(Size, MVT::i32),
1424 Align, false, false,
1425 MachinePointerInfo(),
1426 MachinePointerInfo()));
1428 InVals.push_back(ArgDI->SDV);
1432 // 4, chain mem ops nodes into a TokenFactor.
1433 if (!MemOps.empty()) {
1434 MemOps.push_back(Chain);
1435 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
1441 //===----------------------------------------------------------------------===//
1442 // Return Value Calling Convention Implementation
1443 //===----------------------------------------------------------------------===//
1445 bool XCoreTargetLowering::
1446 CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF,
1448 const SmallVectorImpl<ISD::OutputArg> &Outs,
1449 LLVMContext &Context) const {
1450 SmallVector<CCValAssign, 16> RVLocs;
1451 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
1452 if (!CCInfo.CheckReturn(Outs, RetCC_XCore))
1454 if (CCInfo.getNextStackOffset() != 0 && isVarArg)
1460 XCoreTargetLowering::LowerReturn(SDValue Chain,
1461 CallingConv::ID CallConv, bool isVarArg,
1462 const SmallVectorImpl<ISD::OutputArg> &Outs,
1463 const SmallVectorImpl<SDValue> &OutVals,
1464 SDLoc dl, SelectionDAG &DAG) const {
1466 XCoreFunctionInfo *XFI =
1467 DAG.getMachineFunction().getInfo<XCoreFunctionInfo>();
1468 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1470 // CCValAssign - represent the assignment of
1471 // the return value to a location
1472 SmallVector<CCValAssign, 16> RVLocs;
1474 // CCState - Info about the registers and stack slot.
1475 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1476 getTargetMachine(), RVLocs, *DAG.getContext());
1478 // Analyze return values.
1480 CCInfo.AllocateStack(XFI->getReturnStackOffset(), 4);
1482 CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
1485 SmallVector<SDValue, 4> RetOps(1, Chain);
1487 // Return on XCore is always a "retsp 0"
1488 RetOps.push_back(DAG.getConstant(0, MVT::i32));
1490 SmallVector<SDValue, 4> MemOpChains;
1491 // Handle return values that must be copied to memory.
1492 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1493 CCValAssign &VA = RVLocs[i];
1496 assert(VA.isMemLoc());
1498 report_fatal_error("Can't return value from vararg function in memory");
1501 int Offset = VA.getLocMemOffset();
1502 unsigned ObjSize = VA.getLocVT().getSizeInBits() / 8;
1503 // Create the frame index object for the memory location.
1504 int FI = MFI->CreateFixedObject(ObjSize, Offset, false);
1506 // Create a SelectionDAG node corresponding to a store
1507 // to this memory location.
1508 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1509 MemOpChains.push_back(DAG.getStore(Chain, dl, OutVals[i], FIN,
1510 MachinePointerInfo::getFixedStack(FI), false, false,
1514 // Transform all store nodes into one single node because
1515 // all stores are independent of each other.
1516 if (!MemOpChains.empty())
1517 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1519 // Now handle return values copied to registers.
1520 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1521 CCValAssign &VA = RVLocs[i];
1524 // Copy the result values into the output registers.
1525 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
1527 // guarantee that all emitted copies are
1528 // stuck together, avoiding something bad
1529 Flag = Chain.getValue(1);
1530 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1533 RetOps[0] = Chain; // Update chain.
1535 // Add the flag if we have it.
1537 RetOps.push_back(Flag);
1539 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other, RetOps);
1542 //===----------------------------------------------------------------------===//
1543 // Other Lowering Code
1544 //===----------------------------------------------------------------------===//
1547 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1548 MachineBasicBlock *BB) const {
1549 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1550 DebugLoc dl = MI->getDebugLoc();
1551 assert((MI->getOpcode() == XCore::SELECT_CC) &&
1552 "Unexpected instr type to insert");
1554 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1555 // control-flow pattern. The incoming instruction knows the destination vreg
1556 // to set, the condition code register to branch on, the true/false values to
1557 // select between, and a branch opcode to use.
1558 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1559 MachineFunction::iterator It = BB;
1565 // cmpTY ccX, r1, r2
1567 // fallthrough --> copy0MBB
1568 MachineBasicBlock *thisMBB = BB;
1569 MachineFunction *F = BB->getParent();
1570 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1571 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1572 F->insert(It, copy0MBB);
1573 F->insert(It, sinkMBB);
1575 // Transfer the remainder of BB and its successor edges to sinkMBB.
1576 sinkMBB->splice(sinkMBB->begin(), BB,
1577 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1578 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1580 // Next, add the true and fallthrough blocks as its successors.
1581 BB->addSuccessor(copy0MBB);
1582 BB->addSuccessor(sinkMBB);
1584 BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1585 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1588 // %FalseValue = ...
1589 // # fallthrough to sinkMBB
1592 // Update machine-CFG edges
1593 BB->addSuccessor(sinkMBB);
1596 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1599 BuildMI(*BB, BB->begin(), dl,
1600 TII.get(XCore::PHI), MI->getOperand(0).getReg())
1601 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1602 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1604 MI->eraseFromParent(); // The pseudo instruction is gone now.
1608 //===----------------------------------------------------------------------===//
1609 // Target Optimization Hooks
1610 //===----------------------------------------------------------------------===//
1612 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1613 DAGCombinerInfo &DCI) const {
1614 SelectionDAG &DAG = DCI.DAG;
1616 switch (N->getOpcode()) {
1618 case ISD::INTRINSIC_VOID:
1619 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
1620 case Intrinsic::xcore_outt:
1621 case Intrinsic::xcore_outct:
1622 case Intrinsic::xcore_chkct: {
1623 SDValue OutVal = N->getOperand(3);
1624 // These instructions ignore the high bits.
1625 if (OutVal.hasOneUse()) {
1626 unsigned BitWidth = OutVal.getValueSizeInBits();
1627 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8);
1628 APInt KnownZero, KnownOne;
1629 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1630 !DCI.isBeforeLegalizeOps());
1631 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1632 if (TLO.ShrinkDemandedConstant(OutVal, DemandedMask) ||
1633 TLI.SimplifyDemandedBits(OutVal, DemandedMask, KnownZero, KnownOne,
1635 DCI.CommitTargetLoweringOpt(TLO);
1639 case Intrinsic::xcore_setpt: {
1640 SDValue Time = N->getOperand(3);
1641 // This instruction ignores the high bits.
1642 if (Time.hasOneUse()) {
1643 unsigned BitWidth = Time.getValueSizeInBits();
1644 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
1645 APInt KnownZero, KnownOne;
1646 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1647 !DCI.isBeforeLegalizeOps());
1648 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1649 if (TLO.ShrinkDemandedConstant(Time, DemandedMask) ||
1650 TLI.SimplifyDemandedBits(Time, DemandedMask, KnownZero, KnownOne,
1652 DCI.CommitTargetLoweringOpt(TLO);
1658 case XCoreISD::LADD: {
1659 SDValue N0 = N->getOperand(0);
1660 SDValue N1 = N->getOperand(1);
1661 SDValue N2 = N->getOperand(2);
1662 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1663 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1664 EVT VT = N0.getValueType();
1666 // canonicalize constant to RHS
1668 return DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N1, N0, N2);
1670 // fold (ladd 0, 0, x) -> 0, x & 1
1671 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1672 SDValue Carry = DAG.getConstant(0, VT);
1673 SDValue Result = DAG.getNode(ISD::AND, dl, VT, N2,
1674 DAG.getConstant(1, VT));
1675 SDValue Ops[] = { Result, Carry };
1676 return DAG.getMergeValues(Ops, dl);
1679 // fold (ladd x, 0, y) -> 0, add x, y iff carry is unused and y has only the
1681 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1682 APInt KnownZero, KnownOne;
1683 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1684 VT.getSizeInBits() - 1);
1685 DAG.computeKnownBits(N2, KnownZero, KnownOne);
1686 if ((KnownZero & Mask) == Mask) {
1687 SDValue Carry = DAG.getConstant(0, VT);
1688 SDValue Result = DAG.getNode(ISD::ADD, dl, VT, N0, N2);
1689 SDValue Ops[] = { Result, Carry };
1690 return DAG.getMergeValues(Ops, dl);
1695 case XCoreISD::LSUB: {
1696 SDValue N0 = N->getOperand(0);
1697 SDValue N1 = N->getOperand(1);
1698 SDValue N2 = N->getOperand(2);
1699 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1700 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1701 EVT VT = N0.getValueType();
1703 // fold (lsub 0, 0, x) -> x, -x iff x has only the low bit set
1704 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1705 APInt KnownZero, KnownOne;
1706 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1707 VT.getSizeInBits() - 1);
1708 DAG.computeKnownBits(N2, KnownZero, KnownOne);
1709 if ((KnownZero & Mask) == Mask) {
1710 SDValue Borrow = N2;
1711 SDValue Result = DAG.getNode(ISD::SUB, dl, VT,
1712 DAG.getConstant(0, VT), N2);
1713 SDValue Ops[] = { Result, Borrow };
1714 return DAG.getMergeValues(Ops, dl);
1718 // fold (lsub x, 0, y) -> 0, sub x, y iff borrow is unused and y has only the
1720 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1721 APInt KnownZero, KnownOne;
1722 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1723 VT.getSizeInBits() - 1);
1724 DAG.computeKnownBits(N2, KnownZero, KnownOne);
1725 if ((KnownZero & Mask) == Mask) {
1726 SDValue Borrow = DAG.getConstant(0, VT);
1727 SDValue Result = DAG.getNode(ISD::SUB, dl, VT, N0, N2);
1728 SDValue Ops[] = { Result, Borrow };
1729 return DAG.getMergeValues(Ops, dl);
1734 case XCoreISD::LMUL: {
1735 SDValue N0 = N->getOperand(0);
1736 SDValue N1 = N->getOperand(1);
1737 SDValue N2 = N->getOperand(2);
1738 SDValue N3 = N->getOperand(3);
1739 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1740 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1741 EVT VT = N0.getValueType();
1742 // Canonicalize multiplicative constant to RHS. If both multiplicative
1743 // operands are constant canonicalize smallest to RHS.
1744 if ((N0C && !N1C) ||
1745 (N0C && N1C && N0C->getZExtValue() < N1C->getZExtValue()))
1746 return DAG.getNode(XCoreISD::LMUL, dl, DAG.getVTList(VT, VT),
1750 if (N1C && N1C->isNullValue()) {
1751 // If the high result is unused fold to add(a, b)
1752 if (N->hasNUsesOfValue(0, 0)) {
1753 SDValue Lo = DAG.getNode(ISD::ADD, dl, VT, N2, N3);
1754 SDValue Ops[] = { Lo, Lo };
1755 return DAG.getMergeValues(Ops, dl);
1757 // Otherwise fold to ladd(a, b, 0)
1759 DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N2, N3, N1);
1760 SDValue Carry(Result.getNode(), 1);
1761 SDValue Ops[] = { Carry, Result };
1762 return DAG.getMergeValues(Ops, dl);
1767 // Fold 32 bit expressions such as add(add(mul(x,y),a),b) ->
1768 // lmul(x, y, a, b). The high result of lmul will be ignored.
1769 // This is only profitable if the intermediate results are unused
1771 SDValue Mul0, Mul1, Addend0, Addend1;
1772 if (N->getValueType(0) == MVT::i32 &&
1773 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, true)) {
1774 SDValue Ignored = DAG.getNode(XCoreISD::LMUL, dl,
1775 DAG.getVTList(MVT::i32, MVT::i32), Mul0,
1776 Mul1, Addend0, Addend1);
1777 SDValue Result(Ignored.getNode(), 1);
1780 APInt HighMask = APInt::getHighBitsSet(64, 32);
1781 // Fold 64 bit expression such as add(add(mul(x,y),a),b) ->
1782 // lmul(x, y, a, b) if all operands are zero-extended. We do this
1783 // before type legalization as it is messy to match the operands after
1785 if (N->getValueType(0) == MVT::i64 &&
1786 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, false) &&
1787 DAG.MaskedValueIsZero(Mul0, HighMask) &&
1788 DAG.MaskedValueIsZero(Mul1, HighMask) &&
1789 DAG.MaskedValueIsZero(Addend0, HighMask) &&
1790 DAG.MaskedValueIsZero(Addend1, HighMask)) {
1791 SDValue Mul0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1792 Mul0, DAG.getConstant(0, MVT::i32));
1793 SDValue Mul1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1794 Mul1, DAG.getConstant(0, MVT::i32));
1795 SDValue Addend0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1796 Addend0, DAG.getConstant(0, MVT::i32));
1797 SDValue Addend1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1798 Addend1, DAG.getConstant(0, MVT::i32));
1799 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
1800 DAG.getVTList(MVT::i32, MVT::i32), Mul0L, Mul1L,
1801 Addend0L, Addend1L);
1802 SDValue Lo(Hi.getNode(), 1);
1803 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
1808 // Replace unaligned store of unaligned load with memmove.
1809 StoreSDNode *ST = cast<StoreSDNode>(N);
1810 if (!DCI.isBeforeLegalize() ||
1811 allowsMisalignedMemoryAccesses(ST->getMemoryVT(),
1812 ST->getAddressSpace(),
1813 ST->getAlignment()) ||
1814 ST->isVolatile() || ST->isIndexed()) {
1817 SDValue Chain = ST->getChain();
1819 unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1820 if (StoreBits % 8) {
1823 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(
1824 ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1825 unsigned Alignment = ST->getAlignment();
1826 if (Alignment >= ABIAlignment) {
1830 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1831 if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1832 LD->getAlignment() == Alignment &&
1833 !LD->isVolatile() && !LD->isIndexed() &&
1834 Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1835 return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1837 DAG.getConstant(StoreBits/8, MVT::i32),
1838 Alignment, false, ST->getPointerInfo(),
1839 LD->getPointerInfo());
1848 void XCoreTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
1851 const SelectionDAG &DAG,
1852 unsigned Depth) const {
1853 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
1854 switch (Op.getOpcode()) {
1856 case XCoreISD::LADD:
1857 case XCoreISD::LSUB:
1858 if (Op.getResNo() == 1) {
1859 // Top bits of carry / borrow are clear.
1860 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1861 KnownZero.getBitWidth() - 1);
1864 case ISD::INTRINSIC_W_CHAIN:
1866 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1868 case Intrinsic::xcore_getts:
1869 // High bits are known to be zero.
1870 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1871 KnownZero.getBitWidth() - 16);
1873 case Intrinsic::xcore_int:
1874 case Intrinsic::xcore_inct:
1875 // High bits are known to be zero.
1876 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1877 KnownZero.getBitWidth() - 8);
1879 case Intrinsic::xcore_testct:
1880 // Result is either 0 or 1.
1881 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1882 KnownZero.getBitWidth() - 1);
1884 case Intrinsic::xcore_testwct:
1885 // Result is in the range 0 - 4.
1886 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1887 KnownZero.getBitWidth() - 3);
1895 //===----------------------------------------------------------------------===//
1896 // Addressing mode description hooks
1897 //===----------------------------------------------------------------------===//
1899 static inline bool isImmUs(int64_t val)
1901 return (val >= 0 && val <= 11);
1904 static inline bool isImmUs2(int64_t val)
1906 return (val%2 == 0 && isImmUs(val/2));
1909 static inline bool isImmUs4(int64_t val)
1911 return (val%4 == 0 && isImmUs(val/4));
1914 /// isLegalAddressingMode - Return true if the addressing mode represented
1915 /// by AM is legal for this target, for a load/store of the specified type.
1917 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1919 if (Ty->getTypeID() == Type::VoidTyID)
1920 return AM.Scale == 0 && isImmUs(AM.BaseOffs) && isImmUs4(AM.BaseOffs);
1922 const DataLayout *TD = TM.getDataLayout();
1923 unsigned Size = TD->getTypeAllocSize(Ty);
1925 return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1932 if (AM.Scale == 0) {
1933 return isImmUs(AM.BaseOffs);
1936 return AM.Scale == 1 && AM.BaseOffs == 0;
1940 if (AM.Scale == 0) {
1941 return isImmUs2(AM.BaseOffs);
1944 return AM.Scale == 2 && AM.BaseOffs == 0;
1947 if (AM.Scale == 0) {
1948 return isImmUs4(AM.BaseOffs);
1951 return AM.Scale == 4 && AM.BaseOffs == 0;
1955 //===----------------------------------------------------------------------===//
1956 // XCore Inline Assembly Support
1957 //===----------------------------------------------------------------------===//
1959 std::pair<unsigned, const TargetRegisterClass*>
1960 XCoreTargetLowering::
1961 getRegForInlineAsmConstraint(const std::string &Constraint,
1963 if (Constraint.size() == 1) {
1964 switch (Constraint[0]) {
1967 return std::make_pair(0U, &XCore::GRRegsRegClass);
1970 // Use the default implementation in TargetLowering to convert the register
1971 // constraint into a member of a register class.
1972 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);