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);
114 setOperationAction(ISD::TRAP, MVT::Other, Legal);
117 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
119 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
120 setOperationAction(ISD::BlockAddress, MVT::i32 , Custom);
122 // Conversion of i64 -> double produces constantpool nodes
123 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
126 for (MVT VT : MVT::integer_valuetypes()) {
127 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
128 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
129 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
131 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
132 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i16, Expand);
135 // Custom expand misaligned loads / stores.
136 setOperationAction(ISD::LOAD, MVT::i32, Custom);
137 setOperationAction(ISD::STORE, MVT::i32, Custom);
140 setOperationAction(ISD::VAEND, MVT::Other, Expand);
141 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
142 setOperationAction(ISD::VAARG, MVT::Other, Custom);
143 setOperationAction(ISD::VASTART, MVT::Other, Custom);
146 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
147 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
148 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
150 // Exception handling
151 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
152 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
155 // We request a fence for ATOMIC_* instructions, to reduce them to Monotonic.
156 // As we are always Sequential Consistent, an ATOMIC_FENCE becomes a no OP.
157 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
158 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
159 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
161 // TRAMPOLINE is custom lowered.
162 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
163 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
165 // We want to custom lower some of our intrinsics.
166 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
168 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 4;
169 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize
170 = MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 2;
172 // We have target-specific dag combine patterns for the following nodes:
173 setTargetDAGCombine(ISD::STORE);
174 setTargetDAGCombine(ISD::ADD);
175 setTargetDAGCombine(ISD::INTRINSIC_VOID);
176 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
178 setMinFunctionAlignment(1);
179 setPrefFunctionAlignment(2);
182 bool XCoreTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
183 if (Val.getOpcode() != ISD::LOAD)
186 EVT VT1 = Val.getValueType();
187 if (!VT1.isSimple() || !VT1.isInteger() ||
188 !VT2.isSimple() || !VT2.isInteger())
191 switch (VT1.getSimpleVT().SimpleTy) {
200 SDValue XCoreTargetLowering::
201 LowerOperation(SDValue Op, SelectionDAG &DAG) const {
202 switch (Op.getOpcode())
204 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
205 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
206 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
207 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
208 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
209 case ISD::LOAD: return LowerLOAD(Op, DAG);
210 case ISD::STORE: return LowerSTORE(Op, DAG);
211 case ISD::VAARG: return LowerVAARG(Op, DAG);
212 case ISD::VASTART: return LowerVASTART(Op, DAG);
213 case ISD::SMUL_LOHI: return LowerSMUL_LOHI(Op, DAG);
214 case ISD::UMUL_LOHI: return LowerUMUL_LOHI(Op, DAG);
215 // FIXME: Remove these when LegalizeDAGTypes lands.
217 case ISD::SUB: return ExpandADDSUB(Op.getNode(), DAG);
218 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
219 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
220 case ISD::FRAME_TO_ARGS_OFFSET: return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
221 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
222 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
223 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
224 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
225 case ISD::ATOMIC_LOAD: return LowerATOMIC_LOAD(Op, DAG);
226 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op, DAG);
228 llvm_unreachable("unimplemented operand");
232 /// ReplaceNodeResults - Replace the results of node with an illegal result
233 /// type with new values built out of custom code.
234 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
235 SmallVectorImpl<SDValue>&Results,
236 SelectionDAG &DAG) const {
237 switch (N->getOpcode()) {
239 llvm_unreachable("Don't know how to custom expand this!");
242 Results.push_back(ExpandADDSUB(N, DAG));
247 //===----------------------------------------------------------------------===//
248 // Misc Lower Operation implementation
249 //===----------------------------------------------------------------------===//
251 SDValue XCoreTargetLowering::getGlobalAddressWrapper(SDValue GA,
252 const GlobalValue *GV,
253 SelectionDAG &DAG) const {
254 // FIXME there is no actual debug info here
257 if (GV->getValueType()->isFunctionTy())
258 return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
260 const auto *GVar = dyn_cast<GlobalVariable>(GV);
261 if ((GV->hasSection() && GV->getSection().startswith(".cp.")) ||
262 (GVar && GVar->isConstant() && GV->hasLocalLinkage()))
263 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
265 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
268 static bool IsSmallObject(const GlobalValue *GV, const XCoreTargetLowering &XTL) {
269 if (XTL.getTargetMachine().getCodeModel() == CodeModel::Small)
272 Type *ObjType = GV->getValueType();
273 if (!ObjType->isSized())
276 auto &DL = GV->getParent()->getDataLayout();
277 unsigned ObjSize = DL.getTypeAllocSize(ObjType);
278 return ObjSize < CodeModelLargeSize && ObjSize != 0;
281 SDValue XCoreTargetLowering::
282 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const
284 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
285 const GlobalValue *GV = GN->getGlobal();
287 int64_t Offset = GN->getOffset();
288 if (IsSmallObject(GV, *this)) {
289 // We can only fold positive offsets that are a multiple of the word size.
290 int64_t FoldedOffset = std::max(Offset & ~3, (int64_t)0);
291 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, FoldedOffset);
292 GA = getGlobalAddressWrapper(GA, GV, DAG);
293 // Handle the rest of the offset.
294 if (Offset != FoldedOffset) {
295 SDValue Remaining = DAG.getConstant(Offset - FoldedOffset, DL, MVT::i32);
296 GA = DAG.getNode(ISD::ADD, DL, MVT::i32, GA, Remaining);
300 // Ideally we would not fold in offset with an index <= 11.
301 Type *Ty = Type::getInt8PtrTy(*DAG.getContext());
302 Constant *GA = ConstantExpr::getBitCast(const_cast<GlobalValue*>(GV), Ty);
303 Ty = Type::getInt32Ty(*DAG.getContext());
304 Constant *Idx = ConstantInt::get(Ty, Offset);
305 Constant *GAI = ConstantExpr::getGetElementPtr(
306 Type::getInt8Ty(*DAG.getContext()), GA, Idx);
307 SDValue CP = DAG.getConstantPool(GAI, MVT::i32);
308 return DAG.getLoad(getPointerTy(DAG.getDataLayout()), DL,
309 DAG.getEntryNode(), CP, MachinePointerInfo());
313 SDValue XCoreTargetLowering::
314 LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const
317 auto PtrVT = getPointerTy(DAG.getDataLayout());
318 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
319 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT);
321 return DAG.getNode(XCoreISD::PCRelativeWrapper, DL, PtrVT, Result);
324 SDValue XCoreTargetLowering::
325 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
327 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
328 // FIXME there isn't really debug info here
330 EVT PtrVT = Op.getValueType();
332 if (CP->isMachineConstantPoolEntry()) {
333 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
334 CP->getAlignment(), CP->getOffset());
336 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
337 CP->getAlignment(), CP->getOffset());
339 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
342 unsigned XCoreTargetLowering::getJumpTableEncoding() const {
343 return MachineJumpTableInfo::EK_Inline;
346 SDValue XCoreTargetLowering::
347 LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
349 SDValue Chain = Op.getOperand(0);
350 SDValue Table = Op.getOperand(1);
351 SDValue Index = Op.getOperand(2);
353 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
354 unsigned JTI = JT->getIndex();
355 MachineFunction &MF = DAG.getMachineFunction();
356 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
357 SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
359 unsigned NumEntries = MJTI->getJumpTables()[JTI].MBBs.size();
360 if (NumEntries <= 32) {
361 return DAG.getNode(XCoreISD::BR_JT, dl, MVT::Other, Chain, TargetJT, Index);
363 assert((NumEntries >> 31) == 0);
364 SDValue ScaledIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
365 DAG.getConstant(1, dl, MVT::i32));
366 return DAG.getNode(XCoreISD::BR_JT32, dl, MVT::Other, Chain, TargetJT,
370 SDValue XCoreTargetLowering::lowerLoadWordFromAlignedBasePlusOffset(
371 const SDLoc &DL, SDValue Chain, SDValue Base, int64_t Offset,
372 SelectionDAG &DAG) const {
373 auto PtrVT = getPointerTy(DAG.getDataLayout());
374 if ((Offset & 0x3) == 0) {
375 return DAG.getLoad(PtrVT, DL, Chain, Base, MachinePointerInfo());
377 // Lower to pair of consecutive word aligned loads plus some bit shifting.
378 int32_t HighOffset = alignTo(Offset, 4);
379 int32_t LowOffset = HighOffset - 4;
380 SDValue LowAddr, HighAddr;
381 if (GlobalAddressSDNode *GASD =
382 dyn_cast<GlobalAddressSDNode>(Base.getNode())) {
383 LowAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
385 HighAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
388 LowAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
389 DAG.getConstant(LowOffset, DL, MVT::i32));
390 HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
391 DAG.getConstant(HighOffset, DL, MVT::i32));
393 SDValue LowShift = DAG.getConstant((Offset - LowOffset) * 8, DL, MVT::i32);
394 SDValue HighShift = DAG.getConstant((HighOffset - Offset) * 8, DL, MVT::i32);
396 SDValue Low = DAG.getLoad(PtrVT, DL, Chain, LowAddr, MachinePointerInfo());
397 SDValue High = DAG.getLoad(PtrVT, DL, Chain, HighAddr, MachinePointerInfo());
398 SDValue LowShifted = DAG.getNode(ISD::SRL, DL, MVT::i32, Low, LowShift);
399 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High, HighShift);
400 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, LowShifted, HighShifted);
401 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
403 SDValue Ops[] = { Result, Chain };
404 return DAG.getMergeValues(Ops, DL);
407 static bool isWordAligned(SDValue Value, SelectionDAG &DAG)
409 APInt KnownZero, KnownOne;
410 DAG.computeKnownBits(Value, KnownZero, KnownOne);
411 return KnownZero.countTrailingOnes() >= 2;
414 SDValue XCoreTargetLowering::
415 LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
416 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
417 LoadSDNode *LD = cast<LoadSDNode>(Op);
418 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
419 "Unexpected extension type");
420 assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
421 if (allowsMisalignedMemoryAccesses(LD->getMemoryVT(),
422 LD->getAddressSpace(),
426 auto &TD = DAG.getDataLayout();
427 unsigned ABIAlignment = TD.getABITypeAlignment(
428 LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
429 // Leave aligned load alone.
430 if (LD->getAlignment() >= ABIAlignment)
433 SDValue Chain = LD->getChain();
434 SDValue BasePtr = LD->getBasePtr();
437 if (!LD->isVolatile()) {
438 const GlobalValue *GV;
440 if (DAG.isBaseWithConstantOffset(BasePtr) &&
441 isWordAligned(BasePtr->getOperand(0), DAG)) {
442 SDValue NewBasePtr = BasePtr->getOperand(0);
443 Offset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
444 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
447 if (TLI.isGAPlusOffset(BasePtr.getNode(), GV, Offset) &&
448 MinAlign(GV->getAlignment(), 4) == 4) {
449 SDValue NewBasePtr = DAG.getGlobalAddress(GV, DL,
450 BasePtr->getValueType(0));
451 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
456 if (LD->getAlignment() == 2) {
458 DAG.getExtLoad(ISD::ZEXTLOAD, DL, MVT::i32, Chain, BasePtr,
459 LD->getPointerInfo(), MVT::i16,
460 /* Alignment = */ 2, LD->getMemOperand()->getFlags());
461 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
462 DAG.getConstant(2, DL, MVT::i32));
464 DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, HighAddr,
465 LD->getPointerInfo().getWithOffset(2), MVT::i16,
466 /* Alignment = */ 2, LD->getMemOperand()->getFlags());
467 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High,
468 DAG.getConstant(16, DL, MVT::i32));
469 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Low, HighShifted);
470 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
472 SDValue Ops[] = { Result, Chain };
473 return DAG.getMergeValues(Ops, DL);
476 // Lower to a call to __misaligned_load(BasePtr).
477 Type *IntPtrTy = TD.getIntPtrType(*DAG.getContext());
478 TargetLowering::ArgListTy Args;
479 TargetLowering::ArgListEntry Entry;
482 Entry.Node = BasePtr;
483 Args.push_back(Entry);
485 TargetLowering::CallLoweringInfo CLI(DAG);
486 CLI.setDebugLoc(DL).setChain(Chain).setCallee(
487 CallingConv::C, IntPtrTy,
488 DAG.getExternalSymbol("__misaligned_load",
489 getPointerTy(DAG.getDataLayout())),
492 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
493 SDValue Ops[] = { CallResult.first, CallResult.second };
494 return DAG.getMergeValues(Ops, DL);
497 SDValue XCoreTargetLowering::
498 LowerSTORE(SDValue Op, SelectionDAG &DAG) const
500 StoreSDNode *ST = cast<StoreSDNode>(Op);
501 assert(!ST->isTruncatingStore() && "Unexpected store type");
502 assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
503 if (allowsMisalignedMemoryAccesses(ST->getMemoryVT(),
504 ST->getAddressSpace(),
505 ST->getAlignment())) {
508 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(
509 ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
510 // Leave aligned store alone.
511 if (ST->getAlignment() >= ABIAlignment) {
514 SDValue Chain = ST->getChain();
515 SDValue BasePtr = ST->getBasePtr();
516 SDValue Value = ST->getValue();
519 if (ST->getAlignment() == 2) {
521 SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
522 DAG.getConstant(16, dl, MVT::i32));
523 SDValue StoreLow = DAG.getTruncStore(
524 Chain, dl, Low, BasePtr, ST->getPointerInfo(), MVT::i16,
525 /* Alignment = */ 2, ST->getMemOperand()->getFlags());
526 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
527 DAG.getConstant(2, dl, MVT::i32));
528 SDValue StoreHigh = DAG.getTruncStore(
529 Chain, dl, High, HighAddr, ST->getPointerInfo().getWithOffset(2),
530 MVT::i16, /* Alignment = */ 2, ST->getMemOperand()->getFlags());
531 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
534 // Lower to a call to __misaligned_store(BasePtr, Value).
535 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
536 TargetLowering::ArgListTy Args;
537 TargetLowering::ArgListEntry Entry;
540 Entry.Node = BasePtr;
541 Args.push_back(Entry);
544 Args.push_back(Entry);
546 TargetLowering::CallLoweringInfo CLI(DAG);
547 CLI.setDebugLoc(dl).setChain(Chain).setCallee(
548 CallingConv::C, Type::getVoidTy(*DAG.getContext()),
549 DAG.getExternalSymbol("__misaligned_store",
550 getPointerTy(DAG.getDataLayout())),
553 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
554 return CallResult.second;
557 SDValue XCoreTargetLowering::
558 LowerSMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
560 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::SMUL_LOHI &&
561 "Unexpected operand to lower!");
563 SDValue LHS = Op.getOperand(0);
564 SDValue RHS = Op.getOperand(1);
565 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
566 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
567 DAG.getVTList(MVT::i32, MVT::i32), Zero, Zero,
569 SDValue Lo(Hi.getNode(), 1);
570 SDValue Ops[] = { Lo, Hi };
571 return DAG.getMergeValues(Ops, dl);
574 SDValue XCoreTargetLowering::
575 LowerUMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
577 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::UMUL_LOHI &&
578 "Unexpected operand to lower!");
580 SDValue LHS = Op.getOperand(0);
581 SDValue RHS = Op.getOperand(1);
582 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
583 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
584 DAG.getVTList(MVT::i32, MVT::i32), LHS, RHS,
586 SDValue Lo(Hi.getNode(), 1);
587 SDValue Ops[] = { Lo, Hi };
588 return DAG.getMergeValues(Ops, dl);
591 /// isADDADDMUL - Return whether Op is in a form that is equivalent to
592 /// add(add(mul(x,y),a),b). If requireIntermediatesHaveOneUse is true then
593 /// each intermediate result in the calculation must also have a single use.
594 /// If the Op is in the correct form the constituent parts are written to Mul0,
595 /// Mul1, Addend0 and Addend1.
597 isADDADDMUL(SDValue Op, SDValue &Mul0, SDValue &Mul1, SDValue &Addend0,
598 SDValue &Addend1, bool requireIntermediatesHaveOneUse)
600 if (Op.getOpcode() != ISD::ADD)
602 SDValue N0 = Op.getOperand(0);
603 SDValue N1 = Op.getOperand(1);
606 if (N0.getOpcode() == ISD::ADD) {
609 } else if (N1.getOpcode() == ISD::ADD) {
615 if (requireIntermediatesHaveOneUse && !AddOp.hasOneUse())
617 if (OtherOp.getOpcode() == ISD::MUL) {
618 // add(add(a,b),mul(x,y))
619 if (requireIntermediatesHaveOneUse && !OtherOp.hasOneUse())
621 Mul0 = OtherOp.getOperand(0);
622 Mul1 = OtherOp.getOperand(1);
623 Addend0 = AddOp.getOperand(0);
624 Addend1 = AddOp.getOperand(1);
627 if (AddOp.getOperand(0).getOpcode() == ISD::MUL) {
628 // add(add(mul(x,y),a),b)
629 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(0).hasOneUse())
631 Mul0 = AddOp.getOperand(0).getOperand(0);
632 Mul1 = AddOp.getOperand(0).getOperand(1);
633 Addend0 = AddOp.getOperand(1);
637 if (AddOp.getOperand(1).getOpcode() == ISD::MUL) {
638 // add(add(a,mul(x,y)),b)
639 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(1).hasOneUse())
641 Mul0 = AddOp.getOperand(1).getOperand(0);
642 Mul1 = AddOp.getOperand(1).getOperand(1);
643 Addend0 = AddOp.getOperand(0);
650 SDValue XCoreTargetLowering::
651 TryExpandADDWithMul(SDNode *N, SelectionDAG &DAG) const
655 if (N->getOperand(0).getOpcode() == ISD::MUL) {
656 Mul = N->getOperand(0);
657 Other = N->getOperand(1);
658 } else if (N->getOperand(1).getOpcode() == ISD::MUL) {
659 Mul = N->getOperand(1);
660 Other = N->getOperand(0);
665 SDValue LL, RL, AddendL, AddendH;
666 LL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
667 Mul.getOperand(0), DAG.getConstant(0, dl, MVT::i32));
668 RL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
669 Mul.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
670 AddendL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
671 Other, DAG.getConstant(0, dl, MVT::i32));
672 AddendH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
673 Other, DAG.getConstant(1, dl, MVT::i32));
674 APInt HighMask = APInt::getHighBitsSet(64, 32);
675 unsigned LHSSB = DAG.ComputeNumSignBits(Mul.getOperand(0));
676 unsigned RHSSB = DAG.ComputeNumSignBits(Mul.getOperand(1));
677 if (DAG.MaskedValueIsZero(Mul.getOperand(0), HighMask) &&
678 DAG.MaskedValueIsZero(Mul.getOperand(1), HighMask)) {
679 // The inputs are both zero-extended.
680 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
681 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
683 SDValue Lo(Hi.getNode(), 1);
684 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
686 if (LHSSB > 32 && RHSSB > 32) {
687 // The inputs are both sign-extended.
688 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
689 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
691 SDValue Lo(Hi.getNode(), 1);
692 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
695 LH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
696 Mul.getOperand(0), DAG.getConstant(1, dl, MVT::i32));
697 RH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
698 Mul.getOperand(1), DAG.getConstant(1, dl, MVT::i32));
699 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
700 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
702 SDValue Lo(Hi.getNode(), 1);
703 RH = DAG.getNode(ISD::MUL, dl, MVT::i32, LL, RH);
704 LH = DAG.getNode(ISD::MUL, dl, MVT::i32, LH, RL);
705 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, RH);
706 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, LH);
707 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
710 SDValue XCoreTargetLowering::
711 ExpandADDSUB(SDNode *N, SelectionDAG &DAG) const
713 assert(N->getValueType(0) == MVT::i64 &&
714 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
715 "Unknown operand to lower!");
717 if (N->getOpcode() == ISD::ADD)
718 if (SDValue Result = TryExpandADDWithMul(N, DAG))
723 // Extract components
724 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
726 DAG.getConstant(0, dl, MVT::i32));
727 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
729 DAG.getConstant(1, dl, MVT::i32));
730 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
732 DAG.getConstant(0, dl, MVT::i32));
733 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
735 DAG.getConstant(1, dl, MVT::i32));
738 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
740 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
741 SDValue Lo = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
743 SDValue Carry(Lo.getNode(), 1);
745 SDValue Hi = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
747 SDValue Ignored(Hi.getNode(), 1);
749 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
752 SDValue XCoreTargetLowering::
753 LowerVAARG(SDValue Op, SelectionDAG &DAG) const
755 // Whist llvm does not support aggregate varargs we can ignore
756 // the possibility of the ValueType being an implicit byVal vararg.
757 SDNode *Node = Op.getNode();
758 EVT VT = Node->getValueType(0); // not an aggregate
759 SDValue InChain = Node->getOperand(0);
760 SDValue VAListPtr = Node->getOperand(1);
761 EVT PtrVT = VAListPtr.getValueType();
762 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
765 DAG.getLoad(PtrVT, dl, InChain, VAListPtr, MachinePointerInfo(SV));
766 // Increment the pointer, VAList, to the next vararg
767 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAList,
768 DAG.getIntPtrConstant(VT.getSizeInBits() / 8,
770 // Store the incremented VAList to the legalized pointer
771 InChain = DAG.getStore(VAList.getValue(1), dl, nextPtr, VAListPtr,
772 MachinePointerInfo(SV));
773 // Load the actual argument out of the pointer VAList
774 return DAG.getLoad(VT, dl, InChain, VAList, MachinePointerInfo());
777 SDValue XCoreTargetLowering::
778 LowerVASTART(SDValue Op, SelectionDAG &DAG) const
781 // vastart stores the address of the VarArgsFrameIndex slot into the
782 // memory location argument
783 MachineFunction &MF = DAG.getMachineFunction();
784 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
785 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
786 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1),
787 MachinePointerInfo());
790 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op,
791 SelectionDAG &DAG) const {
792 // This nodes represent llvm.frameaddress on the DAG.
793 // It takes one operand, the index of the frame address to return.
794 // An index of zero corresponds to the current function's frame address.
795 // An index of one to the parent's frame address, and so on.
796 // Depths > 0 not supported yet!
797 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
800 MachineFunction &MF = DAG.getMachineFunction();
801 const TargetRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
802 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op),
803 RegInfo->getFrameRegister(MF), MVT::i32);
806 SDValue XCoreTargetLowering::
807 LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const {
808 // This nodes represent llvm.returnaddress on the DAG.
809 // It takes one operand, the index of the return address to return.
810 // An index of zero corresponds to the current function's return address.
811 // An index of one to the parent's return address, and so on.
812 // Depths > 0 not supported yet!
813 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
816 MachineFunction &MF = DAG.getMachineFunction();
817 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
818 int FI = XFI->createLRSpillSlot(MF);
819 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
820 return DAG.getLoad(getPointerTy(DAG.getDataLayout()), SDLoc(Op),
821 DAG.getEntryNode(), FIN,
822 MachinePointerInfo::getFixedStack(MF, FI));
825 SDValue XCoreTargetLowering::
826 LowerFRAME_TO_ARGS_OFFSET(SDValue Op, SelectionDAG &DAG) const {
827 // This node represents offset from frame pointer to first on-stack argument.
828 // This is needed for correct stack adjustment during unwind.
829 // However, we don't know the offset until after the frame has be finalised.
830 // This is done during the XCoreFTAOElim pass.
831 return DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, SDLoc(Op), MVT::i32);
834 SDValue XCoreTargetLowering::
835 LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
836 // OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER)
837 // This node represents 'eh_return' gcc dwarf builtin, which is used to
838 // return from exception. The general meaning is: adjust stack by OFFSET and
839 // pass execution to HANDLER.
840 MachineFunction &MF = DAG.getMachineFunction();
841 SDValue Chain = Op.getOperand(0);
842 SDValue Offset = Op.getOperand(1);
843 SDValue Handler = Op.getOperand(2);
846 // Absolute SP = (FP + FrameToArgs) + Offset
847 const TargetRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
848 SDValue Stack = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
849 RegInfo->getFrameRegister(MF), MVT::i32);
850 SDValue FrameToArgs = DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, dl,
852 Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, FrameToArgs);
853 Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, Offset);
855 // R0=ExceptionPointerRegister R1=ExceptionSelectorRegister
856 // which leaves 2 caller saved registers, R2 & R3 for us to use.
857 unsigned StackReg = XCore::R2;
858 unsigned HandlerReg = XCore::R3;
860 SDValue OutChains[] = {
861 DAG.getCopyToReg(Chain, dl, StackReg, Stack),
862 DAG.getCopyToReg(Chain, dl, HandlerReg, Handler)
865 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
867 return DAG.getNode(XCoreISD::EH_RETURN, dl, MVT::Other, Chain,
868 DAG.getRegister(StackReg, MVT::i32),
869 DAG.getRegister(HandlerReg, MVT::i32));
873 SDValue XCoreTargetLowering::
874 LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
875 return Op.getOperand(0);
878 SDValue XCoreTargetLowering::
879 LowerINIT_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
880 SDValue Chain = Op.getOperand(0);
881 SDValue Trmp = Op.getOperand(1); // trampoline
882 SDValue FPtr = Op.getOperand(2); // nested function
883 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
885 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
888 // LDAPF_u10 r11, nest
889 // LDW_2rus r11, r11[0]
890 // STWSP_ru6 r11, sp[0]
891 // LDAPF_u10 r11, fptr
892 // LDW_2rus r11, r11[0]
898 SDValue OutChains[5];
904 DAG.getStore(Chain, dl, DAG.getConstant(0x0a3cd805, dl, MVT::i32), Addr,
905 MachinePointerInfo(TrmpAddr));
907 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
908 DAG.getConstant(4, dl, MVT::i32));
910 DAG.getStore(Chain, dl, DAG.getConstant(0xd80456c0, dl, MVT::i32), Addr,
911 MachinePointerInfo(TrmpAddr, 4));
913 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
914 DAG.getConstant(8, dl, MVT::i32));
916 DAG.getStore(Chain, dl, DAG.getConstant(0x27fb0a3c, dl, MVT::i32), Addr,
917 MachinePointerInfo(TrmpAddr, 8));
919 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
920 DAG.getConstant(12, dl, MVT::i32));
922 DAG.getStore(Chain, dl, Nest, Addr, MachinePointerInfo(TrmpAddr, 12));
924 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
925 DAG.getConstant(16, dl, MVT::i32));
927 DAG.getStore(Chain, dl, FPtr, Addr, MachinePointerInfo(TrmpAddr, 16));
929 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
932 SDValue XCoreTargetLowering::
933 LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
935 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
937 case Intrinsic::xcore_crc8:
938 EVT VT = Op.getValueType();
940 DAG.getNode(XCoreISD::CRC8, DL, DAG.getVTList(VT, VT),
941 Op.getOperand(1), Op.getOperand(2) , Op.getOperand(3));
942 SDValue Crc(Data.getNode(), 1);
943 SDValue Results[] = { Crc, Data };
944 return DAG.getMergeValues(Results, DL);
949 SDValue XCoreTargetLowering::
950 LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG) const {
952 return DAG.getNode(XCoreISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
955 SDValue XCoreTargetLowering::
956 LowerATOMIC_LOAD(SDValue Op, SelectionDAG &DAG) const {
957 AtomicSDNode *N = cast<AtomicSDNode>(Op);
958 assert(N->getOpcode() == ISD::ATOMIC_LOAD && "Bad Atomic OP");
959 assert((N->getOrdering() == AtomicOrdering::Unordered ||
960 N->getOrdering() == AtomicOrdering::Monotonic) &&
961 "setInsertFencesForAtomic(true) expects unordered / monotonic");
962 if (N->getMemoryVT() == MVT::i32) {
963 if (N->getAlignment() < 4)
964 report_fatal_error("atomic load must be aligned");
965 return DAG.getLoad(getPointerTy(DAG.getDataLayout()), SDLoc(Op),
966 N->getChain(), N->getBasePtr(), N->getPointerInfo(),
967 N->getAlignment(), N->getMemOperand()->getFlags(),
968 N->getAAInfo(), N->getRanges());
970 if (N->getMemoryVT() == MVT::i16) {
971 if (N->getAlignment() < 2)
972 report_fatal_error("atomic load must be aligned");
973 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
974 N->getBasePtr(), N->getPointerInfo(), MVT::i16,
975 N->getAlignment(), N->getMemOperand()->getFlags(),
978 if (N->getMemoryVT() == MVT::i8)
979 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
980 N->getBasePtr(), N->getPointerInfo(), MVT::i8,
981 N->getAlignment(), N->getMemOperand()->getFlags(),
986 SDValue XCoreTargetLowering::
987 LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) const {
988 AtomicSDNode *N = cast<AtomicSDNode>(Op);
989 assert(N->getOpcode() == ISD::ATOMIC_STORE && "Bad Atomic OP");
990 assert((N->getOrdering() == AtomicOrdering::Unordered ||
991 N->getOrdering() == AtomicOrdering::Monotonic) &&
992 "setInsertFencesForAtomic(true) expects unordered / monotonic");
993 if (N->getMemoryVT() == MVT::i32) {
994 if (N->getAlignment() < 4)
995 report_fatal_error("atomic store must be aligned");
996 return DAG.getStore(N->getChain(), SDLoc(Op), N->getVal(), N->getBasePtr(),
997 N->getPointerInfo(), N->getAlignment(),
998 N->getMemOperand()->getFlags(), N->getAAInfo());
1000 if (N->getMemoryVT() == MVT::i16) {
1001 if (N->getAlignment() < 2)
1002 report_fatal_error("atomic store must be aligned");
1003 return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1004 N->getBasePtr(), N->getPointerInfo(), MVT::i16,
1005 N->getAlignment(), N->getMemOperand()->getFlags(),
1008 if (N->getMemoryVT() == MVT::i8)
1009 return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1010 N->getBasePtr(), N->getPointerInfo(), MVT::i8,
1011 N->getAlignment(), N->getMemOperand()->getFlags(),
1016 //===----------------------------------------------------------------------===//
1017 // Calling Convention Implementation
1018 //===----------------------------------------------------------------------===//
1020 #include "XCoreGenCallingConv.inc"
1022 //===----------------------------------------------------------------------===//
1023 // Call Calling Convention Implementation
1024 //===----------------------------------------------------------------------===//
1026 /// XCore call implementation
1028 XCoreTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1029 SmallVectorImpl<SDValue> &InVals) const {
1030 SelectionDAG &DAG = CLI.DAG;
1032 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1033 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1034 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1035 SDValue Chain = CLI.Chain;
1036 SDValue Callee = CLI.Callee;
1037 bool &isTailCall = CLI.IsTailCall;
1038 CallingConv::ID CallConv = CLI.CallConv;
1039 bool isVarArg = CLI.IsVarArg;
1041 // XCore target does not yet support tail call optimization.
1044 // For now, only CallingConv::C implemented
1048 llvm_unreachable("Unsupported calling convention");
1049 case CallingConv::Fast:
1050 case CallingConv::C:
1051 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
1052 Outs, OutVals, Ins, dl, DAG, InVals);
1056 /// LowerCallResult - Lower the result values of a call into the
1057 /// appropriate copies out of appropriate physical registers / memory locations.
1058 static SDValue LowerCallResult(SDValue Chain, SDValue InFlag,
1059 const SmallVectorImpl<CCValAssign> &RVLocs,
1060 const SDLoc &dl, SelectionDAG &DAG,
1061 SmallVectorImpl<SDValue> &InVals) {
1062 SmallVector<std::pair<int, unsigned>, 4> ResultMemLocs;
1063 // Copy results out of physical registers.
1064 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1065 const CCValAssign &VA = RVLocs[i];
1066 if (VA.isRegLoc()) {
1067 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getValVT(),
1068 InFlag).getValue(1);
1069 InFlag = Chain.getValue(2);
1070 InVals.push_back(Chain.getValue(0));
1072 assert(VA.isMemLoc());
1073 ResultMemLocs.push_back(std::make_pair(VA.getLocMemOffset(),
1075 // Reserve space for this result.
1076 InVals.push_back(SDValue());
1080 // Copy results out of memory.
1081 SmallVector<SDValue, 4> MemOpChains;
1082 for (unsigned i = 0, e = ResultMemLocs.size(); i != e; ++i) {
1083 int offset = ResultMemLocs[i].first;
1084 unsigned index = ResultMemLocs[i].second;
1085 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
1086 SDValue Ops[] = { Chain, DAG.getConstant(offset / 4, dl, MVT::i32) };
1087 SDValue load = DAG.getNode(XCoreISD::LDWSP, dl, VTs, Ops);
1088 InVals[index] = load;
1089 MemOpChains.push_back(load.getValue(1));
1092 // Transform all loads nodes into one single node because
1093 // all load nodes are independent of each other.
1094 if (!MemOpChains.empty())
1095 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1100 /// LowerCCCCallTo - functions arguments are copied from virtual
1101 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
1102 /// CALLSEQ_END are emitted.
1103 /// TODO: isTailCall, sret.
1104 SDValue XCoreTargetLowering::LowerCCCCallTo(
1105 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
1106 bool isTailCall, const SmallVectorImpl<ISD::OutputArg> &Outs,
1107 const SmallVectorImpl<SDValue> &OutVals,
1108 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1109 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1111 // Analyze operands of the call, assigning locations to each operand.
1112 SmallVector<CCValAssign, 16> ArgLocs;
1113 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1116 // The ABI dictates there should be one stack slot available to the callee
1117 // on function entry (for saving lr).
1118 CCInfo.AllocateStack(4, 4);
1120 CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
1122 SmallVector<CCValAssign, 16> RVLocs;
1123 // Analyze return values to determine the number of bytes of stack required.
1124 CCState RetCCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1126 RetCCInfo.AllocateStack(CCInfo.getNextStackOffset(), 4);
1127 RetCCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
1129 // Get a count of how many bytes are to be pushed on the stack.
1130 unsigned NumBytes = RetCCInfo.getNextStackOffset();
1131 auto PtrVT = getPointerTy(DAG.getDataLayout());
1133 Chain = DAG.getCALLSEQ_START(Chain,
1134 DAG.getConstant(NumBytes, dl, PtrVT, true), dl);
1136 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
1137 SmallVector<SDValue, 12> MemOpChains;
1139 // Walk the register/memloc assignments, inserting copies/loads.
1140 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1141 CCValAssign &VA = ArgLocs[i];
1142 SDValue Arg = OutVals[i];
1144 // Promote the value if needed.
1145 switch (VA.getLocInfo()) {
1146 default: llvm_unreachable("Unknown loc info!");
1147 case CCValAssign::Full: break;
1148 case CCValAssign::SExt:
1149 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1151 case CCValAssign::ZExt:
1152 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1154 case CCValAssign::AExt:
1155 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1159 // Arguments that can be passed on register must be kept at
1160 // RegsToPass vector
1161 if (VA.isRegLoc()) {
1162 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1164 assert(VA.isMemLoc());
1166 int Offset = VA.getLocMemOffset();
1168 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
1170 DAG.getConstant(Offset/4, dl,
1175 // Transform all store nodes into one single node because
1176 // all store nodes are independent of each other.
1177 if (!MemOpChains.empty())
1178 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1180 // Build a sequence of copy-to-reg nodes chained together with token
1181 // chain and flag operands which copy the outgoing args into registers.
1182 // The InFlag in necessary since all emitted instructions must be
1185 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1186 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1187 RegsToPass[i].second, InFlag);
1188 InFlag = Chain.getValue(1);
1191 // If the callee is a GlobalAddress node (quite common, every direct call is)
1192 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1193 // Likewise ExternalSymbol -> TargetExternalSymbol.
1194 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1195 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
1196 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
1197 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
1199 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
1200 // = Chain, Callee, Reg#1, Reg#2, ...
1202 // Returns a chain & a flag for retval copy to use.
1203 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1204 SmallVector<SDValue, 8> Ops;
1205 Ops.push_back(Chain);
1206 Ops.push_back(Callee);
1208 // Add argument registers to the end of the list so that they are
1209 // known live into the call.
1210 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1211 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1212 RegsToPass[i].second.getValueType()));
1214 if (InFlag.getNode())
1215 Ops.push_back(InFlag);
1217 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, Ops);
1218 InFlag = Chain.getValue(1);
1220 // Create the CALLSEQ_END node.
1221 Chain = DAG.getCALLSEQ_END(Chain, DAG.getConstant(NumBytes, dl, PtrVT, true),
1222 DAG.getConstant(0, dl, PtrVT, true), InFlag, dl);
1223 InFlag = Chain.getValue(1);
1225 // Handle result values, copying them out of physregs into vregs that we
1227 return LowerCallResult(Chain, InFlag, RVLocs, dl, DAG, InVals);
1230 //===----------------------------------------------------------------------===//
1231 // Formal Arguments Calling Convention Implementation
1232 //===----------------------------------------------------------------------===//
1235 struct ArgDataPair { SDValue SDV; ISD::ArgFlagsTy Flags; };
1238 /// XCore formal arguments implementation
1239 SDValue XCoreTargetLowering::LowerFormalArguments(
1240 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1241 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1242 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1246 llvm_unreachable("Unsupported calling convention");
1247 case CallingConv::C:
1248 case CallingConv::Fast:
1249 return LowerCCCArguments(Chain, CallConv, isVarArg,
1250 Ins, dl, DAG, InVals);
1254 /// LowerCCCArguments - transform physical registers into
1255 /// virtual registers and generate load operations for
1256 /// arguments places on the stack.
1258 SDValue XCoreTargetLowering::LowerCCCArguments(
1259 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1260 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1261 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1262 MachineFunction &MF = DAG.getMachineFunction();
1263 MachineFrameInfo *MFI = MF.getFrameInfo();
1264 MachineRegisterInfo &RegInfo = MF.getRegInfo();
1265 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1267 // Assign locations to all of the incoming arguments.
1268 SmallVector<CCValAssign, 16> ArgLocs;
1269 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1272 CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
1274 unsigned StackSlotSize = XCoreFrameLowering::stackSlotSize();
1276 unsigned LRSaveSize = StackSlotSize;
1279 XFI->setReturnStackOffset(CCInfo.getNextStackOffset() + LRSaveSize);
1281 // All getCopyFromReg ops must precede any getMemcpys to prevent the
1282 // scheduler clobbering a register before it has been copied.
1284 // 1. CopyFromReg (and load) arg & vararg registers.
1285 // 2. Chain CopyFromReg nodes into a TokenFactor.
1286 // 3. Memcpy 'byVal' args & push final InVals.
1287 // 4. Chain mem ops nodes into a TokenFactor.
1288 SmallVector<SDValue, 4> CFRegNode;
1289 SmallVector<ArgDataPair, 4> ArgData;
1290 SmallVector<SDValue, 4> MemOps;
1292 // 1a. CopyFromReg (and load) arg registers.
1293 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1295 CCValAssign &VA = ArgLocs[i];
1298 if (VA.isRegLoc()) {
1299 // Arguments passed in registers
1300 EVT RegVT = VA.getLocVT();
1301 switch (RegVT.getSimpleVT().SimpleTy) {
1305 errs() << "LowerFormalArguments Unhandled argument type: "
1306 << RegVT.getEVTString() << "\n";
1308 llvm_unreachable(nullptr);
1311 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1312 RegInfo.addLiveIn(VA.getLocReg(), VReg);
1313 ArgIn = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
1314 CFRegNode.push_back(ArgIn.getValue(ArgIn->getNumValues() - 1));
1318 assert(VA.isMemLoc());
1319 // Load the argument to a virtual register
1320 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
1321 if (ObjSize > StackSlotSize) {
1322 errs() << "LowerFormalArguments Unhandled argument type: "
1323 << EVT(VA.getLocVT()).getEVTString()
1326 // Create the frame index object for this incoming parameter...
1327 int FI = MFI->CreateFixedObject(ObjSize,
1328 LRSaveSize + VA.getLocMemOffset(),
1331 // Create the SelectionDAG nodes corresponding to a load
1332 //from this parameter
1333 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1334 ArgIn = DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
1335 MachinePointerInfo::getFixedStack(MF, FI));
1337 const ArgDataPair ADP = { ArgIn, Ins[i].Flags };
1338 ArgData.push_back(ADP);
1341 // 1b. CopyFromReg vararg registers.
1343 // Argument registers
1344 static const MCPhysReg ArgRegs[] = {
1345 XCore::R0, XCore::R1, XCore::R2, XCore::R3
1347 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1348 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs);
1349 if (FirstVAReg < array_lengthof(ArgRegs)) {
1351 // Save remaining registers, storing higher register numbers at a higher
1353 for (int i = array_lengthof(ArgRegs) - 1; i >= (int)FirstVAReg; --i) {
1354 // Create a stack slot
1355 int FI = MFI->CreateFixedObject(4, offset, true);
1356 if (i == (int)FirstVAReg) {
1357 XFI->setVarArgsFrameIndex(FI);
1359 offset -= StackSlotSize;
1360 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1361 // Move argument from phys reg -> virt reg
1362 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1363 RegInfo.addLiveIn(ArgRegs[i], VReg);
1364 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1365 CFRegNode.push_back(Val.getValue(Val->getNumValues() - 1));
1366 // Move argument from virt reg -> stack
1368 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
1369 MemOps.push_back(Store);
1372 // This will point to the next argument passed via stack.
1373 XFI->setVarArgsFrameIndex(
1374 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset(),
1379 // 2. chain CopyFromReg nodes into a TokenFactor.
1380 if (!CFRegNode.empty())
1381 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, CFRegNode);
1383 // 3. Memcpy 'byVal' args & push final InVals.
1384 // Aggregates passed "byVal" need to be copied by the callee.
1385 // The callee will use a pointer to this copy, rather than the original
1387 for (SmallVectorImpl<ArgDataPair>::const_iterator ArgDI = ArgData.begin(),
1388 ArgDE = ArgData.end();
1389 ArgDI != ArgDE; ++ArgDI) {
1390 if (ArgDI->Flags.isByVal() && ArgDI->Flags.getByValSize()) {
1391 unsigned Size = ArgDI->Flags.getByValSize();
1392 unsigned Align = std::max(StackSlotSize, ArgDI->Flags.getByValAlign());
1393 // Create a new object on the stack and copy the pointee into it.
1394 int FI = MFI->CreateStackObject(Size, Align, false);
1395 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1396 InVals.push_back(FIN);
1397 MemOps.push_back(DAG.getMemcpy(Chain, dl, FIN, ArgDI->SDV,
1398 DAG.getConstant(Size, dl, MVT::i32),
1399 Align, false, false, false,
1400 MachinePointerInfo(),
1401 MachinePointerInfo()));
1403 InVals.push_back(ArgDI->SDV);
1407 // 4, chain mem ops nodes into a TokenFactor.
1408 if (!MemOps.empty()) {
1409 MemOps.push_back(Chain);
1410 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
1416 //===----------------------------------------------------------------------===//
1417 // Return Value Calling Convention Implementation
1418 //===----------------------------------------------------------------------===//
1420 bool XCoreTargetLowering::
1421 CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF,
1423 const SmallVectorImpl<ISD::OutputArg> &Outs,
1424 LLVMContext &Context) const {
1425 SmallVector<CCValAssign, 16> RVLocs;
1426 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1427 if (!CCInfo.CheckReturn(Outs, RetCC_XCore))
1429 if (CCInfo.getNextStackOffset() != 0 && isVarArg)
1435 XCoreTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1437 const SmallVectorImpl<ISD::OutputArg> &Outs,
1438 const SmallVectorImpl<SDValue> &OutVals,
1439 const SDLoc &dl, SelectionDAG &DAG) const {
1441 XCoreFunctionInfo *XFI =
1442 DAG.getMachineFunction().getInfo<XCoreFunctionInfo>();
1443 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1445 // CCValAssign - represent the assignment of
1446 // the return value to a location
1447 SmallVector<CCValAssign, 16> RVLocs;
1449 // CCState - Info about the registers and stack slot.
1450 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1453 // Analyze return values.
1455 CCInfo.AllocateStack(XFI->getReturnStackOffset(), 4);
1457 CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
1460 SmallVector<SDValue, 4> RetOps(1, Chain);
1462 // Return on XCore is always a "retsp 0"
1463 RetOps.push_back(DAG.getConstant(0, dl, MVT::i32));
1465 SmallVector<SDValue, 4> MemOpChains;
1466 // Handle return values that must be copied to memory.
1467 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1468 CCValAssign &VA = RVLocs[i];
1471 assert(VA.isMemLoc());
1473 report_fatal_error("Can't return value from vararg function in memory");
1476 int Offset = VA.getLocMemOffset();
1477 unsigned ObjSize = VA.getLocVT().getSizeInBits() / 8;
1478 // Create the frame index object for the memory location.
1479 int FI = MFI->CreateFixedObject(ObjSize, Offset, false);
1481 // Create a SelectionDAG node corresponding to a store
1482 // to this memory location.
1483 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1484 MemOpChains.push_back(DAG.getStore(
1485 Chain, dl, OutVals[i], FIN,
1486 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
1489 // Transform all store nodes into one single node because
1490 // all stores are independent of each other.
1491 if (!MemOpChains.empty())
1492 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1494 // Now handle return values copied to registers.
1495 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1496 CCValAssign &VA = RVLocs[i];
1499 // Copy the result values into the output registers.
1500 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
1502 // guarantee that all emitted copies are
1503 // stuck together, avoiding something bad
1504 Flag = Chain.getValue(1);
1505 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1508 RetOps[0] = Chain; // Update chain.
1510 // Add the flag if we have it.
1512 RetOps.push_back(Flag);
1514 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other, RetOps);
1517 //===----------------------------------------------------------------------===//
1518 // Other Lowering Code
1519 //===----------------------------------------------------------------------===//
1522 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
1523 MachineBasicBlock *BB) const {
1524 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1525 DebugLoc dl = MI.getDebugLoc();
1526 assert((MI.getOpcode() == XCore::SELECT_CC) &&
1527 "Unexpected instr type to insert");
1529 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1530 // control-flow pattern. The incoming instruction knows the destination vreg
1531 // to set, the condition code register to branch on, the true/false values to
1532 // select between, and a branch opcode to use.
1533 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1534 MachineFunction::iterator It = ++BB->getIterator();
1539 // cmpTY ccX, r1, r2
1541 // fallthrough --> copy0MBB
1542 MachineBasicBlock *thisMBB = BB;
1543 MachineFunction *F = BB->getParent();
1544 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1545 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1546 F->insert(It, copy0MBB);
1547 F->insert(It, sinkMBB);
1549 // Transfer the remainder of BB and its successor edges to sinkMBB.
1550 sinkMBB->splice(sinkMBB->begin(), BB,
1551 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1552 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1554 // Next, add the true and fallthrough blocks as its successors.
1555 BB->addSuccessor(copy0MBB);
1556 BB->addSuccessor(sinkMBB);
1558 BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1559 .addReg(MI.getOperand(1).getReg())
1563 // %FalseValue = ...
1564 // # fallthrough to sinkMBB
1567 // Update machine-CFG edges
1568 BB->addSuccessor(sinkMBB);
1571 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1574 BuildMI(*BB, BB->begin(), dl, TII.get(XCore::PHI), MI.getOperand(0).getReg())
1575 .addReg(MI.getOperand(3).getReg())
1577 .addReg(MI.getOperand(2).getReg())
1580 MI.eraseFromParent(); // The pseudo instruction is gone now.
1584 //===----------------------------------------------------------------------===//
1585 // Target Optimization Hooks
1586 //===----------------------------------------------------------------------===//
1588 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1589 DAGCombinerInfo &DCI) const {
1590 SelectionDAG &DAG = DCI.DAG;
1592 switch (N->getOpcode()) {
1594 case ISD::INTRINSIC_VOID:
1595 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
1596 case Intrinsic::xcore_outt:
1597 case Intrinsic::xcore_outct:
1598 case Intrinsic::xcore_chkct: {
1599 SDValue OutVal = N->getOperand(3);
1600 // These instructions ignore the high bits.
1601 if (OutVal.hasOneUse()) {
1602 unsigned BitWidth = OutVal.getValueSizeInBits();
1603 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8);
1604 APInt KnownZero, KnownOne;
1605 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1606 !DCI.isBeforeLegalizeOps());
1607 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1608 if (TLO.ShrinkDemandedConstant(OutVal, DemandedMask) ||
1609 TLI.SimplifyDemandedBits(OutVal, DemandedMask, KnownZero, KnownOne,
1611 DCI.CommitTargetLoweringOpt(TLO);
1615 case Intrinsic::xcore_setpt: {
1616 SDValue Time = N->getOperand(3);
1617 // This instruction ignores the high bits.
1618 if (Time.hasOneUse()) {
1619 unsigned BitWidth = Time.getValueSizeInBits();
1620 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
1621 APInt KnownZero, KnownOne;
1622 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1623 !DCI.isBeforeLegalizeOps());
1624 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1625 if (TLO.ShrinkDemandedConstant(Time, DemandedMask) ||
1626 TLI.SimplifyDemandedBits(Time, DemandedMask, KnownZero, KnownOne,
1628 DCI.CommitTargetLoweringOpt(TLO);
1634 case XCoreISD::LADD: {
1635 SDValue N0 = N->getOperand(0);
1636 SDValue N1 = N->getOperand(1);
1637 SDValue N2 = N->getOperand(2);
1638 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1639 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1640 EVT VT = N0.getValueType();
1642 // canonicalize constant to RHS
1644 return DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N1, N0, N2);
1646 // fold (ladd 0, 0, x) -> 0, x & 1
1647 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1648 SDValue Carry = DAG.getConstant(0, dl, VT);
1649 SDValue Result = DAG.getNode(ISD::AND, dl, VT, N2,
1650 DAG.getConstant(1, dl, VT));
1651 SDValue Ops[] = { Result, Carry };
1652 return DAG.getMergeValues(Ops, dl);
1655 // fold (ladd x, 0, y) -> 0, add x, y iff carry is unused and y has only the
1657 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1658 APInt KnownZero, KnownOne;
1659 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1660 VT.getSizeInBits() - 1);
1661 DAG.computeKnownBits(N2, KnownZero, KnownOne);
1662 if ((KnownZero & Mask) == Mask) {
1663 SDValue Carry = DAG.getConstant(0, dl, VT);
1664 SDValue Result = DAG.getNode(ISD::ADD, dl, VT, N0, N2);
1665 SDValue Ops[] = { Result, Carry };
1666 return DAG.getMergeValues(Ops, dl);
1671 case XCoreISD::LSUB: {
1672 SDValue N0 = N->getOperand(0);
1673 SDValue N1 = N->getOperand(1);
1674 SDValue N2 = N->getOperand(2);
1675 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1676 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1677 EVT VT = N0.getValueType();
1679 // fold (lsub 0, 0, x) -> x, -x iff x has only the low bit set
1680 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1681 APInt KnownZero, KnownOne;
1682 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1683 VT.getSizeInBits() - 1);
1684 DAG.computeKnownBits(N2, KnownZero, KnownOne);
1685 if ((KnownZero & Mask) == Mask) {
1686 SDValue Borrow = N2;
1687 SDValue Result = DAG.getNode(ISD::SUB, dl, VT,
1688 DAG.getConstant(0, dl, VT), N2);
1689 SDValue Ops[] = { Result, Borrow };
1690 return DAG.getMergeValues(Ops, dl);
1694 // fold (lsub x, 0, y) -> 0, sub x, y iff borrow is unused and y has only the
1696 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1697 APInt KnownZero, KnownOne;
1698 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1699 VT.getSizeInBits() - 1);
1700 DAG.computeKnownBits(N2, KnownZero, KnownOne);
1701 if ((KnownZero & Mask) == Mask) {
1702 SDValue Borrow = DAG.getConstant(0, dl, VT);
1703 SDValue Result = DAG.getNode(ISD::SUB, dl, VT, N0, N2);
1704 SDValue Ops[] = { Result, Borrow };
1705 return DAG.getMergeValues(Ops, dl);
1710 case XCoreISD::LMUL: {
1711 SDValue N0 = N->getOperand(0);
1712 SDValue N1 = N->getOperand(1);
1713 SDValue N2 = N->getOperand(2);
1714 SDValue N3 = N->getOperand(3);
1715 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1716 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1717 EVT VT = N0.getValueType();
1718 // Canonicalize multiplicative constant to RHS. If both multiplicative
1719 // operands are constant canonicalize smallest to RHS.
1720 if ((N0C && !N1C) ||
1721 (N0C && N1C && N0C->getZExtValue() < N1C->getZExtValue()))
1722 return DAG.getNode(XCoreISD::LMUL, dl, DAG.getVTList(VT, VT),
1726 if (N1C && N1C->isNullValue()) {
1727 // If the high result is unused fold to add(a, b)
1728 if (N->hasNUsesOfValue(0, 0)) {
1729 SDValue Lo = DAG.getNode(ISD::ADD, dl, VT, N2, N3);
1730 SDValue Ops[] = { Lo, Lo };
1731 return DAG.getMergeValues(Ops, dl);
1733 // Otherwise fold to ladd(a, b, 0)
1735 DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N2, N3, N1);
1736 SDValue Carry(Result.getNode(), 1);
1737 SDValue Ops[] = { Carry, Result };
1738 return DAG.getMergeValues(Ops, dl);
1743 // Fold 32 bit expressions such as add(add(mul(x,y),a),b) ->
1744 // lmul(x, y, a, b). The high result of lmul will be ignored.
1745 // This is only profitable if the intermediate results are unused
1747 SDValue Mul0, Mul1, Addend0, Addend1;
1748 if (N->getValueType(0) == MVT::i32 &&
1749 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, true)) {
1750 SDValue Ignored = DAG.getNode(XCoreISD::LMUL, dl,
1751 DAG.getVTList(MVT::i32, MVT::i32), Mul0,
1752 Mul1, Addend0, Addend1);
1753 SDValue Result(Ignored.getNode(), 1);
1756 APInt HighMask = APInt::getHighBitsSet(64, 32);
1757 // Fold 64 bit expression such as add(add(mul(x,y),a),b) ->
1758 // lmul(x, y, a, b) if all operands are zero-extended. We do this
1759 // before type legalization as it is messy to match the operands after
1761 if (N->getValueType(0) == MVT::i64 &&
1762 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, false) &&
1763 DAG.MaskedValueIsZero(Mul0, HighMask) &&
1764 DAG.MaskedValueIsZero(Mul1, HighMask) &&
1765 DAG.MaskedValueIsZero(Addend0, HighMask) &&
1766 DAG.MaskedValueIsZero(Addend1, HighMask)) {
1767 SDValue Mul0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1768 Mul0, DAG.getConstant(0, dl, MVT::i32));
1769 SDValue Mul1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1770 Mul1, DAG.getConstant(0, dl, MVT::i32));
1771 SDValue Addend0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1772 Addend0, DAG.getConstant(0, dl, MVT::i32));
1773 SDValue Addend1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1774 Addend1, DAG.getConstant(0, dl, MVT::i32));
1775 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
1776 DAG.getVTList(MVT::i32, MVT::i32), Mul0L, Mul1L,
1777 Addend0L, Addend1L);
1778 SDValue Lo(Hi.getNode(), 1);
1779 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
1784 // Replace unaligned store of unaligned load with memmove.
1785 StoreSDNode *ST = cast<StoreSDNode>(N);
1786 if (!DCI.isBeforeLegalize() ||
1787 allowsMisalignedMemoryAccesses(ST->getMemoryVT(),
1788 ST->getAddressSpace(),
1789 ST->getAlignment()) ||
1790 ST->isVolatile() || ST->isIndexed()) {
1793 SDValue Chain = ST->getChain();
1795 unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1796 assert((StoreBits % 8) == 0 &&
1797 "Store size in bits must be a multiple of 8");
1798 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(
1799 ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1800 unsigned Alignment = ST->getAlignment();
1801 if (Alignment >= ABIAlignment) {
1805 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1806 if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1807 LD->getAlignment() == Alignment &&
1808 !LD->isVolatile() && !LD->isIndexed() &&
1809 Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1810 bool isTail = isInTailCallPosition(DAG, ST, Chain);
1811 return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1813 DAG.getConstant(StoreBits/8, dl, MVT::i32),
1814 Alignment, false, isTail, ST->getPointerInfo(),
1815 LD->getPointerInfo());
1824 void XCoreTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
1827 const SelectionDAG &DAG,
1828 unsigned Depth) const {
1829 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
1830 switch (Op.getOpcode()) {
1832 case XCoreISD::LADD:
1833 case XCoreISD::LSUB:
1834 if (Op.getResNo() == 1) {
1835 // Top bits of carry / borrow are clear.
1836 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1837 KnownZero.getBitWidth() - 1);
1840 case ISD::INTRINSIC_W_CHAIN:
1842 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1844 case Intrinsic::xcore_getts:
1845 // High bits are known to be zero.
1846 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1847 KnownZero.getBitWidth() - 16);
1849 case Intrinsic::xcore_int:
1850 case Intrinsic::xcore_inct:
1851 // High bits are known to be zero.
1852 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1853 KnownZero.getBitWidth() - 8);
1855 case Intrinsic::xcore_testct:
1856 // Result is either 0 or 1.
1857 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1858 KnownZero.getBitWidth() - 1);
1860 case Intrinsic::xcore_testwct:
1861 // Result is in the range 0 - 4.
1862 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1863 KnownZero.getBitWidth() - 3);
1871 //===----------------------------------------------------------------------===//
1872 // Addressing mode description hooks
1873 //===----------------------------------------------------------------------===//
1875 static inline bool isImmUs(int64_t val)
1877 return (val >= 0 && val <= 11);
1880 static inline bool isImmUs2(int64_t val)
1882 return (val%2 == 0 && isImmUs(val/2));
1885 static inline bool isImmUs4(int64_t val)
1887 return (val%4 == 0 && isImmUs(val/4));
1890 /// isLegalAddressingMode - Return true if the addressing mode represented
1891 /// by AM is legal for this target, for a load/store of the specified type.
1892 bool XCoreTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1893 const AddrMode &AM, Type *Ty,
1894 unsigned AS) const {
1895 if (Ty->getTypeID() == Type::VoidTyID)
1896 return AM.Scale == 0 && isImmUs(AM.BaseOffs) && isImmUs4(AM.BaseOffs);
1898 unsigned Size = DL.getTypeAllocSize(Ty);
1900 return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1907 if (AM.Scale == 0) {
1908 return isImmUs(AM.BaseOffs);
1911 return AM.Scale == 1 && AM.BaseOffs == 0;
1915 if (AM.Scale == 0) {
1916 return isImmUs2(AM.BaseOffs);
1919 return AM.Scale == 2 && AM.BaseOffs == 0;
1922 if (AM.Scale == 0) {
1923 return isImmUs4(AM.BaseOffs);
1926 return AM.Scale == 4 && AM.BaseOffs == 0;
1930 //===----------------------------------------------------------------------===//
1931 // XCore Inline Assembly Support
1932 //===----------------------------------------------------------------------===//
1934 std::pair<unsigned, const TargetRegisterClass *>
1935 XCoreTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
1936 StringRef Constraint,
1938 if (Constraint.size() == 1) {
1939 switch (Constraint[0]) {
1942 return std::make_pair(0U, &XCore::GRRegsRegClass);
1945 // Use the default implementation in TargetLowering to convert the register
1946 // constraint into a member of a register class.
1947 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);