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 const XCoreSubtarget &Subtarget)
73 : TargetLowering(TM), TM(TM), Subtarget(Subtarget) {
75 // Set up the register classes.
76 addRegisterClass(MVT::i32, &XCore::GRRegsRegClass);
78 // Compute derived properties from the register classes
79 computeRegisterProperties(Subtarget.getRegisterInfo());
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 for (MVT VT : MVT::integer_valuetypes()) {
131 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
132 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
133 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
135 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
136 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i16, Expand);
139 // Custom expand misaligned loads / stores.
140 setOperationAction(ISD::LOAD, MVT::i32, Custom);
141 setOperationAction(ISD::STORE, MVT::i32, Custom);
144 setOperationAction(ISD::VAEND, MVT::Other, Expand);
145 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
146 setOperationAction(ISD::VAARG, MVT::Other, Custom);
147 setOperationAction(ISD::VASTART, MVT::Other, Custom);
150 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
151 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
152 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
154 // Exception handling
155 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
156 setExceptionPointerRegister(XCore::R0);
157 setExceptionSelectorRegister(XCore::R1);
158 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
161 // We request a fence for ATOMIC_* instructions, to reduce them to Monotonic.
162 // As we are always Sequential Consistent, an ATOMIC_FENCE becomes a no OP.
163 setInsertFencesForAtomic(true);
164 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
165 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
166 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
168 // TRAMPOLINE is custom lowered.
169 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
170 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
172 // We want to custom lower some of our intrinsics.
173 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
175 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 4;
176 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize
177 = MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 2;
179 // We have target-specific dag combine patterns for the following nodes:
180 setTargetDAGCombine(ISD::STORE);
181 setTargetDAGCombine(ISD::ADD);
182 setTargetDAGCombine(ISD::INTRINSIC_VOID);
183 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
185 setMinFunctionAlignment(1);
186 setPrefFunctionAlignment(2);
189 bool XCoreTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
190 if (Val.getOpcode() != ISD::LOAD)
193 EVT VT1 = Val.getValueType();
194 if (!VT1.isSimple() || !VT1.isInteger() ||
195 !VT2.isSimple() || !VT2.isInteger())
198 switch (VT1.getSimpleVT().SimpleTy) {
207 SDValue XCoreTargetLowering::
208 LowerOperation(SDValue Op, SelectionDAG &DAG) const {
209 switch (Op.getOpcode())
211 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
212 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
213 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
214 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
215 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
216 case ISD::LOAD: return LowerLOAD(Op, DAG);
217 case ISD::STORE: return LowerSTORE(Op, DAG);
218 case ISD::VAARG: return LowerVAARG(Op, DAG);
219 case ISD::VASTART: return LowerVASTART(Op, DAG);
220 case ISD::SMUL_LOHI: return LowerSMUL_LOHI(Op, DAG);
221 case ISD::UMUL_LOHI: return LowerUMUL_LOHI(Op, DAG);
222 // FIXME: Remove these when LegalizeDAGTypes lands.
224 case ISD::SUB: return ExpandADDSUB(Op.getNode(), DAG);
225 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
226 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
227 case ISD::FRAME_TO_ARGS_OFFSET: return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
228 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
229 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
230 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
231 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
232 case ISD::ATOMIC_LOAD: return LowerATOMIC_LOAD(Op, DAG);
233 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op, DAG);
235 llvm_unreachable("unimplemented operand");
239 /// ReplaceNodeResults - Replace the results of node with an illegal result
240 /// type with new values built out of custom code.
241 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
242 SmallVectorImpl<SDValue>&Results,
243 SelectionDAG &DAG) const {
244 switch (N->getOpcode()) {
246 llvm_unreachable("Don't know how to custom expand this!");
249 Results.push_back(ExpandADDSUB(N, DAG));
254 //===----------------------------------------------------------------------===//
255 // Misc Lower Operation implementation
256 //===----------------------------------------------------------------------===//
258 SDValue XCoreTargetLowering::getGlobalAddressWrapper(SDValue GA,
259 const GlobalValue *GV,
260 SelectionDAG &DAG) const {
261 // FIXME there is no actual debug info here
264 if (GV->getType()->getElementType()->isFunctionTy())
265 return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
267 const auto *GVar = dyn_cast<GlobalVariable>(GV);
268 if ((GV->hasSection() && StringRef(GV->getSection()).startswith(".cp.")) ||
269 (GVar && GVar->isConstant() && GV->hasLocalLinkage()))
270 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
272 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
275 static bool IsSmallObject(const GlobalValue *GV, const XCoreTargetLowering &XTL) {
276 if (XTL.getTargetMachine().getCodeModel() == CodeModel::Small)
279 Type *ObjType = GV->getType()->getPointerElementType();
280 if (!ObjType->isSized())
283 unsigned ObjSize = XTL.getDataLayout()->getTypeAllocSize(ObjType);
284 return ObjSize < CodeModelLargeSize && ObjSize != 0;
287 SDValue XCoreTargetLowering::
288 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const
290 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
291 const GlobalValue *GV = GN->getGlobal();
293 int64_t Offset = GN->getOffset();
294 if (IsSmallObject(GV, *this)) {
295 // We can only fold positive offsets that are a multiple of the word size.
296 int64_t FoldedOffset = std::max(Offset & ~3, (int64_t)0);
297 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, FoldedOffset);
298 GA = getGlobalAddressWrapper(GA, GV, DAG);
299 // Handle the rest of the offset.
300 if (Offset != FoldedOffset) {
301 SDValue Remaining = DAG.getConstant(Offset - FoldedOffset, DL, MVT::i32);
302 GA = DAG.getNode(ISD::ADD, DL, MVT::i32, GA, Remaining);
306 // Ideally we would not fold in offset with an index <= 11.
307 Type *Ty = Type::getInt8PtrTy(*DAG.getContext());
308 Constant *GA = ConstantExpr::getBitCast(const_cast<GlobalValue*>(GV), Ty);
309 Ty = Type::getInt32Ty(*DAG.getContext());
310 Constant *Idx = ConstantInt::get(Ty, Offset);
311 Constant *GAI = ConstantExpr::getGetElementPtr(
312 Type::getInt8Ty(*DAG.getContext()), GA, Idx);
313 SDValue CP = DAG.getConstantPool(GAI, MVT::i32);
314 return DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), CP,
315 MachinePointerInfo(), false, false, false, 0);
319 SDValue XCoreTargetLowering::
320 LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const
324 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
325 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy());
327 return DAG.getNode(XCoreISD::PCRelativeWrapper, DL, getPointerTy(), Result);
330 SDValue XCoreTargetLowering::
331 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
333 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
334 // FIXME there isn't really debug info here
336 EVT PtrVT = Op.getValueType();
338 if (CP->isMachineConstantPoolEntry()) {
339 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
340 CP->getAlignment(), CP->getOffset());
342 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
343 CP->getAlignment(), CP->getOffset());
345 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
348 unsigned XCoreTargetLowering::getJumpTableEncoding() const {
349 return MachineJumpTableInfo::EK_Inline;
352 SDValue XCoreTargetLowering::
353 LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
355 SDValue Chain = Op.getOperand(0);
356 SDValue Table = Op.getOperand(1);
357 SDValue Index = Op.getOperand(2);
359 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
360 unsigned JTI = JT->getIndex();
361 MachineFunction &MF = DAG.getMachineFunction();
362 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
363 SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
365 unsigned NumEntries = MJTI->getJumpTables()[JTI].MBBs.size();
366 if (NumEntries <= 32) {
367 return DAG.getNode(XCoreISD::BR_JT, dl, MVT::Other, Chain, TargetJT, Index);
369 assert((NumEntries >> 31) == 0);
370 SDValue ScaledIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
371 DAG.getConstant(1, dl, MVT::i32));
372 return DAG.getNode(XCoreISD::BR_JT32, dl, MVT::Other, Chain, TargetJT,
376 SDValue XCoreTargetLowering::
377 lowerLoadWordFromAlignedBasePlusOffset(SDLoc DL, SDValue Chain, SDValue Base,
378 int64_t Offset, SelectionDAG &DAG) const
380 if ((Offset & 0x3) == 0) {
381 return DAG.getLoad(getPointerTy(), DL, Chain, Base, MachinePointerInfo(),
382 false, false, false, 0);
384 // Lower to pair of consecutive word aligned loads plus some bit shifting.
385 int32_t HighOffset = RoundUpToAlignment(Offset, 4);
386 int32_t LowOffset = HighOffset - 4;
387 SDValue LowAddr, HighAddr;
388 if (GlobalAddressSDNode *GASD =
389 dyn_cast<GlobalAddressSDNode>(Base.getNode())) {
390 LowAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
392 HighAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
395 LowAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
396 DAG.getConstant(LowOffset, DL, MVT::i32));
397 HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
398 DAG.getConstant(HighOffset, DL, MVT::i32));
400 SDValue LowShift = DAG.getConstant((Offset - LowOffset) * 8, DL, MVT::i32);
401 SDValue HighShift = DAG.getConstant((HighOffset - Offset) * 8, DL, MVT::i32);
403 SDValue Low = DAG.getLoad(getPointerTy(), DL, Chain,
404 LowAddr, MachinePointerInfo(),
405 false, false, false, 0);
406 SDValue High = DAG.getLoad(getPointerTy(), DL, Chain,
407 HighAddr, MachinePointerInfo(),
408 false, false, false, 0);
409 SDValue LowShifted = DAG.getNode(ISD::SRL, DL, MVT::i32, Low, LowShift);
410 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High, HighShift);
411 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, LowShifted, HighShifted);
412 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
414 SDValue Ops[] = { Result, Chain };
415 return DAG.getMergeValues(Ops, DL);
418 static bool isWordAligned(SDValue Value, SelectionDAG &DAG)
420 APInt KnownZero, KnownOne;
421 DAG.computeKnownBits(Value, KnownZero, KnownOne);
422 return KnownZero.countTrailingOnes() >= 2;
425 SDValue XCoreTargetLowering::
426 LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
427 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
428 LoadSDNode *LD = cast<LoadSDNode>(Op);
429 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
430 "Unexpected extension type");
431 assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
432 if (allowsMisalignedMemoryAccesses(LD->getMemoryVT(),
433 LD->getAddressSpace(),
437 unsigned ABIAlignment = getDataLayout()->
438 getABITypeAlignment(LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
439 // Leave aligned load alone.
440 if (LD->getAlignment() >= ABIAlignment)
443 SDValue Chain = LD->getChain();
444 SDValue BasePtr = LD->getBasePtr();
447 if (!LD->isVolatile()) {
448 const GlobalValue *GV;
450 if (DAG.isBaseWithConstantOffset(BasePtr) &&
451 isWordAligned(BasePtr->getOperand(0), DAG)) {
452 SDValue NewBasePtr = BasePtr->getOperand(0);
453 Offset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
454 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
457 if (TLI.isGAPlusOffset(BasePtr.getNode(), GV, Offset) &&
458 MinAlign(GV->getAlignment(), 4) == 4) {
459 SDValue NewBasePtr = DAG.getGlobalAddress(GV, DL,
460 BasePtr->getValueType(0));
461 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
466 if (LD->getAlignment() == 2) {
467 SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, DL, MVT::i32, Chain,
468 BasePtr, LD->getPointerInfo(), MVT::i16,
469 LD->isVolatile(), LD->isNonTemporal(),
470 LD->isInvariant(), 2);
471 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
472 DAG.getConstant(2, DL, MVT::i32));
473 SDValue High = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
475 LD->getPointerInfo().getWithOffset(2),
476 MVT::i16, LD->isVolatile(),
477 LD->isNonTemporal(), LD->isInvariant(), 2);
478 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High,
479 DAG.getConstant(16, DL, MVT::i32));
480 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Low, HighShifted);
481 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
483 SDValue Ops[] = { Result, Chain };
484 return DAG.getMergeValues(Ops, DL);
487 // Lower to a call to __misaligned_load(BasePtr).
488 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
489 TargetLowering::ArgListTy Args;
490 TargetLowering::ArgListEntry Entry;
493 Entry.Node = BasePtr;
494 Args.push_back(Entry);
496 TargetLowering::CallLoweringInfo CLI(DAG);
497 CLI.setDebugLoc(DL).setChain(Chain)
498 .setCallee(CallingConv::C, IntPtrTy,
499 DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
502 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
503 SDValue Ops[] = { CallResult.first, CallResult.second };
504 return DAG.getMergeValues(Ops, DL);
507 SDValue XCoreTargetLowering::
508 LowerSTORE(SDValue Op, SelectionDAG &DAG) const
510 StoreSDNode *ST = cast<StoreSDNode>(Op);
511 assert(!ST->isTruncatingStore() && "Unexpected store type");
512 assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
513 if (allowsMisalignedMemoryAccesses(ST->getMemoryVT(),
514 ST->getAddressSpace(),
515 ST->getAlignment())) {
518 unsigned ABIAlignment = getDataLayout()->
519 getABITypeAlignment(ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
520 // Leave aligned store alone.
521 if (ST->getAlignment() >= ABIAlignment) {
524 SDValue Chain = ST->getChain();
525 SDValue BasePtr = ST->getBasePtr();
526 SDValue Value = ST->getValue();
529 if (ST->getAlignment() == 2) {
531 SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
532 DAG.getConstant(16, dl, MVT::i32));
533 SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
534 ST->getPointerInfo(), MVT::i16,
535 ST->isVolatile(), ST->isNonTemporal(),
537 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
538 DAG.getConstant(2, dl, MVT::i32));
539 SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
540 ST->getPointerInfo().getWithOffset(2),
541 MVT::i16, ST->isVolatile(),
542 ST->isNonTemporal(), 2);
543 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
546 // Lower to a call to __misaligned_store(BasePtr, Value).
547 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
548 TargetLowering::ArgListTy Args;
549 TargetLowering::ArgListEntry Entry;
552 Entry.Node = BasePtr;
553 Args.push_back(Entry);
556 Args.push_back(Entry);
558 TargetLowering::CallLoweringInfo CLI(DAG);
559 CLI.setDebugLoc(dl).setChain(Chain)
560 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
561 DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
564 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
565 return CallResult.second;
568 SDValue XCoreTargetLowering::
569 LowerSMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
571 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::SMUL_LOHI &&
572 "Unexpected operand to lower!");
574 SDValue LHS = Op.getOperand(0);
575 SDValue RHS = Op.getOperand(1);
576 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
577 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
578 DAG.getVTList(MVT::i32, MVT::i32), Zero, Zero,
580 SDValue Lo(Hi.getNode(), 1);
581 SDValue Ops[] = { Lo, Hi };
582 return DAG.getMergeValues(Ops, dl);
585 SDValue XCoreTargetLowering::
586 LowerUMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
588 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::UMUL_LOHI &&
589 "Unexpected operand to lower!");
591 SDValue LHS = Op.getOperand(0);
592 SDValue RHS = Op.getOperand(1);
593 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
594 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
595 DAG.getVTList(MVT::i32, MVT::i32), LHS, RHS,
597 SDValue Lo(Hi.getNode(), 1);
598 SDValue Ops[] = { Lo, Hi };
599 return DAG.getMergeValues(Ops, dl);
602 /// isADDADDMUL - Return whether Op is in a form that is equivalent to
603 /// add(add(mul(x,y),a),b). If requireIntermediatesHaveOneUse is true then
604 /// each intermediate result in the calculation must also have a single use.
605 /// If the Op is in the correct form the constituent parts are written to Mul0,
606 /// Mul1, Addend0 and Addend1.
608 isADDADDMUL(SDValue Op, SDValue &Mul0, SDValue &Mul1, SDValue &Addend0,
609 SDValue &Addend1, bool requireIntermediatesHaveOneUse)
611 if (Op.getOpcode() != ISD::ADD)
613 SDValue N0 = Op.getOperand(0);
614 SDValue N1 = Op.getOperand(1);
617 if (N0.getOpcode() == ISD::ADD) {
620 } else if (N1.getOpcode() == ISD::ADD) {
626 if (requireIntermediatesHaveOneUse && !AddOp.hasOneUse())
628 if (OtherOp.getOpcode() == ISD::MUL) {
629 // add(add(a,b),mul(x,y))
630 if (requireIntermediatesHaveOneUse && !OtherOp.hasOneUse())
632 Mul0 = OtherOp.getOperand(0);
633 Mul1 = OtherOp.getOperand(1);
634 Addend0 = AddOp.getOperand(0);
635 Addend1 = AddOp.getOperand(1);
638 if (AddOp.getOperand(0).getOpcode() == ISD::MUL) {
639 // add(add(mul(x,y),a),b)
640 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(0).hasOneUse())
642 Mul0 = AddOp.getOperand(0).getOperand(0);
643 Mul1 = AddOp.getOperand(0).getOperand(1);
644 Addend0 = AddOp.getOperand(1);
648 if (AddOp.getOperand(1).getOpcode() == ISD::MUL) {
649 // add(add(a,mul(x,y)),b)
650 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(1).hasOneUse())
652 Mul0 = AddOp.getOperand(1).getOperand(0);
653 Mul1 = AddOp.getOperand(1).getOperand(1);
654 Addend0 = AddOp.getOperand(0);
661 SDValue XCoreTargetLowering::
662 TryExpandADDWithMul(SDNode *N, SelectionDAG &DAG) const
666 if (N->getOperand(0).getOpcode() == ISD::MUL) {
667 Mul = N->getOperand(0);
668 Other = N->getOperand(1);
669 } else if (N->getOperand(1).getOpcode() == ISD::MUL) {
670 Mul = N->getOperand(1);
671 Other = N->getOperand(0);
676 SDValue LL, RL, AddendL, AddendH;
677 LL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
678 Mul.getOperand(0), DAG.getConstant(0, dl, MVT::i32));
679 RL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
680 Mul.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
681 AddendL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
682 Other, DAG.getConstant(0, dl, MVT::i32));
683 AddendH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
684 Other, DAG.getConstant(1, dl, MVT::i32));
685 APInt HighMask = APInt::getHighBitsSet(64, 32);
686 unsigned LHSSB = DAG.ComputeNumSignBits(Mul.getOperand(0));
687 unsigned RHSSB = DAG.ComputeNumSignBits(Mul.getOperand(1));
688 if (DAG.MaskedValueIsZero(Mul.getOperand(0), HighMask) &&
689 DAG.MaskedValueIsZero(Mul.getOperand(1), HighMask)) {
690 // The inputs are both zero-extended.
691 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
692 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
694 SDValue Lo(Hi.getNode(), 1);
695 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
697 if (LHSSB > 32 && RHSSB > 32) {
698 // The inputs are both sign-extended.
699 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
700 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
702 SDValue Lo(Hi.getNode(), 1);
703 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
706 LH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
707 Mul.getOperand(0), DAG.getConstant(1, dl, MVT::i32));
708 RH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
709 Mul.getOperand(1), DAG.getConstant(1, dl, MVT::i32));
710 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
711 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
713 SDValue Lo(Hi.getNode(), 1);
714 RH = DAG.getNode(ISD::MUL, dl, MVT::i32, LL, RH);
715 LH = DAG.getNode(ISD::MUL, dl, MVT::i32, LH, RL);
716 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, RH);
717 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, LH);
718 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
721 SDValue XCoreTargetLowering::
722 ExpandADDSUB(SDNode *N, SelectionDAG &DAG) const
724 assert(N->getValueType(0) == MVT::i64 &&
725 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
726 "Unknown operand to lower!");
728 if (N->getOpcode() == ISD::ADD) {
729 SDValue Result = TryExpandADDWithMul(N, DAG);
730 if (Result.getNode())
736 // Extract components
737 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
739 DAG.getConstant(0, dl, MVT::i32));
740 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
742 DAG.getConstant(1, dl, MVT::i32));
743 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
745 DAG.getConstant(0, dl, MVT::i32));
746 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
748 DAG.getConstant(1, dl, MVT::i32));
751 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
753 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
754 SDValue Lo = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
756 SDValue Carry(Lo.getNode(), 1);
758 SDValue Hi = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
760 SDValue Ignored(Hi.getNode(), 1);
762 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
765 SDValue XCoreTargetLowering::
766 LowerVAARG(SDValue Op, SelectionDAG &DAG) const
768 // Whist llvm does not support aggregate varargs we can ignore
769 // the possibility of the ValueType being an implicit byVal vararg.
770 SDNode *Node = Op.getNode();
771 EVT VT = Node->getValueType(0); // not an aggregate
772 SDValue InChain = Node->getOperand(0);
773 SDValue VAListPtr = Node->getOperand(1);
774 EVT PtrVT = VAListPtr.getValueType();
775 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
777 SDValue VAList = DAG.getLoad(PtrVT, dl, InChain,
778 VAListPtr, MachinePointerInfo(SV),
779 false, false, false, 0);
780 // Increment the pointer, VAList, to the next vararg
781 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAList,
782 DAG.getIntPtrConstant(VT.getSizeInBits() / 8,
784 // Store the incremented VAList to the legalized pointer
785 InChain = DAG.getStore(VAList.getValue(1), dl, nextPtr, VAListPtr,
786 MachinePointerInfo(SV), false, false, 0);
787 // Load the actual argument out of the pointer VAList
788 return DAG.getLoad(VT, dl, InChain, VAList, MachinePointerInfo(),
789 false, false, false, 0);
792 SDValue XCoreTargetLowering::
793 LowerVASTART(SDValue Op, SelectionDAG &DAG) const
796 // vastart stores the address of the VarArgsFrameIndex slot into the
797 // memory location argument
798 MachineFunction &MF = DAG.getMachineFunction();
799 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
800 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
801 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1),
802 MachinePointerInfo(), false, false, 0);
805 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op,
806 SelectionDAG &DAG) const {
807 // This nodes represent llvm.frameaddress on the DAG.
808 // It takes one operand, the index of the frame address to return.
809 // An index of zero corresponds to the current function's frame address.
810 // An index of one to the parent's frame address, and so on.
811 // Depths > 0 not supported yet!
812 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
815 MachineFunction &MF = DAG.getMachineFunction();
816 const TargetRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
817 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op),
818 RegInfo->getFrameRegister(MF), MVT::i32);
821 SDValue XCoreTargetLowering::
822 LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const {
823 // This nodes represent llvm.returnaddress on the DAG.
824 // It takes one operand, the index of the return address to return.
825 // An index of zero corresponds to the current function's return address.
826 // An index of one to the parent's return address, and so on.
827 // Depths > 0 not supported yet!
828 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
831 MachineFunction &MF = DAG.getMachineFunction();
832 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
833 int FI = XFI->createLRSpillSlot(MF);
834 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
835 return DAG.getLoad(getPointerTy(), SDLoc(Op), DAG.getEntryNode(), FIN,
836 MachinePointerInfo::getFixedStack(FI), false, false,
840 SDValue XCoreTargetLowering::
841 LowerFRAME_TO_ARGS_OFFSET(SDValue Op, SelectionDAG &DAG) const {
842 // This node represents offset from frame pointer to first on-stack argument.
843 // This is needed for correct stack adjustment during unwind.
844 // However, we don't know the offset until after the frame has be finalised.
845 // This is done during the XCoreFTAOElim pass.
846 return DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, SDLoc(Op), MVT::i32);
849 SDValue XCoreTargetLowering::
850 LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
851 // OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER)
852 // This node represents 'eh_return' gcc dwarf builtin, which is used to
853 // return from exception. The general meaning is: adjust stack by OFFSET and
854 // pass execution to HANDLER.
855 MachineFunction &MF = DAG.getMachineFunction();
856 SDValue Chain = Op.getOperand(0);
857 SDValue Offset = Op.getOperand(1);
858 SDValue Handler = Op.getOperand(2);
861 // Absolute SP = (FP + FrameToArgs) + Offset
862 const TargetRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
863 SDValue Stack = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
864 RegInfo->getFrameRegister(MF), MVT::i32);
865 SDValue FrameToArgs = DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, dl,
867 Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, FrameToArgs);
868 Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, Offset);
870 // R0=ExceptionPointerRegister R1=ExceptionSelectorRegister
871 // which leaves 2 caller saved registers, R2 & R3 for us to use.
872 unsigned StackReg = XCore::R2;
873 unsigned HandlerReg = XCore::R3;
875 SDValue OutChains[] = {
876 DAG.getCopyToReg(Chain, dl, StackReg, Stack),
877 DAG.getCopyToReg(Chain, dl, HandlerReg, Handler)
880 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
882 return DAG.getNode(XCoreISD::EH_RETURN, dl, MVT::Other, Chain,
883 DAG.getRegister(StackReg, MVT::i32),
884 DAG.getRegister(HandlerReg, MVT::i32));
888 SDValue XCoreTargetLowering::
889 LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
890 return Op.getOperand(0);
893 SDValue XCoreTargetLowering::
894 LowerINIT_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
895 SDValue Chain = Op.getOperand(0);
896 SDValue Trmp = Op.getOperand(1); // trampoline
897 SDValue FPtr = Op.getOperand(2); // nested function
898 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
900 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
903 // LDAPF_u10 r11, nest
904 // LDW_2rus r11, r11[0]
905 // STWSP_ru6 r11, sp[0]
906 // LDAPF_u10 r11, fptr
907 // LDW_2rus r11, r11[0]
913 SDValue OutChains[5];
918 OutChains[0] = DAG.getStore(Chain, dl,
919 DAG.getConstant(0x0a3cd805, dl, MVT::i32), Addr,
920 MachinePointerInfo(TrmpAddr), false, false, 0);
922 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
923 DAG.getConstant(4, dl, MVT::i32));
924 OutChains[1] = DAG.getStore(Chain, dl,
925 DAG.getConstant(0xd80456c0, dl, MVT::i32), Addr,
926 MachinePointerInfo(TrmpAddr, 4), false, false, 0);
928 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
929 DAG.getConstant(8, dl, MVT::i32));
930 OutChains[2] = DAG.getStore(Chain, dl,
931 DAG.getConstant(0x27fb0a3c, dl, MVT::i32), Addr,
932 MachinePointerInfo(TrmpAddr, 8), false, false, 0);
934 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
935 DAG.getConstant(12, dl, MVT::i32));
936 OutChains[3] = DAG.getStore(Chain, dl, Nest, Addr,
937 MachinePointerInfo(TrmpAddr, 12), false, false,
940 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
941 DAG.getConstant(16, dl, MVT::i32));
942 OutChains[4] = DAG.getStore(Chain, dl, FPtr, Addr,
943 MachinePointerInfo(TrmpAddr, 16), false, false,
946 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
949 SDValue XCoreTargetLowering::
950 LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
952 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
954 case Intrinsic::xcore_crc8:
955 EVT VT = Op.getValueType();
957 DAG.getNode(XCoreISD::CRC8, DL, DAG.getVTList(VT, VT),
958 Op.getOperand(1), Op.getOperand(2) , Op.getOperand(3));
959 SDValue Crc(Data.getNode(), 1);
960 SDValue Results[] = { Crc, Data };
961 return DAG.getMergeValues(Results, DL);
966 SDValue XCoreTargetLowering::
967 LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG) const {
969 return DAG.getNode(XCoreISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
972 SDValue XCoreTargetLowering::
973 LowerATOMIC_LOAD(SDValue Op, SelectionDAG &DAG) const {
974 AtomicSDNode *N = cast<AtomicSDNode>(Op);
975 assert(N->getOpcode() == ISD::ATOMIC_LOAD && "Bad Atomic OP");
976 assert(N->getOrdering() <= Monotonic &&
977 "setInsertFencesForAtomic(true) and yet greater than Monotonic");
978 if (N->getMemoryVT() == MVT::i32) {
979 if (N->getAlignment() < 4)
980 report_fatal_error("atomic load must be aligned");
981 return DAG.getLoad(getPointerTy(), SDLoc(Op), N->getChain(),
982 N->getBasePtr(), N->getPointerInfo(),
983 N->isVolatile(), N->isNonTemporal(),
984 N->isInvariant(), N->getAlignment(),
985 N->getAAInfo(), N->getRanges());
987 if (N->getMemoryVT() == MVT::i16) {
988 if (N->getAlignment() < 2)
989 report_fatal_error("atomic load must be aligned");
990 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
991 N->getBasePtr(), N->getPointerInfo(), MVT::i16,
992 N->isVolatile(), N->isNonTemporal(),
993 N->isInvariant(), N->getAlignment(), N->getAAInfo());
995 if (N->getMemoryVT() == MVT::i8)
996 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
997 N->getBasePtr(), N->getPointerInfo(), MVT::i8,
998 N->isVolatile(), N->isNonTemporal(),
999 N->isInvariant(), N->getAlignment(), N->getAAInfo());
1003 SDValue XCoreTargetLowering::
1004 LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) const {
1005 AtomicSDNode *N = cast<AtomicSDNode>(Op);
1006 assert(N->getOpcode() == ISD::ATOMIC_STORE && "Bad Atomic OP");
1007 assert(N->getOrdering() <= Monotonic &&
1008 "setInsertFencesForAtomic(true) and yet greater than Monotonic");
1009 if (N->getMemoryVT() == MVT::i32) {
1010 if (N->getAlignment() < 4)
1011 report_fatal_error("atomic store must be aligned");
1012 return DAG.getStore(N->getChain(), SDLoc(Op), N->getVal(),
1013 N->getBasePtr(), N->getPointerInfo(),
1014 N->isVolatile(), N->isNonTemporal(),
1015 N->getAlignment(), N->getAAInfo());
1017 if (N->getMemoryVT() == MVT::i16) {
1018 if (N->getAlignment() < 2)
1019 report_fatal_error("atomic store must be aligned");
1020 return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1021 N->getBasePtr(), N->getPointerInfo(), MVT::i16,
1022 N->isVolatile(), N->isNonTemporal(),
1023 N->getAlignment(), N->getAAInfo());
1025 if (N->getMemoryVT() == MVT::i8)
1026 return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1027 N->getBasePtr(), N->getPointerInfo(), MVT::i8,
1028 N->isVolatile(), N->isNonTemporal(),
1029 N->getAlignment(), N->getAAInfo());
1033 //===----------------------------------------------------------------------===//
1034 // Calling Convention Implementation
1035 //===----------------------------------------------------------------------===//
1037 #include "XCoreGenCallingConv.inc"
1039 //===----------------------------------------------------------------------===//
1040 // Call Calling Convention Implementation
1041 //===----------------------------------------------------------------------===//
1043 /// XCore call implementation
1045 XCoreTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1046 SmallVectorImpl<SDValue> &InVals) const {
1047 SelectionDAG &DAG = CLI.DAG;
1049 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1050 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1051 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1052 SDValue Chain = CLI.Chain;
1053 SDValue Callee = CLI.Callee;
1054 bool &isTailCall = CLI.IsTailCall;
1055 CallingConv::ID CallConv = CLI.CallConv;
1056 bool isVarArg = CLI.IsVarArg;
1058 // XCore target does not yet support tail call optimization.
1061 // For now, only CallingConv::C implemented
1065 llvm_unreachable("Unsupported calling convention");
1066 case CallingConv::Fast:
1067 case CallingConv::C:
1068 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
1069 Outs, OutVals, Ins, dl, DAG, InVals);
1073 /// LowerCallResult - Lower the result values of a call into the
1074 /// appropriate copies out of appropriate physical registers / memory locations.
1076 LowerCallResult(SDValue Chain, SDValue InFlag,
1077 const SmallVectorImpl<CCValAssign> &RVLocs,
1078 SDLoc dl, SelectionDAG &DAG,
1079 SmallVectorImpl<SDValue> &InVals) {
1080 SmallVector<std::pair<int, unsigned>, 4> ResultMemLocs;
1081 // Copy results out of physical registers.
1082 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1083 const CCValAssign &VA = RVLocs[i];
1084 if (VA.isRegLoc()) {
1085 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getValVT(),
1086 InFlag).getValue(1);
1087 InFlag = Chain.getValue(2);
1088 InVals.push_back(Chain.getValue(0));
1090 assert(VA.isMemLoc());
1091 ResultMemLocs.push_back(std::make_pair(VA.getLocMemOffset(),
1093 // Reserve space for this result.
1094 InVals.push_back(SDValue());
1098 // Copy results out of memory.
1099 SmallVector<SDValue, 4> MemOpChains;
1100 for (unsigned i = 0, e = ResultMemLocs.size(); i != e; ++i) {
1101 int offset = ResultMemLocs[i].first;
1102 unsigned index = ResultMemLocs[i].second;
1103 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
1104 SDValue Ops[] = { Chain, DAG.getConstant(offset / 4, dl, MVT::i32) };
1105 SDValue load = DAG.getNode(XCoreISD::LDWSP, dl, VTs, Ops);
1106 InVals[index] = load;
1107 MemOpChains.push_back(load.getValue(1));
1110 // Transform all loads nodes into one single node because
1111 // all load nodes are independent of each other.
1112 if (!MemOpChains.empty())
1113 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1118 /// LowerCCCCallTo - functions arguments are copied from virtual
1119 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
1120 /// CALLSEQ_END are emitted.
1121 /// TODO: isTailCall, sret.
1123 XCoreTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
1124 CallingConv::ID CallConv, bool isVarArg,
1126 const SmallVectorImpl<ISD::OutputArg> &Outs,
1127 const SmallVectorImpl<SDValue> &OutVals,
1128 const SmallVectorImpl<ISD::InputArg> &Ins,
1129 SDLoc dl, SelectionDAG &DAG,
1130 SmallVectorImpl<SDValue> &InVals) const {
1132 // Analyze operands of the call, assigning locations to each operand.
1133 SmallVector<CCValAssign, 16> ArgLocs;
1134 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1137 // The ABI dictates there should be one stack slot available to the callee
1138 // on function entry (for saving lr).
1139 CCInfo.AllocateStack(4, 4);
1141 CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
1143 SmallVector<CCValAssign, 16> RVLocs;
1144 // Analyze return values to determine the number of bytes of stack required.
1145 CCState RetCCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1147 RetCCInfo.AllocateStack(CCInfo.getNextStackOffset(), 4);
1148 RetCCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
1150 // Get a count of how many bytes are to be pushed on the stack.
1151 unsigned NumBytes = RetCCInfo.getNextStackOffset();
1153 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, dl,
1154 getPointerTy(), true), dl);
1156 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
1157 SmallVector<SDValue, 12> MemOpChains;
1159 // Walk the register/memloc assignments, inserting copies/loads.
1160 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1161 CCValAssign &VA = ArgLocs[i];
1162 SDValue Arg = OutVals[i];
1164 // Promote the value if needed.
1165 switch (VA.getLocInfo()) {
1166 default: llvm_unreachable("Unknown loc info!");
1167 case CCValAssign::Full: break;
1168 case CCValAssign::SExt:
1169 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1171 case CCValAssign::ZExt:
1172 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1174 case CCValAssign::AExt:
1175 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1179 // Arguments that can be passed on register must be kept at
1180 // RegsToPass vector
1181 if (VA.isRegLoc()) {
1182 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1184 assert(VA.isMemLoc());
1186 int Offset = VA.getLocMemOffset();
1188 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
1190 DAG.getConstant(Offset/4, dl,
1195 // Transform all store nodes into one single node because
1196 // all store nodes are independent of each other.
1197 if (!MemOpChains.empty())
1198 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1200 // Build a sequence of copy-to-reg nodes chained together with token
1201 // chain and flag operands which copy the outgoing args into registers.
1202 // The InFlag in necessary since all emitted instructions must be
1205 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1206 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1207 RegsToPass[i].second, InFlag);
1208 InFlag = Chain.getValue(1);
1211 // If the callee is a GlobalAddress node (quite common, every direct call is)
1212 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1213 // Likewise ExternalSymbol -> TargetExternalSymbol.
1214 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1215 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
1216 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
1217 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
1219 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
1220 // = Chain, Callee, Reg#1, Reg#2, ...
1222 // Returns a chain & a flag for retval copy to use.
1223 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1224 SmallVector<SDValue, 8> Ops;
1225 Ops.push_back(Chain);
1226 Ops.push_back(Callee);
1228 // Add argument registers to the end of the list so that they are
1229 // known live into the call.
1230 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1231 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1232 RegsToPass[i].second.getValueType()));
1234 if (InFlag.getNode())
1235 Ops.push_back(InFlag);
1237 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, Ops);
1238 InFlag = Chain.getValue(1);
1240 // Create the CALLSEQ_END node.
1241 Chain = DAG.getCALLSEQ_END(Chain,
1242 DAG.getConstant(NumBytes, dl, getPointerTy(),
1244 DAG.getConstant(0, dl, getPointerTy(), true),
1246 InFlag = Chain.getValue(1);
1248 // Handle result values, copying them out of physregs into vregs that we
1250 return LowerCallResult(Chain, InFlag, RVLocs, dl, DAG, InVals);
1253 //===----------------------------------------------------------------------===//
1254 // Formal Arguments Calling Convention Implementation
1255 //===----------------------------------------------------------------------===//
1258 struct ArgDataPair { SDValue SDV; ISD::ArgFlagsTy Flags; };
1261 /// XCore formal arguments implementation
1263 XCoreTargetLowering::LowerFormalArguments(SDValue Chain,
1264 CallingConv::ID CallConv,
1266 const SmallVectorImpl<ISD::InputArg> &Ins,
1269 SmallVectorImpl<SDValue> &InVals)
1274 llvm_unreachable("Unsupported calling convention");
1275 case CallingConv::C:
1276 case CallingConv::Fast:
1277 return LowerCCCArguments(Chain, CallConv, isVarArg,
1278 Ins, dl, DAG, InVals);
1282 /// LowerCCCArguments - transform physical registers into
1283 /// virtual registers and generate load operations for
1284 /// arguments places on the stack.
1287 XCoreTargetLowering::LowerCCCArguments(SDValue Chain,
1288 CallingConv::ID CallConv,
1290 const SmallVectorImpl<ISD::InputArg>
1294 SmallVectorImpl<SDValue> &InVals) const {
1295 MachineFunction &MF = DAG.getMachineFunction();
1296 MachineFrameInfo *MFI = MF.getFrameInfo();
1297 MachineRegisterInfo &RegInfo = MF.getRegInfo();
1298 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1300 // Assign locations to all of the incoming arguments.
1301 SmallVector<CCValAssign, 16> ArgLocs;
1302 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1305 CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
1307 unsigned StackSlotSize = XCoreFrameLowering::stackSlotSize();
1309 unsigned LRSaveSize = StackSlotSize;
1312 XFI->setReturnStackOffset(CCInfo.getNextStackOffset() + LRSaveSize);
1314 // All getCopyFromReg ops must precede any getMemcpys to prevent the
1315 // scheduler clobbering a register before it has been copied.
1317 // 1. CopyFromReg (and load) arg & vararg registers.
1318 // 2. Chain CopyFromReg nodes into a TokenFactor.
1319 // 3. Memcpy 'byVal' args & push final InVals.
1320 // 4. Chain mem ops nodes into a TokenFactor.
1321 SmallVector<SDValue, 4> CFRegNode;
1322 SmallVector<ArgDataPair, 4> ArgData;
1323 SmallVector<SDValue, 4> MemOps;
1325 // 1a. CopyFromReg (and load) arg registers.
1326 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1328 CCValAssign &VA = ArgLocs[i];
1331 if (VA.isRegLoc()) {
1332 // Arguments passed in registers
1333 EVT RegVT = VA.getLocVT();
1334 switch (RegVT.getSimpleVT().SimpleTy) {
1338 errs() << "LowerFormalArguments Unhandled argument type: "
1339 << RegVT.getSimpleVT().SimpleTy << "\n";
1341 llvm_unreachable(nullptr);
1344 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1345 RegInfo.addLiveIn(VA.getLocReg(), VReg);
1346 ArgIn = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
1347 CFRegNode.push_back(ArgIn.getValue(ArgIn->getNumValues() - 1));
1351 assert(VA.isMemLoc());
1352 // Load the argument to a virtual register
1353 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
1354 if (ObjSize > StackSlotSize) {
1355 errs() << "LowerFormalArguments Unhandled argument type: "
1356 << EVT(VA.getLocVT()).getEVTString()
1359 // Create the frame index object for this incoming parameter...
1360 int FI = MFI->CreateFixedObject(ObjSize,
1361 LRSaveSize + VA.getLocMemOffset(),
1364 // Create the SelectionDAG nodes corresponding to a load
1365 //from this parameter
1366 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1367 ArgIn = DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
1368 MachinePointerInfo::getFixedStack(FI),
1369 false, false, false, 0);
1371 const ArgDataPair ADP = { ArgIn, Ins[i].Flags };
1372 ArgData.push_back(ADP);
1375 // 1b. CopyFromReg vararg registers.
1377 // Argument registers
1378 static const MCPhysReg ArgRegs[] = {
1379 XCore::R0, XCore::R1, XCore::R2, XCore::R3
1381 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1382 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs);
1383 if (FirstVAReg < array_lengthof(ArgRegs)) {
1385 // Save remaining registers, storing higher register numbers at a higher
1387 for (int i = array_lengthof(ArgRegs) - 1; i >= (int)FirstVAReg; --i) {
1388 // Create a stack slot
1389 int FI = MFI->CreateFixedObject(4, offset, true);
1390 if (i == (int)FirstVAReg) {
1391 XFI->setVarArgsFrameIndex(FI);
1393 offset -= StackSlotSize;
1394 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1395 // Move argument from phys reg -> virt reg
1396 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1397 RegInfo.addLiveIn(ArgRegs[i], VReg);
1398 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1399 CFRegNode.push_back(Val.getValue(Val->getNumValues() - 1));
1400 // Move argument from virt reg -> stack
1401 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
1402 MachinePointerInfo(), false, false, 0);
1403 MemOps.push_back(Store);
1406 // This will point to the next argument passed via stack.
1407 XFI->setVarArgsFrameIndex(
1408 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset(),
1413 // 2. chain CopyFromReg nodes into a TokenFactor.
1414 if (!CFRegNode.empty())
1415 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, CFRegNode);
1417 // 3. Memcpy 'byVal' args & push final InVals.
1418 // Aggregates passed "byVal" need to be copied by the callee.
1419 // The callee will use a pointer to this copy, rather than the original
1421 for (SmallVectorImpl<ArgDataPair>::const_iterator ArgDI = ArgData.begin(),
1422 ArgDE = ArgData.end();
1423 ArgDI != ArgDE; ++ArgDI) {
1424 if (ArgDI->Flags.isByVal() && ArgDI->Flags.getByValSize()) {
1425 unsigned Size = ArgDI->Flags.getByValSize();
1426 unsigned Align = std::max(StackSlotSize, ArgDI->Flags.getByValAlign());
1427 // Create a new object on the stack and copy the pointee into it.
1428 int FI = MFI->CreateStackObject(Size, Align, false);
1429 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1430 InVals.push_back(FIN);
1431 MemOps.push_back(DAG.getMemcpy(Chain, dl, FIN, ArgDI->SDV,
1432 DAG.getConstant(Size, dl, MVT::i32),
1433 Align, false, false, false,
1434 MachinePointerInfo(),
1435 MachinePointerInfo()));
1437 InVals.push_back(ArgDI->SDV);
1441 // 4, chain mem ops nodes into a TokenFactor.
1442 if (!MemOps.empty()) {
1443 MemOps.push_back(Chain);
1444 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
1450 //===----------------------------------------------------------------------===//
1451 // Return Value Calling Convention Implementation
1452 //===----------------------------------------------------------------------===//
1454 bool XCoreTargetLowering::
1455 CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF,
1457 const SmallVectorImpl<ISD::OutputArg> &Outs,
1458 LLVMContext &Context) const {
1459 SmallVector<CCValAssign, 16> RVLocs;
1460 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1461 if (!CCInfo.CheckReturn(Outs, RetCC_XCore))
1463 if (CCInfo.getNextStackOffset() != 0 && isVarArg)
1469 XCoreTargetLowering::LowerReturn(SDValue Chain,
1470 CallingConv::ID CallConv, bool isVarArg,
1471 const SmallVectorImpl<ISD::OutputArg> &Outs,
1472 const SmallVectorImpl<SDValue> &OutVals,
1473 SDLoc dl, SelectionDAG &DAG) const {
1475 XCoreFunctionInfo *XFI =
1476 DAG.getMachineFunction().getInfo<XCoreFunctionInfo>();
1477 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1479 // CCValAssign - represent the assignment of
1480 // the return value to a location
1481 SmallVector<CCValAssign, 16> RVLocs;
1483 // CCState - Info about the registers and stack slot.
1484 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1487 // Analyze return values.
1489 CCInfo.AllocateStack(XFI->getReturnStackOffset(), 4);
1491 CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
1494 SmallVector<SDValue, 4> RetOps(1, Chain);
1496 // Return on XCore is always a "retsp 0"
1497 RetOps.push_back(DAG.getConstant(0, dl, MVT::i32));
1499 SmallVector<SDValue, 4> MemOpChains;
1500 // Handle return values that must be copied to memory.
1501 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1502 CCValAssign &VA = RVLocs[i];
1505 assert(VA.isMemLoc());
1507 report_fatal_error("Can't return value from vararg function in memory");
1510 int Offset = VA.getLocMemOffset();
1511 unsigned ObjSize = VA.getLocVT().getSizeInBits() / 8;
1512 // Create the frame index object for the memory location.
1513 int FI = MFI->CreateFixedObject(ObjSize, Offset, false);
1515 // Create a SelectionDAG node corresponding to a store
1516 // to this memory location.
1517 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1518 MemOpChains.push_back(DAG.getStore(Chain, dl, OutVals[i], FIN,
1519 MachinePointerInfo::getFixedStack(FI), false, false,
1523 // Transform all store nodes into one single node because
1524 // all stores are independent of each other.
1525 if (!MemOpChains.empty())
1526 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1528 // Now handle return values copied to registers.
1529 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1530 CCValAssign &VA = RVLocs[i];
1533 // Copy the result values into the output registers.
1534 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
1536 // guarantee that all emitted copies are
1537 // stuck together, avoiding something bad
1538 Flag = Chain.getValue(1);
1539 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1542 RetOps[0] = Chain; // Update chain.
1544 // Add the flag if we have it.
1546 RetOps.push_back(Flag);
1548 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other, RetOps);
1551 //===----------------------------------------------------------------------===//
1552 // Other Lowering Code
1553 //===----------------------------------------------------------------------===//
1556 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1557 MachineBasicBlock *BB) const {
1558 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1559 DebugLoc dl = MI->getDebugLoc();
1560 assert((MI->getOpcode() == XCore::SELECT_CC) &&
1561 "Unexpected instr type to insert");
1563 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1564 // control-flow pattern. The incoming instruction knows the destination vreg
1565 // to set, the condition code register to branch on, the true/false values to
1566 // select between, and a branch opcode to use.
1567 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1568 MachineFunction::iterator It = BB;
1574 // cmpTY ccX, r1, r2
1576 // fallthrough --> copy0MBB
1577 MachineBasicBlock *thisMBB = BB;
1578 MachineFunction *F = BB->getParent();
1579 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1580 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1581 F->insert(It, copy0MBB);
1582 F->insert(It, sinkMBB);
1584 // Transfer the remainder of BB and its successor edges to sinkMBB.
1585 sinkMBB->splice(sinkMBB->begin(), BB,
1586 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1587 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1589 // Next, add the true and fallthrough blocks as its successors.
1590 BB->addSuccessor(copy0MBB);
1591 BB->addSuccessor(sinkMBB);
1593 BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1594 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1597 // %FalseValue = ...
1598 // # fallthrough to sinkMBB
1601 // Update machine-CFG edges
1602 BB->addSuccessor(sinkMBB);
1605 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1608 BuildMI(*BB, BB->begin(), dl,
1609 TII.get(XCore::PHI), MI->getOperand(0).getReg())
1610 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1611 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1613 MI->eraseFromParent(); // The pseudo instruction is gone now.
1617 //===----------------------------------------------------------------------===//
1618 // Target Optimization Hooks
1619 //===----------------------------------------------------------------------===//
1621 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1622 DAGCombinerInfo &DCI) const {
1623 SelectionDAG &DAG = DCI.DAG;
1625 switch (N->getOpcode()) {
1627 case ISD::INTRINSIC_VOID:
1628 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
1629 case Intrinsic::xcore_outt:
1630 case Intrinsic::xcore_outct:
1631 case Intrinsic::xcore_chkct: {
1632 SDValue OutVal = N->getOperand(3);
1633 // These instructions ignore the high bits.
1634 if (OutVal.hasOneUse()) {
1635 unsigned BitWidth = OutVal.getValueSizeInBits();
1636 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8);
1637 APInt KnownZero, KnownOne;
1638 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1639 !DCI.isBeforeLegalizeOps());
1640 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1641 if (TLO.ShrinkDemandedConstant(OutVal, DemandedMask) ||
1642 TLI.SimplifyDemandedBits(OutVal, DemandedMask, KnownZero, KnownOne,
1644 DCI.CommitTargetLoweringOpt(TLO);
1648 case Intrinsic::xcore_setpt: {
1649 SDValue Time = N->getOperand(3);
1650 // This instruction ignores the high bits.
1651 if (Time.hasOneUse()) {
1652 unsigned BitWidth = Time.getValueSizeInBits();
1653 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
1654 APInt KnownZero, KnownOne;
1655 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1656 !DCI.isBeforeLegalizeOps());
1657 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1658 if (TLO.ShrinkDemandedConstant(Time, DemandedMask) ||
1659 TLI.SimplifyDemandedBits(Time, DemandedMask, KnownZero, KnownOne,
1661 DCI.CommitTargetLoweringOpt(TLO);
1667 case XCoreISD::LADD: {
1668 SDValue N0 = N->getOperand(0);
1669 SDValue N1 = N->getOperand(1);
1670 SDValue N2 = N->getOperand(2);
1671 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1672 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1673 EVT VT = N0.getValueType();
1675 // canonicalize constant to RHS
1677 return DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N1, N0, N2);
1679 // fold (ladd 0, 0, x) -> 0, x & 1
1680 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1681 SDValue Carry = DAG.getConstant(0, dl, VT);
1682 SDValue Result = DAG.getNode(ISD::AND, dl, VT, N2,
1683 DAG.getConstant(1, dl, VT));
1684 SDValue Ops[] = { Result, Carry };
1685 return DAG.getMergeValues(Ops, dl);
1688 // fold (ladd x, 0, y) -> 0, add x, y iff carry is unused and y has only the
1690 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1691 APInt KnownZero, KnownOne;
1692 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1693 VT.getSizeInBits() - 1);
1694 DAG.computeKnownBits(N2, KnownZero, KnownOne);
1695 if ((KnownZero & Mask) == Mask) {
1696 SDValue Carry = DAG.getConstant(0, dl, VT);
1697 SDValue Result = DAG.getNode(ISD::ADD, dl, VT, N0, N2);
1698 SDValue Ops[] = { Result, Carry };
1699 return DAG.getMergeValues(Ops, dl);
1704 case XCoreISD::LSUB: {
1705 SDValue N0 = N->getOperand(0);
1706 SDValue N1 = N->getOperand(1);
1707 SDValue N2 = N->getOperand(2);
1708 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1709 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1710 EVT VT = N0.getValueType();
1712 // fold (lsub 0, 0, x) -> x, -x iff x has only the low bit set
1713 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1714 APInt KnownZero, KnownOne;
1715 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1716 VT.getSizeInBits() - 1);
1717 DAG.computeKnownBits(N2, KnownZero, KnownOne);
1718 if ((KnownZero & Mask) == Mask) {
1719 SDValue Borrow = N2;
1720 SDValue Result = DAG.getNode(ISD::SUB, dl, VT,
1721 DAG.getConstant(0, dl, VT), N2);
1722 SDValue Ops[] = { Result, Borrow };
1723 return DAG.getMergeValues(Ops, dl);
1727 // fold (lsub x, 0, y) -> 0, sub x, y iff borrow is unused and y has only the
1729 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1730 APInt KnownZero, KnownOne;
1731 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1732 VT.getSizeInBits() - 1);
1733 DAG.computeKnownBits(N2, KnownZero, KnownOne);
1734 if ((KnownZero & Mask) == Mask) {
1735 SDValue Borrow = DAG.getConstant(0, dl, VT);
1736 SDValue Result = DAG.getNode(ISD::SUB, dl, VT, N0, N2);
1737 SDValue Ops[] = { Result, Borrow };
1738 return DAG.getMergeValues(Ops, dl);
1743 case XCoreISD::LMUL: {
1744 SDValue N0 = N->getOperand(0);
1745 SDValue N1 = N->getOperand(1);
1746 SDValue N2 = N->getOperand(2);
1747 SDValue N3 = N->getOperand(3);
1748 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1749 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1750 EVT VT = N0.getValueType();
1751 // Canonicalize multiplicative constant to RHS. If both multiplicative
1752 // operands are constant canonicalize smallest to RHS.
1753 if ((N0C && !N1C) ||
1754 (N0C && N1C && N0C->getZExtValue() < N1C->getZExtValue()))
1755 return DAG.getNode(XCoreISD::LMUL, dl, DAG.getVTList(VT, VT),
1759 if (N1C && N1C->isNullValue()) {
1760 // If the high result is unused fold to add(a, b)
1761 if (N->hasNUsesOfValue(0, 0)) {
1762 SDValue Lo = DAG.getNode(ISD::ADD, dl, VT, N2, N3);
1763 SDValue Ops[] = { Lo, Lo };
1764 return DAG.getMergeValues(Ops, dl);
1766 // Otherwise fold to ladd(a, b, 0)
1768 DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N2, N3, N1);
1769 SDValue Carry(Result.getNode(), 1);
1770 SDValue Ops[] = { Carry, Result };
1771 return DAG.getMergeValues(Ops, dl);
1776 // Fold 32 bit expressions such as add(add(mul(x,y),a),b) ->
1777 // lmul(x, y, a, b). The high result of lmul will be ignored.
1778 // This is only profitable if the intermediate results are unused
1780 SDValue Mul0, Mul1, Addend0, Addend1;
1781 if (N->getValueType(0) == MVT::i32 &&
1782 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, true)) {
1783 SDValue Ignored = DAG.getNode(XCoreISD::LMUL, dl,
1784 DAG.getVTList(MVT::i32, MVT::i32), Mul0,
1785 Mul1, Addend0, Addend1);
1786 SDValue Result(Ignored.getNode(), 1);
1789 APInt HighMask = APInt::getHighBitsSet(64, 32);
1790 // Fold 64 bit expression such as add(add(mul(x,y),a),b) ->
1791 // lmul(x, y, a, b) if all operands are zero-extended. We do this
1792 // before type legalization as it is messy to match the operands after
1794 if (N->getValueType(0) == MVT::i64 &&
1795 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, false) &&
1796 DAG.MaskedValueIsZero(Mul0, HighMask) &&
1797 DAG.MaskedValueIsZero(Mul1, HighMask) &&
1798 DAG.MaskedValueIsZero(Addend0, HighMask) &&
1799 DAG.MaskedValueIsZero(Addend1, HighMask)) {
1800 SDValue Mul0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1801 Mul0, DAG.getConstant(0, dl, MVT::i32));
1802 SDValue Mul1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1803 Mul1, DAG.getConstant(0, dl, MVT::i32));
1804 SDValue Addend0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1805 Addend0, DAG.getConstant(0, dl, MVT::i32));
1806 SDValue Addend1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1807 Addend1, DAG.getConstant(0, dl, MVT::i32));
1808 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
1809 DAG.getVTList(MVT::i32, MVT::i32), Mul0L, Mul1L,
1810 Addend0L, Addend1L);
1811 SDValue Lo(Hi.getNode(), 1);
1812 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
1817 // Replace unaligned store of unaligned load with memmove.
1818 StoreSDNode *ST = cast<StoreSDNode>(N);
1819 if (!DCI.isBeforeLegalize() ||
1820 allowsMisalignedMemoryAccesses(ST->getMemoryVT(),
1821 ST->getAddressSpace(),
1822 ST->getAlignment()) ||
1823 ST->isVolatile() || ST->isIndexed()) {
1826 SDValue Chain = ST->getChain();
1828 unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1829 if (StoreBits % 8) {
1832 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(
1833 ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1834 unsigned Alignment = ST->getAlignment();
1835 if (Alignment >= ABIAlignment) {
1839 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1840 if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1841 LD->getAlignment() == Alignment &&
1842 !LD->isVolatile() && !LD->isIndexed() &&
1843 Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1844 bool isTail = isInTailCallPosition(DAG, ST, Chain);
1845 return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1847 DAG.getConstant(StoreBits/8, dl, MVT::i32),
1848 Alignment, false, isTail, ST->getPointerInfo(),
1849 LD->getPointerInfo());
1858 void XCoreTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
1861 const SelectionDAG &DAG,
1862 unsigned Depth) const {
1863 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
1864 switch (Op.getOpcode()) {
1866 case XCoreISD::LADD:
1867 case XCoreISD::LSUB:
1868 if (Op.getResNo() == 1) {
1869 // Top bits of carry / borrow are clear.
1870 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1871 KnownZero.getBitWidth() - 1);
1874 case ISD::INTRINSIC_W_CHAIN:
1876 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1878 case Intrinsic::xcore_getts:
1879 // High bits are known to be zero.
1880 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1881 KnownZero.getBitWidth() - 16);
1883 case Intrinsic::xcore_int:
1884 case Intrinsic::xcore_inct:
1885 // High bits are known to be zero.
1886 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1887 KnownZero.getBitWidth() - 8);
1889 case Intrinsic::xcore_testct:
1890 // Result is either 0 or 1.
1891 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1892 KnownZero.getBitWidth() - 1);
1894 case Intrinsic::xcore_testwct:
1895 // Result is in the range 0 - 4.
1896 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1897 KnownZero.getBitWidth() - 3);
1905 //===----------------------------------------------------------------------===//
1906 // Addressing mode description hooks
1907 //===----------------------------------------------------------------------===//
1909 static inline bool isImmUs(int64_t val)
1911 return (val >= 0 && val <= 11);
1914 static inline bool isImmUs2(int64_t val)
1916 return (val%2 == 0 && isImmUs(val/2));
1919 static inline bool isImmUs4(int64_t val)
1921 return (val%4 == 0 && isImmUs(val/4));
1924 /// isLegalAddressingMode - Return true if the addressing mode represented
1925 /// by AM is legal for this target, for a load/store of the specified type.
1927 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1929 if (Ty->getTypeID() == Type::VoidTyID)
1930 return AM.Scale == 0 && isImmUs(AM.BaseOffs) && isImmUs4(AM.BaseOffs);
1932 const DataLayout *TD = TM.getDataLayout();
1933 unsigned Size = TD->getTypeAllocSize(Ty);
1935 return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1942 if (AM.Scale == 0) {
1943 return isImmUs(AM.BaseOffs);
1946 return AM.Scale == 1 && AM.BaseOffs == 0;
1950 if (AM.Scale == 0) {
1951 return isImmUs2(AM.BaseOffs);
1954 return AM.Scale == 2 && AM.BaseOffs == 0;
1957 if (AM.Scale == 0) {
1958 return isImmUs4(AM.BaseOffs);
1961 return AM.Scale == 4 && AM.BaseOffs == 0;
1965 //===----------------------------------------------------------------------===//
1966 // XCore Inline Assembly Support
1967 //===----------------------------------------------------------------------===//
1969 std::pair<unsigned, const TargetRegisterClass *>
1970 XCoreTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
1971 const std::string &Constraint,
1973 if (Constraint.size() == 1) {
1974 switch (Constraint[0]) {
1977 return std::make_pair(0U, &XCore::GRRegsRegClass);
1980 // Use the default implementation in TargetLowering to convert the register
1981 // constraint into a member of a register class.
1982 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);