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 "VECustomDAG.h"
17 #include "VEInstrBuilder.h"
18 #include "VEMachineFunctionInfo.h"
19 #include "VERegisterInfo.h"
20 #include "VETargetMachine.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/CodeGen/CallingConvLower.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineJumpTableInfo.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/SelectionDAG.h"
30 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/KnownBits.h"
37 using namespace llvm;
38 
39 #define DEBUG_TYPE "ve-lower"
40 
41 //===----------------------------------------------------------------------===//
42 // Calling Convention Implementation
43 //===----------------------------------------------------------------------===//
44 
45 #include "VEGenCallingConv.inc"
46 
47 CCAssignFn *getReturnCC(CallingConv::ID CallConv) {
48   switch (CallConv) {
49   default:
50     return RetCC_VE_C;
51   case CallingConv::Fast:
52     return RetCC_VE_Fast;
53   }
54 }
55 
56 CCAssignFn *getParamCC(CallingConv::ID CallConv, bool IsVarArg) {
57   if (IsVarArg)
58     return CC_VE2;
59   switch (CallConv) {
60   default:
61     return CC_VE_C;
62   case CallingConv::Fast:
63     return CC_VE_Fast;
64   }
65 }
66 
67 bool VETargetLowering::CanLowerReturn(
68     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
69     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
70   CCAssignFn *RetCC = getReturnCC(CallConv);
71   SmallVector<CCValAssign, 16> RVLocs;
72   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
73   return CCInfo.CheckReturn(Outs, RetCC);
74 }
75 
76 static const MVT AllVectorVTs[] = {MVT::v256i32, MVT::v512i32, MVT::v256i64,
77                                    MVT::v256f32, MVT::v512f32, MVT::v256f64};
78 
79 static const MVT AllMaskVTs[] = {MVT::v256i1, MVT::v512i1};
80 
81 static const MVT AllPackedVTs[] = {MVT::v512i32, MVT::v512f32};
82 
83 void VETargetLowering::initRegisterClasses() {
84   // Set up the register classes.
85   addRegisterClass(MVT::i32, &VE::I32RegClass);
86   addRegisterClass(MVT::i64, &VE::I64RegClass);
87   addRegisterClass(MVT::f32, &VE::F32RegClass);
88   addRegisterClass(MVT::f64, &VE::I64RegClass);
89   addRegisterClass(MVT::f128, &VE::F128RegClass);
90 
91   if (Subtarget->enableVPU()) {
92     for (MVT VecVT : AllVectorVTs)
93       addRegisterClass(VecVT, &VE::V64RegClass);
94     addRegisterClass(MVT::v256i1, &VE::VMRegClass);
95     addRegisterClass(MVT::v512i1, &VE::VM512RegClass);
96   }
97 }
98 
99 void VETargetLowering::initSPUActions() {
100   const auto &TM = getTargetMachine();
101   /// Load & Store {
102 
103   // VE doesn't have i1 sign extending load.
104   for (MVT VT : MVT::integer_valuetypes()) {
105     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
106     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
107     setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
108     setTruncStoreAction(VT, MVT::i1, Expand);
109   }
110 
111   // VE doesn't have floating point extload/truncstore, so expand them.
112   for (MVT FPVT : MVT::fp_valuetypes()) {
113     for (MVT OtherFPVT : MVT::fp_valuetypes()) {
114       setLoadExtAction(ISD::EXTLOAD, FPVT, OtherFPVT, Expand);
115       setTruncStoreAction(FPVT, OtherFPVT, Expand);
116     }
117   }
118 
119   // VE doesn't have fp128 load/store, so expand them in custom lower.
120   setOperationAction(ISD::LOAD, MVT::f128, Custom);
121   setOperationAction(ISD::STORE, MVT::f128, Custom);
122 
123   /// } Load & Store
124 
125   // Custom legalize address nodes into LO/HI parts.
126   MVT PtrVT = MVT::getIntegerVT(TM.getPointerSizeInBits(0));
127   setOperationAction(ISD::BlockAddress, PtrVT, Custom);
128   setOperationAction(ISD::GlobalAddress, PtrVT, Custom);
129   setOperationAction(ISD::GlobalTLSAddress, PtrVT, Custom);
130   setOperationAction(ISD::ConstantPool, PtrVT, Custom);
131   setOperationAction(ISD::JumpTable, PtrVT, Custom);
132 
133   /// VAARG handling {
134   setOperationAction(ISD::VASTART, MVT::Other, Custom);
135   // VAARG needs to be lowered to access with 8 bytes alignment.
136   setOperationAction(ISD::VAARG, MVT::Other, Custom);
137   // Use the default implementation.
138   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
139   setOperationAction(ISD::VAEND, MVT::Other, Expand);
140   /// } VAARG handling
141 
142   /// Stack {
143   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
144   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
145 
146   // Use the default implementation.
147   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
148   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
149   /// } Stack
150 
151   /// Branch {
152 
153   // VE doesn't have BRCOND
154   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
155 
156   // BR_JT is not implemented yet.
157   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
158 
159   /// } Branch
160 
161   /// Int Ops {
162   for (MVT IntVT : {MVT::i32, MVT::i64}) {
163     // VE has no REM or DIVREM operations.
164     setOperationAction(ISD::UREM, IntVT, Expand);
165     setOperationAction(ISD::SREM, IntVT, Expand);
166     setOperationAction(ISD::SDIVREM, IntVT, Expand);
167     setOperationAction(ISD::UDIVREM, IntVT, Expand);
168 
169     // VE has no SHL_PARTS/SRA_PARTS/SRL_PARTS operations.
170     setOperationAction(ISD::SHL_PARTS, IntVT, Expand);
171     setOperationAction(ISD::SRA_PARTS, IntVT, Expand);
172     setOperationAction(ISD::SRL_PARTS, IntVT, Expand);
173 
174     // VE has no MULHU/S or U/SMUL_LOHI operations.
175     // TODO: Use MPD instruction to implement SMUL_LOHI for i32 type.
176     setOperationAction(ISD::MULHU, IntVT, Expand);
177     setOperationAction(ISD::MULHS, IntVT, Expand);
178     setOperationAction(ISD::UMUL_LOHI, IntVT, Expand);
179     setOperationAction(ISD::SMUL_LOHI, IntVT, Expand);
180 
181     // VE has no CTTZ, ROTL, ROTR operations.
182     setOperationAction(ISD::CTTZ, IntVT, Expand);
183     setOperationAction(ISD::ROTL, IntVT, Expand);
184     setOperationAction(ISD::ROTR, IntVT, Expand);
185 
186     // VE has 64 bits instruction which works as i64 BSWAP operation.  This
187     // instruction works fine as i32 BSWAP operation with an additional
188     // parameter.  Use isel patterns to lower BSWAP.
189     setOperationAction(ISD::BSWAP, IntVT, Legal);
190 
191     // VE has only 64 bits instructions which work as i64 BITREVERSE/CTLZ/CTPOP
192     // operations.  Use isel patterns for i64, promote for i32.
193     LegalizeAction Act = (IntVT == MVT::i32) ? Promote : Legal;
194     setOperationAction(ISD::BITREVERSE, IntVT, Act);
195     setOperationAction(ISD::CTLZ, IntVT, Act);
196     setOperationAction(ISD::CTLZ_ZERO_UNDEF, IntVT, Act);
197     setOperationAction(ISD::CTPOP, IntVT, Act);
198 
199     // VE has only 64 bits instructions which work as i64 AND/OR/XOR operations.
200     // Use isel patterns for i64, promote for i32.
201     setOperationAction(ISD::AND, IntVT, Act);
202     setOperationAction(ISD::OR, IntVT, Act);
203     setOperationAction(ISD::XOR, IntVT, Act);
204   }
205   /// } Int Ops
206 
207   /// Conversion {
208   // VE doesn't have instructions for fp<->uint, so expand them by llvm
209   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Promote); // use i64
210   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Promote); // use i64
211   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
212   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
213 
214   // fp16 not supported
215   for (MVT FPVT : MVT::fp_valuetypes()) {
216     setOperationAction(ISD::FP16_TO_FP, FPVT, Expand);
217     setOperationAction(ISD::FP_TO_FP16, FPVT, Expand);
218   }
219   /// } Conversion
220 
221   /// Floating-point Ops {
222   /// Note: Floating-point operations are fneg, fadd, fsub, fmul, fdiv, frem,
223   ///       and fcmp.
224 
225   // VE doesn't have following floating point operations.
226   for (MVT VT : MVT::fp_valuetypes()) {
227     setOperationAction(ISD::FNEG, VT, Expand);
228     setOperationAction(ISD::FREM, VT, Expand);
229   }
230 
231   // VE doesn't have fdiv of f128.
232   setOperationAction(ISD::FDIV, MVT::f128, Expand);
233 
234   for (MVT FPVT : {MVT::f32, MVT::f64}) {
235     // f32 and f64 uses ConstantFP.  f128 uses ConstantPool.
236     setOperationAction(ISD::ConstantFP, FPVT, Legal);
237   }
238   /// } Floating-point Ops
239 
240   /// Floating-point math functions {
241 
242   // VE doesn't have following floating point math functions.
243   for (MVT VT : MVT::fp_valuetypes()) {
244     setOperationAction(ISD::FABS, VT, Expand);
245     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
246     setOperationAction(ISD::FCOS, VT, Expand);
247     setOperationAction(ISD::FSIN, VT, Expand);
248     setOperationAction(ISD::FSQRT, VT, Expand);
249   }
250 
251   /// } Floating-point math functions
252 
253   /// Atomic instructions {
254 
255   setMaxAtomicSizeInBitsSupported(64);
256   setMinCmpXchgSizeInBits(32);
257   setSupportsUnalignedAtomics(false);
258 
259   // Use custom inserter for ATOMIC_FENCE.
260   setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
261 
262   // Other atomic instructions.
263   for (MVT VT : MVT::integer_valuetypes()) {
264     // Support i8/i16 atomic swap.
265     setOperationAction(ISD::ATOMIC_SWAP, VT, Custom);
266 
267     // FIXME: Support "atmam" instructions.
268     setOperationAction(ISD::ATOMIC_LOAD_ADD, VT, Expand);
269     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Expand);
270     setOperationAction(ISD::ATOMIC_LOAD_AND, VT, Expand);
271     setOperationAction(ISD::ATOMIC_LOAD_OR, VT, Expand);
272 
273     // VE doesn't have follwing instructions.
274     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Expand);
275     setOperationAction(ISD::ATOMIC_LOAD_CLR, VT, Expand);
276     setOperationAction(ISD::ATOMIC_LOAD_XOR, VT, Expand);
277     setOperationAction(ISD::ATOMIC_LOAD_NAND, VT, Expand);
278     setOperationAction(ISD::ATOMIC_LOAD_MIN, VT, Expand);
279     setOperationAction(ISD::ATOMIC_LOAD_MAX, VT, Expand);
280     setOperationAction(ISD::ATOMIC_LOAD_UMIN, VT, Expand);
281     setOperationAction(ISD::ATOMIC_LOAD_UMAX, VT, Expand);
282   }
283 
284   /// } Atomic instructions
285 
286   /// SJLJ instructions {
287   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
288   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
289   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
290   if (TM.Options.ExceptionModel == ExceptionHandling::SjLj)
291     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
292   /// } SJLJ instructions
293 
294   // Intrinsic instructions
295   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
296 }
297 
298 void VETargetLowering::initVPUActions() {
299   for (MVT LegalMaskVT : AllMaskVTs)
300     setOperationAction(ISD::BUILD_VECTOR, LegalMaskVT, Custom);
301 
302   for (MVT LegalVecVT : AllVectorVTs) {
303     setOperationAction(ISD::BUILD_VECTOR, LegalVecVT, Custom);
304     setOperationAction(ISD::INSERT_VECTOR_ELT, LegalVecVT, Legal);
305     setOperationAction(ISD::EXTRACT_VECTOR_ELT, LegalVecVT, Legal);
306     // Translate all vector instructions with legal element types to VVP_*
307     // nodes.
308     // TODO We will custom-widen into VVP_* nodes in the future. While we are
309     // buildling the infrastructure for this, we only do this for legal vector
310     // VTs.
311 #define HANDLE_VP_TO_VVP(VP_OPC, VVP_NAME)                                     \
312   setOperationAction(ISD::VP_OPC, LegalVecVT, Custom);
313 #define ADD_VVP_OP(VVP_NAME, ISD_NAME)                                         \
314   setOperationAction(ISD::ISD_NAME, LegalVecVT, Custom);
315 #include "VVPNodes.def"
316   }
317 
318   for (MVT LegalPackedVT : AllPackedVTs) {
319     setOperationAction(ISD::INSERT_VECTOR_ELT, LegalPackedVT, Custom);
320     setOperationAction(ISD::EXTRACT_VECTOR_ELT, LegalPackedVT, Custom);
321   }
322 }
323 
324 SDValue
325 VETargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
326                               bool IsVarArg,
327                               const SmallVectorImpl<ISD::OutputArg> &Outs,
328                               const SmallVectorImpl<SDValue> &OutVals,
329                               const SDLoc &DL, SelectionDAG &DAG) const {
330   // CCValAssign - represent the assignment of the return value to locations.
331   SmallVector<CCValAssign, 16> RVLocs;
332 
333   // CCState - Info about the registers and stack slot.
334   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
335                  *DAG.getContext());
336 
337   // Analyze return values.
338   CCInfo.AnalyzeReturn(Outs, getReturnCC(CallConv));
339 
340   SDValue Flag;
341   SmallVector<SDValue, 4> RetOps(1, Chain);
342 
343   // Copy the result values into the output registers.
344   for (unsigned i = 0; i != RVLocs.size(); ++i) {
345     CCValAssign &VA = RVLocs[i];
346     assert(VA.isRegLoc() && "Can only return in registers!");
347     assert(!VA.needsCustom() && "Unexpected custom lowering");
348     SDValue OutVal = OutVals[i];
349 
350     // Integer return values must be sign or zero extended by the callee.
351     switch (VA.getLocInfo()) {
352     case CCValAssign::Full:
353       break;
354     case CCValAssign::SExt:
355       OutVal = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), OutVal);
356       break;
357     case CCValAssign::ZExt:
358       OutVal = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), OutVal);
359       break;
360     case CCValAssign::AExt:
361       OutVal = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), OutVal);
362       break;
363     case CCValAssign::BCvt: {
364       // Convert a float return value to i64 with padding.
365       //     63     31   0
366       //    +------+------+
367       //    | float|   0  |
368       //    +------+------+
369       assert(VA.getLocVT() == MVT::i64);
370       assert(VA.getValVT() == MVT::f32);
371       SDValue Undef = SDValue(
372           DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::i64), 0);
373       SDValue Sub_f32 = DAG.getTargetConstant(VE::sub_f32, DL, MVT::i32);
374       OutVal = SDValue(DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
375                                           MVT::i64, Undef, OutVal, Sub_f32),
376                        0);
377       break;
378     }
379     default:
380       llvm_unreachable("Unknown loc info!");
381     }
382 
383     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), OutVal, Flag);
384 
385     // Guarantee that all emitted copies are stuck together with flags.
386     Flag = Chain.getValue(1);
387     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
388   }
389 
390   RetOps[0] = Chain; // Update chain.
391 
392   // Add the flag if we have it.
393   if (Flag.getNode())
394     RetOps.push_back(Flag);
395 
396   return DAG.getNode(VEISD::RET_FLAG, DL, MVT::Other, RetOps);
397 }
398 
399 SDValue VETargetLowering::LowerFormalArguments(
400     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
401     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
402     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
403   MachineFunction &MF = DAG.getMachineFunction();
404 
405   // Get the base offset of the incoming arguments stack space.
406   unsigned ArgsBaseOffset = Subtarget->getRsaSize();
407   // Get the size of the preserved arguments area
408   unsigned ArgsPreserved = 64;
409 
410   // Analyze arguments according to CC_VE.
411   SmallVector<CCValAssign, 16> ArgLocs;
412   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
413                  *DAG.getContext());
414   // Allocate the preserved area first.
415   CCInfo.AllocateStack(ArgsPreserved, Align(8));
416   // We already allocated the preserved area, so the stack offset computed
417   // by CC_VE would be correct now.
418   CCInfo.AnalyzeFormalArguments(Ins, getParamCC(CallConv, false));
419 
420   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
421     CCValAssign &VA = ArgLocs[i];
422     assert(!VA.needsCustom() && "Unexpected custom lowering");
423     if (VA.isRegLoc()) {
424       // This argument is passed in a register.
425       // All integer register arguments are promoted by the caller to i64.
426 
427       // Create a virtual register for the promoted live-in value.
428       Register VReg =
429           MF.addLiveIn(VA.getLocReg(), getRegClassFor(VA.getLocVT()));
430       SDValue Arg = DAG.getCopyFromReg(Chain, DL, VReg, VA.getLocVT());
431 
432       // The caller promoted the argument, so insert an Assert?ext SDNode so we
433       // won't promote the value again in this function.
434       switch (VA.getLocInfo()) {
435       case CCValAssign::SExt:
436         Arg = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Arg,
437                           DAG.getValueType(VA.getValVT()));
438         break;
439       case CCValAssign::ZExt:
440         Arg = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Arg,
441                           DAG.getValueType(VA.getValVT()));
442         break;
443       case CCValAssign::BCvt: {
444         // Extract a float argument from i64 with padding.
445         //     63     31   0
446         //    +------+------+
447         //    | float|   0  |
448         //    +------+------+
449         assert(VA.getLocVT() == MVT::i64);
450         assert(VA.getValVT() == MVT::f32);
451         SDValue Sub_f32 = DAG.getTargetConstant(VE::sub_f32, DL, MVT::i32);
452         Arg = SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
453                                          MVT::f32, Arg, Sub_f32),
454                       0);
455         break;
456       }
457       default:
458         break;
459       }
460 
461       // Truncate the register down to the argument type.
462       if (VA.isExtInLoc())
463         Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
464 
465       InVals.push_back(Arg);
466       continue;
467     }
468 
469     // The registers are exhausted. This argument was passed on the stack.
470     assert(VA.isMemLoc());
471     // The CC_VE_Full/Half functions compute stack offsets relative to the
472     // beginning of the arguments area at %fp + the size of reserved area.
473     unsigned Offset = VA.getLocMemOffset() + ArgsBaseOffset;
474     unsigned ValSize = VA.getValVT().getSizeInBits() / 8;
475 
476     // Adjust offset for a float argument by adding 4 since the argument is
477     // stored in 8 bytes buffer with offset like below.  LLVM generates
478     // 4 bytes load instruction, so need to adjust offset here.  This
479     // adjustment is required in only LowerFormalArguments.  In LowerCall,
480     // a float argument is converted to i64 first, and stored as 8 bytes
481     // data, which is required by ABI, so no need for adjustment.
482     //    0      4
483     //    +------+------+
484     //    | empty| float|
485     //    +------+------+
486     if (VA.getValVT() == MVT::f32)
487       Offset += 4;
488 
489     int FI = MF.getFrameInfo().CreateFixedObject(ValSize, Offset, true);
490     InVals.push_back(
491         DAG.getLoad(VA.getValVT(), DL, Chain,
492                     DAG.getFrameIndex(FI, getPointerTy(MF.getDataLayout())),
493                     MachinePointerInfo::getFixedStack(MF, FI)));
494   }
495 
496   if (!IsVarArg)
497     return Chain;
498 
499   // This function takes variable arguments, some of which may have been passed
500   // in registers %s0-%s8.
501   //
502   // The va_start intrinsic needs to know the offset to the first variable
503   // argument.
504   // TODO: need to calculate offset correctly once we support f128.
505   unsigned ArgOffset = ArgLocs.size() * 8;
506   VEMachineFunctionInfo *FuncInfo = MF.getInfo<VEMachineFunctionInfo>();
507   // Skip the reserved area at the top of stack.
508   FuncInfo->setVarArgsFrameOffset(ArgOffset + ArgsBaseOffset);
509 
510   return Chain;
511 }
512 
513 // FIXME? Maybe this could be a TableGen attribute on some registers and
514 // this table could be generated automatically from RegInfo.
515 Register VETargetLowering::getRegisterByName(const char *RegName, LLT VT,
516                                              const MachineFunction &MF) const {
517   Register Reg = StringSwitch<Register>(RegName)
518                      .Case("sp", VE::SX11)    // Stack pointer
519                      .Case("fp", VE::SX9)     // Frame pointer
520                      .Case("sl", VE::SX8)     // Stack limit
521                      .Case("lr", VE::SX10)    // Link register
522                      .Case("tp", VE::SX14)    // Thread pointer
523                      .Case("outer", VE::SX12) // Outer regiser
524                      .Case("info", VE::SX17)  // Info area register
525                      .Case("got", VE::SX15)   // Global offset table register
526                      .Case("plt", VE::SX16) // Procedure linkage table register
527                      .Default(0);
528 
529   if (Reg)
530     return Reg;
531 
532   report_fatal_error("Invalid register name global variable");
533 }
534 
535 //===----------------------------------------------------------------------===//
536 // TargetLowering Implementation
537 //===----------------------------------------------------------------------===//
538 
539 SDValue VETargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
540                                     SmallVectorImpl<SDValue> &InVals) const {
541   SelectionDAG &DAG = CLI.DAG;
542   SDLoc DL = CLI.DL;
543   SDValue Chain = CLI.Chain;
544   auto PtrVT = getPointerTy(DAG.getDataLayout());
545 
546   // VE target does not yet support tail call optimization.
547   CLI.IsTailCall = false;
548 
549   // Get the base offset of the outgoing arguments stack space.
550   unsigned ArgsBaseOffset = Subtarget->getRsaSize();
551   // Get the size of the preserved arguments area
552   unsigned ArgsPreserved = 8 * 8u;
553 
554   // Analyze operands of the call, assigning locations to each operand.
555   SmallVector<CCValAssign, 16> ArgLocs;
556   CCState CCInfo(CLI.CallConv, CLI.IsVarArg, DAG.getMachineFunction(), ArgLocs,
557                  *DAG.getContext());
558   // Allocate the preserved area first.
559   CCInfo.AllocateStack(ArgsPreserved, Align(8));
560   // We already allocated the preserved area, so the stack offset computed
561   // by CC_VE would be correct now.
562   CCInfo.AnalyzeCallOperands(CLI.Outs, getParamCC(CLI.CallConv, false));
563 
564   // VE requires to use both register and stack for varargs or no-prototyped
565   // functions.
566   bool UseBoth = CLI.IsVarArg;
567 
568   // Analyze operands again if it is required to store BOTH.
569   SmallVector<CCValAssign, 16> ArgLocs2;
570   CCState CCInfo2(CLI.CallConv, CLI.IsVarArg, DAG.getMachineFunction(),
571                   ArgLocs2, *DAG.getContext());
572   if (UseBoth)
573     CCInfo2.AnalyzeCallOperands(CLI.Outs, getParamCC(CLI.CallConv, true));
574 
575   // Get the size of the outgoing arguments stack space requirement.
576   unsigned ArgsSize = CCInfo.getNextStackOffset();
577 
578   // Keep stack frames 16-byte aligned.
579   ArgsSize = alignTo(ArgsSize, 16);
580 
581   // Adjust the stack pointer to make room for the arguments.
582   // FIXME: Use hasReservedCallFrame to avoid %sp adjustments around all calls
583   // with more than 6 arguments.
584   Chain = DAG.getCALLSEQ_START(Chain, ArgsSize, 0, DL);
585 
586   // Collect the set of registers to pass to the function and their values.
587   // This will be emitted as a sequence of CopyToReg nodes glued to the call
588   // instruction.
589   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
590 
591   // Collect chains from all the memory opeations that copy arguments to the
592   // stack. They must follow the stack pointer adjustment above and precede the
593   // call instruction itself.
594   SmallVector<SDValue, 8> MemOpChains;
595 
596   // VE needs to get address of callee function in a register
597   // So, prepare to copy it to SX12 here.
598 
599   // If the callee is a GlobalAddress node (quite common, every direct call is)
600   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
601   // Likewise ExternalSymbol -> TargetExternalSymbol.
602   SDValue Callee = CLI.Callee;
603 
604   bool IsPICCall = isPositionIndependent();
605 
606   // PC-relative references to external symbols should go through $stub.
607   // If so, we need to prepare GlobalBaseReg first.
608   const TargetMachine &TM = DAG.getTarget();
609   const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
610   const GlobalValue *GV = nullptr;
611   auto *CalleeG = dyn_cast<GlobalAddressSDNode>(Callee);
612   if (CalleeG)
613     GV = CalleeG->getGlobal();
614   bool Local = TM.shouldAssumeDSOLocal(*Mod, GV);
615   bool UsePlt = !Local;
616   MachineFunction &MF = DAG.getMachineFunction();
617 
618   // Turn GlobalAddress/ExternalSymbol node into a value node
619   // containing the address of them here.
620   if (CalleeG) {
621     if (IsPICCall) {
622       if (UsePlt)
623         Subtarget->getInstrInfo()->getGlobalBaseReg(&MF);
624       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
625       Callee = DAG.getNode(VEISD::GETFUNPLT, DL, PtrVT, Callee);
626     } else {
627       Callee =
628           makeHiLoPair(Callee, VEMCExpr::VK_VE_HI32, VEMCExpr::VK_VE_LO32, DAG);
629     }
630   } else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
631     if (IsPICCall) {
632       if (UsePlt)
633         Subtarget->getInstrInfo()->getGlobalBaseReg(&MF);
634       Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT, 0);
635       Callee = DAG.getNode(VEISD::GETFUNPLT, DL, PtrVT, Callee);
636     } else {
637       Callee =
638           makeHiLoPair(Callee, VEMCExpr::VK_VE_HI32, VEMCExpr::VK_VE_LO32, DAG);
639     }
640   }
641 
642   RegsToPass.push_back(std::make_pair(VE::SX12, Callee));
643 
644   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
645     CCValAssign &VA = ArgLocs[i];
646     SDValue Arg = CLI.OutVals[i];
647 
648     // Promote the value if needed.
649     switch (VA.getLocInfo()) {
650     default:
651       llvm_unreachable("Unknown location info!");
652     case CCValAssign::Full:
653       break;
654     case CCValAssign::SExt:
655       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
656       break;
657     case CCValAssign::ZExt:
658       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
659       break;
660     case CCValAssign::AExt:
661       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
662       break;
663     case CCValAssign::BCvt: {
664       // Convert a float argument to i64 with padding.
665       //     63     31   0
666       //    +------+------+
667       //    | float|   0  |
668       //    +------+------+
669       assert(VA.getLocVT() == MVT::i64);
670       assert(VA.getValVT() == MVT::f32);
671       SDValue Undef = SDValue(
672           DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::i64), 0);
673       SDValue Sub_f32 = DAG.getTargetConstant(VE::sub_f32, DL, MVT::i32);
674       Arg = SDValue(DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
675                                        MVT::i64, Undef, Arg, Sub_f32),
676                     0);
677       break;
678     }
679     }
680 
681     if (VA.isRegLoc()) {
682       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
683       if (!UseBoth)
684         continue;
685       VA = ArgLocs2[i];
686     }
687 
688     assert(VA.isMemLoc());
689 
690     // Create a store off the stack pointer for this argument.
691     SDValue StackPtr = DAG.getRegister(VE::SX11, PtrVT);
692     // The argument area starts at %fp/%sp + the size of reserved area.
693     SDValue PtrOff =
694         DAG.getIntPtrConstant(VA.getLocMemOffset() + ArgsBaseOffset, DL);
695     PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
696     MemOpChains.push_back(
697         DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo()));
698   }
699 
700   // Emit all stores, make sure they occur before the call.
701   if (!MemOpChains.empty())
702     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
703 
704   // Build a sequence of CopyToReg nodes glued together with token chain and
705   // glue operands which copy the outgoing args into registers. The InGlue is
706   // necessary since all emitted instructions must be stuck together in order
707   // to pass the live physical registers.
708   SDValue InGlue;
709   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
710     Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[i].first,
711                              RegsToPass[i].second, InGlue);
712     InGlue = Chain.getValue(1);
713   }
714 
715   // Build the operands for the call instruction itself.
716   SmallVector<SDValue, 8> Ops;
717   Ops.push_back(Chain);
718   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
719     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
720                                   RegsToPass[i].second.getValueType()));
721 
722   // Add a register mask operand representing the call-preserved registers.
723   const VERegisterInfo *TRI = Subtarget->getRegisterInfo();
724   const uint32_t *Mask =
725       TRI->getCallPreservedMask(DAG.getMachineFunction(), CLI.CallConv);
726   assert(Mask && "Missing call preserved mask for calling convention");
727   Ops.push_back(DAG.getRegisterMask(Mask));
728 
729   // Make sure the CopyToReg nodes are glued to the call instruction which
730   // consumes the registers.
731   if (InGlue.getNode())
732     Ops.push_back(InGlue);
733 
734   // Now the call itself.
735   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
736   Chain = DAG.getNode(VEISD::CALL, DL, NodeTys, Ops);
737   InGlue = Chain.getValue(1);
738 
739   // Revert the stack pointer immediately after the call.
740   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(ArgsSize, DL, true),
741                              DAG.getIntPtrConstant(0, DL, true), InGlue, DL);
742   InGlue = Chain.getValue(1);
743 
744   // Now extract the return values. This is more or less the same as
745   // LowerFormalArguments.
746 
747   // Assign locations to each value returned by this call.
748   SmallVector<CCValAssign, 16> RVLocs;
749   CCState RVInfo(CLI.CallConv, CLI.IsVarArg, DAG.getMachineFunction(), RVLocs,
750                  *DAG.getContext());
751 
752   // Set inreg flag manually for codegen generated library calls that
753   // return float.
754   if (CLI.Ins.size() == 1 && CLI.Ins[0].VT == MVT::f32 && !CLI.CB)
755     CLI.Ins[0].Flags.setInReg();
756 
757   RVInfo.AnalyzeCallResult(CLI.Ins, getReturnCC(CLI.CallConv));
758 
759   // Copy all of the result registers out of their specified physreg.
760   for (unsigned i = 0; i != RVLocs.size(); ++i) {
761     CCValAssign &VA = RVLocs[i];
762     assert(!VA.needsCustom() && "Unexpected custom lowering");
763     Register Reg = VA.getLocReg();
764 
765     // When returning 'inreg {i32, i32 }', two consecutive i32 arguments can
766     // reside in the same register in the high and low bits. Reuse the
767     // CopyFromReg previous node to avoid duplicate copies.
768     SDValue RV;
769     if (RegisterSDNode *SrcReg = dyn_cast<RegisterSDNode>(Chain.getOperand(1)))
770       if (SrcReg->getReg() == Reg && Chain->getOpcode() == ISD::CopyFromReg)
771         RV = Chain.getValue(0);
772 
773     // But usually we'll create a new CopyFromReg for a different register.
774     if (!RV.getNode()) {
775       RV = DAG.getCopyFromReg(Chain, DL, Reg, RVLocs[i].getLocVT(), InGlue);
776       Chain = RV.getValue(1);
777       InGlue = Chain.getValue(2);
778     }
779 
780     // The callee promoted the return value, so insert an Assert?ext SDNode so
781     // we won't promote the value again in this function.
782     switch (VA.getLocInfo()) {
783     case CCValAssign::SExt:
784       RV = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), RV,
785                        DAG.getValueType(VA.getValVT()));
786       break;
787     case CCValAssign::ZExt:
788       RV = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), RV,
789                        DAG.getValueType(VA.getValVT()));
790       break;
791     case CCValAssign::BCvt: {
792       // Extract a float return value from i64 with padding.
793       //     63     31   0
794       //    +------+------+
795       //    | float|   0  |
796       //    +------+------+
797       assert(VA.getLocVT() == MVT::i64);
798       assert(VA.getValVT() == MVT::f32);
799       SDValue Sub_f32 = DAG.getTargetConstant(VE::sub_f32, DL, MVT::i32);
800       RV = SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
801                                       MVT::f32, RV, Sub_f32),
802                    0);
803       break;
804     }
805     default:
806       break;
807     }
808 
809     // Truncate the register down to the return value type.
810     if (VA.isExtInLoc())
811       RV = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), RV);
812 
813     InVals.push_back(RV);
814   }
815 
816   return Chain;
817 }
818 
819 bool VETargetLowering::isOffsetFoldingLegal(
820     const GlobalAddressSDNode *GA) const {
821   // VE uses 64 bit addressing, so we need multiple instructions to generate
822   // an address.  Folding address with offset increases the number of
823   // instructions, so that we disable it here.  Offsets will be folded in
824   // the DAG combine later if it worth to do so.
825   return false;
826 }
827 
828 /// isFPImmLegal - Returns true if the target can instruction select the
829 /// specified FP immediate natively. If false, the legalizer will
830 /// materialize the FP immediate as a load from a constant pool.
831 bool VETargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
832                                     bool ForCodeSize) const {
833   return VT == MVT::f32 || VT == MVT::f64;
834 }
835 
836 /// Determine if the target supports unaligned memory accesses.
837 ///
838 /// This function returns true if the target allows unaligned memory accesses
839 /// of the specified type in the given address space. If true, it also returns
840 /// whether the unaligned memory access is "fast" in the last argument by
841 /// reference. This is used, for example, in situations where an array
842 /// copy/move/set is converted to a sequence of store operations. Its use
843 /// helps to ensure that such replacements don't generate code that causes an
844 /// alignment error (trap) on the target machine.
845 bool VETargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
846                                                       unsigned AddrSpace,
847                                                       Align A,
848                                                       MachineMemOperand::Flags,
849                                                       bool *Fast) const {
850   if (Fast) {
851     // It's fast anytime on VE
852     *Fast = true;
853   }
854   return true;
855 }
856 
857 VETargetLowering::VETargetLowering(const TargetMachine &TM,
858                                    const VESubtarget &STI)
859     : TargetLowering(TM), Subtarget(&STI) {
860   // Instructions which use registers as conditionals examine all the
861   // bits (as does the pseudo SELECT_CC expansion). I don't think it
862   // matters much whether it's ZeroOrOneBooleanContent, or
863   // ZeroOrNegativeOneBooleanContent, so, arbitrarily choose the
864   // former.
865   setBooleanContents(ZeroOrOneBooleanContent);
866   setBooleanVectorContents(ZeroOrOneBooleanContent);
867 
868   initRegisterClasses();
869   initSPUActions();
870   initVPUActions();
871 
872   setStackPointerRegisterToSaveRestore(VE::SX11);
873 
874   // We have target-specific dag combine patterns for the following nodes:
875   setTargetDAGCombine(ISD::TRUNCATE);
876 
877   // Set function alignment to 16 bytes
878   setMinFunctionAlignment(Align(16));
879 
880   // VE stores all argument by 8 bytes alignment
881   setMinStackArgumentAlignment(Align(8));
882 
883   computeRegisterProperties(Subtarget->getRegisterInfo());
884 }
885 
886 const char *VETargetLowering::getTargetNodeName(unsigned Opcode) const {
887 #define TARGET_NODE_CASE(NAME)                                                 \
888   case VEISD::NAME:                                                            \
889     return "VEISD::" #NAME;
890   switch ((VEISD::NodeType)Opcode) {
891   case VEISD::FIRST_NUMBER:
892     break;
893     TARGET_NODE_CASE(CALL)
894     TARGET_NODE_CASE(EH_SJLJ_LONGJMP)
895     TARGET_NODE_CASE(EH_SJLJ_SETJMP)
896     TARGET_NODE_CASE(EH_SJLJ_SETUP_DISPATCH)
897     TARGET_NODE_CASE(GETFUNPLT)
898     TARGET_NODE_CASE(GETSTACKTOP)
899     TARGET_NODE_CASE(GETTLSADDR)
900     TARGET_NODE_CASE(GLOBAL_BASE_REG)
901     TARGET_NODE_CASE(Hi)
902     TARGET_NODE_CASE(Lo)
903     TARGET_NODE_CASE(MEMBARRIER)
904     TARGET_NODE_CASE(RET_FLAG)
905     TARGET_NODE_CASE(TS1AM)
906     TARGET_NODE_CASE(VEC_BROADCAST)
907     TARGET_NODE_CASE(REPL_I32)
908     TARGET_NODE_CASE(REPL_F32)
909 
910     TARGET_NODE_CASE(LEGALAVL)
911 
912     // Register the VVP_* SDNodes.
913 #define ADD_VVP_OP(VVP_NAME, ...) TARGET_NODE_CASE(VVP_NAME)
914 #include "VVPNodes.def"
915   }
916 #undef TARGET_NODE_CASE
917   return nullptr;
918 }
919 
920 EVT VETargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
921                                          EVT VT) const {
922   return MVT::i32;
923 }
924 
925 // Convert to a target node and set target flags.
926 SDValue VETargetLowering::withTargetFlags(SDValue Op, unsigned TF,
927                                           SelectionDAG &DAG) const {
928   if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op))
929     return DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(GA),
930                                       GA->getValueType(0), GA->getOffset(), TF);
931 
932   if (const BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(Op))
933     return DAG.getTargetBlockAddress(BA->getBlockAddress(), Op.getValueType(),
934                                      0, TF);
935 
936   if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op))
937     return DAG.getTargetConstantPool(CP->getConstVal(), CP->getValueType(0),
938                                      CP->getAlign(), CP->getOffset(), TF);
939 
940   if (const ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op))
941     return DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0),
942                                        TF);
943 
944   if (const JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op))
945     return DAG.getTargetJumpTable(JT->getIndex(), JT->getValueType(0), TF);
946 
947   llvm_unreachable("Unhandled address SDNode");
948 }
949 
950 // Split Op into high and low parts according to HiTF and LoTF.
951 // Return an ADD node combining the parts.
952 SDValue VETargetLowering::makeHiLoPair(SDValue Op, unsigned HiTF, unsigned LoTF,
953                                        SelectionDAG &DAG) const {
954   SDLoc DL(Op);
955   EVT VT = Op.getValueType();
956   SDValue Hi = DAG.getNode(VEISD::Hi, DL, VT, withTargetFlags(Op, HiTF, DAG));
957   SDValue Lo = DAG.getNode(VEISD::Lo, DL, VT, withTargetFlags(Op, LoTF, DAG));
958   return DAG.getNode(ISD::ADD, DL, VT, Hi, Lo);
959 }
960 
961 // Build SDNodes for producing an address from a GlobalAddress, ConstantPool,
962 // or ExternalSymbol SDNode.
963 SDValue VETargetLowering::makeAddress(SDValue Op, SelectionDAG &DAG) const {
964   SDLoc DL(Op);
965   EVT PtrVT = Op.getValueType();
966 
967   // Handle PIC mode first. VE needs a got load for every variable!
968   if (isPositionIndependent()) {
969     auto GlobalN = dyn_cast<GlobalAddressSDNode>(Op);
970 
971     if (isa<ConstantPoolSDNode>(Op) || isa<JumpTableSDNode>(Op) ||
972         (GlobalN && GlobalN->getGlobal()->hasLocalLinkage())) {
973       // Create following instructions for local linkage PIC code.
974       //     lea %reg, label@gotoff_lo
975       //     and %reg, %reg, (32)0
976       //     lea.sl %reg, label@gotoff_hi(%reg, %got)
977       SDValue HiLo = makeHiLoPair(Op, VEMCExpr::VK_VE_GOTOFF_HI32,
978                                   VEMCExpr::VK_VE_GOTOFF_LO32, DAG);
979       SDValue GlobalBase = DAG.getNode(VEISD::GLOBAL_BASE_REG, DL, PtrVT);
980       return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalBase, HiLo);
981     }
982     // Create following instructions for not local linkage PIC code.
983     //     lea %reg, label@got_lo
984     //     and %reg, %reg, (32)0
985     //     lea.sl %reg, label@got_hi(%reg)
986     //     ld %reg, (%reg, %got)
987     SDValue HiLo = makeHiLoPair(Op, VEMCExpr::VK_VE_GOT_HI32,
988                                 VEMCExpr::VK_VE_GOT_LO32, DAG);
989     SDValue GlobalBase = DAG.getNode(VEISD::GLOBAL_BASE_REG, DL, PtrVT);
990     SDValue AbsAddr = DAG.getNode(ISD::ADD, DL, PtrVT, GlobalBase, HiLo);
991     return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), AbsAddr,
992                        MachinePointerInfo::getGOT(DAG.getMachineFunction()));
993   }
994 
995   // This is one of the absolute code models.
996   switch (getTargetMachine().getCodeModel()) {
997   default:
998     llvm_unreachable("Unsupported absolute code model");
999   case CodeModel::Small:
1000   case CodeModel::Medium:
1001   case CodeModel::Large:
1002     // abs64.
1003     return makeHiLoPair(Op, VEMCExpr::VK_VE_HI32, VEMCExpr::VK_VE_LO32, DAG);
1004   }
1005 }
1006 
1007 /// Custom Lower {
1008 
1009 // The mappings for emitLeading/TrailingFence for VE is designed by following
1010 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
1011 Instruction *VETargetLowering::emitLeadingFence(IRBuilderBase &Builder,
1012                                                 Instruction *Inst,
1013                                                 AtomicOrdering Ord) const {
1014   switch (Ord) {
1015   case AtomicOrdering::NotAtomic:
1016   case AtomicOrdering::Unordered:
1017     llvm_unreachable("Invalid fence: unordered/non-atomic");
1018   case AtomicOrdering::Monotonic:
1019   case AtomicOrdering::Acquire:
1020     return nullptr; // Nothing to do
1021   case AtomicOrdering::Release:
1022   case AtomicOrdering::AcquireRelease:
1023     return Builder.CreateFence(AtomicOrdering::Release);
1024   case AtomicOrdering::SequentiallyConsistent:
1025     if (!Inst->hasAtomicStore())
1026       return nullptr; // Nothing to do
1027     return Builder.CreateFence(AtomicOrdering::SequentiallyConsistent);
1028   }
1029   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
1030 }
1031 
1032 Instruction *VETargetLowering::emitTrailingFence(IRBuilderBase &Builder,
1033                                                  Instruction *Inst,
1034                                                  AtomicOrdering Ord) const {
1035   switch (Ord) {
1036   case AtomicOrdering::NotAtomic:
1037   case AtomicOrdering::Unordered:
1038     llvm_unreachable("Invalid fence: unordered/not-atomic");
1039   case AtomicOrdering::Monotonic:
1040   case AtomicOrdering::Release:
1041     return nullptr; // Nothing to do
1042   case AtomicOrdering::Acquire:
1043   case AtomicOrdering::AcquireRelease:
1044     return Builder.CreateFence(AtomicOrdering::Acquire);
1045   case AtomicOrdering::SequentiallyConsistent:
1046     return Builder.CreateFence(AtomicOrdering::SequentiallyConsistent);
1047   }
1048   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
1049 }
1050 
1051 SDValue VETargetLowering::lowerATOMIC_FENCE(SDValue Op,
1052                                             SelectionDAG &DAG) const {
1053   SDLoc DL(Op);
1054   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
1055       cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
1056   SyncScope::ID FenceSSID = static_cast<SyncScope::ID>(
1057       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
1058 
1059   // VE uses Release consistency, so need a fence instruction if it is a
1060   // cross-thread fence.
1061   if (FenceSSID == SyncScope::System) {
1062     switch (FenceOrdering) {
1063     case AtomicOrdering::NotAtomic:
1064     case AtomicOrdering::Unordered:
1065     case AtomicOrdering::Monotonic:
1066       // No need to generate fencem instruction here.
1067       break;
1068     case AtomicOrdering::Acquire:
1069       // Generate "fencem 2" as acquire fence.
1070       return SDValue(DAG.getMachineNode(VE::FENCEM, DL, MVT::Other,
1071                                         DAG.getTargetConstant(2, DL, MVT::i32),
1072                                         Op.getOperand(0)),
1073                      0);
1074     case AtomicOrdering::Release:
1075       // Generate "fencem 1" as release fence.
1076       return SDValue(DAG.getMachineNode(VE::FENCEM, DL, MVT::Other,
1077                                         DAG.getTargetConstant(1, DL, MVT::i32),
1078                                         Op.getOperand(0)),
1079                      0);
1080     case AtomicOrdering::AcquireRelease:
1081     case AtomicOrdering::SequentiallyConsistent:
1082       // Generate "fencem 3" as acq_rel and seq_cst fence.
1083       // FIXME: "fencem 3" doesn't wait for for PCIe deveices accesses,
1084       //        so  seq_cst may require more instruction for them.
1085       return SDValue(DAG.getMachineNode(VE::FENCEM, DL, MVT::Other,
1086                                         DAG.getTargetConstant(3, DL, MVT::i32),
1087                                         Op.getOperand(0)),
1088                      0);
1089     }
1090   }
1091 
1092   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
1093   return DAG.getNode(VEISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
1094 }
1095 
1096 TargetLowering::AtomicExpansionKind
1097 VETargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
1098   // We have TS1AM implementation for i8/i16/i32/i64, so use it.
1099   if (AI->getOperation() == AtomicRMWInst::Xchg) {
1100     return AtomicExpansionKind::None;
1101   }
1102   // FIXME: Support "ATMAM" instruction for LOAD_ADD/SUB/AND/OR.
1103 
1104   // Otherwise, expand it using compare and exchange instruction to not call
1105   // __sync_fetch_and_* functions.
1106   return AtomicExpansionKind::CmpXChg;
1107 }
1108 
1109 static SDValue prepareTS1AM(SDValue Op, SelectionDAG &DAG, SDValue &Flag,
1110                             SDValue &Bits) {
1111   SDLoc DL(Op);
1112   AtomicSDNode *N = cast<AtomicSDNode>(Op);
1113   SDValue Ptr = N->getOperand(1);
1114   SDValue Val = N->getOperand(2);
1115   EVT PtrVT = Ptr.getValueType();
1116   bool Byte = N->getMemoryVT() == MVT::i8;
1117   //   Remainder = AND Ptr, 3
1118   //   Flag = 1 << Remainder  ; If Byte is true (1 byte swap flag)
1119   //   Flag = 3 << Remainder  ; If Byte is false (2 bytes swap flag)
1120   //   Bits = Remainder << 3
1121   //   NewVal = Val << Bits
1122   SDValue Const3 = DAG.getConstant(3, DL, PtrVT);
1123   SDValue Remainder = DAG.getNode(ISD::AND, DL, PtrVT, {Ptr, Const3});
1124   SDValue Mask = Byte ? DAG.getConstant(1, DL, MVT::i32)
1125                       : DAG.getConstant(3, DL, MVT::i32);
1126   Flag = DAG.getNode(ISD::SHL, DL, MVT::i32, {Mask, Remainder});
1127   Bits = DAG.getNode(ISD::SHL, DL, PtrVT, {Remainder, Const3});
1128   return DAG.getNode(ISD::SHL, DL, Val.getValueType(), {Val, Bits});
1129 }
1130 
1131 static SDValue finalizeTS1AM(SDValue Op, SelectionDAG &DAG, SDValue Data,
1132                              SDValue Bits) {
1133   SDLoc DL(Op);
1134   EVT VT = Data.getValueType();
1135   bool Byte = cast<AtomicSDNode>(Op)->getMemoryVT() == MVT::i8;
1136   //   NewData = Data >> Bits
1137   //   Result = NewData & 0xff   ; If Byte is true (1 byte)
1138   //   Result = NewData & 0xffff ; If Byte is false (2 bytes)
1139 
1140   SDValue NewData = DAG.getNode(ISD::SRL, DL, VT, Data, Bits);
1141   return DAG.getNode(ISD::AND, DL, VT,
1142                      {NewData, DAG.getConstant(Byte ? 0xff : 0xffff, DL, VT)});
1143 }
1144 
1145 SDValue VETargetLowering::lowerATOMIC_SWAP(SDValue Op,
1146                                            SelectionDAG &DAG) const {
1147   SDLoc DL(Op);
1148   AtomicSDNode *N = cast<AtomicSDNode>(Op);
1149 
1150   if (N->getMemoryVT() == MVT::i8) {
1151     // For i8, use "ts1am"
1152     //   Input:
1153     //     ATOMIC_SWAP Ptr, Val, Order
1154     //
1155     //   Output:
1156     //     Remainder = AND Ptr, 3
1157     //     Flag = 1 << Remainder   ; 1 byte swap flag for TS1AM inst.
1158     //     Bits = Remainder << 3
1159     //     NewVal = Val << Bits
1160     //
1161     //     Aligned = AND Ptr, -4
1162     //     Data = TS1AM Aligned, Flag, NewVal
1163     //
1164     //     NewData = Data >> Bits
1165     //     Result = NewData & 0xff ; 1 byte result
1166     SDValue Flag;
1167     SDValue Bits;
1168     SDValue NewVal = prepareTS1AM(Op, DAG, Flag, Bits);
1169 
1170     SDValue Ptr = N->getOperand(1);
1171     SDValue Aligned = DAG.getNode(ISD::AND, DL, Ptr.getValueType(),
1172                                   {Ptr, DAG.getConstant(-4, DL, MVT::i64)});
1173     SDValue TS1AM = DAG.getAtomic(VEISD::TS1AM, DL, N->getMemoryVT(),
1174                                   DAG.getVTList(Op.getNode()->getValueType(0),
1175                                                 Op.getNode()->getValueType(1)),
1176                                   {N->getChain(), Aligned, Flag, NewVal},
1177                                   N->getMemOperand());
1178 
1179     SDValue Result = finalizeTS1AM(Op, DAG, TS1AM, Bits);
1180     SDValue Chain = TS1AM.getValue(1);
1181     return DAG.getMergeValues({Result, Chain}, DL);
1182   }
1183   if (N->getMemoryVT() == MVT::i16) {
1184     // For i16, use "ts1am"
1185     SDValue Flag;
1186     SDValue Bits;
1187     SDValue NewVal = prepareTS1AM(Op, DAG, Flag, Bits);
1188 
1189     SDValue Ptr = N->getOperand(1);
1190     SDValue Aligned = DAG.getNode(ISD::AND, DL, Ptr.getValueType(),
1191                                   {Ptr, DAG.getConstant(-4, DL, MVT::i64)});
1192     SDValue TS1AM = DAG.getAtomic(VEISD::TS1AM, DL, N->getMemoryVT(),
1193                                   DAG.getVTList(Op.getNode()->getValueType(0),
1194                                                 Op.getNode()->getValueType(1)),
1195                                   {N->getChain(), Aligned, Flag, NewVal},
1196                                   N->getMemOperand());
1197 
1198     SDValue Result = finalizeTS1AM(Op, DAG, TS1AM, Bits);
1199     SDValue Chain = TS1AM.getValue(1);
1200     return DAG.getMergeValues({Result, Chain}, DL);
1201   }
1202   // Otherwise, let llvm legalize it.
1203   return Op;
1204 }
1205 
1206 SDValue VETargetLowering::lowerGlobalAddress(SDValue Op,
1207                                              SelectionDAG &DAG) const {
1208   return makeAddress(Op, DAG);
1209 }
1210 
1211 SDValue VETargetLowering::lowerBlockAddress(SDValue Op,
1212                                             SelectionDAG &DAG) const {
1213   return makeAddress(Op, DAG);
1214 }
1215 
1216 SDValue VETargetLowering::lowerConstantPool(SDValue Op,
1217                                             SelectionDAG &DAG) const {
1218   return makeAddress(Op, DAG);
1219 }
1220 
1221 SDValue
1222 VETargetLowering::lowerToTLSGeneralDynamicModel(SDValue Op,
1223                                                 SelectionDAG &DAG) const {
1224   SDLoc DL(Op);
1225 
1226   // Generate the following code:
1227   //   t1: ch,glue = callseq_start t0, 0, 0
1228   //   t2: i64,ch,glue = VEISD::GETTLSADDR t1, label, t1:1
1229   //   t3: ch,glue = callseq_end t2, 0, 0, t2:2
1230   //   t4: i64,ch,glue = CopyFromReg t3, Register:i64 $sx0, t3:1
1231   SDValue Label = withTargetFlags(Op, 0, DAG);
1232   EVT PtrVT = Op.getValueType();
1233 
1234   // Lowering the machine isd will make sure everything is in the right
1235   // location.
1236   SDValue Chain = DAG.getEntryNode();
1237   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1238   const uint32_t *Mask = Subtarget->getRegisterInfo()->getCallPreservedMask(
1239       DAG.getMachineFunction(), CallingConv::C);
1240   Chain = DAG.getCALLSEQ_START(Chain, 64, 0, DL);
1241   SDValue Args[] = {Chain, Label, DAG.getRegisterMask(Mask), Chain.getValue(1)};
1242   Chain = DAG.getNode(VEISD::GETTLSADDR, DL, NodeTys, Args);
1243   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(64, DL, true),
1244                              DAG.getIntPtrConstant(0, DL, true),
1245                              Chain.getValue(1), DL);
1246   Chain = DAG.getCopyFromReg(Chain, DL, VE::SX0, PtrVT, Chain.getValue(1));
1247 
1248   // GETTLSADDR will be codegen'ed as call. Inform MFI that function has calls.
1249   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
1250   MFI.setHasCalls(true);
1251 
1252   // Also generate code to prepare a GOT register if it is PIC.
1253   if (isPositionIndependent()) {
1254     MachineFunction &MF = DAG.getMachineFunction();
1255     Subtarget->getInstrInfo()->getGlobalBaseReg(&MF);
1256   }
1257 
1258   return Chain;
1259 }
1260 
1261 SDValue VETargetLowering::lowerGlobalTLSAddress(SDValue Op,
1262                                                 SelectionDAG &DAG) const {
1263   // The current implementation of nld (2.26) doesn't allow local exec model
1264   // code described in VE-tls_v1.1.pdf (*1) as its input. Instead, we always
1265   // generate the general dynamic model code sequence.
1266   //
1267   // *1: https://www.nec.com/en/global/prod/hpc/aurora/document/VE-tls_v1.1.pdf
1268   return lowerToTLSGeneralDynamicModel(Op, DAG);
1269 }
1270 
1271 SDValue VETargetLowering::lowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1272   return makeAddress(Op, DAG);
1273 }
1274 
1275 // Lower a f128 load into two f64 loads.
1276 static SDValue lowerLoadF128(SDValue Op, SelectionDAG &DAG) {
1277   SDLoc DL(Op);
1278   LoadSDNode *LdNode = dyn_cast<LoadSDNode>(Op.getNode());
1279   assert(LdNode && LdNode->getOffset().isUndef() && "Unexpected node type");
1280   unsigned Alignment = LdNode->getAlign().value();
1281   if (Alignment > 8)
1282     Alignment = 8;
1283 
1284   SDValue Lo64 =
1285       DAG.getLoad(MVT::f64, DL, LdNode->getChain(), LdNode->getBasePtr(),
1286                   LdNode->getPointerInfo(), Alignment,
1287                   LdNode->isVolatile() ? MachineMemOperand::MOVolatile
1288                                        : MachineMemOperand::MONone);
1289   EVT AddrVT = LdNode->getBasePtr().getValueType();
1290   SDValue HiPtr = DAG.getNode(ISD::ADD, DL, AddrVT, LdNode->getBasePtr(),
1291                               DAG.getConstant(8, DL, AddrVT));
1292   SDValue Hi64 =
1293       DAG.getLoad(MVT::f64, DL, LdNode->getChain(), HiPtr,
1294                   LdNode->getPointerInfo(), Alignment,
1295                   LdNode->isVolatile() ? MachineMemOperand::MOVolatile
1296                                        : MachineMemOperand::MONone);
1297 
1298   SDValue SubRegEven = DAG.getTargetConstant(VE::sub_even, DL, MVT::i32);
1299   SDValue SubRegOdd = DAG.getTargetConstant(VE::sub_odd, DL, MVT::i32);
1300 
1301   // VE stores Hi64 to 8(addr) and Lo64 to 0(addr)
1302   SDNode *InFP128 =
1303       DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f128);
1304   InFP128 = DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f128,
1305                                SDValue(InFP128, 0), Hi64, SubRegEven);
1306   InFP128 = DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f128,
1307                                SDValue(InFP128, 0), Lo64, SubRegOdd);
1308   SDValue OutChains[2] = {SDValue(Lo64.getNode(), 1),
1309                           SDValue(Hi64.getNode(), 1)};
1310   SDValue OutChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
1311   SDValue Ops[2] = {SDValue(InFP128, 0), OutChain};
1312   return DAG.getMergeValues(Ops, DL);
1313 }
1314 
1315 SDValue VETargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1316   LoadSDNode *LdNode = cast<LoadSDNode>(Op.getNode());
1317 
1318   SDValue BasePtr = LdNode->getBasePtr();
1319   if (isa<FrameIndexSDNode>(BasePtr.getNode())) {
1320     // Do not expand store instruction with frame index here because of
1321     // dependency problems.  We expand it later in eliminateFrameIndex().
1322     return Op;
1323   }
1324 
1325   EVT MemVT = LdNode->getMemoryVT();
1326   if (MemVT == MVT::f128)
1327     return lowerLoadF128(Op, DAG);
1328 
1329   return Op;
1330 }
1331 
1332 // Lower a f128 store into two f64 stores.
1333 static SDValue lowerStoreF128(SDValue Op, SelectionDAG &DAG) {
1334   SDLoc DL(Op);
1335   StoreSDNode *StNode = dyn_cast<StoreSDNode>(Op.getNode());
1336   assert(StNode && StNode->getOffset().isUndef() && "Unexpected node type");
1337 
1338   SDValue SubRegEven = DAG.getTargetConstant(VE::sub_even, DL, MVT::i32);
1339   SDValue SubRegOdd = DAG.getTargetConstant(VE::sub_odd, DL, MVT::i32);
1340 
1341   SDNode *Hi64 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i64,
1342                                     StNode->getValue(), SubRegEven);
1343   SDNode *Lo64 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i64,
1344                                     StNode->getValue(), SubRegOdd);
1345 
1346   unsigned Alignment = StNode->getAlign().value();
1347   if (Alignment > 8)
1348     Alignment = 8;
1349 
1350   // VE stores Hi64 to 8(addr) and Lo64 to 0(addr)
1351   SDValue OutChains[2];
1352   OutChains[0] =
1353       DAG.getStore(StNode->getChain(), DL, SDValue(Lo64, 0),
1354                    StNode->getBasePtr(), MachinePointerInfo(), Alignment,
1355                    StNode->isVolatile() ? MachineMemOperand::MOVolatile
1356                                         : MachineMemOperand::MONone);
1357   EVT AddrVT = StNode->getBasePtr().getValueType();
1358   SDValue HiPtr = DAG.getNode(ISD::ADD, DL, AddrVT, StNode->getBasePtr(),
1359                               DAG.getConstant(8, DL, AddrVT));
1360   OutChains[1] =
1361       DAG.getStore(StNode->getChain(), DL, SDValue(Hi64, 0), HiPtr,
1362                    MachinePointerInfo(), Alignment,
1363                    StNode->isVolatile() ? MachineMemOperand::MOVolatile
1364                                         : MachineMemOperand::MONone);
1365   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
1366 }
1367 
1368 SDValue VETargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1369   StoreSDNode *StNode = cast<StoreSDNode>(Op.getNode());
1370   assert(StNode && StNode->getOffset().isUndef() && "Unexpected node type");
1371 
1372   SDValue BasePtr = StNode->getBasePtr();
1373   if (isa<FrameIndexSDNode>(BasePtr.getNode())) {
1374     // Do not expand store instruction with frame index here because of
1375     // dependency problems.  We expand it later in eliminateFrameIndex().
1376     return Op;
1377   }
1378 
1379   EVT MemVT = StNode->getMemoryVT();
1380   if (MemVT == MVT::f128)
1381     return lowerStoreF128(Op, DAG);
1382 
1383   // Otherwise, ask llvm to expand it.
1384   return SDValue();
1385 }
1386 
1387 SDValue VETargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1388   MachineFunction &MF = DAG.getMachineFunction();
1389   VEMachineFunctionInfo *FuncInfo = MF.getInfo<VEMachineFunctionInfo>();
1390   auto PtrVT = getPointerTy(DAG.getDataLayout());
1391 
1392   // Need frame address to find the address of VarArgsFrameIndex.
1393   MF.getFrameInfo().setFrameAddressIsTaken(true);
1394 
1395   // vastart just stores the address of the VarArgsFrameIndex slot into the
1396   // memory location argument.
1397   SDLoc DL(Op);
1398   SDValue Offset =
1399       DAG.getNode(ISD::ADD, DL, PtrVT, DAG.getRegister(VE::SX9, PtrVT),
1400                   DAG.getIntPtrConstant(FuncInfo->getVarArgsFrameOffset(), DL));
1401   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1402   return DAG.getStore(Op.getOperand(0), DL, Offset, Op.getOperand(1),
1403                       MachinePointerInfo(SV));
1404 }
1405 
1406 SDValue VETargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
1407   SDNode *Node = Op.getNode();
1408   EVT VT = Node->getValueType(0);
1409   SDValue InChain = Node->getOperand(0);
1410   SDValue VAListPtr = Node->getOperand(1);
1411   EVT PtrVT = VAListPtr.getValueType();
1412   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1413   SDLoc DL(Node);
1414   SDValue VAList =
1415       DAG.getLoad(PtrVT, DL, InChain, VAListPtr, MachinePointerInfo(SV));
1416   SDValue Chain = VAList.getValue(1);
1417   SDValue NextPtr;
1418 
1419   if (VT == MVT::f128) {
1420     // VE f128 values must be stored with 16 bytes alignment.  We doesn't
1421     // know the actual alignment of VAList, so we take alignment of it
1422     // dyanmically.
1423     int Align = 16;
1424     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
1425                          DAG.getConstant(Align - 1, DL, PtrVT));
1426     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
1427                          DAG.getConstant(-Align, DL, PtrVT));
1428     // Increment the pointer, VAList, by 16 to the next vaarg.
1429     NextPtr =
1430         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getIntPtrConstant(16, DL));
1431   } else if (VT == MVT::f32) {
1432     // float --> need special handling like below.
1433     //    0      4
1434     //    +------+------+
1435     //    | empty| float|
1436     //    +------+------+
1437     // Increment the pointer, VAList, by 8 to the next vaarg.
1438     NextPtr =
1439         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getIntPtrConstant(8, DL));
1440     // Then, adjust VAList.
1441     unsigned InternalOffset = 4;
1442     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
1443                          DAG.getConstant(InternalOffset, DL, PtrVT));
1444   } else {
1445     // Increment the pointer, VAList, by 8 to the next vaarg.
1446     NextPtr =
1447         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getIntPtrConstant(8, DL));
1448   }
1449 
1450   // Store the incremented VAList to the legalized pointer.
1451   InChain = DAG.getStore(Chain, DL, NextPtr, VAListPtr, MachinePointerInfo(SV));
1452 
1453   // Load the actual argument out of the pointer VAList.
1454   // We can't count on greater alignment than the word size.
1455   return DAG.getLoad(VT, DL, InChain, VAList, MachinePointerInfo(),
1456                      std::min(PtrVT.getSizeInBits(), VT.getSizeInBits()) / 8);
1457 }
1458 
1459 SDValue VETargetLowering::lowerDYNAMIC_STACKALLOC(SDValue Op,
1460                                                   SelectionDAG &DAG) const {
1461   // Generate following code.
1462   //   (void)__llvm_grow_stack(size);
1463   //   ret = GETSTACKTOP;        // pseudo instruction
1464   SDLoc DL(Op);
1465 
1466   // Get the inputs.
1467   SDNode *Node = Op.getNode();
1468   SDValue Chain = Op.getOperand(0);
1469   SDValue Size = Op.getOperand(1);
1470   MaybeAlign Alignment(Op.getConstantOperandVal(2));
1471   EVT VT = Node->getValueType(0);
1472 
1473   // Chain the dynamic stack allocation so that it doesn't modify the stack
1474   // pointer when other instructions are using the stack.
1475   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
1476 
1477   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
1478   Align StackAlign = TFI.getStackAlign();
1479   bool NeedsAlign = Alignment.valueOrOne() > StackAlign;
1480 
1481   // Prepare arguments
1482   TargetLowering::ArgListTy Args;
1483   TargetLowering::ArgListEntry Entry;
1484   Entry.Node = Size;
1485   Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
1486   Args.push_back(Entry);
1487   if (NeedsAlign) {
1488     Entry.Node = DAG.getConstant(~(Alignment->value() - 1ULL), DL, VT);
1489     Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
1490     Args.push_back(Entry);
1491   }
1492   Type *RetTy = Type::getVoidTy(*DAG.getContext());
1493 
1494   EVT PtrVT = Op.getValueType();
1495   SDValue Callee;
1496   if (NeedsAlign) {
1497     Callee = DAG.getTargetExternalSymbol("__ve_grow_stack_align", PtrVT, 0);
1498   } else {
1499     Callee = DAG.getTargetExternalSymbol("__ve_grow_stack", PtrVT, 0);
1500   }
1501 
1502   TargetLowering::CallLoweringInfo CLI(DAG);
1503   CLI.setDebugLoc(DL)
1504       .setChain(Chain)
1505       .setCallee(CallingConv::PreserveAll, RetTy, Callee, std::move(Args))
1506       .setDiscardResult(true);
1507   std::pair<SDValue, SDValue> pair = LowerCallTo(CLI);
1508   Chain = pair.second;
1509   SDValue Result = DAG.getNode(VEISD::GETSTACKTOP, DL, VT, Chain);
1510   if (NeedsAlign) {
1511     Result = DAG.getNode(ISD::ADD, DL, VT, Result,
1512                          DAG.getConstant((Alignment->value() - 1ULL), DL, VT));
1513     Result = DAG.getNode(ISD::AND, DL, VT, Result,
1514                          DAG.getConstant(~(Alignment->value() - 1ULL), DL, VT));
1515   }
1516   //  Chain = Result.getValue(1);
1517   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, DL, true),
1518                              DAG.getIntPtrConstant(0, DL, true), SDValue(), DL);
1519 
1520   SDValue Ops[2] = {Result, Chain};
1521   return DAG.getMergeValues(Ops, DL);
1522 }
1523 
1524 SDValue VETargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
1525                                                SelectionDAG &DAG) const {
1526   SDLoc DL(Op);
1527   return DAG.getNode(VEISD::EH_SJLJ_LONGJMP, DL, MVT::Other, Op.getOperand(0),
1528                      Op.getOperand(1));
1529 }
1530 
1531 SDValue VETargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
1532                                               SelectionDAG &DAG) const {
1533   SDLoc DL(Op);
1534   return DAG.getNode(VEISD::EH_SJLJ_SETJMP, DL,
1535                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
1536                      Op.getOperand(1));
1537 }
1538 
1539 SDValue VETargetLowering::lowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
1540                                                       SelectionDAG &DAG) const {
1541   SDLoc DL(Op);
1542   return DAG.getNode(VEISD::EH_SJLJ_SETUP_DISPATCH, DL, MVT::Other,
1543                      Op.getOperand(0));
1544 }
1545 
1546 static SDValue lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG,
1547                               const VETargetLowering &TLI,
1548                               const VESubtarget *Subtarget) {
1549   SDLoc DL(Op);
1550   MachineFunction &MF = DAG.getMachineFunction();
1551   EVT PtrVT = TLI.getPointerTy(MF.getDataLayout());
1552 
1553   MachineFrameInfo &MFI = MF.getFrameInfo();
1554   MFI.setFrameAddressIsTaken(true);
1555 
1556   unsigned Depth = Op.getConstantOperandVal(0);
1557   const VERegisterInfo *RegInfo = Subtarget->getRegisterInfo();
1558   Register FrameReg = RegInfo->getFrameRegister(MF);
1559   SDValue FrameAddr =
1560       DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, PtrVT);
1561   while (Depth--)
1562     FrameAddr = DAG.getLoad(Op.getValueType(), DL, DAG.getEntryNode(),
1563                             FrameAddr, MachinePointerInfo());
1564   return FrameAddr;
1565 }
1566 
1567 static SDValue lowerRETURNADDR(SDValue Op, SelectionDAG &DAG,
1568                                const VETargetLowering &TLI,
1569                                const VESubtarget *Subtarget) {
1570   MachineFunction &MF = DAG.getMachineFunction();
1571   MachineFrameInfo &MFI = MF.getFrameInfo();
1572   MFI.setReturnAddressIsTaken(true);
1573 
1574   if (TLI.verifyReturnAddressArgumentIsConstant(Op, DAG))
1575     return SDValue();
1576 
1577   SDValue FrameAddr = lowerFRAMEADDR(Op, DAG, TLI, Subtarget);
1578 
1579   SDLoc DL(Op);
1580   EVT VT = Op.getValueType();
1581   SDValue Offset = DAG.getConstant(8, DL, VT);
1582   return DAG.getLoad(VT, DL, DAG.getEntryNode(),
1583                      DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
1584                      MachinePointerInfo());
1585 }
1586 
1587 SDValue VETargetLowering::lowerINTRINSIC_WO_CHAIN(SDValue Op,
1588                                                   SelectionDAG &DAG) const {
1589   SDLoc DL(Op);
1590   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1591   switch (IntNo) {
1592   default: // Don't custom lower most intrinsics.
1593     return SDValue();
1594   case Intrinsic::eh_sjlj_lsda: {
1595     MachineFunction &MF = DAG.getMachineFunction();
1596     MVT VT = Op.getSimpleValueType();
1597     const VETargetMachine *TM =
1598         static_cast<const VETargetMachine *>(&DAG.getTarget());
1599 
1600     // Create GCC_except_tableXX string.  The real symbol for that will be
1601     // generated in EHStreamer::emitExceptionTable() later.  So, we just
1602     // borrow it's name here.
1603     TM->getStrList()->push_back(std::string(
1604         (Twine("GCC_except_table") + Twine(MF.getFunctionNumber())).str()));
1605     SDValue Addr =
1606         DAG.getTargetExternalSymbol(TM->getStrList()->back().c_str(), VT, 0);
1607     if (isPositionIndependent()) {
1608       Addr = makeHiLoPair(Addr, VEMCExpr::VK_VE_GOTOFF_HI32,
1609                           VEMCExpr::VK_VE_GOTOFF_LO32, DAG);
1610       SDValue GlobalBase = DAG.getNode(VEISD::GLOBAL_BASE_REG, DL, VT);
1611       return DAG.getNode(ISD::ADD, DL, VT, GlobalBase, Addr);
1612     }
1613     return makeHiLoPair(Addr, VEMCExpr::VK_VE_HI32, VEMCExpr::VK_VE_LO32, DAG);
1614   }
1615   }
1616 }
1617 
1618 static bool getUniqueInsertion(SDNode *N, unsigned &UniqueIdx) {
1619   if (!isa<BuildVectorSDNode>(N))
1620     return false;
1621   const auto *BVN = cast<BuildVectorSDNode>(N);
1622 
1623   // Find first non-undef insertion.
1624   unsigned Idx;
1625   for (Idx = 0; Idx < BVN->getNumOperands(); ++Idx) {
1626     auto ElemV = BVN->getOperand(Idx);
1627     if (!ElemV->isUndef())
1628       break;
1629   }
1630   // Catch the (hypothetical) all-undef case.
1631   if (Idx == BVN->getNumOperands())
1632     return false;
1633   // Remember insertion.
1634   UniqueIdx = Idx++;
1635   // Verify that all other insertions are undef.
1636   for (; Idx < BVN->getNumOperands(); ++Idx) {
1637     auto ElemV = BVN->getOperand(Idx);
1638     if (!ElemV->isUndef())
1639       return false;
1640   }
1641   return true;
1642 }
1643 
1644 static SDValue getSplatValue(SDNode *N) {
1645   if (auto *BuildVec = dyn_cast<BuildVectorSDNode>(N)) {
1646     return BuildVec->getSplatValue();
1647   }
1648   return SDValue();
1649 }
1650 
1651 SDValue VETargetLowering::lowerBUILD_VECTOR(SDValue Op,
1652                                             SelectionDAG &DAG) const {
1653   VECustomDAG CDAG(DAG, Op);
1654   MVT ResultVT = Op.getSimpleValueType();
1655 
1656   // If there is just one element, expand to INSERT_VECTOR_ELT.
1657   unsigned UniqueIdx;
1658   if (getUniqueInsertion(Op.getNode(), UniqueIdx)) {
1659     SDValue AccuV = CDAG.getUNDEF(Op.getValueType());
1660     auto ElemV = Op->getOperand(UniqueIdx);
1661     SDValue IdxV = CDAG.getConstant(UniqueIdx, MVT::i64);
1662     return CDAG.getNode(ISD::INSERT_VECTOR_ELT, ResultVT, {AccuV, ElemV, IdxV});
1663   }
1664 
1665   // Else emit a broadcast.
1666   if (SDValue ScalarV = getSplatValue(Op.getNode())) {
1667     unsigned NumEls = ResultVT.getVectorNumElements();
1668     auto AVL = CDAG.getConstant(NumEls, MVT::i32);
1669     return CDAG.getBroadcast(ResultVT, ScalarV, AVL);
1670   }
1671 
1672   // Expand
1673   return SDValue();
1674 }
1675 
1676 TargetLowering::LegalizeAction
1677 VETargetLowering::getCustomOperationAction(SDNode &Op) const {
1678   // Custom lower to legalize AVL for packed mode.
1679   if (isVVPOrVEC(Op.getOpcode()))
1680     return Custom;
1681   return Legal;
1682 }
1683 
1684 SDValue VETargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
1685   LLVM_DEBUG(dbgs() << "::LowerOperation"; Op->print(dbgs()););
1686   unsigned Opcode = Op.getOpcode();
1687   if (ISD::isVPOpcode(Opcode))
1688     return lowerToVVP(Op, DAG);
1689 
1690   switch (Opcode) {
1691   default:
1692     llvm_unreachable("Should not custom lower this!");
1693   case ISD::ATOMIC_FENCE:
1694     return lowerATOMIC_FENCE(Op, DAG);
1695   case ISD::ATOMIC_SWAP:
1696     return lowerATOMIC_SWAP(Op, DAG);
1697   case ISD::BlockAddress:
1698     return lowerBlockAddress(Op, DAG);
1699   case ISD::ConstantPool:
1700     return lowerConstantPool(Op, DAG);
1701   case ISD::DYNAMIC_STACKALLOC:
1702     return lowerDYNAMIC_STACKALLOC(Op, DAG);
1703   case ISD::EH_SJLJ_LONGJMP:
1704     return lowerEH_SJLJ_LONGJMP(Op, DAG);
1705   case ISD::EH_SJLJ_SETJMP:
1706     return lowerEH_SJLJ_SETJMP(Op, DAG);
1707   case ISD::EH_SJLJ_SETUP_DISPATCH:
1708     return lowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
1709   case ISD::FRAMEADDR:
1710     return lowerFRAMEADDR(Op, DAG, *this, Subtarget);
1711   case ISD::GlobalAddress:
1712     return lowerGlobalAddress(Op, DAG);
1713   case ISD::GlobalTLSAddress:
1714     return lowerGlobalTLSAddress(Op, DAG);
1715   case ISD::INTRINSIC_WO_CHAIN:
1716     return lowerINTRINSIC_WO_CHAIN(Op, DAG);
1717   case ISD::JumpTable:
1718     return lowerJumpTable(Op, DAG);
1719   case ISD::LOAD:
1720     return lowerLOAD(Op, DAG);
1721   case ISD::RETURNADDR:
1722     return lowerRETURNADDR(Op, DAG, *this, Subtarget);
1723   case ISD::BUILD_VECTOR:
1724     return lowerBUILD_VECTOR(Op, DAG);
1725   case ISD::STORE:
1726     return lowerSTORE(Op, DAG);
1727   case ISD::VASTART:
1728     return lowerVASTART(Op, DAG);
1729   case ISD::VAARG:
1730     return lowerVAARG(Op, DAG);
1731 
1732   case ISD::INSERT_VECTOR_ELT:
1733     return lowerINSERT_VECTOR_ELT(Op, DAG);
1734   case ISD::EXTRACT_VECTOR_ELT:
1735     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
1736 
1737   // Legalize the AVL of this internal node.
1738   case VEISD::VEC_BROADCAST:
1739 #define ADD_VVP_OP(VVP_NAME, ...) case VEISD::VVP_NAME:
1740 #include "VVPNodes.def"
1741     // AVL already legalized.
1742     if (getAnnotatedNodeAVL(Op).second)
1743       return Op;
1744     return legalizeInternalVectorOp(Op, DAG);
1745 
1746     // Translate into a VEC_*/VVP_* layer operation.
1747 #define ADD_VVP_OP(VVP_NAME, ISD_NAME) case ISD::ISD_NAME:
1748 #include "VVPNodes.def"
1749     return lowerToVVP(Op, DAG);
1750   }
1751 }
1752 /// } Custom Lower
1753 
1754 void VETargetLowering::ReplaceNodeResults(SDNode *N,
1755                                           SmallVectorImpl<SDValue> &Results,
1756                                           SelectionDAG &DAG) const {
1757   switch (N->getOpcode()) {
1758   case ISD::ATOMIC_SWAP:
1759     // Let LLVM expand atomic swap instruction through LowerOperation.
1760     return;
1761   default:
1762     LLVM_DEBUG(N->dumpr(&DAG));
1763     llvm_unreachable("Do not know how to custom type legalize this operation!");
1764   }
1765 }
1766 
1767 /// JumpTable for VE.
1768 ///
1769 ///   VE cannot generate relocatable symbol in jump table.  VE cannot
1770 ///   generate expressions using symbols in both text segment and data
1771 ///   segment like below.
1772 ///             .4byte  .LBB0_2-.LJTI0_0
1773 ///   So, we generate offset from the top of function like below as
1774 ///   a custom label.
1775 ///             .4byte  .LBB0_2-<function name>
1776 
1777 unsigned VETargetLowering::getJumpTableEncoding() const {
1778   // Use custom label for PIC.
1779   if (isPositionIndependent())
1780     return MachineJumpTableInfo::EK_Custom32;
1781 
1782   // Otherwise, use the normal jump table encoding heuristics.
1783   return TargetLowering::getJumpTableEncoding();
1784 }
1785 
1786 const MCExpr *VETargetLowering::LowerCustomJumpTableEntry(
1787     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
1788     unsigned Uid, MCContext &Ctx) const {
1789   assert(isPositionIndependent());
1790 
1791   // Generate custom label for PIC like below.
1792   //    .4bytes  .LBB0_2-<function name>
1793   const auto *Value = MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
1794   MCSymbol *Sym = Ctx.getOrCreateSymbol(MBB->getParent()->getName().data());
1795   const auto *Base = MCSymbolRefExpr::create(Sym, Ctx);
1796   return MCBinaryExpr::createSub(Value, Base, Ctx);
1797 }
1798 
1799 SDValue VETargetLowering::getPICJumpTableRelocBase(SDValue Table,
1800                                                    SelectionDAG &DAG) const {
1801   assert(isPositionIndependent());
1802   SDLoc DL(Table);
1803   Function *Function = &DAG.getMachineFunction().getFunction();
1804   assert(Function != nullptr);
1805   auto PtrTy = getPointerTy(DAG.getDataLayout(), Function->getAddressSpace());
1806 
1807   // In the jump table, we have following values in PIC mode.
1808   //    .4bytes  .LBB0_2-<function name>
1809   // We need to add this value and the address of this function to generate
1810   // .LBB0_2 label correctly under PIC mode.  So, we want to generate following
1811   // instructions:
1812   //     lea %reg, fun@gotoff_lo
1813   //     and %reg, %reg, (32)0
1814   //     lea.sl %reg, fun@gotoff_hi(%reg, %got)
1815   // In order to do so, we need to genarate correctly marked DAG node using
1816   // makeHiLoPair.
1817   SDValue Op = DAG.getGlobalAddress(Function, DL, PtrTy);
1818   SDValue HiLo = makeHiLoPair(Op, VEMCExpr::VK_VE_GOTOFF_HI32,
1819                               VEMCExpr::VK_VE_GOTOFF_LO32, DAG);
1820   SDValue GlobalBase = DAG.getNode(VEISD::GLOBAL_BASE_REG, DL, PtrTy);
1821   return DAG.getNode(ISD::ADD, DL, PtrTy, GlobalBase, HiLo);
1822 }
1823 
1824 Register VETargetLowering::prepareMBB(MachineBasicBlock &MBB,
1825                                       MachineBasicBlock::iterator I,
1826                                       MachineBasicBlock *TargetBB,
1827                                       const DebugLoc &DL) const {
1828   MachineFunction *MF = MBB.getParent();
1829   MachineRegisterInfo &MRI = MF->getRegInfo();
1830   const VEInstrInfo *TII = Subtarget->getInstrInfo();
1831 
1832   const TargetRegisterClass *RC = &VE::I64RegClass;
1833   Register Tmp1 = MRI.createVirtualRegister(RC);
1834   Register Tmp2 = MRI.createVirtualRegister(RC);
1835   Register Result = MRI.createVirtualRegister(RC);
1836 
1837   if (isPositionIndependent()) {
1838     // Create following instructions for local linkage PIC code.
1839     //     lea %Tmp1, TargetBB@gotoff_lo
1840     //     and %Tmp2, %Tmp1, (32)0
1841     //     lea.sl %Result, TargetBB@gotoff_hi(%Tmp2, %s15) ; %s15 is GOT
1842     BuildMI(MBB, I, DL, TII->get(VE::LEAzii), Tmp1)
1843         .addImm(0)
1844         .addImm(0)
1845         .addMBB(TargetBB, VEMCExpr::VK_VE_GOTOFF_LO32);
1846     BuildMI(MBB, I, DL, TII->get(VE::ANDrm), Tmp2)
1847         .addReg(Tmp1, getKillRegState(true))
1848         .addImm(M0(32));
1849     BuildMI(MBB, I, DL, TII->get(VE::LEASLrri), Result)
1850         .addReg(VE::SX15)
1851         .addReg(Tmp2, getKillRegState(true))
1852         .addMBB(TargetBB, VEMCExpr::VK_VE_GOTOFF_HI32);
1853   } else {
1854     // Create following instructions for non-PIC code.
1855     //     lea     %Tmp1, TargetBB@lo
1856     //     and     %Tmp2, %Tmp1, (32)0
1857     //     lea.sl  %Result, TargetBB@hi(%Tmp2)
1858     BuildMI(MBB, I, DL, TII->get(VE::LEAzii), Tmp1)
1859         .addImm(0)
1860         .addImm(0)
1861         .addMBB(TargetBB, VEMCExpr::VK_VE_LO32);
1862     BuildMI(MBB, I, DL, TII->get(VE::ANDrm), Tmp2)
1863         .addReg(Tmp1, getKillRegState(true))
1864         .addImm(M0(32));
1865     BuildMI(MBB, I, DL, TII->get(VE::LEASLrii), Result)
1866         .addReg(Tmp2, getKillRegState(true))
1867         .addImm(0)
1868         .addMBB(TargetBB, VEMCExpr::VK_VE_HI32);
1869   }
1870   return Result;
1871 }
1872 
1873 Register VETargetLowering::prepareSymbol(MachineBasicBlock &MBB,
1874                                          MachineBasicBlock::iterator I,
1875                                          StringRef Symbol, const DebugLoc &DL,
1876                                          bool IsLocal = false,
1877                                          bool IsCall = false) const {
1878   MachineFunction *MF = MBB.getParent();
1879   MachineRegisterInfo &MRI = MF->getRegInfo();
1880   const VEInstrInfo *TII = Subtarget->getInstrInfo();
1881 
1882   const TargetRegisterClass *RC = &VE::I64RegClass;
1883   Register Result = MRI.createVirtualRegister(RC);
1884 
1885   if (isPositionIndependent()) {
1886     if (IsCall && !IsLocal) {
1887       // Create following instructions for non-local linkage PIC code function
1888       // calls.  These instructions uses IC and magic number -24, so we expand
1889       // them in VEAsmPrinter.cpp from GETFUNPLT pseudo instruction.
1890       //     lea %Reg, Symbol@plt_lo(-24)
1891       //     and %Reg, %Reg, (32)0
1892       //     sic %s16
1893       //     lea.sl %Result, Symbol@plt_hi(%Reg, %s16) ; %s16 is PLT
1894       BuildMI(MBB, I, DL, TII->get(VE::GETFUNPLT), Result)
1895           .addExternalSymbol("abort");
1896     } else if (IsLocal) {
1897       Register Tmp1 = MRI.createVirtualRegister(RC);
1898       Register Tmp2 = MRI.createVirtualRegister(RC);
1899       // Create following instructions for local linkage PIC code.
1900       //     lea %Tmp1, Symbol@gotoff_lo
1901       //     and %Tmp2, %Tmp1, (32)0
1902       //     lea.sl %Result, Symbol@gotoff_hi(%Tmp2, %s15) ; %s15 is GOT
1903       BuildMI(MBB, I, DL, TII->get(VE::LEAzii), Tmp1)
1904           .addImm(0)
1905           .addImm(0)
1906           .addExternalSymbol(Symbol.data(), VEMCExpr::VK_VE_GOTOFF_LO32);
1907       BuildMI(MBB, I, DL, TII->get(VE::ANDrm), Tmp2)
1908           .addReg(Tmp1, getKillRegState(true))
1909           .addImm(M0(32));
1910       BuildMI(MBB, I, DL, TII->get(VE::LEASLrri), Result)
1911           .addReg(VE::SX15)
1912           .addReg(Tmp2, getKillRegState(true))
1913           .addExternalSymbol(Symbol.data(), VEMCExpr::VK_VE_GOTOFF_HI32);
1914     } else {
1915       Register Tmp1 = MRI.createVirtualRegister(RC);
1916       Register Tmp2 = MRI.createVirtualRegister(RC);
1917       // Create following instructions for not local linkage PIC code.
1918       //     lea %Tmp1, Symbol@got_lo
1919       //     and %Tmp2, %Tmp1, (32)0
1920       //     lea.sl %Tmp3, Symbol@gotoff_hi(%Tmp2, %s15) ; %s15 is GOT
1921       //     ld %Result, 0(%Tmp3)
1922       Register Tmp3 = MRI.createVirtualRegister(RC);
1923       BuildMI(MBB, I, DL, TII->get(VE::LEAzii), Tmp1)
1924           .addImm(0)
1925           .addImm(0)
1926           .addExternalSymbol(Symbol.data(), VEMCExpr::VK_VE_GOT_LO32);
1927       BuildMI(MBB, I, DL, TII->get(VE::ANDrm), Tmp2)
1928           .addReg(Tmp1, getKillRegState(true))
1929           .addImm(M0(32));
1930       BuildMI(MBB, I, DL, TII->get(VE::LEASLrri), Tmp3)
1931           .addReg(VE::SX15)
1932           .addReg(Tmp2, getKillRegState(true))
1933           .addExternalSymbol(Symbol.data(), VEMCExpr::VK_VE_GOT_HI32);
1934       BuildMI(MBB, I, DL, TII->get(VE::LDrii), Result)
1935           .addReg(Tmp3, getKillRegState(true))
1936           .addImm(0)
1937           .addImm(0);
1938     }
1939   } else {
1940     Register Tmp1 = MRI.createVirtualRegister(RC);
1941     Register Tmp2 = MRI.createVirtualRegister(RC);
1942     // Create following instructions for non-PIC code.
1943     //     lea     %Tmp1, Symbol@lo
1944     //     and     %Tmp2, %Tmp1, (32)0
1945     //     lea.sl  %Result, Symbol@hi(%Tmp2)
1946     BuildMI(MBB, I, DL, TII->get(VE::LEAzii), Tmp1)
1947         .addImm(0)
1948         .addImm(0)
1949         .addExternalSymbol(Symbol.data(), VEMCExpr::VK_VE_LO32);
1950     BuildMI(MBB, I, DL, TII->get(VE::ANDrm), Tmp2)
1951         .addReg(Tmp1, getKillRegState(true))
1952         .addImm(M0(32));
1953     BuildMI(MBB, I, DL, TII->get(VE::LEASLrii), Result)
1954         .addReg(Tmp2, getKillRegState(true))
1955         .addImm(0)
1956         .addExternalSymbol(Symbol.data(), VEMCExpr::VK_VE_HI32);
1957   }
1958   return Result;
1959 }
1960 
1961 void VETargetLowering::setupEntryBlockForSjLj(MachineInstr &MI,
1962                                               MachineBasicBlock *MBB,
1963                                               MachineBasicBlock *DispatchBB,
1964                                               int FI, int Offset) const {
1965   DebugLoc DL = MI.getDebugLoc();
1966   const VEInstrInfo *TII = Subtarget->getInstrInfo();
1967 
1968   Register LabelReg =
1969       prepareMBB(*MBB, MachineBasicBlock::iterator(MI), DispatchBB, DL);
1970 
1971   // Store an address of DispatchBB to a given jmpbuf[1] where has next IC
1972   // referenced by longjmp (throw) later.
1973   MachineInstrBuilder MIB = BuildMI(*MBB, MI, DL, TII->get(VE::STrii));
1974   addFrameReference(MIB, FI, Offset); // jmpbuf[1]
1975   MIB.addReg(LabelReg, getKillRegState(true));
1976 }
1977 
1978 MachineBasicBlock *
1979 VETargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
1980                                    MachineBasicBlock *MBB) const {
1981   DebugLoc DL = MI.getDebugLoc();
1982   MachineFunction *MF = MBB->getParent();
1983   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1984   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
1985   MachineRegisterInfo &MRI = MF->getRegInfo();
1986 
1987   const BasicBlock *BB = MBB->getBasicBlock();
1988   MachineFunction::iterator I = ++MBB->getIterator();
1989 
1990   // Memory Reference.
1991   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
1992                                            MI.memoperands_end());
1993   Register BufReg = MI.getOperand(1).getReg();
1994 
1995   Register DstReg;
1996 
1997   DstReg = MI.getOperand(0).getReg();
1998   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
1999   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
2000   (void)TRI;
2001   Register MainDestReg = MRI.createVirtualRegister(RC);
2002   Register RestoreDestReg = MRI.createVirtualRegister(RC);
2003 
2004   // For `v = call @llvm.eh.sjlj.setjmp(buf)`, we generate following
2005   // instructions.  SP/FP must be saved in jmpbuf before `llvm.eh.sjlj.setjmp`.
2006   //
2007   // ThisMBB:
2008   //   buf[3] = %s17 iff %s17 is used as BP
2009   //   buf[1] = RestoreMBB as IC after longjmp
2010   //   # SjLjSetup RestoreMBB
2011   //
2012   // MainMBB:
2013   //   v_main = 0
2014   //
2015   // SinkMBB:
2016   //   v = phi(v_main, MainMBB, v_restore, RestoreMBB)
2017   //   ...
2018   //
2019   // RestoreMBB:
2020   //   %s17 = buf[3] = iff %s17 is used as BP
2021   //   v_restore = 1
2022   //   goto SinkMBB
2023 
2024   MachineBasicBlock *ThisMBB = MBB;
2025   MachineBasicBlock *MainMBB = MF->CreateMachineBasicBlock(BB);
2026   MachineBasicBlock *SinkMBB = MF->CreateMachineBasicBlock(BB);
2027   MachineBasicBlock *RestoreMBB = MF->CreateMachineBasicBlock(BB);
2028   MF->insert(I, MainMBB);
2029   MF->insert(I, SinkMBB);
2030   MF->push_back(RestoreMBB);
2031   RestoreMBB->setHasAddressTaken();
2032 
2033   // Transfer the remainder of BB and its successor edges to SinkMBB.
2034   SinkMBB->splice(SinkMBB->begin(), MBB,
2035                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
2036   SinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
2037 
2038   // ThisMBB:
2039   Register LabelReg =
2040       prepareMBB(*MBB, MachineBasicBlock::iterator(MI), RestoreMBB, DL);
2041 
2042   // Store BP in buf[3] iff this function is using BP.
2043   const VEFrameLowering *TFI = Subtarget->getFrameLowering();
2044   if (TFI->hasBP(*MF)) {
2045     MachineInstrBuilder MIB = BuildMI(*MBB, MI, DL, TII->get(VE::STrii));
2046     MIB.addReg(BufReg);
2047     MIB.addImm(0);
2048     MIB.addImm(24);
2049     MIB.addReg(VE::SX17);
2050     MIB.setMemRefs(MMOs);
2051   }
2052 
2053   // Store IP in buf[1].
2054   MachineInstrBuilder MIB = BuildMI(*MBB, MI, DL, TII->get(VE::STrii));
2055   MIB.add(MI.getOperand(1)); // we can preserve the kill flags here.
2056   MIB.addImm(0);
2057   MIB.addImm(8);
2058   MIB.addReg(LabelReg, getKillRegState(true));
2059   MIB.setMemRefs(MMOs);
2060 
2061   // SP/FP are already stored in jmpbuf before `llvm.eh.sjlj.setjmp`.
2062 
2063   // Insert setup.
2064   MIB =
2065       BuildMI(*ThisMBB, MI, DL, TII->get(VE::EH_SjLj_Setup)).addMBB(RestoreMBB);
2066 
2067   const VERegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2068   MIB.addRegMask(RegInfo->getNoPreservedMask());
2069   ThisMBB->addSuccessor(MainMBB);
2070   ThisMBB->addSuccessor(RestoreMBB);
2071 
2072   // MainMBB:
2073   BuildMI(MainMBB, DL, TII->get(VE::LEAzii), MainDestReg)
2074       .addImm(0)
2075       .addImm(0)
2076       .addImm(0);
2077   MainMBB->addSuccessor(SinkMBB);
2078 
2079   // SinkMBB:
2080   BuildMI(*SinkMBB, SinkMBB->begin(), DL, TII->get(VE::PHI), DstReg)
2081       .addReg(MainDestReg)
2082       .addMBB(MainMBB)
2083       .addReg(RestoreDestReg)
2084       .addMBB(RestoreMBB);
2085 
2086   // RestoreMBB:
2087   // Restore BP from buf[3] iff this function is using BP.  The address of
2088   // buf is in SX10.
2089   // FIXME: Better to not use SX10 here
2090   if (TFI->hasBP(*MF)) {
2091     MachineInstrBuilder MIB =
2092         BuildMI(RestoreMBB, DL, TII->get(VE::LDrii), VE::SX17);
2093     MIB.addReg(VE::SX10);
2094     MIB.addImm(0);
2095     MIB.addImm(24);
2096     MIB.setMemRefs(MMOs);
2097   }
2098   BuildMI(RestoreMBB, DL, TII->get(VE::LEAzii), RestoreDestReg)
2099       .addImm(0)
2100       .addImm(0)
2101       .addImm(1);
2102   BuildMI(RestoreMBB, DL, TII->get(VE::BRCFLa_t)).addMBB(SinkMBB);
2103   RestoreMBB->addSuccessor(SinkMBB);
2104 
2105   MI.eraseFromParent();
2106   return SinkMBB;
2107 }
2108 
2109 MachineBasicBlock *
2110 VETargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
2111                                     MachineBasicBlock *MBB) const {
2112   DebugLoc DL = MI.getDebugLoc();
2113   MachineFunction *MF = MBB->getParent();
2114   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2115   MachineRegisterInfo &MRI = MF->getRegInfo();
2116 
2117   // Memory Reference.
2118   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
2119                                            MI.memoperands_end());
2120   Register BufReg = MI.getOperand(0).getReg();
2121 
2122   Register Tmp = MRI.createVirtualRegister(&VE::I64RegClass);
2123   // Since FP is only updated here but NOT referenced, it's treated as GPR.
2124   Register FP = VE::SX9;
2125   Register SP = VE::SX11;
2126 
2127   MachineInstrBuilder MIB;
2128 
2129   MachineBasicBlock *ThisMBB = MBB;
2130 
2131   // For `call @llvm.eh.sjlj.longjmp(buf)`, we generate following instructions.
2132   //
2133   // ThisMBB:
2134   //   %fp = load buf[0]
2135   //   %jmp = load buf[1]
2136   //   %s10 = buf        ; Store an address of buf to SX10 for RestoreMBB
2137   //   %sp = load buf[2] ; generated by llvm.eh.sjlj.setjmp.
2138   //   jmp %jmp
2139 
2140   // Reload FP.
2141   MIB = BuildMI(*ThisMBB, MI, DL, TII->get(VE::LDrii), FP);
2142   MIB.addReg(BufReg);
2143   MIB.addImm(0);
2144   MIB.addImm(0);
2145   MIB.setMemRefs(MMOs);
2146 
2147   // Reload IP.
2148   MIB = BuildMI(*ThisMBB, MI, DL, TII->get(VE::LDrii), Tmp);
2149   MIB.addReg(BufReg);
2150   MIB.addImm(0);
2151   MIB.addImm(8);
2152   MIB.setMemRefs(MMOs);
2153 
2154   // Copy BufReg to SX10 for later use in setjmp.
2155   // FIXME: Better to not use SX10 here
2156   BuildMI(*ThisMBB, MI, DL, TII->get(VE::ORri), VE::SX10)
2157       .addReg(BufReg)
2158       .addImm(0);
2159 
2160   // Reload SP.
2161   MIB = BuildMI(*ThisMBB, MI, DL, TII->get(VE::LDrii), SP);
2162   MIB.add(MI.getOperand(0)); // we can preserve the kill flags here.
2163   MIB.addImm(0);
2164   MIB.addImm(16);
2165   MIB.setMemRefs(MMOs);
2166 
2167   // Jump.
2168   BuildMI(*ThisMBB, MI, DL, TII->get(VE::BCFLari_t))
2169       .addReg(Tmp, getKillRegState(true))
2170       .addImm(0);
2171 
2172   MI.eraseFromParent();
2173   return ThisMBB;
2174 }
2175 
2176 MachineBasicBlock *
2177 VETargetLowering::emitSjLjDispatchBlock(MachineInstr &MI,
2178                                         MachineBasicBlock *BB) const {
2179   DebugLoc DL = MI.getDebugLoc();
2180   MachineFunction *MF = BB->getParent();
2181   MachineFrameInfo &MFI = MF->getFrameInfo();
2182   MachineRegisterInfo &MRI = MF->getRegInfo();
2183   const VEInstrInfo *TII = Subtarget->getInstrInfo();
2184   int FI = MFI.getFunctionContextIndex();
2185 
2186   // Get a mapping of the call site numbers to all of the landing pads they're
2187   // associated with.
2188   DenseMap<unsigned, SmallVector<MachineBasicBlock *, 2>> CallSiteNumToLPad;
2189   unsigned MaxCSNum = 0;
2190   for (auto &MBB : *MF) {
2191     if (!MBB.isEHPad())
2192       continue;
2193 
2194     MCSymbol *Sym = nullptr;
2195     for (const auto &MI : MBB) {
2196       if (MI.isDebugInstr())
2197         continue;
2198 
2199       assert(MI.isEHLabel() && "expected EH_LABEL");
2200       Sym = MI.getOperand(0).getMCSymbol();
2201       break;
2202     }
2203 
2204     if (!MF->hasCallSiteLandingPad(Sym))
2205       continue;
2206 
2207     for (unsigned CSI : MF->getCallSiteLandingPad(Sym)) {
2208       CallSiteNumToLPad[CSI].push_back(&MBB);
2209       MaxCSNum = std::max(MaxCSNum, CSI);
2210     }
2211   }
2212 
2213   // Get an ordered list of the machine basic blocks for the jump table.
2214   std::vector<MachineBasicBlock *> LPadList;
2215   SmallPtrSet<MachineBasicBlock *, 32> InvokeBBs;
2216   LPadList.reserve(CallSiteNumToLPad.size());
2217 
2218   for (unsigned CSI = 1; CSI <= MaxCSNum; ++CSI) {
2219     for (auto &LP : CallSiteNumToLPad[CSI]) {
2220       LPadList.push_back(LP);
2221       InvokeBBs.insert(LP->pred_begin(), LP->pred_end());
2222     }
2223   }
2224 
2225   assert(!LPadList.empty() &&
2226          "No landing pad destinations for the dispatch jump table!");
2227 
2228   // The %fn_context is allocated like below (from --print-after=sjljehprepare):
2229   //   %fn_context = alloca { i8*, i64, [4 x i64], i8*, i8*, [5 x i8*] }
2230   //
2231   // This `[5 x i8*]` is jmpbuf, so jmpbuf[1] is FI+72.
2232   // First `i64` is callsite, so callsite is FI+8.
2233   static const int OffsetIC = 72;
2234   static const int OffsetCS = 8;
2235 
2236   // Create the MBBs for the dispatch code like following:
2237   //
2238   // ThisMBB:
2239   //   Prepare DispatchBB address and store it to buf[1].
2240   //   ...
2241   //
2242   // DispatchBB:
2243   //   %s15 = GETGOT iff isPositionIndependent
2244   //   %callsite = load callsite
2245   //   brgt.l.t #size of callsites, %callsite, DispContBB
2246   //
2247   // TrapBB:
2248   //   Call abort.
2249   //
2250   // DispContBB:
2251   //   %breg = address of jump table
2252   //   %pc = load and calculate next pc from %breg and %callsite
2253   //   jmp %pc
2254 
2255   // Shove the dispatch's address into the return slot in the function context.
2256   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
2257   DispatchBB->setIsEHPad(true);
2258 
2259   // Trap BB will causes trap like `assert(0)`.
2260   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
2261   DispatchBB->addSuccessor(TrapBB);
2262 
2263   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
2264   DispatchBB->addSuccessor(DispContBB);
2265 
2266   // Insert MBBs.
2267   MF->push_back(DispatchBB);
2268   MF->push_back(DispContBB);
2269   MF->push_back(TrapBB);
2270 
2271   // Insert code to call abort in the TrapBB.
2272   Register Abort = prepareSymbol(*TrapBB, TrapBB->end(), "abort", DL,
2273                                  /* Local */ false, /* Call */ true);
2274   BuildMI(TrapBB, DL, TII->get(VE::BSICrii), VE::SX10)
2275       .addReg(Abort, getKillRegState(true))
2276       .addImm(0)
2277       .addImm(0);
2278 
2279   // Insert code into the entry block that creates and registers the function
2280   // context.
2281   setupEntryBlockForSjLj(MI, BB, DispatchBB, FI, OffsetIC);
2282 
2283   // Create the jump table and associated information
2284   unsigned JTE = getJumpTableEncoding();
2285   MachineJumpTableInfo *JTI = MF->getOrCreateJumpTableInfo(JTE);
2286   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
2287 
2288   const VERegisterInfo &RI = TII->getRegisterInfo();
2289   // Add a register mask with no preserved registers.  This results in all
2290   // registers being marked as clobbered.
2291   BuildMI(DispatchBB, DL, TII->get(VE::NOP))
2292       .addRegMask(RI.getNoPreservedMask());
2293 
2294   if (isPositionIndependent()) {
2295     // Force to generate GETGOT, since current implementation doesn't store GOT
2296     // register.
2297     BuildMI(DispatchBB, DL, TII->get(VE::GETGOT), VE::SX15);
2298   }
2299 
2300   // IReg is used as an index in a memory operand and therefore can't be SP
2301   const TargetRegisterClass *RC = &VE::I64RegClass;
2302   Register IReg = MRI.createVirtualRegister(RC);
2303   addFrameReference(BuildMI(DispatchBB, DL, TII->get(VE::LDLZXrii), IReg), FI,
2304                     OffsetCS);
2305   if (LPadList.size() < 64) {
2306     BuildMI(DispatchBB, DL, TII->get(VE::BRCFLir_t))
2307         .addImm(VECC::CC_ILE)
2308         .addImm(LPadList.size())
2309         .addReg(IReg)
2310         .addMBB(TrapBB);
2311   } else {
2312     assert(LPadList.size() <= 0x7FFFFFFF && "Too large Landing Pad!");
2313     Register TmpReg = MRI.createVirtualRegister(RC);
2314     BuildMI(DispatchBB, DL, TII->get(VE::LEAzii), TmpReg)
2315         .addImm(0)
2316         .addImm(0)
2317         .addImm(LPadList.size());
2318     BuildMI(DispatchBB, DL, TII->get(VE::BRCFLrr_t))
2319         .addImm(VECC::CC_ILE)
2320         .addReg(TmpReg, getKillRegState(true))
2321         .addReg(IReg)
2322         .addMBB(TrapBB);
2323   }
2324 
2325   Register BReg = MRI.createVirtualRegister(RC);
2326   Register Tmp1 = MRI.createVirtualRegister(RC);
2327   Register Tmp2 = MRI.createVirtualRegister(RC);
2328 
2329   if (isPositionIndependent()) {
2330     // Create following instructions for local linkage PIC code.
2331     //     lea    %Tmp1, .LJTI0_0@gotoff_lo
2332     //     and    %Tmp2, %Tmp1, (32)0
2333     //     lea.sl %BReg, .LJTI0_0@gotoff_hi(%Tmp2, %s15) ; %s15 is GOT
2334     BuildMI(DispContBB, DL, TII->get(VE::LEAzii), Tmp1)
2335         .addImm(0)
2336         .addImm(0)
2337         .addJumpTableIndex(MJTI, VEMCExpr::VK_VE_GOTOFF_LO32);
2338     BuildMI(DispContBB, DL, TII->get(VE::ANDrm), Tmp2)
2339         .addReg(Tmp1, getKillRegState(true))
2340         .addImm(M0(32));
2341     BuildMI(DispContBB, DL, TII->get(VE::LEASLrri), BReg)
2342         .addReg(VE::SX15)
2343         .addReg(Tmp2, getKillRegState(true))
2344         .addJumpTableIndex(MJTI, VEMCExpr::VK_VE_GOTOFF_HI32);
2345   } else {
2346     // Create following instructions for non-PIC code.
2347     //     lea     %Tmp1, .LJTI0_0@lo
2348     //     and     %Tmp2, %Tmp1, (32)0
2349     //     lea.sl  %BReg, .LJTI0_0@hi(%Tmp2)
2350     BuildMI(DispContBB, DL, TII->get(VE::LEAzii), Tmp1)
2351         .addImm(0)
2352         .addImm(0)
2353         .addJumpTableIndex(MJTI, VEMCExpr::VK_VE_LO32);
2354     BuildMI(DispContBB, DL, TII->get(VE::ANDrm), Tmp2)
2355         .addReg(Tmp1, getKillRegState(true))
2356         .addImm(M0(32));
2357     BuildMI(DispContBB, DL, TII->get(VE::LEASLrii), BReg)
2358         .addReg(Tmp2, getKillRegState(true))
2359         .addImm(0)
2360         .addJumpTableIndex(MJTI, VEMCExpr::VK_VE_HI32);
2361   }
2362 
2363   switch (JTE) {
2364   case MachineJumpTableInfo::EK_BlockAddress: {
2365     // Generate simple block address code for no-PIC model.
2366     //     sll %Tmp1, %IReg, 3
2367     //     lds %TReg, 0(%Tmp1, %BReg)
2368     //     bcfla %TReg
2369 
2370     Register TReg = MRI.createVirtualRegister(RC);
2371     Register Tmp1 = MRI.createVirtualRegister(RC);
2372 
2373     BuildMI(DispContBB, DL, TII->get(VE::SLLri), Tmp1)
2374         .addReg(IReg, getKillRegState(true))
2375         .addImm(3);
2376     BuildMI(DispContBB, DL, TII->get(VE::LDrri), TReg)
2377         .addReg(BReg, getKillRegState(true))
2378         .addReg(Tmp1, getKillRegState(true))
2379         .addImm(0);
2380     BuildMI(DispContBB, DL, TII->get(VE::BCFLari_t))
2381         .addReg(TReg, getKillRegState(true))
2382         .addImm(0);
2383     break;
2384   }
2385   case MachineJumpTableInfo::EK_Custom32: {
2386     // Generate block address code using differences from the function pointer
2387     // for PIC model.
2388     //     sll %Tmp1, %IReg, 2
2389     //     ldl.zx %OReg, 0(%Tmp1, %BReg)
2390     //     Prepare function address in BReg2.
2391     //     adds.l %TReg, %BReg2, %OReg
2392     //     bcfla %TReg
2393 
2394     assert(isPositionIndependent());
2395     Register OReg = MRI.createVirtualRegister(RC);
2396     Register TReg = MRI.createVirtualRegister(RC);
2397     Register Tmp1 = MRI.createVirtualRegister(RC);
2398 
2399     BuildMI(DispContBB, DL, TII->get(VE::SLLri), Tmp1)
2400         .addReg(IReg, getKillRegState(true))
2401         .addImm(2);
2402     BuildMI(DispContBB, DL, TII->get(VE::LDLZXrri), OReg)
2403         .addReg(BReg, getKillRegState(true))
2404         .addReg(Tmp1, getKillRegState(true))
2405         .addImm(0);
2406     Register BReg2 =
2407         prepareSymbol(*DispContBB, DispContBB->end(),
2408                       DispContBB->getParent()->getName(), DL, /* Local */ true);
2409     BuildMI(DispContBB, DL, TII->get(VE::ADDSLrr), TReg)
2410         .addReg(OReg, getKillRegState(true))
2411         .addReg(BReg2, getKillRegState(true));
2412     BuildMI(DispContBB, DL, TII->get(VE::BCFLari_t))
2413         .addReg(TReg, getKillRegState(true))
2414         .addImm(0);
2415     break;
2416   }
2417   default:
2418     llvm_unreachable("Unexpected jump table encoding");
2419   }
2420 
2421   // Add the jump table entries as successors to the MBB.
2422   SmallPtrSet<MachineBasicBlock *, 8> SeenMBBs;
2423   for (auto &LP : LPadList)
2424     if (SeenMBBs.insert(LP).second)
2425       DispContBB->addSuccessor(LP);
2426 
2427   // N.B. the order the invoke BBs are processed in doesn't matter here.
2428   SmallVector<MachineBasicBlock *, 64> MBBLPads;
2429   const MCPhysReg *SavedRegs = MF->getRegInfo().getCalleeSavedRegs();
2430   for (MachineBasicBlock *MBB : InvokeBBs) {
2431     // Remove the landing pad successor from the invoke block and replace it
2432     // with the new dispatch block.
2433     // Keep a copy of Successors since it's modified inside the loop.
2434     SmallVector<MachineBasicBlock *, 8> Successors(MBB->succ_rbegin(),
2435                                                    MBB->succ_rend());
2436     // FIXME: Avoid quadratic complexity.
2437     for (auto MBBS : Successors) {
2438       if (MBBS->isEHPad()) {
2439         MBB->removeSuccessor(MBBS);
2440         MBBLPads.push_back(MBBS);
2441       }
2442     }
2443 
2444     MBB->addSuccessor(DispatchBB);
2445 
2446     // Find the invoke call and mark all of the callee-saved registers as
2447     // 'implicit defined' so that they're spilled.  This prevents code from
2448     // moving instructions to before the EH block, where they will never be
2449     // executed.
2450     for (auto &II : reverse(*MBB)) {
2451       if (!II.isCall())
2452         continue;
2453 
2454       DenseMap<Register, bool> DefRegs;
2455       for (auto &MOp : II.operands())
2456         if (MOp.isReg())
2457           DefRegs[MOp.getReg()] = true;
2458 
2459       MachineInstrBuilder MIB(*MF, &II);
2460       for (unsigned RI = 0; SavedRegs[RI]; ++RI) {
2461         Register Reg = SavedRegs[RI];
2462         if (!DefRegs[Reg])
2463           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
2464       }
2465 
2466       break;
2467     }
2468   }
2469 
2470   // Mark all former landing pads as non-landing pads.  The dispatch is the only
2471   // landing pad now.
2472   for (auto &LP : MBBLPads)
2473     LP->setIsEHPad(false);
2474 
2475   // The instruction is gone now.
2476   MI.eraseFromParent();
2477   return BB;
2478 }
2479 
2480 MachineBasicBlock *
2481 VETargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
2482                                               MachineBasicBlock *BB) const {
2483   switch (MI.getOpcode()) {
2484   default:
2485     llvm_unreachable("Unknown Custom Instruction!");
2486   case VE::EH_SjLj_LongJmp:
2487     return emitEHSjLjLongJmp(MI, BB);
2488   case VE::EH_SjLj_SetJmp:
2489     return emitEHSjLjSetJmp(MI, BB);
2490   case VE::EH_SjLj_Setup_Dispatch:
2491     return emitSjLjDispatchBlock(MI, BB);
2492   }
2493 }
2494 
2495 static bool isI32Insn(const SDNode *User, const SDNode *N) {
2496   switch (User->getOpcode()) {
2497   default:
2498     return false;
2499   case ISD::ADD:
2500   case ISD::SUB:
2501   case ISD::MUL:
2502   case ISD::SDIV:
2503   case ISD::UDIV:
2504   case ISD::SETCC:
2505   case ISD::SMIN:
2506   case ISD::SMAX:
2507   case ISD::SHL:
2508   case ISD::SRA:
2509   case ISD::BSWAP:
2510   case ISD::SINT_TO_FP:
2511   case ISD::UINT_TO_FP:
2512   case ISD::BR_CC:
2513   case ISD::BITCAST:
2514   case ISD::ATOMIC_CMP_SWAP:
2515   case ISD::ATOMIC_SWAP:
2516     return true;
2517   case ISD::SRL:
2518     if (N->getOperand(0).getOpcode() != ISD::SRL)
2519       return true;
2520     // (srl (trunc (srl ...))) may be optimized by combining srl, so
2521     // doesn't optimize trunc now.
2522     return false;
2523   case ISD::SELECT_CC:
2524     if (User->getOperand(2).getNode() != N &&
2525         User->getOperand(3).getNode() != N)
2526       return true;
2527     LLVM_FALLTHROUGH;
2528   case ISD::AND:
2529   case ISD::OR:
2530   case ISD::XOR:
2531   case ISD::SELECT:
2532   case ISD::CopyToReg:
2533     // Check all use of selections, bit operations, and copies.  If all of them
2534     // are safe, optimize truncate to extract_subreg.
2535     for (const SDNode *U : User->uses()) {
2536       switch (U->getOpcode()) {
2537       default:
2538         // If the use is an instruction which treats the source operand as i32,
2539         // it is safe to avoid truncate here.
2540         if (isI32Insn(U, N))
2541           continue;
2542         break;
2543       case ISD::ANY_EXTEND:
2544       case ISD::SIGN_EXTEND:
2545       case ISD::ZERO_EXTEND: {
2546         // Special optimizations to the combination of ext and trunc.
2547         // (ext ... (select ... (trunc ...))) is safe to avoid truncate here
2548         // since this truncate instruction clears higher 32 bits which is filled
2549         // by one of ext instructions later.
2550         assert(N->getValueType(0) == MVT::i32 &&
2551                "find truncate to not i32 integer");
2552         if (User->getOpcode() == ISD::SELECT_CC ||
2553             User->getOpcode() == ISD::SELECT)
2554           continue;
2555         break;
2556       }
2557       }
2558       return false;
2559     }
2560     return true;
2561   }
2562 }
2563 
2564 // Optimize TRUNCATE in DAG combining.  Optimizing it in CUSTOM lower is
2565 // sometime too early.  Optimizing it in DAG pattern matching in VEInstrInfo.td
2566 // is sometime too late.  So, doing it at here.
2567 SDValue VETargetLowering::combineTRUNCATE(SDNode *N,
2568                                           DAGCombinerInfo &DCI) const {
2569   assert(N->getOpcode() == ISD::TRUNCATE &&
2570          "Should be called with a TRUNCATE node");
2571 
2572   SelectionDAG &DAG = DCI.DAG;
2573   SDLoc DL(N);
2574   EVT VT = N->getValueType(0);
2575 
2576   // We prefer to do this when all types are legal.
2577   if (!DCI.isAfterLegalizeDAG())
2578     return SDValue();
2579 
2580   // Skip combine TRUNCATE atm if the operand of TRUNCATE might be a constant.
2581   if (N->getOperand(0)->getOpcode() == ISD::SELECT_CC &&
2582       isa<ConstantSDNode>(N->getOperand(0)->getOperand(0)) &&
2583       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
2584     return SDValue();
2585 
2586   // Check all use of this TRUNCATE.
2587   for (const SDNode *User : N->uses()) {
2588     // Make sure that we're not going to replace TRUNCATE for non i32
2589     // instructions.
2590     //
2591     // FIXME: Although we could sometimes handle this, and it does occur in
2592     // practice that one of the condition inputs to the select is also one of
2593     // the outputs, we currently can't deal with this.
2594     if (isI32Insn(User, N))
2595       continue;
2596 
2597     return SDValue();
2598   }
2599 
2600   SDValue SubI32 = DAG.getTargetConstant(VE::sub_i32, DL, MVT::i32);
2601   return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, VT,
2602                                     N->getOperand(0), SubI32),
2603                  0);
2604 }
2605 
2606 SDValue VETargetLowering::PerformDAGCombine(SDNode *N,
2607                                             DAGCombinerInfo &DCI) const {
2608   switch (N->getOpcode()) {
2609   default:
2610     break;
2611   case ISD::TRUNCATE:
2612     return combineTRUNCATE(N, DCI);
2613   }
2614 
2615   return SDValue();
2616 }
2617 
2618 //===----------------------------------------------------------------------===//
2619 // VE Inline Assembly Support
2620 //===----------------------------------------------------------------------===//
2621 
2622 VETargetLowering::ConstraintType
2623 VETargetLowering::getConstraintType(StringRef Constraint) const {
2624   if (Constraint.size() == 1) {
2625     switch (Constraint[0]) {
2626     default:
2627       break;
2628     case 'v': // vector registers
2629       return C_RegisterClass;
2630     }
2631   }
2632   return TargetLowering::getConstraintType(Constraint);
2633 }
2634 
2635 std::pair<unsigned, const TargetRegisterClass *>
2636 VETargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
2637                                                StringRef Constraint,
2638                                                MVT VT) const {
2639   const TargetRegisterClass *RC = nullptr;
2640   if (Constraint.size() == 1) {
2641     switch (Constraint[0]) {
2642     default:
2643       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
2644     case 'r':
2645       RC = &VE::I64RegClass;
2646       break;
2647     case 'v':
2648       RC = &VE::V64RegClass;
2649       break;
2650     }
2651     return std::make_pair(0U, RC);
2652   }
2653 
2654   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
2655 }
2656 
2657 //===----------------------------------------------------------------------===//
2658 // VE Target Optimization Support
2659 //===----------------------------------------------------------------------===//
2660 
2661 unsigned VETargetLowering::getMinimumJumpTableEntries() const {
2662   // Specify 8 for PIC model to relieve the impact of PIC load instructions.
2663   if (isJumpTableRelative())
2664     return 8;
2665 
2666   return TargetLowering::getMinimumJumpTableEntries();
2667 }
2668 
2669 bool VETargetLowering::hasAndNot(SDValue Y) const {
2670   EVT VT = Y.getValueType();
2671 
2672   // VE doesn't have vector and not instruction.
2673   if (VT.isVector())
2674     return false;
2675 
2676   // VE allows different immediate values for X and Y where ~X & Y.
2677   // Only simm7 works for X, and only mimm works for Y on VE.  However, this
2678   // function is used to check whether an immediate value is OK for and-not
2679   // instruction as both X and Y.  Generating additional instruction to
2680   // retrieve an immediate value is no good since the purpose of this
2681   // function is to convert a series of 3 instructions to another series of
2682   // 3 instructions with better parallelism.  Therefore, we return false
2683   // for all immediate values now.
2684   // FIXME: Change hasAndNot function to have two operands to make it work
2685   //        correctly with Aurora VE.
2686   if (isa<ConstantSDNode>(Y))
2687     return false;
2688 
2689   // It's ok for generic registers.
2690   return true;
2691 }
2692 
2693 SDValue VETargetLowering::lowerToVVP(SDValue Op, SelectionDAG &DAG) const {
2694   // Can we represent this as a VVP node.
2695   const unsigned Opcode = Op->getOpcode();
2696   auto VVPOpcodeOpt = getVVPOpcode(Opcode);
2697   if (!VVPOpcodeOpt.hasValue())
2698     return SDValue();
2699   unsigned VVPOpcode = VVPOpcodeOpt.getValue();
2700   const bool FromVP = ISD::isVPOpcode(Opcode);
2701 
2702   // The representative and legalized vector type of this operation.
2703   VECustomDAG CDAG(DAG, Op);
2704   EVT OpVecVT = Op.getValueType();
2705   EVT LegalVecVT = getTypeToTransformTo(*DAG.getContext(), OpVecVT);
2706   auto Packing = getTypePacking(LegalVecVT.getSimpleVT());
2707 
2708   SDValue AVL;
2709   SDValue Mask;
2710 
2711   if (FromVP) {
2712     // All upstream VP SDNodes always have a mask and avl.
2713     auto MaskIdx = ISD::getVPMaskIdx(Opcode);
2714     auto AVLIdx = ISD::getVPExplicitVectorLengthIdx(Opcode);
2715     if (MaskIdx)
2716       Mask = Op->getOperand(*MaskIdx);
2717     if (AVLIdx)
2718       AVL = Op->getOperand(*AVLIdx);
2719 
2720   }
2721 
2722   // Materialize default mask and avl.
2723   if (!AVL)
2724     AVL = CDAG.getConstant(OpVecVT.getVectorNumElements(), MVT::i32);
2725   if (!Mask)
2726     Mask = CDAG.getConstantMask(Packing, true);
2727 
2728   if (isVVPBinaryOp(VVPOpcode)) {
2729     assert(LegalVecVT.isSimple());
2730     return CDAG.getNode(VVPOpcode, LegalVecVT,
2731                         {Op->getOperand(0), Op->getOperand(1), Mask, AVL});
2732   }
2733   if (VVPOpcode == VEISD::VVP_SELECT) {
2734     auto Mask = Op->getOperand(0);
2735     auto OnTrue = Op->getOperand(1);
2736     auto OnFalse = Op->getOperand(2);
2737     return CDAG.getNode(VVPOpcode, LegalVecVT, {OnTrue, OnFalse, Mask, AVL});
2738   }
2739   if (VVPOpcode == VEISD::VVP_SETCC) {
2740     auto LHS = Op->getOperand(0);
2741     auto RHS = Op->getOperand(1);
2742     auto Pred = Op->getOperand(2);
2743     return CDAG.getNode(VVPOpcode, LegalVecVT, {LHS, RHS, Pred, Mask, AVL});
2744   }
2745   llvm_unreachable("lowerToVVP called for unexpected SDNode.");
2746 }
2747 
2748 SDValue VETargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
2749                                                   SelectionDAG &DAG) const {
2750   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
2751   MVT VT = Op.getOperand(0).getSimpleValueType();
2752 
2753   // Special treatment for packed V64 types.
2754   assert(VT == MVT::v512i32 || VT == MVT::v512f32);
2755   (void)VT;
2756   // Example of codes:
2757   //   %packed_v = extractelt %vr, %idx / 2
2758   //   %v = %packed_v >> (%idx % 2 * 32)
2759   //   %res = %v & 0xffffffff
2760 
2761   SDValue Vec = Op.getOperand(0);
2762   SDValue Idx = Op.getOperand(1);
2763   SDLoc DL(Op);
2764   SDValue Result = Op;
2765   if (false /* Idx->isConstant() */) {
2766     // TODO: optimized implementation using constant values
2767   } else {
2768     SDValue Const1 = DAG.getConstant(1, DL, MVT::i64);
2769     SDValue HalfIdx = DAG.getNode(ISD::SRL, DL, MVT::i64, {Idx, Const1});
2770     SDValue PackedElt =
2771         SDValue(DAG.getMachineNode(VE::LVSvr, DL, MVT::i64, {Vec, HalfIdx}), 0);
2772     SDValue AndIdx = DAG.getNode(ISD::AND, DL, MVT::i64, {Idx, Const1});
2773     SDValue Shift = DAG.getNode(ISD::XOR, DL, MVT::i64, {AndIdx, Const1});
2774     SDValue Const5 = DAG.getConstant(5, DL, MVT::i64);
2775     Shift = DAG.getNode(ISD::SHL, DL, MVT::i64, {Shift, Const5});
2776     PackedElt = DAG.getNode(ISD::SRL, DL, MVT::i64, {PackedElt, Shift});
2777     SDValue Mask = DAG.getConstant(0xFFFFFFFFL, DL, MVT::i64);
2778     PackedElt = DAG.getNode(ISD::AND, DL, MVT::i64, {PackedElt, Mask});
2779     SDValue SubI32 = DAG.getTargetConstant(VE::sub_i32, DL, MVT::i32);
2780     Result = SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
2781                                         MVT::i32, PackedElt, SubI32),
2782                      0);
2783 
2784     if (Op.getSimpleValueType() == MVT::f32) {
2785       Result = DAG.getBitcast(MVT::f32, Result);
2786     } else {
2787       assert(Op.getSimpleValueType() == MVT::i32);
2788     }
2789   }
2790   return Result;
2791 }
2792 
2793 SDValue VETargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
2794                                                  SelectionDAG &DAG) const {
2795   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
2796   MVT VT = Op.getOperand(0).getSimpleValueType();
2797 
2798   // Special treatment for packed V64 types.
2799   assert(VT == MVT::v512i32 || VT == MVT::v512f32);
2800   (void)VT;
2801   // The v512i32 and v512f32 starts from upper bits (0..31).  This "upper
2802   // bits" required `val << 32` from C implementation's point of view.
2803   //
2804   // Example of codes:
2805   //   %packed_elt = extractelt %vr, (%idx >> 1)
2806   //   %shift = ((%idx & 1) ^ 1) << 5
2807   //   %packed_elt &= 0xffffffff00000000 >> shift
2808   //   %packed_elt |= (zext %val) << shift
2809   //   %vr = insertelt %vr, %packed_elt, (%idx >> 1)
2810 
2811   SDLoc DL(Op);
2812   SDValue Vec = Op.getOperand(0);
2813   SDValue Val = Op.getOperand(1);
2814   SDValue Idx = Op.getOperand(2);
2815   if (Idx.getSimpleValueType() == MVT::i32)
2816     Idx = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Idx);
2817   if (Val.getSimpleValueType() == MVT::f32)
2818     Val = DAG.getBitcast(MVT::i32, Val);
2819   assert(Val.getSimpleValueType() == MVT::i32);
2820   Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
2821 
2822   SDValue Result = Op;
2823   if (false /* Idx->isConstant()*/) {
2824     // TODO: optimized implementation using constant values
2825   } else {
2826     SDValue Const1 = DAG.getConstant(1, DL, MVT::i64);
2827     SDValue HalfIdx = DAG.getNode(ISD::SRL, DL, MVT::i64, {Idx, Const1});
2828     SDValue PackedElt =
2829         SDValue(DAG.getMachineNode(VE::LVSvr, DL, MVT::i64, {Vec, HalfIdx}), 0);
2830     SDValue AndIdx = DAG.getNode(ISD::AND, DL, MVT::i64, {Idx, Const1});
2831     SDValue Shift = DAG.getNode(ISD::XOR, DL, MVT::i64, {AndIdx, Const1});
2832     SDValue Const5 = DAG.getConstant(5, DL, MVT::i64);
2833     Shift = DAG.getNode(ISD::SHL, DL, MVT::i64, {Shift, Const5});
2834     SDValue Mask = DAG.getConstant(0xFFFFFFFF00000000L, DL, MVT::i64);
2835     Mask = DAG.getNode(ISD::SRL, DL, MVT::i64, {Mask, Shift});
2836     PackedElt = DAG.getNode(ISD::AND, DL, MVT::i64, {PackedElt, Mask});
2837     Val = DAG.getNode(ISD::SHL, DL, MVT::i64, {Val, Shift});
2838     PackedElt = DAG.getNode(ISD::OR, DL, MVT::i64, {PackedElt, Val});
2839     Result =
2840         SDValue(DAG.getMachineNode(VE::LSVrr_v, DL, Vec.getSimpleValueType(),
2841                                    {HalfIdx, PackedElt, Vec}),
2842                 0);
2843   }
2844   return Result;
2845 }
2846