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 // Division is expensive
83 setIntDivIsCheap(false);
85 setStackPointerRegisterToSaveRestore(XCore::SP);
87 setSchedulingPreference(Sched::Source);
89 // Use i32 for setcc operations results (slt, sgt, ...).
90 setBooleanContents(ZeroOrOneBooleanContent);
91 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
93 // XCore does not have the NodeTypes below.
94 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
95 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
96 setOperationAction(ISD::ADDC, MVT::i32, Expand);
97 setOperationAction(ISD::ADDE, MVT::i32, Expand);
98 setOperationAction(ISD::SUBC, MVT::i32, Expand);
99 setOperationAction(ISD::SUBE, MVT::i32, Expand);
102 setOperationAction(ISD::ADD, MVT::i64, Custom);
103 setOperationAction(ISD::SUB, MVT::i64, Custom);
104 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
105 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
106 setOperationAction(ISD::MULHS, MVT::i32, Expand);
107 setOperationAction(ISD::MULHU, MVT::i32, Expand);
108 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
109 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
110 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
113 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
114 setOperationAction(ISD::ROTL , MVT::i32, Expand);
115 setOperationAction(ISD::ROTR , MVT::i32, Expand);
116 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
117 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
119 setOperationAction(ISD::TRAP, MVT::Other, Legal);
122 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
124 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
125 setOperationAction(ISD::BlockAddress, MVT::i32 , Custom);
127 // Conversion of i64 -> double produces constantpool nodes
128 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
131 for (MVT VT : MVT::integer_valuetypes()) {
132 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
133 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
134 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
136 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
137 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i16, Expand);
140 // Custom expand misaligned loads / stores.
141 setOperationAction(ISD::LOAD, MVT::i32, Custom);
142 setOperationAction(ISD::STORE, MVT::i32, Custom);
145 setOperationAction(ISD::VAEND, MVT::Other, Expand);
146 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
147 setOperationAction(ISD::VAARG, MVT::Other, Custom);
148 setOperationAction(ISD::VASTART, MVT::Other, Custom);
151 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
152 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
153 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
155 // Exception handling
156 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
157 setExceptionPointerRegister(XCore::R0);
158 setExceptionSelectorRegister(XCore::R1);
159 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
162 // We request a fence for ATOMIC_* instructions, to reduce them to Monotonic.
163 // As we are always Sequential Consistent, an ATOMIC_FENCE becomes a no OP.
164 setInsertFencesForAtomic(true);
165 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
166 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
167 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
169 // TRAMPOLINE is custom lowered.
170 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
171 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
173 // We want to custom lower some of our intrinsics.
174 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
176 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 4;
177 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize
178 = MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 2;
180 // We have target-specific dag combine patterns for the following nodes:
181 setTargetDAGCombine(ISD::STORE);
182 setTargetDAGCombine(ISD::ADD);
183 setTargetDAGCombine(ISD::INTRINSIC_VOID);
184 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
186 setMinFunctionAlignment(1);
187 setPrefFunctionAlignment(2);
190 bool XCoreTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
191 if (Val.getOpcode() != ISD::LOAD)
194 EVT VT1 = Val.getValueType();
195 if (!VT1.isSimple() || !VT1.isInteger() ||
196 !VT2.isSimple() || !VT2.isInteger())
199 switch (VT1.getSimpleVT().SimpleTy) {
208 SDValue XCoreTargetLowering::
209 LowerOperation(SDValue Op, SelectionDAG &DAG) const {
210 switch (Op.getOpcode())
212 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
213 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
214 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
215 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
216 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
217 case ISD::LOAD: return LowerLOAD(Op, DAG);
218 case ISD::STORE: return LowerSTORE(Op, DAG);
219 case ISD::VAARG: return LowerVAARG(Op, DAG);
220 case ISD::VASTART: return LowerVASTART(Op, DAG);
221 case ISD::SMUL_LOHI: return LowerSMUL_LOHI(Op, DAG);
222 case ISD::UMUL_LOHI: return LowerUMUL_LOHI(Op, DAG);
223 // FIXME: Remove these when LegalizeDAGTypes lands.
225 case ISD::SUB: return ExpandADDSUB(Op.getNode(), DAG);
226 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
227 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
228 case ISD::FRAME_TO_ARGS_OFFSET: return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
229 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
230 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
231 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
232 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
233 case ISD::ATOMIC_LOAD: return LowerATOMIC_LOAD(Op, DAG);
234 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op, DAG);
236 llvm_unreachable("unimplemented operand");
240 /// ReplaceNodeResults - Replace the results of node with an illegal result
241 /// type with new values built out of custom code.
242 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
243 SmallVectorImpl<SDValue>&Results,
244 SelectionDAG &DAG) const {
245 switch (N->getOpcode()) {
247 llvm_unreachable("Don't know how to custom expand this!");
250 Results.push_back(ExpandADDSUB(N, DAG));
255 //===----------------------------------------------------------------------===//
256 // Misc Lower Operation implementation
257 //===----------------------------------------------------------------------===//
259 SDValue XCoreTargetLowering::getGlobalAddressWrapper(SDValue GA,
260 const GlobalValue *GV,
261 SelectionDAG &DAG) const {
262 // FIXME there is no actual debug info here
265 if (GV->getType()->getElementType()->isFunctionTy())
266 return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
268 const auto *GVar = dyn_cast<GlobalVariable>(GV);
269 if ((GV->hasSection() && StringRef(GV->getSection()).startswith(".cp.")) ||
270 (GVar && GVar->isConstant() && GV->hasLocalLinkage()))
271 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
273 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
276 static bool IsSmallObject(const GlobalValue *GV, const XCoreTargetLowering &XTL) {
277 if (XTL.getTargetMachine().getCodeModel() == CodeModel::Small)
280 Type *ObjType = GV->getType()->getPointerElementType();
281 if (!ObjType->isSized())
284 unsigned ObjSize = XTL.getDataLayout()->getTypeAllocSize(ObjType);
285 return ObjSize < CodeModelLargeSize && ObjSize != 0;
288 SDValue XCoreTargetLowering::
289 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const
291 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
292 const GlobalValue *GV = GN->getGlobal();
294 int64_t Offset = GN->getOffset();
295 if (IsSmallObject(GV, *this)) {
296 // We can only fold positive offsets that are a multiple of the word size.
297 int64_t FoldedOffset = std::max(Offset & ~3, (int64_t)0);
298 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, FoldedOffset);
299 GA = getGlobalAddressWrapper(GA, GV, DAG);
300 // Handle the rest of the offset.
301 if (Offset != FoldedOffset) {
302 SDValue Remaining = DAG.getConstant(Offset - FoldedOffset, DL, MVT::i32);
303 GA = DAG.getNode(ISD::ADD, DL, MVT::i32, GA, Remaining);
307 // Ideally we would not fold in offset with an index <= 11.
308 Type *Ty = Type::getInt8PtrTy(*DAG.getContext());
309 Constant *GA = ConstantExpr::getBitCast(const_cast<GlobalValue*>(GV), Ty);
310 Ty = Type::getInt32Ty(*DAG.getContext());
311 Constant *Idx = ConstantInt::get(Ty, Offset);
312 Constant *GAI = ConstantExpr::getGetElementPtr(
313 Type::getInt8Ty(*DAG.getContext()), GA, Idx);
314 SDValue CP = DAG.getConstantPool(GAI, MVT::i32);
315 return DAG.getLoad(getPointerTy(DAG.getDataLayout()), DL,
316 DAG.getEntryNode(), CP, MachinePointerInfo(), false,
321 SDValue XCoreTargetLowering::
322 LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const
325 auto PtrVT = getPointerTy(DAG.getDataLayout());
326 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
327 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT);
329 return DAG.getNode(XCoreISD::PCRelativeWrapper, DL, PtrVT, Result);
332 SDValue XCoreTargetLowering::
333 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
335 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
336 // FIXME there isn't really debug info here
338 EVT PtrVT = Op.getValueType();
340 if (CP->isMachineConstantPoolEntry()) {
341 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
342 CP->getAlignment(), CP->getOffset());
344 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
345 CP->getAlignment(), CP->getOffset());
347 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
350 unsigned XCoreTargetLowering::getJumpTableEncoding() const {
351 return MachineJumpTableInfo::EK_Inline;
354 SDValue XCoreTargetLowering::
355 LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
357 SDValue Chain = Op.getOperand(0);
358 SDValue Table = Op.getOperand(1);
359 SDValue Index = Op.getOperand(2);
361 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
362 unsigned JTI = JT->getIndex();
363 MachineFunction &MF = DAG.getMachineFunction();
364 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
365 SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
367 unsigned NumEntries = MJTI->getJumpTables()[JTI].MBBs.size();
368 if (NumEntries <= 32) {
369 return DAG.getNode(XCoreISD::BR_JT, dl, MVT::Other, Chain, TargetJT, Index);
371 assert((NumEntries >> 31) == 0);
372 SDValue ScaledIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
373 DAG.getConstant(1, dl, MVT::i32));
374 return DAG.getNode(XCoreISD::BR_JT32, dl, MVT::Other, Chain, TargetJT,
378 SDValue XCoreTargetLowering::
379 lowerLoadWordFromAlignedBasePlusOffset(SDLoc DL, SDValue Chain, SDValue Base,
380 int64_t Offset, SelectionDAG &DAG) const
382 auto PtrVT = getPointerTy(DAG.getDataLayout());
383 if ((Offset & 0x3) == 0) {
384 return DAG.getLoad(PtrVT, DL, Chain, Base, MachinePointerInfo(), false,
387 // Lower to pair of consecutive word aligned loads plus some bit shifting.
388 int32_t HighOffset = RoundUpToAlignment(Offset, 4);
389 int32_t LowOffset = HighOffset - 4;
390 SDValue LowAddr, HighAddr;
391 if (GlobalAddressSDNode *GASD =
392 dyn_cast<GlobalAddressSDNode>(Base.getNode())) {
393 LowAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
395 HighAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
398 LowAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
399 DAG.getConstant(LowOffset, DL, MVT::i32));
400 HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
401 DAG.getConstant(HighOffset, DL, MVT::i32));
403 SDValue LowShift = DAG.getConstant((Offset - LowOffset) * 8, DL, MVT::i32);
404 SDValue HighShift = DAG.getConstant((HighOffset - Offset) * 8, DL, MVT::i32);
406 SDValue Low = DAG.getLoad(PtrVT, DL, Chain, LowAddr, MachinePointerInfo(),
407 false, false, false, 0);
408 SDValue High = DAG.getLoad(PtrVT, DL, Chain, HighAddr, MachinePointerInfo(),
409 false, false, false, 0);
410 SDValue LowShifted = DAG.getNode(ISD::SRL, DL, MVT::i32, Low, LowShift);
411 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High, HighShift);
412 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, LowShifted, HighShifted);
413 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
415 SDValue Ops[] = { Result, Chain };
416 return DAG.getMergeValues(Ops, DL);
419 static bool isWordAligned(SDValue Value, SelectionDAG &DAG)
421 APInt KnownZero, KnownOne;
422 DAG.computeKnownBits(Value, KnownZero, KnownOne);
423 return KnownZero.countTrailingOnes() >= 2;
426 SDValue XCoreTargetLowering::
427 LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
428 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
429 LoadSDNode *LD = cast<LoadSDNode>(Op);
430 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
431 "Unexpected extension type");
432 assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
433 if (allowsMisalignedMemoryAccesses(LD->getMemoryVT(),
434 LD->getAddressSpace(),
438 unsigned ABIAlignment = getDataLayout()->
439 getABITypeAlignment(LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
440 // Leave aligned load alone.
441 if (LD->getAlignment() >= ABIAlignment)
444 SDValue Chain = LD->getChain();
445 SDValue BasePtr = LD->getBasePtr();
448 if (!LD->isVolatile()) {
449 const GlobalValue *GV;
451 if (DAG.isBaseWithConstantOffset(BasePtr) &&
452 isWordAligned(BasePtr->getOperand(0), DAG)) {
453 SDValue NewBasePtr = BasePtr->getOperand(0);
454 Offset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
455 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
458 if (TLI.isGAPlusOffset(BasePtr.getNode(), GV, Offset) &&
459 MinAlign(GV->getAlignment(), 4) == 4) {
460 SDValue NewBasePtr = DAG.getGlobalAddress(GV, DL,
461 BasePtr->getValueType(0));
462 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
467 if (LD->getAlignment() == 2) {
468 SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, DL, MVT::i32, Chain,
469 BasePtr, LD->getPointerInfo(), MVT::i16,
470 LD->isVolatile(), LD->isNonTemporal(),
471 LD->isInvariant(), 2);
472 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
473 DAG.getConstant(2, DL, MVT::i32));
474 SDValue High = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
476 LD->getPointerInfo().getWithOffset(2),
477 MVT::i16, LD->isVolatile(),
478 LD->isNonTemporal(), LD->isInvariant(), 2);
479 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High,
480 DAG.getConstant(16, DL, MVT::i32));
481 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Low, HighShifted);
482 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
484 SDValue Ops[] = { Result, Chain };
485 return DAG.getMergeValues(Ops, DL);
488 // Lower to a call to __misaligned_load(BasePtr).
489 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
490 TargetLowering::ArgListTy Args;
491 TargetLowering::ArgListEntry Entry;
494 Entry.Node = BasePtr;
495 Args.push_back(Entry);
497 TargetLowering::CallLoweringInfo CLI(DAG);
498 CLI.setDebugLoc(DL).setChain(Chain).setCallee(
499 CallingConv::C, IntPtrTy,
500 DAG.getExternalSymbol("__misaligned_load",
501 getPointerTy(DAG.getDataLayout())),
504 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
505 SDValue Ops[] = { CallResult.first, CallResult.second };
506 return DAG.getMergeValues(Ops, DL);
509 SDValue XCoreTargetLowering::
510 LowerSTORE(SDValue Op, SelectionDAG &DAG) const
512 StoreSDNode *ST = cast<StoreSDNode>(Op);
513 assert(!ST->isTruncatingStore() && "Unexpected store type");
514 assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
515 if (allowsMisalignedMemoryAccesses(ST->getMemoryVT(),
516 ST->getAddressSpace(),
517 ST->getAlignment())) {
520 unsigned ABIAlignment = getDataLayout()->
521 getABITypeAlignment(ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
522 // Leave aligned store alone.
523 if (ST->getAlignment() >= ABIAlignment) {
526 SDValue Chain = ST->getChain();
527 SDValue BasePtr = ST->getBasePtr();
528 SDValue Value = ST->getValue();
531 if (ST->getAlignment() == 2) {
533 SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
534 DAG.getConstant(16, dl, MVT::i32));
535 SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
536 ST->getPointerInfo(), MVT::i16,
537 ST->isVolatile(), ST->isNonTemporal(),
539 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
540 DAG.getConstant(2, dl, MVT::i32));
541 SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
542 ST->getPointerInfo().getWithOffset(2),
543 MVT::i16, ST->isVolatile(),
544 ST->isNonTemporal(), 2);
545 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
548 // Lower to a call to __misaligned_store(BasePtr, Value).
549 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
550 TargetLowering::ArgListTy Args;
551 TargetLowering::ArgListEntry Entry;
554 Entry.Node = BasePtr;
555 Args.push_back(Entry);
558 Args.push_back(Entry);
560 TargetLowering::CallLoweringInfo CLI(DAG);
561 CLI.setDebugLoc(dl).setChain(Chain).setCallee(
562 CallingConv::C, Type::getVoidTy(*DAG.getContext()),
563 DAG.getExternalSymbol("__misaligned_store",
564 getPointerTy(DAG.getDataLayout())),
567 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
568 return CallResult.second;
571 SDValue XCoreTargetLowering::
572 LowerSMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
574 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::SMUL_LOHI &&
575 "Unexpected operand to lower!");
577 SDValue LHS = Op.getOperand(0);
578 SDValue RHS = Op.getOperand(1);
579 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
580 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
581 DAG.getVTList(MVT::i32, MVT::i32), Zero, Zero,
583 SDValue Lo(Hi.getNode(), 1);
584 SDValue Ops[] = { Lo, Hi };
585 return DAG.getMergeValues(Ops, dl);
588 SDValue XCoreTargetLowering::
589 LowerUMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
591 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::UMUL_LOHI &&
592 "Unexpected operand to lower!");
594 SDValue LHS = Op.getOperand(0);
595 SDValue RHS = Op.getOperand(1);
596 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
597 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
598 DAG.getVTList(MVT::i32, MVT::i32), LHS, RHS,
600 SDValue Lo(Hi.getNode(), 1);
601 SDValue Ops[] = { Lo, Hi };
602 return DAG.getMergeValues(Ops, dl);
605 /// isADDADDMUL - Return whether Op is in a form that is equivalent to
606 /// add(add(mul(x,y),a),b). If requireIntermediatesHaveOneUse is true then
607 /// each intermediate result in the calculation must also have a single use.
608 /// If the Op is in the correct form the constituent parts are written to Mul0,
609 /// Mul1, Addend0 and Addend1.
611 isADDADDMUL(SDValue Op, SDValue &Mul0, SDValue &Mul1, SDValue &Addend0,
612 SDValue &Addend1, bool requireIntermediatesHaveOneUse)
614 if (Op.getOpcode() != ISD::ADD)
616 SDValue N0 = Op.getOperand(0);
617 SDValue N1 = Op.getOperand(1);
620 if (N0.getOpcode() == ISD::ADD) {
623 } else if (N1.getOpcode() == ISD::ADD) {
629 if (requireIntermediatesHaveOneUse && !AddOp.hasOneUse())
631 if (OtherOp.getOpcode() == ISD::MUL) {
632 // add(add(a,b),mul(x,y))
633 if (requireIntermediatesHaveOneUse && !OtherOp.hasOneUse())
635 Mul0 = OtherOp.getOperand(0);
636 Mul1 = OtherOp.getOperand(1);
637 Addend0 = AddOp.getOperand(0);
638 Addend1 = AddOp.getOperand(1);
641 if (AddOp.getOperand(0).getOpcode() == ISD::MUL) {
642 // add(add(mul(x,y),a),b)
643 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(0).hasOneUse())
645 Mul0 = AddOp.getOperand(0).getOperand(0);
646 Mul1 = AddOp.getOperand(0).getOperand(1);
647 Addend0 = AddOp.getOperand(1);
651 if (AddOp.getOperand(1).getOpcode() == ISD::MUL) {
652 // add(add(a,mul(x,y)),b)
653 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(1).hasOneUse())
655 Mul0 = AddOp.getOperand(1).getOperand(0);
656 Mul1 = AddOp.getOperand(1).getOperand(1);
657 Addend0 = AddOp.getOperand(0);
664 SDValue XCoreTargetLowering::
665 TryExpandADDWithMul(SDNode *N, SelectionDAG &DAG) const
669 if (N->getOperand(0).getOpcode() == ISD::MUL) {
670 Mul = N->getOperand(0);
671 Other = N->getOperand(1);
672 } else if (N->getOperand(1).getOpcode() == ISD::MUL) {
673 Mul = N->getOperand(1);
674 Other = N->getOperand(0);
679 SDValue LL, RL, AddendL, AddendH;
680 LL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
681 Mul.getOperand(0), DAG.getConstant(0, dl, MVT::i32));
682 RL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
683 Mul.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
684 AddendL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
685 Other, DAG.getConstant(0, dl, MVT::i32));
686 AddendH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
687 Other, DAG.getConstant(1, dl, MVT::i32));
688 APInt HighMask = APInt::getHighBitsSet(64, 32);
689 unsigned LHSSB = DAG.ComputeNumSignBits(Mul.getOperand(0));
690 unsigned RHSSB = DAG.ComputeNumSignBits(Mul.getOperand(1));
691 if (DAG.MaskedValueIsZero(Mul.getOperand(0), HighMask) &&
692 DAG.MaskedValueIsZero(Mul.getOperand(1), HighMask)) {
693 // The inputs are both zero-extended.
694 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
695 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
697 SDValue Lo(Hi.getNode(), 1);
698 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
700 if (LHSSB > 32 && RHSSB > 32) {
701 // The inputs are both sign-extended.
702 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
703 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
705 SDValue Lo(Hi.getNode(), 1);
706 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
709 LH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
710 Mul.getOperand(0), DAG.getConstant(1, dl, MVT::i32));
711 RH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
712 Mul.getOperand(1), DAG.getConstant(1, dl, MVT::i32));
713 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
714 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
716 SDValue Lo(Hi.getNode(), 1);
717 RH = DAG.getNode(ISD::MUL, dl, MVT::i32, LL, RH);
718 LH = DAG.getNode(ISD::MUL, dl, MVT::i32, LH, RL);
719 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, RH);
720 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, LH);
721 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
724 SDValue XCoreTargetLowering::
725 ExpandADDSUB(SDNode *N, SelectionDAG &DAG) const
727 assert(N->getValueType(0) == MVT::i64 &&
728 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
729 "Unknown operand to lower!");
731 if (N->getOpcode() == ISD::ADD) {
732 SDValue Result = TryExpandADDWithMul(N, DAG);
733 if (Result.getNode())
739 // Extract components
740 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
742 DAG.getConstant(0, dl, MVT::i32));
743 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
745 DAG.getConstant(1, dl, MVT::i32));
746 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
748 DAG.getConstant(0, dl, MVT::i32));
749 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
751 DAG.getConstant(1, dl, MVT::i32));
754 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
756 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
757 SDValue Lo = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
759 SDValue Carry(Lo.getNode(), 1);
761 SDValue Hi = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
763 SDValue Ignored(Hi.getNode(), 1);
765 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
768 SDValue XCoreTargetLowering::
769 LowerVAARG(SDValue Op, SelectionDAG &DAG) const
771 // Whist llvm does not support aggregate varargs we can ignore
772 // the possibility of the ValueType being an implicit byVal vararg.
773 SDNode *Node = Op.getNode();
774 EVT VT = Node->getValueType(0); // not an aggregate
775 SDValue InChain = Node->getOperand(0);
776 SDValue VAListPtr = Node->getOperand(1);
777 EVT PtrVT = VAListPtr.getValueType();
778 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
780 SDValue VAList = DAG.getLoad(PtrVT, dl, InChain,
781 VAListPtr, MachinePointerInfo(SV),
782 false, false, false, 0);
783 // Increment the pointer, VAList, to the next vararg
784 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAList,
785 DAG.getIntPtrConstant(VT.getSizeInBits() / 8,
787 // Store the incremented VAList to the legalized pointer
788 InChain = DAG.getStore(VAList.getValue(1), dl, nextPtr, VAListPtr,
789 MachinePointerInfo(SV), false, false, 0);
790 // Load the actual argument out of the pointer VAList
791 return DAG.getLoad(VT, dl, InChain, VAList, MachinePointerInfo(),
792 false, false, false, 0);
795 SDValue XCoreTargetLowering::
796 LowerVASTART(SDValue Op, SelectionDAG &DAG) const
799 // vastart stores the address of the VarArgsFrameIndex slot into the
800 // memory location argument
801 MachineFunction &MF = DAG.getMachineFunction();
802 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
803 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
804 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1),
805 MachinePointerInfo(), false, false, 0);
808 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op,
809 SelectionDAG &DAG) const {
810 // This nodes represent llvm.frameaddress on the DAG.
811 // It takes one operand, the index of the frame address to return.
812 // An index of zero corresponds to the current function's frame address.
813 // An index of one to the parent's frame address, and so on.
814 // Depths > 0 not supported yet!
815 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
818 MachineFunction &MF = DAG.getMachineFunction();
819 const TargetRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
820 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op),
821 RegInfo->getFrameRegister(MF), MVT::i32);
824 SDValue XCoreTargetLowering::
825 LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const {
826 // This nodes represent llvm.returnaddress on the DAG.
827 // It takes one operand, the index of the return address to return.
828 // An index of zero corresponds to the current function's return address.
829 // An index of one to the parent's return address, and so on.
830 // Depths > 0 not supported yet!
831 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
834 MachineFunction &MF = DAG.getMachineFunction();
835 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
836 int FI = XFI->createLRSpillSlot(MF);
837 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
839 getPointerTy(DAG.getDataLayout()), SDLoc(Op), DAG.getEntryNode(), FIN,
840 MachinePointerInfo::getFixedStack(FI), false, false, false, 0);
843 SDValue XCoreTargetLowering::
844 LowerFRAME_TO_ARGS_OFFSET(SDValue Op, SelectionDAG &DAG) const {
845 // This node represents offset from frame pointer to first on-stack argument.
846 // This is needed for correct stack adjustment during unwind.
847 // However, we don't know the offset until after the frame has be finalised.
848 // This is done during the XCoreFTAOElim pass.
849 return DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, SDLoc(Op), MVT::i32);
852 SDValue XCoreTargetLowering::
853 LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
854 // OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER)
855 // This node represents 'eh_return' gcc dwarf builtin, which is used to
856 // return from exception. The general meaning is: adjust stack by OFFSET and
857 // pass execution to HANDLER.
858 MachineFunction &MF = DAG.getMachineFunction();
859 SDValue Chain = Op.getOperand(0);
860 SDValue Offset = Op.getOperand(1);
861 SDValue Handler = Op.getOperand(2);
864 // Absolute SP = (FP + FrameToArgs) + Offset
865 const TargetRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
866 SDValue Stack = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
867 RegInfo->getFrameRegister(MF), MVT::i32);
868 SDValue FrameToArgs = DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, dl,
870 Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, FrameToArgs);
871 Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, Offset);
873 // R0=ExceptionPointerRegister R1=ExceptionSelectorRegister
874 // which leaves 2 caller saved registers, R2 & R3 for us to use.
875 unsigned StackReg = XCore::R2;
876 unsigned HandlerReg = XCore::R3;
878 SDValue OutChains[] = {
879 DAG.getCopyToReg(Chain, dl, StackReg, Stack),
880 DAG.getCopyToReg(Chain, dl, HandlerReg, Handler)
883 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
885 return DAG.getNode(XCoreISD::EH_RETURN, dl, MVT::Other, Chain,
886 DAG.getRegister(StackReg, MVT::i32),
887 DAG.getRegister(HandlerReg, MVT::i32));
891 SDValue XCoreTargetLowering::
892 LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
893 return Op.getOperand(0);
896 SDValue XCoreTargetLowering::
897 LowerINIT_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
898 SDValue Chain = Op.getOperand(0);
899 SDValue Trmp = Op.getOperand(1); // trampoline
900 SDValue FPtr = Op.getOperand(2); // nested function
901 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
903 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
906 // LDAPF_u10 r11, nest
907 // LDW_2rus r11, r11[0]
908 // STWSP_ru6 r11, sp[0]
909 // LDAPF_u10 r11, fptr
910 // LDW_2rus r11, r11[0]
916 SDValue OutChains[5];
921 OutChains[0] = DAG.getStore(Chain, dl,
922 DAG.getConstant(0x0a3cd805, dl, MVT::i32), Addr,
923 MachinePointerInfo(TrmpAddr), false, false, 0);
925 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
926 DAG.getConstant(4, dl, MVT::i32));
927 OutChains[1] = DAG.getStore(Chain, dl,
928 DAG.getConstant(0xd80456c0, dl, MVT::i32), Addr,
929 MachinePointerInfo(TrmpAddr, 4), false, false, 0);
931 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
932 DAG.getConstant(8, dl, MVT::i32));
933 OutChains[2] = DAG.getStore(Chain, dl,
934 DAG.getConstant(0x27fb0a3c, dl, MVT::i32), Addr,
935 MachinePointerInfo(TrmpAddr, 8), false, false, 0);
937 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
938 DAG.getConstant(12, dl, MVT::i32));
939 OutChains[3] = DAG.getStore(Chain, dl, Nest, Addr,
940 MachinePointerInfo(TrmpAddr, 12), false, false,
943 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
944 DAG.getConstant(16, dl, MVT::i32));
945 OutChains[4] = DAG.getStore(Chain, dl, FPtr, Addr,
946 MachinePointerInfo(TrmpAddr, 16), false, false,
949 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
952 SDValue XCoreTargetLowering::
953 LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
955 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
957 case Intrinsic::xcore_crc8:
958 EVT VT = Op.getValueType();
960 DAG.getNode(XCoreISD::CRC8, DL, DAG.getVTList(VT, VT),
961 Op.getOperand(1), Op.getOperand(2) , Op.getOperand(3));
962 SDValue Crc(Data.getNode(), 1);
963 SDValue Results[] = { Crc, Data };
964 return DAG.getMergeValues(Results, DL);
969 SDValue XCoreTargetLowering::
970 LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG) const {
972 return DAG.getNode(XCoreISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
975 SDValue XCoreTargetLowering::
976 LowerATOMIC_LOAD(SDValue Op, SelectionDAG &DAG) const {
977 AtomicSDNode *N = cast<AtomicSDNode>(Op);
978 assert(N->getOpcode() == ISD::ATOMIC_LOAD && "Bad Atomic OP");
979 assert(N->getOrdering() <= Monotonic &&
980 "setInsertFencesForAtomic(true) and yet greater than Monotonic");
981 if (N->getMemoryVT() == MVT::i32) {
982 if (N->getAlignment() < 4)
983 report_fatal_error("atomic load must be aligned");
984 return DAG.getLoad(getPointerTy(DAG.getDataLayout()), SDLoc(Op),
985 N->getChain(), N->getBasePtr(), N->getPointerInfo(),
986 N->isVolatile(), N->isNonTemporal(), N->isInvariant(),
987 N->getAlignment(), N->getAAInfo(), N->getRanges());
989 if (N->getMemoryVT() == MVT::i16) {
990 if (N->getAlignment() < 2)
991 report_fatal_error("atomic load must be aligned");
992 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
993 N->getBasePtr(), N->getPointerInfo(), MVT::i16,
994 N->isVolatile(), N->isNonTemporal(),
995 N->isInvariant(), N->getAlignment(), N->getAAInfo());
997 if (N->getMemoryVT() == MVT::i8)
998 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
999 N->getBasePtr(), N->getPointerInfo(), MVT::i8,
1000 N->isVolatile(), N->isNonTemporal(),
1001 N->isInvariant(), N->getAlignment(), N->getAAInfo());
1005 SDValue XCoreTargetLowering::
1006 LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) const {
1007 AtomicSDNode *N = cast<AtomicSDNode>(Op);
1008 assert(N->getOpcode() == ISD::ATOMIC_STORE && "Bad Atomic OP");
1009 assert(N->getOrdering() <= Monotonic &&
1010 "setInsertFencesForAtomic(true) and yet greater than Monotonic");
1011 if (N->getMemoryVT() == MVT::i32) {
1012 if (N->getAlignment() < 4)
1013 report_fatal_error("atomic store must be aligned");
1014 return DAG.getStore(N->getChain(), SDLoc(Op), N->getVal(),
1015 N->getBasePtr(), N->getPointerInfo(),
1016 N->isVolatile(), N->isNonTemporal(),
1017 N->getAlignment(), N->getAAInfo());
1019 if (N->getMemoryVT() == MVT::i16) {
1020 if (N->getAlignment() < 2)
1021 report_fatal_error("atomic store must be aligned");
1022 return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1023 N->getBasePtr(), N->getPointerInfo(), MVT::i16,
1024 N->isVolatile(), N->isNonTemporal(),
1025 N->getAlignment(), N->getAAInfo());
1027 if (N->getMemoryVT() == MVT::i8)
1028 return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1029 N->getBasePtr(), N->getPointerInfo(), MVT::i8,
1030 N->isVolatile(), N->isNonTemporal(),
1031 N->getAlignment(), N->getAAInfo());
1035 //===----------------------------------------------------------------------===//
1036 // Calling Convention Implementation
1037 //===----------------------------------------------------------------------===//
1039 #include "XCoreGenCallingConv.inc"
1041 //===----------------------------------------------------------------------===//
1042 // Call Calling Convention Implementation
1043 //===----------------------------------------------------------------------===//
1045 /// XCore call implementation
1047 XCoreTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1048 SmallVectorImpl<SDValue> &InVals) const {
1049 SelectionDAG &DAG = CLI.DAG;
1051 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1052 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1053 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1054 SDValue Chain = CLI.Chain;
1055 SDValue Callee = CLI.Callee;
1056 bool &isTailCall = CLI.IsTailCall;
1057 CallingConv::ID CallConv = CLI.CallConv;
1058 bool isVarArg = CLI.IsVarArg;
1060 // XCore target does not yet support tail call optimization.
1063 // For now, only CallingConv::C implemented
1067 llvm_unreachable("Unsupported calling convention");
1068 case CallingConv::Fast:
1069 case CallingConv::C:
1070 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
1071 Outs, OutVals, Ins, dl, DAG, InVals);
1075 /// LowerCallResult - Lower the result values of a call into the
1076 /// appropriate copies out of appropriate physical registers / memory locations.
1078 LowerCallResult(SDValue Chain, SDValue InFlag,
1079 const SmallVectorImpl<CCValAssign> &RVLocs,
1080 SDLoc dl, SelectionDAG &DAG,
1081 SmallVectorImpl<SDValue> &InVals) {
1082 SmallVector<std::pair<int, unsigned>, 4> ResultMemLocs;
1083 // Copy results out of physical registers.
1084 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1085 const CCValAssign &VA = RVLocs[i];
1086 if (VA.isRegLoc()) {
1087 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getValVT(),
1088 InFlag).getValue(1);
1089 InFlag = Chain.getValue(2);
1090 InVals.push_back(Chain.getValue(0));
1092 assert(VA.isMemLoc());
1093 ResultMemLocs.push_back(std::make_pair(VA.getLocMemOffset(),
1095 // Reserve space for this result.
1096 InVals.push_back(SDValue());
1100 // Copy results out of memory.
1101 SmallVector<SDValue, 4> MemOpChains;
1102 for (unsigned i = 0, e = ResultMemLocs.size(); i != e; ++i) {
1103 int offset = ResultMemLocs[i].first;
1104 unsigned index = ResultMemLocs[i].second;
1105 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
1106 SDValue Ops[] = { Chain, DAG.getConstant(offset / 4, dl, MVT::i32) };
1107 SDValue load = DAG.getNode(XCoreISD::LDWSP, dl, VTs, Ops);
1108 InVals[index] = load;
1109 MemOpChains.push_back(load.getValue(1));
1112 // Transform all loads nodes into one single node because
1113 // all load nodes are independent of each other.
1114 if (!MemOpChains.empty())
1115 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1120 /// LowerCCCCallTo - functions arguments are copied from virtual
1121 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
1122 /// CALLSEQ_END are emitted.
1123 /// TODO: isTailCall, sret.
1125 XCoreTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
1126 CallingConv::ID CallConv, bool isVarArg,
1128 const SmallVectorImpl<ISD::OutputArg> &Outs,
1129 const SmallVectorImpl<SDValue> &OutVals,
1130 const SmallVectorImpl<ISD::InputArg> &Ins,
1131 SDLoc dl, SelectionDAG &DAG,
1132 SmallVectorImpl<SDValue> &InVals) const {
1134 // Analyze operands of the call, assigning locations to each operand.
1135 SmallVector<CCValAssign, 16> ArgLocs;
1136 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1139 // The ABI dictates there should be one stack slot available to the callee
1140 // on function entry (for saving lr).
1141 CCInfo.AllocateStack(4, 4);
1143 CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
1145 SmallVector<CCValAssign, 16> RVLocs;
1146 // Analyze return values to determine the number of bytes of stack required.
1147 CCState RetCCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1149 RetCCInfo.AllocateStack(CCInfo.getNextStackOffset(), 4);
1150 RetCCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
1152 // Get a count of how many bytes are to be pushed on the stack.
1153 unsigned NumBytes = RetCCInfo.getNextStackOffset();
1154 auto PtrVT = getPointerTy(DAG.getDataLayout());
1156 Chain = DAG.getCALLSEQ_START(Chain,
1157 DAG.getConstant(NumBytes, dl, PtrVT, true), dl);
1159 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
1160 SmallVector<SDValue, 12> MemOpChains;
1162 // Walk the register/memloc assignments, inserting copies/loads.
1163 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1164 CCValAssign &VA = ArgLocs[i];
1165 SDValue Arg = OutVals[i];
1167 // Promote the value if needed.
1168 switch (VA.getLocInfo()) {
1169 default: llvm_unreachable("Unknown loc info!");
1170 case CCValAssign::Full: break;
1171 case CCValAssign::SExt:
1172 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1174 case CCValAssign::ZExt:
1175 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1177 case CCValAssign::AExt:
1178 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1182 // Arguments that can be passed on register must be kept at
1183 // RegsToPass vector
1184 if (VA.isRegLoc()) {
1185 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1187 assert(VA.isMemLoc());
1189 int Offset = VA.getLocMemOffset();
1191 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
1193 DAG.getConstant(Offset/4, dl,
1198 // Transform all store nodes into one single node because
1199 // all store nodes are independent of each other.
1200 if (!MemOpChains.empty())
1201 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1203 // Build a sequence of copy-to-reg nodes chained together with token
1204 // chain and flag operands which copy the outgoing args into registers.
1205 // The InFlag in necessary since all emitted instructions must be
1208 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1209 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1210 RegsToPass[i].second, InFlag);
1211 InFlag = Chain.getValue(1);
1214 // If the callee is a GlobalAddress node (quite common, every direct call is)
1215 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1216 // Likewise ExternalSymbol -> TargetExternalSymbol.
1217 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1218 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
1219 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
1220 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
1222 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
1223 // = Chain, Callee, Reg#1, Reg#2, ...
1225 // Returns a chain & a flag for retval copy to use.
1226 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1227 SmallVector<SDValue, 8> Ops;
1228 Ops.push_back(Chain);
1229 Ops.push_back(Callee);
1231 // Add argument registers to the end of the list so that they are
1232 // known live into the call.
1233 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1234 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1235 RegsToPass[i].second.getValueType()));
1237 if (InFlag.getNode())
1238 Ops.push_back(InFlag);
1240 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, Ops);
1241 InFlag = Chain.getValue(1);
1243 // Create the CALLSEQ_END node.
1244 Chain = DAG.getCALLSEQ_END(Chain, DAG.getConstant(NumBytes, dl, PtrVT, true),
1245 DAG.getConstant(0, dl, PtrVT, true), InFlag, dl);
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.
1926 bool XCoreTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1927 const AddrMode &AM, Type *Ty,
1928 unsigned AS) const {
1929 if (Ty->getTypeID() == Type::VoidTyID)
1930 return AM.Scale == 0 && isImmUs(AM.BaseOffs) && isImmUs4(AM.BaseOffs);
1932 unsigned Size = DL.getTypeAllocSize(Ty);
1934 return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1941 if (AM.Scale == 0) {
1942 return isImmUs(AM.BaseOffs);
1945 return AM.Scale == 1 && AM.BaseOffs == 0;
1949 if (AM.Scale == 0) {
1950 return isImmUs2(AM.BaseOffs);
1953 return AM.Scale == 2 && AM.BaseOffs == 0;
1956 if (AM.Scale == 0) {
1957 return isImmUs4(AM.BaseOffs);
1960 return AM.Scale == 4 && AM.BaseOffs == 0;
1964 //===----------------------------------------------------------------------===//
1965 // XCore Inline Assembly Support
1966 //===----------------------------------------------------------------------===//
1968 std::pair<unsigned, const TargetRegisterClass *>
1969 XCoreTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
1970 StringRef Constraint,
1972 if (Constraint.size() == 1) {
1973 switch (Constraint[0]) {
1976 return std::make_pair(0U, &XCore::GRRegsRegClass);
1979 // Use the default implementation in TargetLowering to convert the register
1980 // constraint into a member of a register class.
1981 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);