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