1 //===-- XCoreISelLowering.cpp - XCore DAG Lowering Implementation ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the XCoreTargetLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "XCoreISelLowering.h"
16 #include "XCoreMachineFunctionInfo.h"
17 #include "XCoreSubtarget.h"
18 #include "XCoreTargetMachine.h"
19 #include "XCoreTargetObjectFile.h"
20 #include "llvm/CodeGen/CallingConvLower.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAGISel.h"
27 #include "llvm/CodeGen/ValueTypes.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GlobalAlias.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
42 #define DEBUG_TYPE "xcore-lower"
44 const char *XCoreTargetLowering::
45 getTargetNodeName(unsigned Opcode) const
49 case XCoreISD::BL : return "XCoreISD::BL";
50 case XCoreISD::PCRelativeWrapper : return "XCoreISD::PCRelativeWrapper";
51 case XCoreISD::DPRelativeWrapper : return "XCoreISD::DPRelativeWrapper";
52 case XCoreISD::CPRelativeWrapper : return "XCoreISD::CPRelativeWrapper";
53 case XCoreISD::LDWSP : return "XCoreISD::LDWSP";
54 case XCoreISD::STWSP : return "XCoreISD::STWSP";
55 case XCoreISD::RETSP : return "XCoreISD::RETSP";
56 case XCoreISD::LADD : return "XCoreISD::LADD";
57 case XCoreISD::LSUB : return "XCoreISD::LSUB";
58 case XCoreISD::LMUL : return "XCoreISD::LMUL";
59 case XCoreISD::MACCU : return "XCoreISD::MACCU";
60 case XCoreISD::MACCS : return "XCoreISD::MACCS";
61 case XCoreISD::CRC8 : return "XCoreISD::CRC8";
62 case XCoreISD::BR_JT : return "XCoreISD::BR_JT";
63 case XCoreISD::BR_JT32 : return "XCoreISD::BR_JT32";
64 case XCoreISD::FRAME_TO_ARGS_OFFSET : return "XCoreISD::FRAME_TO_ARGS_OFFSET";
65 case XCoreISD::EH_RETURN : return "XCoreISD::EH_RETURN";
66 case XCoreISD::MEMBARRIER : return "XCoreISD::MEMBARRIER";
67 default : return nullptr;
71 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
72 : TargetLowering(XTM, new XCoreTargetObjectFile()),
74 Subtarget(*XTM.getSubtargetImpl()) {
76 // Set up the register classes.
77 addRegisterClass(MVT::i32, &XCore::GRRegsRegClass);
79 // Compute derived properties from the register classes
80 computeRegisterProperties();
82 // Division is expensive
83 setIntDivIsCheap(false);
85 setStackPointerRegisterToSaveRestore(XCore::SP);
87 setSchedulingPreference(Sched::Source);
89 // Use i32 for setcc operations results (slt, sgt, ...).
90 setBooleanContents(ZeroOrOneBooleanContent);
91 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
93 // XCore does not have the NodeTypes below.
94 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
95 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
96 setOperationAction(ISD::ADDC, MVT::i32, Expand);
97 setOperationAction(ISD::ADDE, MVT::i32, Expand);
98 setOperationAction(ISD::SUBC, MVT::i32, Expand);
99 setOperationAction(ISD::SUBE, MVT::i32, Expand);
101 // Stop the combiner recombining select and set_cc
102 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
105 setOperationAction(ISD::ADD, MVT::i64, Custom);
106 setOperationAction(ISD::SUB, MVT::i64, Custom);
107 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
108 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
109 setOperationAction(ISD::MULHS, MVT::i32, Expand);
110 setOperationAction(ISD::MULHU, MVT::i32, Expand);
111 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
112 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
113 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
116 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
117 setOperationAction(ISD::ROTL , MVT::i32, Expand);
118 setOperationAction(ISD::ROTR , MVT::i32, Expand);
119 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
120 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
122 setOperationAction(ISD::TRAP, MVT::Other, Legal);
125 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
127 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
128 setOperationAction(ISD::BlockAddress, MVT::i32 , Custom);
130 // Conversion of i64 -> double produces constantpool nodes
131 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
134 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
135 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
136 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
138 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
139 setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
141 // Custom expand misaligned loads / stores.
142 setOperationAction(ISD::LOAD, MVT::i32, Custom);
143 setOperationAction(ISD::STORE, MVT::i32, Custom);
146 setOperationAction(ISD::VAEND, MVT::Other, Expand);
147 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
148 setOperationAction(ISD::VAARG, MVT::Other, Custom);
149 setOperationAction(ISD::VASTART, MVT::Other, Custom);
152 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
153 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
154 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
156 // Exception handling
157 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
158 setExceptionPointerRegister(XCore::R0);
159 setExceptionSelectorRegister(XCore::R1);
160 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
163 // We request a fence for ATOMIC_* instructions, to reduce them to Monotonic.
164 // As we are always Sequential Consistent, an ATOMIC_FENCE becomes a no OP.
165 setInsertFencesForAtomic(true);
166 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
167 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
168 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
170 // TRAMPOLINE is custom lowered.
171 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
172 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
174 // We want to custom lower some of our intrinsics.
175 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
177 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 4;
178 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize
179 = MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 2;
181 // We have target-specific dag combine patterns for the following nodes:
182 setTargetDAGCombine(ISD::STORE);
183 setTargetDAGCombine(ISD::ADD);
184 setTargetDAGCombine(ISD::INTRINSIC_VOID);
185 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
187 setMinFunctionAlignment(1);
188 setPrefFunctionAlignment(2);
191 bool XCoreTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
192 if (Val.getOpcode() != ISD::LOAD)
195 EVT VT1 = Val.getValueType();
196 if (!VT1.isSimple() || !VT1.isInteger() ||
197 !VT2.isSimple() || !VT2.isInteger())
200 switch (VT1.getSimpleVT().SimpleTy) {
209 SDValue XCoreTargetLowering::
210 LowerOperation(SDValue Op, SelectionDAG &DAG) const {
211 switch (Op.getOpcode())
213 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
214 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
215 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
216 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
217 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
218 case ISD::LOAD: return LowerLOAD(Op, DAG);
219 case ISD::STORE: return LowerSTORE(Op, DAG);
220 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
221 case ISD::VAARG: return LowerVAARG(Op, DAG);
222 case ISD::VASTART: return LowerVASTART(Op, DAG);
223 case ISD::SMUL_LOHI: return LowerSMUL_LOHI(Op, DAG);
224 case ISD::UMUL_LOHI: return LowerUMUL_LOHI(Op, DAG);
225 // FIXME: Remove these when LegalizeDAGTypes lands.
227 case ISD::SUB: return ExpandADDSUB(Op.getNode(), DAG);
228 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
229 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
230 case ISD::FRAME_TO_ARGS_OFFSET: return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
231 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
232 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
233 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
234 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
235 case ISD::ATOMIC_LOAD: return LowerATOMIC_LOAD(Op, DAG);
236 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op, DAG);
238 llvm_unreachable("unimplemented operand");
242 /// ReplaceNodeResults - Replace the results of node with an illegal result
243 /// type with new values built out of custom code.
244 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
245 SmallVectorImpl<SDValue>&Results,
246 SelectionDAG &DAG) const {
247 switch (N->getOpcode()) {
249 llvm_unreachable("Don't know how to custom expand this!");
252 Results.push_back(ExpandADDSUB(N, DAG));
257 //===----------------------------------------------------------------------===//
258 // Misc Lower Operation implementation
259 //===----------------------------------------------------------------------===//
261 SDValue XCoreTargetLowering::
262 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
265 SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i32, Op.getOperand(2),
266 Op.getOperand(3), Op.getOperand(4));
267 return DAG.getNode(ISD::SELECT, dl, MVT::i32, Cond, Op.getOperand(0),
271 SDValue XCoreTargetLowering::getGlobalAddressWrapper(SDValue GA,
272 const GlobalValue *GV,
273 SelectionDAG &DAG) const {
274 // FIXME there is no actual debug info here
277 if (GV->getType()->getElementType()->isFunctionTy())
278 return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
280 const auto *GVar = dyn_cast<GlobalVariable>(GV);
281 if ((GV->hasSection() && StringRef(GV->getSection()).startswith(".cp.")) ||
282 (GVar && GVar->isConstant() && GV->hasLocalLinkage()))
283 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
285 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
288 static bool IsSmallObject(const GlobalValue *GV, const XCoreTargetLowering &XTL) {
289 if (XTL.getTargetMachine().getCodeModel() == CodeModel::Small)
292 Type *ObjType = GV->getType()->getPointerElementType();
293 if (!ObjType->isSized())
296 unsigned ObjSize = XTL.getDataLayout()->getTypeAllocSize(ObjType);
297 return ObjSize < CodeModelLargeSize && ObjSize != 0;
300 SDValue XCoreTargetLowering::
301 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const
303 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
304 const GlobalValue *GV = GN->getGlobal();
306 int64_t Offset = GN->getOffset();
307 if (IsSmallObject(GV, *this)) {
308 // We can only fold positive offsets that are a multiple of the word size.
309 int64_t FoldedOffset = std::max(Offset & ~3, (int64_t)0);
310 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, FoldedOffset);
311 GA = getGlobalAddressWrapper(GA, GV, DAG);
312 // Handle the rest of the offset.
313 if (Offset != FoldedOffset) {
314 SDValue Remaining = DAG.getConstant(Offset - FoldedOffset, MVT::i32);
315 GA = DAG.getNode(ISD::ADD, DL, MVT::i32, GA, Remaining);
319 // Ideally we would not fold in offset with an index <= 11.
320 Type *Ty = Type::getInt8PtrTy(*DAG.getContext());
321 Constant *GA = ConstantExpr::getBitCast(const_cast<GlobalValue*>(GV), Ty);
322 Ty = Type::getInt32Ty(*DAG.getContext());
323 Constant *Idx = ConstantInt::get(Ty, Offset);
324 Constant *GAI = ConstantExpr::getGetElementPtr(GA, Idx);
325 SDValue CP = DAG.getConstantPool(GAI, MVT::i32);
326 return DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), CP,
327 MachinePointerInfo(), false, false, false, 0);
331 SDValue XCoreTargetLowering::
332 LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const
336 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
337 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy());
339 return DAG.getNode(XCoreISD::PCRelativeWrapper, DL, getPointerTy(), Result);
342 SDValue XCoreTargetLowering::
343 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
345 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
346 // FIXME there isn't really debug info here
348 EVT PtrVT = Op.getValueType();
350 if (CP->isMachineConstantPoolEntry()) {
351 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
352 CP->getAlignment(), CP->getOffset());
354 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
355 CP->getAlignment(), CP->getOffset());
357 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
360 unsigned XCoreTargetLowering::getJumpTableEncoding() const {
361 return MachineJumpTableInfo::EK_Inline;
364 SDValue XCoreTargetLowering::
365 LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
367 SDValue Chain = Op.getOperand(0);
368 SDValue Table = Op.getOperand(1);
369 SDValue Index = Op.getOperand(2);
371 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
372 unsigned JTI = JT->getIndex();
373 MachineFunction &MF = DAG.getMachineFunction();
374 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
375 SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
377 unsigned NumEntries = MJTI->getJumpTables()[JTI].MBBs.size();
378 if (NumEntries <= 32) {
379 return DAG.getNode(XCoreISD::BR_JT, dl, MVT::Other, Chain, TargetJT, Index);
381 assert((NumEntries >> 31) == 0);
382 SDValue ScaledIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
383 DAG.getConstant(1, MVT::i32));
384 return DAG.getNode(XCoreISD::BR_JT32, dl, MVT::Other, Chain, TargetJT,
388 SDValue XCoreTargetLowering::
389 lowerLoadWordFromAlignedBasePlusOffset(SDLoc DL, SDValue Chain, SDValue Base,
390 int64_t Offset, SelectionDAG &DAG) const
392 if ((Offset & 0x3) == 0) {
393 return DAG.getLoad(getPointerTy(), DL, Chain, Base, MachinePointerInfo(),
394 false, false, false, 0);
396 // Lower to pair of consecutive word aligned loads plus some bit shifting.
397 int32_t HighOffset = RoundUpToAlignment(Offset, 4);
398 int32_t LowOffset = HighOffset - 4;
399 SDValue LowAddr, HighAddr;
400 if (GlobalAddressSDNode *GASD =
401 dyn_cast<GlobalAddressSDNode>(Base.getNode())) {
402 LowAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
404 HighAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
407 LowAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
408 DAG.getConstant(LowOffset, MVT::i32));
409 HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
410 DAG.getConstant(HighOffset, MVT::i32));
412 SDValue LowShift = DAG.getConstant((Offset - LowOffset) * 8, MVT::i32);
413 SDValue HighShift = DAG.getConstant((HighOffset - Offset) * 8, MVT::i32);
415 SDValue Low = DAG.getLoad(getPointerTy(), DL, Chain,
416 LowAddr, MachinePointerInfo(),
417 false, false, false, 0);
418 SDValue High = DAG.getLoad(getPointerTy(), DL, Chain,
419 HighAddr, MachinePointerInfo(),
420 false, false, false, 0);
421 SDValue LowShifted = DAG.getNode(ISD::SRL, DL, MVT::i32, Low, LowShift);
422 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High, HighShift);
423 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, LowShifted, HighShifted);
424 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
426 SDValue Ops[] = { Result, Chain };
427 return DAG.getMergeValues(Ops, DL);
430 static bool isWordAligned(SDValue Value, SelectionDAG &DAG)
432 APInt KnownZero, KnownOne;
433 DAG.computeKnownBits(Value, KnownZero, KnownOne);
434 return KnownZero.countTrailingOnes() >= 2;
437 SDValue XCoreTargetLowering::
438 LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
439 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
440 LoadSDNode *LD = cast<LoadSDNode>(Op);
441 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
442 "Unexpected extension type");
443 assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
444 if (allowsUnalignedMemoryAccesses(LD->getMemoryVT()))
447 unsigned ABIAlignment = getDataLayout()->
448 getABITypeAlignment(LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
449 // Leave aligned load alone.
450 if (LD->getAlignment() >= ABIAlignment)
453 SDValue Chain = LD->getChain();
454 SDValue BasePtr = LD->getBasePtr();
457 if (!LD->isVolatile()) {
458 const GlobalValue *GV;
460 if (DAG.isBaseWithConstantOffset(BasePtr) &&
461 isWordAligned(BasePtr->getOperand(0), DAG)) {
462 SDValue NewBasePtr = BasePtr->getOperand(0);
463 Offset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
464 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
467 if (TLI.isGAPlusOffset(BasePtr.getNode(), GV, Offset) &&
468 MinAlign(GV->getAlignment(), 4) == 4) {
469 SDValue NewBasePtr = DAG.getGlobalAddress(GV, DL,
470 BasePtr->getValueType(0));
471 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
476 if (LD->getAlignment() == 2) {
477 SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, DL, MVT::i32, Chain,
478 BasePtr, LD->getPointerInfo(), MVT::i16,
479 LD->isVolatile(), LD->isNonTemporal(), 2);
480 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
481 DAG.getConstant(2, MVT::i32));
482 SDValue High = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
484 LD->getPointerInfo().getWithOffset(2),
485 MVT::i16, LD->isVolatile(),
486 LD->isNonTemporal(), 2);
487 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High,
488 DAG.getConstant(16, MVT::i32));
489 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Low, HighShifted);
490 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
492 SDValue Ops[] = { Result, Chain };
493 return DAG.getMergeValues(Ops, DL);
496 // Lower to a call to __misaligned_load(BasePtr).
497 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
498 TargetLowering::ArgListTy Args;
499 TargetLowering::ArgListEntry Entry;
502 Entry.Node = BasePtr;
503 Args.push_back(Entry);
505 TargetLowering::CallLoweringInfo CLI(DAG);
506 CLI.setDebugLoc(DL).setChain(Chain)
507 .setCallee(CallingConv::C, IntPtrTy,
508 DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
511 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
512 SDValue Ops[] = { CallResult.first, CallResult.second };
513 return DAG.getMergeValues(Ops, DL);
516 SDValue XCoreTargetLowering::
517 LowerSTORE(SDValue Op, SelectionDAG &DAG) const
519 StoreSDNode *ST = cast<StoreSDNode>(Op);
520 assert(!ST->isTruncatingStore() && "Unexpected store type");
521 assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
522 if (allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
525 unsigned ABIAlignment = getDataLayout()->
526 getABITypeAlignment(ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
527 // Leave aligned store alone.
528 if (ST->getAlignment() >= ABIAlignment) {
531 SDValue Chain = ST->getChain();
532 SDValue BasePtr = ST->getBasePtr();
533 SDValue Value = ST->getValue();
536 if (ST->getAlignment() == 2) {
538 SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
539 DAG.getConstant(16, MVT::i32));
540 SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
541 ST->getPointerInfo(), MVT::i16,
542 ST->isVolatile(), ST->isNonTemporal(),
544 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
545 DAG.getConstant(2, MVT::i32));
546 SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
547 ST->getPointerInfo().getWithOffset(2),
548 MVT::i16, ST->isVolatile(),
549 ST->isNonTemporal(), 2);
550 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
553 // Lower to a call to __misaligned_store(BasePtr, Value).
554 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
555 TargetLowering::ArgListTy Args;
556 TargetLowering::ArgListEntry Entry;
559 Entry.Node = BasePtr;
560 Args.push_back(Entry);
563 Args.push_back(Entry);
565 TargetLowering::CallLoweringInfo CLI(DAG);
566 CLI.setDebugLoc(dl).setChain(Chain)
567 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
568 DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
571 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
572 return CallResult.second;
575 SDValue XCoreTargetLowering::
576 LowerSMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
578 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::SMUL_LOHI &&
579 "Unexpected operand to lower!");
581 SDValue LHS = Op.getOperand(0);
582 SDValue RHS = Op.getOperand(1);
583 SDValue Zero = DAG.getConstant(0, MVT::i32);
584 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
585 DAG.getVTList(MVT::i32, MVT::i32), Zero, Zero,
587 SDValue Lo(Hi.getNode(), 1);
588 SDValue Ops[] = { Lo, Hi };
589 return DAG.getMergeValues(Ops, dl);
592 SDValue XCoreTargetLowering::
593 LowerUMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
595 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::UMUL_LOHI &&
596 "Unexpected operand to lower!");
598 SDValue LHS = Op.getOperand(0);
599 SDValue RHS = Op.getOperand(1);
600 SDValue Zero = DAG.getConstant(0, MVT::i32);
601 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
602 DAG.getVTList(MVT::i32, MVT::i32), LHS, RHS,
604 SDValue Lo(Hi.getNode(), 1);
605 SDValue Ops[] = { Lo, Hi };
606 return DAG.getMergeValues(Ops, dl);
609 /// isADDADDMUL - Return whether Op is in a form that is equivalent to
610 /// add(add(mul(x,y),a),b). If requireIntermediatesHaveOneUse is true then
611 /// each intermediate result in the calculation must also have a single use.
612 /// If the Op is in the correct form the constituent parts are written to Mul0,
613 /// Mul1, Addend0 and Addend1.
615 isADDADDMUL(SDValue Op, SDValue &Mul0, SDValue &Mul1, SDValue &Addend0,
616 SDValue &Addend1, bool requireIntermediatesHaveOneUse)
618 if (Op.getOpcode() != ISD::ADD)
620 SDValue N0 = Op.getOperand(0);
621 SDValue N1 = Op.getOperand(1);
624 if (N0.getOpcode() == ISD::ADD) {
627 } else if (N1.getOpcode() == ISD::ADD) {
633 if (requireIntermediatesHaveOneUse && !AddOp.hasOneUse())
635 if (OtherOp.getOpcode() == ISD::MUL) {
636 // add(add(a,b),mul(x,y))
637 if (requireIntermediatesHaveOneUse && !OtherOp.hasOneUse())
639 Mul0 = OtherOp.getOperand(0);
640 Mul1 = OtherOp.getOperand(1);
641 Addend0 = AddOp.getOperand(0);
642 Addend1 = AddOp.getOperand(1);
645 if (AddOp.getOperand(0).getOpcode() == ISD::MUL) {
646 // add(add(mul(x,y),a),b)
647 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(0).hasOneUse())
649 Mul0 = AddOp.getOperand(0).getOperand(0);
650 Mul1 = AddOp.getOperand(0).getOperand(1);
651 Addend0 = AddOp.getOperand(1);
655 if (AddOp.getOperand(1).getOpcode() == ISD::MUL) {
656 // add(add(a,mul(x,y)),b)
657 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(1).hasOneUse())
659 Mul0 = AddOp.getOperand(1).getOperand(0);
660 Mul1 = AddOp.getOperand(1).getOperand(1);
661 Addend0 = AddOp.getOperand(0);
668 SDValue XCoreTargetLowering::
669 TryExpandADDWithMul(SDNode *N, SelectionDAG &DAG) const
673 if (N->getOperand(0).getOpcode() == ISD::MUL) {
674 Mul = N->getOperand(0);
675 Other = N->getOperand(1);
676 } else if (N->getOperand(1).getOpcode() == ISD::MUL) {
677 Mul = N->getOperand(1);
678 Other = N->getOperand(0);
683 SDValue LL, RL, AddendL, AddendH;
684 LL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
685 Mul.getOperand(0), DAG.getConstant(0, MVT::i32));
686 RL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
687 Mul.getOperand(1), DAG.getConstant(0, MVT::i32));
688 AddendL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
689 Other, DAG.getConstant(0, MVT::i32));
690 AddendH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
691 Other, DAG.getConstant(1, MVT::i32));
692 APInt HighMask = APInt::getHighBitsSet(64, 32);
693 unsigned LHSSB = DAG.ComputeNumSignBits(Mul.getOperand(0));
694 unsigned RHSSB = DAG.ComputeNumSignBits(Mul.getOperand(1));
695 if (DAG.MaskedValueIsZero(Mul.getOperand(0), HighMask) &&
696 DAG.MaskedValueIsZero(Mul.getOperand(1), HighMask)) {
697 // The inputs are both zero-extended.
698 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
699 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
701 SDValue Lo(Hi.getNode(), 1);
702 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
704 if (LHSSB > 32 && RHSSB > 32) {
705 // The inputs are both sign-extended.
706 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
707 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
709 SDValue Lo(Hi.getNode(), 1);
710 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
713 LH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
714 Mul.getOperand(0), DAG.getConstant(1, MVT::i32));
715 RH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
716 Mul.getOperand(1), DAG.getConstant(1, MVT::i32));
717 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
718 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
720 SDValue Lo(Hi.getNode(), 1);
721 RH = DAG.getNode(ISD::MUL, dl, MVT::i32, LL, RH);
722 LH = DAG.getNode(ISD::MUL, dl, MVT::i32, LH, RL);
723 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, RH);
724 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, LH);
725 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
728 SDValue XCoreTargetLowering::
729 ExpandADDSUB(SDNode *N, SelectionDAG &DAG) const
731 assert(N->getValueType(0) == MVT::i64 &&
732 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
733 "Unknown operand to lower!");
735 if (N->getOpcode() == ISD::ADD) {
736 SDValue Result = TryExpandADDWithMul(N, DAG);
737 if (Result.getNode())
743 // Extract components
744 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
745 N->getOperand(0), DAG.getConstant(0, MVT::i32));
746 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
747 N->getOperand(0), DAG.getConstant(1, MVT::i32));
748 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
749 N->getOperand(1), DAG.getConstant(0, MVT::i32));
750 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
751 N->getOperand(1), DAG.getConstant(1, MVT::i32));
754 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
756 SDValue Zero = DAG.getConstant(0, MVT::i32);
757 SDValue Lo = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
759 SDValue Carry(Lo.getNode(), 1);
761 SDValue Hi = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
763 SDValue Ignored(Hi.getNode(), 1);
765 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
768 SDValue XCoreTargetLowering::
769 LowerVAARG(SDValue Op, SelectionDAG &DAG) const
771 // Whist llvm does not support aggregate varargs we can ignore
772 // the possibility of the ValueType being an implicit byVal vararg.
773 SDNode *Node = Op.getNode();
774 EVT VT = Node->getValueType(0); // not an aggregate
775 SDValue InChain = Node->getOperand(0);
776 SDValue VAListPtr = Node->getOperand(1);
777 EVT PtrVT = VAListPtr.getValueType();
778 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
780 SDValue VAList = DAG.getLoad(PtrVT, dl, InChain,
781 VAListPtr, MachinePointerInfo(SV),
782 false, false, false, 0);
783 // Increment the pointer, VAList, to the next vararg
784 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAList,
785 DAG.getIntPtrConstant(VT.getSizeInBits() / 8));
786 // Store the incremented VAList to the legalized pointer
787 InChain = DAG.getStore(VAList.getValue(1), dl, nextPtr, VAListPtr,
788 MachinePointerInfo(SV), false, false, 0);
789 // Load the actual argument out of the pointer VAList
790 return DAG.getLoad(VT, dl, InChain, VAList, MachinePointerInfo(),
791 false, false, false, 0);
794 SDValue XCoreTargetLowering::
795 LowerVASTART(SDValue Op, SelectionDAG &DAG) const
798 // vastart stores the address of the VarArgsFrameIndex slot into the
799 // memory location argument
800 MachineFunction &MF = DAG.getMachineFunction();
801 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
802 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
803 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1),
804 MachinePointerInfo(), false, false, 0);
807 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op,
808 SelectionDAG &DAG) const {
809 // This nodes represent llvm.frameaddress on the DAG.
810 // It takes one operand, the index of the frame address to return.
811 // An index of zero corresponds to the current function's frame address.
812 // An index of one to the parent's frame address, and so on.
813 // Depths > 0 not supported yet!
814 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
817 MachineFunction &MF = DAG.getMachineFunction();
818 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
819 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op),
820 RegInfo->getFrameRegister(MF), MVT::i32);
823 SDValue XCoreTargetLowering::
824 LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const {
825 // This nodes represent llvm.returnaddress on the DAG.
826 // It takes one operand, the index of the return address to return.
827 // An index of zero corresponds to the current function's return address.
828 // An index of one to the parent's return address, and so on.
829 // Depths > 0 not supported yet!
830 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
833 MachineFunction &MF = DAG.getMachineFunction();
834 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
835 int FI = XFI->createLRSpillSlot(MF);
836 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
837 return DAG.getLoad(getPointerTy(), SDLoc(Op), DAG.getEntryNode(), FIN,
838 MachinePointerInfo::getFixedStack(FI), false, false,
842 SDValue XCoreTargetLowering::
843 LowerFRAME_TO_ARGS_OFFSET(SDValue Op, SelectionDAG &DAG) const {
844 // This node represents offset from frame pointer to first on-stack argument.
845 // This is needed for correct stack adjustment during unwind.
846 // However, we don't know the offset until after the frame has be finalised.
847 // This is done during the XCoreFTAOElim pass.
848 return DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, SDLoc(Op), MVT::i32);
851 SDValue XCoreTargetLowering::
852 LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
853 // OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER)
854 // This node represents 'eh_return' gcc dwarf builtin, which is used to
855 // return from exception. The general meaning is: adjust stack by OFFSET and
856 // pass execution to HANDLER.
857 MachineFunction &MF = DAG.getMachineFunction();
858 SDValue Chain = Op.getOperand(0);
859 SDValue Offset = Op.getOperand(1);
860 SDValue Handler = Op.getOperand(2);
863 // Absolute SP = (FP + FrameToArgs) + Offset
864 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
865 SDValue Stack = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
866 RegInfo->getFrameRegister(MF), MVT::i32);
867 SDValue FrameToArgs = DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, dl,
869 Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, FrameToArgs);
870 Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, Offset);
872 // R0=ExceptionPointerRegister R1=ExceptionSelectorRegister
873 // which leaves 2 caller saved registers, R2 & R3 for us to use.
874 unsigned StackReg = XCore::R2;
875 unsigned HandlerReg = XCore::R3;
877 SDValue OutChains[] = {
878 DAG.getCopyToReg(Chain, dl, StackReg, Stack),
879 DAG.getCopyToReg(Chain, dl, HandlerReg, Handler)
882 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
884 return DAG.getNode(XCoreISD::EH_RETURN, dl, MVT::Other, Chain,
885 DAG.getRegister(StackReg, MVT::i32),
886 DAG.getRegister(HandlerReg, MVT::i32));
890 SDValue XCoreTargetLowering::
891 LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
892 return Op.getOperand(0);
895 SDValue XCoreTargetLowering::
896 LowerINIT_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
897 SDValue Chain = Op.getOperand(0);
898 SDValue Trmp = Op.getOperand(1); // trampoline
899 SDValue FPtr = Op.getOperand(2); // nested function
900 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
902 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
905 // LDAPF_u10 r11, nest
906 // LDW_2rus r11, r11[0]
907 // STWSP_ru6 r11, sp[0]
908 // LDAPF_u10 r11, fptr
909 // LDW_2rus r11, r11[0]
915 SDValue OutChains[5];
920 OutChains[0] = DAG.getStore(Chain, dl, DAG.getConstant(0x0a3cd805, MVT::i32),
921 Addr, MachinePointerInfo(TrmpAddr), false, false,
924 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
925 DAG.getConstant(4, MVT::i32));
926 OutChains[1] = DAG.getStore(Chain, dl, DAG.getConstant(0xd80456c0, MVT::i32),
927 Addr, MachinePointerInfo(TrmpAddr, 4), false,
930 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
931 DAG.getConstant(8, MVT::i32));
932 OutChains[2] = DAG.getStore(Chain, dl, DAG.getConstant(0x27fb0a3c, MVT::i32),
933 Addr, MachinePointerInfo(TrmpAddr, 8), false,
936 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
937 DAG.getConstant(12, MVT::i32));
938 OutChains[3] = DAG.getStore(Chain, dl, Nest, Addr,
939 MachinePointerInfo(TrmpAddr, 12), false, false,
942 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
943 DAG.getConstant(16, MVT::i32));
944 OutChains[4] = DAG.getStore(Chain, dl, FPtr, Addr,
945 MachinePointerInfo(TrmpAddr, 16), false, false,
948 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
951 SDValue XCoreTargetLowering::
952 LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
954 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
956 case Intrinsic::xcore_crc8:
957 EVT VT = Op.getValueType();
959 DAG.getNode(XCoreISD::CRC8, DL, DAG.getVTList(VT, VT),
960 Op.getOperand(1), Op.getOperand(2) , Op.getOperand(3));
961 SDValue Crc(Data.getNode(), 1);
962 SDValue Results[] = { Crc, Data };
963 return DAG.getMergeValues(Results, DL);
968 SDValue XCoreTargetLowering::
969 LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG) const {
971 return DAG.getNode(XCoreISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
974 SDValue XCoreTargetLowering::
975 LowerATOMIC_LOAD(SDValue Op, SelectionDAG &DAG) const {
976 AtomicSDNode *N = cast<AtomicSDNode>(Op);
977 assert(N->getOpcode() == ISD::ATOMIC_LOAD && "Bad Atomic OP");
978 assert(N->getOrdering() <= Monotonic &&
979 "setInsertFencesForAtomic(true) and yet greater than Monotonic");
980 if (N->getMemoryVT() == MVT::i32) {
981 if (N->getAlignment() < 4)
982 report_fatal_error("atomic load must be aligned");
983 return DAG.getLoad(getPointerTy(), SDLoc(Op), N->getChain(),
984 N->getBasePtr(), N->getPointerInfo(),
985 N->isVolatile(), N->isNonTemporal(),
986 N->isInvariant(), N->getAlignment(),
987 N->getTBAAInfo(), N->getRanges());
989 if (N->getMemoryVT() == MVT::i16) {
990 if (N->getAlignment() < 2)
991 report_fatal_error("atomic load must be aligned");
992 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
993 N->getBasePtr(), N->getPointerInfo(), MVT::i16,
994 N->isVolatile(), N->isNonTemporal(),
995 N->getAlignment(), N->getTBAAInfo());
997 if (N->getMemoryVT() == MVT::i8)
998 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
999 N->getBasePtr(), N->getPointerInfo(), MVT::i8,
1000 N->isVolatile(), N->isNonTemporal(),
1001 N->getAlignment(), N->getTBAAInfo());
1005 SDValue XCoreTargetLowering::
1006 LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) const {
1007 AtomicSDNode *N = cast<AtomicSDNode>(Op);
1008 assert(N->getOpcode() == ISD::ATOMIC_STORE && "Bad Atomic OP");
1009 assert(N->getOrdering() <= Monotonic &&
1010 "setInsertFencesForAtomic(true) and yet greater than Monotonic");
1011 if (N->getMemoryVT() == MVT::i32) {
1012 if (N->getAlignment() < 4)
1013 report_fatal_error("atomic store must be aligned");
1014 return DAG.getStore(N->getChain(), SDLoc(Op), N->getVal(),
1015 N->getBasePtr(), N->getPointerInfo(),
1016 N->isVolatile(), N->isNonTemporal(),
1017 N->getAlignment(), N->getTBAAInfo());
1019 if (N->getMemoryVT() == MVT::i16) {
1020 if (N->getAlignment() < 2)
1021 report_fatal_error("atomic store must be aligned");
1022 return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1023 N->getBasePtr(), N->getPointerInfo(), MVT::i16,
1024 N->isVolatile(), N->isNonTemporal(),
1025 N->getAlignment(), N->getTBAAInfo());
1027 if (N->getMemoryVT() == MVT::i8)
1028 return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1029 N->getBasePtr(), N->getPointerInfo(), MVT::i8,
1030 N->isVolatile(), N->isNonTemporal(),
1031 N->getAlignment(), N->getTBAAInfo());
1035 //===----------------------------------------------------------------------===//
1036 // Calling Convention Implementation
1037 //===----------------------------------------------------------------------===//
1039 #include "XCoreGenCallingConv.inc"
1041 //===----------------------------------------------------------------------===//
1042 // Call Calling Convention Implementation
1043 //===----------------------------------------------------------------------===//
1045 /// XCore call implementation
1047 XCoreTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1048 SmallVectorImpl<SDValue> &InVals) const {
1049 SelectionDAG &DAG = CLI.DAG;
1051 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1052 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1053 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1054 SDValue Chain = CLI.Chain;
1055 SDValue Callee = CLI.Callee;
1056 bool &isTailCall = CLI.IsTailCall;
1057 CallingConv::ID CallConv = CLI.CallConv;
1058 bool isVarArg = CLI.IsVarArg;
1060 // XCore target does not yet support tail call optimization.
1063 // For now, only CallingConv::C implemented
1067 llvm_unreachable("Unsupported calling convention");
1068 case CallingConv::Fast:
1069 case CallingConv::C:
1070 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
1071 Outs, OutVals, Ins, dl, DAG, InVals);
1075 /// LowerCallResult - Lower the result values of a call into the
1076 /// appropriate copies out of appropriate physical registers / memory locations.
1078 LowerCallResult(SDValue Chain, SDValue InFlag,
1079 const SmallVectorImpl<CCValAssign> &RVLocs,
1080 SDLoc dl, SelectionDAG &DAG,
1081 SmallVectorImpl<SDValue> &InVals) {
1082 SmallVector<std::pair<int, unsigned>, 4> ResultMemLocs;
1083 // Copy results out of physical registers.
1084 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1085 const CCValAssign &VA = RVLocs[i];
1086 if (VA.isRegLoc()) {
1087 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getValVT(),
1088 InFlag).getValue(1);
1089 InFlag = Chain.getValue(2);
1090 InVals.push_back(Chain.getValue(0));
1092 assert(VA.isMemLoc());
1093 ResultMemLocs.push_back(std::make_pair(VA.getLocMemOffset(),
1095 // Reserve space for this result.
1096 InVals.push_back(SDValue());
1100 // Copy results out of memory.
1101 SmallVector<SDValue, 4> MemOpChains;
1102 for (unsigned i = 0, e = ResultMemLocs.size(); i != e; ++i) {
1103 int offset = ResultMemLocs[i].first;
1104 unsigned index = ResultMemLocs[i].second;
1105 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
1106 SDValue Ops[] = { Chain, DAG.getConstant(offset / 4, MVT::i32) };
1107 SDValue load = DAG.getNode(XCoreISD::LDWSP, dl, VTs, Ops);
1108 InVals[index] = load;
1109 MemOpChains.push_back(load.getValue(1));
1112 // Transform all loads nodes into one single node because
1113 // all load nodes are independent of each other.
1114 if (!MemOpChains.empty())
1115 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1120 /// LowerCCCCallTo - functions arguments are copied from virtual
1121 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
1122 /// CALLSEQ_END are emitted.
1123 /// TODO: isTailCall, sret.
1125 XCoreTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
1126 CallingConv::ID CallConv, bool isVarArg,
1128 const SmallVectorImpl<ISD::OutputArg> &Outs,
1129 const SmallVectorImpl<SDValue> &OutVals,
1130 const SmallVectorImpl<ISD::InputArg> &Ins,
1131 SDLoc dl, SelectionDAG &DAG,
1132 SmallVectorImpl<SDValue> &InVals) const {
1134 // Analyze operands of the call, assigning locations to each operand.
1135 SmallVector<CCValAssign, 16> ArgLocs;
1136 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1137 getTargetMachine(), ArgLocs, *DAG.getContext());
1139 // The ABI dictates there should be one stack slot available to the callee
1140 // on function entry (for saving lr).
1141 CCInfo.AllocateStack(4, 4);
1143 CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
1145 SmallVector<CCValAssign, 16> RVLocs;
1146 // Analyze return values to determine the number of bytes of stack required.
1147 CCState RetCCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1148 getTargetMachine(), RVLocs, *DAG.getContext());
1149 RetCCInfo.AllocateStack(CCInfo.getNextStackOffset(), 4);
1150 RetCCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
1152 // Get a count of how many bytes are to be pushed on the stack.
1153 unsigned NumBytes = RetCCInfo.getNextStackOffset();
1155 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
1156 getPointerTy(), true), dl);
1158 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
1159 SmallVector<SDValue, 12> MemOpChains;
1161 // Walk the register/memloc assignments, inserting copies/loads.
1162 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1163 CCValAssign &VA = ArgLocs[i];
1164 SDValue Arg = OutVals[i];
1166 // Promote the value if needed.
1167 switch (VA.getLocInfo()) {
1168 default: llvm_unreachable("Unknown loc info!");
1169 case CCValAssign::Full: break;
1170 case CCValAssign::SExt:
1171 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1173 case CCValAssign::ZExt:
1174 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1176 case CCValAssign::AExt:
1177 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1181 // Arguments that can be passed on register must be kept at
1182 // RegsToPass vector
1183 if (VA.isRegLoc()) {
1184 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1186 assert(VA.isMemLoc());
1188 int Offset = VA.getLocMemOffset();
1190 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
1192 DAG.getConstant(Offset/4, MVT::i32)));
1196 // Transform all store nodes into one single node because
1197 // all store nodes are independent of each other.
1198 if (!MemOpChains.empty())
1199 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1201 // Build a sequence of copy-to-reg nodes chained together with token
1202 // chain and flag operands which copy the outgoing args into registers.
1203 // The InFlag in necessary since all emitted instructions must be
1206 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1207 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1208 RegsToPass[i].second, InFlag);
1209 InFlag = Chain.getValue(1);
1212 // If the callee is a GlobalAddress node (quite common, every direct call is)
1213 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1214 // Likewise ExternalSymbol -> TargetExternalSymbol.
1215 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1216 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
1217 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
1218 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
1220 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
1221 // = Chain, Callee, Reg#1, Reg#2, ...
1223 // Returns a chain & a flag for retval copy to use.
1224 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1225 SmallVector<SDValue, 8> Ops;
1226 Ops.push_back(Chain);
1227 Ops.push_back(Callee);
1229 // Add argument registers to the end of the list so that they are
1230 // known live into the call.
1231 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1232 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1233 RegsToPass[i].second.getValueType()));
1235 if (InFlag.getNode())
1236 Ops.push_back(InFlag);
1238 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, Ops);
1239 InFlag = Chain.getValue(1);
1241 // Create the CALLSEQ_END node.
1242 Chain = DAG.getCALLSEQ_END(Chain,
1243 DAG.getConstant(NumBytes, getPointerTy(), true),
1244 DAG.getConstant(0, getPointerTy(), true),
1246 InFlag = Chain.getValue(1);
1248 // Handle result values, copying them out of physregs into vregs that we
1250 return LowerCallResult(Chain, InFlag, RVLocs, dl, DAG, InVals);
1253 //===----------------------------------------------------------------------===//
1254 // Formal Arguments Calling Convention Implementation
1255 //===----------------------------------------------------------------------===//
1258 struct ArgDataPair { SDValue SDV; ISD::ArgFlagsTy Flags; };
1261 /// XCore formal arguments implementation
1263 XCoreTargetLowering::LowerFormalArguments(SDValue Chain,
1264 CallingConv::ID CallConv,
1266 const SmallVectorImpl<ISD::InputArg> &Ins,
1269 SmallVectorImpl<SDValue> &InVals)
1274 llvm_unreachable("Unsupported calling convention");
1275 case CallingConv::C:
1276 case CallingConv::Fast:
1277 return LowerCCCArguments(Chain, CallConv, isVarArg,
1278 Ins, dl, DAG, InVals);
1282 /// LowerCCCArguments - transform physical registers into
1283 /// virtual registers and generate load operations for
1284 /// arguments places on the stack.
1287 XCoreTargetLowering::LowerCCCArguments(SDValue Chain,
1288 CallingConv::ID CallConv,
1290 const SmallVectorImpl<ISD::InputArg>
1294 SmallVectorImpl<SDValue> &InVals) const {
1295 MachineFunction &MF = DAG.getMachineFunction();
1296 MachineFrameInfo *MFI = MF.getFrameInfo();
1297 MachineRegisterInfo &RegInfo = MF.getRegInfo();
1298 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1300 // Assign locations to all of the incoming arguments.
1301 SmallVector<CCValAssign, 16> ArgLocs;
1302 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1303 getTargetMachine(), ArgLocs, *DAG.getContext());
1305 CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
1307 unsigned StackSlotSize = XCoreFrameLowering::stackSlotSize();
1309 unsigned LRSaveSize = StackSlotSize;
1312 XFI->setReturnStackOffset(CCInfo.getNextStackOffset() + LRSaveSize);
1314 // All getCopyFromReg ops must precede any getMemcpys to prevent the
1315 // scheduler clobbering a register before it has been copied.
1317 // 1. CopyFromReg (and load) arg & vararg registers.
1318 // 2. Chain CopyFromReg nodes into a TokenFactor.
1319 // 3. Memcpy 'byVal' args & push final InVals.
1320 // 4. Chain mem ops nodes into a TokenFactor.
1321 SmallVector<SDValue, 4> CFRegNode;
1322 SmallVector<ArgDataPair, 4> ArgData;
1323 SmallVector<SDValue, 4> MemOps;
1325 // 1a. CopyFromReg (and load) arg registers.
1326 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1328 CCValAssign &VA = ArgLocs[i];
1331 if (VA.isRegLoc()) {
1332 // Arguments passed in registers
1333 EVT RegVT = VA.getLocVT();
1334 switch (RegVT.getSimpleVT().SimpleTy) {
1338 errs() << "LowerFormalArguments Unhandled argument type: "
1339 << RegVT.getSimpleVT().SimpleTy << "\n";
1341 llvm_unreachable(nullptr);
1344 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1345 RegInfo.addLiveIn(VA.getLocReg(), VReg);
1346 ArgIn = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
1347 CFRegNode.push_back(ArgIn.getValue(ArgIn->getNumValues() - 1));
1351 assert(VA.isMemLoc());
1352 // Load the argument to a virtual register
1353 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
1354 if (ObjSize > StackSlotSize) {
1355 errs() << "LowerFormalArguments Unhandled argument type: "
1356 << EVT(VA.getLocVT()).getEVTString()
1359 // Create the frame index object for this incoming parameter...
1360 int FI = MFI->CreateFixedObject(ObjSize,
1361 LRSaveSize + VA.getLocMemOffset(),
1364 // Create the SelectionDAG nodes corresponding to a load
1365 //from this parameter
1366 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1367 ArgIn = DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
1368 MachinePointerInfo::getFixedStack(FI),
1369 false, false, false, 0);
1371 const ArgDataPair ADP = { ArgIn, Ins[i].Flags };
1372 ArgData.push_back(ADP);
1375 // 1b. CopyFromReg vararg registers.
1377 // Argument registers
1378 static const MCPhysReg ArgRegs[] = {
1379 XCore::R0, XCore::R1, XCore::R2, XCore::R3
1381 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1382 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
1383 array_lengthof(ArgRegs));
1384 if (FirstVAReg < array_lengthof(ArgRegs)) {
1386 // Save remaining registers, storing higher register numbers at a higher
1388 for (int i = array_lengthof(ArgRegs) - 1; i >= (int)FirstVAReg; --i) {
1389 // Create a stack slot
1390 int FI = MFI->CreateFixedObject(4, offset, true);
1391 if (i == (int)FirstVAReg) {
1392 XFI->setVarArgsFrameIndex(FI);
1394 offset -= StackSlotSize;
1395 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1396 // Move argument from phys reg -> virt reg
1397 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1398 RegInfo.addLiveIn(ArgRegs[i], VReg);
1399 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1400 CFRegNode.push_back(Val.getValue(Val->getNumValues() - 1));
1401 // Move argument from virt reg -> stack
1402 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
1403 MachinePointerInfo(), false, false, 0);
1404 MemOps.push_back(Store);
1407 // This will point to the next argument passed via stack.
1408 XFI->setVarArgsFrameIndex(
1409 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset(),
1414 // 2. chain CopyFromReg nodes into a TokenFactor.
1415 if (!CFRegNode.empty())
1416 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, CFRegNode);
1418 // 3. Memcpy 'byVal' args & push final InVals.
1419 // Aggregates passed "byVal" need to be copied by the callee.
1420 // The callee will use a pointer to this copy, rather than the original
1422 for (SmallVectorImpl<ArgDataPair>::const_iterator ArgDI = ArgData.begin(),
1423 ArgDE = ArgData.end();
1424 ArgDI != ArgDE; ++ArgDI) {
1425 if (ArgDI->Flags.isByVal() && ArgDI->Flags.getByValSize()) {
1426 unsigned Size = ArgDI->Flags.getByValSize();
1427 unsigned Align = std::max(StackSlotSize, ArgDI->Flags.getByValAlign());
1428 // Create a new object on the stack and copy the pointee into it.
1429 int FI = MFI->CreateStackObject(Size, Align, false);
1430 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1431 InVals.push_back(FIN);
1432 MemOps.push_back(DAG.getMemcpy(Chain, dl, FIN, ArgDI->SDV,
1433 DAG.getConstant(Size, MVT::i32),
1434 Align, false, false,
1435 MachinePointerInfo(),
1436 MachinePointerInfo()));
1438 InVals.push_back(ArgDI->SDV);
1442 // 4, chain mem ops nodes into a TokenFactor.
1443 if (!MemOps.empty()) {
1444 MemOps.push_back(Chain);
1445 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
1451 //===----------------------------------------------------------------------===//
1452 // Return Value Calling Convention Implementation
1453 //===----------------------------------------------------------------------===//
1455 bool XCoreTargetLowering::
1456 CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF,
1458 const SmallVectorImpl<ISD::OutputArg> &Outs,
1459 LLVMContext &Context) const {
1460 SmallVector<CCValAssign, 16> RVLocs;
1461 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
1462 if (!CCInfo.CheckReturn(Outs, RetCC_XCore))
1464 if (CCInfo.getNextStackOffset() != 0 && isVarArg)
1470 XCoreTargetLowering::LowerReturn(SDValue Chain,
1471 CallingConv::ID CallConv, bool isVarArg,
1472 const SmallVectorImpl<ISD::OutputArg> &Outs,
1473 const SmallVectorImpl<SDValue> &OutVals,
1474 SDLoc dl, SelectionDAG &DAG) const {
1476 XCoreFunctionInfo *XFI =
1477 DAG.getMachineFunction().getInfo<XCoreFunctionInfo>();
1478 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1480 // CCValAssign - represent the assignment of
1481 // the return value to a location
1482 SmallVector<CCValAssign, 16> RVLocs;
1484 // CCState - Info about the registers and stack slot.
1485 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1486 getTargetMachine(), RVLocs, *DAG.getContext());
1488 // Analyze return values.
1490 CCInfo.AllocateStack(XFI->getReturnStackOffset(), 4);
1492 CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
1495 SmallVector<SDValue, 4> RetOps(1, Chain);
1497 // Return on XCore is always a "retsp 0"
1498 RetOps.push_back(DAG.getConstant(0, MVT::i32));
1500 SmallVector<SDValue, 4> MemOpChains;
1501 // Handle return values that must be copied to memory.
1502 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1503 CCValAssign &VA = RVLocs[i];
1506 assert(VA.isMemLoc());
1508 report_fatal_error("Can't return value from vararg function in memory");
1511 int Offset = VA.getLocMemOffset();
1512 unsigned ObjSize = VA.getLocVT().getSizeInBits() / 8;
1513 // Create the frame index object for the memory location.
1514 int FI = MFI->CreateFixedObject(ObjSize, Offset, false);
1516 // Create a SelectionDAG node corresponding to a store
1517 // to this memory location.
1518 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1519 MemOpChains.push_back(DAG.getStore(Chain, dl, OutVals[i], FIN,
1520 MachinePointerInfo::getFixedStack(FI), false, false,
1524 // Transform all store nodes into one single node because
1525 // all stores are independent of each other.
1526 if (!MemOpChains.empty())
1527 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1529 // Now handle return values copied to registers.
1530 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1531 CCValAssign &VA = RVLocs[i];
1534 // Copy the result values into the output registers.
1535 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
1537 // guarantee that all emitted copies are
1538 // stuck together, avoiding something bad
1539 Flag = Chain.getValue(1);
1540 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1543 RetOps[0] = Chain; // Update chain.
1545 // Add the flag if we have it.
1547 RetOps.push_back(Flag);
1549 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other, RetOps);
1552 //===----------------------------------------------------------------------===//
1553 // Other Lowering Code
1554 //===----------------------------------------------------------------------===//
1557 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1558 MachineBasicBlock *BB) const {
1559 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1560 DebugLoc dl = MI->getDebugLoc();
1561 assert((MI->getOpcode() == XCore::SELECT_CC) &&
1562 "Unexpected instr type to insert");
1564 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1565 // control-flow pattern. The incoming instruction knows the destination vreg
1566 // to set, the condition code register to branch on, the true/false values to
1567 // select between, and a branch opcode to use.
1568 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1569 MachineFunction::iterator It = BB;
1575 // cmpTY ccX, r1, r2
1577 // fallthrough --> copy0MBB
1578 MachineBasicBlock *thisMBB = BB;
1579 MachineFunction *F = BB->getParent();
1580 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1581 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1582 F->insert(It, copy0MBB);
1583 F->insert(It, sinkMBB);
1585 // Transfer the remainder of BB and its successor edges to sinkMBB.
1586 sinkMBB->splice(sinkMBB->begin(), BB,
1587 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1588 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1590 // Next, add the true and fallthrough blocks as its successors.
1591 BB->addSuccessor(copy0MBB);
1592 BB->addSuccessor(sinkMBB);
1594 BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1595 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1598 // %FalseValue = ...
1599 // # fallthrough to sinkMBB
1602 // Update machine-CFG edges
1603 BB->addSuccessor(sinkMBB);
1606 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1609 BuildMI(*BB, BB->begin(), dl,
1610 TII.get(XCore::PHI), MI->getOperand(0).getReg())
1611 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1612 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1614 MI->eraseFromParent(); // The pseudo instruction is gone now.
1618 //===----------------------------------------------------------------------===//
1619 // Target Optimization Hooks
1620 //===----------------------------------------------------------------------===//
1622 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1623 DAGCombinerInfo &DCI) const {
1624 SelectionDAG &DAG = DCI.DAG;
1626 switch (N->getOpcode()) {
1628 case ISD::INTRINSIC_VOID:
1629 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
1630 case Intrinsic::xcore_outt:
1631 case Intrinsic::xcore_outct:
1632 case Intrinsic::xcore_chkct: {
1633 SDValue OutVal = N->getOperand(3);
1634 // These instructions ignore the high bits.
1635 if (OutVal.hasOneUse()) {
1636 unsigned BitWidth = OutVal.getValueSizeInBits();
1637 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8);
1638 APInt KnownZero, KnownOne;
1639 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1640 !DCI.isBeforeLegalizeOps());
1641 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1642 if (TLO.ShrinkDemandedConstant(OutVal, DemandedMask) ||
1643 TLI.SimplifyDemandedBits(OutVal, DemandedMask, KnownZero, KnownOne,
1645 DCI.CommitTargetLoweringOpt(TLO);
1649 case Intrinsic::xcore_setpt: {
1650 SDValue Time = N->getOperand(3);
1651 // This instruction ignores the high bits.
1652 if (Time.hasOneUse()) {
1653 unsigned BitWidth = Time.getValueSizeInBits();
1654 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
1655 APInt KnownZero, KnownOne;
1656 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1657 !DCI.isBeforeLegalizeOps());
1658 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1659 if (TLO.ShrinkDemandedConstant(Time, DemandedMask) ||
1660 TLI.SimplifyDemandedBits(Time, DemandedMask, KnownZero, KnownOne,
1662 DCI.CommitTargetLoweringOpt(TLO);
1668 case XCoreISD::LADD: {
1669 SDValue N0 = N->getOperand(0);
1670 SDValue N1 = N->getOperand(1);
1671 SDValue N2 = N->getOperand(2);
1672 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1673 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1674 EVT VT = N0.getValueType();
1676 // canonicalize constant to RHS
1678 return DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N1, N0, N2);
1680 // fold (ladd 0, 0, x) -> 0, x & 1
1681 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1682 SDValue Carry = DAG.getConstant(0, VT);
1683 SDValue Result = DAG.getNode(ISD::AND, dl, VT, N2,
1684 DAG.getConstant(1, VT));
1685 SDValue Ops[] = { Result, Carry };
1686 return DAG.getMergeValues(Ops, dl);
1689 // fold (ladd x, 0, y) -> 0, add x, y iff carry is unused and y has only the
1691 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1692 APInt KnownZero, KnownOne;
1693 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1694 VT.getSizeInBits() - 1);
1695 DAG.computeKnownBits(N2, KnownZero, KnownOne);
1696 if ((KnownZero & Mask) == Mask) {
1697 SDValue Carry = DAG.getConstant(0, VT);
1698 SDValue Result = DAG.getNode(ISD::ADD, dl, VT, N0, N2);
1699 SDValue Ops[] = { Result, Carry };
1700 return DAG.getMergeValues(Ops, dl);
1705 case XCoreISD::LSUB: {
1706 SDValue N0 = N->getOperand(0);
1707 SDValue N1 = N->getOperand(1);
1708 SDValue N2 = N->getOperand(2);
1709 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1710 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1711 EVT VT = N0.getValueType();
1713 // fold (lsub 0, 0, x) -> x, -x iff x has only the low bit set
1714 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1715 APInt KnownZero, KnownOne;
1716 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1717 VT.getSizeInBits() - 1);
1718 DAG.computeKnownBits(N2, KnownZero, KnownOne);
1719 if ((KnownZero & Mask) == Mask) {
1720 SDValue Borrow = N2;
1721 SDValue Result = DAG.getNode(ISD::SUB, dl, VT,
1722 DAG.getConstant(0, VT), N2);
1723 SDValue Ops[] = { Result, Borrow };
1724 return DAG.getMergeValues(Ops, dl);
1728 // fold (lsub x, 0, y) -> 0, sub x, y iff borrow is unused and y has only the
1730 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1731 APInt KnownZero, KnownOne;
1732 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1733 VT.getSizeInBits() - 1);
1734 DAG.computeKnownBits(N2, KnownZero, KnownOne);
1735 if ((KnownZero & Mask) == Mask) {
1736 SDValue Borrow = DAG.getConstant(0, VT);
1737 SDValue Result = DAG.getNode(ISD::SUB, dl, VT, N0, N2);
1738 SDValue Ops[] = { Result, Borrow };
1739 return DAG.getMergeValues(Ops, dl);
1744 case XCoreISD::LMUL: {
1745 SDValue N0 = N->getOperand(0);
1746 SDValue N1 = N->getOperand(1);
1747 SDValue N2 = N->getOperand(2);
1748 SDValue N3 = N->getOperand(3);
1749 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1750 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1751 EVT VT = N0.getValueType();
1752 // Canonicalize multiplicative constant to RHS. If both multiplicative
1753 // operands are constant canonicalize smallest to RHS.
1754 if ((N0C && !N1C) ||
1755 (N0C && N1C && N0C->getZExtValue() < N1C->getZExtValue()))
1756 return DAG.getNode(XCoreISD::LMUL, dl, DAG.getVTList(VT, VT),
1760 if (N1C && N1C->isNullValue()) {
1761 // If the high result is unused fold to add(a, b)
1762 if (N->hasNUsesOfValue(0, 0)) {
1763 SDValue Lo = DAG.getNode(ISD::ADD, dl, VT, N2, N3);
1764 SDValue Ops[] = { Lo, Lo };
1765 return DAG.getMergeValues(Ops, dl);
1767 // Otherwise fold to ladd(a, b, 0)
1769 DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N2, N3, N1);
1770 SDValue Carry(Result.getNode(), 1);
1771 SDValue Ops[] = { Carry, Result };
1772 return DAG.getMergeValues(Ops, dl);
1777 // Fold 32 bit expressions such as add(add(mul(x,y),a),b) ->
1778 // lmul(x, y, a, b). The high result of lmul will be ignored.
1779 // This is only profitable if the intermediate results are unused
1781 SDValue Mul0, Mul1, Addend0, Addend1;
1782 if (N->getValueType(0) == MVT::i32 &&
1783 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, true)) {
1784 SDValue Ignored = DAG.getNode(XCoreISD::LMUL, dl,
1785 DAG.getVTList(MVT::i32, MVT::i32), Mul0,
1786 Mul1, Addend0, Addend1);
1787 SDValue Result(Ignored.getNode(), 1);
1790 APInt HighMask = APInt::getHighBitsSet(64, 32);
1791 // Fold 64 bit expression such as add(add(mul(x,y),a),b) ->
1792 // lmul(x, y, a, b) if all operands are zero-extended. We do this
1793 // before type legalization as it is messy to match the operands after
1795 if (N->getValueType(0) == MVT::i64 &&
1796 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, false) &&
1797 DAG.MaskedValueIsZero(Mul0, HighMask) &&
1798 DAG.MaskedValueIsZero(Mul1, HighMask) &&
1799 DAG.MaskedValueIsZero(Addend0, HighMask) &&
1800 DAG.MaskedValueIsZero(Addend1, HighMask)) {
1801 SDValue Mul0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1802 Mul0, DAG.getConstant(0, MVT::i32));
1803 SDValue Mul1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1804 Mul1, DAG.getConstant(0, MVT::i32));
1805 SDValue Addend0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1806 Addend0, DAG.getConstant(0, MVT::i32));
1807 SDValue Addend1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1808 Addend1, DAG.getConstant(0, MVT::i32));
1809 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
1810 DAG.getVTList(MVT::i32, MVT::i32), Mul0L, Mul1L,
1811 Addend0L, Addend1L);
1812 SDValue Lo(Hi.getNode(), 1);
1813 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
1818 // Replace unaligned store of unaligned load with memmove.
1819 StoreSDNode *ST = cast<StoreSDNode>(N);
1820 if (!DCI.isBeforeLegalize() ||
1821 allowsUnalignedMemoryAccesses(ST->getMemoryVT()) ||
1822 ST->isVolatile() || ST->isIndexed()) {
1825 SDValue Chain = ST->getChain();
1827 unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1828 if (StoreBits % 8) {
1831 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(
1832 ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1833 unsigned Alignment = ST->getAlignment();
1834 if (Alignment >= ABIAlignment) {
1838 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1839 if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1840 LD->getAlignment() == Alignment &&
1841 !LD->isVolatile() && !LD->isIndexed() &&
1842 Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1843 return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1845 DAG.getConstant(StoreBits/8, MVT::i32),
1846 Alignment, false, ST->getPointerInfo(),
1847 LD->getPointerInfo());
1856 void XCoreTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
1859 const SelectionDAG &DAG,
1860 unsigned Depth) const {
1861 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
1862 switch (Op.getOpcode()) {
1864 case XCoreISD::LADD:
1865 case XCoreISD::LSUB:
1866 if (Op.getResNo() == 1) {
1867 // Top bits of carry / borrow are clear.
1868 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1869 KnownZero.getBitWidth() - 1);
1872 case ISD::INTRINSIC_W_CHAIN:
1874 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1876 case Intrinsic::xcore_getts:
1877 // High bits are known to be zero.
1878 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1879 KnownZero.getBitWidth() - 16);
1881 case Intrinsic::xcore_int:
1882 case Intrinsic::xcore_inct:
1883 // High bits are known to be zero.
1884 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1885 KnownZero.getBitWidth() - 8);
1887 case Intrinsic::xcore_testct:
1888 // Result is either 0 or 1.
1889 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1890 KnownZero.getBitWidth() - 1);
1892 case Intrinsic::xcore_testwct:
1893 // Result is in the range 0 - 4.
1894 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1895 KnownZero.getBitWidth() - 3);
1903 //===----------------------------------------------------------------------===//
1904 // Addressing mode description hooks
1905 //===----------------------------------------------------------------------===//
1907 static inline bool isImmUs(int64_t val)
1909 return (val >= 0 && val <= 11);
1912 static inline bool isImmUs2(int64_t val)
1914 return (val%2 == 0 && isImmUs(val/2));
1917 static inline bool isImmUs4(int64_t val)
1919 return (val%4 == 0 && isImmUs(val/4));
1922 /// isLegalAddressingMode - Return true if the addressing mode represented
1923 /// by AM is legal for this target, for a load/store of the specified type.
1925 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1927 if (Ty->getTypeID() == Type::VoidTyID)
1928 return AM.Scale == 0 && isImmUs(AM.BaseOffs) && isImmUs4(AM.BaseOffs);
1930 const DataLayout *TD = TM.getDataLayout();
1931 unsigned Size = TD->getTypeAllocSize(Ty);
1933 return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1940 if (AM.Scale == 0) {
1941 return isImmUs(AM.BaseOffs);
1944 return AM.Scale == 1 && AM.BaseOffs == 0;
1948 if (AM.Scale == 0) {
1949 return isImmUs2(AM.BaseOffs);
1952 return AM.Scale == 2 && AM.BaseOffs == 0;
1955 if (AM.Scale == 0) {
1956 return isImmUs4(AM.BaseOffs);
1959 return AM.Scale == 4 && AM.BaseOffs == 0;
1963 //===----------------------------------------------------------------------===//
1964 // XCore Inline Assembly Support
1965 //===----------------------------------------------------------------------===//
1967 std::pair<unsigned, const TargetRegisterClass*>
1968 XCoreTargetLowering::
1969 getRegForInlineAsmConstraint(const std::string &Constraint,
1971 if (Constraint.size() == 1) {
1972 switch (Constraint[0]) {
1975 return std::make_pair(0U, &XCore::GRRegsRegClass);
1978 // Use the default implementation in TargetLowering to convert the register
1979 // constraint into a member of a register class.
1980 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);