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 #define DEBUG_TYPE "xcore-lower"
16 #include "XCoreISelLowering.h"
18 #include "XCoreMachineFunctionInfo.h"
19 #include "XCoreSubtarget.h"
20 #include "XCoreTargetMachine.h"
21 #include "XCoreTargetObjectFile.h"
22 #include "llvm/CodeGen/CallingConvLower.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineJumpTableInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/SelectionDAGISel.h"
29 #include "llvm/CodeGen/ValueTypes.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/GlobalAlias.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/raw_ostream.h"
44 const char *XCoreTargetLowering::
45 getTargetNodeName(unsigned Opcode) const
49 case XCoreISD::BL : return "XCoreISD::BL";
50 case XCoreISD::PCRelativeWrapper : return "XCoreISD::PCRelativeWrapper";
51 case XCoreISD::DPRelativeWrapper : return "XCoreISD::DPRelativeWrapper";
52 case XCoreISD::CPRelativeWrapper : return "XCoreISD::CPRelativeWrapper";
53 case XCoreISD::STWSP : return "XCoreISD::STWSP";
54 case XCoreISD::RETSP : return "XCoreISD::RETSP";
55 case XCoreISD::LADD : return "XCoreISD::LADD";
56 case XCoreISD::LSUB : return "XCoreISD::LSUB";
57 case XCoreISD::LMUL : return "XCoreISD::LMUL";
58 case XCoreISD::MACCU : return "XCoreISD::MACCU";
59 case XCoreISD::MACCS : return "XCoreISD::MACCS";
60 case XCoreISD::CRC8 : return "XCoreISD::CRC8";
61 case XCoreISD::BR_JT : return "XCoreISD::BR_JT";
62 case XCoreISD::BR_JT32 : return "XCoreISD::BR_JT32";
63 case XCoreISD::FRAME_TO_ARGS_OFFSET : return "XCoreISD::FRAME_TO_ARGS_OFFSET";
64 case XCoreISD::EH_RETURN : return "XCoreISD::EH_RETURN";
65 case XCoreISD::MEMBARRIER : return "XCoreISD::MEMBARRIER";
66 default : return NULL;
70 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
71 : TargetLowering(XTM, new XCoreTargetObjectFile()),
73 Subtarget(*XTM.getSubtargetImpl()) {
75 // Set up the register classes.
76 addRegisterClass(MVT::i32, &XCore::GRRegsRegClass);
78 // Compute derived properties from the register classes
79 computeRegisterProperties();
81 // Division is expensive
82 setIntDivIsCheap(false);
84 setStackPointerRegisterToSaveRestore(XCore::SP);
86 setSchedulingPreference(Sched::Source);
88 // Use i32 for setcc operations results (slt, sgt, ...).
89 setBooleanContents(ZeroOrOneBooleanContent);
90 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
92 // XCore does not have the NodeTypes below.
93 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
94 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
95 setOperationAction(ISD::ADDC, MVT::i32, Expand);
96 setOperationAction(ISD::ADDE, MVT::i32, Expand);
97 setOperationAction(ISD::SUBC, MVT::i32, Expand);
98 setOperationAction(ISD::SUBE, MVT::i32, Expand);
100 // Stop the combiner recombining select and set_cc
101 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
104 setOperationAction(ISD::ADD, MVT::i64, Custom);
105 setOperationAction(ISD::SUB, MVT::i64, Custom);
106 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
107 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
108 setOperationAction(ISD::MULHS, MVT::i32, Expand);
109 setOperationAction(ISD::MULHU, MVT::i32, Expand);
110 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
111 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
112 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
115 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
116 setOperationAction(ISD::ROTL , MVT::i32, Expand);
117 setOperationAction(ISD::ROTR , MVT::i32, Expand);
118 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
119 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
121 setOperationAction(ISD::TRAP, MVT::Other, Legal);
124 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
126 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
127 setOperationAction(ISD::BlockAddress, MVT::i32 , Custom);
129 // Conversion of i64 -> double produces constantpool nodes
130 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
133 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
134 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
135 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
137 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
138 setLoadExtAction(ISD::ZEXTLOAD, 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::SELECT_CC: return LowerSELECT_CC(Op, DAG);
220 case ISD::VAARG: return LowerVAARG(Op, DAG);
221 case ISD::VASTART: return LowerVASTART(Op, DAG);
222 case ISD::SMUL_LOHI: return LowerSMUL_LOHI(Op, DAG);
223 case ISD::UMUL_LOHI: return LowerUMUL_LOHI(Op, DAG);
224 // FIXME: Remove these when LegalizeDAGTypes lands.
226 case ISD::SUB: return ExpandADDSUB(Op.getNode(), DAG);
227 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
228 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
229 case ISD::FRAME_TO_ARGS_OFFSET: return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
230 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
231 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
232 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
233 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
234 case ISD::ATOMIC_LOAD: return LowerATOMIC_LOAD(Op, DAG);
235 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op, DAG);
237 llvm_unreachable("unimplemented operand");
241 /// ReplaceNodeResults - Replace the results of node with an illegal result
242 /// type with new values built out of custom code.
243 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
244 SmallVectorImpl<SDValue>&Results,
245 SelectionDAG &DAG) const {
246 switch (N->getOpcode()) {
248 llvm_unreachable("Don't know how to custom expand this!");
251 Results.push_back(ExpandADDSUB(N, DAG));
256 //===----------------------------------------------------------------------===//
257 // Misc Lower Operation implementation
258 //===----------------------------------------------------------------------===//
260 SDValue XCoreTargetLowering::
261 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
264 SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i32, Op.getOperand(2),
265 Op.getOperand(3), Op.getOperand(4));
266 return DAG.getNode(ISD::SELECT, dl, MVT::i32, Cond, Op.getOperand(0),
270 SDValue XCoreTargetLowering::
271 getGlobalAddressWrapper(SDValue GA, const GlobalValue *GV,
272 SelectionDAG &DAG) const
274 // FIXME there is no actual debug info here
276 const GlobalValue *UnderlyingGV = GV;
277 // If GV is an alias then use the aliasee to determine the wrapper type
278 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
279 UnderlyingGV = GA->resolveAliasedGlobal();
280 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(UnderlyingGV)) {
281 if ( ( GVar->isConstant() &&
282 UnderlyingGV->isLocalLinkage(GV->getLinkage()) )
283 || ( GVar->hasSection() &&
284 StringRef(GVar->getSection()).startswith(".cp.") ) )
285 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
286 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
288 return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
291 static bool IsSmallObject(const GlobalValue *GV, const XCoreTargetLowering &XTL) {
292 if (XTL.getTargetMachine().getCodeModel() == CodeModel::Small)
295 Type *ObjType = GV->getType()->getPointerElementType();
296 if (!ObjType->isSized())
299 unsigned ObjSize = XTL.getDataLayout()->getTypeAllocSize(ObjType);
300 return ObjSize < CodeModelLargeSize && ObjSize != 0;
303 SDValue XCoreTargetLowering::
304 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const
306 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
307 const GlobalValue *GV = GN->getGlobal();
309 int64_t Offset = GN->getOffset();
310 if (IsSmallObject(GV, *this)) {
311 // We can only fold positive offsets that are a multiple of the word size.
312 int64_t FoldedOffset = std::max(Offset & ~3, (int64_t)0);
313 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, FoldedOffset);
314 GA = getGlobalAddressWrapper(GA, GV, DAG);
315 // Handle the rest of the offset.
316 if (Offset != FoldedOffset) {
317 SDValue Remaining = DAG.getConstant(Offset - FoldedOffset, MVT::i32);
318 GA = DAG.getNode(ISD::ADD, DL, MVT::i32, GA, Remaining);
322 // Ideally we would not fold in offset with an index <= 11.
323 Type *Ty = Type::getInt8PtrTy(*DAG.getContext());
324 Constant *GA = ConstantExpr::getBitCast(const_cast<GlobalValue*>(GV), Ty);
325 Ty = Type::getInt32Ty(*DAG.getContext());
326 Constant *Idx = ConstantInt::get(Ty, Offset);
327 Constant *GAI = ConstantExpr::getGetElementPtr(GA, Idx);
328 SDValue CP = DAG.getConstantPool(GAI, MVT::i32);
329 return DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), CP,
330 MachinePointerInfo(), false, false, false, 0);
334 SDValue XCoreTargetLowering::
335 LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const
339 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
340 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy());
342 return DAG.getNode(XCoreISD::PCRelativeWrapper, DL, getPointerTy(), Result);
345 SDValue XCoreTargetLowering::
346 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
348 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
349 // FIXME there isn't really debug info here
351 EVT PtrVT = Op.getValueType();
353 if (CP->isMachineConstantPoolEntry()) {
354 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
355 CP->getAlignment(), CP->getOffset());
357 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
358 CP->getAlignment(), CP->getOffset());
360 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
363 unsigned XCoreTargetLowering::getJumpTableEncoding() const {
364 return MachineJumpTableInfo::EK_Inline;
367 SDValue XCoreTargetLowering::
368 LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
370 SDValue Chain = Op.getOperand(0);
371 SDValue Table = Op.getOperand(1);
372 SDValue Index = Op.getOperand(2);
374 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
375 unsigned JTI = JT->getIndex();
376 MachineFunction &MF = DAG.getMachineFunction();
377 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
378 SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
380 unsigned NumEntries = MJTI->getJumpTables()[JTI].MBBs.size();
381 if (NumEntries <= 32) {
382 return DAG.getNode(XCoreISD::BR_JT, dl, MVT::Other, Chain, TargetJT, Index);
384 assert((NumEntries >> 31) == 0);
385 SDValue ScaledIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
386 DAG.getConstant(1, MVT::i32));
387 return DAG.getNode(XCoreISD::BR_JT32, dl, MVT::Other, Chain, TargetJT,
391 SDValue XCoreTargetLowering::
392 lowerLoadWordFromAlignedBasePlusOffset(SDLoc DL, SDValue Chain, SDValue Base,
393 int64_t Offset, SelectionDAG &DAG) const
395 if ((Offset & 0x3) == 0) {
396 return DAG.getLoad(getPointerTy(), DL, Chain, Base, MachinePointerInfo(),
397 false, false, false, 0);
399 // Lower to pair of consecutive word aligned loads plus some bit shifting.
400 int32_t HighOffset = RoundUpToAlignment(Offset, 4);
401 int32_t LowOffset = HighOffset - 4;
402 SDValue LowAddr, HighAddr;
403 if (GlobalAddressSDNode *GASD =
404 dyn_cast<GlobalAddressSDNode>(Base.getNode())) {
405 LowAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
407 HighAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
410 LowAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
411 DAG.getConstant(LowOffset, MVT::i32));
412 HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
413 DAG.getConstant(HighOffset, MVT::i32));
415 SDValue LowShift = DAG.getConstant((Offset - LowOffset) * 8, MVT::i32);
416 SDValue HighShift = DAG.getConstant((HighOffset - Offset) * 8, MVT::i32);
418 SDValue Low = DAG.getLoad(getPointerTy(), DL, Chain,
419 LowAddr, MachinePointerInfo(),
420 false, false, false, 0);
421 SDValue High = DAG.getLoad(getPointerTy(), DL, Chain,
422 HighAddr, MachinePointerInfo(),
423 false, false, false, 0);
424 SDValue LowShifted = DAG.getNode(ISD::SRL, DL, MVT::i32, Low, LowShift);
425 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High, HighShift);
426 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, LowShifted, HighShifted);
427 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
429 SDValue Ops[] = { Result, Chain };
430 return DAG.getMergeValues(Ops, 2, DL);
433 static bool isWordAligned(SDValue Value, SelectionDAG &DAG)
435 APInt KnownZero, KnownOne;
436 DAG.ComputeMaskedBits(Value, KnownZero, KnownOne);
437 return KnownZero.countTrailingOnes() >= 2;
440 SDValue XCoreTargetLowering::
441 LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
442 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
443 LoadSDNode *LD = cast<LoadSDNode>(Op);
444 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
445 "Unexpected extension type");
446 assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
447 if (allowsUnalignedMemoryAccesses(LD->getMemoryVT()))
450 unsigned ABIAlignment = getDataLayout()->
451 getABITypeAlignment(LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
452 // Leave aligned load alone.
453 if (LD->getAlignment() >= ABIAlignment)
456 SDValue Chain = LD->getChain();
457 SDValue BasePtr = LD->getBasePtr();
460 if (!LD->isVolatile()) {
461 const GlobalValue *GV;
463 if (DAG.isBaseWithConstantOffset(BasePtr) &&
464 isWordAligned(BasePtr->getOperand(0), DAG)) {
465 SDValue NewBasePtr = BasePtr->getOperand(0);
466 Offset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
467 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
470 if (TLI.isGAPlusOffset(BasePtr.getNode(), GV, Offset) &&
471 MinAlign(GV->getAlignment(), 4) == 4) {
472 SDValue NewBasePtr = DAG.getGlobalAddress(GV, DL,
473 BasePtr->getValueType(0));
474 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
479 if (LD->getAlignment() == 2) {
480 SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, DL, MVT::i32, Chain,
481 BasePtr, LD->getPointerInfo(), MVT::i16,
482 LD->isVolatile(), LD->isNonTemporal(), 2);
483 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
484 DAG.getConstant(2, MVT::i32));
485 SDValue High = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
487 LD->getPointerInfo().getWithOffset(2),
488 MVT::i16, LD->isVolatile(),
489 LD->isNonTemporal(), 2);
490 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High,
491 DAG.getConstant(16, MVT::i32));
492 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Low, HighShifted);
493 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
495 SDValue Ops[] = { Result, Chain };
496 return DAG.getMergeValues(Ops, 2, DL);
499 // Lower to a call to __misaligned_load(BasePtr).
500 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
501 TargetLowering::ArgListTy Args;
502 TargetLowering::ArgListEntry Entry;
505 Entry.Node = BasePtr;
506 Args.push_back(Entry);
508 TargetLowering::CallLoweringInfo CLI(Chain, IntPtrTy, false, false,
509 false, false, 0, CallingConv::C, /*isTailCall=*/false,
510 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
511 DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
513 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
516 { CallResult.first, CallResult.second };
518 return DAG.getMergeValues(Ops, 2, DL);
521 SDValue XCoreTargetLowering::
522 LowerSTORE(SDValue Op, SelectionDAG &DAG) const
524 StoreSDNode *ST = cast<StoreSDNode>(Op);
525 assert(!ST->isTruncatingStore() && "Unexpected store type");
526 assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
527 if (allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
530 unsigned ABIAlignment = getDataLayout()->
531 getABITypeAlignment(ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
532 // Leave aligned store alone.
533 if (ST->getAlignment() >= ABIAlignment) {
536 SDValue Chain = ST->getChain();
537 SDValue BasePtr = ST->getBasePtr();
538 SDValue Value = ST->getValue();
541 if (ST->getAlignment() == 2) {
543 SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
544 DAG.getConstant(16, MVT::i32));
545 SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
546 ST->getPointerInfo(), MVT::i16,
547 ST->isVolatile(), ST->isNonTemporal(),
549 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
550 DAG.getConstant(2, MVT::i32));
551 SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
552 ST->getPointerInfo().getWithOffset(2),
553 MVT::i16, ST->isVolatile(),
554 ST->isNonTemporal(), 2);
555 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
558 // Lower to a call to __misaligned_store(BasePtr, Value).
559 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
560 TargetLowering::ArgListTy Args;
561 TargetLowering::ArgListEntry Entry;
564 Entry.Node = BasePtr;
565 Args.push_back(Entry);
568 Args.push_back(Entry);
570 TargetLowering::CallLoweringInfo CLI(Chain,
571 Type::getVoidTy(*DAG.getContext()), false, false,
572 false, false, 0, CallingConv::C, /*isTailCall=*/false,
573 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
574 DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
576 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
578 return CallResult.second;
581 SDValue XCoreTargetLowering::
582 LowerSMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
584 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::SMUL_LOHI &&
585 "Unexpected operand to lower!");
587 SDValue LHS = Op.getOperand(0);
588 SDValue RHS = Op.getOperand(1);
589 SDValue Zero = DAG.getConstant(0, MVT::i32);
590 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
591 DAG.getVTList(MVT::i32, MVT::i32), Zero, Zero,
593 SDValue Lo(Hi.getNode(), 1);
594 SDValue Ops[] = { Lo, Hi };
595 return DAG.getMergeValues(Ops, 2, dl);
598 SDValue XCoreTargetLowering::
599 LowerUMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
601 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::UMUL_LOHI &&
602 "Unexpected operand to lower!");
604 SDValue LHS = Op.getOperand(0);
605 SDValue RHS = Op.getOperand(1);
606 SDValue Zero = DAG.getConstant(0, MVT::i32);
607 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
608 DAG.getVTList(MVT::i32, MVT::i32), LHS, RHS,
610 SDValue Lo(Hi.getNode(), 1);
611 SDValue Ops[] = { Lo, Hi };
612 return DAG.getMergeValues(Ops, 2, dl);
615 /// isADDADDMUL - Return whether Op is in a form that is equivalent to
616 /// add(add(mul(x,y),a),b). If requireIntermediatesHaveOneUse is true then
617 /// each intermediate result in the calculation must also have a single use.
618 /// If the Op is in the correct form the constituent parts are written to Mul0,
619 /// Mul1, Addend0 and Addend1.
621 isADDADDMUL(SDValue Op, SDValue &Mul0, SDValue &Mul1, SDValue &Addend0,
622 SDValue &Addend1, bool requireIntermediatesHaveOneUse)
624 if (Op.getOpcode() != ISD::ADD)
626 SDValue N0 = Op.getOperand(0);
627 SDValue N1 = Op.getOperand(1);
630 if (N0.getOpcode() == ISD::ADD) {
633 } else if (N1.getOpcode() == ISD::ADD) {
639 if (requireIntermediatesHaveOneUse && !AddOp.hasOneUse())
641 if (OtherOp.getOpcode() == ISD::MUL) {
642 // add(add(a,b),mul(x,y))
643 if (requireIntermediatesHaveOneUse && !OtherOp.hasOneUse())
645 Mul0 = OtherOp.getOperand(0);
646 Mul1 = OtherOp.getOperand(1);
647 Addend0 = AddOp.getOperand(0);
648 Addend1 = AddOp.getOperand(1);
651 if (AddOp.getOperand(0).getOpcode() == ISD::MUL) {
652 // add(add(mul(x,y),a),b)
653 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(0).hasOneUse())
655 Mul0 = AddOp.getOperand(0).getOperand(0);
656 Mul1 = AddOp.getOperand(0).getOperand(1);
657 Addend0 = AddOp.getOperand(1);
661 if (AddOp.getOperand(1).getOpcode() == ISD::MUL) {
662 // add(add(a,mul(x,y)),b)
663 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(1).hasOneUse())
665 Mul0 = AddOp.getOperand(1).getOperand(0);
666 Mul1 = AddOp.getOperand(1).getOperand(1);
667 Addend0 = AddOp.getOperand(0);
674 SDValue XCoreTargetLowering::
675 TryExpandADDWithMul(SDNode *N, SelectionDAG &DAG) const
679 if (N->getOperand(0).getOpcode() == ISD::MUL) {
680 Mul = N->getOperand(0);
681 Other = N->getOperand(1);
682 } else if (N->getOperand(1).getOpcode() == ISD::MUL) {
683 Mul = N->getOperand(1);
684 Other = N->getOperand(0);
689 SDValue LL, RL, AddendL, AddendH;
690 LL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
691 Mul.getOperand(0), DAG.getConstant(0, MVT::i32));
692 RL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
693 Mul.getOperand(1), DAG.getConstant(0, MVT::i32));
694 AddendL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
695 Other, DAG.getConstant(0, MVT::i32));
696 AddendH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
697 Other, DAG.getConstant(1, MVT::i32));
698 APInt HighMask = APInt::getHighBitsSet(64, 32);
699 unsigned LHSSB = DAG.ComputeNumSignBits(Mul.getOperand(0));
700 unsigned RHSSB = DAG.ComputeNumSignBits(Mul.getOperand(1));
701 if (DAG.MaskedValueIsZero(Mul.getOperand(0), HighMask) &&
702 DAG.MaskedValueIsZero(Mul.getOperand(1), HighMask)) {
703 // The inputs are both zero-extended.
704 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
705 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
707 SDValue Lo(Hi.getNode(), 1);
708 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
710 if (LHSSB > 32 && RHSSB > 32) {
711 // The inputs are both sign-extended.
712 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
713 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
715 SDValue Lo(Hi.getNode(), 1);
716 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
719 LH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
720 Mul.getOperand(0), DAG.getConstant(1, MVT::i32));
721 RH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
722 Mul.getOperand(1), DAG.getConstant(1, MVT::i32));
723 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
724 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
726 SDValue Lo(Hi.getNode(), 1);
727 RH = DAG.getNode(ISD::MUL, dl, MVT::i32, LL, RH);
728 LH = DAG.getNode(ISD::MUL, dl, MVT::i32, LH, RL);
729 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, RH);
730 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, LH);
731 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
734 SDValue XCoreTargetLowering::
735 ExpandADDSUB(SDNode *N, SelectionDAG &DAG) const
737 assert(N->getValueType(0) == MVT::i64 &&
738 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
739 "Unknown operand to lower!");
741 if (N->getOpcode() == ISD::ADD) {
742 SDValue Result = TryExpandADDWithMul(N, DAG);
743 if (Result.getNode() != 0)
749 // Extract components
750 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
751 N->getOperand(0), DAG.getConstant(0, MVT::i32));
752 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
753 N->getOperand(0), DAG.getConstant(1, MVT::i32));
754 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
755 N->getOperand(1), DAG.getConstant(0, MVT::i32));
756 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
757 N->getOperand(1), DAG.getConstant(1, MVT::i32));
760 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
762 SDValue Zero = DAG.getConstant(0, MVT::i32);
763 SDValue Lo = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
765 SDValue Carry(Lo.getNode(), 1);
767 SDValue Hi = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
769 SDValue Ignored(Hi.getNode(), 1);
771 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
774 SDValue XCoreTargetLowering::
775 LowerVAARG(SDValue Op, SelectionDAG &DAG) const
777 // Whist llvm does not support aggregate varargs we can ignore
778 // the possibility of the ValueType being an implicit byVal vararg.
779 SDNode *Node = Op.getNode();
780 EVT VT = Node->getValueType(0); // not an aggregate
781 SDValue InChain = Node->getOperand(0);
782 SDValue VAListPtr = Node->getOperand(1);
783 EVT PtrVT = VAListPtr.getValueType();
784 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
786 SDValue VAList = DAG.getLoad(PtrVT, dl, InChain,
787 VAListPtr, MachinePointerInfo(SV),
788 false, false, false, 0);
789 // Increment the pointer, VAList, to the next vararg
790 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAList,
791 DAG.getIntPtrConstant(VT.getSizeInBits() / 8));
792 // Store the incremented VAList to the legalized pointer
793 InChain = DAG.getStore(VAList.getValue(1), dl, nextPtr, VAListPtr,
794 MachinePointerInfo(SV), false, false, 0);
795 // Load the actual argument out of the pointer VAList
796 return DAG.getLoad(VT, dl, InChain, VAList, MachinePointerInfo(),
797 false, false, false, 0);
800 SDValue XCoreTargetLowering::
801 LowerVASTART(SDValue Op, SelectionDAG &DAG) const
804 // vastart stores the address of the VarArgsFrameIndex slot into the
805 // memory location argument
806 MachineFunction &MF = DAG.getMachineFunction();
807 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
808 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
809 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1),
810 MachinePointerInfo(), false, false, 0);
813 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op,
814 SelectionDAG &DAG) const {
815 // This nodes represent llvm.frameaddress on the DAG.
816 // It takes one operand, the index of the frame address to return.
817 // An index of zero corresponds to the current function's frame address.
818 // An index of one to the parent's frame address, and so on.
819 // Depths > 0 not supported yet!
820 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
823 MachineFunction &MF = DAG.getMachineFunction();
824 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
825 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op),
826 RegInfo->getFrameRegister(MF), MVT::i32);
829 SDValue XCoreTargetLowering::
830 LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const {
831 // This nodes represent llvm.returnaddress on the DAG.
832 // It takes one operand, the index of the return address to return.
833 // An index of zero corresponds to the current function's return address.
834 // An index of one to the parent's return address, and so on.
835 // Depths > 0 not supported yet!
836 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
839 MachineFunction &MF = DAG.getMachineFunction();
840 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
841 int FI = XFI->createLRSpillSlot(MF);
842 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
843 return DAG.getLoad(getPointerTy(), SDLoc(Op), DAG.getEntryNode(), FIN,
844 MachinePointerInfo::getFixedStack(FI), false, false,
848 SDValue XCoreTargetLowering::
849 LowerFRAME_TO_ARGS_OFFSET(SDValue Op, SelectionDAG &DAG) const {
850 // This node represents offset from frame pointer to first on-stack argument.
851 // This is needed for correct stack adjustment during unwind.
852 // However, we don't know the offset until after the frame has be finalised.
853 // This is done during the XCoreFTAOElim pass.
854 return DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, SDLoc(Op), MVT::i32);
857 SDValue XCoreTargetLowering::
858 LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
859 // OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER)
860 // This node represents 'eh_return' gcc dwarf builtin, which is used to
861 // return from exception. The general meaning is: adjust stack by OFFSET and
862 // pass execution to HANDLER.
863 MachineFunction &MF = DAG.getMachineFunction();
864 SDValue Chain = Op.getOperand(0);
865 SDValue Offset = Op.getOperand(1);
866 SDValue Handler = Op.getOperand(2);
869 // Absolute SP = (FP + FrameToArgs) + Offset
870 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
871 SDValue Stack = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
872 RegInfo->getFrameRegister(MF), MVT::i32);
873 SDValue FrameToArgs = DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, dl,
875 Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, FrameToArgs);
876 Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, Offset);
878 // R0=ExceptionPointerRegister R1=ExceptionSelectorRegister
879 // which leaves 2 caller saved registers, R2 & R3 for us to use.
880 unsigned StackReg = XCore::R2;
881 unsigned HandlerReg = XCore::R3;
883 SDValue OutChains[] = {
884 DAG.getCopyToReg(Chain, dl, StackReg, Stack),
885 DAG.getCopyToReg(Chain, dl, HandlerReg, Handler)
888 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 2);
890 return DAG.getNode(XCoreISD::EH_RETURN, dl, MVT::Other, Chain,
891 DAG.getRegister(StackReg, MVT::i32),
892 DAG.getRegister(HandlerReg, MVT::i32));
896 SDValue XCoreTargetLowering::
897 LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
898 return Op.getOperand(0);
901 SDValue XCoreTargetLowering::
902 LowerINIT_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
903 SDValue Chain = Op.getOperand(0);
904 SDValue Trmp = Op.getOperand(1); // trampoline
905 SDValue FPtr = Op.getOperand(2); // nested function
906 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
908 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
911 // LDAPF_u10 r11, nest
912 // LDW_2rus r11, r11[0]
913 // STWSP_ru6 r11, sp[0]
914 // LDAPF_u10 r11, fptr
915 // LDW_2rus r11, r11[0]
921 SDValue OutChains[5];
926 OutChains[0] = DAG.getStore(Chain, dl, DAG.getConstant(0x0a3cd805, MVT::i32),
927 Addr, MachinePointerInfo(TrmpAddr), false, false,
930 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
931 DAG.getConstant(4, MVT::i32));
932 OutChains[1] = DAG.getStore(Chain, dl, DAG.getConstant(0xd80456c0, MVT::i32),
933 Addr, MachinePointerInfo(TrmpAddr, 4), false,
936 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
937 DAG.getConstant(8, MVT::i32));
938 OutChains[2] = DAG.getStore(Chain, dl, DAG.getConstant(0x27fb0a3c, MVT::i32),
939 Addr, MachinePointerInfo(TrmpAddr, 8), false,
942 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
943 DAG.getConstant(12, MVT::i32));
944 OutChains[3] = DAG.getStore(Chain, dl, Nest, Addr,
945 MachinePointerInfo(TrmpAddr, 12), false, false,
948 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
949 DAG.getConstant(16, MVT::i32));
950 OutChains[4] = DAG.getStore(Chain, dl, FPtr, Addr,
951 MachinePointerInfo(TrmpAddr, 16), false, false,
954 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 5);
957 SDValue XCoreTargetLowering::
958 LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
960 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
962 case Intrinsic::xcore_crc8:
963 EVT VT = Op.getValueType();
965 DAG.getNode(XCoreISD::CRC8, DL, DAG.getVTList(VT, VT),
966 Op.getOperand(1), Op.getOperand(2) , Op.getOperand(3));
967 SDValue Crc(Data.getNode(), 1);
968 SDValue Results[] = { Crc, Data };
969 return DAG.getMergeValues(Results, 2, DL);
974 SDValue XCoreTargetLowering::
975 LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG) const {
977 return DAG.getNode(XCoreISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
980 SDValue XCoreTargetLowering::
981 LowerATOMIC_LOAD(SDValue Op, SelectionDAG &DAG) const {
982 AtomicSDNode *N = cast<AtomicSDNode>(Op);
983 assert(N->getOpcode() == ISD::ATOMIC_LOAD && "Bad Atomic OP");
984 assert(N->getOrdering() <= Monotonic &&
985 "setInsertFencesForAtomic(true) and yet greater than Monotonic");
986 if (N->getMemoryVT() == MVT::i32) {
987 if (N->getAlignment() < 4)
988 report_fatal_error("atomic load must be aligned");
989 return DAG.getLoad(getPointerTy(), SDLoc(Op), N->getChain(),
990 N->getBasePtr(), N->getPointerInfo(),
991 N->isVolatile(), N->isNonTemporal(),
992 N->isInvariant(), N->getAlignment(),
993 N->getTBAAInfo(), N->getRanges());
995 if (N->getMemoryVT() == MVT::i16) {
996 if (N->getAlignment() < 2)
997 report_fatal_error("atomic load must be aligned");
998 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
999 N->getBasePtr(), N->getPointerInfo(), MVT::i16,
1000 N->isVolatile(), N->isNonTemporal(),
1001 N->getAlignment(), N->getTBAAInfo());
1003 if (N->getMemoryVT() == MVT::i8)
1004 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
1005 N->getBasePtr(), N->getPointerInfo(), MVT::i8,
1006 N->isVolatile(), N->isNonTemporal(),
1007 N->getAlignment(), N->getTBAAInfo());
1011 SDValue XCoreTargetLowering::
1012 LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) const {
1013 AtomicSDNode *N = cast<AtomicSDNode>(Op);
1014 assert(N->getOpcode() == ISD::ATOMIC_STORE && "Bad Atomic OP");
1015 assert(N->getOrdering() <= Monotonic &&
1016 "setInsertFencesForAtomic(true) and yet greater than Monotonic");
1017 if (N->getMemoryVT() == MVT::i32) {
1018 if (N->getAlignment() < 4)
1019 report_fatal_error("atomic store must be aligned");
1020 return DAG.getStore(N->getChain(), SDLoc(Op), N->getVal(),
1021 N->getBasePtr(), N->getPointerInfo(),
1022 N->isVolatile(), N->isNonTemporal(),
1023 N->getAlignment(), N->getTBAAInfo());
1025 if (N->getMemoryVT() == MVT::i16) {
1026 if (N->getAlignment() < 2)
1027 report_fatal_error("atomic store must be aligned");
1028 return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1029 N->getBasePtr(), N->getPointerInfo(), MVT::i16,
1030 N->isVolatile(), N->isNonTemporal(),
1031 N->getAlignment(), N->getTBAAInfo());
1033 if (N->getMemoryVT() == MVT::i8)
1034 return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1035 N->getBasePtr(), N->getPointerInfo(), MVT::i8,
1036 N->isVolatile(), N->isNonTemporal(),
1037 N->getAlignment(), N->getTBAAInfo());
1041 //===----------------------------------------------------------------------===//
1042 // Calling Convention Implementation
1043 //===----------------------------------------------------------------------===//
1045 #include "XCoreGenCallingConv.inc"
1047 //===----------------------------------------------------------------------===//
1048 // Call Calling Convention Implementation
1049 //===----------------------------------------------------------------------===//
1051 /// XCore call implementation
1053 XCoreTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1054 SmallVectorImpl<SDValue> &InVals) const {
1055 SelectionDAG &DAG = CLI.DAG;
1057 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1058 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1059 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1060 SDValue Chain = CLI.Chain;
1061 SDValue Callee = CLI.Callee;
1062 bool &isTailCall = CLI.IsTailCall;
1063 CallingConv::ID CallConv = CLI.CallConv;
1064 bool isVarArg = CLI.IsVarArg;
1066 // XCore target does not yet support tail call optimization.
1069 // For now, only CallingConv::C implemented
1073 llvm_unreachable("Unsupported calling convention");
1074 case CallingConv::Fast:
1075 case CallingConv::C:
1076 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
1077 Outs, OutVals, Ins, dl, DAG, InVals);
1081 /// LowerCCCCallTo - functions arguments are copied from virtual
1082 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
1083 /// CALLSEQ_END are emitted.
1084 /// TODO: isTailCall, sret.
1086 XCoreTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
1087 CallingConv::ID CallConv, bool isVarArg,
1089 const SmallVectorImpl<ISD::OutputArg> &Outs,
1090 const SmallVectorImpl<SDValue> &OutVals,
1091 const SmallVectorImpl<ISD::InputArg> &Ins,
1092 SDLoc dl, SelectionDAG &DAG,
1093 SmallVectorImpl<SDValue> &InVals) const {
1095 // Analyze operands of the call, assigning locations to each operand.
1096 SmallVector<CCValAssign, 16> ArgLocs;
1097 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1098 getTargetMachine(), ArgLocs, *DAG.getContext());
1100 // The ABI dictates there should be one stack slot available to the callee
1101 // on function entry (for saving lr).
1102 CCInfo.AllocateStack(4, 4);
1104 CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
1106 // Get a count of how many bytes are to be pushed on the stack.
1107 unsigned NumBytes = CCInfo.getNextStackOffset();
1109 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
1110 getPointerTy(), true), dl);
1112 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
1113 SmallVector<SDValue, 12> MemOpChains;
1115 // Walk the register/memloc assignments, inserting copies/loads.
1116 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1117 CCValAssign &VA = ArgLocs[i];
1118 SDValue Arg = OutVals[i];
1120 // Promote the value if needed.
1121 switch (VA.getLocInfo()) {
1122 default: llvm_unreachable("Unknown loc info!");
1123 case CCValAssign::Full: break;
1124 case CCValAssign::SExt:
1125 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1127 case CCValAssign::ZExt:
1128 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1130 case CCValAssign::AExt:
1131 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1135 // Arguments that can be passed on register must be kept at
1136 // RegsToPass vector
1137 if (VA.isRegLoc()) {
1138 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1140 assert(VA.isMemLoc());
1142 int Offset = VA.getLocMemOffset();
1144 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
1146 DAG.getConstant(Offset/4, MVT::i32)));
1150 // Transform all store nodes into one single node because
1151 // all store nodes are independent of each other.
1152 if (!MemOpChains.empty())
1153 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1154 &MemOpChains[0], MemOpChains.size());
1156 // Build a sequence of copy-to-reg nodes chained together with token
1157 // chain and flag operands which copy the outgoing args into registers.
1158 // The InFlag in necessary since all emitted instructions must be
1161 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1162 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1163 RegsToPass[i].second, InFlag);
1164 InFlag = Chain.getValue(1);
1167 // If the callee is a GlobalAddress node (quite common, every direct call is)
1168 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1169 // Likewise ExternalSymbol -> TargetExternalSymbol.
1170 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1171 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
1172 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
1173 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
1175 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
1176 // = Chain, Callee, Reg#1, Reg#2, ...
1178 // Returns a chain & a flag for retval copy to use.
1179 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1180 SmallVector<SDValue, 8> Ops;
1181 Ops.push_back(Chain);
1182 Ops.push_back(Callee);
1184 // Add argument registers to the end of the list so that they are
1185 // known live into the call.
1186 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1187 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1188 RegsToPass[i].second.getValueType()));
1190 if (InFlag.getNode())
1191 Ops.push_back(InFlag);
1193 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, &Ops[0], Ops.size());
1194 InFlag = Chain.getValue(1);
1196 // Create the CALLSEQ_END node.
1197 Chain = DAG.getCALLSEQ_END(Chain,
1198 DAG.getConstant(NumBytes, getPointerTy(), true),
1199 DAG.getConstant(0, getPointerTy(), true),
1201 InFlag = Chain.getValue(1);
1203 // Handle result values, copying them out of physregs into vregs that we
1205 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
1206 Ins, dl, DAG, InVals);
1209 /// LowerCallResult - Lower the result values of a call into the
1210 /// appropriate copies out of appropriate physical registers.
1212 XCoreTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1213 CallingConv::ID CallConv, bool isVarArg,
1214 const SmallVectorImpl<ISD::InputArg> &Ins,
1215 SDLoc dl, SelectionDAG &DAG,
1216 SmallVectorImpl<SDValue> &InVals) const {
1218 // Assign locations to each value returned by this call.
1219 SmallVector<CCValAssign, 16> RVLocs;
1220 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1221 getTargetMachine(), RVLocs, *DAG.getContext());
1223 CCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
1225 // Copy all of the result registers out of their specified physreg.
1226 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1227 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
1228 RVLocs[i].getValVT(), InFlag).getValue(1);
1229 InFlag = Chain.getValue(2);
1230 InVals.push_back(Chain.getValue(0));
1236 //===----------------------------------------------------------------------===//
1237 // Formal Arguments Calling Convention Implementation
1238 //===----------------------------------------------------------------------===//
1241 struct ArgDataPair { SDValue SDV; ISD::ArgFlagsTy Flags; };
1244 /// XCore formal arguments implementation
1246 XCoreTargetLowering::LowerFormalArguments(SDValue Chain,
1247 CallingConv::ID CallConv,
1249 const SmallVectorImpl<ISD::InputArg> &Ins,
1252 SmallVectorImpl<SDValue> &InVals)
1257 llvm_unreachable("Unsupported calling convention");
1258 case CallingConv::C:
1259 case CallingConv::Fast:
1260 return LowerCCCArguments(Chain, CallConv, isVarArg,
1261 Ins, dl, DAG, InVals);
1265 /// LowerCCCArguments - transform physical registers into
1266 /// virtual registers and generate load operations for
1267 /// arguments places on the stack.
1270 XCoreTargetLowering::LowerCCCArguments(SDValue Chain,
1271 CallingConv::ID CallConv,
1273 const SmallVectorImpl<ISD::InputArg>
1277 SmallVectorImpl<SDValue> &InVals) const {
1278 MachineFunction &MF = DAG.getMachineFunction();
1279 MachineFrameInfo *MFI = MF.getFrameInfo();
1280 MachineRegisterInfo &RegInfo = MF.getRegInfo();
1282 // Assign locations to all of the incoming arguments.
1283 SmallVector<CCValAssign, 16> ArgLocs;
1284 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1285 getTargetMachine(), ArgLocs, *DAG.getContext());
1287 CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
1289 unsigned StackSlotSize = XCoreFrameLowering::stackSlotSize();
1291 unsigned LRSaveSize = StackSlotSize;
1293 // All getCopyFromReg ops must precede any getMemcpys to prevent the
1294 // scheduler clobbering a register before it has been copied.
1296 // 1. CopyFromReg (and load) arg & vararg registers.
1297 // 2. Chain CopyFromReg nodes into a TokenFactor.
1298 // 3. Memcpy 'byVal' args & push final InVals.
1299 // 4. Chain mem ops nodes into a TokenFactor.
1300 SmallVector<SDValue, 4> CFRegNode;
1301 SmallVector<ArgDataPair, 4> ArgData;
1302 SmallVector<SDValue, 4> MemOps;
1304 // 1a. CopyFromReg (and load) arg registers.
1305 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1307 CCValAssign &VA = ArgLocs[i];
1310 if (VA.isRegLoc()) {
1311 // Arguments passed in registers
1312 EVT RegVT = VA.getLocVT();
1313 switch (RegVT.getSimpleVT().SimpleTy) {
1317 errs() << "LowerFormalArguments Unhandled argument type: "
1318 << RegVT.getSimpleVT().SimpleTy << "\n";
1320 llvm_unreachable(0);
1323 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1324 RegInfo.addLiveIn(VA.getLocReg(), VReg);
1325 ArgIn = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
1326 CFRegNode.push_back(ArgIn.getValue(ArgIn->getNumValues() - 1));
1330 assert(VA.isMemLoc());
1331 // Load the argument to a virtual register
1332 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
1333 if (ObjSize > StackSlotSize) {
1334 errs() << "LowerFormalArguments Unhandled argument type: "
1335 << EVT(VA.getLocVT()).getEVTString()
1338 // Create the frame index object for this incoming parameter...
1339 int FI = MFI->CreateFixedObject(ObjSize,
1340 LRSaveSize + VA.getLocMemOffset(),
1343 // Create the SelectionDAG nodes corresponding to a load
1344 //from this parameter
1345 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1346 ArgIn = DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
1347 MachinePointerInfo::getFixedStack(FI),
1348 false, false, false, 0);
1350 const ArgDataPair ADP = { ArgIn, Ins[i].Flags };
1351 ArgData.push_back(ADP);
1354 // 1b. CopyFromReg vararg registers.
1356 // Argument registers
1357 static const uint16_t ArgRegs[] = {
1358 XCore::R0, XCore::R1, XCore::R2, XCore::R3
1360 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1361 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
1362 array_lengthof(ArgRegs));
1363 if (FirstVAReg < array_lengthof(ArgRegs)) {
1365 // Save remaining registers, storing higher register numbers at a higher
1367 for (int i = array_lengthof(ArgRegs) - 1; i >= (int)FirstVAReg; --i) {
1368 // Create a stack slot
1369 int FI = MFI->CreateFixedObject(4, offset, true);
1370 if (i == (int)FirstVAReg) {
1371 XFI->setVarArgsFrameIndex(FI);
1373 offset -= StackSlotSize;
1374 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1375 // Move argument from phys reg -> virt reg
1376 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1377 RegInfo.addLiveIn(ArgRegs[i], VReg);
1378 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1379 CFRegNode.push_back(Val.getValue(Val->getNumValues() - 1));
1380 // Move argument from virt reg -> stack
1381 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
1382 MachinePointerInfo(), false, false, 0);
1383 MemOps.push_back(Store);
1386 // This will point to the next argument passed via stack.
1387 XFI->setVarArgsFrameIndex(
1388 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset(),
1393 // 2. chain CopyFromReg nodes into a TokenFactor.
1394 if (!CFRegNode.empty())
1395 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &CFRegNode[0],
1398 // 3. Memcpy 'byVal' args & push final InVals.
1399 // Aggregates passed "byVal" need to be copied by the callee.
1400 // The callee will use a pointer to this copy, rather than the original
1402 for (SmallVectorImpl<ArgDataPair>::const_iterator ArgDI = ArgData.begin(),
1403 ArgDE = ArgData.end();
1404 ArgDI != ArgDE; ++ArgDI) {
1405 if (ArgDI->Flags.isByVal() && ArgDI->Flags.getByValSize()) {
1406 unsigned Size = ArgDI->Flags.getByValSize();
1407 unsigned Align = std::max(StackSlotSize, ArgDI->Flags.getByValAlign());
1408 // Create a new object on the stack and copy the pointee into it.
1409 int FI = MFI->CreateStackObject(Size, Align, false);
1410 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1411 InVals.push_back(FIN);
1412 MemOps.push_back(DAG.getMemcpy(Chain, dl, FIN, ArgDI->SDV,
1413 DAG.getConstant(Size, MVT::i32),
1414 Align, false, false,
1415 MachinePointerInfo(),
1416 MachinePointerInfo()));
1418 InVals.push_back(ArgDI->SDV);
1422 // 4, chain mem ops nodes into a TokenFactor.
1423 if (!MemOps.empty()) {
1424 MemOps.push_back(Chain);
1425 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &MemOps[0],
1432 //===----------------------------------------------------------------------===//
1433 // Return Value Calling Convention Implementation
1434 //===----------------------------------------------------------------------===//
1436 bool XCoreTargetLowering::
1437 CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF,
1439 const SmallVectorImpl<ISD::OutputArg> &Outs,
1440 LLVMContext &Context) const {
1441 SmallVector<CCValAssign, 16> RVLocs;
1442 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
1443 return CCInfo.CheckReturn(Outs, RetCC_XCore);
1447 XCoreTargetLowering::LowerReturn(SDValue Chain,
1448 CallingConv::ID CallConv, bool isVarArg,
1449 const SmallVectorImpl<ISD::OutputArg> &Outs,
1450 const SmallVectorImpl<SDValue> &OutVals,
1451 SDLoc dl, SelectionDAG &DAG) const {
1453 // CCValAssign - represent the assignment of
1454 // the return value to a location
1455 SmallVector<CCValAssign, 16> RVLocs;
1457 // CCState - Info about the registers and stack slot.
1458 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1459 getTargetMachine(), RVLocs, *DAG.getContext());
1461 // Analyze return values.
1462 CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
1465 SmallVector<SDValue, 4> RetOps(1, Chain);
1467 // Return on XCore is always a "retsp 0"
1468 RetOps.push_back(DAG.getConstant(0, MVT::i32));
1470 // Copy the result values into the output registers.
1471 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1472 CCValAssign &VA = RVLocs[i];
1473 assert(VA.isRegLoc() && "Can only return in registers!");
1475 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1478 // guarantee that all emitted copies are
1479 // stuck together, avoiding something bad
1480 Flag = Chain.getValue(1);
1481 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1484 RetOps[0] = Chain; // Update chain.
1486 // Add the flag if we have it.
1488 RetOps.push_back(Flag);
1490 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
1491 &RetOps[0], RetOps.size());
1494 //===----------------------------------------------------------------------===//
1495 // Other Lowering Code
1496 //===----------------------------------------------------------------------===//
1499 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1500 MachineBasicBlock *BB) const {
1501 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1502 DebugLoc dl = MI->getDebugLoc();
1503 assert((MI->getOpcode() == XCore::SELECT_CC) &&
1504 "Unexpected instr type to insert");
1506 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1507 // control-flow pattern. The incoming instruction knows the destination vreg
1508 // to set, the condition code register to branch on, the true/false values to
1509 // select between, and a branch opcode to use.
1510 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1511 MachineFunction::iterator It = BB;
1517 // cmpTY ccX, r1, r2
1519 // fallthrough --> copy0MBB
1520 MachineBasicBlock *thisMBB = BB;
1521 MachineFunction *F = BB->getParent();
1522 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1523 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1524 F->insert(It, copy0MBB);
1525 F->insert(It, sinkMBB);
1527 // Transfer the remainder of BB and its successor edges to sinkMBB.
1528 sinkMBB->splice(sinkMBB->begin(), BB,
1529 llvm::next(MachineBasicBlock::iterator(MI)),
1531 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1533 // Next, add the true and fallthrough blocks as its successors.
1534 BB->addSuccessor(copy0MBB);
1535 BB->addSuccessor(sinkMBB);
1537 BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1538 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1541 // %FalseValue = ...
1542 // # fallthrough to sinkMBB
1545 // Update machine-CFG edges
1546 BB->addSuccessor(sinkMBB);
1549 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1552 BuildMI(*BB, BB->begin(), dl,
1553 TII.get(XCore::PHI), MI->getOperand(0).getReg())
1554 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1555 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1557 MI->eraseFromParent(); // The pseudo instruction is gone now.
1561 //===----------------------------------------------------------------------===//
1562 // Target Optimization Hooks
1563 //===----------------------------------------------------------------------===//
1565 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1566 DAGCombinerInfo &DCI) const {
1567 SelectionDAG &DAG = DCI.DAG;
1569 switch (N->getOpcode()) {
1571 case ISD::INTRINSIC_VOID:
1572 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
1573 case Intrinsic::xcore_outt:
1574 case Intrinsic::xcore_outct:
1575 case Intrinsic::xcore_chkct: {
1576 SDValue OutVal = N->getOperand(3);
1577 // These instructions ignore the high bits.
1578 if (OutVal.hasOneUse()) {
1579 unsigned BitWidth = OutVal.getValueSizeInBits();
1580 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8);
1581 APInt KnownZero, KnownOne;
1582 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1583 !DCI.isBeforeLegalizeOps());
1584 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1585 if (TLO.ShrinkDemandedConstant(OutVal, DemandedMask) ||
1586 TLI.SimplifyDemandedBits(OutVal, DemandedMask, KnownZero, KnownOne,
1588 DCI.CommitTargetLoweringOpt(TLO);
1592 case Intrinsic::xcore_setpt: {
1593 SDValue Time = N->getOperand(3);
1594 // This instruction ignores the high bits.
1595 if (Time.hasOneUse()) {
1596 unsigned BitWidth = Time.getValueSizeInBits();
1597 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
1598 APInt KnownZero, KnownOne;
1599 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1600 !DCI.isBeforeLegalizeOps());
1601 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1602 if (TLO.ShrinkDemandedConstant(Time, DemandedMask) ||
1603 TLI.SimplifyDemandedBits(Time, DemandedMask, KnownZero, KnownOne,
1605 DCI.CommitTargetLoweringOpt(TLO);
1611 case XCoreISD::LADD: {
1612 SDValue N0 = N->getOperand(0);
1613 SDValue N1 = N->getOperand(1);
1614 SDValue N2 = N->getOperand(2);
1615 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1616 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1617 EVT VT = N0.getValueType();
1619 // canonicalize constant to RHS
1621 return DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N1, N0, N2);
1623 // fold (ladd 0, 0, x) -> 0, x & 1
1624 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1625 SDValue Carry = DAG.getConstant(0, VT);
1626 SDValue Result = DAG.getNode(ISD::AND, dl, VT, N2,
1627 DAG.getConstant(1, VT));
1628 SDValue Ops[] = { Result, Carry };
1629 return DAG.getMergeValues(Ops, 2, dl);
1632 // fold (ladd x, 0, y) -> 0, add x, y iff carry is unused and y has only the
1634 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1635 APInt KnownZero, KnownOne;
1636 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1637 VT.getSizeInBits() - 1);
1638 DAG.ComputeMaskedBits(N2, KnownZero, KnownOne);
1639 if ((KnownZero & Mask) == Mask) {
1640 SDValue Carry = DAG.getConstant(0, VT);
1641 SDValue Result = DAG.getNode(ISD::ADD, dl, VT, N0, N2);
1642 SDValue Ops[] = { Result, Carry };
1643 return DAG.getMergeValues(Ops, 2, dl);
1648 case XCoreISD::LSUB: {
1649 SDValue N0 = N->getOperand(0);
1650 SDValue N1 = N->getOperand(1);
1651 SDValue N2 = N->getOperand(2);
1652 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1653 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1654 EVT VT = N0.getValueType();
1656 // fold (lsub 0, 0, x) -> x, -x iff x has only the low bit set
1657 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1658 APInt KnownZero, KnownOne;
1659 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1660 VT.getSizeInBits() - 1);
1661 DAG.ComputeMaskedBits(N2, KnownZero, KnownOne);
1662 if ((KnownZero & Mask) == Mask) {
1663 SDValue Borrow = N2;
1664 SDValue Result = DAG.getNode(ISD::SUB, dl, VT,
1665 DAG.getConstant(0, VT), N2);
1666 SDValue Ops[] = { Result, Borrow };
1667 return DAG.getMergeValues(Ops, 2, dl);
1671 // fold (lsub x, 0, y) -> 0, sub x, y iff borrow is unused and y has only the
1673 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1674 APInt KnownZero, KnownOne;
1675 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1676 VT.getSizeInBits() - 1);
1677 DAG.ComputeMaskedBits(N2, KnownZero, KnownOne);
1678 if ((KnownZero & Mask) == Mask) {
1679 SDValue Borrow = DAG.getConstant(0, VT);
1680 SDValue Result = DAG.getNode(ISD::SUB, dl, VT, N0, N2);
1681 SDValue Ops[] = { Result, Borrow };
1682 return DAG.getMergeValues(Ops, 2, dl);
1687 case XCoreISD::LMUL: {
1688 SDValue N0 = N->getOperand(0);
1689 SDValue N1 = N->getOperand(1);
1690 SDValue N2 = N->getOperand(2);
1691 SDValue N3 = N->getOperand(3);
1692 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1693 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1694 EVT VT = N0.getValueType();
1695 // Canonicalize multiplicative constant to RHS. If both multiplicative
1696 // operands are constant canonicalize smallest to RHS.
1697 if ((N0C && !N1C) ||
1698 (N0C && N1C && N0C->getZExtValue() < N1C->getZExtValue()))
1699 return DAG.getNode(XCoreISD::LMUL, dl, DAG.getVTList(VT, VT),
1703 if (N1C && N1C->isNullValue()) {
1704 // If the high result is unused fold to add(a, b)
1705 if (N->hasNUsesOfValue(0, 0)) {
1706 SDValue Lo = DAG.getNode(ISD::ADD, dl, VT, N2, N3);
1707 SDValue Ops[] = { Lo, Lo };
1708 return DAG.getMergeValues(Ops, 2, dl);
1710 // Otherwise fold to ladd(a, b, 0)
1712 DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N2, N3, N1);
1713 SDValue Carry(Result.getNode(), 1);
1714 SDValue Ops[] = { Carry, Result };
1715 return DAG.getMergeValues(Ops, 2, dl);
1720 // Fold 32 bit expressions such as add(add(mul(x,y),a),b) ->
1721 // lmul(x, y, a, b). The high result of lmul will be ignored.
1722 // This is only profitable if the intermediate results are unused
1724 SDValue Mul0, Mul1, Addend0, Addend1;
1725 if (N->getValueType(0) == MVT::i32 &&
1726 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, true)) {
1727 SDValue Ignored = DAG.getNode(XCoreISD::LMUL, dl,
1728 DAG.getVTList(MVT::i32, MVT::i32), Mul0,
1729 Mul1, Addend0, Addend1);
1730 SDValue Result(Ignored.getNode(), 1);
1733 APInt HighMask = APInt::getHighBitsSet(64, 32);
1734 // Fold 64 bit expression such as add(add(mul(x,y),a),b) ->
1735 // lmul(x, y, a, b) if all operands are zero-extended. We do this
1736 // before type legalization as it is messy to match the operands after
1738 if (N->getValueType(0) == MVT::i64 &&
1739 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, false) &&
1740 DAG.MaskedValueIsZero(Mul0, HighMask) &&
1741 DAG.MaskedValueIsZero(Mul1, HighMask) &&
1742 DAG.MaskedValueIsZero(Addend0, HighMask) &&
1743 DAG.MaskedValueIsZero(Addend1, HighMask)) {
1744 SDValue Mul0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1745 Mul0, DAG.getConstant(0, MVT::i32));
1746 SDValue Mul1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1747 Mul1, DAG.getConstant(0, MVT::i32));
1748 SDValue Addend0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1749 Addend0, DAG.getConstant(0, MVT::i32));
1750 SDValue Addend1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1751 Addend1, DAG.getConstant(0, MVT::i32));
1752 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
1753 DAG.getVTList(MVT::i32, MVT::i32), Mul0L, Mul1L,
1754 Addend0L, Addend1L);
1755 SDValue Lo(Hi.getNode(), 1);
1756 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
1761 // Replace unaligned store of unaligned load with memmove.
1762 StoreSDNode *ST = cast<StoreSDNode>(N);
1763 if (!DCI.isBeforeLegalize() ||
1764 allowsUnalignedMemoryAccesses(ST->getMemoryVT()) ||
1765 ST->isVolatile() || ST->isIndexed()) {
1768 SDValue Chain = ST->getChain();
1770 unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1771 if (StoreBits % 8) {
1774 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(
1775 ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1776 unsigned Alignment = ST->getAlignment();
1777 if (Alignment >= ABIAlignment) {
1781 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1782 if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1783 LD->getAlignment() == Alignment &&
1784 !LD->isVolatile() && !LD->isIndexed() &&
1785 Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1786 return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1788 DAG.getConstant(StoreBits/8, MVT::i32),
1789 Alignment, false, ST->getPointerInfo(),
1790 LD->getPointerInfo());
1799 void XCoreTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
1802 const SelectionDAG &DAG,
1803 unsigned Depth) const {
1804 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
1805 switch (Op.getOpcode()) {
1807 case XCoreISD::LADD:
1808 case XCoreISD::LSUB:
1809 if (Op.getResNo() == 1) {
1810 // Top bits of carry / borrow are clear.
1811 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1812 KnownZero.getBitWidth() - 1);
1815 case ISD::INTRINSIC_W_CHAIN:
1817 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1819 case Intrinsic::xcore_getts:
1820 // High bits are known to be zero.
1821 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1822 KnownZero.getBitWidth() - 16);
1824 case Intrinsic::xcore_int:
1825 case Intrinsic::xcore_inct:
1826 // High bits are known to be zero.
1827 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1828 KnownZero.getBitWidth() - 8);
1830 case Intrinsic::xcore_testct:
1831 // Result is either 0 or 1.
1832 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1833 KnownZero.getBitWidth() - 1);
1835 case Intrinsic::xcore_testwct:
1836 // Result is in the range 0 - 4.
1837 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1838 KnownZero.getBitWidth() - 3);
1846 //===----------------------------------------------------------------------===//
1847 // Addressing mode description hooks
1848 //===----------------------------------------------------------------------===//
1850 static inline bool isImmUs(int64_t val)
1852 return (val >= 0 && val <= 11);
1855 static inline bool isImmUs2(int64_t val)
1857 return (val%2 == 0 && isImmUs(val/2));
1860 static inline bool isImmUs4(int64_t val)
1862 return (val%4 == 0 && isImmUs(val/4));
1865 /// isLegalAddressingMode - Return true if the addressing mode represented
1866 /// by AM is legal for this target, for a load/store of the specified type.
1868 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1870 if (Ty->getTypeID() == Type::VoidTyID)
1871 return AM.Scale == 0 && isImmUs(AM.BaseOffs) && isImmUs4(AM.BaseOffs);
1873 const DataLayout *TD = TM.getDataLayout();
1874 unsigned Size = TD->getTypeAllocSize(Ty);
1876 return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1883 if (AM.Scale == 0) {
1884 return isImmUs(AM.BaseOffs);
1887 return AM.Scale == 1 && AM.BaseOffs == 0;
1891 if (AM.Scale == 0) {
1892 return isImmUs2(AM.BaseOffs);
1895 return AM.Scale == 2 && AM.BaseOffs == 0;
1898 if (AM.Scale == 0) {
1899 return isImmUs4(AM.BaseOffs);
1902 return AM.Scale == 4 && AM.BaseOffs == 0;
1906 //===----------------------------------------------------------------------===//
1907 // XCore Inline Assembly Support
1908 //===----------------------------------------------------------------------===//
1910 std::pair<unsigned, const TargetRegisterClass*>
1911 XCoreTargetLowering::
1912 getRegForInlineAsmConstraint(const std::string &Constraint,
1914 if (Constraint.size() == 1) {
1915 switch (Constraint[0]) {
1918 return std::make_pair(0U, &XCore::GRRegsRegClass);
1921 // Use the default implementation in TargetLowering to convert the register
1922 // constraint into a member of a register class.
1923 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);