1//===-- XCoreISelLowering.cpp - XCore DAG Lowering Implementation ---------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the XCoreTargetLowering class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "XCoreISelLowering.h"
14#include "XCore.h"
15#include "XCoreMachineFunctionInfo.h"
16#include "XCoreSubtarget.h"
17#include "XCoreTargetMachine.h"
18#include "XCoreTargetObjectFile.h"
19#include "llvm/CodeGen/CallingConvLower.h"
20#include "llvm/CodeGen/MachineFrameInfo.h"
21#include "llvm/CodeGen/MachineFunction.h"
22#include "llvm/CodeGen/MachineInstrBuilder.h"
23#include "llvm/CodeGen/MachineJumpTableInfo.h"
24#include "llvm/CodeGen/MachineRegisterInfo.h"
25#include "llvm/CodeGen/ValueTypes.h"
26#include "llvm/IR/CallingConv.h"
27#include "llvm/IR/Constants.h"
28#include "llvm/IR/DerivedTypes.h"
29#include "llvm/IR/Function.h"
30#include "llvm/IR/GlobalAlias.h"
31#include "llvm/IR/GlobalVariable.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/IntrinsicsXCore.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/Support/ErrorHandling.h"
36#include "llvm/Support/KnownBits.h"
37#include "llvm/Support/raw_ostream.h"
38#include <algorithm>
39
40using namespace llvm;
41
42#define DEBUG_TYPE "xcore-lower"
43
44const char *XCoreTargetLowering::
45getTargetNodeName(unsigned Opcode) const
46{
47 switch ((XCoreISD::NodeType)Opcode)
48 {
49 case XCoreISD::FIRST_NUMBER : break;
50 case XCoreISD::BL : return "XCoreISD::BL";
51 case XCoreISD::PCRelativeWrapper : return "XCoreISD::PCRelativeWrapper";
52 case XCoreISD::DPRelativeWrapper : return "XCoreISD::DPRelativeWrapper";
53 case XCoreISD::CPRelativeWrapper : return "XCoreISD::CPRelativeWrapper";
54 case XCoreISD::LDWSP : return "XCoreISD::LDWSP";
55 case XCoreISD::STWSP : return "XCoreISD::STWSP";
56 case XCoreISD::RETSP : return "XCoreISD::RETSP";
57 case XCoreISD::LADD : return "XCoreISD::LADD";
58 case XCoreISD::LSUB : return "XCoreISD::LSUB";
59 case XCoreISD::LMUL : return "XCoreISD::LMUL";
60 case XCoreISD::MACCU : return "XCoreISD::MACCU";
61 case XCoreISD::MACCS : return "XCoreISD::MACCS";
62 case XCoreISD::CRC8 : return "XCoreISD::CRC8";
63 case XCoreISD::BR_JT : return "XCoreISD::BR_JT";
64 case XCoreISD::BR_JT32 : return "XCoreISD::BR_JT32";
65 case XCoreISD::FRAME_TO_ARGS_OFFSET : return "XCoreISD::FRAME_TO_ARGS_OFFSET";
66 case XCoreISD::EH_RETURN : return "XCoreISD::EH_RETURN";
67 }
68 return nullptr;
69}
70
71XCoreTargetLowering::XCoreTargetLowering(const TargetMachine &TM,
72 const XCoreSubtarget &Subtarget)
73 : TargetLowering(TM), TM(TM), Subtarget(Subtarget) {
74
75 // Set up the register classes.
76 addRegisterClass(VT: MVT::i32, RC: &XCore::GRRegsRegClass);
77
78 // Compute derived properties from the register classes
79 computeRegisterProperties(TRI: Subtarget.getRegisterInfo());
80
81 setStackPointerRegisterToSaveRestore(XCore::SP);
82
83 setSchedulingPreference(Sched::Source);
84
85 // Use i32 for setcc operations results (slt, sgt, ...).
86 setBooleanContents(ZeroOrOneBooleanContent);
87 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
88
89 // XCore does not have the NodeTypes below.
90 setOperationAction(Op: ISD::BR_CC, VT: MVT::i32, Action: Expand);
91 setOperationAction(Op: ISD::SELECT_CC, VT: MVT::i32, Action: Expand);
92
93 // 64bit
94 setOperationAction(Op: ISD::ADD, VT: MVT::i64, Action: Custom);
95 setOperationAction(Op: ISD::SUB, VT: MVT::i64, Action: Custom);
96 setOperationAction(Op: ISD::SMUL_LOHI, VT: MVT::i32, Action: Custom);
97 setOperationAction(Op: ISD::UMUL_LOHI, VT: MVT::i32, Action: Custom);
98 setOperationAction(Op: ISD::MULHS, VT: MVT::i32, Action: Expand);
99 setOperationAction(Op: ISD::MULHU, VT: MVT::i32, Action: Expand);
100 setOperationAction(Op: ISD::SHL_PARTS, VT: MVT::i32, Action: Expand);
101 setOperationAction(Op: ISD::SRA_PARTS, VT: MVT::i32, Action: Expand);
102 setOperationAction(Op: ISD::SRL_PARTS, VT: MVT::i32, Action: Expand);
103
104 // Bit Manipulation
105 setOperationAction(Op: ISD::CTPOP, VT: MVT::i32, Action: Expand);
106 setOperationAction(Op: ISD::ROTL , VT: MVT::i32, Action: Expand);
107 setOperationAction(Op: ISD::ROTR , VT: MVT::i32, Action: Expand);
108 setOperationAction(Op: ISD::BITREVERSE , VT: MVT::i32, Action: Legal);
109
110 setOperationAction(Op: ISD::TRAP, VT: MVT::Other, Action: Legal);
111
112 // Jump tables.
113 setOperationAction(Op: ISD::BR_JT, VT: MVT::Other, Action: Custom);
114
115 setOperationAction(Op: ISD::GlobalAddress, VT: MVT::i32, Action: Custom);
116 setOperationAction(Op: ISD::BlockAddress, VT: MVT::i32 , Action: Custom);
117
118 // Conversion of i64 -> double produces constantpool nodes
119 setOperationAction(Op: ISD::ConstantPool, VT: MVT::i32, Action: Custom);
120
121 // Loads
122 for (MVT VT : MVT::integer_valuetypes()) {
123 setLoadExtAction(ExtType: ISD::EXTLOAD, ValVT: VT, MemVT: MVT::i1, Action: Promote);
124 setLoadExtAction(ExtType: ISD::ZEXTLOAD, ValVT: VT, MemVT: MVT::i1, Action: Promote);
125 setLoadExtAction(ExtType: ISD::SEXTLOAD, ValVT: VT, MemVT: MVT::i1, Action: Promote);
126
127 setLoadExtAction(ExtType: ISD::SEXTLOAD, ValVT: VT, MemVT: MVT::i8, Action: Expand);
128 setLoadExtAction(ExtType: ISD::ZEXTLOAD, ValVT: VT, MemVT: MVT::i16, Action: Expand);
129 }
130
131 // Custom expand misaligned loads / stores.
132 setOperationAction(Op: ISD::LOAD, VT: MVT::i32, Action: Custom);
133 setOperationAction(Op: ISD::STORE, VT: MVT::i32, Action: Custom);
134
135 // Varargs
136 setOperationAction(Op: ISD::VAEND, VT: MVT::Other, Action: Expand);
137 setOperationAction(Op: ISD::VACOPY, VT: MVT::Other, Action: Expand);
138 setOperationAction(Op: ISD::VAARG, VT: MVT::Other, Action: Custom);
139 setOperationAction(Op: ISD::VASTART, VT: MVT::Other, Action: Custom);
140
141 // Dynamic stack
142 setOperationAction(Op: ISD::STACKSAVE, VT: MVT::Other, Action: Expand);
143 setOperationAction(Op: ISD::STACKRESTORE, VT: MVT::Other, Action: Expand);
144 setOperationAction(Op: ISD::DYNAMIC_STACKALLOC, VT: MVT::i32, Action: Expand);
145
146 // Exception handling
147 setOperationAction(Op: ISD::EH_RETURN, VT: MVT::Other, Action: Custom);
148 setOperationAction(Op: ISD::FRAME_TO_ARGS_OFFSET, VT: MVT::i32, Action: Custom);
149
150 setOperationAction(Op: ISD::ATOMIC_FENCE, VT: MVT::Other, Action: Custom);
151
152 // TRAMPOLINE is custom lowered.
153 setOperationAction(Op: ISD::INIT_TRAMPOLINE, VT: MVT::Other, Action: Custom);
154 setOperationAction(Op: ISD::ADJUST_TRAMPOLINE, VT: MVT::Other, Action: Custom);
155
156 // We want to custom lower some of our intrinsics.
157 setOperationAction(Op: ISD::INTRINSIC_WO_CHAIN, VT: MVT::Other, Action: Custom);
158
159 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 4;
160 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize
161 = MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 2;
162
163 // We have target-specific dag combine patterns for the following nodes:
164 setTargetDAGCombine(
165 {ISD::STORE, ISD::ADD, ISD::INTRINSIC_VOID, ISD::INTRINSIC_W_CHAIN});
166
167 setMinFunctionAlignment(Align(2));
168 setPrefFunctionAlignment(Align(4));
169
170 // This target doesn't implement native atomics.
171 setMaxAtomicSizeInBitsSupported(0);
172}
173
174bool XCoreTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
175 if (Val.getOpcode() != ISD::LOAD)
176 return false;
177
178 EVT VT1 = Val.getValueType();
179 if (!VT1.isSimple() || !VT1.isInteger() ||
180 !VT2.isSimple() || !VT2.isInteger())
181 return false;
182
183 switch (VT1.getSimpleVT().SimpleTy) {
184 default: break;
185 case MVT::i8:
186 return true;
187 }
188
189 return false;
190}
191
192SDValue XCoreTargetLowering::
193LowerOperation(SDValue Op, SelectionDAG &DAG) const {
194 switch (Op.getOpcode())
195 {
196 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
197 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
198 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
199 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
200 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
201 case ISD::LOAD: return LowerLOAD(Op, DAG);
202 case ISD::STORE: return LowerSTORE(Op, DAG);
203 case ISD::VAARG: return LowerVAARG(Op, DAG);
204 case ISD::VASTART: return LowerVASTART(Op, DAG);
205 case ISD::SMUL_LOHI: return LowerSMUL_LOHI(Op, DAG);
206 case ISD::UMUL_LOHI: return LowerUMUL_LOHI(Op, DAG);
207 // FIXME: Remove these when LegalizeDAGTypes lands.
208 case ISD::ADD:
209 case ISD::SUB: return ExpandADDSUB(Op: Op.getNode(), DAG);
210 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
211 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
212 case ISD::FRAME_TO_ARGS_OFFSET: return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
213 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
214 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
215 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
216 case ISD::ATOMIC_FENCE:
217 return LowerATOMIC_FENCE(Op, DAG);
218 default:
219 llvm_unreachable("unimplemented operand");
220 }
221}
222
223/// ReplaceNodeResults - Replace the results of node with an illegal result
224/// type with new values built out of custom code.
225void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
226 SmallVectorImpl<SDValue>&Results,
227 SelectionDAG &DAG) const {
228 switch (N->getOpcode()) {
229 default:
230 llvm_unreachable("Don't know how to custom expand this!");
231 case ISD::ADD:
232 case ISD::SUB:
233 Results.push_back(Elt: ExpandADDSUB(Op: N, DAG));
234 return;
235 }
236}
237
238//===----------------------------------------------------------------------===//
239// Misc Lower Operation implementation
240//===----------------------------------------------------------------------===//
241
242SDValue XCoreTargetLowering::getGlobalAddressWrapper(SDValue GA,
243 const GlobalValue *GV,
244 SelectionDAG &DAG) const {
245 // FIXME there is no actual debug info here
246 SDLoc dl(GA);
247
248 if (GV->getValueType()->isFunctionTy())
249 return DAG.getNode(Opcode: XCoreISD::PCRelativeWrapper, DL: dl, VT: MVT::i32, Operand: GA);
250
251 const auto *GVar = dyn_cast<GlobalVariable>(Val: GV);
252 if ((GV->hasSection() && GV->getSection().starts_with(Prefix: ".cp.")) ||
253 (GVar && GVar->isConstant() && GV->hasLocalLinkage()))
254 return DAG.getNode(Opcode: XCoreISD::CPRelativeWrapper, DL: dl, VT: MVT::i32, Operand: GA);
255
256 return DAG.getNode(Opcode: XCoreISD::DPRelativeWrapper, DL: dl, VT: MVT::i32, Operand: GA);
257}
258
259static bool IsSmallObject(const GlobalValue *GV, const XCoreTargetLowering &XTL) {
260 if (XTL.getTargetMachine().getCodeModel() == CodeModel::Small)
261 return true;
262
263 Type *ObjType = GV->getValueType();
264 if (!ObjType->isSized())
265 return false;
266
267 auto &DL = GV->getDataLayout();
268 unsigned ObjSize = DL.getTypeAllocSize(Ty: ObjType);
269 return ObjSize < CodeModelLargeSize && ObjSize != 0;
270}
271
272SDValue XCoreTargetLowering::
273LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const
274{
275 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Val&: Op);
276 const GlobalValue *GV = GN->getGlobal();
277 SDLoc DL(GN);
278 int64_t Offset = GN->getOffset();
279 if (IsSmallObject(GV, XTL: *this)) {
280 // We can only fold positive offsets that are a multiple of the word size.
281 int64_t FoldedOffset = std::max(a: Offset & ~3, b: (int64_t)0);
282 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, VT: MVT::i32, offset: FoldedOffset);
283 GA = getGlobalAddressWrapper(GA, GV, DAG);
284 // Handle the rest of the offset.
285 if (Offset != FoldedOffset) {
286 SDValue Remaining = DAG.getConstant(Val: Offset - FoldedOffset, DL, VT: MVT::i32);
287 GA = DAG.getNode(Opcode: ISD::ADD, DL, VT: MVT::i32, N1: GA, N2: Remaining);
288 }
289 return GA;
290 } else {
291 // Ideally we would not fold in offset with an index <= 11.
292 Type *Ty = Type::getInt32Ty(C&: *DAG.getContext());
293 Constant *Idx = ConstantInt::get(Ty, V: Offset);
294 Constant *GAI = ConstantExpr::getGetElementPtr(
295 Ty: Type::getInt8Ty(C&: *DAG.getContext()), C: const_cast<GlobalValue *>(GV), Idx);
296 SDValue CP = DAG.getConstantPool(C: GAI, VT: MVT::i32);
297 return DAG.getLoad(VT: getPointerTy(DL: DAG.getDataLayout()), dl: DL,
298 Chain: DAG.getEntryNode(), Ptr: CP, PtrInfo: MachinePointerInfo());
299 }
300}
301
302SDValue XCoreTargetLowering::
303LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const
304{
305 SDLoc DL(Op);
306 auto PtrVT = getPointerTy(DL: DAG.getDataLayout());
307 const BlockAddress *BA = cast<BlockAddressSDNode>(Val&: Op)->getBlockAddress();
308 SDValue Result = DAG.getTargetBlockAddress(BA, VT: PtrVT);
309
310 return DAG.getNode(Opcode: XCoreISD::PCRelativeWrapper, DL, VT: PtrVT, Operand: Result);
311}
312
313SDValue XCoreTargetLowering::
314LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
315{
316 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Val&: Op);
317 // FIXME there isn't really debug info here
318 SDLoc dl(CP);
319 EVT PtrVT = Op.getValueType();
320 SDValue Res;
321 if (CP->isMachineConstantPoolEntry()) {
322 Res = DAG.getTargetConstantPool(C: CP->getMachineCPVal(), VT: PtrVT,
323 Align: CP->getAlign(), Offset: CP->getOffset());
324 } else {
325 Res = DAG.getTargetConstantPool(C: CP->getConstVal(), VT: PtrVT, Align: CP->getAlign(),
326 Offset: CP->getOffset());
327 }
328 return DAG.getNode(Opcode: XCoreISD::CPRelativeWrapper, DL: dl, VT: MVT::i32, Operand: Res);
329}
330
331unsigned XCoreTargetLowering::getJumpTableEncoding() const {
332 return MachineJumpTableInfo::EK_Inline;
333}
334
335SDValue XCoreTargetLowering::
336LowerBR_JT(SDValue Op, SelectionDAG &DAG) const
337{
338 SDValue Chain = Op.getOperand(i: 0);
339 SDValue Table = Op.getOperand(i: 1);
340 SDValue Index = Op.getOperand(i: 2);
341 SDLoc dl(Op);
342 JumpTableSDNode *JT = cast<JumpTableSDNode>(Val&: Table);
343 unsigned JTI = JT->getIndex();
344 MachineFunction &MF = DAG.getMachineFunction();
345 const MachineJumpTableInfo *MJTI = MF.getJumpTableInfo();
346 SDValue TargetJT = DAG.getTargetJumpTable(JTI: JT->getIndex(), VT: MVT::i32);
347
348 unsigned NumEntries = MJTI->getJumpTables()[JTI].MBBs.size();
349 if (NumEntries <= 32) {
350 return DAG.getNode(Opcode: XCoreISD::BR_JT, DL: dl, VT: MVT::Other, N1: Chain, N2: TargetJT, N3: Index);
351 }
352 assert((NumEntries >> 31) == 0);
353 SDValue ScaledIndex = DAG.getNode(Opcode: ISD::SHL, DL: dl, VT: MVT::i32, N1: Index,
354 N2: DAG.getConstant(Val: 1, DL: dl, VT: MVT::i32));
355 return DAG.getNode(Opcode: XCoreISD::BR_JT32, DL: dl, VT: MVT::Other, N1: Chain, N2: TargetJT,
356 N3: ScaledIndex);
357}
358
359SDValue XCoreTargetLowering::lowerLoadWordFromAlignedBasePlusOffset(
360 const SDLoc &DL, SDValue Chain, SDValue Base, int64_t Offset,
361 SelectionDAG &DAG) const {
362 auto PtrVT = getPointerTy(DL: DAG.getDataLayout());
363 if ((Offset & 0x3) == 0) {
364 return DAG.getLoad(VT: PtrVT, dl: DL, Chain, Ptr: Base, PtrInfo: MachinePointerInfo());
365 }
366 // Lower to pair of consecutive word aligned loads plus some bit shifting.
367 int32_t HighOffset = alignTo(Value: Offset, Align: 4);
368 int32_t LowOffset = HighOffset - 4;
369 SDValue LowAddr, HighAddr;
370 if (GlobalAddressSDNode *GASD =
371 dyn_cast<GlobalAddressSDNode>(Val: Base.getNode())) {
372 LowAddr = DAG.getGlobalAddress(GV: GASD->getGlobal(), DL, VT: Base.getValueType(),
373 offset: LowOffset);
374 HighAddr = DAG.getGlobalAddress(GV: GASD->getGlobal(), DL, VT: Base.getValueType(),
375 offset: HighOffset);
376 } else {
377 LowAddr = DAG.getNode(Opcode: ISD::ADD, DL, VT: MVT::i32, N1: Base,
378 N2: DAG.getConstant(Val: LowOffset, DL, VT: MVT::i32));
379 HighAddr = DAG.getNode(Opcode: ISD::ADD, DL, VT: MVT::i32, N1: Base,
380 N2: DAG.getConstant(Val: HighOffset, DL, VT: MVT::i32));
381 }
382 SDValue LowShift = DAG.getConstant(Val: (Offset - LowOffset) * 8, DL, VT: MVT::i32);
383 SDValue HighShift = DAG.getConstant(Val: (HighOffset - Offset) * 8, DL, VT: MVT::i32);
384
385 SDValue Low = DAG.getLoad(VT: PtrVT, dl: DL, Chain, Ptr: LowAddr, PtrInfo: MachinePointerInfo());
386 SDValue High = DAG.getLoad(VT: PtrVT, dl: DL, Chain, Ptr: HighAddr, PtrInfo: MachinePointerInfo());
387 SDValue LowShifted = DAG.getNode(Opcode: ISD::SRL, DL, VT: MVT::i32, N1: Low, N2: LowShift);
388 SDValue HighShifted = DAG.getNode(Opcode: ISD::SHL, DL, VT: MVT::i32, N1: High, N2: HighShift);
389 SDValue Result = DAG.getNode(Opcode: ISD::OR, DL, VT: MVT::i32, N1: LowShifted, N2: HighShifted);
390 Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL, VT: MVT::Other, N1: Low.getValue(R: 1),
391 N2: High.getValue(R: 1));
392 SDValue Ops[] = { Result, Chain };
393 return DAG.getMergeValues(Ops, dl: DL);
394}
395
396static bool isWordAligned(SDValue Value, SelectionDAG &DAG)
397{
398 KnownBits Known = DAG.computeKnownBits(Op: Value);
399 return Known.countMinTrailingZeros() >= 2;
400}
401
402SDValue XCoreTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
403 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
404 LLVMContext &Context = *DAG.getContext();
405 LoadSDNode *LD = cast<LoadSDNode>(Val&: Op);
406 assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
407 "Unexpected extension type");
408 assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
409
410 if (allowsMemoryAccessForAlignment(Context, DL: DAG.getDataLayout(),
411 VT: LD->getMemoryVT(), MMO: *LD->getMemOperand()))
412 return SDValue();
413
414 SDValue Chain = LD->getChain();
415 SDValue BasePtr = LD->getBasePtr();
416 SDLoc DL(Op);
417
418 if (!LD->isVolatile()) {
419 const GlobalValue *GV;
420 int64_t Offset = 0;
421 if (DAG.isBaseWithConstantOffset(Op: BasePtr) &&
422 isWordAligned(Value: BasePtr->getOperand(Num: 0), DAG)) {
423 SDValue NewBasePtr = BasePtr->getOperand(Num: 0);
424 Offset = cast<ConstantSDNode>(Val: BasePtr->getOperand(Num: 1))->getSExtValue();
425 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, Base: NewBasePtr,
426 Offset, DAG);
427 }
428 if (TLI.isGAPlusOffset(N: BasePtr.getNode(), GA&: GV, Offset) &&
429 GV->getPointerAlignment(DL: DAG.getDataLayout()) >= 4) {
430 SDValue NewBasePtr = DAG.getGlobalAddress(GV, DL,
431 VT: BasePtr->getValueType(ResNo: 0));
432 return lowerLoadWordFromAlignedBasePlusOffset(DL, Chain, Base: NewBasePtr,
433 Offset, DAG);
434 }
435 }
436
437 if (LD->getAlign() == Align(2)) {
438 SDValue Low = DAG.getExtLoad(ExtType: ISD::ZEXTLOAD, dl: DL, VT: MVT::i32, Chain, Ptr: BasePtr,
439 PtrInfo: LD->getPointerInfo(), MemVT: MVT::i16, Alignment: Align(2),
440 MMOFlags: LD->getMemOperand()->getFlags());
441 SDValue HighAddr = DAG.getNode(Opcode: ISD::ADD, DL, VT: MVT::i32, N1: BasePtr,
442 N2: DAG.getConstant(Val: 2, DL, VT: MVT::i32));
443 SDValue High =
444 DAG.getExtLoad(ExtType: ISD::EXTLOAD, dl: DL, VT: MVT::i32, Chain, Ptr: HighAddr,
445 PtrInfo: LD->getPointerInfo().getWithOffset(O: 2), MemVT: MVT::i16,
446 Alignment: Align(2), MMOFlags: LD->getMemOperand()->getFlags());
447 SDValue HighShifted = DAG.getNode(Opcode: ISD::SHL, DL, VT: MVT::i32, N1: High,
448 N2: DAG.getConstant(Val: 16, DL, VT: MVT::i32));
449 SDValue Result = DAG.getNode(Opcode: ISD::OR, DL, VT: MVT::i32, N1: Low, N2: HighShifted);
450 Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL, VT: MVT::Other, N1: Low.getValue(R: 1),
451 N2: High.getValue(R: 1));
452 SDValue Ops[] = { Result, Chain };
453 return DAG.getMergeValues(Ops, dl: DL);
454 }
455
456 // Lower to a call to __misaligned_load(BasePtr).
457 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(C&: Context);
458 TargetLowering::ArgListTy Args;
459 TargetLowering::ArgListEntry Entry;
460
461 Entry.Ty = IntPtrTy;
462 Entry.Node = BasePtr;
463 Args.push_back(x: Entry);
464
465 TargetLowering::CallLoweringInfo CLI(DAG);
466 CLI.setDebugLoc(DL).setChain(Chain).setLibCallee(
467 CC: CallingConv::C, ResultType: IntPtrTy,
468 Target: DAG.getExternalSymbol(Sym: "__misaligned_load",
469 VT: getPointerTy(DL: DAG.getDataLayout())),
470 ArgsList: std::move(Args));
471
472 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
473 SDValue Ops[] = { CallResult.first, CallResult.second };
474 return DAG.getMergeValues(Ops, dl: DL);
475}
476
477SDValue XCoreTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
478 LLVMContext &Context = *DAG.getContext();
479 StoreSDNode *ST = cast<StoreSDNode>(Val&: Op);
480 assert(!ST->isTruncatingStore() && "Unexpected store type");
481 assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
482
483 if (allowsMemoryAccessForAlignment(Context, DL: DAG.getDataLayout(),
484 VT: ST->getMemoryVT(), MMO: *ST->getMemOperand()))
485 return SDValue();
486
487 SDValue Chain = ST->getChain();
488 SDValue BasePtr = ST->getBasePtr();
489 SDValue Value = ST->getValue();
490 SDLoc dl(Op);
491
492 if (ST->getAlign() == Align(2)) {
493 SDValue Low = Value;
494 SDValue High = DAG.getNode(Opcode: ISD::SRL, DL: dl, VT: MVT::i32, N1: Value,
495 N2: DAG.getConstant(Val: 16, DL: dl, VT: MVT::i32));
496 SDValue StoreLow =
497 DAG.getTruncStore(Chain, dl, Val: Low, Ptr: BasePtr, PtrInfo: ST->getPointerInfo(),
498 SVT: MVT::i16, Alignment: Align(2), MMOFlags: ST->getMemOperand()->getFlags());
499 SDValue HighAddr = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: MVT::i32, N1: BasePtr,
500 N2: DAG.getConstant(Val: 2, DL: dl, VT: MVT::i32));
501 SDValue StoreHigh = DAG.getTruncStore(
502 Chain, dl, Val: High, Ptr: HighAddr, PtrInfo: ST->getPointerInfo().getWithOffset(O: 2),
503 SVT: MVT::i16, Alignment: Align(2), MMOFlags: ST->getMemOperand()->getFlags());
504 return DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other, N1: StoreLow, N2: StoreHigh);
505 }
506
507 // Lower to a call to __misaligned_store(BasePtr, Value).
508 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(C&: Context);
509 TargetLowering::ArgListTy Args;
510 TargetLowering::ArgListEntry Entry;
511
512 Entry.Ty = IntPtrTy;
513 Entry.Node = BasePtr;
514 Args.push_back(x: Entry);
515
516 Entry.Node = Value;
517 Args.push_back(x: Entry);
518
519 TargetLowering::CallLoweringInfo CLI(DAG);
520 CLI.setDebugLoc(dl).setChain(Chain).setCallee(
521 CC: CallingConv::C, ResultType: Type::getVoidTy(C&: Context),
522 Target: DAG.getExternalSymbol(Sym: "__misaligned_store",
523 VT: getPointerTy(DL: DAG.getDataLayout())),
524 ArgsList: std::move(Args));
525
526 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
527 return CallResult.second;
528}
529
530SDValue XCoreTargetLowering::
531LowerSMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
532{
533 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::SMUL_LOHI &&
534 "Unexpected operand to lower!");
535 SDLoc dl(Op);
536 SDValue LHS = Op.getOperand(i: 0);
537 SDValue RHS = Op.getOperand(i: 1);
538 SDValue Zero = DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32);
539 SDValue Hi = DAG.getNode(Opcode: XCoreISD::MACCS, DL: dl,
540 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32), N1: Zero, N2: Zero,
541 N3: LHS, N4: RHS);
542 SDValue Lo(Hi.getNode(), 1);
543 SDValue Ops[] = { Lo, Hi };
544 return DAG.getMergeValues(Ops, dl);
545}
546
547SDValue XCoreTargetLowering::
548LowerUMUL_LOHI(SDValue Op, SelectionDAG &DAG) const
549{
550 assert(Op.getValueType() == MVT::i32 && Op.getOpcode() == ISD::UMUL_LOHI &&
551 "Unexpected operand to lower!");
552 SDLoc dl(Op);
553 SDValue LHS = Op.getOperand(i: 0);
554 SDValue RHS = Op.getOperand(i: 1);
555 SDValue Zero = DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32);
556 SDValue Hi = DAG.getNode(Opcode: XCoreISD::LMUL, DL: dl,
557 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32), N1: LHS, N2: RHS,
558 N3: Zero, N4: Zero);
559 SDValue Lo(Hi.getNode(), 1);
560 SDValue Ops[] = { Lo, Hi };
561 return DAG.getMergeValues(Ops, dl);
562}
563
564/// isADDADDMUL - Return whether Op is in a form that is equivalent to
565/// add(add(mul(x,y),a),b). If requireIntermediatesHaveOneUse is true then
566/// each intermediate result in the calculation must also have a single use.
567/// If the Op is in the correct form the constituent parts are written to Mul0,
568/// Mul1, Addend0 and Addend1.
569static bool
570isADDADDMUL(SDValue Op, SDValue &Mul0, SDValue &Mul1, SDValue &Addend0,
571 SDValue &Addend1, bool requireIntermediatesHaveOneUse)
572{
573 if (Op.getOpcode() != ISD::ADD)
574 return false;
575 SDValue N0 = Op.getOperand(i: 0);
576 SDValue N1 = Op.getOperand(i: 1);
577 SDValue AddOp;
578 SDValue OtherOp;
579 if (N0.getOpcode() == ISD::ADD) {
580 AddOp = N0;
581 OtherOp = N1;
582 } else if (N1.getOpcode() == ISD::ADD) {
583 AddOp = N1;
584 OtherOp = N0;
585 } else {
586 return false;
587 }
588 if (requireIntermediatesHaveOneUse && !AddOp.hasOneUse())
589 return false;
590 if (OtherOp.getOpcode() == ISD::MUL) {
591 // add(add(a,b),mul(x,y))
592 if (requireIntermediatesHaveOneUse && !OtherOp.hasOneUse())
593 return false;
594 Mul0 = OtherOp.getOperand(i: 0);
595 Mul1 = OtherOp.getOperand(i: 1);
596 Addend0 = AddOp.getOperand(i: 0);
597 Addend1 = AddOp.getOperand(i: 1);
598 return true;
599 }
600 if (AddOp.getOperand(i: 0).getOpcode() == ISD::MUL) {
601 // add(add(mul(x,y),a),b)
602 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(i: 0).hasOneUse())
603 return false;
604 Mul0 = AddOp.getOperand(i: 0).getOperand(i: 0);
605 Mul1 = AddOp.getOperand(i: 0).getOperand(i: 1);
606 Addend0 = AddOp.getOperand(i: 1);
607 Addend1 = OtherOp;
608 return true;
609 }
610 if (AddOp.getOperand(i: 1).getOpcode() == ISD::MUL) {
611 // add(add(a,mul(x,y)),b)
612 if (requireIntermediatesHaveOneUse && !AddOp.getOperand(i: 1).hasOneUse())
613 return false;
614 Mul0 = AddOp.getOperand(i: 1).getOperand(i: 0);
615 Mul1 = AddOp.getOperand(i: 1).getOperand(i: 1);
616 Addend0 = AddOp.getOperand(i: 0);
617 Addend1 = OtherOp;
618 return true;
619 }
620 return false;
621}
622
623SDValue XCoreTargetLowering::
624TryExpandADDWithMul(SDNode *N, SelectionDAG &DAG) const
625{
626 SDValue Mul;
627 SDValue Other;
628 if (N->getOperand(Num: 0).getOpcode() == ISD::MUL) {
629 Mul = N->getOperand(Num: 0);
630 Other = N->getOperand(Num: 1);
631 } else if (N->getOperand(Num: 1).getOpcode() == ISD::MUL) {
632 Mul = N->getOperand(Num: 1);
633 Other = N->getOperand(Num: 0);
634 } else {
635 return SDValue();
636 }
637 SDLoc dl(N);
638 SDValue LL, RL, AddendL, AddendH;
639 LL = DAG.getNode(Opcode: ISD::EXTRACT_ELEMENT, DL: dl, VT: MVT::i32,
640 N1: Mul.getOperand(i: 0), N2: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
641 RL = DAG.getNode(Opcode: ISD::EXTRACT_ELEMENT, DL: dl, VT: MVT::i32,
642 N1: Mul.getOperand(i: 1), N2: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
643 AddendL = DAG.getNode(Opcode: ISD::EXTRACT_ELEMENT, DL: dl, VT: MVT::i32,
644 N1: Other, N2: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
645 AddendH = DAG.getNode(Opcode: ISD::EXTRACT_ELEMENT, DL: dl, VT: MVT::i32,
646 N1: Other, N2: DAG.getConstant(Val: 1, DL: dl, VT: MVT::i32));
647 APInt HighMask = APInt::getHighBitsSet(numBits: 64, hiBitsSet: 32);
648 unsigned LHSSB = DAG.ComputeNumSignBits(Op: Mul.getOperand(i: 0));
649 unsigned RHSSB = DAG.ComputeNumSignBits(Op: Mul.getOperand(i: 1));
650 if (DAG.MaskedValueIsZero(Op: Mul.getOperand(i: 0), Mask: HighMask) &&
651 DAG.MaskedValueIsZero(Op: Mul.getOperand(i: 1), Mask: HighMask)) {
652 // The inputs are both zero-extended.
653 SDValue Hi = DAG.getNode(Opcode: XCoreISD::MACCU, DL: dl,
654 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32), N1: AddendH,
655 N2: AddendL, N3: LL, N4: RL);
656 SDValue Lo(Hi.getNode(), 1);
657 return DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT: MVT::i64, N1: Lo, N2: Hi);
658 }
659 if (LHSSB > 32 && RHSSB > 32) {
660 // The inputs are both sign-extended.
661 SDValue Hi = DAG.getNode(Opcode: XCoreISD::MACCS, DL: dl,
662 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32), N1: AddendH,
663 N2: AddendL, N3: LL, N4: RL);
664 SDValue Lo(Hi.getNode(), 1);
665 return DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT: MVT::i64, N1: Lo, N2: Hi);
666 }
667 SDValue LH, RH;
668 LH = DAG.getNode(Opcode: ISD::EXTRACT_ELEMENT, DL: dl, VT: MVT::i32,
669 N1: Mul.getOperand(i: 0), N2: DAG.getConstant(Val: 1, DL: dl, VT: MVT::i32));
670 RH = DAG.getNode(Opcode: ISD::EXTRACT_ELEMENT, DL: dl, VT: MVT::i32,
671 N1: Mul.getOperand(i: 1), N2: DAG.getConstant(Val: 1, DL: dl, VT: MVT::i32));
672 SDValue Hi = DAG.getNode(Opcode: XCoreISD::MACCU, DL: dl,
673 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32), N1: AddendH,
674 N2: AddendL, N3: LL, N4: RL);
675 SDValue Lo(Hi.getNode(), 1);
676 RH = DAG.getNode(Opcode: ISD::MUL, DL: dl, VT: MVT::i32, N1: LL, N2: RH);
677 LH = DAG.getNode(Opcode: ISD::MUL, DL: dl, VT: MVT::i32, N1: LH, N2: RL);
678 Hi = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: MVT::i32, N1: Hi, N2: RH);
679 Hi = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: MVT::i32, N1: Hi, N2: LH);
680 return DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT: MVT::i64, N1: Lo, N2: Hi);
681}
682
683SDValue XCoreTargetLowering::
684ExpandADDSUB(SDNode *N, SelectionDAG &DAG) const
685{
686 assert(N->getValueType(0) == MVT::i64 &&
687 (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
688 "Unknown operand to lower!");
689
690 if (N->getOpcode() == ISD::ADD)
691 if (SDValue Result = TryExpandADDWithMul(N, DAG))
692 return Result;
693
694 SDLoc dl(N);
695
696 // Extract components
697 SDValue LHSL = DAG.getNode(Opcode: ISD::EXTRACT_ELEMENT, DL: dl, VT: MVT::i32,
698 N1: N->getOperand(Num: 0),
699 N2: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
700 SDValue LHSH = DAG.getNode(Opcode: ISD::EXTRACT_ELEMENT, DL: dl, VT: MVT::i32,
701 N1: N->getOperand(Num: 0),
702 N2: DAG.getConstant(Val: 1, DL: dl, VT: MVT::i32));
703 SDValue RHSL = DAG.getNode(Opcode: ISD::EXTRACT_ELEMENT, DL: dl, VT: MVT::i32,
704 N1: N->getOperand(Num: 1),
705 N2: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
706 SDValue RHSH = DAG.getNode(Opcode: ISD::EXTRACT_ELEMENT, DL: dl, VT: MVT::i32,
707 N1: N->getOperand(Num: 1),
708 N2: DAG.getConstant(Val: 1, DL: dl, VT: MVT::i32));
709
710 // Expand
711 unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
712 XCoreISD::LSUB;
713 SDValue Zero = DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32);
714 SDValue Lo = DAG.getNode(Opcode, DL: dl, VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32),
715 N1: LHSL, N2: RHSL, N3: Zero);
716 SDValue Carry(Lo.getNode(), 1);
717
718 SDValue Hi = DAG.getNode(Opcode, DL: dl, VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32),
719 N1: LHSH, N2: RHSH, N3: Carry);
720 SDValue Ignored(Hi.getNode(), 1);
721 // Merge the pieces
722 return DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT: MVT::i64, N1: Lo, N2: Hi);
723}
724
725SDValue XCoreTargetLowering::
726LowerVAARG(SDValue Op, SelectionDAG &DAG) const
727{
728 // Whist llvm does not support aggregate varargs we can ignore
729 // the possibility of the ValueType being an implicit byVal vararg.
730 SDNode *Node = Op.getNode();
731 EVT VT = Node->getValueType(ResNo: 0); // not an aggregate
732 SDValue InChain = Node->getOperand(Num: 0);
733 SDValue VAListPtr = Node->getOperand(Num: 1);
734 EVT PtrVT = VAListPtr.getValueType();
735 const Value *SV = cast<SrcValueSDNode>(Val: Node->getOperand(Num: 2))->getValue();
736 SDLoc dl(Node);
737 SDValue VAList =
738 DAG.getLoad(VT: PtrVT, dl, Chain: InChain, Ptr: VAListPtr, PtrInfo: MachinePointerInfo(SV));
739 // Increment the pointer, VAList, to the next vararg
740 SDValue nextPtr = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: PtrVT, N1: VAList,
741 N2: DAG.getIntPtrConstant(Val: VT.getSizeInBits() / 8,
742 DL: dl));
743 // Store the incremented VAList to the legalized pointer
744 InChain = DAG.getStore(Chain: VAList.getValue(R: 1), dl, Val: nextPtr, Ptr: VAListPtr,
745 PtrInfo: MachinePointerInfo(SV));
746 // Load the actual argument out of the pointer VAList
747 return DAG.getLoad(VT, dl, Chain: InChain, Ptr: VAList, PtrInfo: MachinePointerInfo());
748}
749
750SDValue XCoreTargetLowering::
751LowerVASTART(SDValue Op, SelectionDAG &DAG) const
752{
753 SDLoc dl(Op);
754 // vastart stores the address of the VarArgsFrameIndex slot into the
755 // memory location argument
756 MachineFunction &MF = DAG.getMachineFunction();
757 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
758 SDValue Addr = DAG.getFrameIndex(FI: XFI->getVarArgsFrameIndex(), VT: MVT::i32);
759 return DAG.getStore(Chain: Op.getOperand(i: 0), dl, Val: Addr, Ptr: Op.getOperand(i: 1),
760 PtrInfo: MachinePointerInfo());
761}
762
763SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op,
764 SelectionDAG &DAG) const {
765 // This nodes represent llvm.frameaddress on the DAG.
766 // It takes one operand, the index of the frame address to return.
767 // An index of zero corresponds to the current function's frame address.
768 // An index of one to the parent's frame address, and so on.
769 // Depths > 0 not supported yet!
770 if (Op.getConstantOperandVal(i: 0) > 0)
771 return SDValue();
772
773 MachineFunction &MF = DAG.getMachineFunction();
774 const TargetRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
775 return DAG.getCopyFromReg(Chain: DAG.getEntryNode(), dl: SDLoc(Op),
776 Reg: RegInfo->getFrameRegister(MF), VT: MVT::i32);
777}
778
779SDValue XCoreTargetLowering::
780LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const {
781 // This nodes represent llvm.returnaddress on the DAG.
782 // It takes one operand, the index of the return address to return.
783 // An index of zero corresponds to the current function's return address.
784 // An index of one to the parent's return address, and so on.
785 // Depths > 0 not supported yet!
786 if (Op.getConstantOperandVal(i: 0) > 0)
787 return SDValue();
788
789 MachineFunction &MF = DAG.getMachineFunction();
790 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
791 int FI = XFI->createLRSpillSlot(MF);
792 SDValue FIN = DAG.getFrameIndex(FI, VT: MVT::i32);
793 return DAG.getLoad(VT: getPointerTy(DL: DAG.getDataLayout()), dl: SDLoc(Op),
794 Chain: DAG.getEntryNode(), Ptr: FIN,
795 PtrInfo: MachinePointerInfo::getFixedStack(MF, FI));
796}
797
798SDValue XCoreTargetLowering::
799LowerFRAME_TO_ARGS_OFFSET(SDValue Op, SelectionDAG &DAG) const {
800 // This node represents offset from frame pointer to first on-stack argument.
801 // This is needed for correct stack adjustment during unwind.
802 // However, we don't know the offset until after the frame has be finalised.
803 // This is done during the XCoreFTAOElim pass.
804 return DAG.getNode(Opcode: XCoreISD::FRAME_TO_ARGS_OFFSET, DL: SDLoc(Op), VT: MVT::i32);
805}
806
807SDValue XCoreTargetLowering::
808LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
809 // OUTCHAIN = EH_RETURN(INCHAIN, OFFSET, HANDLER)
810 // This node represents 'eh_return' gcc dwarf builtin, which is used to
811 // return from exception. The general meaning is: adjust stack by OFFSET and
812 // pass execution to HANDLER.
813 MachineFunction &MF = DAG.getMachineFunction();
814 SDValue Chain = Op.getOperand(i: 0);
815 SDValue Offset = Op.getOperand(i: 1);
816 SDValue Handler = Op.getOperand(i: 2);
817 SDLoc dl(Op);
818
819 // Absolute SP = (FP + FrameToArgs) + Offset
820 const TargetRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
821 SDValue Stack = DAG.getCopyFromReg(Chain: DAG.getEntryNode(), dl,
822 Reg: RegInfo->getFrameRegister(MF), VT: MVT::i32);
823 SDValue FrameToArgs = DAG.getNode(Opcode: XCoreISD::FRAME_TO_ARGS_OFFSET, DL: dl,
824 VT: MVT::i32);
825 Stack = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: MVT::i32, N1: Stack, N2: FrameToArgs);
826 Stack = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: MVT::i32, N1: Stack, N2: Offset);
827
828 // R0=ExceptionPointerRegister R1=ExceptionSelectorRegister
829 // which leaves 2 caller saved registers, R2 & R3 for us to use.
830 unsigned StackReg = XCore::R2;
831 unsigned HandlerReg = XCore::R3;
832
833 SDValue OutChains[] = {
834 DAG.getCopyToReg(Chain, dl, Reg: StackReg, N: Stack),
835 DAG.getCopyToReg(Chain, dl, Reg: HandlerReg, N: Handler)
836 };
837
838 Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other, Ops: OutChains);
839
840 return DAG.getNode(Opcode: XCoreISD::EH_RETURN, DL: dl, VT: MVT::Other, N1: Chain,
841 N2: DAG.getRegister(Reg: StackReg, VT: MVT::i32),
842 N3: DAG.getRegister(Reg: HandlerReg, VT: MVT::i32));
843
844}
845
846SDValue XCoreTargetLowering::
847LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
848 return Op.getOperand(i: 0);
849}
850
851SDValue XCoreTargetLowering::
852LowerINIT_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const {
853 SDValue Chain = Op.getOperand(i: 0);
854 SDValue Trmp = Op.getOperand(i: 1); // trampoline
855 SDValue FPtr = Op.getOperand(i: 2); // nested function
856 SDValue Nest = Op.getOperand(i: 3); // 'nest' parameter value
857
858 const Value *TrmpAddr = cast<SrcValueSDNode>(Val: Op.getOperand(i: 4))->getValue();
859
860 // .align 4
861 // LDAPF_u10 r11, nest
862 // LDW_2rus r11, r11[0]
863 // STWSP_ru6 r11, sp[0]
864 // LDAPF_u10 r11, fptr
865 // LDW_2rus r11, r11[0]
866 // BAU_1r r11
867 // nest:
868 // .word nest
869 // fptr:
870 // .word fptr
871 SDValue OutChains[5];
872
873 SDValue Addr = Trmp;
874
875 SDLoc dl(Op);
876 OutChains[0] =
877 DAG.getStore(Chain, dl, Val: DAG.getConstant(Val: 0x0a3cd805, DL: dl, VT: MVT::i32), Ptr: Addr,
878 PtrInfo: MachinePointerInfo(TrmpAddr));
879
880 Addr = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: MVT::i32, N1: Trmp,
881 N2: DAG.getConstant(Val: 4, DL: dl, VT: MVT::i32));
882 OutChains[1] =
883 DAG.getStore(Chain, dl, Val: DAG.getConstant(Val: 0xd80456c0, DL: dl, VT: MVT::i32), Ptr: Addr,
884 PtrInfo: MachinePointerInfo(TrmpAddr, 4));
885
886 Addr = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: MVT::i32, N1: Trmp,
887 N2: DAG.getConstant(Val: 8, DL: dl, VT: MVT::i32));
888 OutChains[2] =
889 DAG.getStore(Chain, dl, Val: DAG.getConstant(Val: 0x27fb0a3c, DL: dl, VT: MVT::i32), Ptr: Addr,
890 PtrInfo: MachinePointerInfo(TrmpAddr, 8));
891
892 Addr = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: MVT::i32, N1: Trmp,
893 N2: DAG.getConstant(Val: 12, DL: dl, VT: MVT::i32));
894 OutChains[3] =
895 DAG.getStore(Chain, dl, Val: Nest, Ptr: Addr, PtrInfo: MachinePointerInfo(TrmpAddr, 12));
896
897 Addr = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT: MVT::i32, N1: Trmp,
898 N2: DAG.getConstant(Val: 16, DL: dl, VT: MVT::i32));
899 OutChains[4] =
900 DAG.getStore(Chain, dl, Val: FPtr, Ptr: Addr, PtrInfo: MachinePointerInfo(TrmpAddr, 16));
901
902 return DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other, Ops: OutChains);
903}
904
905SDValue XCoreTargetLowering::
906LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
907 SDLoc DL(Op);
908 unsigned IntNo = Op.getConstantOperandVal(i: 0);
909 switch (IntNo) {
910 case Intrinsic::xcore_crc8:
911 EVT VT = Op.getValueType();
912 SDValue Data =
913 DAG.getNode(Opcode: XCoreISD::CRC8, DL, VTList: DAG.getVTList(VT1: VT, VT2: VT),
914 N1: Op.getOperand(i: 1), N2: Op.getOperand(i: 2) , N3: Op.getOperand(i: 3));
915 SDValue Crc(Data.getNode(), 1);
916 SDValue Results[] = { Crc, Data };
917 return DAG.getMergeValues(Ops: Results, dl: DL);
918 }
919 return SDValue();
920}
921
922SDValue XCoreTargetLowering::
923LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG) const {
924 SDLoc DL(Op);
925 return DAG.getNode(Opcode: ISD::MEMBARRIER, DL, VT: MVT::Other, Operand: Op.getOperand(i: 0));
926}
927
928//===----------------------------------------------------------------------===//
929// Calling Convention Implementation
930//===----------------------------------------------------------------------===//
931
932#include "XCoreGenCallingConv.inc"
933
934//===----------------------------------------------------------------------===//
935// Call Calling Convention Implementation
936//===----------------------------------------------------------------------===//
937
938/// XCore call implementation
939SDValue
940XCoreTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
941 SmallVectorImpl<SDValue> &InVals) const {
942 SelectionDAG &DAG = CLI.DAG;
943 SDLoc &dl = CLI.DL;
944 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
945 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
946 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
947 SDValue Chain = CLI.Chain;
948 SDValue Callee = CLI.Callee;
949 bool &isTailCall = CLI.IsTailCall;
950 CallingConv::ID CallConv = CLI.CallConv;
951 bool isVarArg = CLI.IsVarArg;
952
953 // XCore target does not yet support tail call optimization.
954 isTailCall = false;
955
956 // For now, only CallingConv::C implemented
957 switch (CallConv)
958 {
959 default:
960 report_fatal_error(reason: "Unsupported calling convention");
961 case CallingConv::Fast:
962 case CallingConv::C:
963 return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
964 Outs, OutVals, Ins, dl, DAG, InVals);
965 }
966}
967
968/// LowerCallResult - Lower the result values of a call into the
969/// appropriate copies out of appropriate physical registers / memory locations.
970static SDValue LowerCallResult(SDValue Chain, SDValue InGlue,
971 const SmallVectorImpl<CCValAssign> &RVLocs,
972 const SDLoc &dl, SelectionDAG &DAG,
973 SmallVectorImpl<SDValue> &InVals) {
974 SmallVector<std::pair<int, unsigned>, 4> ResultMemLocs;
975 // Copy results out of physical registers.
976 for (const CCValAssign &VA : RVLocs) {
977 if (VA.isRegLoc()) {
978 Chain = DAG.getCopyFromReg(Chain, dl, Reg: VA.getLocReg(), VT: VA.getValVT(),
979 Glue: InGlue).getValue(R: 1);
980 InGlue = Chain.getValue(R: 2);
981 InVals.push_back(Elt: Chain.getValue(R: 0));
982 } else {
983 assert(VA.isMemLoc());
984 ResultMemLocs.push_back(Elt: std::make_pair(x: VA.getLocMemOffset(),
985 y: InVals.size()));
986 // Reserve space for this result.
987 InVals.push_back(Elt: SDValue());
988 }
989 }
990
991 // Copy results out of memory.
992 SmallVector<SDValue, 4> MemOpChains;
993 for (unsigned i = 0, e = ResultMemLocs.size(); i != e; ++i) {
994 int offset = ResultMemLocs[i].first;
995 unsigned index = ResultMemLocs[i].second;
996 SDVTList VTs = DAG.getVTList(VT1: MVT::i32, VT2: MVT::Other);
997 SDValue Ops[] = { Chain, DAG.getConstant(Val: offset / 4, DL: dl, VT: MVT::i32) };
998 SDValue load = DAG.getNode(Opcode: XCoreISD::LDWSP, DL: dl, VTList: VTs, Ops);
999 InVals[index] = load;
1000 MemOpChains.push_back(Elt: load.getValue(R: 1));
1001 }
1002
1003 // Transform all loads nodes into one single node because
1004 // all load nodes are independent of each other.
1005 if (!MemOpChains.empty())
1006 Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other, Ops: MemOpChains);
1007
1008 return Chain;
1009}
1010
1011/// LowerCCCCallTo - functions arguments are copied from virtual
1012/// regs to (physical regs)/(stack frame), CALLSEQ_START and
1013/// CALLSEQ_END are emitted.
1014/// TODO: isTailCall, sret.
1015SDValue XCoreTargetLowering::LowerCCCCallTo(
1016 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
1017 bool isTailCall, const SmallVectorImpl<ISD::OutputArg> &Outs,
1018 const SmallVectorImpl<SDValue> &OutVals,
1019 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1020 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1021
1022 // Analyze operands of the call, assigning locations to each operand.
1023 SmallVector<CCValAssign, 16> ArgLocs;
1024 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1025 *DAG.getContext());
1026
1027 // The ABI dictates there should be one stack slot available to the callee
1028 // on function entry (for saving lr).
1029 CCInfo.AllocateStack(Size: 4, Alignment: Align(4));
1030
1031 CCInfo.AnalyzeCallOperands(Outs, Fn: CC_XCore);
1032
1033 SmallVector<CCValAssign, 16> RVLocs;
1034 // Analyze return values to determine the number of bytes of stack required.
1035 CCState RetCCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1036 *DAG.getContext());
1037 RetCCInfo.AllocateStack(Size: CCInfo.getStackSize(), Alignment: Align(4));
1038 RetCCInfo.AnalyzeCallResult(Ins, Fn: RetCC_XCore);
1039
1040 // Get a count of how many bytes are to be pushed on the stack.
1041 unsigned NumBytes = RetCCInfo.getStackSize();
1042
1043 Chain = DAG.getCALLSEQ_START(Chain, InSize: NumBytes, OutSize: 0, DL: dl);
1044
1045 SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
1046 SmallVector<SDValue, 12> MemOpChains;
1047
1048 // Walk the register/memloc assignments, inserting copies/loads.
1049 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1050 CCValAssign &VA = ArgLocs[i];
1051 SDValue Arg = OutVals[i];
1052
1053 // Promote the value if needed.
1054 switch (VA.getLocInfo()) {
1055 default: llvm_unreachable("Unknown loc info!");
1056 case CCValAssign::Full: break;
1057 case CCValAssign::SExt:
1058 Arg = DAG.getNode(Opcode: ISD::SIGN_EXTEND, DL: dl, VT: VA.getLocVT(), Operand: Arg);
1059 break;
1060 case CCValAssign::ZExt:
1061 Arg = DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL: dl, VT: VA.getLocVT(), Operand: Arg);
1062 break;
1063 case CCValAssign::AExt:
1064 Arg = DAG.getNode(Opcode: ISD::ANY_EXTEND, DL: dl, VT: VA.getLocVT(), Operand: Arg);
1065 break;
1066 }
1067
1068 // Arguments that can be passed on register must be kept at
1069 // RegsToPass vector
1070 if (VA.isRegLoc()) {
1071 RegsToPass.push_back(Elt: std::make_pair(x: VA.getLocReg(), y&: Arg));
1072 } else {
1073 assert(VA.isMemLoc());
1074
1075 int Offset = VA.getLocMemOffset();
1076
1077 MemOpChains.push_back(Elt: DAG.getNode(Opcode: XCoreISD::STWSP, DL: dl, VT: MVT::Other,
1078 N1: Chain, N2: Arg,
1079 N3: DAG.getConstant(Val: Offset/4, DL: dl,
1080 VT: MVT::i32)));
1081 }
1082 }
1083
1084 // Transform all store nodes into one single node because
1085 // all store nodes are independent of each other.
1086 if (!MemOpChains.empty())
1087 Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other, Ops: MemOpChains);
1088
1089 // Build a sequence of copy-to-reg nodes chained together with token
1090 // chain and flag operands which copy the outgoing args into registers.
1091 // The InGlue in necessary since all emitted instructions must be
1092 // stuck together.
1093 SDValue InGlue;
1094 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1095 Chain = DAG.getCopyToReg(Chain, dl, Reg: RegsToPass[i].first,
1096 N: RegsToPass[i].second, Glue: InGlue);
1097 InGlue = Chain.getValue(R: 1);
1098 }
1099
1100 // If the callee is a GlobalAddress node (quite common, every direct call is)
1101 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1102 // Likewise ExternalSymbol -> TargetExternalSymbol.
1103 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Val&: Callee))
1104 Callee = DAG.getTargetGlobalAddress(GV: G->getGlobal(), DL: dl, VT: MVT::i32);
1105 else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Val&: Callee))
1106 Callee = DAG.getTargetExternalSymbol(Sym: E->getSymbol(), VT: MVT::i32);
1107
1108 // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
1109 // = Chain, Callee, Reg#1, Reg#2, ...
1110 //
1111 // Returns a chain & a flag for retval copy to use.
1112 SDVTList NodeTys = DAG.getVTList(VT1: MVT::Other, VT2: MVT::Glue);
1113 SmallVector<SDValue, 8> Ops;
1114 Ops.push_back(Elt: Chain);
1115 Ops.push_back(Elt: Callee);
1116
1117 // Add argument registers to the end of the list so that they are
1118 // known live into the call.
1119 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1120 Ops.push_back(Elt: DAG.getRegister(Reg: RegsToPass[i].first,
1121 VT: RegsToPass[i].second.getValueType()));
1122
1123 if (InGlue.getNode())
1124 Ops.push_back(Elt: InGlue);
1125
1126 Chain = DAG.getNode(Opcode: XCoreISD::BL, DL: dl, VTList: NodeTys, Ops);
1127 InGlue = Chain.getValue(R: 1);
1128
1129 // Create the CALLSEQ_END node.
1130 Chain = DAG.getCALLSEQ_END(Chain, Size1: NumBytes, Size2: 0, Glue: InGlue, DL: dl);
1131 InGlue = Chain.getValue(R: 1);
1132
1133 // Handle result values, copying them out of physregs into vregs that we
1134 // return.
1135 return LowerCallResult(Chain, InGlue, RVLocs, dl, DAG, InVals);
1136}
1137
1138//===----------------------------------------------------------------------===//
1139// Formal Arguments Calling Convention Implementation
1140//===----------------------------------------------------------------------===//
1141
1142namespace {
1143 struct ArgDataPair { SDValue SDV; ISD::ArgFlagsTy Flags; };
1144}
1145
1146/// XCore formal arguments implementation
1147SDValue XCoreTargetLowering::LowerFormalArguments(
1148 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1149 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1150 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1151 switch (CallConv)
1152 {
1153 default:
1154 report_fatal_error(reason: "Unsupported calling convention");
1155 case CallingConv::C:
1156 case CallingConv::Fast:
1157 return LowerCCCArguments(Chain, CallConv, isVarArg,
1158 Ins, dl, DAG, InVals);
1159 }
1160}
1161
1162/// LowerCCCArguments - transform physical registers into
1163/// virtual registers and generate load operations for
1164/// arguments places on the stack.
1165/// TODO: sret
1166SDValue XCoreTargetLowering::LowerCCCArguments(
1167 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1168 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1169 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1170 MachineFunction &MF = DAG.getMachineFunction();
1171 MachineFrameInfo &MFI = MF.getFrameInfo();
1172 MachineRegisterInfo &RegInfo = MF.getRegInfo();
1173 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1174
1175 // Assign locations to all of the incoming arguments.
1176 SmallVector<CCValAssign, 16> ArgLocs;
1177 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1178 *DAG.getContext());
1179
1180 CCInfo.AnalyzeFormalArguments(Ins, Fn: CC_XCore);
1181
1182 unsigned StackSlotSize = XCoreFrameLowering::stackSlotSize();
1183
1184 unsigned LRSaveSize = StackSlotSize;
1185
1186 if (!isVarArg)
1187 XFI->setReturnStackOffset(CCInfo.getStackSize() + LRSaveSize);
1188
1189 // All getCopyFromReg ops must precede any getMemcpys to prevent the
1190 // scheduler clobbering a register before it has been copied.
1191 // The stages are:
1192 // 1. CopyFromReg (and load) arg & vararg registers.
1193 // 2. Chain CopyFromReg nodes into a TokenFactor.
1194 // 3. Memcpy 'byVal' args & push final InVals.
1195 // 4. Chain mem ops nodes into a TokenFactor.
1196 SmallVector<SDValue, 4> CFRegNode;
1197 SmallVector<ArgDataPair, 4> ArgData;
1198 SmallVector<SDValue, 4> MemOps;
1199
1200 // 1a. CopyFromReg (and load) arg registers.
1201 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1202
1203 CCValAssign &VA = ArgLocs[i];
1204 SDValue ArgIn;
1205
1206 if (VA.isRegLoc()) {
1207 // Arguments passed in registers
1208 EVT RegVT = VA.getLocVT();
1209 switch (RegVT.getSimpleVT().SimpleTy) {
1210 default:
1211 {
1212#ifndef NDEBUG
1213 errs() << "LowerFormalArguments Unhandled argument type: "
1214 << RegVT << "\n";
1215#endif
1216 llvm_unreachable(nullptr);
1217 }
1218 case MVT::i32:
1219 Register VReg = RegInfo.createVirtualRegister(RegClass: &XCore::GRRegsRegClass);
1220 RegInfo.addLiveIn(Reg: VA.getLocReg(), vreg: VReg);
1221 ArgIn = DAG.getCopyFromReg(Chain, dl, Reg: VReg, VT: RegVT);
1222 CFRegNode.push_back(Elt: ArgIn.getValue(R: ArgIn->getNumValues() - 1));
1223 }
1224 } else {
1225 // Only arguments passed on the stack should make it here.
1226 assert(VA.isMemLoc());
1227 // Load the argument to a virtual register
1228 unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
1229 if (ObjSize > StackSlotSize) {
1230 errs() << "LowerFormalArguments Unhandled argument type: "
1231 << VA.getLocVT() << "\n";
1232 }
1233 // Create the frame index object for this incoming parameter...
1234 int FI = MFI.CreateFixedObject(Size: ObjSize,
1235 SPOffset: LRSaveSize + VA.getLocMemOffset(),
1236 IsImmutable: true);
1237
1238 // Create the SelectionDAG nodes corresponding to a load
1239 //from this parameter
1240 SDValue FIN = DAG.getFrameIndex(FI, VT: MVT::i32);
1241 ArgIn = DAG.getLoad(VT: VA.getLocVT(), dl, Chain, Ptr: FIN,
1242 PtrInfo: MachinePointerInfo::getFixedStack(MF, FI));
1243 }
1244 const ArgDataPair ADP = { .SDV: ArgIn, .Flags: Ins[i].Flags };
1245 ArgData.push_back(Elt: ADP);
1246 }
1247
1248 // 1b. CopyFromReg vararg registers.
1249 if (isVarArg) {
1250 // Argument registers
1251 static const MCPhysReg ArgRegs[] = {
1252 XCore::R0, XCore::R1, XCore::R2, XCore::R3
1253 };
1254 XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
1255 unsigned FirstVAReg = CCInfo.getFirstUnallocated(Regs: ArgRegs);
1256 if (FirstVAReg < std::size(ArgRegs)) {
1257 int offset = 0;
1258 // Save remaining registers, storing higher register numbers at a higher
1259 // address
1260 for (int i = std::size(ArgRegs) - 1; i >= (int)FirstVAReg; --i) {
1261 // Create a stack slot
1262 int FI = MFI.CreateFixedObject(Size: 4, SPOffset: offset, IsImmutable: true);
1263 if (i == (int)FirstVAReg) {
1264 XFI->setVarArgsFrameIndex(FI);
1265 }
1266 offset -= StackSlotSize;
1267 SDValue FIN = DAG.getFrameIndex(FI, VT: MVT::i32);
1268 // Move argument from phys reg -> virt reg
1269 Register VReg = RegInfo.createVirtualRegister(RegClass: &XCore::GRRegsRegClass);
1270 RegInfo.addLiveIn(Reg: ArgRegs[i], vreg: VReg);
1271 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg: VReg, VT: MVT::i32);
1272 CFRegNode.push_back(Elt: Val.getValue(R: Val->getNumValues() - 1));
1273 // Move argument from virt reg -> stack
1274 SDValue Store =
1275 DAG.getStore(Chain: Val.getValue(R: 1), dl, Val, Ptr: FIN, PtrInfo: MachinePointerInfo());
1276 MemOps.push_back(Elt: Store);
1277 }
1278 } else {
1279 // This will point to the next argument passed via stack.
1280 XFI->setVarArgsFrameIndex(
1281 MFI.CreateFixedObject(Size: 4, SPOffset: LRSaveSize + CCInfo.getStackSize(), IsImmutable: true));
1282 }
1283 }
1284
1285 // 2. chain CopyFromReg nodes into a TokenFactor.
1286 if (!CFRegNode.empty())
1287 Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other, Ops: CFRegNode);
1288
1289 // 3. Memcpy 'byVal' args & push final InVals.
1290 // Aggregates passed "byVal" need to be copied by the callee.
1291 // The callee will use a pointer to this copy, rather than the original
1292 // pointer.
1293 for (const ArgDataPair &ArgDI : ArgData) {
1294 if (ArgDI.Flags.isByVal() && ArgDI.Flags.getByValSize()) {
1295 unsigned Size = ArgDI.Flags.getByValSize();
1296 Align Alignment =
1297 std::max(a: Align(StackSlotSize), b: ArgDI.Flags.getNonZeroByValAlign());
1298 // Create a new object on the stack and copy the pointee into it.
1299 int FI = MFI.CreateStackObject(Size, Alignment, isSpillSlot: false);
1300 SDValue FIN = DAG.getFrameIndex(FI, VT: MVT::i32);
1301 InVals.push_back(Elt: FIN);
1302 MemOps.push_back(Elt: DAG.getMemcpy(
1303 Chain, dl, Dst: FIN, Src: ArgDI.SDV, Size: DAG.getConstant(Val: Size, DL: dl, VT: MVT::i32),
1304 Alignment, isVol: false, AlwaysInline: false, /*CI=*/nullptr, OverrideTailCall: std::nullopt,
1305 DstPtrInfo: MachinePointerInfo(), SrcPtrInfo: MachinePointerInfo()));
1306 } else {
1307 InVals.push_back(Elt: ArgDI.SDV);
1308 }
1309 }
1310
1311 // 4, chain mem ops nodes into a TokenFactor.
1312 if (!MemOps.empty()) {
1313 MemOps.push_back(Elt: Chain);
1314 Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other, Ops: MemOps);
1315 }
1316
1317 return Chain;
1318}
1319
1320//===----------------------------------------------------------------------===//
1321// Return Value Calling Convention Implementation
1322//===----------------------------------------------------------------------===//
1323
1324bool XCoreTargetLowering::
1325CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF,
1326 bool isVarArg,
1327 const SmallVectorImpl<ISD::OutputArg> &Outs,
1328 LLVMContext &Context) const {
1329 SmallVector<CCValAssign, 16> RVLocs;
1330 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1331 if (!CCInfo.CheckReturn(Outs, Fn: RetCC_XCore))
1332 return false;
1333 if (CCInfo.getStackSize() != 0 && isVarArg)
1334 return false;
1335 return true;
1336}
1337
1338SDValue
1339XCoreTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1340 bool isVarArg,
1341 const SmallVectorImpl<ISD::OutputArg> &Outs,
1342 const SmallVectorImpl<SDValue> &OutVals,
1343 const SDLoc &dl, SelectionDAG &DAG) const {
1344
1345 XCoreFunctionInfo *XFI =
1346 DAG.getMachineFunction().getInfo<XCoreFunctionInfo>();
1347 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
1348
1349 // CCValAssign - represent the assignment of
1350 // the return value to a location
1351 SmallVector<CCValAssign, 16> RVLocs;
1352
1353 // CCState - Info about the registers and stack slot.
1354 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1355 *DAG.getContext());
1356
1357 // Analyze return values.
1358 if (!isVarArg)
1359 CCInfo.AllocateStack(Size: XFI->getReturnStackOffset(), Alignment: Align(4));
1360
1361 CCInfo.AnalyzeReturn(Outs, Fn: RetCC_XCore);
1362
1363 SDValue Glue;
1364 SmallVector<SDValue, 4> RetOps(1, Chain);
1365
1366 // Return on XCore is always a "retsp 0"
1367 RetOps.push_back(Elt: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
1368
1369 SmallVector<SDValue, 4> MemOpChains;
1370 // Handle return values that must be copied to memory.
1371 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1372 CCValAssign &VA = RVLocs[i];
1373 if (VA.isRegLoc())
1374 continue;
1375 assert(VA.isMemLoc());
1376 if (isVarArg) {
1377 report_fatal_error(reason: "Can't return value from vararg function in memory");
1378 }
1379
1380 int Offset = VA.getLocMemOffset();
1381 unsigned ObjSize = VA.getLocVT().getSizeInBits() / 8;
1382 // Create the frame index object for the memory location.
1383 int FI = MFI.CreateFixedObject(Size: ObjSize, SPOffset: Offset, IsImmutable: false);
1384
1385 // Create a SelectionDAG node corresponding to a store
1386 // to this memory location.
1387 SDValue FIN = DAG.getFrameIndex(FI, VT: MVT::i32);
1388 MemOpChains.push_back(Elt: DAG.getStore(
1389 Chain, dl, Val: OutVals[i], Ptr: FIN,
1390 PtrInfo: MachinePointerInfo::getFixedStack(MF&: DAG.getMachineFunction(), FI)));
1391 }
1392
1393 // Transform all store nodes into one single node because
1394 // all stores are independent of each other.
1395 if (!MemOpChains.empty())
1396 Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL: dl, VT: MVT::Other, Ops: MemOpChains);
1397
1398 // Now handle return values copied to registers.
1399 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1400 CCValAssign &VA = RVLocs[i];
1401 if (!VA.isRegLoc())
1402 continue;
1403 // Copy the result values into the output registers.
1404 Chain = DAG.getCopyToReg(Chain, dl, Reg: VA.getLocReg(), N: OutVals[i], Glue);
1405
1406 // guarantee that all emitted copies are
1407 // stuck together, avoiding something bad
1408 Glue = Chain.getValue(R: 1);
1409 RetOps.push_back(Elt: DAG.getRegister(Reg: VA.getLocReg(), VT: VA.getLocVT()));
1410 }
1411
1412 RetOps[0] = Chain; // Update chain.
1413
1414 // Add the glue if we have it.
1415 if (Glue.getNode())
1416 RetOps.push_back(Elt: Glue);
1417
1418 return DAG.getNode(Opcode: XCoreISD::RETSP, DL: dl, VT: MVT::Other, Ops: RetOps);
1419}
1420
1421//===----------------------------------------------------------------------===//
1422// Other Lowering Code
1423//===----------------------------------------------------------------------===//
1424
1425MachineBasicBlock *
1426XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
1427 MachineBasicBlock *BB) const {
1428 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1429 DebugLoc dl = MI.getDebugLoc();
1430 assert((MI.getOpcode() == XCore::SELECT_CC) &&
1431 "Unexpected instr type to insert");
1432
1433 // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1434 // control-flow pattern. The incoming instruction knows the destination vreg
1435 // to set, the condition code register to branch on, the true/false values to
1436 // select between, and a branch opcode to use.
1437 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1438 MachineFunction::iterator It = ++BB->getIterator();
1439
1440 // thisMBB:
1441 // ...
1442 // TrueVal = ...
1443 // cmpTY ccX, r1, r2
1444 // bCC copy1MBB
1445 // fallthrough --> copy0MBB
1446 MachineBasicBlock *thisMBB = BB;
1447 MachineFunction *F = BB->getParent();
1448 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(BB: LLVM_BB);
1449 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(BB: LLVM_BB);
1450 F->insert(MBBI: It, MBB: copy0MBB);
1451 F->insert(MBBI: It, MBB: sinkMBB);
1452
1453 // Transfer the remainder of BB and its successor edges to sinkMBB.
1454 sinkMBB->splice(Where: sinkMBB->begin(), Other: BB,
1455 From: std::next(x: MachineBasicBlock::iterator(MI)), To: BB->end());
1456 sinkMBB->transferSuccessorsAndUpdatePHIs(FromMBB: BB);
1457
1458 // Next, add the true and fallthrough blocks as its successors.
1459 BB->addSuccessor(Succ: copy0MBB);
1460 BB->addSuccessor(Succ: sinkMBB);
1461
1462 BuildMI(BB, MIMD: dl, MCID: TII.get(Opcode: XCore::BRFT_lru6))
1463 .addReg(RegNo: MI.getOperand(i: 1).getReg())
1464 .addMBB(MBB: sinkMBB);
1465
1466 // copy0MBB:
1467 // %FalseValue = ...
1468 // # fallthrough to sinkMBB
1469 BB = copy0MBB;
1470
1471 // Update machine-CFG edges
1472 BB->addSuccessor(Succ: sinkMBB);
1473
1474 // sinkMBB:
1475 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1476 // ...
1477 BB = sinkMBB;
1478 BuildMI(BB&: *BB, I: BB->begin(), MIMD: dl, MCID: TII.get(Opcode: XCore::PHI), DestReg: MI.getOperand(i: 0).getReg())
1479 .addReg(RegNo: MI.getOperand(i: 3).getReg())
1480 .addMBB(MBB: copy0MBB)
1481 .addReg(RegNo: MI.getOperand(i: 2).getReg())
1482 .addMBB(MBB: thisMBB);
1483
1484 MI.eraseFromParent(); // The pseudo instruction is gone now.
1485 return BB;
1486}
1487
1488//===----------------------------------------------------------------------===//
1489// Target Optimization Hooks
1490//===----------------------------------------------------------------------===//
1491
1492SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
1493 DAGCombinerInfo &DCI) const {
1494 SelectionDAG &DAG = DCI.DAG;
1495 SDLoc dl(N);
1496 switch (N->getOpcode()) {
1497 default: break;
1498 case ISD::INTRINSIC_VOID:
1499 switch (N->getConstantOperandVal(Num: 1)) {
1500 case Intrinsic::xcore_outt:
1501 case Intrinsic::xcore_outct:
1502 case Intrinsic::xcore_chkct: {
1503 SDValue OutVal = N->getOperand(Num: 3);
1504 // These instructions ignore the high bits.
1505 if (OutVal.hasOneUse()) {
1506 unsigned BitWidth = OutVal.getValueSizeInBits();
1507 APInt DemandedMask = APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: 8);
1508 KnownBits Known;
1509 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1510 !DCI.isBeforeLegalizeOps());
1511 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1512 if (TLI.ShrinkDemandedConstant(Op: OutVal, DemandedBits: DemandedMask, TLO) ||
1513 TLI.SimplifyDemandedBits(Op: OutVal, DemandedBits: DemandedMask, Known, TLO))
1514 DCI.CommitTargetLoweringOpt(TLO);
1515 }
1516 break;
1517 }
1518 case Intrinsic::xcore_setpt: {
1519 SDValue Time = N->getOperand(Num: 3);
1520 // This instruction ignores the high bits.
1521 if (Time.hasOneUse()) {
1522 unsigned BitWidth = Time.getValueSizeInBits();
1523 APInt DemandedMask = APInt::getLowBitsSet(numBits: BitWidth, loBitsSet: 16);
1524 KnownBits Known;
1525 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1526 !DCI.isBeforeLegalizeOps());
1527 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1528 if (TLI.ShrinkDemandedConstant(Op: Time, DemandedBits: DemandedMask, TLO) ||
1529 TLI.SimplifyDemandedBits(Op: Time, DemandedBits: DemandedMask, Known, TLO))
1530 DCI.CommitTargetLoweringOpt(TLO);
1531 }
1532 break;
1533 }
1534 }
1535 break;
1536 case XCoreISD::LADD: {
1537 SDValue N0 = N->getOperand(Num: 0);
1538 SDValue N1 = N->getOperand(Num: 1);
1539 SDValue N2 = N->getOperand(Num: 2);
1540 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(Val&: N0);
1541 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Val&: N1);
1542 EVT VT = N0.getValueType();
1543
1544 // canonicalize constant to RHS
1545 if (N0C && !N1C)
1546 return DAG.getNode(Opcode: XCoreISD::LADD, DL: dl, VTList: DAG.getVTList(VT1: VT, VT2: VT), N1, N2: N0, N3: N2);
1547
1548 // fold (ladd 0, 0, x) -> 0, x & 1
1549 if (N0C && N0C->isZero() && N1C && N1C->isZero()) {
1550 SDValue Carry = DAG.getConstant(Val: 0, DL: dl, VT);
1551 SDValue Result = DAG.getNode(Opcode: ISD::AND, DL: dl, VT, N1: N2,
1552 N2: DAG.getConstant(Val: 1, DL: dl, VT));
1553 SDValue Ops[] = { Result, Carry };
1554 return DAG.getMergeValues(Ops, dl);
1555 }
1556
1557 // fold (ladd x, 0, y) -> 0, add x, y iff carry is unused and y has only the
1558 // low bit set
1559 if (N1C && N1C->isZero() && N->hasNUsesOfValue(NUses: 0, Value: 1)) {
1560 APInt Mask = APInt::getHighBitsSet(numBits: VT.getSizeInBits(),
1561 hiBitsSet: VT.getSizeInBits() - 1);
1562 KnownBits Known = DAG.computeKnownBits(Op: N2);
1563 if ((Known.Zero & Mask) == Mask) {
1564 SDValue Carry = DAG.getConstant(Val: 0, DL: dl, VT);
1565 SDValue Result = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT, N1: N0, N2);
1566 SDValue Ops[] = { Result, Carry };
1567 return DAG.getMergeValues(Ops, dl);
1568 }
1569 }
1570 }
1571 break;
1572 case XCoreISD::LSUB: {
1573 SDValue N0 = N->getOperand(Num: 0);
1574 SDValue N1 = N->getOperand(Num: 1);
1575 SDValue N2 = N->getOperand(Num: 2);
1576 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(Val&: N0);
1577 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Val&: N1);
1578 EVT VT = N0.getValueType();
1579
1580 // fold (lsub 0, 0, x) -> x, -x iff x has only the low bit set
1581 if (N0C && N0C->isZero() && N1C && N1C->isZero()) {
1582 APInt Mask = APInt::getHighBitsSet(numBits: VT.getSizeInBits(),
1583 hiBitsSet: VT.getSizeInBits() - 1);
1584 KnownBits Known = DAG.computeKnownBits(Op: N2);
1585 if ((Known.Zero & Mask) == Mask) {
1586 SDValue Borrow = N2;
1587 SDValue Result = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT,
1588 N1: DAG.getConstant(Val: 0, DL: dl, VT), N2);
1589 SDValue Ops[] = { Result, Borrow };
1590 return DAG.getMergeValues(Ops, dl);
1591 }
1592 }
1593
1594 // fold (lsub x, 0, y) -> 0, sub x, y iff borrow is unused and y has only the
1595 // low bit set
1596 if (N1C && N1C->isZero() && N->hasNUsesOfValue(NUses: 0, Value: 1)) {
1597 APInt Mask = APInt::getHighBitsSet(numBits: VT.getSizeInBits(),
1598 hiBitsSet: VT.getSizeInBits() - 1);
1599 KnownBits Known = DAG.computeKnownBits(Op: N2);
1600 if ((Known.Zero & Mask) == Mask) {
1601 SDValue Borrow = DAG.getConstant(Val: 0, DL: dl, VT);
1602 SDValue Result = DAG.getNode(Opcode: ISD::SUB, DL: dl, VT, N1: N0, N2);
1603 SDValue Ops[] = { Result, Borrow };
1604 return DAG.getMergeValues(Ops, dl);
1605 }
1606 }
1607 }
1608 break;
1609 case XCoreISD::LMUL: {
1610 SDValue N0 = N->getOperand(Num: 0);
1611 SDValue N1 = N->getOperand(Num: 1);
1612 SDValue N2 = N->getOperand(Num: 2);
1613 SDValue N3 = N->getOperand(Num: 3);
1614 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(Val&: N0);
1615 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Val&: N1);
1616 EVT VT = N0.getValueType();
1617 // Canonicalize multiplicative constant to RHS. If both multiplicative
1618 // operands are constant canonicalize smallest to RHS.
1619 if ((N0C && !N1C) ||
1620 (N0C && N1C && N0C->getZExtValue() < N1C->getZExtValue()))
1621 return DAG.getNode(Opcode: XCoreISD::LMUL, DL: dl, VTList: DAG.getVTList(VT1: VT, VT2: VT),
1622 N1, N2: N0, N3: N2, N4: N3);
1623
1624 // lmul(x, 0, a, b)
1625 if (N1C && N1C->isZero()) {
1626 // If the high result is unused fold to add(a, b)
1627 if (N->hasNUsesOfValue(NUses: 0, Value: 0)) {
1628 SDValue Lo = DAG.getNode(Opcode: ISD::ADD, DL: dl, VT, N1: N2, N2: N3);
1629 SDValue Ops[] = { Lo, Lo };
1630 return DAG.getMergeValues(Ops, dl);
1631 }
1632 // Otherwise fold to ladd(a, b, 0)
1633 SDValue Result =
1634 DAG.getNode(Opcode: XCoreISD::LADD, DL: dl, VTList: DAG.getVTList(VT1: VT, VT2: VT), N1: N2, N2: N3, N3: N1);
1635 SDValue Carry(Result.getNode(), 1);
1636 SDValue Ops[] = { Carry, Result };
1637 return DAG.getMergeValues(Ops, dl);
1638 }
1639 }
1640 break;
1641 case ISD::ADD: {
1642 // Fold 32 bit expressions such as add(add(mul(x,y),a),b) ->
1643 // lmul(x, y, a, b). The high result of lmul will be ignored.
1644 // This is only profitable if the intermediate results are unused
1645 // elsewhere.
1646 SDValue Mul0, Mul1, Addend0, Addend1;
1647 if (N->getValueType(ResNo: 0) == MVT::i32 &&
1648 isADDADDMUL(Op: SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, requireIntermediatesHaveOneUse: true)) {
1649 SDValue Ignored = DAG.getNode(Opcode: XCoreISD::LMUL, DL: dl,
1650 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32), N1: Mul0,
1651 N2: Mul1, N3: Addend0, N4: Addend1);
1652 SDValue Result(Ignored.getNode(), 1);
1653 return Result;
1654 }
1655 APInt HighMask = APInt::getHighBitsSet(numBits: 64, hiBitsSet: 32);
1656 // Fold 64 bit expression such as add(add(mul(x,y),a),b) ->
1657 // lmul(x, y, a, b) if all operands are zero-extended. We do this
1658 // before type legalization as it is messy to match the operands after
1659 // that.
1660 if (N->getValueType(ResNo: 0) == MVT::i64 &&
1661 isADDADDMUL(Op: SDValue(N, 0), Mul0, Mul1, Addend0, Addend1, requireIntermediatesHaveOneUse: false) &&
1662 DAG.MaskedValueIsZero(Op: Mul0, Mask: HighMask) &&
1663 DAG.MaskedValueIsZero(Op: Mul1, Mask: HighMask) &&
1664 DAG.MaskedValueIsZero(Op: Addend0, Mask: HighMask) &&
1665 DAG.MaskedValueIsZero(Op: Addend1, Mask: HighMask)) {
1666 SDValue Mul0L = DAG.getNode(Opcode: ISD::EXTRACT_ELEMENT, DL: dl, VT: MVT::i32,
1667 N1: Mul0, N2: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
1668 SDValue Mul1L = DAG.getNode(Opcode: ISD::EXTRACT_ELEMENT, DL: dl, VT: MVT::i32,
1669 N1: Mul1, N2: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
1670 SDValue Addend0L = DAG.getNode(Opcode: ISD::EXTRACT_ELEMENT, DL: dl, VT: MVT::i32,
1671 N1: Addend0, N2: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
1672 SDValue Addend1L = DAG.getNode(Opcode: ISD::EXTRACT_ELEMENT, DL: dl, VT: MVT::i32,
1673 N1: Addend1, N2: DAG.getConstant(Val: 0, DL: dl, VT: MVT::i32));
1674 SDValue Hi = DAG.getNode(Opcode: XCoreISD::LMUL, DL: dl,
1675 VTList: DAG.getVTList(VT1: MVT::i32, VT2: MVT::i32), N1: Mul0L, N2: Mul1L,
1676 N3: Addend0L, N4: Addend1L);
1677 SDValue Lo(Hi.getNode(), 1);
1678 return DAG.getNode(Opcode: ISD::BUILD_PAIR, DL: dl, VT: MVT::i64, N1: Lo, N2: Hi);
1679 }
1680 }
1681 break;
1682 case ISD::STORE: {
1683 // Replace unaligned store of unaligned load with memmove.
1684 StoreSDNode *ST = cast<StoreSDNode>(Val: N);
1685 if (!DCI.isBeforeLegalize() ||
1686 allowsMemoryAccessForAlignment(Context&: *DAG.getContext(), DL: DAG.getDataLayout(),
1687 VT: ST->getMemoryVT(),
1688 MMO: *ST->getMemOperand()) ||
1689 ST->isVolatile() || ST->isIndexed()) {
1690 break;
1691 }
1692 SDValue Chain = ST->getChain();
1693
1694 unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
1695 assert((StoreBits % 8) == 0 &&
1696 "Store size in bits must be a multiple of 8");
1697 Align Alignment = ST->getAlign();
1698
1699 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val: ST->getValue())) {
1700 if (LD->hasNUsesOfValue(NUses: 1, Value: 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
1701 LD->getAlign() == Alignment &&
1702 !LD->isVolatile() && !LD->isIndexed() &&
1703 Chain.reachesChainWithoutSideEffects(Dest: SDValue(LD, 1))) {
1704 bool isTail = isInTailCallPosition(DAG, Node: ST, Chain);
1705 return DAG.getMemmove(Chain, dl, Dst: ST->getBasePtr(), Src: LD->getBasePtr(),
1706 Size: DAG.getConstant(Val: StoreBits / 8, DL: dl, VT: MVT::i32),
1707 Alignment, isVol: false, CI: nullptr, OverrideTailCall: isTail,
1708 DstPtrInfo: ST->getPointerInfo(), SrcPtrInfo: LD->getPointerInfo());
1709 }
1710 }
1711 break;
1712 }
1713 }
1714 return SDValue();
1715}
1716
1717void XCoreTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
1718 KnownBits &Known,
1719 const APInt &DemandedElts,
1720 const SelectionDAG &DAG,
1721 unsigned Depth) const {
1722 Known.resetAll();
1723 switch (Op.getOpcode()) {
1724 default: break;
1725 case XCoreISD::LADD:
1726 case XCoreISD::LSUB:
1727 if (Op.getResNo() == 1) {
1728 // Top bits of carry / borrow are clear.
1729 Known.Zero = APInt::getHighBitsSet(numBits: Known.getBitWidth(),
1730 hiBitsSet: Known.getBitWidth() - 1);
1731 }
1732 break;
1733 case ISD::INTRINSIC_W_CHAIN:
1734 {
1735 unsigned IntNo = Op.getConstantOperandVal(i: 1);
1736 switch (IntNo) {
1737 case Intrinsic::xcore_getts:
1738 // High bits are known to be zero.
1739 Known.Zero =
1740 APInt::getHighBitsSet(numBits: Known.getBitWidth(), hiBitsSet: Known.getBitWidth() - 16);
1741 break;
1742 case Intrinsic::xcore_int:
1743 case Intrinsic::xcore_inct:
1744 // High bits are known to be zero.
1745 Known.Zero =
1746 APInt::getHighBitsSet(numBits: Known.getBitWidth(), hiBitsSet: Known.getBitWidth() - 8);
1747 break;
1748 case Intrinsic::xcore_testct:
1749 // Result is either 0 or 1.
1750 Known.Zero =
1751 APInt::getHighBitsSet(numBits: Known.getBitWidth(), hiBitsSet: Known.getBitWidth() - 1);
1752 break;
1753 case Intrinsic::xcore_testwct:
1754 // Result is in the range 0 - 4.
1755 Known.Zero =
1756 APInt::getHighBitsSet(numBits: Known.getBitWidth(), hiBitsSet: Known.getBitWidth() - 3);
1757 break;
1758 }
1759 }
1760 break;
1761 }
1762}
1763
1764//===----------------------------------------------------------------------===//
1765// Addressing mode description hooks
1766//===----------------------------------------------------------------------===//
1767
1768static inline bool isImmUs(int64_t val)
1769{
1770 return (val >= 0 && val <= 11);
1771}
1772
1773static inline bool isImmUs2(int64_t val)
1774{
1775 return (val%2 == 0 && isImmUs(val: val/2));
1776}
1777
1778static inline bool isImmUs4(int64_t val)
1779{
1780 return (val%4 == 0 && isImmUs(val: val/4));
1781}
1782
1783/// isLegalAddressingMode - Return true if the addressing mode represented
1784/// by AM is legal for this target, for a load/store of the specified type.
1785bool XCoreTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1786 const AddrMode &AM, Type *Ty,
1787 unsigned AS,
1788 Instruction *I) const {
1789 if (Ty->getTypeID() == Type::VoidTyID)
1790 return AM.Scale == 0 && isImmUs(val: AM.BaseOffs) && isImmUs4(val: AM.BaseOffs);
1791
1792 unsigned Size = DL.getTypeAllocSize(Ty);
1793 if (AM.BaseGV) {
1794 return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
1795 AM.BaseOffs%4 == 0;
1796 }
1797
1798 switch (Size) {
1799 case 1:
1800 // reg + imm
1801 if (AM.Scale == 0) {
1802 return isImmUs(val: AM.BaseOffs);
1803 }
1804 // reg + reg
1805 return AM.Scale == 1 && AM.BaseOffs == 0;
1806 case 2:
1807 case 3:
1808 // reg + imm
1809 if (AM.Scale == 0) {
1810 return isImmUs2(val: AM.BaseOffs);
1811 }
1812 // reg + reg<<1
1813 return AM.Scale == 2 && AM.BaseOffs == 0;
1814 default:
1815 // reg + imm
1816 if (AM.Scale == 0) {
1817 return isImmUs4(val: AM.BaseOffs);
1818 }
1819 // reg + reg<<2
1820 return AM.Scale == 4 && AM.BaseOffs == 0;
1821 }
1822}
1823
1824//===----------------------------------------------------------------------===//
1825// XCore Inline Assembly Support
1826//===----------------------------------------------------------------------===//
1827
1828std::pair<unsigned, const TargetRegisterClass *>
1829XCoreTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
1830 StringRef Constraint,
1831 MVT VT) const {
1832 if (Constraint.size() == 1) {
1833 switch (Constraint[0]) {
1834 default : break;
1835 case 'r':
1836 return std::make_pair(x: 0U, y: &XCore::GRRegsRegClass);
1837 }
1838 }
1839 // Use the default implementation in TargetLowering to convert the register
1840 // constraint into a member of a register class.
1841 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
1842}
1843