Coverage Report

Created: 2019-07-24 05:18

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