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::
272 getGlobalAddressWrapper(SDValue GA, const GlobalValue *GV,
273 SelectionDAG &DAG) const
275 // FIXME there is no actual debug info here
277 const GlobalValue *UnderlyingGV = GV;
278 // If GV is an alias then use the aliasee to determine the wrapper type
279 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
280 UnderlyingGV = GA->getAliasee();
281 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(UnderlyingGV)) {
282 if ( ( GVar->isConstant() &&
283 UnderlyingGV->isLocalLinkage(GV->getLinkage()) )
284 || ( GVar->hasSection() &&
285 StringRef(GVar->getSection()).startswith(".cp.") ) )
286 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
287 return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
289 return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
292 static bool IsSmallObject(const GlobalValue *GV, const XCoreTargetLowering &XTL) {
293 if (XTL.getTargetMachine().getCodeModel() == CodeModel::Small)
296 Type *ObjType = GV->getType()->getPointerElementType();
297 if (!ObjType->isSized())
300 unsigned ObjSize = XTL.getDataLayout()->getTypeAllocSize(ObjType);
301 return ObjSize < CodeModelLargeSize && ObjSize != 0;
304 SDValue XCoreTargetLowering::
305 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const
307 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
308 const GlobalValue *GV = GN->getGlobal();
310 int64_t Offset = GN->getOffset();
311 if (IsSmallObject(GV, *this)) {
312 // We can only fold positive offsets that are a multiple of the word size.
313 int64_t FoldedOffset = std::max(Offset & ~3, (int64_t)0);
314 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, FoldedOffset);
315 GA = getGlobalAddressWrapper(GA, GV, DAG);
316 // Handle the rest of the offset.
317 if (Offset != FoldedOffset) {
318 SDValue Remaining = DAG.getConstant(Offset - FoldedOffset, MVT::i32);
319 GA = DAG.getNode(ISD::ADD, DL, MVT::i32, GA, Remaining);
323 // Ideally we would not fold in offset with an index <= 11.
324 Type *Ty = Type::getInt8PtrTy(*DAG.getContext());
325 Constant *GA = ConstantExpr::getBitCast(const_cast<GlobalValue*>(GV), Ty);
326 Ty = Type::getInt32Ty(*DAG.getContext());
327 Constant *Idx = ConstantInt::get(Ty, Offset);
328 Constant *GAI = ConstantExpr::getGetElementPtr(GA, Idx);
329 SDValue CP = DAG.getConstantPool(GAI, MVT::i32);
330 return DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), CP,
331 MachinePointerInfo(), false, false, false, 0);
335 SDValue XCoreTargetLowering::
336 LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const
340 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
341 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy());
343 return DAG.getNode(XCoreISD::PCRelativeWrapper, DL, getPointerTy(), Result);
346 SDValue XCoreTargetLowering::
347 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
349 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
350 // FIXME there isn't really debug info here
352 EVT PtrVT = Op.getValueType();
354 if (CP->isMachineConstantPoolEntry()) {
355 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
356 CP->getAlignment(), CP->getOffset());
358 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
359 CP->getAlignment(), CP->getOffset());
361 return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
364 unsigned XCoreTargetLowering::getJumpTableEncoding() const {
365 return MachineJumpTableInfo::EK_Inline;
368 SDValue XCoreTargetLowering::
369 LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
371 SDValue Chain = Op.getOperand(0);
372 SDValue Table = Op.getOperand(1);
373 SDValue Index = Op.getOperand(2);
375 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
376 unsigned JTI = JT->getIndex();
377 MachineFunction &MF = DAG.getMachineFunction();
378 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
379 SDValue TargetJT = DAG.getTargetJumpTable(JT->getIndex(), MVT::i32);
381 unsigned NumEntries = MJTI->getJumpTables()[JTI].MBBs.size();
382 if (NumEntries <= 32) {
383 return DAG.getNode(XCoreISD::BR_JT, dl, MVT::Other, Chain, TargetJT, Index);
385 assert((NumEntries >> 31) == 0);
386 SDValue ScaledIndex = DAG.getNode(ISD::SHL, dl, MVT::i32, Index,
387 DAG.getConstant(1, MVT::i32));
388 return DAG.getNode(XCoreISD::BR_JT32, dl, MVT::Other, Chain, TargetJT,
392 SDValue XCoreTargetLowering::
393 lowerLoadWordFromAlignedBasePlusOffset(SDLoc DL, SDValue Chain, SDValue Base,
394 int64_t Offset, SelectionDAG &DAG) const
396 if ((Offset & 0x3) == 0) {
397 return DAG.getLoad(getPointerTy(), DL, Chain, Base, MachinePointerInfo(),
398 false, false, false, 0);
400 // Lower to pair of consecutive word aligned loads plus some bit shifting.
401 int32_t HighOffset = RoundUpToAlignment(Offset, 4);
402 int32_t LowOffset = HighOffset - 4;
403 SDValue LowAddr, HighAddr;
404 if (GlobalAddressSDNode *GASD =
405 dyn_cast<GlobalAddressSDNode>(Base.getNode())) {
406 LowAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
408 HighAddr = DAG.getGlobalAddress(GASD->getGlobal(), DL, Base.getValueType(),
411 LowAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
412 DAG.getConstant(LowOffset, MVT::i32));
413 HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, Base,
414 DAG.getConstant(HighOffset, MVT::i32));
416 SDValue LowShift = DAG.getConstant((Offset - LowOffset) * 8, MVT::i32);
417 SDValue HighShift = DAG.getConstant((HighOffset - Offset) * 8, MVT::i32);
419 SDValue Low = DAG.getLoad(getPointerTy(), DL, Chain,
420 LowAddr, MachinePointerInfo(),
421 false, false, false, 0);
422 SDValue High = DAG.getLoad(getPointerTy(), DL, Chain,
423 HighAddr, MachinePointerInfo(),
424 false, false, false, 0);
425 SDValue LowShifted = DAG.getNode(ISD::SRL, DL, MVT::i32, Low, LowShift);
426 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High, HighShift);
427 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, LowShifted, HighShifted);
428 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
430 SDValue Ops[] = { Result, Chain };
431 return DAG.getMergeValues(Ops, DL);
434 static bool isWordAligned(SDValue Value, SelectionDAG &DAG)
436 APInt KnownZero, KnownOne;
437 DAG.computeKnownBits(Value, KnownZero, KnownOne);
438 return KnownZero.countTrailingOnes() >= 2;
441 SDValue XCoreTargetLowering::
442 LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
443 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
444 LoadSDNode *LD = cast<LoadSDNode>(Op);
445 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
446 "Unexpected extension type");
447 assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
448 if (allowsUnalignedMemoryAccesses(LD->getMemoryVT()))
451 unsigned ABIAlignment = getDataLayout()->
452 getABITypeAlignment(LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
453 // Leave aligned load alone.
454 if (LD->getAlignment() >= ABIAlignment)
457 SDValue Chain = LD->getChain();
458 SDValue BasePtr = LD->getBasePtr();
461 if (!LD->isVolatile()) {
462 const GlobalValue *GV;
464 if (DAG.isBaseWithConstantOffset(BasePtr) &&
465 isWordAligned(BasePtr->getOperand(0), DAG)) {
466 SDValue NewBasePtr = BasePtr->getOperand(0);
467 Offset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
468 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
471 if (TLI.isGAPlusOffset(BasePtr.getNode(), GV, Offset) &&
472 MinAlign(GV->getAlignment(), 4) == 4) {
473 SDValue NewBasePtr = DAG.getGlobalAddress(GV, DL,
474 BasePtr->getValueType(0));
475 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, NewBasePtr,
480 if (LD->getAlignment() == 2) {
481 SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, DL, MVT::i32, Chain,
482 BasePtr, LD->getPointerInfo(), MVT::i16,
483 LD->isVolatile(), LD->isNonTemporal(), 2);
484 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
485 DAG.getConstant(2, MVT::i32));
486 SDValue High = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
488 LD->getPointerInfo().getWithOffset(2),
489 MVT::i16, LD->isVolatile(),
490 LD->isNonTemporal(), 2);
491 SDValue HighShifted = DAG.getNode(ISD::SHL, DL, MVT::i32, High,
492 DAG.getConstant(16, MVT::i32));
493 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i32, Low, HighShifted);
494 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Low.getValue(1),
496 SDValue Ops[] = { Result, Chain };
497 return DAG.getMergeValues(Ops, DL);
500 // Lower to a call to __misaligned_load(BasePtr).
501 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
502 TargetLowering::ArgListTy Args;
503 TargetLowering::ArgListEntry Entry;
506 Entry.Node = BasePtr;
507 Args.push_back(Entry);
509 TargetLowering::CallLoweringInfo CLI(DAG);
510 CLI.setDebugLoc(DL).setChain(Chain)
511 .setCallee(CallingConv::C, IntPtrTy,
512 DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
515 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
516 SDValue Ops[] = { CallResult.first, CallResult.second };
517 return DAG.getMergeValues(Ops, DL);
520 SDValue XCoreTargetLowering::
521 LowerSTORE(SDValue Op, SelectionDAG &DAG) const
523 StoreSDNode *ST = cast<StoreSDNode>(Op);
524 assert(!ST->isTruncatingStore() && "Unexpected store type");
525 assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
526 if (allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
529 unsigned ABIAlignment = getDataLayout()->
530 getABITypeAlignment(ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
531 // Leave aligned store alone.
532 if (ST->getAlignment() >= ABIAlignment) {
535 SDValue Chain = ST->getChain();
536 SDValue BasePtr = ST->getBasePtr();
537 SDValue Value = ST->getValue();
540 if (ST->getAlignment() == 2) {
542 SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
543 DAG.getConstant(16, MVT::i32));
544 SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
545 ST->getPointerInfo(), MVT::i16,
546 ST->isVolatile(), ST->isNonTemporal(),
548 SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
549 DAG.getConstant(2, MVT::i32));
550 SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
551 ST->getPointerInfo().getWithOffset(2),
552 MVT::i16, ST->isVolatile(),
553 ST->isNonTemporal(), 2);
554 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
557 // Lower to a call to __misaligned_store(BasePtr, Value).
558 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
559 TargetLowering::ArgListTy Args;
560 TargetLowering::ArgListEntry Entry;
563 Entry.Node = BasePtr;
564 Args.push_back(Entry);
567 Args.push_back(Entry);
569 TargetLowering::CallLoweringInfo CLI(DAG);
570 CLI.setDebugLoc(dl).setChain(Chain)
571 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
572 DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
575 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
576 return CallResult.second;
579 SDValue XCoreTargetLowering::
580 LowerSMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
582 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::SMUL_LOHI &&
583 "Unexpected operand to lower!");
585 SDValue LHS = Op.getOperand(0);
586 SDValue RHS = Op.getOperand(1);
587 SDValue Zero = DAG.getConstant(0, MVT::i32);
588 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
589 DAG.getVTList(MVT::i32, MVT::i32), Zero, Zero,
591 SDValue Lo(Hi.getNode(), 1);
592 SDValue Ops[] = { Lo, Hi };
593 return DAG.getMergeValues(Ops, dl);
596 SDValue XCoreTargetLowering::
597 LowerUMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
599 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::UMUL_LOHI &&
600 "Unexpected operand to lower!");
602 SDValue LHS = Op.getOperand(0);
603 SDValue RHS = Op.getOperand(1);
604 SDValue Zero = DAG.getConstant(0, MVT::i32);
605 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
606 DAG.getVTList(MVT::i32, MVT::i32), LHS, RHS,
608 SDValue Lo(Hi.getNode(), 1);
609 SDValue Ops[] = { Lo, Hi };
610 return DAG.getMergeValues(Ops, dl);
613 /// isADDADDMUL - Return whether Op is in a form that is equivalent to
614 /// add(add(mul(x,y),a),b). If requireIntermediatesHaveOneUse is true then
615 /// each intermediate result in the calculation must also have a single use.
616 /// If the Op is in the correct form the constituent parts are written to Mul0,
617 /// Mul1, Addend0 and Addend1.
619 isADDADDMUL(SDValue Op, SDValue &Mul0, SDValue &Mul1, SDValue &Addend0,
620 SDValue &Addend1, bool requireIntermediatesHaveOneUse)
622 if (Op.getOpcode() != ISD::ADD)
624 SDValue N0 = Op.getOperand(0);
625 SDValue N1 = Op.getOperand(1);
628 if (N0.getOpcode() == ISD::ADD) {
631 } else if (N1.getOpcode() == ISD::ADD) {
637 if (requireIntermediatesHaveOneUse && !AddOp.hasOneUse())
639 if (OtherOp.getOpcode() == ISD::MUL) {
640 // add(add(a,b),mul(x,y))
641 if (requireIntermediatesHaveOneUse && !OtherOp.hasOneUse())
643 Mul0 = OtherOp.getOperand(0);
644 Mul1 = OtherOp.getOperand(1);
645 Addend0 = AddOp.getOperand(0);
646 Addend1 = AddOp.getOperand(1);
649 if (AddOp.getOperand(0).getOpcode() == ISD::MUL) {
650 // add(add(mul(x,y),a),b)
651 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(0).hasOneUse())
653 Mul0 = AddOp.getOperand(0).getOperand(0);
654 Mul1 = AddOp.getOperand(0).getOperand(1);
655 Addend0 = AddOp.getOperand(1);
659 if (AddOp.getOperand(1).getOpcode() == ISD::MUL) {
660 // add(add(a,mul(x,y)),b)
661 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(1).hasOneUse())
663 Mul0 = AddOp.getOperand(1).getOperand(0);
664 Mul1 = AddOp.getOperand(1).getOperand(1);
665 Addend0 = AddOp.getOperand(0);
672 SDValue XCoreTargetLowering::
673 TryExpandADDWithMul(SDNode *N, SelectionDAG &DAG) const
677 if (N->getOperand(0).getOpcode() == ISD::MUL) {
678 Mul = N->getOperand(0);
679 Other = N->getOperand(1);
680 } else if (N->getOperand(1).getOpcode() == ISD::MUL) {
681 Mul = N->getOperand(1);
682 Other = N->getOperand(0);
687 SDValue LL, RL, AddendL, AddendH;
688 LL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
689 Mul.getOperand(0), DAG.getConstant(0, MVT::i32));
690 RL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
691 Mul.getOperand(1), DAG.getConstant(0, MVT::i32));
692 AddendL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
693 Other, DAG.getConstant(0, MVT::i32));
694 AddendH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
695 Other, DAG.getConstant(1, MVT::i32));
696 APInt HighMask = APInt::getHighBitsSet(64, 32);
697 unsigned LHSSB = DAG.ComputeNumSignBits(Mul.getOperand(0));
698 unsigned RHSSB = DAG.ComputeNumSignBits(Mul.getOperand(1));
699 if (DAG.MaskedValueIsZero(Mul.getOperand(0), HighMask) &&
700 DAG.MaskedValueIsZero(Mul.getOperand(1), HighMask)) {
701 // The inputs are both zero-extended.
702 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
703 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
705 SDValue Lo(Hi.getNode(), 1);
706 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
708 if (LHSSB > 32 && RHSSB > 32) {
709 // The inputs are both sign-extended.
710 SDValue Hi = DAG.getNode(XCoreISD::MACCS, dl,
711 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
713 SDValue Lo(Hi.getNode(), 1);
714 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
717 LH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
718 Mul.getOperand(0), DAG.getConstant(1, MVT::i32));
719 RH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
720 Mul.getOperand(1), DAG.getConstant(1, MVT::i32));
721 SDValue Hi = DAG.getNode(XCoreISD::MACCU, dl,
722 DAG.getVTList(MVT::i32, MVT::i32), AddendH,
724 SDValue Lo(Hi.getNode(), 1);
725 RH = DAG.getNode(ISD::MUL, dl, MVT::i32, LL, RH);
726 LH = DAG.getNode(ISD::MUL, dl, MVT::i32, LH, RL);
727 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, RH);
728 Hi = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, LH);
729 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
732 SDValue XCoreTargetLowering::
733 ExpandADDSUB(SDNode *N, SelectionDAG &DAG) const
735 assert(N->getValueType(0) == MVT::i64 &&
736 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
737 "Unknown operand to lower!");
739 if (N->getOpcode() == ISD::ADD) {
740 SDValue Result = TryExpandADDWithMul(N, DAG);
741 if (Result.getNode())
747 // Extract components
748 SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
749 N->getOperand(0), DAG.getConstant(0, MVT::i32));
750 SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
751 N->getOperand(0), DAG.getConstant(1, MVT::i32));
752 SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
753 N->getOperand(1), DAG.getConstant(0, MVT::i32));
754 SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
755 N->getOperand(1), DAG.getConstant(1, MVT::i32));
758 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
760 SDValue Zero = DAG.getConstant(0, MVT::i32);
761 SDValue Lo = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
763 SDValue Carry(Lo.getNode(), 1);
765 SDValue Hi = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
767 SDValue Ignored(Hi.getNode(), 1);
769 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
772 SDValue XCoreTargetLowering::
773 LowerVAARG(SDValue Op, SelectionDAG &DAG) const
775 // Whist llvm does not support aggregate varargs we can ignore
776 // the possibility of the ValueType being an implicit byVal vararg.
777 SDNode *Node = Op.getNode();
778 EVT VT = Node->getValueType(0); // not an aggregate
779 SDValue InChain = Node->getOperand(0);
780 SDValue VAListPtr = Node->getOperand(1);
781 EVT PtrVT = VAListPtr.getValueType();
782 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
784 SDValue VAList = DAG.getLoad(PtrVT, dl, InChain,
785 VAListPtr, MachinePointerInfo(SV),
786 false, false, false, 0);
787 // Increment the pointer, VAList, to the next vararg
788 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAList,
789 DAG.getIntPtrConstant(VT.getSizeInBits() / 8));
790 // Store the incremented VAList to the legalized pointer
791 InChain = DAG.getStore(VAList.getValue(1), dl, nextPtr, VAListPtr,
792 MachinePointerInfo(SV), false, false, 0);
793 // Load the actual argument out of the pointer VAList
794 return DAG.getLoad(VT, dl, InChain, VAList, MachinePointerInfo(),
795 false, false, false, 0);
798 SDValue XCoreTargetLowering::
799 LowerVASTART(SDValue Op, SelectionDAG &DAG) const
802 // vastart stores the address of the VarArgsFrameIndex slot into the
803 // memory location argument
804 MachineFunction &MF = DAG.getMachineFunction();
805 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
806 SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
807 return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1),
808 MachinePointerInfo(), false, false, 0);
811 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op,
812 SelectionDAG &DAG) const {
813 // This nodes represent llvm.frameaddress on the DAG.
814 // It takes one operand, the index of the frame address to return.
815 // An index of zero corresponds to the current function's frame address.
816 // An index of one to the parent's frame address, and so on.
817 // Depths > 0 not supported yet!
818 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
821 MachineFunction &MF = DAG.getMachineFunction();
822 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
823 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op),
824 RegInfo->getFrameRegister(MF), MVT::i32);
827 SDValue XCoreTargetLowering::
828 LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const {
829 // This nodes represent llvm.returnaddress on the DAG.
830 // It takes one operand, the index of the return address to return.
831 // An index of zero corresponds to the current function's return address.
832 // An index of one to the parent's return address, and so on.
833 // Depths > 0 not supported yet!
834 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
837 MachineFunction &MF = DAG.getMachineFunction();
838 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
839 int FI = XFI->createLRSpillSlot(MF);
840 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
841 return DAG.getLoad(getPointerTy(), SDLoc(Op), DAG.getEntryNode(), FIN,
842 MachinePointerInfo::getFixedStack(FI), false, false,
846 SDValue XCoreTargetLowering::
847 LowerFRAME_TO_ARGS_OFFSET(SDValue Op, SelectionDAG &DAG) const {
848 // This node represents offset from frame pointer to first on-stack argument.
849 // This is needed for correct stack adjustment during unwind.
850 // However, we don't know the offset until after the frame has be finalised.
851 // This is done during the XCoreFTAOElim pass.
852 return DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, SDLoc(Op), MVT::i32);
855 SDValue XCoreTargetLowering::
856 LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
857 // OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER)
858 // This node represents 'eh_return' gcc dwarf builtin, which is used to
859 // return from exception. The general meaning is: adjust stack by OFFSET and
860 // pass execution to HANDLER.
861 MachineFunction &MF = DAG.getMachineFunction();
862 SDValue Chain = Op.getOperand(0);
863 SDValue Offset = Op.getOperand(1);
864 SDValue Handler = Op.getOperand(2);
867 // Absolute SP = (FP + FrameToArgs) + Offset
868 const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
869 SDValue Stack = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
870 RegInfo->getFrameRegister(MF), MVT::i32);
871 SDValue FrameToArgs = DAG.getNode(XCoreISD::FRAME_TO_ARGS_OFFSET, dl,
873 Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, FrameToArgs);
874 Stack = DAG.getNode(ISD::ADD, dl, MVT::i32, Stack, Offset);
876 // R0=ExceptionPointerRegister R1=ExceptionSelectorRegister
877 // which leaves 2 caller saved registers, R2 & R3 for us to use.
878 unsigned StackReg = XCore::R2;
879 unsigned HandlerReg = XCore::R3;
881 SDValue OutChains[] = {
882 DAG.getCopyToReg(Chain, dl, StackReg, Stack),
883 DAG.getCopyToReg(Chain, dl, HandlerReg, Handler)
886 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
888 return DAG.getNode(XCoreISD::EH_RETURN, dl, MVT::Other, Chain,
889 DAG.getRegister(StackReg, MVT::i32),
890 DAG.getRegister(HandlerReg, MVT::i32));
894 SDValue XCoreTargetLowering::
895 LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
896 return Op.getOperand(0);
899 SDValue XCoreTargetLowering::
900 LowerINIT_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
901 SDValue Chain = Op.getOperand(0);
902 SDValue Trmp = Op.getOperand(1); // trampoline
903 SDValue FPtr = Op.getOperand(2); // nested function
904 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
906 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
909 // LDAPF_u10 r11, nest
910 // LDW_2rus r11, r11[0]
911 // STWSP_ru6 r11, sp[0]
912 // LDAPF_u10 r11, fptr
913 // LDW_2rus r11, r11[0]
919 SDValue OutChains[5];
924 OutChains[0] = DAG.getStore(Chain, dl, DAG.getConstant(0x0a3cd805, MVT::i32),
925 Addr, MachinePointerInfo(TrmpAddr), false, false,
928 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
929 DAG.getConstant(4, MVT::i32));
930 OutChains[1] = DAG.getStore(Chain, dl, DAG.getConstant(0xd80456c0, MVT::i32),
931 Addr, MachinePointerInfo(TrmpAddr, 4), false,
934 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
935 DAG.getConstant(8, MVT::i32));
936 OutChains[2] = DAG.getStore(Chain, dl, DAG.getConstant(0x27fb0a3c, MVT::i32),
937 Addr, MachinePointerInfo(TrmpAddr, 8), false,
940 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
941 DAG.getConstant(12, MVT::i32));
942 OutChains[3] = DAG.getStore(Chain, dl, Nest, Addr,
943 MachinePointerInfo(TrmpAddr, 12), false, false,
946 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
947 DAG.getConstant(16, MVT::i32));
948 OutChains[4] = DAG.getStore(Chain, dl, FPtr, Addr,
949 MachinePointerInfo(TrmpAddr, 16), false, false,
952 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
955 SDValue XCoreTargetLowering::
956 LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
958 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
960 case Intrinsic::xcore_crc8:
961 EVT VT = Op.getValueType();
963 DAG.getNode(XCoreISD::CRC8, DL, DAG.getVTList(VT, VT),
964 Op.getOperand(1), Op.getOperand(2) , Op.getOperand(3));
965 SDValue Crc(Data.getNode(), 1);
966 SDValue Results[] = { Crc, Data };
967 return DAG.getMergeValues(Results, DL);
972 SDValue XCoreTargetLowering::
973 LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG) const {
975 return DAG.getNode(XCoreISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
978 SDValue XCoreTargetLowering::
979 LowerATOMIC_LOAD(SDValue Op, SelectionDAG &DAG) const {
980 AtomicSDNode *N = cast<AtomicSDNode>(Op);
981 assert(N->getOpcode() == ISD::ATOMIC_LOAD && "Bad Atomic OP");
982 assert(N->getOrdering() <= Monotonic &&
983 "setInsertFencesForAtomic(true) and yet greater than Monotonic");
984 if (N->getMemoryVT() == MVT::i32) {
985 if (N->getAlignment() < 4)
986 report_fatal_error("atomic load must be aligned");
987 return DAG.getLoad(getPointerTy(), SDLoc(Op), N->getChain(),
988 N->getBasePtr(), N->getPointerInfo(),
989 N->isVolatile(), N->isNonTemporal(),
990 N->isInvariant(), N->getAlignment(),
991 N->getTBAAInfo(), N->getRanges());
993 if (N->getMemoryVT() == MVT::i16) {
994 if (N->getAlignment() < 2)
995 report_fatal_error("atomic load must be aligned");
996 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
997 N->getBasePtr(), N->getPointerInfo(), MVT::i16,
998 N->isVolatile(), N->isNonTemporal(),
999 N->getAlignment(), N->getTBAAInfo());
1001 if (N->getMemoryVT() == MVT::i8)
1002 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), MVT::i32, N->getChain(),
1003 N->getBasePtr(), N->getPointerInfo(), MVT::i8,
1004 N->isVolatile(), N->isNonTemporal(),
1005 N->getAlignment(), N->getTBAAInfo());
1009 SDValue XCoreTargetLowering::
1010 LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) const {
1011 AtomicSDNode *N = cast<AtomicSDNode>(Op);
1012 assert(N->getOpcode() == ISD::ATOMIC_STORE && "Bad Atomic OP");
1013 assert(N->getOrdering() <= Monotonic &&
1014 "setInsertFencesForAtomic(true) and yet greater than Monotonic");
1015 if (N->getMemoryVT() == MVT::i32) {
1016 if (N->getAlignment() < 4)
1017 report_fatal_error("atomic store must be aligned");
1018 return DAG.getStore(N->getChain(), SDLoc(Op), N->getVal(),
1019 N->getBasePtr(), N->getPointerInfo(),
1020 N->isVolatile(), N->isNonTemporal(),
1021 N->getAlignment(), N->getTBAAInfo());
1023 if (N->getMemoryVT() == MVT::i16) {
1024 if (N->getAlignment() < 2)
1025 report_fatal_error("atomic store must be aligned");
1026 return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1027 N->getBasePtr(), N->getPointerInfo(), MVT::i16,
1028 N->isVolatile(), N->isNonTemporal(),
1029 N->getAlignment(), N->getTBAAInfo());
1031 if (N->getMemoryVT() == MVT::i8)
1032 return DAG.getTruncStore(N->getChain(), SDLoc(Op), N->getVal(),
1033 N->getBasePtr(), N->getPointerInfo(), MVT::i8,
1034 N->isVolatile(), N->isNonTemporal(),
1035 N->getAlignment(), N->getTBAAInfo());
1039 //===----------------------------------------------------------------------===//
1040 // Calling Convention Implementation
1041 //===----------------------------------------------------------------------===//
1043 #include "XCoreGenCallingConv.inc"
1045 //===----------------------------------------------------------------------===//
1046 // Call Calling Convention Implementation
1047 //===----------------------------------------------------------------------===//
1049 /// XCore call implementation
1051 XCoreTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1052 SmallVectorImpl<SDValue> &InVals) const {
1053 SelectionDAG &DAG = CLI.DAG;
1055 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1056 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1057 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1058 SDValue Chain = CLI.Chain;
1059 SDValue Callee = CLI.Callee;
1060 bool &isTailCall = CLI.IsTailCall;
1061 CallingConv::ID CallConv = CLI.CallConv;
1062 bool isVarArg = CLI.IsVarArg;
1064 // XCore target does not yet support tail call optimization.
1067 // For now, only CallingConv::C implemented
1071 llvm_unreachable("Unsupported calling convention");
1072 case CallingConv::Fast:
1073 case CallingConv::C:
1074 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
1075 Outs, OutVals, Ins, dl, DAG, InVals);
1079 /// LowerCallResult - Lower the result values of a call into the
1080 /// appropriate copies out of appropriate physical registers / memory locations.
1082 LowerCallResult(SDValue Chain, SDValue InFlag,
1083 const SmallVectorImpl<CCValAssign> &RVLocs,
1084 SDLoc dl, SelectionDAG &DAG,
1085 SmallVectorImpl<SDValue> &InVals) {
1086 SmallVector<std::pair<int, unsigned>, 4> ResultMemLocs;
1087 // Copy results out of physical registers.
1088 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1089 const CCValAssign &VA = RVLocs[i];
1090 if (VA.isRegLoc()) {
1091 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getValVT(),
1092 InFlag).getValue(1);
1093 InFlag = Chain.getValue(2);
1094 InVals.push_back(Chain.getValue(0));
1096 assert(VA.isMemLoc());
1097 ResultMemLocs.push_back(std::make_pair(VA.getLocMemOffset(),
1099 // Reserve space for this result.
1100 InVals.push_back(SDValue());
1104 // Copy results out of memory.
1105 SmallVector<SDValue, 4> MemOpChains;
1106 for (unsigned i = 0, e = ResultMemLocs.size(); i != e; ++i) {
1107 int offset = ResultMemLocs[i].first;
1108 unsigned index = ResultMemLocs[i].second;
1109 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
1110 SDValue Ops[] = { Chain, DAG.getConstant(offset / 4, MVT::i32) };
1111 SDValue load = DAG.getNode(XCoreISD::LDWSP, dl, VTs, Ops);
1112 InVals[index] = load;
1113 MemOpChains.push_back(load.getValue(1));
1116 // Transform all loads nodes into one single node because
1117 // all load nodes are independent of each other.
1118 if (!MemOpChains.empty())
1119 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1124 /// LowerCCCCallTo - functions arguments are copied from virtual
1125 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
1126 /// CALLSEQ_END are emitted.
1127 /// TODO: isTailCall, sret.
1129 XCoreTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
1130 CallingConv::ID CallConv, bool isVarArg,
1132 const SmallVectorImpl<ISD::OutputArg> &Outs,
1133 const SmallVectorImpl<SDValue> &OutVals,
1134 const SmallVectorImpl<ISD::InputArg> &Ins,
1135 SDLoc dl, SelectionDAG &DAG,
1136 SmallVectorImpl<SDValue> &InVals) const {
1138 // Analyze operands of the call, assigning locations to each operand.
1139 SmallVector<CCValAssign, 16> ArgLocs;
1140 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1141 getTargetMachine(), ArgLocs, *DAG.getContext());
1143 // The ABI dictates there should be one stack slot available to the callee
1144 // on function entry (for saving lr).
1145 CCInfo.AllocateStack(4, 4);
1147 CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
1149 SmallVector<CCValAssign, 16> RVLocs;
1150 // Analyze return values to determine the number of bytes of stack required.
1151 CCState RetCCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1152 getTargetMachine(), RVLocs, *DAG.getContext());
1153 RetCCInfo.AllocateStack(CCInfo.getNextStackOffset(), 4);
1154 RetCCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
1156 // Get a count of how many bytes are to be pushed on the stack.
1157 unsigned NumBytes = RetCCInfo.getNextStackOffset();
1159 Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes,
1160 getPointerTy(), true), dl);
1162 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
1163 SmallVector<SDValue, 12> MemOpChains;
1165 // Walk the register/memloc assignments, inserting copies/loads.
1166 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1167 CCValAssign &VA = ArgLocs[i];
1168 SDValue Arg = OutVals[i];
1170 // Promote the value if needed.
1171 switch (VA.getLocInfo()) {
1172 default: llvm_unreachable("Unknown loc info!");
1173 case CCValAssign::Full: break;
1174 case CCValAssign::SExt:
1175 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1177 case CCValAssign::ZExt:
1178 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1180 case CCValAssign::AExt:
1181 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1185 // Arguments that can be passed on register must be kept at
1186 // RegsToPass vector
1187 if (VA.isRegLoc()) {
1188 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1190 assert(VA.isMemLoc());
1192 int Offset = VA.getLocMemOffset();
1194 MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other,
1196 DAG.getConstant(Offset/4, MVT::i32)));
1200 // Transform all store nodes into one single node because
1201 // all store nodes are independent of each other.
1202 if (!MemOpChains.empty())
1203 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1205 // Build a sequence of copy-to-reg nodes chained together with token
1206 // chain and flag operands which copy the outgoing args into registers.
1207 // The InFlag in necessary since all emitted instructions must be
1210 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1211 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1212 RegsToPass[i].second, InFlag);
1213 InFlag = Chain.getValue(1);
1216 // If the callee is a GlobalAddress node (quite common, every direct call is)
1217 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1218 // Likewise ExternalSymbol -> TargetExternalSymbol.
1219 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1220 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
1221 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
1222 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
1224 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
1225 // = Chain, Callee, Reg#1, Reg#2, ...
1227 // Returns a chain & a flag for retval copy to use.
1228 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1229 SmallVector<SDValue, 8> Ops;
1230 Ops.push_back(Chain);
1231 Ops.push_back(Callee);
1233 // Add argument registers to the end of the list so that they are
1234 // known live into the call.
1235 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1236 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1237 RegsToPass[i].second.getValueType()));
1239 if (InFlag.getNode())
1240 Ops.push_back(InFlag);
1242 Chain = DAG.getNode(XCoreISD::BL, dl, NodeTys, Ops);
1243 InFlag = Chain.getValue(1);
1245 // Create the CALLSEQ_END node.
1246 Chain = DAG.getCALLSEQ_END(Chain,
1247 DAG.getConstant(NumBytes, getPointerTy(), true),
1248 DAG.getConstant(0, getPointerTy(), true),
1250 InFlag = Chain.getValue(1);
1252 // Handle result values, copying them out of physregs into vregs that we
1254 return LowerCallResult(Chain, InFlag, RVLocs, dl, DAG, InVals);
1257 //===----------------------------------------------------------------------===//
1258 // Formal Arguments Calling Convention Implementation
1259 //===----------------------------------------------------------------------===//
1262 struct ArgDataPair { SDValue SDV; ISD::ArgFlagsTy Flags; };
1265 /// XCore formal arguments implementation
1267 XCoreTargetLowering::LowerFormalArguments(SDValue Chain,
1268 CallingConv::ID CallConv,
1270 const SmallVectorImpl<ISD::InputArg> &Ins,
1273 SmallVectorImpl<SDValue> &InVals)
1278 llvm_unreachable("Unsupported calling convention");
1279 case CallingConv::C:
1280 case CallingConv::Fast:
1281 return LowerCCCArguments(Chain, CallConv, isVarArg,
1282 Ins, dl, DAG, InVals);
1286 /// LowerCCCArguments - transform physical registers into
1287 /// virtual registers and generate load operations for
1288 /// arguments places on the stack.
1291 XCoreTargetLowering::LowerCCCArguments(SDValue Chain,
1292 CallingConv::ID CallConv,
1294 const SmallVectorImpl<ISD::InputArg>
1298 SmallVectorImpl<SDValue> &InVals) const {
1299 MachineFunction &MF = DAG.getMachineFunction();
1300 MachineFrameInfo *MFI = MF.getFrameInfo();
1301 MachineRegisterInfo &RegInfo = MF.getRegInfo();
1302 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1304 // Assign locations to all of the incoming arguments.
1305 SmallVector<CCValAssign, 16> ArgLocs;
1306 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1307 getTargetMachine(), ArgLocs, *DAG.getContext());
1309 CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
1311 unsigned StackSlotSize = XCoreFrameLowering::stackSlotSize();
1313 unsigned LRSaveSize = StackSlotSize;
1316 XFI->setReturnStackOffset(CCInfo.getNextStackOffset() + LRSaveSize);
1318 // All getCopyFromReg ops must precede any getMemcpys to prevent the
1319 // scheduler clobbering a register before it has been copied.
1321 // 1. CopyFromReg (and load) arg & vararg registers.
1322 // 2. Chain CopyFromReg nodes into a TokenFactor.
1323 // 3. Memcpy 'byVal' args & push final InVals.
1324 // 4. Chain mem ops nodes into a TokenFactor.
1325 SmallVector<SDValue, 4> CFRegNode;
1326 SmallVector<ArgDataPair, 4> ArgData;
1327 SmallVector<SDValue, 4> MemOps;
1329 // 1a. CopyFromReg (and load) arg registers.
1330 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1332 CCValAssign &VA = ArgLocs[i];
1335 if (VA.isRegLoc()) {
1336 // Arguments passed in registers
1337 EVT RegVT = VA.getLocVT();
1338 switch (RegVT.getSimpleVT().SimpleTy) {
1342 errs() << "LowerFormalArguments Unhandled argument type: "
1343 << RegVT.getSimpleVT().SimpleTy << "\n";
1345 llvm_unreachable(nullptr);
1348 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1349 RegInfo.addLiveIn(VA.getLocReg(), VReg);
1350 ArgIn = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
1351 CFRegNode.push_back(ArgIn.getValue(ArgIn->getNumValues() - 1));
1355 assert(VA.isMemLoc());
1356 // Load the argument to a virtual register
1357 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
1358 if (ObjSize > StackSlotSize) {
1359 errs() << "LowerFormalArguments Unhandled argument type: "
1360 << EVT(VA.getLocVT()).getEVTString()
1363 // Create the frame index object for this incoming parameter...
1364 int FI = MFI->CreateFixedObject(ObjSize,
1365 LRSaveSize + VA.getLocMemOffset(),
1368 // Create the SelectionDAG nodes corresponding to a load
1369 //from this parameter
1370 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1371 ArgIn = DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
1372 MachinePointerInfo::getFixedStack(FI),
1373 false, false, false, 0);
1375 const ArgDataPair ADP = { ArgIn, Ins[i].Flags };
1376 ArgData.push_back(ADP);
1379 // 1b. CopyFromReg vararg registers.
1381 // Argument registers
1382 static const MCPhysReg ArgRegs[] = {
1383 XCore::R0, XCore::R1, XCore::R2, XCore::R3
1385 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1386 unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
1387 array_lengthof(ArgRegs));
1388 if (FirstVAReg < array_lengthof(ArgRegs)) {
1390 // Save remaining registers, storing higher register numbers at a higher
1392 for (int i = array_lengthof(ArgRegs) - 1; i >= (int)FirstVAReg; --i) {
1393 // Create a stack slot
1394 int FI = MFI->CreateFixedObject(4, offset, true);
1395 if (i == (int)FirstVAReg) {
1396 XFI->setVarArgsFrameIndex(FI);
1398 offset -= StackSlotSize;
1399 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1400 // Move argument from phys reg -> virt reg
1401 unsigned VReg = RegInfo.createVirtualRegister(&XCore::GRRegsRegClass);
1402 RegInfo.addLiveIn(ArgRegs[i], VReg);
1403 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1404 CFRegNode.push_back(Val.getValue(Val->getNumValues() - 1));
1405 // Move argument from virt reg -> stack
1406 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
1407 MachinePointerInfo(), false, false, 0);
1408 MemOps.push_back(Store);
1411 // This will point to the next argument passed via stack.
1412 XFI->setVarArgsFrameIndex(
1413 MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset(),
1418 // 2. chain CopyFromReg nodes into a TokenFactor.
1419 if (!CFRegNode.empty())
1420 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, CFRegNode);
1422 // 3. Memcpy 'byVal' args & push final InVals.
1423 // Aggregates passed "byVal" need to be copied by the callee.
1424 // The callee will use a pointer to this copy, rather than the original
1426 for (SmallVectorImpl<ArgDataPair>::const_iterator ArgDI = ArgData.begin(),
1427 ArgDE = ArgData.end();
1428 ArgDI != ArgDE; ++ArgDI) {
1429 if (ArgDI->Flags.isByVal() && ArgDI->Flags.getByValSize()) {
1430 unsigned Size = ArgDI->Flags.getByValSize();
1431 unsigned Align = std::max(StackSlotSize, ArgDI->Flags.getByValAlign());
1432 // Create a new object on the stack and copy the pointee into it.
1433 int FI = MFI->CreateStackObject(Size, Align, false);
1434 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1435 InVals.push_back(FIN);
1436 MemOps.push_back(DAG.getMemcpy(Chain, dl, FIN, ArgDI->SDV,
1437 DAG.getConstant(Size, MVT::i32),
1438 Align, false, false,
1439 MachinePointerInfo(),
1440 MachinePointerInfo()));
1442 InVals.push_back(ArgDI->SDV);
1446 // 4, chain mem ops nodes into a TokenFactor.
1447 if (!MemOps.empty()) {
1448 MemOps.push_back(Chain);
1449 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
1455 //===----------------------------------------------------------------------===//
1456 // Return Value Calling Convention Implementation
1457 //===----------------------------------------------------------------------===//
1459 bool XCoreTargetLowering::
1460 CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF,
1462 const SmallVectorImpl<ISD::OutputArg> &Outs,
1463 LLVMContext &Context) const {
1464 SmallVector<CCValAssign, 16> RVLocs;
1465 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
1466 if (!CCInfo.CheckReturn(Outs, RetCC_XCore))
1468 if (CCInfo.getNextStackOffset() != 0 && isVarArg)
1474 XCoreTargetLowering::LowerReturn(SDValue Chain,
1475 CallingConv::ID CallConv, bool isVarArg,
1476 const SmallVectorImpl<ISD::OutputArg> &Outs,
1477 const SmallVectorImpl<SDValue> &OutVals,
1478 SDLoc dl, SelectionDAG &DAG) const {
1480 XCoreFunctionInfo *XFI =
1481 DAG.getMachineFunction().getInfo<XCoreFunctionInfo>();
1482 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1484 // CCValAssign - represent the assignment of
1485 // the return value to a location
1486 SmallVector<CCValAssign, 16> RVLocs;
1488 // CCState - Info about the registers and stack slot.
1489 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1490 getTargetMachine(), RVLocs, *DAG.getContext());
1492 // Analyze return values.
1494 CCInfo.AllocateStack(XFI->getReturnStackOffset(), 4);
1496 CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
1499 SmallVector<SDValue, 4> RetOps(1, Chain);
1501 // Return on XCore is always a "retsp 0"
1502 RetOps.push_back(DAG.getConstant(0, MVT::i32));
1504 SmallVector<SDValue, 4> MemOpChains;
1505 // Handle return values that must be copied to memory.
1506 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1507 CCValAssign &VA = RVLocs[i];
1510 assert(VA.isMemLoc());
1512 report_fatal_error("Can't return value from vararg function in memory");
1515 int Offset = VA.getLocMemOffset();
1516 unsigned ObjSize = VA.getLocVT().getSizeInBits() / 8;
1517 // Create the frame index object for the memory location.
1518 int FI = MFI->CreateFixedObject(ObjSize, Offset, false);
1520 // Create a SelectionDAG node corresponding to a store
1521 // to this memory location.
1522 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1523 MemOpChains.push_back(DAG.getStore(Chain, dl, OutVals[i], FIN,
1524 MachinePointerInfo::getFixedStack(FI), false, false,
1528 // Transform all store nodes into one single node because
1529 // all stores are independent of each other.
1530 if (!MemOpChains.empty())
1531 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1533 // Now handle return values copied to registers.
1534 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1535 CCValAssign &VA = RVLocs[i];
1538 // Copy the result values into the output registers.
1539 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
1541 // guarantee that all emitted copies are
1542 // stuck together, avoiding something bad
1543 Flag = Chain.getValue(1);
1544 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1547 RetOps[0] = Chain; // Update chain.
1549 // Add the flag if we have it.
1551 RetOps.push_back(Flag);
1553 return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other, RetOps);
1556 //===----------------------------------------------------------------------===//
1557 // Other Lowering Code
1558 //===----------------------------------------------------------------------===//
1561 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1562 MachineBasicBlock *BB) const {
1563 const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1564 DebugLoc dl = MI->getDebugLoc();
1565 assert((MI->getOpcode() == XCore::SELECT_CC) &&
1566 "Unexpected instr type to insert");
1568 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1569 // control-flow pattern. The incoming instruction knows the destination vreg
1570 // to set, the condition code register to branch on, the true/false values to
1571 // select between, and a branch opcode to use.
1572 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1573 MachineFunction::iterator It = BB;
1579 // cmpTY ccX, r1, r2
1581 // fallthrough --> copy0MBB
1582 MachineBasicBlock *thisMBB = BB;
1583 MachineFunction *F = BB->getParent();
1584 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1585 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1586 F->insert(It, copy0MBB);
1587 F->insert(It, sinkMBB);
1589 // Transfer the remainder of BB and its successor edges to sinkMBB.
1590 sinkMBB->splice(sinkMBB->begin(), BB,
1591 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1592 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1594 // Next, add the true and fallthrough blocks as its successors.
1595 BB->addSuccessor(copy0MBB);
1596 BB->addSuccessor(sinkMBB);
1598 BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
1599 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
1602 // %FalseValue = ...
1603 // # fallthrough to sinkMBB
1606 // Update machine-CFG edges
1607 BB->addSuccessor(sinkMBB);
1610 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1613 BuildMI(*BB, BB->begin(), dl,
1614 TII.get(XCore::PHI), MI->getOperand(0).getReg())
1615 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
1616 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1618 MI->eraseFromParent(); // The pseudo instruction is gone now.
1622 //===----------------------------------------------------------------------===//
1623 // Target Optimization Hooks
1624 //===----------------------------------------------------------------------===//
1626 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1627 DAGCombinerInfo &DCI) const {
1628 SelectionDAG &DAG = DCI.DAG;
1630 switch (N->getOpcode()) {
1632 case ISD::INTRINSIC_VOID:
1633 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
1634 case Intrinsic::xcore_outt:
1635 case Intrinsic::xcore_outct:
1636 case Intrinsic::xcore_chkct: {
1637 SDValue OutVal = N->getOperand(3);
1638 // These instructions ignore the high bits.
1639 if (OutVal.hasOneUse()) {
1640 unsigned BitWidth = OutVal.getValueSizeInBits();
1641 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8);
1642 APInt KnownZero, KnownOne;
1643 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1644 !DCI.isBeforeLegalizeOps());
1645 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1646 if (TLO.ShrinkDemandedConstant(OutVal, DemandedMask) ||
1647 TLI.SimplifyDemandedBits(OutVal, DemandedMask, KnownZero, KnownOne,
1649 DCI.CommitTargetLoweringOpt(TLO);
1653 case Intrinsic::xcore_setpt: {
1654 SDValue Time = N->getOperand(3);
1655 // This instruction ignores the high bits.
1656 if (Time.hasOneUse()) {
1657 unsigned BitWidth = Time.getValueSizeInBits();
1658 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
1659 APInt KnownZero, KnownOne;
1660 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1661 !DCI.isBeforeLegalizeOps());
1662 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1663 if (TLO.ShrinkDemandedConstant(Time, DemandedMask) ||
1664 TLI.SimplifyDemandedBits(Time, DemandedMask, KnownZero, KnownOne,
1666 DCI.CommitTargetLoweringOpt(TLO);
1672 case XCoreISD::LADD: {
1673 SDValue N0 = N->getOperand(0);
1674 SDValue N1 = N->getOperand(1);
1675 SDValue N2 = N->getOperand(2);
1676 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1677 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1678 EVT VT = N0.getValueType();
1680 // canonicalize constant to RHS
1682 return DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N1, N0, N2);
1684 // fold (ladd 0, 0, x) -> 0, x & 1
1685 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1686 SDValue Carry = DAG.getConstant(0, VT);
1687 SDValue Result = DAG.getNode(ISD::AND, dl, VT, N2,
1688 DAG.getConstant(1, VT));
1689 SDValue Ops[] = { Result, Carry };
1690 return DAG.getMergeValues(Ops, dl);
1693 // fold (ladd x, 0, y) -> 0, add x, y iff carry is unused and y has only the
1695 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1696 APInt KnownZero, KnownOne;
1697 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1698 VT.getSizeInBits() - 1);
1699 DAG.computeKnownBits(N2, KnownZero, KnownOne);
1700 if ((KnownZero & Mask) == Mask) {
1701 SDValue Carry = DAG.getConstant(0, VT);
1702 SDValue Result = DAG.getNode(ISD::ADD, dl, VT, N0, N2);
1703 SDValue Ops[] = { Result, Carry };
1704 return DAG.getMergeValues(Ops, dl);
1709 case XCoreISD::LSUB: {
1710 SDValue N0 = N->getOperand(0);
1711 SDValue N1 = N->getOperand(1);
1712 SDValue N2 = N->getOperand(2);
1713 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1714 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1715 EVT VT = N0.getValueType();
1717 // fold (lsub 0, 0, x) -> x, -x iff x has only the low bit set
1718 if (N0C && N0C->isNullValue() && N1C && N1C->isNullValue()) {
1719 APInt KnownZero, KnownOne;
1720 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1721 VT.getSizeInBits() - 1);
1722 DAG.computeKnownBits(N2, KnownZero, KnownOne);
1723 if ((KnownZero & Mask) == Mask) {
1724 SDValue Borrow = N2;
1725 SDValue Result = DAG.getNode(ISD::SUB, dl, VT,
1726 DAG.getConstant(0, VT), N2);
1727 SDValue Ops[] = { Result, Borrow };
1728 return DAG.getMergeValues(Ops, dl);
1732 // fold (lsub x, 0, y) -> 0, sub x, y iff borrow is unused and y has only the
1734 if (N1C && N1C->isNullValue() && N->hasNUsesOfValue(0, 1)) {
1735 APInt KnownZero, KnownOne;
1736 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
1737 VT.getSizeInBits() - 1);
1738 DAG.computeKnownBits(N2, KnownZero, KnownOne);
1739 if ((KnownZero & Mask) == Mask) {
1740 SDValue Borrow = DAG.getConstant(0, VT);
1741 SDValue Result = DAG.getNode(ISD::SUB, dl, VT, N0, N2);
1742 SDValue Ops[] = { Result, Borrow };
1743 return DAG.getMergeValues(Ops, dl);
1748 case XCoreISD::LMUL: {
1749 SDValue N0 = N->getOperand(0);
1750 SDValue N1 = N->getOperand(1);
1751 SDValue N2 = N->getOperand(2);
1752 SDValue N3 = N->getOperand(3);
1753 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1754 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1755 EVT VT = N0.getValueType();
1756 // Canonicalize multiplicative constant to RHS. If both multiplicative
1757 // operands are constant canonicalize smallest to RHS.
1758 if ((N0C && !N1C) ||
1759 (N0C && N1C && N0C->getZExtValue() < N1C->getZExtValue()))
1760 return DAG.getNode(XCoreISD::LMUL, dl, DAG.getVTList(VT, VT),
1764 if (N1C && N1C->isNullValue()) {
1765 // If the high result is unused fold to add(a, b)
1766 if (N->hasNUsesOfValue(0, 0)) {
1767 SDValue Lo = DAG.getNode(ISD::ADD, dl, VT, N2, N3);
1768 SDValue Ops[] = { Lo, Lo };
1769 return DAG.getMergeValues(Ops, dl);
1771 // Otherwise fold to ladd(a, b, 0)
1773 DAG.getNode(XCoreISD::LADD, dl, DAG.getVTList(VT, VT), N2, N3, N1);
1774 SDValue Carry(Result.getNode(), 1);
1775 SDValue Ops[] = { Carry, Result };
1776 return DAG.getMergeValues(Ops, dl);
1781 // Fold 32 bit expressions such as add(add(mul(x,y),a),b) ->
1782 // lmul(x, y, a, b). The high result of lmul will be ignored.
1783 // This is only profitable if the intermediate results are unused
1785 SDValue Mul0, Mul1, Addend0, Addend1;
1786 if (N->getValueType(0) == MVT::i32 &&
1787 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, true)) {
1788 SDValue Ignored = DAG.getNode(XCoreISD::LMUL, dl,
1789 DAG.getVTList(MVT::i32, MVT::i32), Mul0,
1790 Mul1, Addend0, Addend1);
1791 SDValue Result(Ignored.getNode(), 1);
1794 APInt HighMask = APInt::getHighBitsSet(64, 32);
1795 // Fold 64 bit expression such as add(add(mul(x,y),a),b) ->
1796 // lmul(x, y, a, b) if all operands are zero-extended. We do this
1797 // before type legalization as it is messy to match the operands after
1799 if (N->getValueType(0) == MVT::i64 &&
1800 isADDADDMUL(SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, false) &&
1801 DAG.MaskedValueIsZero(Mul0, HighMask) &&
1802 DAG.MaskedValueIsZero(Mul1, HighMask) &&
1803 DAG.MaskedValueIsZero(Addend0, HighMask) &&
1804 DAG.MaskedValueIsZero(Addend1, HighMask)) {
1805 SDValue Mul0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1806 Mul0, DAG.getConstant(0, MVT::i32));
1807 SDValue Mul1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1808 Mul1, DAG.getConstant(0, MVT::i32));
1809 SDValue Addend0L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1810 Addend0, DAG.getConstant(0, MVT::i32));
1811 SDValue Addend1L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
1812 Addend1, DAG.getConstant(0, MVT::i32));
1813 SDValue Hi = DAG.getNode(XCoreISD::LMUL, dl,
1814 DAG.getVTList(MVT::i32, MVT::i32), Mul0L, Mul1L,
1815 Addend0L, Addend1L);
1816 SDValue Lo(Hi.getNode(), 1);
1817 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
1822 // Replace unaligned store of unaligned load with memmove.
1823 StoreSDNode *ST = cast<StoreSDNode>(N);
1824 if (!DCI.isBeforeLegalize() ||
1825 allowsUnalignedMemoryAccesses(ST->getMemoryVT()) ||
1826 ST->isVolatile() || ST->isIndexed()) {
1829 SDValue Chain = ST->getChain();
1831 unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1832 if (StoreBits % 8) {
1835 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(
1836 ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
1837 unsigned Alignment = ST->getAlignment();
1838 if (Alignment >= ABIAlignment) {
1842 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
1843 if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1844 LD->getAlignment() == Alignment &&
1845 !LD->isVolatile() && !LD->isIndexed() &&
1846 Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
1847 return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
1849 DAG.getConstant(StoreBits/8, MVT::i32),
1850 Alignment, false, ST->getPointerInfo(),
1851 LD->getPointerInfo());
1860 void XCoreTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
1863 const SelectionDAG &DAG,
1864 unsigned Depth) const {
1865 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
1866 switch (Op.getOpcode()) {
1868 case XCoreISD::LADD:
1869 case XCoreISD::LSUB:
1870 if (Op.getResNo() == 1) {
1871 // Top bits of carry / borrow are clear.
1872 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1873 KnownZero.getBitWidth() - 1);
1876 case ISD::INTRINSIC_W_CHAIN:
1878 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1880 case Intrinsic::xcore_getts:
1881 // High bits are known to be zero.
1882 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1883 KnownZero.getBitWidth() - 16);
1885 case Intrinsic::xcore_int:
1886 case Intrinsic::xcore_inct:
1887 // High bits are known to be zero.
1888 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1889 KnownZero.getBitWidth() - 8);
1891 case Intrinsic::xcore_testct:
1892 // Result is either 0 or 1.
1893 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1894 KnownZero.getBitWidth() - 1);
1896 case Intrinsic::xcore_testwct:
1897 // Result is in the range 0 - 4.
1898 KnownZero = APInt::getHighBitsSet(KnownZero.getBitWidth(),
1899 KnownZero.getBitWidth() - 3);
1907 //===----------------------------------------------------------------------===//
1908 // Addressing mode description hooks
1909 //===----------------------------------------------------------------------===//
1911 static inline bool isImmUs(int64_t val)
1913 return (val >= 0 && val <= 11);
1916 static inline bool isImmUs2(int64_t val)
1918 return (val%2 == 0 && isImmUs(val/2));
1921 static inline bool isImmUs4(int64_t val)
1923 return (val%4 == 0 && isImmUs(val/4));
1926 /// isLegalAddressingMode - Return true if the addressing mode represented
1927 /// by AM is legal for this target, for a load/store of the specified type.
1929 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1931 if (Ty->getTypeID() == Type::VoidTyID)
1932 return AM.Scale == 0 && isImmUs(AM.BaseOffs) && isImmUs4(AM.BaseOffs);
1934 const DataLayout *TD = TM.getDataLayout();
1935 unsigned Size = TD->getTypeAllocSize(Ty);
1937 return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1944 if (AM.Scale == 0) {
1945 return isImmUs(AM.BaseOffs);
1948 return AM.Scale == 1 && AM.BaseOffs == 0;
1952 if (AM.Scale == 0) {
1953 return isImmUs2(AM.BaseOffs);
1956 return AM.Scale == 2 && AM.BaseOffs == 0;
1959 if (AM.Scale == 0) {
1960 return isImmUs4(AM.BaseOffs);
1963 return AM.Scale == 4 && AM.BaseOffs == 0;
1967 //===----------------------------------------------------------------------===//
1968 // XCore Inline Assembly Support
1969 //===----------------------------------------------------------------------===//
1971 std::pair<unsigned, const TargetRegisterClass*>
1972 XCoreTargetLowering::
1973 getRegForInlineAsmConstraint(const std::string &Constraint,
1975 if (Constraint.size() == 1) {
1976 switch (Constraint[0]) {
1979 return std::make_pair(0U, &XCore::GRRegsRegClass);
1982 // Use the default implementation in TargetLowering to convert the register
1983 // constraint into a member of a register class.
1984 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);