1 //===-- VEISelLowering.cpp - VE 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 interfaces that VE uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "VEISelLowering.h"
15 #include "MCTargetDesc/VEMCExpr.h"
16 #include "VEMachineFunctionInfo.h"
17 #include "VERegisterInfo.h"
18 #include "VETargetMachine.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/CodeGen/CallingConvLower.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAG.h"
27 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/KnownBits.h"
33 using namespace llvm;
34 
35 #define DEBUG_TYPE "ve-lower"
36 
37 //===----------------------------------------------------------------------===//
38 // Calling Convention Implementation
39 //===----------------------------------------------------------------------===//
40 
41 #include "VEGenCallingConv.inc"
42 
43 CCAssignFn *getReturnCC(CallingConv::ID CallConv) {
44   switch (CallConv) {
45   default:
46     return RetCC_VE_C;
47   }
48 }
49 
50 CCAssignFn *getParamCC(CallingConv::ID CallConv, bool IsVarArg) {
51   if (IsVarArg)
52     return CC_VE2;
53   switch (CallConv) {
54   default:
55     return CC_VE_C;
56   }
57 }
58 
59 bool VETargetLowering::CanLowerReturn(
60     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
61     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
62   CCAssignFn *RetCC = getReturnCC(CallConv);
63   SmallVector<CCValAssign, 16> RVLocs;
64   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
65   return CCInfo.CheckReturn(Outs, RetCC);
66 }
67 
68 void VETargetLowering::initRegisterClasses() {
69   // Set up the register classes.
70   addRegisterClass(MVT::i32, &VE::I32RegClass);
71   addRegisterClass(MVT::i64, &VE::I64RegClass);
72   addRegisterClass(MVT::f32, &VE::F32RegClass);
73   addRegisterClass(MVT::f64, &VE::I64RegClass);
74   addRegisterClass(MVT::f128, &VE::F128RegClass);
75 
76   if (Subtarget->enableVPU()) {
77     addRegisterClass(MVT::v2i32, &VE::V64RegClass);
78     addRegisterClass(MVT::v4i32, &VE::V64RegClass);
79     addRegisterClass(MVT::v8i32, &VE::V64RegClass);
80     addRegisterClass(MVT::v16i32, &VE::V64RegClass);
81     addRegisterClass(MVT::v32i32, &VE::V64RegClass);
82     addRegisterClass(MVT::v64i32, &VE::V64RegClass);
83     addRegisterClass(MVT::v128i32, &VE::V64RegClass);
84     addRegisterClass(MVT::v256i32, &VE::V64RegClass);
85     addRegisterClass(MVT::v512i32, &VE::V64RegClass);
86 
87     addRegisterClass(MVT::v2i64, &VE::V64RegClass);
88     addRegisterClass(MVT::v4i64, &VE::V64RegClass);
89     addRegisterClass(MVT::v8i64, &VE::V64RegClass);
90     addRegisterClass(MVT::v16i64, &VE::V64RegClass);
91     addRegisterClass(MVT::v32i64, &VE::V64RegClass);
92     addRegisterClass(MVT::v64i64, &VE::V64RegClass);
93     addRegisterClass(MVT::v128i64, &VE::V64RegClass);
94     addRegisterClass(MVT::v256i64, &VE::V64RegClass);
95 
96     addRegisterClass(MVT::v2f32, &VE::V64RegClass);
97     addRegisterClass(MVT::v4f32, &VE::V64RegClass);
98     addRegisterClass(MVT::v8f32, &VE::V64RegClass);
99     addRegisterClass(MVT::v16f32, &VE::V64RegClass);
100     addRegisterClass(MVT::v32f32, &VE::V64RegClass);
101     addRegisterClass(MVT::v64f32, &VE::V64RegClass);
102     addRegisterClass(MVT::v128f32, &VE::V64RegClass);
103     addRegisterClass(MVT::v256f32, &VE::V64RegClass);
104     addRegisterClass(MVT::v512f32, &VE::V64RegClass);
105 
106     addRegisterClass(MVT::v2f64, &VE::V64RegClass);
107     addRegisterClass(MVT::v4f64, &VE::V64RegClass);
108     addRegisterClass(MVT::v8f64, &VE::V64RegClass);
109     addRegisterClass(MVT::v16f64, &VE::V64RegClass);
110     addRegisterClass(MVT::v32f64, &VE::V64RegClass);
111     addRegisterClass(MVT::v64f64, &VE::V64RegClass);
112     addRegisterClass(MVT::v128f64, &VE::V64RegClass);
113     addRegisterClass(MVT::v256f64, &VE::V64RegClass);
114 
115     addRegisterClass(MVT::v256i1, &VE::VMRegClass);
116     addRegisterClass(MVT::v512i1, &VE::VM512RegClass);
117   }
118 }
119 
120 void VETargetLowering::initSPUActions() {
121   const auto &TM = getTargetMachine();
122   /// Load & Store {
123 
124   // VE doesn't have i1 sign extending load.
125   for (MVT VT : MVT::integer_valuetypes()) {
126     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
127     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
128     setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
129     setTruncStoreAction(VT, MVT::i1, Expand);
130   }
131 
132   // VE doesn't have floating point extload/truncstore, so expand them.
133   for (MVT FPVT : MVT::fp_valuetypes()) {
134     for (MVT OtherFPVT : MVT::fp_valuetypes()) {
135       setLoadExtAction(ISD::EXTLOAD, FPVT, OtherFPVT, Expand);
136       setTruncStoreAction(FPVT, OtherFPVT, Expand);
137     }
138   }
139 
140   // VE doesn't have fp128 load/store, so expand them in custom lower.
141   setOperationAction(ISD::LOAD, MVT::f128, Custom);
142   setOperationAction(ISD::STORE, MVT::f128, Custom);
143 
144   /// } Load & Store
145 
146   // Custom legalize address nodes into LO/HI parts.
147   MVT PtrVT = MVT::getIntegerVT(TM.getPointerSizeInBits(0));
148   setOperationAction(ISD::BlockAddress, PtrVT, Custom);
149   setOperationAction(ISD::GlobalAddress, PtrVT, Custom);
150   setOperationAction(ISD::GlobalTLSAddress, PtrVT, Custom);
151   setOperationAction(ISD::ConstantPool, PtrVT, Custom);
152 
153   /// VAARG handling {
154   setOperationAction(ISD::VASTART, MVT::Other, Custom);
155   // VAARG needs to be lowered to access with 8 bytes alignment.
156   setOperationAction(ISD::VAARG, MVT::Other, Custom);
157   // Use the default implementation.
158   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
159   setOperationAction(ISD::VAEND, MVT::Other, Expand);
160   /// } VAARG handling
161 
162   /// Stack {
163   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
164   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
165   /// } Stack
166 
167   /// Branch {
168 
169   // VE doesn't have BRCOND
170   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
171 
172   // BRIND and BR_JT are not implemented yet.
173   // FIXME: Implement both for the scalar perforamnce.
174   setOperationAction(ISD::BRIND, MVT::Other, Expand);
175   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
176 
177   /// } Branch
178 
179   /// Int Ops {
180   for (MVT IntVT : {MVT::i32, MVT::i64}) {
181     // VE has no REM or DIVREM operations.
182     setOperationAction(ISD::UREM, IntVT, Expand);
183     setOperationAction(ISD::SREM, IntVT, Expand);
184     setOperationAction(ISD::SDIVREM, IntVT, Expand);
185     setOperationAction(ISD::UDIVREM, IntVT, Expand);
186 
187     // VE has no SHL_PARTS/SRA_PARTS/SRL_PARTS operations.
188     setOperationAction(ISD::SHL_PARTS, IntVT, Expand);
189     setOperationAction(ISD::SRA_PARTS, IntVT, Expand);
190     setOperationAction(ISD::SRL_PARTS, IntVT, Expand);
191 
192     // VE has no MULHU/S or U/SMUL_LOHI operations.
193     // TODO: Use MPD instruction to implement SMUL_LOHI for i32 type.
194     setOperationAction(ISD::MULHU, IntVT, Expand);
195     setOperationAction(ISD::MULHS, IntVT, Expand);
196     setOperationAction(ISD::UMUL_LOHI, IntVT, Expand);
197     setOperationAction(ISD::SMUL_LOHI, IntVT, Expand);
198 
199     // VE has no CTTZ, ROTL, ROTR operations.
200     setOperationAction(ISD::CTTZ, IntVT, Expand);
201     setOperationAction(ISD::ROTL, IntVT, Expand);
202     setOperationAction(ISD::ROTR, IntVT, Expand);
203 
204     // VE has 64 bits instruction which works as i64 BSWAP operation.  This
205     // instruction works fine as i32 BSWAP operation with an additional
206     // parameter.  Use isel patterns to lower BSWAP.
207     setOperationAction(ISD::BSWAP, IntVT, Legal);
208 
209     // VE has only 64 bits instructions which work as i64 BITREVERSE/CTLZ/CTPOP
210     // operations.  Use isel patterns for i64, promote for i32.
211     LegalizeAction Act = (IntVT == MVT::i32) ? Promote : Legal;
212     setOperationAction(ISD::BITREVERSE, IntVT, Act);
213     setOperationAction(ISD::CTLZ, IntVT, Act);
214     setOperationAction(ISD::CTLZ_ZERO_UNDEF, IntVT, Act);
215     setOperationAction(ISD::CTPOP, IntVT, Act);
216 
217     // VE has only 64 bits instructions which work as i64 AND/OR/XOR operations.
218     // Use isel patterns for i64, promote for i32.
219     setOperationAction(ISD::AND, IntVT, Act);
220     setOperationAction(ISD::OR, IntVT, Act);
221     setOperationAction(ISD::XOR, IntVT, Act);
222   }
223   /// } Int Ops
224 
225   /// Conversion {
226   // VE doesn't have instructions for fp<->uint, so expand them by llvm
227   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Promote); // use i64
228   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Promote); // use i64
229   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
230   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
231 
232   // fp16 not supported
233   for (MVT FPVT : MVT::fp_valuetypes()) {
234     setOperationAction(ISD::FP16_TO_FP, FPVT, Expand);
235     setOperationAction(ISD::FP_TO_FP16, FPVT, Expand);
236   }
237   /// } Conversion
238 
239   /// Floating-point Ops {
240   /// Note: Floating-point operations are fneg, fadd, fsub, fmul, fdiv, frem,
241   ///       and fcmp.
242 
243   // VE doesn't have following floating point operations.
244   for (MVT VT : MVT::fp_valuetypes()) {
245     setOperationAction(ISD::FNEG, VT, Expand);
246     setOperationAction(ISD::FREM, VT, Expand);
247   }
248 
249   // VE doesn't have fdiv of f128.
250   setOperationAction(ISD::FDIV, MVT::f128, Expand);
251 
252   for (MVT FPVT : {MVT::f32, MVT::f64}) {
253     // f32 and f64 uses ConstantFP.  f128 uses ConstantPool.
254     setOperationAction(ISD::ConstantFP, FPVT, Legal);
255   }
256   /// } Floating-point Ops
257 
258   /// Floating-point math functions {
259 
260   // VE doesn't have following floating point math functions.
261   for (MVT VT : MVT::fp_valuetypes()) {
262     setOperationAction(ISD::FABS, VT, Expand);
263     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
264     setOperationAction(ISD::FCOS, VT, Expand);
265     setOperationAction(ISD::FSIN, VT, Expand);
266     setOperationAction(ISD::FSQRT, VT, Expand);
267   }
268 
269   /// } Floating-point math functions
270 
271   /// Atomic instructions {
272 
273   setMaxAtomicSizeInBitsSupported(64);
274   setMinCmpXchgSizeInBits(32);
275   setSupportsUnalignedAtomics(false);
276 
277   // Use custom inserter for ATOMIC_FENCE.
278   setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
279 
280   /// } Atomic isntructions
281 }
282 
283 void VETargetLowering::initVPUActions() {
284   // TODO upstream vector isel
285 }
286 
287 SDValue
288 VETargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
289                               bool IsVarArg,
290                               const SmallVectorImpl<ISD::OutputArg> &Outs,
291                               const SmallVectorImpl<SDValue> &OutVals,
292                               const SDLoc &DL, SelectionDAG &DAG) const {
293   // CCValAssign - represent the assignment of the return value to locations.
294   SmallVector<CCValAssign, 16> RVLocs;
295 
296   // CCState - Info about the registers and stack slot.
297   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
298                  *DAG.getContext());
299 
300   // Analyze return values.
301   CCInfo.AnalyzeReturn(Outs, getReturnCC(CallConv));
302 
303   SDValue Flag;
304   SmallVector<SDValue, 4> RetOps(1, Chain);
305 
306   // Copy the result values into the output registers.
307   for (unsigned i = 0; i != RVLocs.size(); ++i) {
308     CCValAssign &VA = RVLocs[i];
309     assert(VA.isRegLoc() && "Can only return in registers!");
310     SDValue OutVal = OutVals[i];
311 
312     // Integer return values must be sign or zero extended by the callee.
313     switch (VA.getLocInfo()) {
314     case CCValAssign::Full:
315       break;
316     case CCValAssign::SExt:
317       OutVal = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), OutVal);
318       break;
319     case CCValAssign::ZExt:
320       OutVal = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), OutVal);
321       break;
322     case CCValAssign::AExt:
323       OutVal = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), OutVal);
324       break;
325     case CCValAssign::BCvt: {
326       // Convert a float return value to i64 with padding.
327       //     63     31   0
328       //    +------+------+
329       //    | float|   0  |
330       //    +------+------+
331       assert(VA.getLocVT() == MVT::i64);
332       assert(VA.getValVT() == MVT::f32);
333       SDValue Undef = SDValue(
334           DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::i64), 0);
335       SDValue Sub_f32 = DAG.getTargetConstant(VE::sub_f32, DL, MVT::i32);
336       OutVal = SDValue(DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
337                                           MVT::i64, Undef, OutVal, Sub_f32),
338                        0);
339       break;
340     }
341     default:
342       llvm_unreachable("Unknown loc info!");
343     }
344 
345     assert(!VA.needsCustom() && "Unexpected custom lowering");
346 
347     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), OutVal, Flag);
348 
349     // Guarantee that all emitted copies are stuck together with flags.
350     Flag = Chain.getValue(1);
351     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
352   }
353 
354   RetOps[0] = Chain; // Update chain.
355 
356   // Add the flag if we have it.
357   if (Flag.getNode())
358     RetOps.push_back(Flag);
359 
360   return DAG.getNode(VEISD::RET_FLAG, DL, MVT::Other, RetOps);
361 }
362 
363 SDValue VETargetLowering::LowerFormalArguments(
364     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
365     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
366     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
367   MachineFunction &MF = DAG.getMachineFunction();
368 
369   // Get the base offset of the incoming arguments stack space.
370   unsigned ArgsBaseOffset = 176;
371   // Get the size of the preserved arguments area
372   unsigned ArgsPreserved = 64;
373 
374   // Analyze arguments according to CC_VE.
375   SmallVector<CCValAssign, 16> ArgLocs;
376   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
377                  *DAG.getContext());
378   // Allocate the preserved area first.
379   CCInfo.AllocateStack(ArgsPreserved, Align(8));
380   // We already allocated the preserved area, so the stack offset computed
381   // by CC_VE would be correct now.
382   CCInfo.AnalyzeFormalArguments(Ins, getParamCC(CallConv, false));
383 
384   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
385     CCValAssign &VA = ArgLocs[i];
386     if (VA.isRegLoc()) {
387       // This argument is passed in a register.
388       // All integer register arguments are promoted by the caller to i64.
389 
390       // Create a virtual register for the promoted live-in value.
391       unsigned VReg =
392           MF.addLiveIn(VA.getLocReg(), getRegClassFor(VA.getLocVT()));
393       SDValue Arg = DAG.getCopyFromReg(Chain, DL, VReg, VA.getLocVT());
394 
395       // Get the high bits for i32 struct elements.
396       if (VA.getValVT() == MVT::i32 && VA.needsCustom())
397         Arg = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Arg,
398                           DAG.getConstant(32, DL, MVT::i32));
399 
400       // The caller promoted the argument, so insert an Assert?ext SDNode so we
401       // won't promote the value again in this function.
402       switch (VA.getLocInfo()) {
403       case CCValAssign::SExt:
404         Arg = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Arg,
405                           DAG.getValueType(VA.getValVT()));
406         break;
407       case CCValAssign::ZExt:
408         Arg = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Arg,
409                           DAG.getValueType(VA.getValVT()));
410         break;
411       case CCValAssign::BCvt: {
412         // Extract a float argument from i64 with padding.
413         //     63     31   0
414         //    +------+------+
415         //    | float|   0  |
416         //    +------+------+
417         assert(VA.getLocVT() == MVT::i64);
418         assert(VA.getValVT() == MVT::f32);
419         SDValue Sub_f32 = DAG.getTargetConstant(VE::sub_f32, DL, MVT::i32);
420         Arg = SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
421                                          MVT::f32, Arg, Sub_f32),
422                       0);
423         break;
424       }
425       default:
426         break;
427       }
428 
429       // Truncate the register down to the argument type.
430       if (VA.isExtInLoc())
431         Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
432 
433       InVals.push_back(Arg);
434       continue;
435     }
436 
437     // The registers are exhausted. This argument was passed on the stack.
438     assert(VA.isMemLoc());
439     // The CC_VE_Full/Half functions compute stack offsets relative to the
440     // beginning of the arguments area at %fp+176.
441     unsigned Offset = VA.getLocMemOffset() + ArgsBaseOffset;
442     unsigned ValSize = VA.getValVT().getSizeInBits() / 8;
443 
444     // Adjust offset for a float argument by adding 4 since the argument is
445     // stored in 8 bytes buffer with offset like below.  LLVM generates
446     // 4 bytes load instruction, so need to adjust offset here.  This
447     // adjustment is required in only LowerFormalArguments.  In LowerCall,
448     // a float argument is converted to i64 first, and stored as 8 bytes
449     // data, which is required by ABI, so no need for adjustment.
450     //    0      4
451     //    +------+------+
452     //    | empty| float|
453     //    +------+------+
454     if (VA.getValVT() == MVT::f32)
455       Offset += 4;
456 
457     int FI = MF.getFrameInfo().CreateFixedObject(ValSize, Offset, true);
458     InVals.push_back(
459         DAG.getLoad(VA.getValVT(), DL, Chain,
460                     DAG.getFrameIndex(FI, getPointerTy(MF.getDataLayout())),
461                     MachinePointerInfo::getFixedStack(MF, FI)));
462   }
463 
464   if (!IsVarArg)
465     return Chain;
466 
467   // This function takes variable arguments, some of which may have been passed
468   // in registers %s0-%s8.
469   //
470   // The va_start intrinsic needs to know the offset to the first variable
471   // argument.
472   // TODO: need to calculate offset correctly once we support f128.
473   unsigned ArgOffset = ArgLocs.size() * 8;
474   VEMachineFunctionInfo *FuncInfo = MF.getInfo<VEMachineFunctionInfo>();
475   // Skip the 176 bytes of register save area.
476   FuncInfo->setVarArgsFrameOffset(ArgOffset + ArgsBaseOffset);
477 
478   return Chain;
479 }
480 
481 // FIXME? Maybe this could be a TableGen attribute on some registers and
482 // this table could be generated automatically from RegInfo.
483 Register VETargetLowering::getRegisterByName(const char *RegName, LLT VT,
484                                              const MachineFunction &MF) const {
485   Register Reg = StringSwitch<Register>(RegName)
486                      .Case("sp", VE::SX11)    // Stack pointer
487                      .Case("fp", VE::SX9)     // Frame pointer
488                      .Case("sl", VE::SX8)     // Stack limit
489                      .Case("lr", VE::SX10)    // Link register
490                      .Case("tp", VE::SX14)    // Thread pointer
491                      .Case("outer", VE::SX12) // Outer regiser
492                      .Case("info", VE::SX17)  // Info area register
493                      .Case("got", VE::SX15)   // Global offset table register
494                      .Case("plt", VE::SX16) // Procedure linkage table register
495                      .Default(0);
496 
497   if (Reg)
498     return Reg;
499 
500   report_fatal_error("Invalid register name global variable");
501 }
502 
503 //===----------------------------------------------------------------------===//
504 // TargetLowering Implementation
505 //===----------------------------------------------------------------------===//
506 
507 SDValue VETargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
508                                     SmallVectorImpl<SDValue> &InVals) const {
509   SelectionDAG &DAG = CLI.DAG;
510   SDLoc DL = CLI.DL;
511   SDValue Chain = CLI.Chain;
512   auto PtrVT = getPointerTy(DAG.getDataLayout());
513 
514   // VE target does not yet support tail call optimization.
515   CLI.IsTailCall = false;
516 
517   // Get the base offset of the outgoing arguments stack space.
518   unsigned ArgsBaseOffset = 176;
519   // Get the size of the preserved arguments area
520   unsigned ArgsPreserved = 8 * 8u;
521 
522   // Analyze operands of the call, assigning locations to each operand.
523   SmallVector<CCValAssign, 16> ArgLocs;
524   CCState CCInfo(CLI.CallConv, CLI.IsVarArg, DAG.getMachineFunction(), ArgLocs,
525                  *DAG.getContext());
526   // Allocate the preserved area first.
527   CCInfo.AllocateStack(ArgsPreserved, Align(8));
528   // We already allocated the preserved area, so the stack offset computed
529   // by CC_VE would be correct now.
530   CCInfo.AnalyzeCallOperands(CLI.Outs, getParamCC(CLI.CallConv, false));
531 
532   // VE requires to use both register and stack for varargs or no-prototyped
533   // functions.
534   bool UseBoth = CLI.IsVarArg;
535 
536   // Analyze operands again if it is required to store BOTH.
537   SmallVector<CCValAssign, 16> ArgLocs2;
538   CCState CCInfo2(CLI.CallConv, CLI.IsVarArg, DAG.getMachineFunction(),
539                   ArgLocs2, *DAG.getContext());
540   if (UseBoth)
541     CCInfo2.AnalyzeCallOperands(CLI.Outs, getParamCC(CLI.CallConv, true));
542 
543   // Get the size of the outgoing arguments stack space requirement.
544   unsigned ArgsSize = CCInfo.getNextStackOffset();
545 
546   // Keep stack frames 16-byte aligned.
547   ArgsSize = alignTo(ArgsSize, 16);
548 
549   // Adjust the stack pointer to make room for the arguments.
550   // FIXME: Use hasReservedCallFrame to avoid %sp adjustments around all calls
551   // with more than 6 arguments.
552   Chain = DAG.getCALLSEQ_START(Chain, ArgsSize, 0, DL);
553 
554   // Collect the set of registers to pass to the function and their values.
555   // This will be emitted as a sequence of CopyToReg nodes glued to the call
556   // instruction.
557   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
558 
559   // Collect chains from all the memory opeations that copy arguments to the
560   // stack. They must follow the stack pointer adjustment above and precede the
561   // call instruction itself.
562   SmallVector<SDValue, 8> MemOpChains;
563 
564   // VE needs to get address of callee function in a register
565   // So, prepare to copy it to SX12 here.
566 
567   // If the callee is a GlobalAddress node (quite common, every direct call is)
568   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
569   // Likewise ExternalSymbol -> TargetExternalSymbol.
570   SDValue Callee = CLI.Callee;
571 
572   bool IsPICCall = isPositionIndependent();
573 
574   // PC-relative references to external symbols should go through $stub.
575   // If so, we need to prepare GlobalBaseReg first.
576   const TargetMachine &TM = DAG.getTarget();
577   const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
578   const GlobalValue *GV = nullptr;
579   auto *CalleeG = dyn_cast<GlobalAddressSDNode>(Callee);
580   if (CalleeG)
581     GV = CalleeG->getGlobal();
582   bool Local = TM.shouldAssumeDSOLocal(*Mod, GV);
583   bool UsePlt = !Local;
584   MachineFunction &MF = DAG.getMachineFunction();
585 
586   // Turn GlobalAddress/ExternalSymbol node into a value node
587   // containing the address of them here.
588   if (CalleeG) {
589     if (IsPICCall) {
590       if (UsePlt)
591         Subtarget->getInstrInfo()->getGlobalBaseReg(&MF);
592       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
593       Callee = DAG.getNode(VEISD::GETFUNPLT, DL, PtrVT, Callee);
594     } else {
595       Callee =
596           makeHiLoPair(Callee, VEMCExpr::VK_VE_HI32, VEMCExpr::VK_VE_LO32, DAG);
597     }
598   } else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
599     if (IsPICCall) {
600       if (UsePlt)
601         Subtarget->getInstrInfo()->getGlobalBaseReg(&MF);
602       Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT, 0);
603       Callee = DAG.getNode(VEISD::GETFUNPLT, DL, PtrVT, Callee);
604     } else {
605       Callee =
606           makeHiLoPair(Callee, VEMCExpr::VK_VE_HI32, VEMCExpr::VK_VE_LO32, DAG);
607     }
608   }
609 
610   RegsToPass.push_back(std::make_pair(VE::SX12, Callee));
611 
612   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
613     CCValAssign &VA = ArgLocs[i];
614     SDValue Arg = CLI.OutVals[i];
615 
616     // Promote the value if needed.
617     switch (VA.getLocInfo()) {
618     default:
619       llvm_unreachable("Unknown location info!");
620     case CCValAssign::Full:
621       break;
622     case CCValAssign::SExt:
623       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
624       break;
625     case CCValAssign::ZExt:
626       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
627       break;
628     case CCValAssign::AExt:
629       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
630       break;
631     case CCValAssign::BCvt: {
632       // Convert a float argument to i64 with padding.
633       //     63     31   0
634       //    +------+------+
635       //    | float|   0  |
636       //    +------+------+
637       assert(VA.getLocVT() == MVT::i64);
638       assert(VA.getValVT() == MVT::f32);
639       SDValue Undef = SDValue(
640           DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::i64), 0);
641       SDValue Sub_f32 = DAG.getTargetConstant(VE::sub_f32, DL, MVT::i32);
642       Arg = SDValue(DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
643                                        MVT::i64, Undef, Arg, Sub_f32),
644                     0);
645       break;
646     }
647     }
648 
649     if (VA.isRegLoc()) {
650       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
651       if (!UseBoth)
652         continue;
653       VA = ArgLocs2[i];
654     }
655 
656     assert(VA.isMemLoc());
657 
658     // Create a store off the stack pointer for this argument.
659     SDValue StackPtr = DAG.getRegister(VE::SX11, PtrVT);
660     // The argument area starts at %fp+176 in the callee frame,
661     // %sp+176 in ours.
662     SDValue PtrOff =
663         DAG.getIntPtrConstant(VA.getLocMemOffset() + ArgsBaseOffset, DL);
664     PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
665     MemOpChains.push_back(
666         DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo()));
667   }
668 
669   // Emit all stores, make sure they occur before the call.
670   if (!MemOpChains.empty())
671     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
672 
673   // Build a sequence of CopyToReg nodes glued together with token chain and
674   // glue operands which copy the outgoing args into registers. The InGlue is
675   // necessary since all emitted instructions must be stuck together in order
676   // to pass the live physical registers.
677   SDValue InGlue;
678   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
679     Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[i].first,
680                              RegsToPass[i].second, InGlue);
681     InGlue = Chain.getValue(1);
682   }
683 
684   // Build the operands for the call instruction itself.
685   SmallVector<SDValue, 8> Ops;
686   Ops.push_back(Chain);
687   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
688     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
689                                   RegsToPass[i].second.getValueType()));
690 
691   // Add a register mask operand representing the call-preserved registers.
692   const VERegisterInfo *TRI = Subtarget->getRegisterInfo();
693   const uint32_t *Mask =
694       TRI->getCallPreservedMask(DAG.getMachineFunction(), CLI.CallConv);
695   assert(Mask && "Missing call preserved mask for calling convention");
696   Ops.push_back(DAG.getRegisterMask(Mask));
697 
698   // Make sure the CopyToReg nodes are glued to the call instruction which
699   // consumes the registers.
700   if (InGlue.getNode())
701     Ops.push_back(InGlue);
702 
703   // Now the call itself.
704   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
705   Chain = DAG.getNode(VEISD::CALL, DL, NodeTys, Ops);
706   InGlue = Chain.getValue(1);
707 
708   // Revert the stack pointer immediately after the call.
709   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(ArgsSize, DL, true),
710                              DAG.getIntPtrConstant(0, DL, true), InGlue, DL);
711   InGlue = Chain.getValue(1);
712 
713   // Now extract the return values. This is more or less the same as
714   // LowerFormalArguments.
715 
716   // Assign locations to each value returned by this call.
717   SmallVector<CCValAssign, 16> RVLocs;
718   CCState RVInfo(CLI.CallConv, CLI.IsVarArg, DAG.getMachineFunction(), RVLocs,
719                  *DAG.getContext());
720 
721   // Set inreg flag manually for codegen generated library calls that
722   // return float.
723   if (CLI.Ins.size() == 1 && CLI.Ins[0].VT == MVT::f32 && !CLI.CB)
724     CLI.Ins[0].Flags.setInReg();
725 
726   RVInfo.AnalyzeCallResult(CLI.Ins, getReturnCC(CLI.CallConv));
727 
728   // Copy all of the result registers out of their specified physreg.
729   for (unsigned i = 0; i != RVLocs.size(); ++i) {
730     CCValAssign &VA = RVLocs[i];
731     unsigned Reg = VA.getLocReg();
732 
733     // When returning 'inreg {i32, i32 }', two consecutive i32 arguments can
734     // reside in the same register in the high and low bits. Reuse the
735     // CopyFromReg previous node to avoid duplicate copies.
736     SDValue RV;
737     if (RegisterSDNode *SrcReg = dyn_cast<RegisterSDNode>(Chain.getOperand(1)))
738       if (SrcReg->getReg() == Reg && Chain->getOpcode() == ISD::CopyFromReg)
739         RV = Chain.getValue(0);
740 
741     // But usually we'll create a new CopyFromReg for a different register.
742     if (!RV.getNode()) {
743       RV = DAG.getCopyFromReg(Chain, DL, Reg, RVLocs[i].getLocVT(), InGlue);
744       Chain = RV.getValue(1);
745       InGlue = Chain.getValue(2);
746     }
747 
748     // Get the high bits for i32 struct elements.
749     if (VA.getValVT() == MVT::i32 && VA.needsCustom())
750       RV = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), RV,
751                        DAG.getConstant(32, DL, MVT::i32));
752 
753     // The callee promoted the return value, so insert an Assert?ext SDNode so
754     // we won't promote the value again in this function.
755     switch (VA.getLocInfo()) {
756     case CCValAssign::SExt:
757       RV = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), RV,
758                        DAG.getValueType(VA.getValVT()));
759       break;
760     case CCValAssign::ZExt:
761       RV = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), RV,
762                        DAG.getValueType(VA.getValVT()));
763       break;
764     case CCValAssign::BCvt: {
765       // Extract a float return value from i64 with padding.
766       //     63     31   0
767       //    +------+------+
768       //    | float|   0  |
769       //    +------+------+
770       assert(VA.getLocVT() == MVT::i64);
771       assert(VA.getValVT() == MVT::f32);
772       SDValue Sub_f32 = DAG.getTargetConstant(VE::sub_f32, DL, MVT::i32);
773       RV = SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
774                                       MVT::f32, RV, Sub_f32),
775                    0);
776       break;
777     }
778     default:
779       break;
780     }
781 
782     // Truncate the register down to the return value type.
783     if (VA.isExtInLoc())
784       RV = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), RV);
785 
786     InVals.push_back(RV);
787   }
788 
789   return Chain;
790 }
791 
792 bool VETargetLowering::isOffsetFoldingLegal(
793     const GlobalAddressSDNode *GA) const {
794   // VE uses 64 bit addressing, so we need multiple instructions to generate
795   // an address.  Folding address with offset increases the number of
796   // instructions, so that we disable it here.  Offsets will be folded in
797   // the DAG combine later if it worth to do so.
798   return false;
799 }
800 
801 /// isFPImmLegal - Returns true if the target can instruction select the
802 /// specified FP immediate natively. If false, the legalizer will
803 /// materialize the FP immediate as a load from a constant pool.
804 bool VETargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
805                                     bool ForCodeSize) const {
806   return VT == MVT::f32 || VT == MVT::f64;
807 }
808 
809 /// Determine if the target supports unaligned memory accesses.
810 ///
811 /// This function returns true if the target allows unaligned memory accesses
812 /// of the specified type in the given address space. If true, it also returns
813 /// whether the unaligned memory access is "fast" in the last argument by
814 /// reference. This is used, for example, in situations where an array
815 /// copy/move/set is converted to a sequence of store operations. Its use
816 /// helps to ensure that such replacements don't generate code that causes an
817 /// alignment error (trap) on the target machine.
818 bool VETargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
819                                                       unsigned AddrSpace,
820                                                       unsigned Align,
821                                                       MachineMemOperand::Flags,
822                                                       bool *Fast) const {
823   if (Fast) {
824     // It's fast anytime on VE
825     *Fast = true;
826   }
827   return true;
828 }
829 
830 bool VETargetLowering::hasAndNot(SDValue Y) const {
831   EVT VT = Y.getValueType();
832 
833   // VE doesn't have vector and not instruction.
834   if (VT.isVector())
835     return false;
836 
837   // VE allows different immediate values for X and Y where ~X & Y.
838   // Only simm7 works for X, and only mimm works for Y on VE.  However, this
839   // function is used to check whether an immediate value is OK for and-not
840   // instruction as both X and Y.  Generating additional instruction to
841   // retrieve an immediate value is no good since the purpose of this
842   // function is to convert a series of 3 instructions to another series of
843   // 3 instructions with better parallelism.  Therefore, we return false
844   // for all immediate values now.
845   // FIXME: Change hasAndNot function to have two operands to make it work
846   //        correctly with Aurora VE.
847   if (isa<ConstantSDNode>(Y))
848     return false;
849 
850   // It's ok for generic registers.
851   return true;
852 }
853 
854 VETargetLowering::VETargetLowering(const TargetMachine &TM,
855                                    const VESubtarget &STI)
856     : TargetLowering(TM), Subtarget(&STI) {
857   // Instructions which use registers as conditionals examine all the
858   // bits (as does the pseudo SELECT_CC expansion). I don't think it
859   // matters much whether it's ZeroOrOneBooleanContent, or
860   // ZeroOrNegativeOneBooleanContent, so, arbitrarily choose the
861   // former.
862   setBooleanContents(ZeroOrOneBooleanContent);
863   setBooleanVectorContents(ZeroOrOneBooleanContent);
864 
865   initRegisterClasses();
866   initSPUActions();
867   initVPUActions();
868 
869   setStackPointerRegisterToSaveRestore(VE::SX11);
870 
871   // We have target-specific dag combine patterns for the following nodes:
872   setTargetDAGCombine(ISD::TRUNCATE);
873 
874   // Set function alignment to 16 bytes
875   setMinFunctionAlignment(Align(16));
876 
877   // VE stores all argument by 8 bytes alignment
878   setMinStackArgumentAlignment(Align(8));
879 
880   computeRegisterProperties(Subtarget->getRegisterInfo());
881 }
882 
883 const char *VETargetLowering::getTargetNodeName(unsigned Opcode) const {
884 #define TARGET_NODE_CASE(NAME)                                                 \
885   case VEISD::NAME:                                                            \
886     return "VEISD::" #NAME;
887   switch ((VEISD::NodeType)Opcode) {
888   case VEISD::FIRST_NUMBER:
889     break;
890     TARGET_NODE_CASE(Lo)
891     TARGET_NODE_CASE(Hi)
892     TARGET_NODE_CASE(GETFUNPLT)
893     TARGET_NODE_CASE(GETSTACKTOP)
894     TARGET_NODE_CASE(GETTLSADDR)
895     TARGET_NODE_CASE(MEMBARRIER)
896     TARGET_NODE_CASE(CALL)
897     TARGET_NODE_CASE(RET_FLAG)
898     TARGET_NODE_CASE(GLOBAL_BASE_REG)
899   }
900 #undef TARGET_NODE_CASE
901   return nullptr;
902 }
903 
904 EVT VETargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
905                                          EVT VT) const {
906   return MVT::i32;
907 }
908 
909 // Convert to a target node and set target flags.
910 SDValue VETargetLowering::withTargetFlags(SDValue Op, unsigned TF,
911                                           SelectionDAG &DAG) const {
912   if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op))
913     return DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(GA),
914                                       GA->getValueType(0), GA->getOffset(), TF);
915 
916   if (const BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(Op))
917     return DAG.getTargetBlockAddress(BA->getBlockAddress(), Op.getValueType(),
918                                      0, TF);
919 
920   if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op))
921     return DAG.getTargetConstantPool(CP->getConstVal(), CP->getValueType(0),
922                                      CP->getAlign(), CP->getOffset(), TF);
923 
924   if (const ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op))
925     return DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0),
926                                        TF);
927 
928   llvm_unreachable("Unhandled address SDNode");
929 }
930 
931 // Split Op into high and low parts according to HiTF and LoTF.
932 // Return an ADD node combining the parts.
933 SDValue VETargetLowering::makeHiLoPair(SDValue Op, unsigned HiTF, unsigned LoTF,
934                                        SelectionDAG &DAG) const {
935   SDLoc DL(Op);
936   EVT VT = Op.getValueType();
937   SDValue Hi = DAG.getNode(VEISD::Hi, DL, VT, withTargetFlags(Op, HiTF, DAG));
938   SDValue Lo = DAG.getNode(VEISD::Lo, DL, VT, withTargetFlags(Op, LoTF, DAG));
939   return DAG.getNode(ISD::ADD, DL, VT, Hi, Lo);
940 }
941 
942 // Build SDNodes for producing an address from a GlobalAddress, ConstantPool,
943 // or ExternalSymbol SDNode.
944 SDValue VETargetLowering::makeAddress(SDValue Op, SelectionDAG &DAG) const {
945   SDLoc DL(Op);
946   EVT PtrVT = Op.getValueType();
947 
948   // Handle PIC mode first. VE needs a got load for every variable!
949   if (isPositionIndependent()) {
950     // GLOBAL_BASE_REG codegen'ed with call. Inform MFI that this
951     // function has calls.
952     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
953     MFI.setHasCalls(true);
954     auto GlobalN = dyn_cast<GlobalAddressSDNode>(Op);
955 
956     if (isa<ConstantPoolSDNode>(Op) ||
957         (GlobalN && GlobalN->getGlobal()->hasLocalLinkage())) {
958       // Create following instructions for local linkage PIC code.
959       //     lea %reg, label@gotoff_lo
960       //     and %reg, %reg, (32)0
961       //     lea.sl %reg, label@gotoff_hi(%reg, %got)
962       SDValue HiLo = makeHiLoPair(Op, VEMCExpr::VK_VE_GOTOFF_HI32,
963                                   VEMCExpr::VK_VE_GOTOFF_LO32, DAG);
964       SDValue GlobalBase = DAG.getNode(VEISD::GLOBAL_BASE_REG, DL, PtrVT);
965       return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalBase, HiLo);
966     }
967     // Create following instructions for not local linkage PIC code.
968     //     lea %reg, label@got_lo
969     //     and %reg, %reg, (32)0
970     //     lea.sl %reg, label@got_hi(%reg)
971     //     ld %reg, (%reg, %got)
972     SDValue HiLo = makeHiLoPair(Op, VEMCExpr::VK_VE_GOT_HI32,
973                                 VEMCExpr::VK_VE_GOT_LO32, DAG);
974     SDValue GlobalBase = DAG.getNode(VEISD::GLOBAL_BASE_REG, DL, PtrVT);
975     SDValue AbsAddr = DAG.getNode(ISD::ADD, DL, PtrVT, GlobalBase, HiLo);
976     return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), AbsAddr,
977                        MachinePointerInfo::getGOT(DAG.getMachineFunction()));
978   }
979 
980   // This is one of the absolute code models.
981   switch (getTargetMachine().getCodeModel()) {
982   default:
983     llvm_unreachable("Unsupported absolute code model");
984   case CodeModel::Small:
985   case CodeModel::Medium:
986   case CodeModel::Large:
987     // abs64.
988     return makeHiLoPair(Op, VEMCExpr::VK_VE_HI32, VEMCExpr::VK_VE_LO32, DAG);
989   }
990 }
991 
992 /// Custom Lower {
993 
994 // The mappings for emitLeading/TrailingFence for VE is designed by following
995 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
996 Instruction *VETargetLowering::emitLeadingFence(IRBuilder<> &Builder,
997                                                 Instruction *Inst,
998                                                 AtomicOrdering Ord) const {
999   switch (Ord) {
1000   case AtomicOrdering::NotAtomic:
1001   case AtomicOrdering::Unordered:
1002     llvm_unreachable("Invalid fence: unordered/non-atomic");
1003   case AtomicOrdering::Monotonic:
1004   case AtomicOrdering::Acquire:
1005     return nullptr; // Nothing to do
1006   case AtomicOrdering::Release:
1007   case AtomicOrdering::AcquireRelease:
1008     return Builder.CreateFence(AtomicOrdering::Release);
1009   case AtomicOrdering::SequentiallyConsistent:
1010     if (!Inst->hasAtomicStore())
1011       return nullptr; // Nothing to do
1012     return Builder.CreateFence(AtomicOrdering::SequentiallyConsistent);
1013   }
1014   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
1015 }
1016 
1017 Instruction *VETargetLowering::emitTrailingFence(IRBuilder<> &Builder,
1018                                                  Instruction *Inst,
1019                                                  AtomicOrdering Ord) const {
1020   switch (Ord) {
1021   case AtomicOrdering::NotAtomic:
1022   case AtomicOrdering::Unordered:
1023     llvm_unreachable("Invalid fence: unordered/not-atomic");
1024   case AtomicOrdering::Monotonic:
1025   case AtomicOrdering::Release:
1026     return nullptr; // Nothing to do
1027   case AtomicOrdering::Acquire:
1028   case AtomicOrdering::AcquireRelease:
1029     return Builder.CreateFence(AtomicOrdering::Acquire);
1030   case AtomicOrdering::SequentiallyConsistent:
1031     return Builder.CreateFence(AtomicOrdering::SequentiallyConsistent);
1032   }
1033   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
1034 }
1035 
1036 SDValue VETargetLowering::lowerATOMIC_FENCE(SDValue Op,
1037                                             SelectionDAG &DAG) const {
1038   SDLoc DL(Op);
1039   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
1040       cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
1041   SyncScope::ID FenceSSID = static_cast<SyncScope::ID>(
1042       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
1043 
1044   // VE uses Release consistency, so need a fence instruction if it is a
1045   // cross-thread fence.
1046   if (FenceSSID == SyncScope::System) {
1047     switch (FenceOrdering) {
1048     case AtomicOrdering::NotAtomic:
1049     case AtomicOrdering::Unordered:
1050     case AtomicOrdering::Monotonic:
1051       // No need to generate fencem instruction here.
1052       break;
1053     case AtomicOrdering::Acquire:
1054       // Generate "fencem 2" as acquire fence.
1055       return SDValue(DAG.getMachineNode(VE::FENCEM, DL, MVT::Other,
1056                                         DAG.getTargetConstant(2, DL, MVT::i32),
1057                                         Op.getOperand(0)),
1058                      0);
1059     case AtomicOrdering::Release:
1060       // Generate "fencem 1" as release fence.
1061       return SDValue(DAG.getMachineNode(VE::FENCEM, DL, MVT::Other,
1062                                         DAG.getTargetConstant(1, DL, MVT::i32),
1063                                         Op.getOperand(0)),
1064                      0);
1065     case AtomicOrdering::AcquireRelease:
1066     case AtomicOrdering::SequentiallyConsistent:
1067       // Generate "fencem 3" as acq_rel and seq_cst fence.
1068       // FIXME: "fencem 3" doesn't wait for for PCIe deveices accesses,
1069       //        so  seq_cst may require more instruction for them.
1070       return SDValue(DAG.getMachineNode(VE::FENCEM, DL, MVT::Other,
1071                                         DAG.getTargetConstant(3, DL, MVT::i32),
1072                                         Op.getOperand(0)),
1073                      0);
1074     }
1075   }
1076 
1077   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
1078   return DAG.getNode(VEISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
1079 }
1080 
1081 SDValue VETargetLowering::lowerGlobalAddress(SDValue Op,
1082                                              SelectionDAG &DAG) const {
1083   return makeAddress(Op, DAG);
1084 }
1085 
1086 SDValue VETargetLowering::lowerBlockAddress(SDValue Op,
1087                                             SelectionDAG &DAG) const {
1088   return makeAddress(Op, DAG);
1089 }
1090 
1091 SDValue VETargetLowering::lowerConstantPool(SDValue Op,
1092                                             SelectionDAG &DAG) const {
1093   return makeAddress(Op, DAG);
1094 }
1095 
1096 SDValue
1097 VETargetLowering::lowerToTLSGeneralDynamicModel(SDValue Op,
1098                                                 SelectionDAG &DAG) const {
1099   SDLoc DL(Op);
1100 
1101   // Generate the following code:
1102   //   t1: ch,glue = callseq_start t0, 0, 0
1103   //   t2: i64,ch,glue = VEISD::GETTLSADDR t1, label, t1:1
1104   //   t3: ch,glue = callseq_end t2, 0, 0, t2:2
1105   //   t4: i64,ch,glue = CopyFromReg t3, Register:i64 $sx0, t3:1
1106   SDValue Label = withTargetFlags(Op, 0, DAG);
1107   EVT PtrVT = Op.getValueType();
1108 
1109   // Lowering the machine isd will make sure everything is in the right
1110   // location.
1111   SDValue Chain = DAG.getEntryNode();
1112   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1113   const uint32_t *Mask = Subtarget->getRegisterInfo()->getCallPreservedMask(
1114       DAG.getMachineFunction(), CallingConv::C);
1115   Chain = DAG.getCALLSEQ_START(Chain, 64, 0, DL);
1116   SDValue Args[] = {Chain, Label, DAG.getRegisterMask(Mask), Chain.getValue(1)};
1117   Chain = DAG.getNode(VEISD::GETTLSADDR, DL, NodeTys, Args);
1118   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(64, DL, true),
1119                              DAG.getIntPtrConstant(0, DL, true),
1120                              Chain.getValue(1), DL);
1121   Chain = DAG.getCopyFromReg(Chain, DL, VE::SX0, PtrVT, Chain.getValue(1));
1122 
1123   // GETTLSADDR will be codegen'ed as call. Inform MFI that function has calls.
1124   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
1125   MFI.setHasCalls(true);
1126 
1127   // Also generate code to prepare a GOT register if it is PIC.
1128   if (isPositionIndependent()) {
1129     MachineFunction &MF = DAG.getMachineFunction();
1130     Subtarget->getInstrInfo()->getGlobalBaseReg(&MF);
1131   }
1132 
1133   return Chain;
1134 }
1135 
1136 SDValue VETargetLowering::lowerGlobalTLSAddress(SDValue Op,
1137                                                 SelectionDAG &DAG) const {
1138   // The current implementation of nld (2.26) doesn't allow local exec model
1139   // code described in VE-tls_v1.1.pdf (*1) as its input. Instead, we always
1140   // generate the general dynamic model code sequence.
1141   //
1142   // *1: https://www.nec.com/en/global/prod/hpc/aurora/document/VE-tls_v1.1.pdf
1143   return lowerToTLSGeneralDynamicModel(Op, DAG);
1144 }
1145 
1146 // Lower a f128 load into two f64 loads.
1147 static SDValue lowerLoadF128(SDValue Op, SelectionDAG &DAG) {
1148   SDLoc DL(Op);
1149   LoadSDNode *LdNode = dyn_cast<LoadSDNode>(Op.getNode());
1150   assert(LdNode && LdNode->getOffset().isUndef() && "Unexpected node type");
1151   unsigned Alignment = LdNode->getAlign().value();
1152   if (Alignment > 8)
1153     Alignment = 8;
1154 
1155   SDValue Lo64 =
1156       DAG.getLoad(MVT::f64, DL, LdNode->getChain(), LdNode->getBasePtr(),
1157                   LdNode->getPointerInfo(), Alignment,
1158                   LdNode->isVolatile() ? MachineMemOperand::MOVolatile
1159                                        : MachineMemOperand::MONone);
1160   EVT AddrVT = LdNode->getBasePtr().getValueType();
1161   SDValue HiPtr = DAG.getNode(ISD::ADD, DL, AddrVT, LdNode->getBasePtr(),
1162                               DAG.getConstant(8, DL, AddrVT));
1163   SDValue Hi64 =
1164       DAG.getLoad(MVT::f64, DL, LdNode->getChain(), HiPtr,
1165                   LdNode->getPointerInfo(), Alignment,
1166                   LdNode->isVolatile() ? MachineMemOperand::MOVolatile
1167                                        : MachineMemOperand::MONone);
1168 
1169   SDValue SubRegEven = DAG.getTargetConstant(VE::sub_even, DL, MVT::i32);
1170   SDValue SubRegOdd = DAG.getTargetConstant(VE::sub_odd, DL, MVT::i32);
1171 
1172   // VE stores Hi64 to 8(addr) and Lo64 to 0(addr)
1173   SDNode *InFP128 =
1174       DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f128);
1175   InFP128 = DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f128,
1176                                SDValue(InFP128, 0), Hi64, SubRegEven);
1177   InFP128 = DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f128,
1178                                SDValue(InFP128, 0), Lo64, SubRegOdd);
1179   SDValue OutChains[2] = {SDValue(Lo64.getNode(), 1),
1180                           SDValue(Hi64.getNode(), 1)};
1181   SDValue OutChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
1182   SDValue Ops[2] = {SDValue(InFP128, 0), OutChain};
1183   return DAG.getMergeValues(Ops, DL);
1184 }
1185 
1186 SDValue VETargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1187   LoadSDNode *LdNode = cast<LoadSDNode>(Op.getNode());
1188 
1189   SDValue BasePtr = LdNode->getBasePtr();
1190   if (isa<FrameIndexSDNode>(BasePtr.getNode())) {
1191     // Do not expand store instruction with frame index here because of
1192     // dependency problems.  We expand it later in eliminateFrameIndex().
1193     return Op;
1194   }
1195 
1196   EVT MemVT = LdNode->getMemoryVT();
1197   if (MemVT == MVT::f128)
1198     return lowerLoadF128(Op, DAG);
1199 
1200   return Op;
1201 }
1202 
1203 // Lower a f128 store into two f64 stores.
1204 static SDValue lowerStoreF128(SDValue Op, SelectionDAG &DAG) {
1205   SDLoc DL(Op);
1206   StoreSDNode *StNode = dyn_cast<StoreSDNode>(Op.getNode());
1207   assert(StNode && StNode->getOffset().isUndef() && "Unexpected node type");
1208 
1209   SDValue SubRegEven = DAG.getTargetConstant(VE::sub_even, DL, MVT::i32);
1210   SDValue SubRegOdd = DAG.getTargetConstant(VE::sub_odd, DL, MVT::i32);
1211 
1212   SDNode *Hi64 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i64,
1213                                     StNode->getValue(), SubRegEven);
1214   SDNode *Lo64 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i64,
1215                                     StNode->getValue(), SubRegOdd);
1216 
1217   unsigned Alignment = StNode->getAlign().value();
1218   if (Alignment > 8)
1219     Alignment = 8;
1220 
1221   // VE stores Hi64 to 8(addr) and Lo64 to 0(addr)
1222   SDValue OutChains[2];
1223   OutChains[0] =
1224       DAG.getStore(StNode->getChain(), DL, SDValue(Lo64, 0),
1225                    StNode->getBasePtr(), MachinePointerInfo(), Alignment,
1226                    StNode->isVolatile() ? MachineMemOperand::MOVolatile
1227                                         : MachineMemOperand::MONone);
1228   EVT AddrVT = StNode->getBasePtr().getValueType();
1229   SDValue HiPtr = DAG.getNode(ISD::ADD, DL, AddrVT, StNode->getBasePtr(),
1230                               DAG.getConstant(8, DL, AddrVT));
1231   OutChains[1] =
1232       DAG.getStore(StNode->getChain(), DL, SDValue(Hi64, 0), HiPtr,
1233                    MachinePointerInfo(), Alignment,
1234                    StNode->isVolatile() ? MachineMemOperand::MOVolatile
1235                                         : MachineMemOperand::MONone);
1236   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
1237 }
1238 
1239 SDValue VETargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1240   StoreSDNode *StNode = cast<StoreSDNode>(Op.getNode());
1241   assert(StNode && StNode->getOffset().isUndef() && "Unexpected node type");
1242 
1243   SDValue BasePtr = StNode->getBasePtr();
1244   if (isa<FrameIndexSDNode>(BasePtr.getNode())) {
1245     // Do not expand store instruction with frame index here because of
1246     // dependency problems.  We expand it later in eliminateFrameIndex().
1247     return Op;
1248   }
1249 
1250   EVT MemVT = StNode->getMemoryVT();
1251   if (MemVT == MVT::f128)
1252     return lowerStoreF128(Op, DAG);
1253 
1254   // Otherwise, ask llvm to expand it.
1255   return SDValue();
1256 }
1257 
1258 SDValue VETargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1259   MachineFunction &MF = DAG.getMachineFunction();
1260   VEMachineFunctionInfo *FuncInfo = MF.getInfo<VEMachineFunctionInfo>();
1261   auto PtrVT = getPointerTy(DAG.getDataLayout());
1262 
1263   // Need frame address to find the address of VarArgsFrameIndex.
1264   MF.getFrameInfo().setFrameAddressIsTaken(true);
1265 
1266   // vastart just stores the address of the VarArgsFrameIndex slot into the
1267   // memory location argument.
1268   SDLoc DL(Op);
1269   SDValue Offset =
1270       DAG.getNode(ISD::ADD, DL, PtrVT, DAG.getRegister(VE::SX9, PtrVT),
1271                   DAG.getIntPtrConstant(FuncInfo->getVarArgsFrameOffset(), DL));
1272   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1273   return DAG.getStore(Op.getOperand(0), DL, Offset, Op.getOperand(1),
1274                       MachinePointerInfo(SV));
1275 }
1276 
1277 SDValue VETargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
1278   SDNode *Node = Op.getNode();
1279   EVT VT = Node->getValueType(0);
1280   SDValue InChain = Node->getOperand(0);
1281   SDValue VAListPtr = Node->getOperand(1);
1282   EVT PtrVT = VAListPtr.getValueType();
1283   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1284   SDLoc DL(Node);
1285   SDValue VAList =
1286       DAG.getLoad(PtrVT, DL, InChain, VAListPtr, MachinePointerInfo(SV));
1287   SDValue Chain = VAList.getValue(1);
1288   SDValue NextPtr;
1289 
1290   if (VT == MVT::f128) {
1291     // VE f128 values must be stored with 16 bytes alignment.  We doesn't
1292     // know the actual alignment of VAList, so we take alignment of it
1293     // dyanmically.
1294     int Align = 16;
1295     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
1296                          DAG.getConstant(Align - 1, DL, PtrVT));
1297     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
1298                          DAG.getConstant(-Align, DL, PtrVT));
1299     // Increment the pointer, VAList, by 16 to the next vaarg.
1300     NextPtr =
1301         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getIntPtrConstant(16, DL));
1302   } else if (VT == MVT::f32) {
1303     // float --> need special handling like below.
1304     //    0      4
1305     //    +------+------+
1306     //    | empty| float|
1307     //    +------+------+
1308     // Increment the pointer, VAList, by 8 to the next vaarg.
1309     NextPtr =
1310         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getIntPtrConstant(8, DL));
1311     // Then, adjust VAList.
1312     unsigned InternalOffset = 4;
1313     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
1314                          DAG.getConstant(InternalOffset, DL, PtrVT));
1315   } else {
1316     // Increment the pointer, VAList, by 8 to the next vaarg.
1317     NextPtr =
1318         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getIntPtrConstant(8, DL));
1319   }
1320 
1321   // Store the incremented VAList to the legalized pointer.
1322   InChain = DAG.getStore(Chain, DL, NextPtr, VAListPtr, MachinePointerInfo(SV));
1323 
1324   // Load the actual argument out of the pointer VAList.
1325   // We can't count on greater alignment than the word size.
1326   return DAG.getLoad(VT, DL, InChain, VAList, MachinePointerInfo(),
1327                      std::min(PtrVT.getSizeInBits(), VT.getSizeInBits()) / 8);
1328 }
1329 
1330 SDValue VETargetLowering::lowerDYNAMIC_STACKALLOC(SDValue Op,
1331                                                   SelectionDAG &DAG) const {
1332   // Generate following code.
1333   //   (void)__llvm_grow_stack(size);
1334   //   ret = GETSTACKTOP;        // pseudo instruction
1335   SDLoc DL(Op);
1336 
1337   // Get the inputs.
1338   SDNode *Node = Op.getNode();
1339   SDValue Chain = Op.getOperand(0);
1340   SDValue Size = Op.getOperand(1);
1341   MaybeAlign Alignment(Op.getConstantOperandVal(2));
1342   EVT VT = Node->getValueType(0);
1343 
1344   // Chain the dynamic stack allocation so that it doesn't modify the stack
1345   // pointer when other instructions are using the stack.
1346   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
1347 
1348   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
1349   Align StackAlign = TFI.getStackAlign();
1350   bool NeedsAlign = Alignment.valueOrOne() > StackAlign;
1351 
1352   // Prepare arguments
1353   TargetLowering::ArgListTy Args;
1354   TargetLowering::ArgListEntry Entry;
1355   Entry.Node = Size;
1356   Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
1357   Args.push_back(Entry);
1358   if (NeedsAlign) {
1359     Entry.Node = DAG.getConstant(~(Alignment->value() - 1ULL), DL, VT);
1360     Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
1361     Args.push_back(Entry);
1362   }
1363   Type *RetTy = Type::getVoidTy(*DAG.getContext());
1364 
1365   EVT PtrVT = Op.getValueType();
1366   SDValue Callee;
1367   if (NeedsAlign) {
1368     Callee = DAG.getTargetExternalSymbol("__ve_grow_stack_align", PtrVT, 0);
1369   } else {
1370     Callee = DAG.getTargetExternalSymbol("__ve_grow_stack", PtrVT, 0);
1371   }
1372 
1373   TargetLowering::CallLoweringInfo CLI(DAG);
1374   CLI.setDebugLoc(DL)
1375       .setChain(Chain)
1376       .setCallee(CallingConv::PreserveAll, RetTy, Callee, std::move(Args))
1377       .setDiscardResult(true);
1378   std::pair<SDValue, SDValue> pair = LowerCallTo(CLI);
1379   Chain = pair.second;
1380   SDValue Result = DAG.getNode(VEISD::GETSTACKTOP, DL, VT, Chain);
1381   if (NeedsAlign) {
1382     Result = DAG.getNode(ISD::ADD, DL, VT, Result,
1383                          DAG.getConstant((Alignment->value() - 1ULL), DL, VT));
1384     Result = DAG.getNode(ISD::AND, DL, VT, Result,
1385                          DAG.getConstant(~(Alignment->value() - 1ULL), DL, VT));
1386   }
1387   //  Chain = Result.getValue(1);
1388   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, DL, true),
1389                              DAG.getIntPtrConstant(0, DL, true), SDValue(), DL);
1390 
1391   SDValue Ops[2] = {Result, Chain};
1392   return DAG.getMergeValues(Ops, DL);
1393 }
1394 
1395 SDValue VETargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
1396   switch (Op.getOpcode()) {
1397   default:
1398     llvm_unreachable("Should not custom lower this!");
1399   case ISD::ATOMIC_FENCE:
1400     return lowerATOMIC_FENCE(Op, DAG);
1401   case ISD::BlockAddress:
1402     return lowerBlockAddress(Op, DAG);
1403   case ISD::ConstantPool:
1404     return lowerConstantPool(Op, DAG);
1405   case ISD::DYNAMIC_STACKALLOC:
1406     return lowerDYNAMIC_STACKALLOC(Op, DAG);
1407   case ISD::GlobalAddress:
1408     return lowerGlobalAddress(Op, DAG);
1409   case ISD::GlobalTLSAddress:
1410     return lowerGlobalTLSAddress(Op, DAG);
1411   case ISD::LOAD:
1412     return lowerLOAD(Op, DAG);
1413   case ISD::STORE:
1414     return lowerSTORE(Op, DAG);
1415   case ISD::VASTART:
1416     return lowerVASTART(Op, DAG);
1417   case ISD::VAARG:
1418     return lowerVAARG(Op, DAG);
1419   }
1420 }
1421 /// } Custom Lower
1422 
1423 static bool isI32Insn(const SDNode *User, const SDNode *N) {
1424   switch (User->getOpcode()) {
1425   default:
1426     return false;
1427   case ISD::ADD:
1428   case ISD::SUB:
1429   case ISD::MUL:
1430   case ISD::SDIV:
1431   case ISD::UDIV:
1432   case ISD::SETCC:
1433   case ISD::SMIN:
1434   case ISD::SMAX:
1435   case ISD::SHL:
1436   case ISD::SRA:
1437   case ISD::BSWAP:
1438   case ISD::SINT_TO_FP:
1439   case ISD::UINT_TO_FP:
1440   case ISD::BR_CC:
1441   case ISD::BITCAST:
1442   case ISD::ATOMIC_CMP_SWAP:
1443   case ISD::ATOMIC_SWAP:
1444     return true;
1445   case ISD::SRL:
1446     if (N->getOperand(0).getOpcode() != ISD::SRL)
1447       return true;
1448     // (srl (trunc (srl ...))) may be optimized by combining srl, so
1449     // doesn't optimize trunc now.
1450     return false;
1451   case ISD::SELECT_CC:
1452     if (User->getOperand(2).getNode() != N &&
1453         User->getOperand(3).getNode() != N)
1454       return true;
1455     LLVM_FALLTHROUGH;
1456   case ISD::AND:
1457   case ISD::OR:
1458   case ISD::XOR:
1459   case ISD::SELECT:
1460   case ISD::CopyToReg:
1461     // Check all use of selections, bit operations, and copies.  If all of them
1462     // are safe, optimize truncate to extract_subreg.
1463     for (SDNode::use_iterator UI = User->use_begin(), UE = User->use_end();
1464          UI != UE; ++UI) {
1465       switch ((*UI)->getOpcode()) {
1466       default:
1467         // If the use is an instruction which treats the source operand as i32,
1468         // it is safe to avoid truncate here.
1469         if (isI32Insn(*UI, N))
1470           continue;
1471         break;
1472       case ISD::ANY_EXTEND:
1473       case ISD::SIGN_EXTEND:
1474       case ISD::ZERO_EXTEND: {
1475         // Special optimizations to the combination of ext and trunc.
1476         // (ext ... (select ... (trunc ...))) is safe to avoid truncate here
1477         // since this truncate instruction clears higher 32 bits which is filled
1478         // by one of ext instructions later.
1479         assert(N->getValueType(0) == MVT::i32 &&
1480                "find truncate to not i32 integer");
1481         if (User->getOpcode() == ISD::SELECT_CC ||
1482             User->getOpcode() == ISD::SELECT)
1483           continue;
1484         break;
1485       }
1486       }
1487       return false;
1488     }
1489     return true;
1490   }
1491 }
1492 
1493 // Optimize TRUNCATE in DAG combining.  Optimizing it in CUSTOM lower is
1494 // sometime too early.  Optimizing it in DAG pattern matching in VEInstrInfo.td
1495 // is sometime too late.  So, doing it at here.
1496 SDValue VETargetLowering::combineTRUNCATE(SDNode *N,
1497                                           DAGCombinerInfo &DCI) const {
1498   assert(N->getOpcode() == ISD::TRUNCATE &&
1499          "Should be called with a TRUNCATE node");
1500 
1501   SelectionDAG &DAG = DCI.DAG;
1502   SDLoc DL(N);
1503   EVT VT = N->getValueType(0);
1504 
1505   // We prefer to do this when all types are legal.
1506   if (!DCI.isAfterLegalizeDAG())
1507     return SDValue();
1508 
1509   // Skip combine TRUNCATE atm if the operand of TRUNCATE might be a constant.
1510   if (N->getOperand(0)->getOpcode() == ISD::SELECT_CC &&
1511       isa<ConstantSDNode>(N->getOperand(0)->getOperand(0)) &&
1512       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
1513     return SDValue();
1514 
1515   // Check all use of this TRUNCATE.
1516   for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); UI != UE;
1517        ++UI) {
1518     SDNode *User = *UI;
1519 
1520     // Make sure that we're not going to replace TRUNCATE for non i32
1521     // instructions.
1522     //
1523     // FIXME: Although we could sometimes handle this, and it does occur in
1524     // practice that one of the condition inputs to the select is also one of
1525     // the outputs, we currently can't deal with this.
1526     if (isI32Insn(User, N))
1527       continue;
1528 
1529     return SDValue();
1530   }
1531 
1532   SDValue SubI32 = DAG.getTargetConstant(VE::sub_i32, DL, MVT::i32);
1533   return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, VT,
1534                                     N->getOperand(0), SubI32),
1535                  0);
1536 }
1537 
1538 SDValue VETargetLowering::PerformDAGCombine(SDNode *N,
1539                                             DAGCombinerInfo &DCI) const {
1540   switch (N->getOpcode()) {
1541   default:
1542     break;
1543   case ISD::TRUNCATE:
1544     return combineTRUNCATE(N, DCI);
1545   }
1546 
1547   return SDValue();
1548 }
1549