1 //=- WebAssemblyISelLowering.cpp - WebAssembly 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 /// \file
10 /// This file implements the WebAssemblyTargetLowering class.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "WebAssemblyISelLowering.h"
15 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
16 #include "WebAssemblyMachineFunctionInfo.h"
17 #include "WebAssemblySubtarget.h"
18 #include "WebAssemblyTargetMachine.h"
19 #include "llvm/CodeGen/Analysis.h"
20 #include "llvm/CodeGen/CallingConvLower.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineJumpTableInfo.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/SelectionDAG.h"
26 #include "llvm/CodeGen/WasmEHFuncInfo.h"
27 #include "llvm/IR/DiagnosticInfo.h"
28 #include "llvm/IR/DiagnosticPrinter.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/Intrinsics.h"
31 #include "llvm/IR/IntrinsicsWebAssembly.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetOptions.h"
36 using namespace llvm;
37 
38 #define DEBUG_TYPE "wasm-lower"
39 
40 WebAssemblyTargetLowering::WebAssemblyTargetLowering(
41     const TargetMachine &TM, const WebAssemblySubtarget &STI)
42     : TargetLowering(TM), Subtarget(&STI) {
43   auto MVTPtr = Subtarget->hasAddr64() ? MVT::i64 : MVT::i32;
44 
45   // Booleans always contain 0 or 1.
46   setBooleanContents(ZeroOrOneBooleanContent);
47   // Except in SIMD vectors
48   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
49   // We don't know the microarchitecture here, so just reduce register pressure.
50   setSchedulingPreference(Sched::RegPressure);
51   // Tell ISel that we have a stack pointer.
52   setStackPointerRegisterToSaveRestore(
53       Subtarget->hasAddr64() ? WebAssembly::SP64 : WebAssembly::SP32);
54   // Set up the register classes.
55   addRegisterClass(MVT::i32, &WebAssembly::I32RegClass);
56   addRegisterClass(MVT::i64, &WebAssembly::I64RegClass);
57   addRegisterClass(MVT::f32, &WebAssembly::F32RegClass);
58   addRegisterClass(MVT::f64, &WebAssembly::F64RegClass);
59   if (Subtarget->hasSIMD128()) {
60     addRegisterClass(MVT::v16i8, &WebAssembly::V128RegClass);
61     addRegisterClass(MVT::v8i16, &WebAssembly::V128RegClass);
62     addRegisterClass(MVT::v4i32, &WebAssembly::V128RegClass);
63     addRegisterClass(MVT::v4f32, &WebAssembly::V128RegClass);
64     addRegisterClass(MVT::v2i64, &WebAssembly::V128RegClass);
65     addRegisterClass(MVT::v2f64, &WebAssembly::V128RegClass);
66   }
67   // Compute derived properties from the register classes.
68   computeRegisterProperties(Subtarget->getRegisterInfo());
69 
70   setOperationAction(ISD::GlobalAddress, MVTPtr, Custom);
71   setOperationAction(ISD::ExternalSymbol, MVTPtr, Custom);
72   setOperationAction(ISD::JumpTable, MVTPtr, Custom);
73   setOperationAction(ISD::BlockAddress, MVTPtr, Custom);
74   setOperationAction(ISD::BRIND, MVT::Other, Custom);
75 
76   // Take the default expansion for va_arg, va_copy, and va_end. There is no
77   // default action for va_start, so we do that custom.
78   setOperationAction(ISD::VASTART, MVT::Other, Custom);
79   setOperationAction(ISD::VAARG, MVT::Other, Expand);
80   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
81   setOperationAction(ISD::VAEND, MVT::Other, Expand);
82 
83   for (auto T : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
84     // Don't expand the floating-point types to constant pools.
85     setOperationAction(ISD::ConstantFP, T, Legal);
86     // Expand floating-point comparisons.
87     for (auto CC : {ISD::SETO, ISD::SETUO, ISD::SETUEQ, ISD::SETONE,
88                     ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE})
89       setCondCodeAction(CC, T, Expand);
90     // Expand floating-point library function operators.
91     for (auto Op :
92          {ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FREM, ISD::FMA})
93       setOperationAction(Op, T, Expand);
94     // Note supported floating-point library function operators that otherwise
95     // default to expand.
96     for (auto Op :
97          {ISD::FCEIL, ISD::FFLOOR, ISD::FTRUNC, ISD::FNEARBYINT, ISD::FRINT})
98       setOperationAction(Op, T, Legal);
99     // Support minimum and maximum, which otherwise default to expand.
100     setOperationAction(ISD::FMINIMUM, T, Legal);
101     setOperationAction(ISD::FMAXIMUM, T, Legal);
102     // WebAssembly currently has no builtin f16 support.
103     setOperationAction(ISD::FP16_TO_FP, T, Expand);
104     setOperationAction(ISD::FP_TO_FP16, T, Expand);
105     setLoadExtAction(ISD::EXTLOAD, T, MVT::f16, Expand);
106     setTruncStoreAction(T, MVT::f16, Expand);
107   }
108 
109   // Expand unavailable integer operations.
110   for (auto Op :
111        {ISD::BSWAP, ISD::SMUL_LOHI, ISD::UMUL_LOHI, ISD::MULHS, ISD::MULHU,
112         ISD::SDIVREM, ISD::UDIVREM, ISD::SHL_PARTS, ISD::SRA_PARTS,
113         ISD::SRL_PARTS, ISD::ADDC, ISD::ADDE, ISD::SUBC, ISD::SUBE}) {
114     for (auto T : {MVT::i32, MVT::i64})
115       setOperationAction(Op, T, Expand);
116     if (Subtarget->hasSIMD128())
117       for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64})
118         setOperationAction(Op, T, Expand);
119   }
120 
121   // SIMD-specific configuration
122   if (Subtarget->hasSIMD128()) {
123     // Hoist bitcasts out of shuffles
124     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
125 
126     // Support saturating add for i8x16 and i16x8
127     for (auto Op : {ISD::SADDSAT, ISD::UADDSAT})
128       for (auto T : {MVT::v16i8, MVT::v8i16})
129         setOperationAction(Op, T, Legal);
130 
131     // Support integer abs
132     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
133       setOperationAction(ISD::ABS, T, Legal);
134 
135     // Custom lower BUILD_VECTORs to minimize number of replace_lanes
136     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
137                    MVT::v2f64})
138       setOperationAction(ISD::BUILD_VECTOR, T, Custom);
139 
140     // We have custom shuffle lowering to expose the shuffle mask
141     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
142                    MVT::v2f64})
143       setOperationAction(ISD::VECTOR_SHUFFLE, T, Custom);
144 
145     // Custom lowering since wasm shifts must have a scalar shift amount
146     for (auto Op : {ISD::SHL, ISD::SRA, ISD::SRL})
147       for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64})
148         setOperationAction(Op, T, Custom);
149 
150     // Custom lower lane accesses to expand out variable indices
151     for (auto Op : {ISD::EXTRACT_VECTOR_ELT, ISD::INSERT_VECTOR_ELT})
152       for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
153                      MVT::v2f64})
154         setOperationAction(Op, T, Custom);
155 
156     // There is no i8x16.mul instruction
157     setOperationAction(ISD::MUL, MVT::v16i8, Expand);
158 
159     // There is no vector conditional select instruction
160     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
161                    MVT::v2f64})
162       setOperationAction(ISD::SELECT_CC, T, Expand);
163 
164     // Expand integer operations supported for scalars but not SIMD
165     for (auto Op : {ISD::CTLZ, ISD::CTTZ, ISD::CTPOP, ISD::SDIV, ISD::UDIV,
166                     ISD::SREM, ISD::UREM, ISD::ROTL, ISD::ROTR})
167       for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64})
168         setOperationAction(Op, T, Expand);
169 
170     // But we do have integer min and max operations
171     for (auto Op : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
172       for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
173         setOperationAction(Op, T, Legal);
174 
175     // Expand float operations supported for scalars but not SIMD
176     for (auto Op : {ISD::FCEIL, ISD::FFLOOR, ISD::FTRUNC, ISD::FNEARBYINT,
177                     ISD::FCOPYSIGN, ISD::FLOG, ISD::FLOG2, ISD::FLOG10,
178                     ISD::FEXP, ISD::FEXP2, ISD::FRINT})
179       for (auto T : {MVT::v4f32, MVT::v2f64})
180         setOperationAction(Op, T, Expand);
181 
182     // Expand operations not supported for i64x2 vectors
183     for (unsigned CC = 0; CC < ISD::SETCC_INVALID; ++CC)
184       setCondCodeAction(static_cast<ISD::CondCode>(CC), MVT::v2i64, Custom);
185 
186     // 64x2 conversions are not in the spec
187     for (auto Op :
188          {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT})
189       for (auto T : {MVT::v2i64, MVT::v2f64})
190         setOperationAction(Op, T, Expand);
191   }
192 
193   // As a special case, these operators use the type to mean the type to
194   // sign-extend from.
195   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
196   if (!Subtarget->hasSignExt()) {
197     // Sign extends are legal only when extending a vector extract
198     auto Action = Subtarget->hasSIMD128() ? Custom : Expand;
199     for (auto T : {MVT::i8, MVT::i16, MVT::i32})
200       setOperationAction(ISD::SIGN_EXTEND_INREG, T, Action);
201   }
202   for (auto T : MVT::integer_fixedlen_vector_valuetypes())
203     setOperationAction(ISD::SIGN_EXTEND_INREG, T, Expand);
204 
205   // Dynamic stack allocation: use the default expansion.
206   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
207   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
208   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVTPtr, Expand);
209 
210   setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
211   setOperationAction(ISD::FrameIndex, MVT::i64, Custom);
212   setOperationAction(ISD::CopyToReg, MVT::Other, Custom);
213 
214   // Expand these forms; we pattern-match the forms that we can handle in isel.
215   for (auto T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64})
216     for (auto Op : {ISD::BR_CC, ISD::SELECT_CC})
217       setOperationAction(Op, T, Expand);
218 
219   // We have custom switch handling.
220   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
221 
222   // WebAssembly doesn't have:
223   //  - Floating-point extending loads.
224   //  - Floating-point truncating stores.
225   //  - i1 extending loads.
226   //  - truncating SIMD stores and most extending loads
227   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
228   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
229   for (auto T : MVT::integer_valuetypes())
230     for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD})
231       setLoadExtAction(Ext, T, MVT::i1, Promote);
232   if (Subtarget->hasSIMD128()) {
233     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64, MVT::v4f32,
234                    MVT::v2f64}) {
235       for (auto MemT : MVT::fixedlen_vector_valuetypes()) {
236         if (MVT(T) != MemT) {
237           setTruncStoreAction(T, MemT, Expand);
238           for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD})
239             setLoadExtAction(Ext, T, MemT, Expand);
240         }
241       }
242     }
243     // But some vector extending loads are legal
244     for (auto Ext : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) {
245       setLoadExtAction(Ext, MVT::v8i16, MVT::v8i8, Legal);
246       setLoadExtAction(Ext, MVT::v4i32, MVT::v4i16, Legal);
247       setLoadExtAction(Ext, MVT::v2i64, MVT::v2i32, Legal);
248     }
249   }
250 
251   // Don't do anything clever with build_pairs
252   setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
253 
254   // Trap lowers to wasm unreachable
255   setOperationAction(ISD::TRAP, MVT::Other, Legal);
256   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
257 
258   // Exception handling intrinsics
259   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
260   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
261 
262   setMaxAtomicSizeInBitsSupported(64);
263 
264   // Override the __gnu_f2h_ieee/__gnu_h2f_ieee names so that the f32 name is
265   // consistent with the f64 and f128 names.
266   setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
267   setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
268 
269   // Define the emscripten name for return address helper.
270   // TODO: when implementing other WASM backends, make this generic or only do
271   // this on emscripten depending on what they end up doing.
272   setLibcallName(RTLIB::RETURN_ADDRESS, "emscripten_return_address");
273 
274   // Always convert switches to br_tables unless there is only one case, which
275   // is equivalent to a simple branch. This reduces code size for wasm, and we
276   // defer possible jump table optimizations to the VM.
277   setMinimumJumpTableEntries(2);
278 }
279 
280 TargetLowering::AtomicExpansionKind
281 WebAssemblyTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
282   // We have wasm instructions for these
283   switch (AI->getOperation()) {
284   case AtomicRMWInst::Add:
285   case AtomicRMWInst::Sub:
286   case AtomicRMWInst::And:
287   case AtomicRMWInst::Or:
288   case AtomicRMWInst::Xor:
289   case AtomicRMWInst::Xchg:
290     return AtomicExpansionKind::None;
291   default:
292     break;
293   }
294   return AtomicExpansionKind::CmpXChg;
295 }
296 
297 FastISel *WebAssemblyTargetLowering::createFastISel(
298     FunctionLoweringInfo &FuncInfo, const TargetLibraryInfo *LibInfo) const {
299   return WebAssembly::createFastISel(FuncInfo, LibInfo);
300 }
301 
302 MVT WebAssemblyTargetLowering::getScalarShiftAmountTy(const DataLayout & /*DL*/,
303                                                       EVT VT) const {
304   unsigned BitWidth = NextPowerOf2(VT.getSizeInBits() - 1);
305   if (BitWidth > 1 && BitWidth < 8)
306     BitWidth = 8;
307 
308   if (BitWidth > 64) {
309     // The shift will be lowered to a libcall, and compiler-rt libcalls expect
310     // the count to be an i32.
311     BitWidth = 32;
312     assert(BitWidth >= Log2_32_Ceil(VT.getSizeInBits()) &&
313            "32-bit shift counts ought to be enough for anyone");
314   }
315 
316   MVT Result = MVT::getIntegerVT(BitWidth);
317   assert(Result != MVT::INVALID_SIMPLE_VALUE_TYPE &&
318          "Unable to represent scalar shift amount type");
319   return Result;
320 }
321 
322 // Lower an fp-to-int conversion operator from the LLVM opcode, which has an
323 // undefined result on invalid/overflow, to the WebAssembly opcode, which
324 // traps on invalid/overflow.
325 static MachineBasicBlock *LowerFPToInt(MachineInstr &MI, DebugLoc DL,
326                                        MachineBasicBlock *BB,
327                                        const TargetInstrInfo &TII,
328                                        bool IsUnsigned, bool Int64,
329                                        bool Float64, unsigned LoweredOpcode) {
330   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
331 
332   Register OutReg = MI.getOperand(0).getReg();
333   Register InReg = MI.getOperand(1).getReg();
334 
335   unsigned Abs = Float64 ? WebAssembly::ABS_F64 : WebAssembly::ABS_F32;
336   unsigned FConst = Float64 ? WebAssembly::CONST_F64 : WebAssembly::CONST_F32;
337   unsigned LT = Float64 ? WebAssembly::LT_F64 : WebAssembly::LT_F32;
338   unsigned GE = Float64 ? WebAssembly::GE_F64 : WebAssembly::GE_F32;
339   unsigned IConst = Int64 ? WebAssembly::CONST_I64 : WebAssembly::CONST_I32;
340   unsigned Eqz = WebAssembly::EQZ_I32;
341   unsigned And = WebAssembly::AND_I32;
342   int64_t Limit = Int64 ? INT64_MIN : INT32_MIN;
343   int64_t Substitute = IsUnsigned ? 0 : Limit;
344   double CmpVal = IsUnsigned ? -(double)Limit * 2.0 : -(double)Limit;
345   auto &Context = BB->getParent()->getFunction().getContext();
346   Type *Ty = Float64 ? Type::getDoubleTy(Context) : Type::getFloatTy(Context);
347 
348   const BasicBlock *LLVMBB = BB->getBasicBlock();
349   MachineFunction *F = BB->getParent();
350   MachineBasicBlock *TrueMBB = F->CreateMachineBasicBlock(LLVMBB);
351   MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(LLVMBB);
352   MachineBasicBlock *DoneMBB = F->CreateMachineBasicBlock(LLVMBB);
353 
354   MachineFunction::iterator It = ++BB->getIterator();
355   F->insert(It, FalseMBB);
356   F->insert(It, TrueMBB);
357   F->insert(It, DoneMBB);
358 
359   // Transfer the remainder of BB and its successor edges to DoneMBB.
360   DoneMBB->splice(DoneMBB->begin(), BB, std::next(MI.getIterator()), BB->end());
361   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
362 
363   BB->addSuccessor(TrueMBB);
364   BB->addSuccessor(FalseMBB);
365   TrueMBB->addSuccessor(DoneMBB);
366   FalseMBB->addSuccessor(DoneMBB);
367 
368   unsigned Tmp0, Tmp1, CmpReg, EqzReg, FalseReg, TrueReg;
369   Tmp0 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
370   Tmp1 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
371   CmpReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
372   EqzReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
373   FalseReg = MRI.createVirtualRegister(MRI.getRegClass(OutReg));
374   TrueReg = MRI.createVirtualRegister(MRI.getRegClass(OutReg));
375 
376   MI.eraseFromParent();
377   // For signed numbers, we can do a single comparison to determine whether
378   // fabs(x) is within range.
379   if (IsUnsigned) {
380     Tmp0 = InReg;
381   } else {
382     BuildMI(BB, DL, TII.get(Abs), Tmp0).addReg(InReg);
383   }
384   BuildMI(BB, DL, TII.get(FConst), Tmp1)
385       .addFPImm(cast<ConstantFP>(ConstantFP::get(Ty, CmpVal)));
386   BuildMI(BB, DL, TII.get(LT), CmpReg).addReg(Tmp0).addReg(Tmp1);
387 
388   // For unsigned numbers, we have to do a separate comparison with zero.
389   if (IsUnsigned) {
390     Tmp1 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
391     Register SecondCmpReg =
392         MRI.createVirtualRegister(&WebAssembly::I32RegClass);
393     Register AndReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
394     BuildMI(BB, DL, TII.get(FConst), Tmp1)
395         .addFPImm(cast<ConstantFP>(ConstantFP::get(Ty, 0.0)));
396     BuildMI(BB, DL, TII.get(GE), SecondCmpReg).addReg(Tmp0).addReg(Tmp1);
397     BuildMI(BB, DL, TII.get(And), AndReg).addReg(CmpReg).addReg(SecondCmpReg);
398     CmpReg = AndReg;
399   }
400 
401   BuildMI(BB, DL, TII.get(Eqz), EqzReg).addReg(CmpReg);
402 
403   // Create the CFG diamond to select between doing the conversion or using
404   // the substitute value.
405   BuildMI(BB, DL, TII.get(WebAssembly::BR_IF)).addMBB(TrueMBB).addReg(EqzReg);
406   BuildMI(FalseMBB, DL, TII.get(LoweredOpcode), FalseReg).addReg(InReg);
407   BuildMI(FalseMBB, DL, TII.get(WebAssembly::BR)).addMBB(DoneMBB);
408   BuildMI(TrueMBB, DL, TII.get(IConst), TrueReg).addImm(Substitute);
409   BuildMI(*DoneMBB, DoneMBB->begin(), DL, TII.get(TargetOpcode::PHI), OutReg)
410       .addReg(FalseReg)
411       .addMBB(FalseMBB)
412       .addReg(TrueReg)
413       .addMBB(TrueMBB);
414 
415   return DoneMBB;
416 }
417 
418 static MachineBasicBlock *LowerCallResults(MachineInstr &CallResults,
419                                            DebugLoc DL, MachineBasicBlock *BB,
420                                            const TargetInstrInfo &TII) {
421   MachineInstr &CallParams = *CallResults.getPrevNode();
422   assert(CallParams.getOpcode() == WebAssembly::CALL_PARAMS);
423   assert(CallResults.getOpcode() == WebAssembly::CALL_RESULTS ||
424          CallResults.getOpcode() == WebAssembly::RET_CALL_RESULTS);
425 
426   bool IsIndirect = CallParams.getOperand(0).isReg();
427   bool IsRetCall = CallResults.getOpcode() == WebAssembly::RET_CALL_RESULTS;
428 
429   unsigned CallOp;
430   if (IsIndirect && IsRetCall) {
431     CallOp = WebAssembly::RET_CALL_INDIRECT;
432   } else if (IsIndirect) {
433     CallOp = WebAssembly::CALL_INDIRECT;
434   } else if (IsRetCall) {
435     CallOp = WebAssembly::RET_CALL;
436   } else {
437     CallOp = WebAssembly::CALL;
438   }
439 
440   MachineFunction &MF = *BB->getParent();
441   const MCInstrDesc &MCID = TII.get(CallOp);
442   MachineInstrBuilder MIB(MF, MF.CreateMachineInstr(MCID, DL));
443 
444   // See if we must truncate the function pointer.
445   // CALL_INDIRECT takes an i32, but in wasm64 we represent function pointers
446   // as 64-bit for uniformity with other pointer types.
447   if (IsIndirect && MF.getSubtarget<WebAssemblySubtarget>().hasAddr64()) {
448     Register Reg32 =
449         MF.getRegInfo().createVirtualRegister(&WebAssembly::I32RegClass);
450     auto &FnPtr = CallParams.getOperand(0);
451     BuildMI(*BB, CallResults.getIterator(), DL,
452             TII.get(WebAssembly::I32_WRAP_I64), Reg32)
453         .addReg(FnPtr.getReg());
454     FnPtr.setReg(Reg32);
455   }
456 
457   // Move the function pointer to the end of the arguments for indirect calls
458   if (IsIndirect) {
459     auto FnPtr = CallParams.getOperand(0);
460     CallParams.RemoveOperand(0);
461     CallParams.addOperand(FnPtr);
462   }
463 
464   for (auto Def : CallResults.defs())
465     MIB.add(Def);
466 
467   // Add placeholders for the type index and immediate flags
468   if (IsIndirect) {
469     MIB.addImm(0);
470     MIB.addImm(0);
471   }
472 
473   for (auto Use : CallParams.uses())
474     MIB.add(Use);
475 
476   BB->insert(CallResults.getIterator(), MIB);
477   CallParams.eraseFromParent();
478   CallResults.eraseFromParent();
479 
480   return BB;
481 }
482 
483 MachineBasicBlock *WebAssemblyTargetLowering::EmitInstrWithCustomInserter(
484     MachineInstr &MI, MachineBasicBlock *BB) const {
485   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
486   DebugLoc DL = MI.getDebugLoc();
487 
488   switch (MI.getOpcode()) {
489   default:
490     llvm_unreachable("Unexpected instr type to insert");
491   case WebAssembly::FP_TO_SINT_I32_F32:
492     return LowerFPToInt(MI, DL, BB, TII, false, false, false,
493                         WebAssembly::I32_TRUNC_S_F32);
494   case WebAssembly::FP_TO_UINT_I32_F32:
495     return LowerFPToInt(MI, DL, BB, TII, true, false, false,
496                         WebAssembly::I32_TRUNC_U_F32);
497   case WebAssembly::FP_TO_SINT_I64_F32:
498     return LowerFPToInt(MI, DL, BB, TII, false, true, false,
499                         WebAssembly::I64_TRUNC_S_F32);
500   case WebAssembly::FP_TO_UINT_I64_F32:
501     return LowerFPToInt(MI, DL, BB, TII, true, true, false,
502                         WebAssembly::I64_TRUNC_U_F32);
503   case WebAssembly::FP_TO_SINT_I32_F64:
504     return LowerFPToInt(MI, DL, BB, TII, false, false, true,
505                         WebAssembly::I32_TRUNC_S_F64);
506   case WebAssembly::FP_TO_UINT_I32_F64:
507     return LowerFPToInt(MI, DL, BB, TII, true, false, true,
508                         WebAssembly::I32_TRUNC_U_F64);
509   case WebAssembly::FP_TO_SINT_I64_F64:
510     return LowerFPToInt(MI, DL, BB, TII, false, true, true,
511                         WebAssembly::I64_TRUNC_S_F64);
512   case WebAssembly::FP_TO_UINT_I64_F64:
513     return LowerFPToInt(MI, DL, BB, TII, true, true, true,
514                         WebAssembly::I64_TRUNC_U_F64);
515   case WebAssembly::CALL_RESULTS:
516   case WebAssembly::RET_CALL_RESULTS:
517     return LowerCallResults(MI, DL, BB, TII);
518   }
519 }
520 
521 const char *
522 WebAssemblyTargetLowering::getTargetNodeName(unsigned Opcode) const {
523   switch (static_cast<WebAssemblyISD::NodeType>(Opcode)) {
524   case WebAssemblyISD::FIRST_NUMBER:
525   case WebAssemblyISD::FIRST_MEM_OPCODE:
526     break;
527 #define HANDLE_NODETYPE(NODE)                                                  \
528   case WebAssemblyISD::NODE:                                                   \
529     return "WebAssemblyISD::" #NODE;
530 #define HANDLE_MEM_NODETYPE(NODE) HANDLE_NODETYPE(NODE)
531 #include "WebAssemblyISD.def"
532 #undef HANDLE_MEM_NODETYPE
533 #undef HANDLE_NODETYPE
534   }
535   return nullptr;
536 }
537 
538 std::pair<unsigned, const TargetRegisterClass *>
539 WebAssemblyTargetLowering::getRegForInlineAsmConstraint(
540     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
541   // First, see if this is a constraint that directly corresponds to a
542   // WebAssembly register class.
543   if (Constraint.size() == 1) {
544     switch (Constraint[0]) {
545     case 'r':
546       assert(VT != MVT::iPTR && "Pointer MVT not expected here");
547       if (Subtarget->hasSIMD128() && VT.isVector()) {
548         if (VT.getSizeInBits() == 128)
549           return std::make_pair(0U, &WebAssembly::V128RegClass);
550       }
551       if (VT.isInteger() && !VT.isVector()) {
552         if (VT.getSizeInBits() <= 32)
553           return std::make_pair(0U, &WebAssembly::I32RegClass);
554         if (VT.getSizeInBits() <= 64)
555           return std::make_pair(0U, &WebAssembly::I64RegClass);
556       }
557       break;
558     default:
559       break;
560     }
561   }
562 
563   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
564 }
565 
566 bool WebAssemblyTargetLowering::isCheapToSpeculateCttz() const {
567   // Assume ctz is a relatively cheap operation.
568   return true;
569 }
570 
571 bool WebAssemblyTargetLowering::isCheapToSpeculateCtlz() const {
572   // Assume clz is a relatively cheap operation.
573   return true;
574 }
575 
576 bool WebAssemblyTargetLowering::isLegalAddressingMode(const DataLayout &DL,
577                                                       const AddrMode &AM,
578                                                       Type *Ty, unsigned AS,
579                                                       Instruction *I) const {
580   // WebAssembly offsets are added as unsigned without wrapping. The
581   // isLegalAddressingMode gives us no way to determine if wrapping could be
582   // happening, so we approximate this by accepting only non-negative offsets.
583   if (AM.BaseOffs < 0)
584     return false;
585 
586   // WebAssembly has no scale register operands.
587   if (AM.Scale != 0)
588     return false;
589 
590   // Everything else is legal.
591   return true;
592 }
593 
594 bool WebAssemblyTargetLowering::allowsMisalignedMemoryAccesses(
595     EVT /*VT*/, unsigned /*AddrSpace*/, unsigned /*Align*/,
596     MachineMemOperand::Flags /*Flags*/, bool *Fast) const {
597   // WebAssembly supports unaligned accesses, though it should be declared
598   // with the p2align attribute on loads and stores which do so, and there
599   // may be a performance impact. We tell LLVM they're "fast" because
600   // for the kinds of things that LLVM uses this for (merging adjacent stores
601   // of constants, etc.), WebAssembly implementations will either want the
602   // unaligned access or they'll split anyway.
603   if (Fast)
604     *Fast = true;
605   return true;
606 }
607 
608 bool WebAssemblyTargetLowering::isIntDivCheap(EVT VT,
609                                               AttributeList Attr) const {
610   // The current thinking is that wasm engines will perform this optimization,
611   // so we can save on code size.
612   return true;
613 }
614 
615 bool WebAssemblyTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
616   MVT ExtT = ExtVal.getSimpleValueType();
617   MVT MemT = cast<LoadSDNode>(ExtVal->getOperand(0))->getSimpleValueType(0);
618   return (ExtT == MVT::v8i16 && MemT == MVT::v8i8) ||
619          (ExtT == MVT::v4i32 && MemT == MVT::v4i16) ||
620          (ExtT == MVT::v2i64 && MemT == MVT::v2i32);
621 }
622 
623 EVT WebAssemblyTargetLowering::getSetCCResultType(const DataLayout &DL,
624                                                   LLVMContext &C,
625                                                   EVT VT) const {
626   if (VT.isVector())
627     return VT.changeVectorElementTypeToInteger();
628 
629   // So far, all branch instructions in Wasm take an I32 condition.
630   // The default TargetLowering::getSetCCResultType returns the pointer size,
631   // which would be useful to reduce instruction counts when testing
632   // against 64-bit pointers/values if at some point Wasm supports that.
633   return EVT::getIntegerVT(C, 32);
634 }
635 
636 bool WebAssemblyTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
637                                                    const CallInst &I,
638                                                    MachineFunction &MF,
639                                                    unsigned Intrinsic) const {
640   switch (Intrinsic) {
641   case Intrinsic::wasm_atomic_notify:
642     Info.opc = ISD::INTRINSIC_W_CHAIN;
643     Info.memVT = MVT::i32;
644     Info.ptrVal = I.getArgOperand(0);
645     Info.offset = 0;
646     Info.align = Align(4);
647     // atomic.notify instruction does not really load the memory specified with
648     // this argument, but MachineMemOperand should either be load or store, so
649     // we set this to a load.
650     // FIXME Volatile isn't really correct, but currently all LLVM atomic
651     // instructions are treated as volatiles in the backend, so we should be
652     // consistent. The same applies for wasm_atomic_wait intrinsics too.
653     Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
654     return true;
655   case Intrinsic::wasm_atomic_wait_i32:
656     Info.opc = ISD::INTRINSIC_W_CHAIN;
657     Info.memVT = MVT::i32;
658     Info.ptrVal = I.getArgOperand(0);
659     Info.offset = 0;
660     Info.align = Align(4);
661     Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
662     return true;
663   case Intrinsic::wasm_atomic_wait_i64:
664     Info.opc = ISD::INTRINSIC_W_CHAIN;
665     Info.memVT = MVT::i64;
666     Info.ptrVal = I.getArgOperand(0);
667     Info.offset = 0;
668     Info.align = Align(8);
669     Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
670     return true;
671   default:
672     return false;
673   }
674 }
675 
676 //===----------------------------------------------------------------------===//
677 // WebAssembly Lowering private implementation.
678 //===----------------------------------------------------------------------===//
679 
680 //===----------------------------------------------------------------------===//
681 // Lowering Code
682 //===----------------------------------------------------------------------===//
683 
684 static void fail(const SDLoc &DL, SelectionDAG &DAG, const char *Msg) {
685   MachineFunction &MF = DAG.getMachineFunction();
686   DAG.getContext()->diagnose(
687       DiagnosticInfoUnsupported(MF.getFunction(), Msg, DL.getDebugLoc()));
688 }
689 
690 // Test whether the given calling convention is supported.
691 static bool callingConvSupported(CallingConv::ID CallConv) {
692   // We currently support the language-independent target-independent
693   // conventions. We don't yet have a way to annotate calls with properties like
694   // "cold", and we don't have any call-clobbered registers, so these are mostly
695   // all handled the same.
696   return CallConv == CallingConv::C || CallConv == CallingConv::Fast ||
697          CallConv == CallingConv::Cold ||
698          CallConv == CallingConv::PreserveMost ||
699          CallConv == CallingConv::PreserveAll ||
700          CallConv == CallingConv::CXX_FAST_TLS ||
701          CallConv == CallingConv::WASM_EmscriptenInvoke ||
702          CallConv == CallingConv::Swift;
703 }
704 
705 SDValue
706 WebAssemblyTargetLowering::LowerCall(CallLoweringInfo &CLI,
707                                      SmallVectorImpl<SDValue> &InVals) const {
708   SelectionDAG &DAG = CLI.DAG;
709   SDLoc DL = CLI.DL;
710   SDValue Chain = CLI.Chain;
711   SDValue Callee = CLI.Callee;
712   MachineFunction &MF = DAG.getMachineFunction();
713   auto Layout = MF.getDataLayout();
714 
715   CallingConv::ID CallConv = CLI.CallConv;
716   if (!callingConvSupported(CallConv))
717     fail(DL, DAG,
718          "WebAssembly doesn't support language-specific or target-specific "
719          "calling conventions yet");
720   if (CLI.IsPatchPoint)
721     fail(DL, DAG, "WebAssembly doesn't support patch point yet");
722 
723   if (CLI.IsTailCall) {
724     auto NoTail = [&](const char *Msg) {
725       if (CLI.CB && CLI.CB->isMustTailCall())
726         fail(DL, DAG, Msg);
727       CLI.IsTailCall = false;
728     };
729 
730     if (!Subtarget->hasTailCall())
731       NoTail("WebAssembly 'tail-call' feature not enabled");
732 
733     // Varargs calls cannot be tail calls because the buffer is on the stack
734     if (CLI.IsVarArg)
735       NoTail("WebAssembly does not support varargs tail calls");
736 
737     // Do not tail call unless caller and callee return types match
738     const Function &F = MF.getFunction();
739     const TargetMachine &TM = getTargetMachine();
740     Type *RetTy = F.getReturnType();
741     SmallVector<MVT, 4> CallerRetTys;
742     SmallVector<MVT, 4> CalleeRetTys;
743     computeLegalValueVTs(F, TM, RetTy, CallerRetTys);
744     computeLegalValueVTs(F, TM, CLI.RetTy, CalleeRetTys);
745     bool TypesMatch = CallerRetTys.size() == CalleeRetTys.size() &&
746                       std::equal(CallerRetTys.begin(), CallerRetTys.end(),
747                                  CalleeRetTys.begin());
748     if (!TypesMatch)
749       NoTail("WebAssembly tail call requires caller and callee return types to "
750              "match");
751 
752     // If pointers to local stack values are passed, we cannot tail call
753     if (CLI.CB) {
754       for (auto &Arg : CLI.CB->args()) {
755         Value *Val = Arg.get();
756         // Trace the value back through pointer operations
757         while (true) {
758           Value *Src = Val->stripPointerCastsAndAliases();
759           if (auto *GEP = dyn_cast<GetElementPtrInst>(Src))
760             Src = GEP->getPointerOperand();
761           if (Val == Src)
762             break;
763           Val = Src;
764         }
765         if (isa<AllocaInst>(Val)) {
766           NoTail(
767               "WebAssembly does not support tail calling with stack arguments");
768           break;
769         }
770       }
771     }
772   }
773 
774   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
775   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
776   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
777 
778   // The generic code may have added an sret argument. If we're lowering an
779   // invoke function, the ABI requires that the function pointer be the first
780   // argument, so we may have to swap the arguments.
781   if (CallConv == CallingConv::WASM_EmscriptenInvoke && Outs.size() >= 2 &&
782       Outs[0].Flags.isSRet()) {
783     std::swap(Outs[0], Outs[1]);
784     std::swap(OutVals[0], OutVals[1]);
785   }
786 
787   bool HasSwiftSelfArg = false;
788   bool HasSwiftErrorArg = false;
789   unsigned NumFixedArgs = 0;
790   for (unsigned I = 0; I < Outs.size(); ++I) {
791     const ISD::OutputArg &Out = Outs[I];
792     SDValue &OutVal = OutVals[I];
793     HasSwiftSelfArg |= Out.Flags.isSwiftSelf();
794     HasSwiftErrorArg |= Out.Flags.isSwiftError();
795     if (Out.Flags.isNest())
796       fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
797     if (Out.Flags.isInAlloca())
798       fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
799     if (Out.Flags.isInConsecutiveRegs())
800       fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
801     if (Out.Flags.isInConsecutiveRegsLast())
802       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
803     if (Out.Flags.isByVal() && Out.Flags.getByValSize() != 0) {
804       auto &MFI = MF.getFrameInfo();
805       int FI = MFI.CreateStackObject(Out.Flags.getByValSize(),
806                                      Out.Flags.getNonZeroByValAlign(),
807                                      /*isSS=*/false);
808       SDValue SizeNode =
809           DAG.getConstant(Out.Flags.getByValSize(), DL, MVT::i32);
810       SDValue FINode = DAG.getFrameIndex(FI, getPointerTy(Layout));
811       Chain = DAG.getMemcpy(
812           Chain, DL, FINode, OutVal, SizeNode, Out.Flags.getNonZeroByValAlign(),
813           /*isVolatile*/ false, /*AlwaysInline=*/false,
814           /*isTailCall*/ false, MachinePointerInfo(), MachinePointerInfo());
815       OutVal = FINode;
816     }
817     // Count the number of fixed args *after* legalization.
818     NumFixedArgs += Out.IsFixed;
819   }
820 
821   bool IsVarArg = CLI.IsVarArg;
822   auto PtrVT = getPointerTy(Layout);
823 
824   // For swiftcc, emit additional swiftself and swifterror arguments
825   // if there aren't. These additional arguments are also added for callee
826   // signature They are necessary to match callee and caller signature for
827   // indirect call.
828   if (CallConv == CallingConv::Swift) {
829     if (!HasSwiftSelfArg) {
830       NumFixedArgs++;
831       ISD::OutputArg Arg;
832       Arg.Flags.setSwiftSelf();
833       CLI.Outs.push_back(Arg);
834       SDValue ArgVal = DAG.getUNDEF(PtrVT);
835       CLI.OutVals.push_back(ArgVal);
836     }
837     if (!HasSwiftErrorArg) {
838       NumFixedArgs++;
839       ISD::OutputArg Arg;
840       Arg.Flags.setSwiftError();
841       CLI.Outs.push_back(Arg);
842       SDValue ArgVal = DAG.getUNDEF(PtrVT);
843       CLI.OutVals.push_back(ArgVal);
844     }
845   }
846 
847   // Analyze operands of the call, assigning locations to each operand.
848   SmallVector<CCValAssign, 16> ArgLocs;
849   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
850 
851   if (IsVarArg) {
852     // Outgoing non-fixed arguments are placed in a buffer. First
853     // compute their offsets and the total amount of buffer space needed.
854     for (unsigned I = NumFixedArgs; I < Outs.size(); ++I) {
855       const ISD::OutputArg &Out = Outs[I];
856       SDValue &Arg = OutVals[I];
857       EVT VT = Arg.getValueType();
858       assert(VT != MVT::iPTR && "Legalized args should be concrete");
859       Type *Ty = VT.getTypeForEVT(*DAG.getContext());
860       Align Alignment =
861           std::max(Out.Flags.getNonZeroOrigAlign(), Layout.getABITypeAlign(Ty));
862       unsigned Offset =
863           CCInfo.AllocateStack(Layout.getTypeAllocSize(Ty), Alignment);
864       CCInfo.addLoc(CCValAssign::getMem(ArgLocs.size(), VT.getSimpleVT(),
865                                         Offset, VT.getSimpleVT(),
866                                         CCValAssign::Full));
867     }
868   }
869 
870   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
871 
872   SDValue FINode;
873   if (IsVarArg && NumBytes) {
874     // For non-fixed arguments, next emit stores to store the argument values
875     // to the stack buffer at the offsets computed above.
876     int FI = MF.getFrameInfo().CreateStackObject(NumBytes,
877                                                  Layout.getStackAlignment(),
878                                                  /*isSS=*/false);
879     unsigned ValNo = 0;
880     SmallVector<SDValue, 8> Chains;
881     for (SDValue Arg :
882          make_range(OutVals.begin() + NumFixedArgs, OutVals.end())) {
883       assert(ArgLocs[ValNo].getValNo() == ValNo &&
884              "ArgLocs should remain in order and only hold varargs args");
885       unsigned Offset = ArgLocs[ValNo++].getLocMemOffset();
886       FINode = DAG.getFrameIndex(FI, getPointerTy(Layout));
887       SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, FINode,
888                                 DAG.getConstant(Offset, DL, PtrVT));
889       Chains.push_back(
890           DAG.getStore(Chain, DL, Arg, Add,
891                        MachinePointerInfo::getFixedStack(MF, FI, Offset), 0));
892     }
893     if (!Chains.empty())
894       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
895   } else if (IsVarArg) {
896     FINode = DAG.getIntPtrConstant(0, DL);
897   }
898 
899   if (Callee->getOpcode() == ISD::GlobalAddress) {
900     // If the callee is a GlobalAddress node (quite common, every direct call
901     // is) turn it into a TargetGlobalAddress node so that LowerGlobalAddress
902     // doesn't at MO_GOT which is not needed for direct calls.
903     GlobalAddressSDNode* GA = cast<GlobalAddressSDNode>(Callee);
904     Callee = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
905                                         getPointerTy(DAG.getDataLayout()),
906                                         GA->getOffset());
907     Callee = DAG.getNode(WebAssemblyISD::Wrapper, DL,
908                          getPointerTy(DAG.getDataLayout()), Callee);
909   }
910 
911   // Compute the operands for the CALLn node.
912   SmallVector<SDValue, 16> Ops;
913   Ops.push_back(Chain);
914   Ops.push_back(Callee);
915 
916   // Add all fixed arguments. Note that for non-varargs calls, NumFixedArgs
917   // isn't reliable.
918   Ops.append(OutVals.begin(),
919              IsVarArg ? OutVals.begin() + NumFixedArgs : OutVals.end());
920   // Add a pointer to the vararg buffer.
921   if (IsVarArg)
922     Ops.push_back(FINode);
923 
924   SmallVector<EVT, 8> InTys;
925   for (const auto &In : Ins) {
926     assert(!In.Flags.isByVal() && "byval is not valid for return values");
927     assert(!In.Flags.isNest() && "nest is not valid for return values");
928     if (In.Flags.isInAlloca())
929       fail(DL, DAG, "WebAssembly hasn't implemented inalloca return values");
930     if (In.Flags.isInConsecutiveRegs())
931       fail(DL, DAG, "WebAssembly hasn't implemented cons regs return values");
932     if (In.Flags.isInConsecutiveRegsLast())
933       fail(DL, DAG,
934            "WebAssembly hasn't implemented cons regs last return values");
935     // Ignore In.getNonZeroOrigAlign() because all our arguments are passed in
936     // registers.
937     InTys.push_back(In.VT);
938   }
939 
940   if (CLI.IsTailCall) {
941     // ret_calls do not return values to the current frame
942     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
943     return DAG.getNode(WebAssemblyISD::RET_CALL, DL, NodeTys, Ops);
944   }
945 
946   InTys.push_back(MVT::Other);
947   SDVTList InTyList = DAG.getVTList(InTys);
948   SDValue Res = DAG.getNode(WebAssemblyISD::CALL, DL, InTyList, Ops);
949 
950   for (size_t I = 0; I < Ins.size(); ++I)
951     InVals.push_back(Res.getValue(I));
952 
953   // Return the chain
954   return Res.getValue(Ins.size());
955 }
956 
957 bool WebAssemblyTargetLowering::CanLowerReturn(
958     CallingConv::ID /*CallConv*/, MachineFunction & /*MF*/, bool /*IsVarArg*/,
959     const SmallVectorImpl<ISD::OutputArg> &Outs,
960     LLVMContext & /*Context*/) const {
961   // WebAssembly can only handle returning tuples with multivalue enabled
962   return Subtarget->hasMultivalue() || Outs.size() <= 1;
963 }
964 
965 SDValue WebAssemblyTargetLowering::LowerReturn(
966     SDValue Chain, CallingConv::ID CallConv, bool /*IsVarArg*/,
967     const SmallVectorImpl<ISD::OutputArg> &Outs,
968     const SmallVectorImpl<SDValue> &OutVals, const SDLoc &DL,
969     SelectionDAG &DAG) const {
970   assert((Subtarget->hasMultivalue() || Outs.size() <= 1) &&
971          "MVP WebAssembly can only return up to one value");
972   if (!callingConvSupported(CallConv))
973     fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
974 
975   SmallVector<SDValue, 4> RetOps(1, Chain);
976   RetOps.append(OutVals.begin(), OutVals.end());
977   Chain = DAG.getNode(WebAssemblyISD::RETURN, DL, MVT::Other, RetOps);
978 
979   // Record the number and types of the return values.
980   for (const ISD::OutputArg &Out : Outs) {
981     assert(!Out.Flags.isByVal() && "byval is not valid for return values");
982     assert(!Out.Flags.isNest() && "nest is not valid for return values");
983     assert(Out.IsFixed && "non-fixed return value is not valid");
984     if (Out.Flags.isInAlloca())
985       fail(DL, DAG, "WebAssembly hasn't implemented inalloca results");
986     if (Out.Flags.isInConsecutiveRegs())
987       fail(DL, DAG, "WebAssembly hasn't implemented cons regs results");
988     if (Out.Flags.isInConsecutiveRegsLast())
989       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last results");
990   }
991 
992   return Chain;
993 }
994 
995 SDValue WebAssemblyTargetLowering::LowerFormalArguments(
996     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
997     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
998     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
999   if (!callingConvSupported(CallConv))
1000     fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
1001 
1002   MachineFunction &MF = DAG.getMachineFunction();
1003   auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>();
1004 
1005   // Set up the incoming ARGUMENTS value, which serves to represent the liveness
1006   // of the incoming values before they're represented by virtual registers.
1007   MF.getRegInfo().addLiveIn(WebAssembly::ARGUMENTS);
1008 
1009   bool HasSwiftErrorArg = false;
1010   bool HasSwiftSelfArg = false;
1011   for (const ISD::InputArg &In : Ins) {
1012     HasSwiftSelfArg |= In.Flags.isSwiftSelf();
1013     HasSwiftErrorArg |= In.Flags.isSwiftError();
1014     if (In.Flags.isInAlloca())
1015       fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
1016     if (In.Flags.isNest())
1017       fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
1018     if (In.Flags.isInConsecutiveRegs())
1019       fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
1020     if (In.Flags.isInConsecutiveRegsLast())
1021       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
1022     // Ignore In.getNonZeroOrigAlign() because all our arguments are passed in
1023     // registers.
1024     InVals.push_back(In.Used ? DAG.getNode(WebAssemblyISD::ARGUMENT, DL, In.VT,
1025                                            DAG.getTargetConstant(InVals.size(),
1026                                                                  DL, MVT::i32))
1027                              : DAG.getUNDEF(In.VT));
1028 
1029     // Record the number and types of arguments.
1030     MFI->addParam(In.VT);
1031   }
1032 
1033   // For swiftcc, emit additional swiftself and swifterror arguments
1034   // if there aren't. These additional arguments are also added for callee
1035   // signature They are necessary to match callee and caller signature for
1036   // indirect call.
1037   auto PtrVT = getPointerTy(MF.getDataLayout());
1038   if (CallConv == CallingConv::Swift) {
1039     if (!HasSwiftSelfArg) {
1040       MFI->addParam(PtrVT);
1041     }
1042     if (!HasSwiftErrorArg) {
1043       MFI->addParam(PtrVT);
1044     }
1045   }
1046   // Varargs are copied into a buffer allocated by the caller, and a pointer to
1047   // the buffer is passed as an argument.
1048   if (IsVarArg) {
1049     MVT PtrVT = getPointerTy(MF.getDataLayout());
1050     Register VarargVreg =
1051         MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrVT));
1052     MFI->setVarargBufferVreg(VarargVreg);
1053     Chain = DAG.getCopyToReg(
1054         Chain, DL, VarargVreg,
1055         DAG.getNode(WebAssemblyISD::ARGUMENT, DL, PtrVT,
1056                     DAG.getTargetConstant(Ins.size(), DL, MVT::i32)));
1057     MFI->addParam(PtrVT);
1058   }
1059 
1060   // Record the number and types of arguments and results.
1061   SmallVector<MVT, 4> Params;
1062   SmallVector<MVT, 4> Results;
1063   computeSignatureVTs(MF.getFunction().getFunctionType(), &MF.getFunction(),
1064                       MF.getFunction(), DAG.getTarget(), Params, Results);
1065   for (MVT VT : Results)
1066     MFI->addResult(VT);
1067   // TODO: Use signatures in WebAssemblyMachineFunctionInfo too and unify
1068   // the param logic here with ComputeSignatureVTs
1069   assert(MFI->getParams().size() == Params.size() &&
1070          std::equal(MFI->getParams().begin(), MFI->getParams().end(),
1071                     Params.begin()));
1072 
1073   return Chain;
1074 }
1075 
1076 void WebAssemblyTargetLowering::ReplaceNodeResults(
1077     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
1078   switch (N->getOpcode()) {
1079   case ISD::SIGN_EXTEND_INREG:
1080     // Do not add any results, signifying that N should not be custom lowered
1081     // after all. This happens because simd128 turns on custom lowering for
1082     // SIGN_EXTEND_INREG, but for non-vector sign extends the result might be an
1083     // illegal type.
1084     break;
1085   default:
1086     llvm_unreachable(
1087         "ReplaceNodeResults not implemented for this op for WebAssembly!");
1088   }
1089 }
1090 
1091 //===----------------------------------------------------------------------===//
1092 //  Custom lowering hooks.
1093 //===----------------------------------------------------------------------===//
1094 
1095 SDValue WebAssemblyTargetLowering::LowerOperation(SDValue Op,
1096                                                   SelectionDAG &DAG) const {
1097   SDLoc DL(Op);
1098   switch (Op.getOpcode()) {
1099   default:
1100     llvm_unreachable("unimplemented operation lowering");
1101     return SDValue();
1102   case ISD::FrameIndex:
1103     return LowerFrameIndex(Op, DAG);
1104   case ISD::GlobalAddress:
1105     return LowerGlobalAddress(Op, DAG);
1106   case ISD::ExternalSymbol:
1107     return LowerExternalSymbol(Op, DAG);
1108   case ISD::JumpTable:
1109     return LowerJumpTable(Op, DAG);
1110   case ISD::BR_JT:
1111     return LowerBR_JT(Op, DAG);
1112   case ISD::VASTART:
1113     return LowerVASTART(Op, DAG);
1114   case ISD::BlockAddress:
1115   case ISD::BRIND:
1116     fail(DL, DAG, "WebAssembly hasn't implemented computed gotos");
1117     return SDValue();
1118   case ISD::RETURNADDR:
1119     return LowerRETURNADDR(Op, DAG);
1120   case ISD::FRAMEADDR:
1121     return LowerFRAMEADDR(Op, DAG);
1122   case ISD::CopyToReg:
1123     return LowerCopyToReg(Op, DAG);
1124   case ISD::EXTRACT_VECTOR_ELT:
1125   case ISD::INSERT_VECTOR_ELT:
1126     return LowerAccessVectorElement(Op, DAG);
1127   case ISD::INTRINSIC_VOID:
1128   case ISD::INTRINSIC_WO_CHAIN:
1129   case ISD::INTRINSIC_W_CHAIN:
1130     return LowerIntrinsic(Op, DAG);
1131   case ISD::SIGN_EXTEND_INREG:
1132     return LowerSIGN_EXTEND_INREG(Op, DAG);
1133   case ISD::BUILD_VECTOR:
1134     return LowerBUILD_VECTOR(Op, DAG);
1135   case ISD::VECTOR_SHUFFLE:
1136     return LowerVECTOR_SHUFFLE(Op, DAG);
1137   case ISD::SETCC:
1138     return LowerSETCC(Op, DAG);
1139   case ISD::SHL:
1140   case ISD::SRA:
1141   case ISD::SRL:
1142     return LowerShift(Op, DAG);
1143   }
1144 }
1145 
1146 SDValue WebAssemblyTargetLowering::LowerCopyToReg(SDValue Op,
1147                                                   SelectionDAG &DAG) const {
1148   SDValue Src = Op.getOperand(2);
1149   if (isa<FrameIndexSDNode>(Src.getNode())) {
1150     // CopyToReg nodes don't support FrameIndex operands. Other targets select
1151     // the FI to some LEA-like instruction, but since we don't have that, we
1152     // need to insert some kind of instruction that can take an FI operand and
1153     // produces a value usable by CopyToReg (i.e. in a vreg). So insert a dummy
1154     // local.copy between Op and its FI operand.
1155     SDValue Chain = Op.getOperand(0);
1156     SDLoc DL(Op);
1157     unsigned Reg = cast<RegisterSDNode>(Op.getOperand(1))->getReg();
1158     EVT VT = Src.getValueType();
1159     SDValue Copy(DAG.getMachineNode(VT == MVT::i32 ? WebAssembly::COPY_I32
1160                                                    : WebAssembly::COPY_I64,
1161                                     DL, VT, Src),
1162                  0);
1163     return Op.getNode()->getNumValues() == 1
1164                ? DAG.getCopyToReg(Chain, DL, Reg, Copy)
1165                : DAG.getCopyToReg(Chain, DL, Reg, Copy,
1166                                   Op.getNumOperands() == 4 ? Op.getOperand(3)
1167                                                            : SDValue());
1168   }
1169   return SDValue();
1170 }
1171 
1172 SDValue WebAssemblyTargetLowering::LowerFrameIndex(SDValue Op,
1173                                                    SelectionDAG &DAG) const {
1174   int FI = cast<FrameIndexSDNode>(Op)->getIndex();
1175   return DAG.getTargetFrameIndex(FI, Op.getValueType());
1176 }
1177 
1178 SDValue WebAssemblyTargetLowering::LowerRETURNADDR(SDValue Op,
1179                                                    SelectionDAG &DAG) const {
1180   SDLoc DL(Op);
1181 
1182   if (!Subtarget->getTargetTriple().isOSEmscripten()) {
1183     fail(DL, DAG,
1184          "Non-Emscripten WebAssembly hasn't implemented "
1185          "__builtin_return_address");
1186     return SDValue();
1187   }
1188 
1189   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1190     return SDValue();
1191 
1192   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1193   MakeLibCallOptions CallOptions;
1194   return makeLibCall(DAG, RTLIB::RETURN_ADDRESS, Op.getValueType(),
1195                      {DAG.getConstant(Depth, DL, MVT::i32)}, CallOptions, DL)
1196       .first;
1197 }
1198 
1199 SDValue WebAssemblyTargetLowering::LowerFRAMEADDR(SDValue Op,
1200                                                   SelectionDAG &DAG) const {
1201   // Non-zero depths are not supported by WebAssembly currently. Use the
1202   // legalizer's default expansion, which is to return 0 (what this function is
1203   // documented to do).
1204   if (Op.getConstantOperandVal(0) > 0)
1205     return SDValue();
1206 
1207   DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
1208   EVT VT = Op.getValueType();
1209   Register FP =
1210       Subtarget->getRegisterInfo()->getFrameRegister(DAG.getMachineFunction());
1211   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), FP, VT);
1212 }
1213 
1214 SDValue WebAssemblyTargetLowering::LowerGlobalAddress(SDValue Op,
1215                                                       SelectionDAG &DAG) const {
1216   SDLoc DL(Op);
1217   const auto *GA = cast<GlobalAddressSDNode>(Op);
1218   EVT VT = Op.getValueType();
1219   assert(GA->getTargetFlags() == 0 &&
1220          "Unexpected target flags on generic GlobalAddressSDNode");
1221   if (GA->getAddressSpace() != 0)
1222     fail(DL, DAG, "WebAssembly only expects the 0 address space");
1223 
1224   unsigned OperandFlags = 0;
1225   if (isPositionIndependent()) {
1226     const GlobalValue *GV = GA->getGlobal();
1227     if (getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) {
1228       MachineFunction &MF = DAG.getMachineFunction();
1229       MVT PtrVT = getPointerTy(MF.getDataLayout());
1230       const char *BaseName;
1231       if (GV->getValueType()->isFunctionTy()) {
1232         BaseName = MF.createExternalSymbolName("__table_base");
1233         OperandFlags = WebAssemblyII::MO_TABLE_BASE_REL;
1234       }
1235       else {
1236         BaseName = MF.createExternalSymbolName("__memory_base");
1237         OperandFlags = WebAssemblyII::MO_MEMORY_BASE_REL;
1238       }
1239       SDValue BaseAddr =
1240           DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT,
1241                       DAG.getTargetExternalSymbol(BaseName, PtrVT));
1242 
1243       SDValue SymAddr = DAG.getNode(
1244           WebAssemblyISD::WrapperPIC, DL, VT,
1245           DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT, GA->getOffset(),
1246                                      OperandFlags));
1247 
1248       return DAG.getNode(ISD::ADD, DL, VT, BaseAddr, SymAddr);
1249     } else {
1250       OperandFlags = WebAssemblyII::MO_GOT;
1251     }
1252   }
1253 
1254   return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1255                      DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT,
1256                                                 GA->getOffset(), OperandFlags));
1257 }
1258 
1259 SDValue
1260 WebAssemblyTargetLowering::LowerExternalSymbol(SDValue Op,
1261                                                SelectionDAG &DAG) const {
1262   SDLoc DL(Op);
1263   const auto *ES = cast<ExternalSymbolSDNode>(Op);
1264   EVT VT = Op.getValueType();
1265   assert(ES->getTargetFlags() == 0 &&
1266          "Unexpected target flags on generic ExternalSymbolSDNode");
1267   return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1268                      DAG.getTargetExternalSymbol(ES->getSymbol(), VT));
1269 }
1270 
1271 SDValue WebAssemblyTargetLowering::LowerJumpTable(SDValue Op,
1272                                                   SelectionDAG &DAG) const {
1273   // There's no need for a Wrapper node because we always incorporate a jump
1274   // table operand into a BR_TABLE instruction, rather than ever
1275   // materializing it in a register.
1276   const JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1277   return DAG.getTargetJumpTable(JT->getIndex(), Op.getValueType(),
1278                                 JT->getTargetFlags());
1279 }
1280 
1281 SDValue WebAssemblyTargetLowering::LowerBR_JT(SDValue Op,
1282                                               SelectionDAG &DAG) const {
1283   SDLoc DL(Op);
1284   SDValue Chain = Op.getOperand(0);
1285   const auto *JT = cast<JumpTableSDNode>(Op.getOperand(1));
1286   SDValue Index = Op.getOperand(2);
1287   assert(JT->getTargetFlags() == 0 && "WebAssembly doesn't set target flags");
1288 
1289   SmallVector<SDValue, 8> Ops;
1290   Ops.push_back(Chain);
1291   Ops.push_back(Index);
1292 
1293   MachineJumpTableInfo *MJTI = DAG.getMachineFunction().getJumpTableInfo();
1294   const auto &MBBs = MJTI->getJumpTables()[JT->getIndex()].MBBs;
1295 
1296   // Add an operand for each case.
1297   for (auto MBB : MBBs)
1298     Ops.push_back(DAG.getBasicBlock(MBB));
1299 
1300   // Add the first MBB as a dummy default target for now. This will be replaced
1301   // with the proper default target (and the preceding range check eliminated)
1302   // if possible by WebAssemblyFixBrTableDefaults.
1303   Ops.push_back(DAG.getBasicBlock(*MBBs.begin()));
1304   return DAG.getNode(WebAssemblyISD::BR_TABLE, DL, MVT::Other, Ops);
1305 }
1306 
1307 SDValue WebAssemblyTargetLowering::LowerVASTART(SDValue Op,
1308                                                 SelectionDAG &DAG) const {
1309   SDLoc DL(Op);
1310   EVT PtrVT = getPointerTy(DAG.getMachineFunction().getDataLayout());
1311 
1312   auto *MFI = DAG.getMachineFunction().getInfo<WebAssemblyFunctionInfo>();
1313   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1314 
1315   SDValue ArgN = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1316                                     MFI->getVarargBufferVreg(), PtrVT);
1317   return DAG.getStore(Op.getOperand(0), DL, ArgN, Op.getOperand(1),
1318                       MachinePointerInfo(SV), 0);
1319 }
1320 
1321 SDValue WebAssemblyTargetLowering::LowerIntrinsic(SDValue Op,
1322                                                   SelectionDAG &DAG) const {
1323   MachineFunction &MF = DAG.getMachineFunction();
1324   unsigned IntNo;
1325   switch (Op.getOpcode()) {
1326   case ISD::INTRINSIC_VOID:
1327   case ISD::INTRINSIC_W_CHAIN:
1328     IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1329     break;
1330   case ISD::INTRINSIC_WO_CHAIN:
1331     IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1332     break;
1333   default:
1334     llvm_unreachable("Invalid intrinsic");
1335   }
1336   SDLoc DL(Op);
1337 
1338   switch (IntNo) {
1339   default:
1340     return SDValue(); // Don't custom lower most intrinsics.
1341 
1342   case Intrinsic::wasm_lsda: {
1343     EVT VT = Op.getValueType();
1344     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1345     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
1346     auto &Context = MF.getMMI().getContext();
1347     MCSymbol *S = Context.getOrCreateSymbol(Twine("GCC_except_table") +
1348                                             Twine(MF.getFunctionNumber()));
1349     return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1350                        DAG.getMCSymbol(S, PtrVT));
1351   }
1352 
1353   case Intrinsic::wasm_throw: {
1354     // We only support C++ exceptions for now
1355     int Tag = cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue();
1356     if (Tag != CPP_EXCEPTION)
1357       llvm_unreachable("Invalid tag!");
1358     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1359     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
1360     const char *SymName = MF.createExternalSymbolName("__cpp_exception");
1361     SDValue SymNode = DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT,
1362                                   DAG.getTargetExternalSymbol(SymName, PtrVT));
1363     return DAG.getNode(WebAssemblyISD::THROW, DL,
1364                        MVT::Other, // outchain type
1365                        {
1366                            Op.getOperand(0), // inchain
1367                            SymNode,          // exception symbol
1368                            Op.getOperand(3)  // thrown value
1369                        });
1370   }
1371 
1372   case Intrinsic::wasm_shuffle: {
1373     // Drop in-chain and replace undefs, but otherwise pass through unchanged
1374     SDValue Ops[18];
1375     size_t OpIdx = 0;
1376     Ops[OpIdx++] = Op.getOperand(1);
1377     Ops[OpIdx++] = Op.getOperand(2);
1378     while (OpIdx < 18) {
1379       const SDValue &MaskIdx = Op.getOperand(OpIdx + 1);
1380       if (MaskIdx.isUndef() ||
1381           cast<ConstantSDNode>(MaskIdx.getNode())->getZExtValue() >= 32) {
1382         Ops[OpIdx++] = DAG.getConstant(0, DL, MVT::i32);
1383       } else {
1384         Ops[OpIdx++] = MaskIdx;
1385       }
1386     }
1387     return DAG.getNode(WebAssemblyISD::SHUFFLE, DL, Op.getValueType(), Ops);
1388   }
1389   }
1390 }
1391 
1392 SDValue
1393 WebAssemblyTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
1394                                                   SelectionDAG &DAG) const {
1395   SDLoc DL(Op);
1396   // If sign extension operations are disabled, allow sext_inreg only if operand
1397   // is a vector extract of an i8 or i16 lane. SIMD does not depend on sign
1398   // extension operations, but allowing sext_inreg in this context lets us have
1399   // simple patterns to select extract_lane_s instructions. Expanding sext_inreg
1400   // everywhere would be simpler in this file, but would necessitate large and
1401   // brittle patterns to undo the expansion and select extract_lane_s
1402   // instructions.
1403   assert(!Subtarget->hasSignExt() && Subtarget->hasSIMD128());
1404   if (Op.getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1405     return SDValue();
1406 
1407   const SDValue &Extract = Op.getOperand(0);
1408   MVT VecT = Extract.getOperand(0).getSimpleValueType();
1409   if (VecT.getVectorElementType().getSizeInBits() > 32)
1410     return SDValue();
1411   MVT ExtractedLaneT =
1412       cast<VTSDNode>(Op.getOperand(1).getNode())->getVT().getSimpleVT();
1413   MVT ExtractedVecT =
1414       MVT::getVectorVT(ExtractedLaneT, 128 / ExtractedLaneT.getSizeInBits());
1415   if (ExtractedVecT == VecT)
1416     return Op;
1417 
1418   // Bitcast vector to appropriate type to ensure ISel pattern coverage
1419   const SDNode *Index = Extract.getOperand(1).getNode();
1420   if (!isa<ConstantSDNode>(Index))
1421     return SDValue();
1422   unsigned IndexVal = cast<ConstantSDNode>(Index)->getZExtValue();
1423   unsigned Scale =
1424       ExtractedVecT.getVectorNumElements() / VecT.getVectorNumElements();
1425   assert(Scale > 1);
1426   SDValue NewIndex =
1427       DAG.getConstant(IndexVal * Scale, DL, Index->getValueType(0));
1428   SDValue NewExtract = DAG.getNode(
1429       ISD::EXTRACT_VECTOR_ELT, DL, Extract.getValueType(),
1430       DAG.getBitcast(ExtractedVecT, Extract.getOperand(0)), NewIndex);
1431   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, Op.getValueType(), NewExtract,
1432                      Op.getOperand(1));
1433 }
1434 
1435 SDValue WebAssemblyTargetLowering::LowerBUILD_VECTOR(SDValue Op,
1436                                                      SelectionDAG &DAG) const {
1437   SDLoc DL(Op);
1438   const EVT VecT = Op.getValueType();
1439   const EVT LaneT = Op.getOperand(0).getValueType();
1440   const size_t Lanes = Op.getNumOperands();
1441   bool CanSwizzle = VecT == MVT::v16i8;
1442 
1443   // BUILD_VECTORs are lowered to the instruction that initializes the highest
1444   // possible number of lanes at once followed by a sequence of replace_lane
1445   // instructions to individually initialize any remaining lanes.
1446 
1447   // TODO: Tune this. For example, lanewise swizzling is very expensive, so
1448   // swizzled lanes should be given greater weight.
1449 
1450   // TODO: Investigate building vectors by shuffling together vectors built by
1451   // separately specialized means.
1452 
1453   auto IsConstant = [](const SDValue &V) {
1454     return V.getOpcode() == ISD::Constant || V.getOpcode() == ISD::ConstantFP;
1455   };
1456 
1457   // Returns the source vector and index vector pair if they exist. Checks for:
1458   //   (extract_vector_elt
1459   //     $src,
1460   //     (sign_extend_inreg (extract_vector_elt $indices, $i))
1461   //   )
1462   auto GetSwizzleSrcs = [](size_t I, const SDValue &Lane) {
1463     auto Bail = std::make_pair(SDValue(), SDValue());
1464     if (Lane->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1465       return Bail;
1466     const SDValue &SwizzleSrc = Lane->getOperand(0);
1467     const SDValue &IndexExt = Lane->getOperand(1);
1468     if (IndexExt->getOpcode() != ISD::SIGN_EXTEND_INREG)
1469       return Bail;
1470     const SDValue &Index = IndexExt->getOperand(0);
1471     if (Index->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1472       return Bail;
1473     const SDValue &SwizzleIndices = Index->getOperand(0);
1474     if (SwizzleSrc.getValueType() != MVT::v16i8 ||
1475         SwizzleIndices.getValueType() != MVT::v16i8 ||
1476         Index->getOperand(1)->getOpcode() != ISD::Constant ||
1477         Index->getConstantOperandVal(1) != I)
1478       return Bail;
1479     return std::make_pair(SwizzleSrc, SwizzleIndices);
1480   };
1481 
1482   using ValueEntry = std::pair<SDValue, size_t>;
1483   SmallVector<ValueEntry, 16> SplatValueCounts;
1484 
1485   using SwizzleEntry = std::pair<std::pair<SDValue, SDValue>, size_t>;
1486   SmallVector<SwizzleEntry, 16> SwizzleCounts;
1487 
1488   auto AddCount = [](auto &Counts, const auto &Val) {
1489     auto CountIt = std::find_if(Counts.begin(), Counts.end(),
1490                                 [&Val](auto E) { return E.first == Val; });
1491     if (CountIt == Counts.end()) {
1492       Counts.emplace_back(Val, 1);
1493     } else {
1494       CountIt->second++;
1495     }
1496   };
1497 
1498   auto GetMostCommon = [](auto &Counts) {
1499     auto CommonIt =
1500         std::max_element(Counts.begin(), Counts.end(),
1501                          [](auto A, auto B) { return A.second < B.second; });
1502     assert(CommonIt != Counts.end() && "Unexpected all-undef build_vector");
1503     return *CommonIt;
1504   };
1505 
1506   size_t NumConstantLanes = 0;
1507 
1508   // Count eligible lanes for each type of vector creation op
1509   for (size_t I = 0; I < Lanes; ++I) {
1510     const SDValue &Lane = Op->getOperand(I);
1511     if (Lane.isUndef())
1512       continue;
1513 
1514     AddCount(SplatValueCounts, Lane);
1515 
1516     if (IsConstant(Lane)) {
1517       NumConstantLanes++;
1518     } else if (CanSwizzle) {
1519       auto SwizzleSrcs = GetSwizzleSrcs(I, Lane);
1520       if (SwizzleSrcs.first)
1521         AddCount(SwizzleCounts, SwizzleSrcs);
1522     }
1523   }
1524 
1525   SDValue SplatValue;
1526   size_t NumSplatLanes;
1527   std::tie(SplatValue, NumSplatLanes) = GetMostCommon(SplatValueCounts);
1528 
1529   SDValue SwizzleSrc;
1530   SDValue SwizzleIndices;
1531   size_t NumSwizzleLanes = 0;
1532   if (SwizzleCounts.size())
1533     std::forward_as_tuple(std::tie(SwizzleSrc, SwizzleIndices),
1534                           NumSwizzleLanes) = GetMostCommon(SwizzleCounts);
1535 
1536   // Predicate returning true if the lane is properly initialized by the
1537   // original instruction
1538   std::function<bool(size_t, const SDValue &)> IsLaneConstructed;
1539   SDValue Result;
1540   // Prefer swizzles over vector consts over splats
1541   if (NumSwizzleLanes >= NumSplatLanes &&
1542       (!Subtarget->hasUnimplementedSIMD128() ||
1543        NumSwizzleLanes >= NumConstantLanes)) {
1544     Result = DAG.getNode(WebAssemblyISD::SWIZZLE, DL, VecT, SwizzleSrc,
1545                          SwizzleIndices);
1546     auto Swizzled = std::make_pair(SwizzleSrc, SwizzleIndices);
1547     IsLaneConstructed = [&, Swizzled](size_t I, const SDValue &Lane) {
1548       return Swizzled == GetSwizzleSrcs(I, Lane);
1549     };
1550   } else if (NumConstantLanes >= NumSplatLanes &&
1551              Subtarget->hasUnimplementedSIMD128()) {
1552     SmallVector<SDValue, 16> ConstLanes;
1553     for (const SDValue &Lane : Op->op_values()) {
1554       if (IsConstant(Lane)) {
1555         ConstLanes.push_back(Lane);
1556       } else if (LaneT.isFloatingPoint()) {
1557         ConstLanes.push_back(DAG.getConstantFP(0, DL, LaneT));
1558       } else {
1559         ConstLanes.push_back(DAG.getConstant(0, DL, LaneT));
1560       }
1561     }
1562     Result = DAG.getBuildVector(VecT, DL, ConstLanes);
1563     IsLaneConstructed = [&](size_t _, const SDValue &Lane) {
1564       return IsConstant(Lane);
1565     };
1566   }
1567   if (!Result) {
1568     // Use a splat, but possibly a load_splat
1569     LoadSDNode *SplattedLoad;
1570     if ((SplattedLoad = dyn_cast<LoadSDNode>(SplatValue)) &&
1571         SplattedLoad->getMemoryVT() == VecT.getVectorElementType()) {
1572       Result = DAG.getMemIntrinsicNode(
1573           WebAssemblyISD::LOAD_SPLAT, DL, DAG.getVTList(VecT),
1574           {SplattedLoad->getChain(), SplattedLoad->getBasePtr(),
1575            SplattedLoad->getOffset()},
1576           SplattedLoad->getMemoryVT(), SplattedLoad->getMemOperand());
1577     } else {
1578       Result = DAG.getSplatBuildVector(VecT, DL, SplatValue);
1579     }
1580     IsLaneConstructed = [&](size_t _, const SDValue &Lane) {
1581       return Lane == SplatValue;
1582     };
1583   }
1584 
1585   // Add replace_lane instructions for any unhandled values
1586   for (size_t I = 0; I < Lanes; ++I) {
1587     const SDValue &Lane = Op->getOperand(I);
1588     if (!Lane.isUndef() && !IsLaneConstructed(I, Lane))
1589       Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VecT, Result, Lane,
1590                            DAG.getConstant(I, DL, MVT::i32));
1591   }
1592 
1593   return Result;
1594 }
1595 
1596 SDValue
1597 WebAssemblyTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
1598                                                SelectionDAG &DAG) const {
1599   SDLoc DL(Op);
1600   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op.getNode())->getMask();
1601   MVT VecType = Op.getOperand(0).getSimpleValueType();
1602   assert(VecType.is128BitVector() && "Unexpected shuffle vector type");
1603   size_t LaneBytes = VecType.getVectorElementType().getSizeInBits() / 8;
1604 
1605   // Space for two vector args and sixteen mask indices
1606   SDValue Ops[18];
1607   size_t OpIdx = 0;
1608   Ops[OpIdx++] = Op.getOperand(0);
1609   Ops[OpIdx++] = Op.getOperand(1);
1610 
1611   // Expand mask indices to byte indices and materialize them as operands
1612   for (int M : Mask) {
1613     for (size_t J = 0; J < LaneBytes; ++J) {
1614       // Lower undefs (represented by -1 in mask) to zero
1615       uint64_t ByteIndex = M == -1 ? 0 : (uint64_t)M * LaneBytes + J;
1616       Ops[OpIdx++] = DAG.getConstant(ByteIndex, DL, MVT::i32);
1617     }
1618   }
1619 
1620   return DAG.getNode(WebAssemblyISD::SHUFFLE, DL, Op.getValueType(), Ops);
1621 }
1622 
1623 SDValue WebAssemblyTargetLowering::LowerSETCC(SDValue Op,
1624                                               SelectionDAG &DAG) const {
1625   SDLoc DL(Op);
1626   // The legalizer does not know how to expand the comparison modes of i64x2
1627   // vectors because no comparison modes are supported. We could solve this by
1628   // expanding all i64x2 SETCC nodes, but that seems to expand f64x2 SETCC nodes
1629   // (which return i64x2 results) as well. So instead we manually unroll i64x2
1630   // comparisons here.
1631   assert(Op->getOperand(0)->getSimpleValueType(0) == MVT::v2i64);
1632   SmallVector<SDValue, 2> LHS, RHS;
1633   DAG.ExtractVectorElements(Op->getOperand(0), LHS);
1634   DAG.ExtractVectorElements(Op->getOperand(1), RHS);
1635   const SDValue &CC = Op->getOperand(2);
1636   auto MakeLane = [&](unsigned I) {
1637     return DAG.getNode(ISD::SELECT_CC, DL, MVT::i64, LHS[I], RHS[I],
1638                        DAG.getConstant(uint64_t(-1), DL, MVT::i64),
1639                        DAG.getConstant(uint64_t(0), DL, MVT::i64), CC);
1640   };
1641   return DAG.getBuildVector(Op->getValueType(0), DL,
1642                             {MakeLane(0), MakeLane(1)});
1643 }
1644 
1645 SDValue
1646 WebAssemblyTargetLowering::LowerAccessVectorElement(SDValue Op,
1647                                                     SelectionDAG &DAG) const {
1648   // Allow constant lane indices, expand variable lane indices
1649   SDNode *IdxNode = Op.getOperand(Op.getNumOperands() - 1).getNode();
1650   if (isa<ConstantSDNode>(IdxNode) || IdxNode->isUndef())
1651     return Op;
1652   else
1653     // Perform default expansion
1654     return SDValue();
1655 }
1656 
1657 static SDValue unrollVectorShift(SDValue Op, SelectionDAG &DAG) {
1658   EVT LaneT = Op.getSimpleValueType().getVectorElementType();
1659   // 32-bit and 64-bit unrolled shifts will have proper semantics
1660   if (LaneT.bitsGE(MVT::i32))
1661     return DAG.UnrollVectorOp(Op.getNode());
1662   // Otherwise mask the shift value to get proper semantics from 32-bit shift
1663   SDLoc DL(Op);
1664   size_t NumLanes = Op.getSimpleValueType().getVectorNumElements();
1665   SDValue Mask = DAG.getConstant(LaneT.getSizeInBits() - 1, DL, MVT::i32);
1666   unsigned ShiftOpcode = Op.getOpcode();
1667   SmallVector<SDValue, 16> ShiftedElements;
1668   DAG.ExtractVectorElements(Op.getOperand(0), ShiftedElements, 0, 0, MVT::i32);
1669   SmallVector<SDValue, 16> ShiftElements;
1670   DAG.ExtractVectorElements(Op.getOperand(1), ShiftElements, 0, 0, MVT::i32);
1671   SmallVector<SDValue, 16> UnrolledOps;
1672   for (size_t i = 0; i < NumLanes; ++i) {
1673     SDValue MaskedShiftValue =
1674         DAG.getNode(ISD::AND, DL, MVT::i32, ShiftElements[i], Mask);
1675     SDValue ShiftedValue = ShiftedElements[i];
1676     if (ShiftOpcode == ISD::SRA)
1677       ShiftedValue = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i32,
1678                                  ShiftedValue, DAG.getValueType(LaneT));
1679     UnrolledOps.push_back(
1680         DAG.getNode(ShiftOpcode, DL, MVT::i32, ShiftedValue, MaskedShiftValue));
1681   }
1682   return DAG.getBuildVector(Op.getValueType(), DL, UnrolledOps);
1683 }
1684 
1685 SDValue WebAssemblyTargetLowering::LowerShift(SDValue Op,
1686                                               SelectionDAG &DAG) const {
1687   SDLoc DL(Op);
1688 
1689   // Only manually lower vector shifts
1690   assert(Op.getSimpleValueType().isVector());
1691 
1692   auto ShiftVal = DAG.getSplatValue(Op.getOperand(1));
1693   if (!ShiftVal)
1694     return unrollVectorShift(Op, DAG);
1695 
1696   // Use anyext because none of the high bits can affect the shift
1697   ShiftVal = DAG.getAnyExtOrTrunc(ShiftVal, DL, MVT::i32);
1698 
1699   unsigned Opcode;
1700   switch (Op.getOpcode()) {
1701   case ISD::SHL:
1702     Opcode = WebAssemblyISD::VEC_SHL;
1703     break;
1704   case ISD::SRA:
1705     Opcode = WebAssemblyISD::VEC_SHR_S;
1706     break;
1707   case ISD::SRL:
1708     Opcode = WebAssemblyISD::VEC_SHR_U;
1709     break;
1710   default:
1711     llvm_unreachable("unexpected opcode");
1712   }
1713 
1714   return DAG.getNode(Opcode, DL, Op.getValueType(), Op.getOperand(0), ShiftVal);
1715 }
1716 
1717 //===----------------------------------------------------------------------===//
1718 //   Custom DAG combine hooks
1719 //===----------------------------------------------------------------------===//
1720 static SDValue
1721 performVECTOR_SHUFFLECombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
1722   auto &DAG = DCI.DAG;
1723   auto Shuffle = cast<ShuffleVectorSDNode>(N);
1724 
1725   // Hoist vector bitcasts that don't change the number of lanes out of unary
1726   // shuffles, where they are less likely to get in the way of other combines.
1727   // (shuffle (vNxT1 (bitcast (vNxT0 x))), undef, mask) ->
1728   //  (vNxT1 (bitcast (vNxT0 (shuffle x, undef, mask))))
1729   SDValue Bitcast = N->getOperand(0);
1730   if (Bitcast.getOpcode() != ISD::BITCAST)
1731     return SDValue();
1732   if (!N->getOperand(1).isUndef())
1733     return SDValue();
1734   SDValue CastOp = Bitcast.getOperand(0);
1735   MVT SrcType = CastOp.getSimpleValueType();
1736   MVT DstType = Bitcast.getSimpleValueType();
1737   if (!SrcType.is128BitVector() ||
1738       SrcType.getVectorNumElements() != DstType.getVectorNumElements())
1739     return SDValue();
1740   SDValue NewShuffle = DAG.getVectorShuffle(
1741       SrcType, SDLoc(N), CastOp, DAG.getUNDEF(SrcType), Shuffle->getMask());
1742   return DAG.getBitcast(DstType, NewShuffle);
1743 }
1744 
1745 SDValue
1746 WebAssemblyTargetLowering::PerformDAGCombine(SDNode *N,
1747                                              DAGCombinerInfo &DCI) const {
1748   switch (N->getOpcode()) {
1749   default:
1750     return SDValue();
1751   case ISD::VECTOR_SHUFFLE:
1752     return performVECTOR_SHUFFLECombine(N, DCI);
1753   }
1754 }
1755