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
47 switch ((XCoreISD::NodeType)Opcode)
49 case XCoreISD::FIRST_NUMBER : break;
50 case XCoreISD::BL : return "XCoreISD::BL";
51 case XCoreISD::PCRelativeWrapper : return "XCoreISD::PCRelativeWrapper";
52 case XCoreISD::DPRelativeWrapper : return "XCoreISD::DPRelativeWrapper";
53 case XCoreISD::CPRelativeWrapper : return "XCoreISD::CPRelativeWrapper";
54 case XCoreISD::LDWSP : return "XCoreISD::LDWSP";
55 case XCoreISD::STWSP : return "XCoreISD::STWSP";
56 case XCoreISD::RETSP : return "XCoreISD::RETSP";
57 case XCoreISD::LADD : return "XCoreISD::LADD";
58 case XCoreISD::LSUB : return "XCoreISD::LSUB";
59 case XCoreISD::LMUL : return "XCoreISD::LMUL";
60 case XCoreISD::MACCU : return "XCoreISD::MACCU";
61 case XCoreISD::MACCS : return "XCoreISD::MACCS";
62 case XCoreISD::CRC8 : return "XCoreISD::CRC8";
63 case XCoreISD::BR_JT : return "XCoreISD::BR_JT";
64 case XCoreISD::BR_JT32 : return "XCoreISD::BR_JT32";
65 case XCoreISD::FRAME_TO_ARGS_OFFSET : return "XCoreISD::FRAME_TO_ARGS_OFFSET";
66 case XCoreISD::EH_RETURN : return "XCoreISD::EH_RETURN";
67 case XCoreISD::MEMBARRIER : return "XCoreISD::MEMBARRIER";
72 XCoreTargetLowering::XCoreTargetLowering(const TargetMachine &TM,
73 const XCoreSubtarget &Subtarget)
74 : TargetLowering(TM), TM(TM), Subtarget(Subtarget) {
76 // Set up the register classes.
77 addRegisterClass(MVT::i32, &XCore::GRRegsRegClass);
79 // Compute derived properties from the register classes
80 computeRegisterProperties(Subtarget.getRegisterInfo());
82 setStackPointerRegisterToSaveRestore(XCore::SP);
84 setSchedulingPreference(Sched::Source);
86 // Use i32 for setcc operations results (slt, sgt, ...).
87 setBooleanContents(ZeroOrOneBooleanContent);
88 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
90 // XCore does not have the NodeTypes below.
91 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
92 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
93 setOperationAction(ISD::ADDC, MVT::i32, Expand);
94 setOperationAction(ISD::ADDE, MVT::i32, Expand);
95 setOperationAction(ISD::SUBC, MVT::i32, Expand);
96 setOperationAction(ISD::SUBE, MVT::i32, Expand);
99 setOperationAction(ISD::ADD, MVT::i64, Custom);
100 setOperationAction(ISD::SUB, MVT::i64, Custom);
101 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
102 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
103 setOperationAction(ISD::MULHS, MVT::i32, Expand);
104 setOperationAction(ISD::MULHU, MVT::i32, Expand);
105 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
106 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
107 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
110 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
111 setOperationAction(ISD::ROTL , MVT::i32, Expand);
112 setOperationAction(ISD::ROTR , MVT::i32, Expand);
113 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
114 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
116 setOperationAction(ISD::TRAP, MVT::Other, Legal);
119 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
121 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
122 setOperationAction(ISD::BlockAddress, MVT::i32 , Custom);
124 // Conversion of i64 -> double produces constantpool nodes
125 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
128 for (MVT VT : MVT::integer_valuetypes()) {
129 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
130 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
131 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
133 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
134 setLoadExtAction(ISD::ZEXTLOAD, VT, 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 auto &DL = GV->getParent()->getDataLayout();
282 unsigned ObjSize = DL.getTypeAllocSize(ObjType);
283 return ObjSize < CodeModelLargeSize && ObjSize != 0;
286 SDValue XCoreTargetLowering::
287 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const
289 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
290 const GlobalValue *GV = GN->getGlobal();
292 int64_t Offset = GN->getOffset();
293 if (IsSmallObject(GV, *this)) {
294 // We can only fold positive offsets that are a multiple of the word size.
295 int64_t FoldedOffset = std::max(Offset & ~3, (int64_t)0);
296 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, FoldedOffset);
297 GA = getGlobalAddressWrapper(GA, GV, DAG);
298 // Handle the rest of the offset.
299 if (Offset != FoldedOffset) {
300 SDValue Remaining = DAG.getConstant(Offset - FoldedOffset, DL, MVT::i32);
301 GA = DAG.getNode(ISD::ADD, DL, MVT::i32, GA, Remaining);
305 // Ideally we would not fold in offset with an index <= 11.
306 Type *Ty = Type::getInt8PtrTy(*DAG.getContext());
307 Constant *GA = ConstantExpr::getBitCast(const_cast<GlobalValue*>(GV), Ty);
308 Ty = Type::getInt32Ty(*DAG.getContext());
309 Constant *Idx = ConstantInt::get(Ty, Offset);
310 Constant *GAI = ConstantExpr::getGetElementPtr(
311 Type::getInt8Ty(*DAG.getContext()), GA, Idx);
312 SDValue CP = DAG.getConstantPool(GAI, MVT::i32);
313 return DAG.getLoad(getPointerTy(DAG.getDataLayout()), DL,
314 DAG.getEntryNode(), CP, MachinePointerInfo(), false,
319 SDValue XCoreTargetLowering::
320 LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const
323 auto PtrVT = getPointerTy(DAG.getDataLayout());
324 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
325 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT);
327 return DAG.getNode(XCoreISD::PCRelativeWrapper, DL, PtrVT, 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 auto PtrVT = getPointerTy(DAG.getDataLayout());
381 if ((Offset & 0x3) == 0) {
382 return DAG.getLoad(PtrVT, DL, Chain, Base, MachinePointerInfo(), false,
385 // Lower to pair of consecutive word aligned loads plus some bit shifting.
386 int32_t HighOffset = RoundUpToAlignment(Offset, 4);
387 int32_t LowOffset = HighOffset - 4;
388 SDValue LowAddr, HighAddr;
389 if (GlobalAddressSDNode *GASD =
390 dyn_cast<GlobalAddressSDNode>(Base.getNode())) {
391 LowAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
393 HighAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
396 LowAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
397 DAG.getConstant(LowOffset, DL, MVT::i32));
398 HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
399 DAG.getConstant(HighOffset, DL, MVT::i32));
401 SDValue LowShift = DAG.getConstant((Offset - LowOffset) * 8, DL, MVT::i32);
402 SDValue HighShift = DAG.getConstant((HighOffset - Offset) * 8, DL, MVT::i32);
404 SDValue Low = DAG.getLoad(PtrVT, DL, Chain, LowAddr, MachinePointerInfo(),
405 false, false, false, 0);
406 SDValue High = DAG.getLoad(PtrVT, DL, Chain, HighAddr, MachinePointerInfo(),
407 false, false, false, 0);
408 SDValue LowShifted = DAG.getNode(ISD::SRL, DL, MVT::i32, Low, LowShift);
409 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High, HighShift);
410 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, LowShifted, HighShifted);
411 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
413 SDValue Ops[] = { Result, Chain };
414 return DAG.getMergeValues(Ops, DL);
417 static bool isWordAligned(SDValue Value, SelectionDAG &DAG)
419 APInt KnownZero, KnownOne;
420 DAG.computeKnownBits(Value, KnownZero, KnownOne);
421 return KnownZero.countTrailingOnes() >= 2;
424 SDValue XCoreTargetLowering::
425 LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
426 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
427 LoadSDNode *LD = cast<LoadSDNode>(Op);
428 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
429 "Unexpected extension type");
430 assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
431 if (allowsMisalignedMemoryAccesses(LD->getMemoryVT(),
432 LD->getAddressSpace(),
436 auto &TD = DAG.getDataLayout();
437 unsigned ABIAlignment = TD.getABITypeAlignment(
438 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 = TD.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).setCallee(
498 CallingConv::C, IntPtrTy,
499 DAG.getExternalSymbol("__misaligned_load",
500 getPointerTy(DAG.getDataLayout())),
503 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
504 SDValue Ops[] = { CallResult.first, CallResult.second };
505 return DAG.getMergeValues(Ops, DL);
508 SDValue XCoreTargetLowering::
509 LowerSTORE(SDValue Op, SelectionDAG &DAG) const
511 StoreSDNode *ST = cast<StoreSDNode>(Op);
512 assert(!ST->isTruncatingStore() && "Unexpected store type");
513 assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
514 if (allowsMisalignedMemoryAccesses(ST->getMemoryVT(),
515 ST->getAddressSpace(),
516 ST->getAlignment())) {
519 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(
520 ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
521 // Leave aligned store alone.
522 if (ST->getAlignment() >= ABIAlignment) {
525 SDValue Chain = ST->getChain();
526 SDValue BasePtr = ST->getBasePtr();
527 SDValue Value = ST->getValue();
530 if (ST->getAlignment() == 2) {
532 SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
533 DAG.getConstant(16, dl, MVT::i32));
534 SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
535 ST->getPointerInfo(), MVT::i16,
536 ST->isVolatile(), ST->isNonTemporal(),
538 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
539 DAG.getConstant(2, dl, MVT::i32));
540 SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
541 ST->getPointerInfo().getWithOffset(2),
542 MVT::i16, ST->isVolatile(),
543 ST->isNonTemporal(), 2);
544 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
547 // Lower to a call to __misaligned_store(BasePtr, Value).
548 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
549 TargetLowering::ArgListTy Args;
550 TargetLowering::ArgListEntry Entry;
553 Entry.Node = BasePtr;
554 Args.push_back(Entry);
557 Args.push_back(Entry);
559 TargetLowering::CallLoweringInfo CLI(DAG);
560 CLI.setDebugLoc(dl).setChain(Chain).setCallee(
561 CallingConv::C, Type::getVoidTy(*DAG.getContext()),
562 DAG.getExternalSymbol("__misaligned_store",
563 getPointerTy(DAG.getDataLayout())),
566 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
567 return CallResult.second;
570 SDValue XCoreTargetLowering::
571 LowerSMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
573 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::SMUL_LOHI &&
574 "Unexpected operand to lower!");
576 SDValue LHS = Op.getOperand(0);
577 SDValue RHS = Op.getOperand(1);
578 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
579 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
580 DAG.getVTList(MVT::i32, MVT::i32), Zero, Zero,
582 SDValue Lo(Hi.getNode(), 1);
583 SDValue Ops[] = { Lo, Hi };
584 return DAG.getMergeValues(Ops, dl);
587 SDValue XCoreTargetLowering::
588 LowerUMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
590 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::UMUL_LOHI &&
591 "Unexpected operand to lower!");
593 SDValue LHS = Op.getOperand(0);
594 SDValue RHS = Op.getOperand(1);
595 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
596 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
597 DAG.getVTList(MVT::i32, MVT::i32), LHS, RHS,
599 SDValue Lo(Hi.getNode(), 1);
600 SDValue Ops[] = { Lo, Hi };
601 return DAG.getMergeValues(Ops, dl);
604 /// isADDADDMUL - Return whether Op is in a form that is equivalent to
605 /// add(add(mul(x,y),a),b). If requireIntermediatesHaveOneUse is true then
606 /// each intermediate result in the calculation must also have a single use.
607 /// If the Op is in the correct form the constituent parts are written to Mul0,
608 /// Mul1, Addend0 and Addend1.
610 isADDADDMUL(SDValue Op, SDValue &Mul0, SDValue &Mul1, SDValue &Addend0,
611 SDValue &Addend1, bool requireIntermediatesHaveOneUse)
613 if (Op.getOpcode() != ISD::ADD)
615 SDValue N0 = Op.getOperand(0);
616 SDValue N1 = Op.getOperand(1);
619 if (N0.getOpcode() == ISD::ADD) {
622 } else if (N1.getOpcode() == ISD::ADD) {
628 if (requireIntermediatesHaveOneUse && !AddOp.hasOneUse())
630 if (OtherOp.getOpcode() == ISD::MUL) {
631 // add(add(a,b),mul(x,y))
632 if (requireIntermediatesHaveOneUse && !OtherOp.hasOneUse())
634 Mul0 = OtherOp.getOperand(0);
635 Mul1 = OtherOp.getOperand(1);
636 Addend0 = AddOp.getOperand(0);
637 Addend1 = AddOp.getOperand(1);
640 if (AddOp.getOperand(0).getOpcode() == ISD::MUL) {
641 // add(add(mul(x,y),a),b)
642 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(0).hasOneUse())
644 Mul0 = AddOp.getOperand(0).getOperand(0);
645 Mul1 = AddOp.getOperand(0).getOperand(1);
646 Addend0 = AddOp.getOperand(1);
650 if (AddOp.getOperand(1).getOpcode() == ISD::MUL) {
651 // add(add(a,mul(x,y)),b)
652 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(1).hasOneUse())
654 Mul0 = AddOp.getOperand(1).getOperand(0);
655 Mul1 = AddOp.getOperand(1).getOperand(1);
656 Addend0 = AddOp.getOperand(0);
663 SDValue XCoreTargetLowering::
664 TryExpandADDWithMul(SDNode *N, SelectionDAG &DAG) const
668 if (N->getOperand(0).getOpcode() == ISD::MUL) {
669 Mul = N->getOperand(0);
670 Other = N->getOperand(1);
671 } else if (N->getOperand(1).getOpcode() == ISD::MUL) {
672 Mul = N->getOperand(1);
673 Other = N->getOperand(0);
678 SDValue LL, RL, AddendL, AddendH;
679 LL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
680 Mul.getOperand(0), DAG.getConstant(0, dl, MVT::i32));
681 RL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
682 Mul.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
683 AddendL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
684 Other, DAG.getConstant(0, dl, MVT::i32));
685 AddendH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
686 Other, DAG.getConstant(1, dl, MVT::i32));
687 APInt HighMask = APInt::getHighBitsSet(64, 32);
688 unsigned LHSSB = DAG.ComputeNumSignBits(Mul.getOperand(0));
689 unsigned RHSSB = DAG.ComputeNumSignBits(Mul.getOperand(1));
690 if (DAG.MaskedValueIsZero(Mul.getOperand(0), HighMask) &&
691 DAG.MaskedValueIsZero(Mul.getOperand(1), HighMask)) {
692 // The inputs are both zero-extended.
693 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
694 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
696 SDValue Lo(Hi.getNode(), 1);
697 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
699 if (LHSSB > 32 && RHSSB > 32) {
700 // The inputs are both sign-extended.
701 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
702 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
704 SDValue Lo(Hi.getNode(), 1);
705 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
708 LH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
709 Mul.getOperand(0), DAG.getConstant(1, dl, MVT::i32));
710 RH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
711 Mul.getOperand(1), DAG.getConstant(1, dl, MVT::i32));
712 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
713 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
715 SDValue Lo(Hi.getNode(), 1);
716 RH = DAG.getNode(ISD::MUL, dl, MVT::i32, LL, RH);
717 LH = DAG.getNode(ISD::MUL, dl, MVT::i32, LH, RL);
718 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, RH);
719 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, LH);
720 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
723 SDValue XCoreTargetLowering::
724 ExpandADDSUB(SDNode *N, SelectionDAG &DAG) const
726 assert(N->getValueType(0) == MVT::i64 &&
727 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
728 "Unknown operand to lower!");
730 if (N->getOpcode() == ISD::ADD) {
731 SDValue Result = TryExpandADDWithMul(N, DAG);
732 if (Result.getNode())
738 // Extract components
739 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
741 DAG.getConstant(0, dl, MVT::i32));
742 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
744 DAG.getConstant(1, dl, MVT::i32));
745 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
747 DAG.getConstant(0, dl, MVT::i32));
748 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
750 DAG.getConstant(1, dl, MVT::i32));
753 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
755 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
756 SDValue Lo = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
758 SDValue Carry(Lo.getNode(), 1);
760 SDValue Hi = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
762 SDValue Ignored(Hi.getNode(), 1);
764 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
767 SDValue XCoreTargetLowering::
768 LowerVAARG(SDValue Op, SelectionDAG &DAG) const
770 // Whist llvm does not support aggregate varargs we can ignore
771 // the possibility of the ValueType being an implicit byVal vararg.
772 SDNode *Node = Op.getNode();
773 EVT VT = Node->getValueType(0); // not an aggregate
774 SDValue InChain = Node->getOperand(0);
775 SDValue VAListPtr = Node->getOperand(1);
776 EVT PtrVT = VAListPtr.getValueType();
777 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
779 SDValue VAList = DAG.getLoad(PtrVT, dl, InChain,
780 VAListPtr, MachinePointerInfo(SV),
781 false, false, false, 0);
782 // Increment the pointer, VAList, to the next vararg
783 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAList,
784 DAG.getIntPtrConstant(VT.getSizeInBits() / 8,
786 // Store the incremented VAList to the legalized pointer
787 InChain = DAG.getStore(VAList.getValue(1), dl, nextPtr, VAListPtr,
788 MachinePointerInfo(SV), false, false, 0);
789 // Load the actual argument out of the pointer VAList
790 return DAG.getLoad(VT, dl, InChain, VAList, MachinePointerInfo(),
791 false, false, false, 0);
794 SDValue XCoreTargetLowering::
795 LowerVASTART(SDValue Op, SelectionDAG &DAG) const
798 // vastart stores the address of the VarArgsFrameIndex slot into the
799 // memory location argument
800 MachineFunction &MF = DAG.getMachineFunction();
801 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
802 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
803 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1),
804 MachinePointerInfo(), false, false, 0);
807 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op,
808 SelectionDAG &DAG) const {
809 // This nodes represent llvm.frameaddress on the DAG.
810 // It takes one operand, the index of the frame address to return.
811 // An index of zero corresponds to the current function's frame address.
812 // An index of one to the parent's frame address, and so on.
813 // Depths > 0 not supported yet!
814 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
817 MachineFunction &MF = DAG.getMachineFunction();
818 const TargetRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
819 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op),
820 RegInfo->getFrameRegister(MF), MVT::i32);
823 SDValue XCoreTargetLowering::
824 LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const {
825 // This nodes represent llvm.returnaddress on the DAG.
826 // It takes one operand, the index of the return address to return.
827 // An index of zero corresponds to the current function's return address.
828 // An index of one to the parent's return address, and so on.
829 // Depths > 0 not supported yet!
830 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
833 MachineFunction &MF = DAG.getMachineFunction();
834 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
835 int FI = XFI->createLRSpillSlot(MF);
836 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
838 getPointerTy(DAG.getDataLayout()), SDLoc(Op), DAG.getEntryNode(), FIN,
839 MachinePointerInfo::getFixedStack(MF, FI), false, false, false, 0);
842 SDValue XCoreTargetLowering::
843 LowerFRAME_TO_ARGS_OFFSET(SDValue Op, SelectionDAG &DAG) const {
844 // This node represents offset from frame pointer to first on-stack argument.
845 // This is needed for correct stack adjustment during unwind.
846 // However, we don't know the offset until after the frame has be finalised.
847 // This is done during the XCoreFTAOElim pass.
848 return DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, SDLoc(Op), MVT::i32);
851 SDValue XCoreTargetLowering::
852 LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
853 // OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER)
854 // This node represents 'eh_return' gcc dwarf builtin, which is used to
855 // return from exception. The general meaning is: adjust stack by OFFSET and
856 // pass execution to HANDLER.
857 MachineFunction &MF = DAG.getMachineFunction();
858 SDValue Chain = Op.getOperand(0);
859 SDValue Offset = Op.getOperand(1);
860 SDValue Handler = Op.getOperand(2);
863 // Absolute SP = (FP + FrameToArgs) + Offset
864 const TargetRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
865 SDValue Stack = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
866 RegInfo->getFrameRegister(MF), MVT::i32);
867 SDValue FrameToArgs = DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, dl,
869 Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, FrameToArgs);
870 Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, Offset);
872 // R0=ExceptionPointerRegister R1=ExceptionSelectorRegister
873 // which leaves 2 caller saved registers, R2 & R3 for us to use.
874 unsigned StackReg = XCore::R2;
875 unsigned HandlerReg = XCore::R3;
877 SDValue OutChains[] = {
878 DAG.getCopyToReg(Chain, dl, StackReg, Stack),
879 DAG.getCopyToReg(Chain, dl, HandlerReg, Handler)
882 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
884 return DAG.getNode(XCoreISD::EH_RETURN, dl, MVT::Other, Chain,
885 DAG.getRegister(StackReg, MVT::i32),
886 DAG.getRegister(HandlerReg, MVT::i32));
890 SDValue XCoreTargetLowering::
891 LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
892 return Op.getOperand(0);
895 SDValue XCoreTargetLowering::
896 LowerINIT_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
897 SDValue Chain = Op.getOperand(0);
898 SDValue Trmp = Op.getOperand(1); // trampoline
899 SDValue FPtr = Op.getOperand(2); // nested function
900 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
902 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
905 // LDAPF_u10 r11, nest
906 // LDW_2rus r11, r11[0]
907 // STWSP_ru6 r11, sp[0]
908 // LDAPF_u10 r11, fptr
909 // LDW_2rus r11, r11[0]
915 SDValue OutChains[5];
920 OutChains[0] = DAG.getStore(Chain, dl,
921 DAG.getConstant(0x0a3cd805, dl, MVT::i32), Addr,
922 MachinePointerInfo(TrmpAddr), false, false, 0);
924 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
925 DAG.getConstant(4, dl, MVT::i32));
926 OutChains[1] = DAG.getStore(Chain, dl,
927 DAG.getConstant(0xd80456c0, dl, MVT::i32), Addr,
928 MachinePointerInfo(TrmpAddr, 4), false, false, 0);
930 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
931 DAG.getConstant(8, dl, MVT::i32));
932 OutChains[2] = DAG.getStore(Chain, dl,
933 DAG.getConstant(0x27fb0a3c, dl, MVT::i32), Addr,
934 MachinePointerInfo(TrmpAddr, 8), false, false, 0);
936 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
937 DAG.getConstant(12, dl, MVT::i32));
938 OutChains[3] = DAG.getStore(Chain, dl, Nest, Addr,
939 MachinePointerInfo(TrmpAddr, 12), false, false,
942 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
943 DAG.getConstant(16, dl, MVT::i32));
944 OutChains[4] = DAG.getStore(Chain, dl, FPtr, Addr,
945 MachinePointerInfo(TrmpAddr, 16), false, false,
948 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
951 SDValue XCoreTargetLowering::
952 LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
954 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
956 case Intrinsic::xcore_crc8:
957 EVT VT = Op.getValueType();
959 DAG.getNode(XCoreISD::CRC8, DL, DAG.getVTList(VT, VT),
960 Op.getOperand(1), Op.getOperand(2) , Op.getOperand(3));
961 SDValue Crc(Data.getNode(), 1);
962 SDValue Results[] = { Crc, Data };
963 return DAG.getMergeValues(Results, DL);
968 SDValue XCoreTargetLowering::
969 LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG) const {
971 return DAG.getNode(XCoreISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
974 SDValue XCoreTargetLowering::
975 LowerATOMIC_LOAD(SDValue Op, SelectionDAG &DAG) const {
976 AtomicSDNode *N = cast<AtomicSDNode>(Op);
977 assert(N->getOpcode() == ISD::ATOMIC_LOAD && "Bad Atomic OP");
978 assert(N->getOrdering() <= Monotonic &&
979 "setInsertFencesForAtomic(true) and yet greater than Monotonic");
980 if (N->getMemoryVT() == MVT::i32) {
981 if (N->getAlignment() < 4)
982 report_fatal_error("atomic load must be aligned");
983 return DAG.getLoad(getPointerTy(DAG.getDataLayout()), SDLoc(Op),
984 N->getChain(), N->getBasePtr(), N->getPointerInfo(),
985 N->isVolatile(), N->isNonTemporal(), N->isInvariant(),
986 N->getAlignment(), N->getAAInfo(), N->getRanges());
988 if (N->getMemoryVT() == MVT::i16) {
989 if (N->getAlignment() < 2)
990 report_fatal_error("atomic load must be aligned");
991 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
992 N->getBasePtr(), N->getPointerInfo(), MVT::i16,
993 N->isVolatile(), N->isNonTemporal(),
994 N->isInvariant(), N->getAlignment(), N->getAAInfo());
996 if (N->getMemoryVT() == MVT::i8)
997 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
998 N->getBasePtr(), N->getPointerInfo(), MVT::i8,
999 N->isVolatile(), N->isNonTemporal(),
1000 N->isInvariant(), N->getAlignment(), N->getAAInfo());
1004 SDValue XCoreTargetLowering::
1005 LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) const {
1006 AtomicSDNode *N = cast<AtomicSDNode>(Op);
1007 assert(N->getOpcode() == ISD::ATOMIC_STORE && "Bad Atomic OP");
1008 assert(N->getOrdering() <= Monotonic &&
1009 "setInsertFencesForAtomic(true) and yet greater than Monotonic");
1010 if (N->getMemoryVT() == MVT::i32) {
1011 if (N->getAlignment() < 4)
1012 report_fatal_error("atomic store must be aligned");
1013 return DAG.getStore(N->getChain(), SDLoc(Op), N->getVal(),
1014 N->getBasePtr(), N->getPointerInfo(),
1015 N->isVolatile(), N->isNonTemporal(),
1016 N->getAlignment(), N->getAAInfo());
1018 if (N->getMemoryVT() == MVT::i16) {
1019 if (N->getAlignment() < 2)
1020 report_fatal_error("atomic store must be aligned");
1021 return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1022 N->getBasePtr(), N->getPointerInfo(), MVT::i16,
1023 N->isVolatile(), N->isNonTemporal(),
1024 N->getAlignment(), N->getAAInfo());
1026 if (N->getMemoryVT() == MVT::i8)
1027 return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1028 N->getBasePtr(), N->getPointerInfo(), MVT::i8,
1029 N->isVolatile(), N->isNonTemporal(),
1030 N->getAlignment(), N->getAAInfo());
1034 //===----------------------------------------------------------------------===//
1035 // Calling Convention Implementation
1036 //===----------------------------------------------------------------------===//
1038 #include "XCoreGenCallingConv.inc"
1040 //===----------------------------------------------------------------------===//
1041 // Call Calling Convention Implementation
1042 //===----------------------------------------------------------------------===//
1044 /// XCore call implementation
1046 XCoreTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1047 SmallVectorImpl<SDValue> &InVals) const {
1048 SelectionDAG &DAG = CLI.DAG;
1050 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1051 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1052 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1053 SDValue Chain = CLI.Chain;
1054 SDValue Callee = CLI.Callee;
1055 bool &isTailCall = CLI.IsTailCall;
1056 CallingConv::ID CallConv = CLI.CallConv;
1057 bool isVarArg = CLI.IsVarArg;
1059 // XCore target does not yet support tail call optimization.
1062 // For now, only CallingConv::C implemented
1066 llvm_unreachable("Unsupported calling convention");
1067 case CallingConv::Fast:
1068 case CallingConv::C:
1069 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
1070 Outs, OutVals, Ins, dl, DAG, InVals);
1074 /// LowerCallResult - Lower the result values of a call into the
1075 /// appropriate copies out of appropriate physical registers / memory locations.
1077 LowerCallResult(SDValue Chain, SDValue InFlag,
1078 const SmallVectorImpl<CCValAssign> &RVLocs,
1079 SDLoc dl, SelectionDAG &DAG,
1080 SmallVectorImpl<SDValue> &InVals) {
1081 SmallVector<std::pair<int, unsigned>, 4> ResultMemLocs;
1082 // Copy results out of physical registers.
1083 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1084 const CCValAssign &VA = RVLocs[i];
1085 if (VA.isRegLoc()) {
1086 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getValVT(),
1087 InFlag).getValue(1);
1088 InFlag = Chain.getValue(2);
1089 InVals.push_back(Chain.getValue(0));
1091 assert(VA.isMemLoc());
1092 ResultMemLocs.push_back(std::make_pair(VA.getLocMemOffset(),
1094 // Reserve space for this result.
1095 InVals.push_back(SDValue());
1099 // Copy results out of memory.
1100 SmallVector<SDValue, 4> MemOpChains;
1101 for (unsigned i = 0, e = ResultMemLocs.size(); i != e; ++i) {
1102 int offset = ResultMemLocs[i].first;
1103 unsigned index = ResultMemLocs[i].second;
1104 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
1105 SDValue Ops[] = { Chain, DAG.getConstant(offset / 4, dl, MVT::i32) };
1106 SDValue load = DAG.getNode(XCoreISD::LDWSP, dl, VTs, Ops);
1107 InVals[index] = load;
1108 MemOpChains.push_back(load.getValue(1));
1111 // Transform all loads nodes into one single node because
1112 // all load nodes are independent of each other.
1113 if (!MemOpChains.empty())
1114 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1119 /// LowerCCCCallTo - functions arguments are copied from virtual
1120 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
1121 /// CALLSEQ_END are emitted.
1122 /// TODO: isTailCall, sret.
1124 XCoreTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
1125 CallingConv::ID CallConv, bool isVarArg,
1127 const SmallVectorImpl<ISD::OutputArg> &Outs,
1128 const SmallVectorImpl<SDValue> &OutVals,
1129 const SmallVectorImpl<ISD::InputArg> &Ins,
1130 SDLoc dl, SelectionDAG &DAG,
1131 SmallVectorImpl<SDValue> &InVals) const {
1133 // Analyze operands of the call, assigning locations to each operand.
1134 SmallVector<CCValAssign, 16> ArgLocs;
1135 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1138 // The ABI dictates there should be one stack slot available to the callee
1139 // on function entry (for saving lr).
1140 CCInfo.AllocateStack(4, 4);
1142 CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
1144 SmallVector<CCValAssign, 16> RVLocs;
1145 // Analyze return values to determine the number of bytes of stack required.
1146 CCState RetCCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1148 RetCCInfo.AllocateStack(CCInfo.getNextStackOffset(), 4);
1149 RetCCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
1151 // Get a count of how many bytes are to be pushed on the stack.
1152 unsigned NumBytes = RetCCInfo.getNextStackOffset();
1153 auto PtrVT = getPointerTy(DAG.getDataLayout());
1155 Chain = DAG.getCALLSEQ_START(Chain,
1156 DAG.getConstant(NumBytes, dl, PtrVT, true), dl);
1158 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
1159 SmallVector<SDValue, 12> MemOpChains;
1161 // Walk the register/memloc assignments, inserting copies/loads.
1162 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1163 CCValAssign &VA = ArgLocs[i];
1164 SDValue Arg = OutVals[i];
1166 // Promote the value if needed.
1167 switch (VA.getLocInfo()) {
1168 default: llvm_unreachable("Unknown loc info!");
1169 case CCValAssign::Full: break;
1170 case CCValAssign::SExt:
1171 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1173 case CCValAssign::ZExt:
1174 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1176 case CCValAssign::AExt:
1177 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1181 // Arguments that can be passed on register must be kept at
1182 // RegsToPass vector
1183 if (VA.isRegLoc()) {
1184 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1186 assert(VA.isMemLoc());
1188 int Offset = VA.getLocMemOffset();
1190 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
1192 DAG.getConstant(Offset/4, dl,
1197 // Transform all store nodes into one single node because
1198 // all store nodes are independent of each other.
1199 if (!MemOpChains.empty())
1200 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1202 // Build a sequence of copy-to-reg nodes chained together with token
1203 // chain and flag operands which copy the outgoing args into registers.
1204 // The InFlag in necessary since all emitted instructions must be
1207 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1208 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1209 RegsToPass[i].second, InFlag);
1210 InFlag = Chain.getValue(1);
1213 // If the callee is a GlobalAddress node (quite common, every direct call is)
1214 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1215 // Likewise ExternalSymbol -> TargetExternalSymbol.
1216 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1217 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
1218 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
1219 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
1221 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
1222 // = Chain, Callee, Reg#1, Reg#2, ...
1224 // Returns a chain & a flag for retval copy to use.
1225 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1226 SmallVector<SDValue, 8> Ops;
1227 Ops.push_back(Chain);
1228 Ops.push_back(Callee);
1230 // Add argument registers to the end of the list so that they are
1231 // known live into the call.
1232 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1233 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1234 RegsToPass[i].second.getValueType()));
1236 if (InFlag.getNode())
1237 Ops.push_back(InFlag);
1239 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, Ops);
1240 InFlag = Chain.getValue(1);
1242 // Create the CALLSEQ_END node.
1243 Chain = DAG.getCALLSEQ_END(Chain, DAG.getConstant(NumBytes, dl, PtrVT, true),
1244 DAG.getConstant(0, dl, PtrVT, true), InFlag, dl);
1245 InFlag = Chain.getValue(1);
1247 // Handle result values, copying them out of physregs into vregs that we
1249 return LowerCallResult(Chain, InFlag, RVLocs, dl, DAG, InVals);
1252 //===----------------------------------------------------------------------===//
1253 // Formal Arguments Calling Convention Implementation
1254 //===----------------------------------------------------------------------===//
1257 struct ArgDataPair { SDValue SDV; ISD::ArgFlagsTy Flags; };
1260 /// XCore formal arguments implementation
1262 XCoreTargetLowering::LowerFormalArguments(SDValue Chain,
1263 CallingConv::ID CallConv,
1265 const SmallVectorImpl<ISD::InputArg> &Ins,
1268 SmallVectorImpl<SDValue> &InVals)
1273 llvm_unreachable("Unsupported calling convention");
1274 case CallingConv::C:
1275 case CallingConv::Fast:
1276 return LowerCCCArguments(Chain, CallConv, isVarArg,
1277 Ins, dl, DAG, InVals);
1281 /// LowerCCCArguments - transform physical registers into
1282 /// virtual registers and generate load operations for
1283 /// arguments places on the stack.
1286 XCoreTargetLowering::LowerCCCArguments(SDValue Chain,
1287 CallingConv::ID CallConv,
1289 const SmallVectorImpl<ISD::InputArg>
1293 SmallVectorImpl<SDValue> &InVals) const {
1294 MachineFunction &MF = DAG.getMachineFunction();
1295 MachineFrameInfo *MFI = MF.getFrameInfo();
1296 MachineRegisterInfo &RegInfo = MF.getRegInfo();
1297 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1299 // Assign locations to all of the incoming arguments.
1300 SmallVector<CCValAssign, 16> ArgLocs;
1301 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1304 CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
1306 unsigned StackSlotSize = XCoreFrameLowering::stackSlotSize();
1308 unsigned LRSaveSize = StackSlotSize;
1311 XFI->setReturnStackOffset(CCInfo.getNextStackOffset() + LRSaveSize);
1313 // All getCopyFromReg ops must precede any getMemcpys to prevent the
1314 // scheduler clobbering a register before it has been copied.
1316 // 1. CopyFromReg (and load) arg & vararg registers.
1317 // 2. Chain CopyFromReg nodes into a TokenFactor.
1318 // 3. Memcpy 'byVal' args & push final InVals.
1319 // 4. Chain mem ops nodes into a TokenFactor.
1320 SmallVector<SDValue, 4> CFRegNode;
1321 SmallVector<ArgDataPair, 4> ArgData;
1322 SmallVector<SDValue, 4> MemOps;
1324 // 1a. CopyFromReg (and load) arg registers.
1325 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1327 CCValAssign &VA = ArgLocs[i];
1330 if (VA.isRegLoc()) {
1331 // Arguments passed in registers
1332 EVT RegVT = VA.getLocVT();
1333 switch (RegVT.getSimpleVT().SimpleTy) {
1337 errs() << "LowerFormalArguments Unhandled argument type: "
1338 << RegVT.getSimpleVT().SimpleTy << "\n";
1340 llvm_unreachable(nullptr);
1343 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1344 RegInfo.addLiveIn(VA.getLocReg(), VReg);
1345 ArgIn = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
1346 CFRegNode.push_back(ArgIn.getValue(ArgIn->getNumValues() - 1));
1350 assert(VA.isMemLoc());
1351 // Load the argument to a virtual register
1352 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
1353 if (ObjSize > StackSlotSize) {
1354 errs() << "LowerFormalArguments Unhandled argument type: "
1355 << EVT(VA.getLocVT()).getEVTString()
1358 // Create the frame index object for this incoming parameter...
1359 int FI = MFI->CreateFixedObject(ObjSize,
1360 LRSaveSize + VA.getLocMemOffset(),
1363 // Create the SelectionDAG nodes corresponding to a load
1364 //from this parameter
1365 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1366 ArgIn = DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
1367 MachinePointerInfo::getFixedStack(MF, FI), false,
1370 const ArgDataPair ADP = { ArgIn, Ins[i].Flags };
1371 ArgData.push_back(ADP);
1374 // 1b. CopyFromReg vararg registers.
1376 // Argument registers
1377 static const MCPhysReg ArgRegs[] = {
1378 XCore::R0, XCore::R1, XCore::R2, XCore::R3
1380 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1381 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs);
1382 if (FirstVAReg < array_lengthof(ArgRegs)) {
1384 // Save remaining registers, storing higher register numbers at a higher
1386 for (int i = array_lengthof(ArgRegs) - 1; i >= (int)FirstVAReg; --i) {
1387 // Create a stack slot
1388 int FI = MFI->CreateFixedObject(4, offset, true);
1389 if (i == (int)FirstVAReg) {
1390 XFI->setVarArgsFrameIndex(FI);
1392 offset -= StackSlotSize;
1393 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1394 // Move argument from phys reg -> virt reg
1395 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1396 RegInfo.addLiveIn(ArgRegs[i], VReg);
1397 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1398 CFRegNode.push_back(Val.getValue(Val->getNumValues() - 1));
1399 // Move argument from virt reg -> stack
1400 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
1401 MachinePointerInfo(), false, false, 0);
1402 MemOps.push_back(Store);
1405 // This will point to the next argument passed via stack.
1406 XFI->setVarArgsFrameIndex(
1407 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset(),
1412 // 2. chain CopyFromReg nodes into a TokenFactor.
1413 if (!CFRegNode.empty())
1414 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, CFRegNode);
1416 // 3. Memcpy 'byVal' args & push final InVals.
1417 // Aggregates passed "byVal" need to be copied by the callee.
1418 // The callee will use a pointer to this copy, rather than the original
1420 for (SmallVectorImpl<ArgDataPair>::const_iterator ArgDI = ArgData.begin(),
1421 ArgDE = ArgData.end();
1422 ArgDI != ArgDE; ++ArgDI) {
1423 if (ArgDI->Flags.isByVal() && ArgDI->Flags.getByValSize()) {
1424 unsigned Size = ArgDI->Flags.getByValSize();
1425 unsigned Align = std::max(StackSlotSize, ArgDI->Flags.getByValAlign());
1426 // Create a new object on the stack and copy the pointee into it.
1427 int FI = MFI->CreateStackObject(Size, Align, false);
1428 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1429 InVals.push_back(FIN);
1430 MemOps.push_back(DAG.getMemcpy(Chain, dl, FIN, ArgDI->SDV,
1431 DAG.getConstant(Size, dl, MVT::i32),
1432 Align, false, false, false,
1433 MachinePointerInfo(),
1434 MachinePointerInfo()));
1436 InVals.push_back(ArgDI->SDV);
1440 // 4, chain mem ops nodes into a TokenFactor.
1441 if (!MemOps.empty()) {
1442 MemOps.push_back(Chain);
1443 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
1449 //===----------------------------------------------------------------------===//
1450 // Return Value Calling Convention Implementation
1451 //===----------------------------------------------------------------------===//
1453 bool XCoreTargetLowering::
1454 CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF,
1456 const SmallVectorImpl<ISD::OutputArg> &Outs,
1457 LLVMContext &Context) const {
1458 SmallVector<CCValAssign, 16> RVLocs;
1459 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1460 if (!CCInfo.CheckReturn(Outs, RetCC_XCore))
1462 if (CCInfo.getNextStackOffset() != 0 && isVarArg)
1468 XCoreTargetLowering::LowerReturn(SDValue Chain,
1469 CallingConv::ID CallConv, bool isVarArg,
1470 const SmallVectorImpl<ISD::OutputArg> &Outs,
1471 const SmallVectorImpl<SDValue> &OutVals,
1472 SDLoc dl, SelectionDAG &DAG) const {
1474 XCoreFunctionInfo *XFI =
1475 DAG.getMachineFunction().getInfo<XCoreFunctionInfo>();
1476 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1478 // CCValAssign - represent the assignment of
1479 // the return value to a location
1480 SmallVector<CCValAssign, 16> RVLocs;
1482 // CCState - Info about the registers and stack slot.
1483 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1486 // Analyze return values.
1488 CCInfo.AllocateStack(XFI->getReturnStackOffset(), 4);
1490 CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
1493 SmallVector<SDValue, 4> RetOps(1, Chain);
1495 // Return on XCore is always a "retsp 0"
1496 RetOps.push_back(DAG.getConstant(0, dl, MVT::i32));
1498 SmallVector<SDValue, 4> MemOpChains;
1499 // Handle return values that must be copied to memory.
1500 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1501 CCValAssign &VA = RVLocs[i];
1504 assert(VA.isMemLoc());
1506 report_fatal_error("Can't return value from vararg function in memory");
1509 int Offset = VA.getLocMemOffset();
1510 unsigned ObjSize = VA.getLocVT().getSizeInBits() / 8;
1511 // Create the frame index object for the memory location.
1512 int FI = MFI->CreateFixedObject(ObjSize, Offset, false);
1514 // Create a SelectionDAG node corresponding to a store
1515 // to this memory location.
1516 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1517 MemOpChains.push_back(DAG.getStore(
1518 Chain, dl, OutVals[i], FIN,
1519 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 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 assert((StoreBits % 8) == 0 &&
1830 "Store size in bits must be a multiple of 8");
1831 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(
1832 ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1833 unsigned Alignment = ST->getAlignment();
1834 if (Alignment >= ABIAlignment) {
1838 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1839 if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1840 LD->getAlignment() == Alignment &&
1841 !LD->isVolatile() && !LD->isIndexed() &&
1842 Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1843 bool isTail = isInTailCallPosition(DAG, ST, Chain);
1844 return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1846 DAG.getConstant(StoreBits/8, dl, MVT::i32),
1847 Alignment, false, isTail, ST->getPointerInfo(),
1848 LD->getPointerInfo());
1857 void XCoreTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
1860 const SelectionDAG &DAG,
1861 unsigned Depth) const {
1862 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
1863 switch (Op.getOpcode()) {
1865 case XCoreISD::LADD:
1866 case XCoreISD::LSUB:
1867 if (Op.getResNo() == 1) {
1868 // Top bits of carry / borrow are clear.
1869 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1870 KnownZero.getBitWidth() - 1);
1873 case ISD::INTRINSIC_W_CHAIN:
1875 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1877 case Intrinsic::xcore_getts:
1878 // High bits are known to be zero.
1879 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1880 KnownZero.getBitWidth() - 16);
1882 case Intrinsic::xcore_int:
1883 case Intrinsic::xcore_inct:
1884 // High bits are known to be zero.
1885 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1886 KnownZero.getBitWidth() - 8);
1888 case Intrinsic::xcore_testct:
1889 // Result is either 0 or 1.
1890 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1891 KnownZero.getBitWidth() - 1);
1893 case Intrinsic::xcore_testwct:
1894 // Result is in the range 0 - 4.
1895 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1896 KnownZero.getBitWidth() - 3);
1904 //===----------------------------------------------------------------------===//
1905 // Addressing mode description hooks
1906 //===----------------------------------------------------------------------===//
1908 static inline bool isImmUs(int64_t val)
1910 return (val >= 0 && val <= 11);
1913 static inline bool isImmUs2(int64_t val)
1915 return (val%2 == 0 && isImmUs(val/2));
1918 static inline bool isImmUs4(int64_t val)
1920 return (val%4 == 0 && isImmUs(val/4));
1923 /// isLegalAddressingMode - Return true if the addressing mode represented
1924 /// by AM is legal for this target, for a load/store of the specified type.
1925 bool XCoreTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1926 const AddrMode &AM, Type *Ty,
1927 unsigned AS) const {
1928 if (Ty->getTypeID() == Type::VoidTyID)
1929 return AM.Scale == 0 && isImmUs(AM.BaseOffs) && isImmUs4(AM.BaseOffs);
1931 unsigned Size = DL.getTypeAllocSize(Ty);
1933 return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1940 if (AM.Scale == 0) {
1941 return isImmUs(AM.BaseOffs);
1944 return AM.Scale == 1 && AM.BaseOffs == 0;
1948 if (AM.Scale == 0) {
1949 return isImmUs2(AM.BaseOffs);
1952 return AM.Scale == 2 && AM.BaseOffs == 0;
1955 if (AM.Scale == 0) {
1956 return isImmUs4(AM.BaseOffs);
1959 return AM.Scale == 4 && AM.BaseOffs == 0;
1963 //===----------------------------------------------------------------------===//
1964 // XCore Inline Assembly Support
1965 //===----------------------------------------------------------------------===//
1967 std::pair<unsigned, const TargetRegisterClass *>
1968 XCoreTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
1969 StringRef Constraint,
1971 if (Constraint.size() == 1) {
1972 switch (Constraint[0]) {
1975 return std::make_pair(0U, &XCore::GRRegsRegClass);
1978 // Use the default implementation in TargetLowering to convert the register
1979 // constraint into a member of a register class.
1980 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);