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 "Utils/WebAssemblyTypeUtilities.h"
17 #include "Utils/WebAssemblyUtilities.h"
18 #include "WebAssemblyMachineFunctionInfo.h"
19 #include "WebAssemblySubtarget.h"
20 #include "WebAssemblyTargetMachine.h"
21 #include "llvm/CodeGen/CallingConvLower.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineJumpTableInfo.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAG.h"
27 #include "llvm/CodeGen/SelectionDAGNodes.h"
28 #include "llvm/IR/DiagnosticInfo.h"
29 #include "llvm/IR/DiagnosticPrinter.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/IR/IntrinsicsWebAssembly.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/KnownBits.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetOptions.h"
39 using namespace llvm;
40 
41 #define DEBUG_TYPE "wasm-lower"
42 
43 WebAssemblyTargetLowering::WebAssemblyTargetLowering(
44     const TargetMachine &TM, const WebAssemblySubtarget &STI)
45     : TargetLowering(TM), Subtarget(&STI) {
46   auto MVTPtr = Subtarget->hasAddr64() ? MVT::i64 : MVT::i32;
47 
48   // Booleans always contain 0 or 1.
49   setBooleanContents(ZeroOrOneBooleanContent);
50   // Except in SIMD vectors
51   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
52   // We don't know the microarchitecture here, so just reduce register pressure.
53   setSchedulingPreference(Sched::RegPressure);
54   // Tell ISel that we have a stack pointer.
55   setStackPointerRegisterToSaveRestore(
56       Subtarget->hasAddr64() ? WebAssembly::SP64 : WebAssembly::SP32);
57   // Set up the register classes.
58   addRegisterClass(MVT::i32, &WebAssembly::I32RegClass);
59   addRegisterClass(MVT::i64, &WebAssembly::I64RegClass);
60   addRegisterClass(MVT::f32, &WebAssembly::F32RegClass);
61   addRegisterClass(MVT::f64, &WebAssembly::F64RegClass);
62   if (Subtarget->hasSIMD128()) {
63     addRegisterClass(MVT::v16i8, &WebAssembly::V128RegClass);
64     addRegisterClass(MVT::v8i16, &WebAssembly::V128RegClass);
65     addRegisterClass(MVT::v4i32, &WebAssembly::V128RegClass);
66     addRegisterClass(MVT::v4f32, &WebAssembly::V128RegClass);
67     addRegisterClass(MVT::v2i64, &WebAssembly::V128RegClass);
68     addRegisterClass(MVT::v2f64, &WebAssembly::V128RegClass);
69   }
70   if (Subtarget->hasReferenceTypes()) {
71     addRegisterClass(MVT::externref, &WebAssembly::EXTERNREFRegClass);
72     addRegisterClass(MVT::funcref, &WebAssembly::FUNCREFRegClass);
73   }
74   // Compute derived properties from the register classes.
75   computeRegisterProperties(Subtarget->getRegisterInfo());
76 
77   // Transform loads and stores to pointers in address space 1 to loads and
78   // stores to WebAssembly global variables, outside linear memory.
79   for (auto T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64}) {
80     setOperationAction(ISD::LOAD, T, Custom);
81     setOperationAction(ISD::STORE, T, Custom);
82   }
83   if (Subtarget->hasSIMD128()) {
84     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
85                    MVT::v2f64}) {
86       setOperationAction(ISD::LOAD, T, Custom);
87       setOperationAction(ISD::STORE, T, Custom);
88     }
89   }
90   if (Subtarget->hasReferenceTypes()) {
91     for (auto T : {MVT::externref, MVT::funcref}) {
92       setOperationAction(ISD::LOAD, T, Custom);
93       setOperationAction(ISD::STORE, T, Custom);
94     }
95   }
96 
97   setOperationAction(ISD::GlobalAddress, MVTPtr, Custom);
98   setOperationAction(ISD::GlobalTLSAddress, MVTPtr, Custom);
99   setOperationAction(ISD::ExternalSymbol, MVTPtr, Custom);
100   setOperationAction(ISD::JumpTable, MVTPtr, Custom);
101   setOperationAction(ISD::BlockAddress, MVTPtr, Custom);
102   setOperationAction(ISD::BRIND, MVT::Other, Custom);
103 
104   // Take the default expansion for va_arg, va_copy, and va_end. There is no
105   // default action for va_start, so we do that custom.
106   setOperationAction(ISD::VASTART, MVT::Other, Custom);
107   setOperationAction(ISD::VAARG, MVT::Other, Expand);
108   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
109   setOperationAction(ISD::VAEND, MVT::Other, Expand);
110 
111   for (auto T : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
112     // Don't expand the floating-point types to constant pools.
113     setOperationAction(ISD::ConstantFP, T, Legal);
114     // Expand floating-point comparisons.
115     for (auto CC : {ISD::SETO, ISD::SETUO, ISD::SETUEQ, ISD::SETONE,
116                     ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE})
117       setCondCodeAction(CC, T, Expand);
118     // Expand floating-point library function operators.
119     for (auto Op :
120          {ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FREM, ISD::FMA})
121       setOperationAction(Op, T, Expand);
122     // Note supported floating-point library function operators that otherwise
123     // default to expand.
124     for (auto Op :
125          {ISD::FCEIL, ISD::FFLOOR, ISD::FTRUNC, ISD::FNEARBYINT, ISD::FRINT})
126       setOperationAction(Op, T, Legal);
127     // Support minimum and maximum, which otherwise default to expand.
128     setOperationAction(ISD::FMINIMUM, T, Legal);
129     setOperationAction(ISD::FMAXIMUM, T, Legal);
130     // WebAssembly currently has no builtin f16 support.
131     setOperationAction(ISD::FP16_TO_FP, T, Expand);
132     setOperationAction(ISD::FP_TO_FP16, T, Expand);
133     setLoadExtAction(ISD::EXTLOAD, T, MVT::f16, Expand);
134     setTruncStoreAction(T, MVT::f16, Expand);
135   }
136 
137   // Expand unavailable integer operations.
138   for (auto Op :
139        {ISD::BSWAP, ISD::SMUL_LOHI, ISD::UMUL_LOHI, ISD::MULHS, ISD::MULHU,
140         ISD::SDIVREM, ISD::UDIVREM, ISD::SHL_PARTS, ISD::SRA_PARTS,
141         ISD::SRL_PARTS, ISD::ADDC, ISD::ADDE, ISD::SUBC, ISD::SUBE}) {
142     for (auto T : {MVT::i32, MVT::i64})
143       setOperationAction(Op, T, Expand);
144     if (Subtarget->hasSIMD128())
145       for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64})
146         setOperationAction(Op, T, Expand);
147   }
148 
149   if (Subtarget->hasNontrappingFPToInt())
150     for (auto Op : {ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT})
151       for (auto T : {MVT::i32, MVT::i64})
152         setOperationAction(Op, T, Custom);
153 
154   // SIMD-specific configuration
155   if (Subtarget->hasSIMD128()) {
156     // Hoist bitcasts out of shuffles
157     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
158 
159     // Combine extends of extract_subvectors into widening ops
160     setTargetDAGCombine(ISD::SIGN_EXTEND);
161     setTargetDAGCombine(ISD::ZERO_EXTEND);
162 
163     // Combine int_to_fp or fp_extend of extract_vectors and vice versa into
164     // conversions ops
165     setTargetDAGCombine(ISD::SINT_TO_FP);
166     setTargetDAGCombine(ISD::UINT_TO_FP);
167     setTargetDAGCombine(ISD::FP_EXTEND);
168     setTargetDAGCombine(ISD::EXTRACT_SUBVECTOR);
169 
170     // Combine fp_to_{s,u}int_sat or fp_round of concat_vectors or vice versa
171     // into conversion ops
172     setTargetDAGCombine(ISD::FP_TO_SINT_SAT);
173     setTargetDAGCombine(ISD::FP_TO_UINT_SAT);
174     setTargetDAGCombine(ISD::FP_ROUND);
175     setTargetDAGCombine(ISD::CONCAT_VECTORS);
176 
177     // Support saturating add for i8x16 and i16x8
178     for (auto Op : {ISD::SADDSAT, ISD::UADDSAT})
179       for (auto T : {MVT::v16i8, MVT::v8i16})
180         setOperationAction(Op, T, Legal);
181 
182     // Support integer abs
183     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64})
184       setOperationAction(ISD::ABS, T, Legal);
185 
186     // Custom lower BUILD_VECTORs to minimize number of replace_lanes
187     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
188                    MVT::v2f64})
189       setOperationAction(ISD::BUILD_VECTOR, T, Custom);
190 
191     // We have custom shuffle lowering to expose the shuffle mask
192     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
193                    MVT::v2f64})
194       setOperationAction(ISD::VECTOR_SHUFFLE, T, Custom);
195 
196     // Custom lowering since wasm shifts must have a scalar shift amount
197     for (auto Op : {ISD::SHL, ISD::SRA, ISD::SRL})
198       for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64})
199         setOperationAction(Op, T, Custom);
200 
201     // Custom lower lane accesses to expand out variable indices
202     for (auto Op : {ISD::EXTRACT_VECTOR_ELT, ISD::INSERT_VECTOR_ELT})
203       for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
204                      MVT::v2f64})
205         setOperationAction(Op, T, Custom);
206 
207     // There is no i8x16.mul instruction
208     setOperationAction(ISD::MUL, MVT::v16i8, Expand);
209 
210     // There is no vector conditional select instruction
211     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
212                    MVT::v2f64})
213       setOperationAction(ISD::SELECT_CC, T, Expand);
214 
215     // Expand integer operations supported for scalars but not SIMD
216     for (auto Op : {ISD::CTLZ, ISD::CTTZ, ISD::CTPOP, ISD::SDIV, ISD::UDIV,
217                     ISD::SREM, ISD::UREM, ISD::ROTL, ISD::ROTR})
218       for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64})
219         setOperationAction(Op, T, Expand);
220 
221     // But we do have integer min and max operations
222     for (auto Op : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
223       for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
224         setOperationAction(Op, T, Legal);
225 
226     // And we have popcnt for i8x16
227     setOperationAction(ISD::CTPOP, MVT::v16i8, Legal);
228 
229     // Expand float operations supported for scalars but not SIMD
230     for (auto Op : {ISD::FCOPYSIGN, ISD::FLOG, ISD::FLOG2, ISD::FLOG10,
231                     ISD::FEXP, ISD::FEXP2, ISD::FRINT})
232       for (auto T : {MVT::v4f32, MVT::v2f64})
233         setOperationAction(Op, T, Expand);
234 
235     // Unsigned comparison operations are unavailable for i64x2 vectors.
236     for (auto CC : {ISD::SETUGT, ISD::SETUGE, ISD::SETULT, ISD::SETULE})
237       setCondCodeAction(CC, MVT::v2i64, Custom);
238 
239     // 64x2 conversions are not in the spec
240     for (auto Op :
241          {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT})
242       for (auto T : {MVT::v2i64, MVT::v2f64})
243         setOperationAction(Op, T, Expand);
244 
245     // But saturating fp_to_int converstions are
246     for (auto Op : {ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT})
247       setOperationAction(Op, MVT::v4i32, Custom);
248   }
249 
250   // As a special case, these operators use the type to mean the type to
251   // sign-extend from.
252   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
253   if (!Subtarget->hasSignExt()) {
254     // Sign extends are legal only when extending a vector extract
255     auto Action = Subtarget->hasSIMD128() ? Custom : Expand;
256     for (auto T : {MVT::i8, MVT::i16, MVT::i32})
257       setOperationAction(ISD::SIGN_EXTEND_INREG, T, Action);
258   }
259   for (auto T : MVT::integer_fixedlen_vector_valuetypes())
260     setOperationAction(ISD::SIGN_EXTEND_INREG, T, Expand);
261 
262   // Dynamic stack allocation: use the default expansion.
263   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
264   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
265   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVTPtr, Expand);
266 
267   setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
268   setOperationAction(ISD::FrameIndex, MVT::i64, Custom);
269   setOperationAction(ISD::CopyToReg, MVT::Other, Custom);
270 
271   // Expand these forms; we pattern-match the forms that we can handle in isel.
272   for (auto T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64})
273     for (auto Op : {ISD::BR_CC, ISD::SELECT_CC})
274       setOperationAction(Op, T, Expand);
275 
276   // We have custom switch handling.
277   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
278 
279   // WebAssembly doesn't have:
280   //  - Floating-point extending loads.
281   //  - Floating-point truncating stores.
282   //  - i1 extending loads.
283   //  - truncating SIMD stores and most extending loads
284   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
285   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
286   for (auto T : MVT::integer_valuetypes())
287     for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD})
288       setLoadExtAction(Ext, T, MVT::i1, Promote);
289   if (Subtarget->hasSIMD128()) {
290     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64, MVT::v4f32,
291                    MVT::v2f64}) {
292       for (auto MemT : MVT::fixedlen_vector_valuetypes()) {
293         if (MVT(T) != MemT) {
294           setTruncStoreAction(T, MemT, Expand);
295           for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD})
296             setLoadExtAction(Ext, T, MemT, Expand);
297         }
298       }
299     }
300     // But some vector extending loads are legal
301     for (auto Ext : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) {
302       setLoadExtAction(Ext, MVT::v8i16, MVT::v8i8, Legal);
303       setLoadExtAction(Ext, MVT::v4i32, MVT::v4i16, Legal);
304       setLoadExtAction(Ext, MVT::v2i64, MVT::v2i32, Legal);
305     }
306     setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f32, Legal);
307   }
308 
309   // Don't do anything clever with build_pairs
310   setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
311 
312   // Trap lowers to wasm unreachable
313   setOperationAction(ISD::TRAP, MVT::Other, Legal);
314   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
315 
316   // Exception handling intrinsics
317   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
318   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
319   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
320 
321   setMaxAtomicSizeInBitsSupported(64);
322 
323   // Override the __gnu_f2h_ieee/__gnu_h2f_ieee names so that the f32 name is
324   // consistent with the f64 and f128 names.
325   setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
326   setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
327 
328   // Define the emscripten name for return address helper.
329   // TODO: when implementing other Wasm backends, make this generic or only do
330   // this on emscripten depending on what they end up doing.
331   setLibcallName(RTLIB::RETURN_ADDRESS, "emscripten_return_address");
332 
333   // Always convert switches to br_tables unless there is only one case, which
334   // is equivalent to a simple branch. This reduces code size for wasm, and we
335   // defer possible jump table optimizations to the VM.
336   setMinimumJumpTableEntries(2);
337 }
338 
339 MVT WebAssemblyTargetLowering::getPointerTy(const DataLayout &DL,
340                                             uint32_t AS) const {
341   if (AS == WebAssembly::WasmAddressSpace::WASM_ADDRESS_SPACE_EXTERNREF)
342     return MVT::externref;
343   if (AS == WebAssembly::WasmAddressSpace::WASM_ADDRESS_SPACE_FUNCREF)
344     return MVT::funcref;
345   return TargetLowering::getPointerTy(DL, AS);
346 }
347 
348 MVT WebAssemblyTargetLowering::getPointerMemTy(const DataLayout &DL,
349                                                uint32_t AS) const {
350   if (AS == WebAssembly::WasmAddressSpace::WASM_ADDRESS_SPACE_EXTERNREF)
351     return MVT::externref;
352   if (AS == WebAssembly::WasmAddressSpace::WASM_ADDRESS_SPACE_FUNCREF)
353     return MVT::funcref;
354   return TargetLowering::getPointerMemTy(DL, AS);
355 }
356 
357 TargetLowering::AtomicExpansionKind
358 WebAssemblyTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
359   // We have wasm instructions for these
360   switch (AI->getOperation()) {
361   case AtomicRMWInst::Add:
362   case AtomicRMWInst::Sub:
363   case AtomicRMWInst::And:
364   case AtomicRMWInst::Or:
365   case AtomicRMWInst::Xor:
366   case AtomicRMWInst::Xchg:
367     return AtomicExpansionKind::None;
368   default:
369     break;
370   }
371   return AtomicExpansionKind::CmpXChg;
372 }
373 
374 bool WebAssemblyTargetLowering::shouldScalarizeBinop(SDValue VecOp) const {
375   // Implementation copied from X86TargetLowering.
376   unsigned Opc = VecOp.getOpcode();
377 
378   // Assume target opcodes can't be scalarized.
379   // TODO - do we have any exceptions?
380   if (Opc >= ISD::BUILTIN_OP_END)
381     return false;
382 
383   // If the vector op is not supported, try to convert to scalar.
384   EVT VecVT = VecOp.getValueType();
385   if (!isOperationLegalOrCustomOrPromote(Opc, VecVT))
386     return true;
387 
388   // If the vector op is supported, but the scalar op is not, the transform may
389   // not be worthwhile.
390   EVT ScalarVT = VecVT.getScalarType();
391   return isOperationLegalOrCustomOrPromote(Opc, ScalarVT);
392 }
393 
394 FastISel *WebAssemblyTargetLowering::createFastISel(
395     FunctionLoweringInfo &FuncInfo, const TargetLibraryInfo *LibInfo) const {
396   return WebAssembly::createFastISel(FuncInfo, LibInfo);
397 }
398 
399 MVT WebAssemblyTargetLowering::getScalarShiftAmountTy(const DataLayout & /*DL*/,
400                                                       EVT VT) const {
401   unsigned BitWidth = NextPowerOf2(VT.getSizeInBits() - 1);
402   if (BitWidth > 1 && BitWidth < 8)
403     BitWidth = 8;
404 
405   if (BitWidth > 64) {
406     // The shift will be lowered to a libcall, and compiler-rt libcalls expect
407     // the count to be an i32.
408     BitWidth = 32;
409     assert(BitWidth >= Log2_32_Ceil(VT.getSizeInBits()) &&
410            "32-bit shift counts ought to be enough for anyone");
411   }
412 
413   MVT Result = MVT::getIntegerVT(BitWidth);
414   assert(Result != MVT::INVALID_SIMPLE_VALUE_TYPE &&
415          "Unable to represent scalar shift amount type");
416   return Result;
417 }
418 
419 // Lower an fp-to-int conversion operator from the LLVM opcode, which has an
420 // undefined result on invalid/overflow, to the WebAssembly opcode, which
421 // traps on invalid/overflow.
422 static MachineBasicBlock *LowerFPToInt(MachineInstr &MI, DebugLoc DL,
423                                        MachineBasicBlock *BB,
424                                        const TargetInstrInfo &TII,
425                                        bool IsUnsigned, bool Int64,
426                                        bool Float64, unsigned LoweredOpcode) {
427   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
428 
429   Register OutReg = MI.getOperand(0).getReg();
430   Register InReg = MI.getOperand(1).getReg();
431 
432   unsigned Abs = Float64 ? WebAssembly::ABS_F64 : WebAssembly::ABS_F32;
433   unsigned FConst = Float64 ? WebAssembly::CONST_F64 : WebAssembly::CONST_F32;
434   unsigned LT = Float64 ? WebAssembly::LT_F64 : WebAssembly::LT_F32;
435   unsigned GE = Float64 ? WebAssembly::GE_F64 : WebAssembly::GE_F32;
436   unsigned IConst = Int64 ? WebAssembly::CONST_I64 : WebAssembly::CONST_I32;
437   unsigned Eqz = WebAssembly::EQZ_I32;
438   unsigned And = WebAssembly::AND_I32;
439   int64_t Limit = Int64 ? INT64_MIN : INT32_MIN;
440   int64_t Substitute = IsUnsigned ? 0 : Limit;
441   double CmpVal = IsUnsigned ? -(double)Limit * 2.0 : -(double)Limit;
442   auto &Context = BB->getParent()->getFunction().getContext();
443   Type *Ty = Float64 ? Type::getDoubleTy(Context) : Type::getFloatTy(Context);
444 
445   const BasicBlock *LLVMBB = BB->getBasicBlock();
446   MachineFunction *F = BB->getParent();
447   MachineBasicBlock *TrueMBB = F->CreateMachineBasicBlock(LLVMBB);
448   MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(LLVMBB);
449   MachineBasicBlock *DoneMBB = F->CreateMachineBasicBlock(LLVMBB);
450 
451   MachineFunction::iterator It = ++BB->getIterator();
452   F->insert(It, FalseMBB);
453   F->insert(It, TrueMBB);
454   F->insert(It, DoneMBB);
455 
456   // Transfer the remainder of BB and its successor edges to DoneMBB.
457   DoneMBB->splice(DoneMBB->begin(), BB, std::next(MI.getIterator()), BB->end());
458   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
459 
460   BB->addSuccessor(TrueMBB);
461   BB->addSuccessor(FalseMBB);
462   TrueMBB->addSuccessor(DoneMBB);
463   FalseMBB->addSuccessor(DoneMBB);
464 
465   unsigned Tmp0, Tmp1, CmpReg, EqzReg, FalseReg, TrueReg;
466   Tmp0 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
467   Tmp1 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
468   CmpReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
469   EqzReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
470   FalseReg = MRI.createVirtualRegister(MRI.getRegClass(OutReg));
471   TrueReg = MRI.createVirtualRegister(MRI.getRegClass(OutReg));
472 
473   MI.eraseFromParent();
474   // For signed numbers, we can do a single comparison to determine whether
475   // fabs(x) is within range.
476   if (IsUnsigned) {
477     Tmp0 = InReg;
478   } else {
479     BuildMI(BB, DL, TII.get(Abs), Tmp0).addReg(InReg);
480   }
481   BuildMI(BB, DL, TII.get(FConst), Tmp1)
482       .addFPImm(cast<ConstantFP>(ConstantFP::get(Ty, CmpVal)));
483   BuildMI(BB, DL, TII.get(LT), CmpReg).addReg(Tmp0).addReg(Tmp1);
484 
485   // For unsigned numbers, we have to do a separate comparison with zero.
486   if (IsUnsigned) {
487     Tmp1 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
488     Register SecondCmpReg =
489         MRI.createVirtualRegister(&WebAssembly::I32RegClass);
490     Register AndReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
491     BuildMI(BB, DL, TII.get(FConst), Tmp1)
492         .addFPImm(cast<ConstantFP>(ConstantFP::get(Ty, 0.0)));
493     BuildMI(BB, DL, TII.get(GE), SecondCmpReg).addReg(Tmp0).addReg(Tmp1);
494     BuildMI(BB, DL, TII.get(And), AndReg).addReg(CmpReg).addReg(SecondCmpReg);
495     CmpReg = AndReg;
496   }
497 
498   BuildMI(BB, DL, TII.get(Eqz), EqzReg).addReg(CmpReg);
499 
500   // Create the CFG diamond to select between doing the conversion or using
501   // the substitute value.
502   BuildMI(BB, DL, TII.get(WebAssembly::BR_IF)).addMBB(TrueMBB).addReg(EqzReg);
503   BuildMI(FalseMBB, DL, TII.get(LoweredOpcode), FalseReg).addReg(InReg);
504   BuildMI(FalseMBB, DL, TII.get(WebAssembly::BR)).addMBB(DoneMBB);
505   BuildMI(TrueMBB, DL, TII.get(IConst), TrueReg).addImm(Substitute);
506   BuildMI(*DoneMBB, DoneMBB->begin(), DL, TII.get(TargetOpcode::PHI), OutReg)
507       .addReg(FalseReg)
508       .addMBB(FalseMBB)
509       .addReg(TrueReg)
510       .addMBB(TrueMBB);
511 
512   return DoneMBB;
513 }
514 
515 static MachineBasicBlock *
516 LowerCallResults(MachineInstr &CallResults, DebugLoc DL, MachineBasicBlock *BB,
517                  const WebAssemblySubtarget *Subtarget,
518                  const TargetInstrInfo &TII) {
519   MachineInstr &CallParams = *CallResults.getPrevNode();
520   assert(CallParams.getOpcode() == WebAssembly::CALL_PARAMS);
521   assert(CallResults.getOpcode() == WebAssembly::CALL_RESULTS ||
522          CallResults.getOpcode() == WebAssembly::RET_CALL_RESULTS);
523 
524   bool IsIndirect = CallParams.getOperand(0).isReg();
525   bool IsRetCall = CallResults.getOpcode() == WebAssembly::RET_CALL_RESULTS;
526 
527   bool IsFuncrefCall = false;
528   if (IsIndirect) {
529     Register Reg = CallParams.getOperand(0).getReg();
530     const MachineFunction *MF = BB->getParent();
531     const MachineRegisterInfo &MRI = MF->getRegInfo();
532     const TargetRegisterClass *TRC = MRI.getRegClass(Reg);
533     IsFuncrefCall = (TRC == &WebAssembly::FUNCREFRegClass);
534     assert(!IsFuncrefCall || Subtarget->hasReferenceTypes());
535   }
536 
537   unsigned CallOp;
538   if (IsIndirect && IsRetCall) {
539     CallOp = WebAssembly::RET_CALL_INDIRECT;
540   } else if (IsIndirect) {
541     CallOp = WebAssembly::CALL_INDIRECT;
542   } else if (IsRetCall) {
543     CallOp = WebAssembly::RET_CALL;
544   } else {
545     CallOp = WebAssembly::CALL;
546   }
547 
548   MachineFunction &MF = *BB->getParent();
549   const MCInstrDesc &MCID = TII.get(CallOp);
550   MachineInstrBuilder MIB(MF, MF.CreateMachineInstr(MCID, DL));
551 
552   // See if we must truncate the function pointer.
553   // CALL_INDIRECT takes an i32, but in wasm64 we represent function pointers
554   // as 64-bit for uniformity with other pointer types.
555   // See also: WebAssemblyFastISel::selectCall
556   if (IsIndirect && MF.getSubtarget<WebAssemblySubtarget>().hasAddr64()) {
557     Register Reg32 =
558         MF.getRegInfo().createVirtualRegister(&WebAssembly::I32RegClass);
559     auto &FnPtr = CallParams.getOperand(0);
560     BuildMI(*BB, CallResults.getIterator(), DL,
561             TII.get(WebAssembly::I32_WRAP_I64), Reg32)
562         .addReg(FnPtr.getReg());
563     FnPtr.setReg(Reg32);
564   }
565 
566   // Move the function pointer to the end of the arguments for indirect calls
567   if (IsIndirect) {
568     auto FnPtr = CallParams.getOperand(0);
569     CallParams.RemoveOperand(0);
570     CallParams.addOperand(FnPtr);
571   }
572 
573   for (auto Def : CallResults.defs())
574     MIB.add(Def);
575 
576   if (IsIndirect) {
577     // Placeholder for the type index.
578     MIB.addImm(0);
579     // The table into which this call_indirect indexes.
580     MCSymbolWasm *Table = IsFuncrefCall
581                               ? WebAssembly::getOrCreateFuncrefCallTableSymbol(
582                                     MF.getContext(), Subtarget)
583                               : WebAssembly::getOrCreateFunctionTableSymbol(
584                                     MF.getContext(), Subtarget);
585     if (Subtarget->hasReferenceTypes()) {
586       MIB.addSym(Table);
587     } else {
588       // For the MVP there is at most one table whose number is 0, but we can't
589       // write a table symbol or issue relocations.  Instead we just ensure the
590       // table is live and write a zero.
591       Table->setNoStrip();
592       MIB.addImm(0);
593     }
594   }
595 
596   for (auto Use : CallParams.uses())
597     MIB.add(Use);
598 
599   BB->insert(CallResults.getIterator(), MIB);
600   CallParams.eraseFromParent();
601   CallResults.eraseFromParent();
602 
603   // If this is a funcref call, to avoid hidden GC roots, we need to clear the
604   // table slot with ref.null upon call_indirect return.
605   //
606   // This generates the following code, which comes right after a call_indirect
607   // of a funcref:
608   //
609   //    i32.const 0
610   //    ref.null func
611   //    table.set __funcref_call_table
612   if (IsIndirect && IsFuncrefCall) {
613     MCSymbolWasm *Table = WebAssembly::getOrCreateFuncrefCallTableSymbol(
614         MF.getContext(), Subtarget);
615     Register RegZero =
616         MF.getRegInfo().createVirtualRegister(&WebAssembly::I32RegClass);
617     MachineInstr *Const0 =
618         BuildMI(MF, DL, TII.get(WebAssembly::CONST_I32), RegZero).addImm(0);
619     BB->insertAfter(MIB.getInstr()->getIterator(), Const0);
620 
621     Register RegFuncref =
622         MF.getRegInfo().createVirtualRegister(&WebAssembly::FUNCREFRegClass);
623     MachineInstr *RefNull =
624         BuildMI(MF, DL, TII.get(WebAssembly::REF_NULL_FUNCREF), RegFuncref)
625             .addImm(static_cast<int32_t>(WebAssembly::HeapType::Funcref));
626     BB->insertAfter(Const0->getIterator(), RefNull);
627 
628     MachineInstr *TableSet =
629         BuildMI(MF, DL, TII.get(WebAssembly::TABLE_SET_FUNCREF))
630             .addSym(Table)
631             .addReg(RegZero)
632             .addReg(RegFuncref);
633     BB->insertAfter(RefNull->getIterator(), TableSet);
634   }
635 
636   return BB;
637 }
638 
639 MachineBasicBlock *WebAssemblyTargetLowering::EmitInstrWithCustomInserter(
640     MachineInstr &MI, MachineBasicBlock *BB) const {
641   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
642   DebugLoc DL = MI.getDebugLoc();
643 
644   switch (MI.getOpcode()) {
645   default:
646     llvm_unreachable("Unexpected instr type to insert");
647   case WebAssembly::FP_TO_SINT_I32_F32:
648     return LowerFPToInt(MI, DL, BB, TII, false, false, false,
649                         WebAssembly::I32_TRUNC_S_F32);
650   case WebAssembly::FP_TO_UINT_I32_F32:
651     return LowerFPToInt(MI, DL, BB, TII, true, false, false,
652                         WebAssembly::I32_TRUNC_U_F32);
653   case WebAssembly::FP_TO_SINT_I64_F32:
654     return LowerFPToInt(MI, DL, BB, TII, false, true, false,
655                         WebAssembly::I64_TRUNC_S_F32);
656   case WebAssembly::FP_TO_UINT_I64_F32:
657     return LowerFPToInt(MI, DL, BB, TII, true, true, false,
658                         WebAssembly::I64_TRUNC_U_F32);
659   case WebAssembly::FP_TO_SINT_I32_F64:
660     return LowerFPToInt(MI, DL, BB, TII, false, false, true,
661                         WebAssembly::I32_TRUNC_S_F64);
662   case WebAssembly::FP_TO_UINT_I32_F64:
663     return LowerFPToInt(MI, DL, BB, TII, true, false, true,
664                         WebAssembly::I32_TRUNC_U_F64);
665   case WebAssembly::FP_TO_SINT_I64_F64:
666     return LowerFPToInt(MI, DL, BB, TII, false, true, true,
667                         WebAssembly::I64_TRUNC_S_F64);
668   case WebAssembly::FP_TO_UINT_I64_F64:
669     return LowerFPToInt(MI, DL, BB, TII, true, true, true,
670                         WebAssembly::I64_TRUNC_U_F64);
671   case WebAssembly::CALL_RESULTS:
672   case WebAssembly::RET_CALL_RESULTS:
673     return LowerCallResults(MI, DL, BB, Subtarget, TII);
674   }
675 }
676 
677 const char *
678 WebAssemblyTargetLowering::getTargetNodeName(unsigned Opcode) const {
679   switch (static_cast<WebAssemblyISD::NodeType>(Opcode)) {
680   case WebAssemblyISD::FIRST_NUMBER:
681   case WebAssemblyISD::FIRST_MEM_OPCODE:
682     break;
683 #define HANDLE_NODETYPE(NODE)                                                  \
684   case WebAssemblyISD::NODE:                                                   \
685     return "WebAssemblyISD::" #NODE;
686 #define HANDLE_MEM_NODETYPE(NODE) HANDLE_NODETYPE(NODE)
687 #include "WebAssemblyISD.def"
688 #undef HANDLE_MEM_NODETYPE
689 #undef HANDLE_NODETYPE
690   }
691   return nullptr;
692 }
693 
694 std::pair<unsigned, const TargetRegisterClass *>
695 WebAssemblyTargetLowering::getRegForInlineAsmConstraint(
696     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
697   // First, see if this is a constraint that directly corresponds to a
698   // WebAssembly register class.
699   if (Constraint.size() == 1) {
700     switch (Constraint[0]) {
701     case 'r':
702       assert(VT != MVT::iPTR && "Pointer MVT not expected here");
703       if (Subtarget->hasSIMD128() && VT.isVector()) {
704         if (VT.getSizeInBits() == 128)
705           return std::make_pair(0U, &WebAssembly::V128RegClass);
706       }
707       if (VT.isInteger() && !VT.isVector()) {
708         if (VT.getSizeInBits() <= 32)
709           return std::make_pair(0U, &WebAssembly::I32RegClass);
710         if (VT.getSizeInBits() <= 64)
711           return std::make_pair(0U, &WebAssembly::I64RegClass);
712       }
713       if (VT.isFloatingPoint() && !VT.isVector()) {
714         switch (VT.getSizeInBits()) {
715         case 32:
716           return std::make_pair(0U, &WebAssembly::F32RegClass);
717         case 64:
718           return std::make_pair(0U, &WebAssembly::F64RegClass);
719         default:
720           break;
721         }
722       }
723       break;
724     default:
725       break;
726     }
727   }
728 
729   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
730 }
731 
732 bool WebAssemblyTargetLowering::isCheapToSpeculateCttz() const {
733   // Assume ctz is a relatively cheap operation.
734   return true;
735 }
736 
737 bool WebAssemblyTargetLowering::isCheapToSpeculateCtlz() const {
738   // Assume clz is a relatively cheap operation.
739   return true;
740 }
741 
742 bool WebAssemblyTargetLowering::isLegalAddressingMode(const DataLayout &DL,
743                                                       const AddrMode &AM,
744                                                       Type *Ty, unsigned AS,
745                                                       Instruction *I) const {
746   // WebAssembly offsets are added as unsigned without wrapping. The
747   // isLegalAddressingMode gives us no way to determine if wrapping could be
748   // happening, so we approximate this by accepting only non-negative offsets.
749   if (AM.BaseOffs < 0)
750     return false;
751 
752   // WebAssembly has no scale register operands.
753   if (AM.Scale != 0)
754     return false;
755 
756   // Everything else is legal.
757   return true;
758 }
759 
760 bool WebAssemblyTargetLowering::allowsMisalignedMemoryAccesses(
761     EVT /*VT*/, unsigned /*AddrSpace*/, Align /*Align*/,
762     MachineMemOperand::Flags /*Flags*/, bool *Fast) const {
763   // WebAssembly supports unaligned accesses, though it should be declared
764   // with the p2align attribute on loads and stores which do so, and there
765   // may be a performance impact. We tell LLVM they're "fast" because
766   // for the kinds of things that LLVM uses this for (merging adjacent stores
767   // of constants, etc.), WebAssembly implementations will either want the
768   // unaligned access or they'll split anyway.
769   if (Fast)
770     *Fast = true;
771   return true;
772 }
773 
774 bool WebAssemblyTargetLowering::isIntDivCheap(EVT VT,
775                                               AttributeList Attr) const {
776   // The current thinking is that wasm engines will perform this optimization,
777   // so we can save on code size.
778   return true;
779 }
780 
781 bool WebAssemblyTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
782   EVT ExtT = ExtVal.getValueType();
783   EVT MemT = cast<LoadSDNode>(ExtVal->getOperand(0))->getValueType(0);
784   return (ExtT == MVT::v8i16 && MemT == MVT::v8i8) ||
785          (ExtT == MVT::v4i32 && MemT == MVT::v4i16) ||
786          (ExtT == MVT::v2i64 && MemT == MVT::v2i32);
787 }
788 
789 bool WebAssemblyTargetLowering::isOffsetFoldingLegal(
790     const GlobalAddressSDNode *GA) const {
791   // Wasm doesn't support function addresses with offsets
792   const GlobalValue *GV = GA->getGlobal();
793   return isa<Function>(GV) ? false : TargetLowering::isOffsetFoldingLegal(GA);
794 }
795 
796 EVT WebAssemblyTargetLowering::getSetCCResultType(const DataLayout &DL,
797                                                   LLVMContext &C,
798                                                   EVT VT) const {
799   if (VT.isVector())
800     return VT.changeVectorElementTypeToInteger();
801 
802   // So far, all branch instructions in Wasm take an I32 condition.
803   // The default TargetLowering::getSetCCResultType returns the pointer size,
804   // which would be useful to reduce instruction counts when testing
805   // against 64-bit pointers/values if at some point Wasm supports that.
806   return EVT::getIntegerVT(C, 32);
807 }
808 
809 bool WebAssemblyTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
810                                                    const CallInst &I,
811                                                    MachineFunction &MF,
812                                                    unsigned Intrinsic) const {
813   switch (Intrinsic) {
814   case Intrinsic::wasm_memory_atomic_notify:
815     Info.opc = ISD::INTRINSIC_W_CHAIN;
816     Info.memVT = MVT::i32;
817     Info.ptrVal = I.getArgOperand(0);
818     Info.offset = 0;
819     Info.align = Align(4);
820     // atomic.notify instruction does not really load the memory specified with
821     // this argument, but MachineMemOperand should either be load or store, so
822     // we set this to a load.
823     // FIXME Volatile isn't really correct, but currently all LLVM atomic
824     // instructions are treated as volatiles in the backend, so we should be
825     // consistent. The same applies for wasm_atomic_wait intrinsics too.
826     Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
827     return true;
828   case Intrinsic::wasm_memory_atomic_wait32:
829     Info.opc = ISD::INTRINSIC_W_CHAIN;
830     Info.memVT = MVT::i32;
831     Info.ptrVal = I.getArgOperand(0);
832     Info.offset = 0;
833     Info.align = Align(4);
834     Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
835     return true;
836   case Intrinsic::wasm_memory_atomic_wait64:
837     Info.opc = ISD::INTRINSIC_W_CHAIN;
838     Info.memVT = MVT::i64;
839     Info.ptrVal = I.getArgOperand(0);
840     Info.offset = 0;
841     Info.align = Align(8);
842     Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
843     return true;
844   default:
845     return false;
846   }
847 }
848 
849 void WebAssemblyTargetLowering::computeKnownBitsForTargetNode(
850     const SDValue Op, KnownBits &Known, const APInt &DemandedElts,
851     const SelectionDAG &DAG, unsigned Depth) const {
852   switch (Op.getOpcode()) {
853   default:
854     break;
855   case ISD::INTRINSIC_WO_CHAIN: {
856     unsigned IntNo = Op.getConstantOperandVal(0);
857     switch (IntNo) {
858     default:
859       break;
860     case Intrinsic::wasm_bitmask: {
861       unsigned BitWidth = Known.getBitWidth();
862       EVT VT = Op.getOperand(1).getSimpleValueType();
863       unsigned PossibleBits = VT.getVectorNumElements();
864       APInt ZeroMask = APInt::getHighBitsSet(BitWidth, BitWidth - PossibleBits);
865       Known.Zero |= ZeroMask;
866       break;
867     }
868     }
869   }
870   }
871 }
872 
873 TargetLoweringBase::LegalizeTypeAction
874 WebAssemblyTargetLowering::getPreferredVectorAction(MVT VT) const {
875   if (VT.isFixedLengthVector()) {
876     MVT EltVT = VT.getVectorElementType();
877     // We have legal vector types with these lane types, so widening the
878     // vector would let us use some of the lanes directly without having to
879     // extend or truncate values.
880     if (EltVT == MVT::i8 || EltVT == MVT::i16 || EltVT == MVT::i32 ||
881         EltVT == MVT::i64 || EltVT == MVT::f32 || EltVT == MVT::f64)
882       return TypeWidenVector;
883   }
884 
885   return TargetLoweringBase::getPreferredVectorAction(VT);
886 }
887 
888 //===----------------------------------------------------------------------===//
889 // WebAssembly Lowering private implementation.
890 //===----------------------------------------------------------------------===//
891 
892 //===----------------------------------------------------------------------===//
893 // Lowering Code
894 //===----------------------------------------------------------------------===//
895 
896 static void fail(const SDLoc &DL, SelectionDAG &DAG, const char *Msg) {
897   MachineFunction &MF = DAG.getMachineFunction();
898   DAG.getContext()->diagnose(
899       DiagnosticInfoUnsupported(MF.getFunction(), Msg, DL.getDebugLoc()));
900 }
901 
902 // Test whether the given calling convention is supported.
903 static bool callingConvSupported(CallingConv::ID CallConv) {
904   // We currently support the language-independent target-independent
905   // conventions. We don't yet have a way to annotate calls with properties like
906   // "cold", and we don't have any call-clobbered registers, so these are mostly
907   // all handled the same.
908   return CallConv == CallingConv::C || CallConv == CallingConv::Fast ||
909          CallConv == CallingConv::Cold ||
910          CallConv == CallingConv::PreserveMost ||
911          CallConv == CallingConv::PreserveAll ||
912          CallConv == CallingConv::CXX_FAST_TLS ||
913          CallConv == CallingConv::WASM_EmscriptenInvoke ||
914          CallConv == CallingConv::Swift;
915 }
916 
917 SDValue
918 WebAssemblyTargetLowering::LowerCall(CallLoweringInfo &CLI,
919                                      SmallVectorImpl<SDValue> &InVals) const {
920   SelectionDAG &DAG = CLI.DAG;
921   SDLoc DL = CLI.DL;
922   SDValue Chain = CLI.Chain;
923   SDValue Callee = CLI.Callee;
924   MachineFunction &MF = DAG.getMachineFunction();
925   auto Layout = MF.getDataLayout();
926 
927   CallingConv::ID CallConv = CLI.CallConv;
928   if (!callingConvSupported(CallConv))
929     fail(DL, DAG,
930          "WebAssembly doesn't support language-specific or target-specific "
931          "calling conventions yet");
932   if (CLI.IsPatchPoint)
933     fail(DL, DAG, "WebAssembly doesn't support patch point yet");
934 
935   if (CLI.IsTailCall) {
936     auto NoTail = [&](const char *Msg) {
937       if (CLI.CB && CLI.CB->isMustTailCall())
938         fail(DL, DAG, Msg);
939       CLI.IsTailCall = false;
940     };
941 
942     if (!Subtarget->hasTailCall())
943       NoTail("WebAssembly 'tail-call' feature not enabled");
944 
945     // Varargs calls cannot be tail calls because the buffer is on the stack
946     if (CLI.IsVarArg)
947       NoTail("WebAssembly does not support varargs tail calls");
948 
949     // Do not tail call unless caller and callee return types match
950     const Function &F = MF.getFunction();
951     const TargetMachine &TM = getTargetMachine();
952     Type *RetTy = F.getReturnType();
953     SmallVector<MVT, 4> CallerRetTys;
954     SmallVector<MVT, 4> CalleeRetTys;
955     computeLegalValueVTs(F, TM, RetTy, CallerRetTys);
956     computeLegalValueVTs(F, TM, CLI.RetTy, CalleeRetTys);
957     bool TypesMatch = CallerRetTys.size() == CalleeRetTys.size() &&
958                       std::equal(CallerRetTys.begin(), CallerRetTys.end(),
959                                  CalleeRetTys.begin());
960     if (!TypesMatch)
961       NoTail("WebAssembly tail call requires caller and callee return types to "
962              "match");
963 
964     // If pointers to local stack values are passed, we cannot tail call
965     if (CLI.CB) {
966       for (auto &Arg : CLI.CB->args()) {
967         Value *Val = Arg.get();
968         // Trace the value back through pointer operations
969         while (true) {
970           Value *Src = Val->stripPointerCastsAndAliases();
971           if (auto *GEP = dyn_cast<GetElementPtrInst>(Src))
972             Src = GEP->getPointerOperand();
973           if (Val == Src)
974             break;
975           Val = Src;
976         }
977         if (isa<AllocaInst>(Val)) {
978           NoTail(
979               "WebAssembly does not support tail calling with stack arguments");
980           break;
981         }
982       }
983     }
984   }
985 
986   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
987   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
988   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
989 
990   // The generic code may have added an sret argument. If we're lowering an
991   // invoke function, the ABI requires that the function pointer be the first
992   // argument, so we may have to swap the arguments.
993   if (CallConv == CallingConv::WASM_EmscriptenInvoke && Outs.size() >= 2 &&
994       Outs[0].Flags.isSRet()) {
995     std::swap(Outs[0], Outs[1]);
996     std::swap(OutVals[0], OutVals[1]);
997   }
998 
999   bool HasSwiftSelfArg = false;
1000   bool HasSwiftErrorArg = false;
1001   unsigned NumFixedArgs = 0;
1002   for (unsigned I = 0; I < Outs.size(); ++I) {
1003     const ISD::OutputArg &Out = Outs[I];
1004     SDValue &OutVal = OutVals[I];
1005     HasSwiftSelfArg |= Out.Flags.isSwiftSelf();
1006     HasSwiftErrorArg |= Out.Flags.isSwiftError();
1007     if (Out.Flags.isNest())
1008       fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
1009     if (Out.Flags.isInAlloca())
1010       fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
1011     if (Out.Flags.isInConsecutiveRegs())
1012       fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
1013     if (Out.Flags.isInConsecutiveRegsLast())
1014       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
1015     if (Out.Flags.isByVal() && Out.Flags.getByValSize() != 0) {
1016       auto &MFI = MF.getFrameInfo();
1017       int FI = MFI.CreateStackObject(Out.Flags.getByValSize(),
1018                                      Out.Flags.getNonZeroByValAlign(),
1019                                      /*isSS=*/false);
1020       SDValue SizeNode =
1021           DAG.getConstant(Out.Flags.getByValSize(), DL, MVT::i32);
1022       SDValue FINode = DAG.getFrameIndex(FI, getPointerTy(Layout));
1023       Chain = DAG.getMemcpy(
1024           Chain, DL, FINode, OutVal, SizeNode, Out.Flags.getNonZeroByValAlign(),
1025           /*isVolatile*/ false, /*AlwaysInline=*/false,
1026           /*isTailCall*/ false, MachinePointerInfo(), MachinePointerInfo());
1027       OutVal = FINode;
1028     }
1029     // Count the number of fixed args *after* legalization.
1030     NumFixedArgs += Out.IsFixed;
1031   }
1032 
1033   bool IsVarArg = CLI.IsVarArg;
1034   auto PtrVT = getPointerTy(Layout);
1035 
1036   // For swiftcc, emit additional swiftself and swifterror arguments
1037   // if there aren't. These additional arguments are also added for callee
1038   // signature They are necessary to match callee and caller signature for
1039   // indirect call.
1040   if (CallConv == CallingConv::Swift) {
1041     if (!HasSwiftSelfArg) {
1042       NumFixedArgs++;
1043       ISD::OutputArg Arg;
1044       Arg.Flags.setSwiftSelf();
1045       CLI.Outs.push_back(Arg);
1046       SDValue ArgVal = DAG.getUNDEF(PtrVT);
1047       CLI.OutVals.push_back(ArgVal);
1048     }
1049     if (!HasSwiftErrorArg) {
1050       NumFixedArgs++;
1051       ISD::OutputArg Arg;
1052       Arg.Flags.setSwiftError();
1053       CLI.Outs.push_back(Arg);
1054       SDValue ArgVal = DAG.getUNDEF(PtrVT);
1055       CLI.OutVals.push_back(ArgVal);
1056     }
1057   }
1058 
1059   // Analyze operands of the call, assigning locations to each operand.
1060   SmallVector<CCValAssign, 16> ArgLocs;
1061   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
1062 
1063   if (IsVarArg) {
1064     // Outgoing non-fixed arguments are placed in a buffer. First
1065     // compute their offsets and the total amount of buffer space needed.
1066     for (unsigned I = NumFixedArgs; I < Outs.size(); ++I) {
1067       const ISD::OutputArg &Out = Outs[I];
1068       SDValue &Arg = OutVals[I];
1069       EVT VT = Arg.getValueType();
1070       assert(VT != MVT::iPTR && "Legalized args should be concrete");
1071       Type *Ty = VT.getTypeForEVT(*DAG.getContext());
1072       Align Alignment =
1073           std::max(Out.Flags.getNonZeroOrigAlign(), Layout.getABITypeAlign(Ty));
1074       unsigned Offset =
1075           CCInfo.AllocateStack(Layout.getTypeAllocSize(Ty), Alignment);
1076       CCInfo.addLoc(CCValAssign::getMem(ArgLocs.size(), VT.getSimpleVT(),
1077                                         Offset, VT.getSimpleVT(),
1078                                         CCValAssign::Full));
1079     }
1080   }
1081 
1082   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
1083 
1084   SDValue FINode;
1085   if (IsVarArg && NumBytes) {
1086     // For non-fixed arguments, next emit stores to store the argument values
1087     // to the stack buffer at the offsets computed above.
1088     int FI = MF.getFrameInfo().CreateStackObject(NumBytes,
1089                                                  Layout.getStackAlignment(),
1090                                                  /*isSS=*/false);
1091     unsigned ValNo = 0;
1092     SmallVector<SDValue, 8> Chains;
1093     for (SDValue Arg : drop_begin(OutVals, NumFixedArgs)) {
1094       assert(ArgLocs[ValNo].getValNo() == ValNo &&
1095              "ArgLocs should remain in order and only hold varargs args");
1096       unsigned Offset = ArgLocs[ValNo++].getLocMemOffset();
1097       FINode = DAG.getFrameIndex(FI, getPointerTy(Layout));
1098       SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, FINode,
1099                                 DAG.getConstant(Offset, DL, PtrVT));
1100       Chains.push_back(
1101           DAG.getStore(Chain, DL, Arg, Add,
1102                        MachinePointerInfo::getFixedStack(MF, FI, Offset)));
1103     }
1104     if (!Chains.empty())
1105       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
1106   } else if (IsVarArg) {
1107     FINode = DAG.getIntPtrConstant(0, DL);
1108   }
1109 
1110   if (Callee->getOpcode() == ISD::GlobalAddress) {
1111     // If the callee is a GlobalAddress node (quite common, every direct call
1112     // is) turn it into a TargetGlobalAddress node so that LowerGlobalAddress
1113     // doesn't at MO_GOT which is not needed for direct calls.
1114     GlobalAddressSDNode* GA = cast<GlobalAddressSDNode>(Callee);
1115     Callee = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
1116                                         getPointerTy(DAG.getDataLayout()),
1117                                         GA->getOffset());
1118     Callee = DAG.getNode(WebAssemblyISD::Wrapper, DL,
1119                          getPointerTy(DAG.getDataLayout()), Callee);
1120   }
1121 
1122   // Compute the operands for the CALLn node.
1123   SmallVector<SDValue, 16> Ops;
1124   Ops.push_back(Chain);
1125   Ops.push_back(Callee);
1126 
1127   // Add all fixed arguments. Note that for non-varargs calls, NumFixedArgs
1128   // isn't reliable.
1129   Ops.append(OutVals.begin(),
1130              IsVarArg ? OutVals.begin() + NumFixedArgs : OutVals.end());
1131   // Add a pointer to the vararg buffer.
1132   if (IsVarArg)
1133     Ops.push_back(FINode);
1134 
1135   SmallVector<EVT, 8> InTys;
1136   for (const auto &In : Ins) {
1137     assert(!In.Flags.isByVal() && "byval is not valid for return values");
1138     assert(!In.Flags.isNest() && "nest is not valid for return values");
1139     if (In.Flags.isInAlloca())
1140       fail(DL, DAG, "WebAssembly hasn't implemented inalloca return values");
1141     if (In.Flags.isInConsecutiveRegs())
1142       fail(DL, DAG, "WebAssembly hasn't implemented cons regs return values");
1143     if (In.Flags.isInConsecutiveRegsLast())
1144       fail(DL, DAG,
1145            "WebAssembly hasn't implemented cons regs last return values");
1146     // Ignore In.getNonZeroOrigAlign() because all our arguments are passed in
1147     // registers.
1148     InTys.push_back(In.VT);
1149   }
1150 
1151   // Lastly, if this is a call to a funcref we need to add an instruction
1152   // table.set to the chain and transform the call.
1153   if (CLI.CB &&
1154       WebAssembly::isFuncrefType(CLI.CB->getCalledOperand()->getType())) {
1155     // In the absence of function references proposal where a funcref call is
1156     // lowered to call_ref, using reference types we generate a table.set to set
1157     // the funcref to a special table used solely for this purpose, followed by
1158     // a call_indirect. Here we just generate the table set, and return the
1159     // SDValue of the table.set so that LowerCall can finalize the lowering by
1160     // generating the call_indirect.
1161     SDValue Chain = Ops[0];
1162 
1163     MCSymbolWasm *Table = WebAssembly::getOrCreateFuncrefCallTableSymbol(
1164         MF.getContext(), Subtarget);
1165     SDValue Sym = DAG.getMCSymbol(Table, PtrVT);
1166     SDValue TableSlot = DAG.getConstant(0, DL, MVT::i32);
1167     SDValue TableSetOps[] = {Chain, Sym, TableSlot, Callee};
1168     SDValue TableSet = DAG.getMemIntrinsicNode(
1169         WebAssemblyISD::TABLE_SET, DL, DAG.getVTList(MVT::Other), TableSetOps,
1170         MVT::funcref,
1171         // Machine Mem Operand args
1172         MachinePointerInfo(
1173             WebAssembly::WasmAddressSpace::WASM_ADDRESS_SPACE_FUNCREF),
1174         CLI.CB->getCalledOperand()->getPointerAlignment(DAG.getDataLayout()),
1175         MachineMemOperand::MOStore);
1176 
1177     Ops[0] = TableSet; // The new chain is the TableSet itself
1178   }
1179 
1180   if (CLI.IsTailCall) {
1181     // ret_calls do not return values to the current frame
1182     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1183     return DAG.getNode(WebAssemblyISD::RET_CALL, DL, NodeTys, Ops);
1184   }
1185 
1186   InTys.push_back(MVT::Other);
1187   SDVTList InTyList = DAG.getVTList(InTys);
1188   SDValue Res = DAG.getNode(WebAssemblyISD::CALL, DL, InTyList, Ops);
1189 
1190   for (size_t I = 0; I < Ins.size(); ++I)
1191     InVals.push_back(Res.getValue(I));
1192 
1193   // Return the chain
1194   return Res.getValue(Ins.size());
1195 }
1196 
1197 bool WebAssemblyTargetLowering::CanLowerReturn(
1198     CallingConv::ID /*CallConv*/, MachineFunction & /*MF*/, bool /*IsVarArg*/,
1199     const SmallVectorImpl<ISD::OutputArg> &Outs,
1200     LLVMContext & /*Context*/) const {
1201   // WebAssembly can only handle returning tuples with multivalue enabled
1202   return Subtarget->hasMultivalue() || Outs.size() <= 1;
1203 }
1204 
1205 SDValue WebAssemblyTargetLowering::LowerReturn(
1206     SDValue Chain, CallingConv::ID CallConv, bool /*IsVarArg*/,
1207     const SmallVectorImpl<ISD::OutputArg> &Outs,
1208     const SmallVectorImpl<SDValue> &OutVals, const SDLoc &DL,
1209     SelectionDAG &DAG) const {
1210   assert((Subtarget->hasMultivalue() || Outs.size() <= 1) &&
1211          "MVP WebAssembly can only return up to one value");
1212   if (!callingConvSupported(CallConv))
1213     fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
1214 
1215   SmallVector<SDValue, 4> RetOps(1, Chain);
1216   RetOps.append(OutVals.begin(), OutVals.end());
1217   Chain = DAG.getNode(WebAssemblyISD::RETURN, DL, MVT::Other, RetOps);
1218 
1219   // Record the number and types of the return values.
1220   for (const ISD::OutputArg &Out : Outs) {
1221     assert(!Out.Flags.isByVal() && "byval is not valid for return values");
1222     assert(!Out.Flags.isNest() && "nest is not valid for return values");
1223     assert(Out.IsFixed && "non-fixed return value is not valid");
1224     if (Out.Flags.isInAlloca())
1225       fail(DL, DAG, "WebAssembly hasn't implemented inalloca results");
1226     if (Out.Flags.isInConsecutiveRegs())
1227       fail(DL, DAG, "WebAssembly hasn't implemented cons regs results");
1228     if (Out.Flags.isInConsecutiveRegsLast())
1229       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last results");
1230   }
1231 
1232   return Chain;
1233 }
1234 
1235 SDValue WebAssemblyTargetLowering::LowerFormalArguments(
1236     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
1237     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1238     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1239   if (!callingConvSupported(CallConv))
1240     fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
1241 
1242   MachineFunction &MF = DAG.getMachineFunction();
1243   auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>();
1244 
1245   // Set up the incoming ARGUMENTS value, which serves to represent the liveness
1246   // of the incoming values before they're represented by virtual registers.
1247   MF.getRegInfo().addLiveIn(WebAssembly::ARGUMENTS);
1248 
1249   bool HasSwiftErrorArg = false;
1250   bool HasSwiftSelfArg = false;
1251   for (const ISD::InputArg &In : Ins) {
1252     HasSwiftSelfArg |= In.Flags.isSwiftSelf();
1253     HasSwiftErrorArg |= In.Flags.isSwiftError();
1254     if (In.Flags.isInAlloca())
1255       fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
1256     if (In.Flags.isNest())
1257       fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
1258     if (In.Flags.isInConsecutiveRegs())
1259       fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
1260     if (In.Flags.isInConsecutiveRegsLast())
1261       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
1262     // Ignore In.getNonZeroOrigAlign() because all our arguments are passed in
1263     // registers.
1264     InVals.push_back(In.Used ? DAG.getNode(WebAssemblyISD::ARGUMENT, DL, In.VT,
1265                                            DAG.getTargetConstant(InVals.size(),
1266                                                                  DL, MVT::i32))
1267                              : DAG.getUNDEF(In.VT));
1268 
1269     // Record the number and types of arguments.
1270     MFI->addParam(In.VT);
1271   }
1272 
1273   // For swiftcc, emit additional swiftself and swifterror arguments
1274   // if there aren't. These additional arguments are also added for callee
1275   // signature They are necessary to match callee and caller signature for
1276   // indirect call.
1277   auto PtrVT = getPointerTy(MF.getDataLayout());
1278   if (CallConv == CallingConv::Swift) {
1279     if (!HasSwiftSelfArg) {
1280       MFI->addParam(PtrVT);
1281     }
1282     if (!HasSwiftErrorArg) {
1283       MFI->addParam(PtrVT);
1284     }
1285   }
1286   // Varargs are copied into a buffer allocated by the caller, and a pointer to
1287   // the buffer is passed as an argument.
1288   if (IsVarArg) {
1289     MVT PtrVT = getPointerTy(MF.getDataLayout());
1290     Register VarargVreg =
1291         MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrVT));
1292     MFI->setVarargBufferVreg(VarargVreg);
1293     Chain = DAG.getCopyToReg(
1294         Chain, DL, VarargVreg,
1295         DAG.getNode(WebAssemblyISD::ARGUMENT, DL, PtrVT,
1296                     DAG.getTargetConstant(Ins.size(), DL, MVT::i32)));
1297     MFI->addParam(PtrVT);
1298   }
1299 
1300   // Record the number and types of arguments and results.
1301   SmallVector<MVT, 4> Params;
1302   SmallVector<MVT, 4> Results;
1303   computeSignatureVTs(MF.getFunction().getFunctionType(), &MF.getFunction(),
1304                       MF.getFunction(), DAG.getTarget(), Params, Results);
1305   for (MVT VT : Results)
1306     MFI->addResult(VT);
1307   // TODO: Use signatures in WebAssemblyMachineFunctionInfo too and unify
1308   // the param logic here with ComputeSignatureVTs
1309   assert(MFI->getParams().size() == Params.size() &&
1310          std::equal(MFI->getParams().begin(), MFI->getParams().end(),
1311                     Params.begin()));
1312 
1313   return Chain;
1314 }
1315 
1316 void WebAssemblyTargetLowering::ReplaceNodeResults(
1317     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
1318   switch (N->getOpcode()) {
1319   case ISD::SIGN_EXTEND_INREG:
1320     // Do not add any results, signifying that N should not be custom lowered
1321     // after all. This happens because simd128 turns on custom lowering for
1322     // SIGN_EXTEND_INREG, but for non-vector sign extends the result might be an
1323     // illegal type.
1324     break;
1325   default:
1326     llvm_unreachable(
1327         "ReplaceNodeResults not implemented for this op for WebAssembly!");
1328   }
1329 }
1330 
1331 //===----------------------------------------------------------------------===//
1332 //  Custom lowering hooks.
1333 //===----------------------------------------------------------------------===//
1334 
1335 SDValue WebAssemblyTargetLowering::LowerOperation(SDValue Op,
1336                                                   SelectionDAG &DAG) const {
1337   SDLoc DL(Op);
1338   switch (Op.getOpcode()) {
1339   default:
1340     llvm_unreachable("unimplemented operation lowering");
1341     return SDValue();
1342   case ISD::FrameIndex:
1343     return LowerFrameIndex(Op, DAG);
1344   case ISD::GlobalAddress:
1345     return LowerGlobalAddress(Op, DAG);
1346   case ISD::GlobalTLSAddress:
1347     return LowerGlobalTLSAddress(Op, DAG);
1348   case ISD::ExternalSymbol:
1349     return LowerExternalSymbol(Op, DAG);
1350   case ISD::JumpTable:
1351     return LowerJumpTable(Op, DAG);
1352   case ISD::BR_JT:
1353     return LowerBR_JT(Op, DAG);
1354   case ISD::VASTART:
1355     return LowerVASTART(Op, DAG);
1356   case ISD::BlockAddress:
1357   case ISD::BRIND:
1358     fail(DL, DAG, "WebAssembly hasn't implemented computed gotos");
1359     return SDValue();
1360   case ISD::RETURNADDR:
1361     return LowerRETURNADDR(Op, DAG);
1362   case ISD::FRAMEADDR:
1363     return LowerFRAMEADDR(Op, DAG);
1364   case ISD::CopyToReg:
1365     return LowerCopyToReg(Op, DAG);
1366   case ISD::EXTRACT_VECTOR_ELT:
1367   case ISD::INSERT_VECTOR_ELT:
1368     return LowerAccessVectorElement(Op, DAG);
1369   case ISD::INTRINSIC_VOID:
1370   case ISD::INTRINSIC_WO_CHAIN:
1371   case ISD::INTRINSIC_W_CHAIN:
1372     return LowerIntrinsic(Op, DAG);
1373   case ISD::SIGN_EXTEND_INREG:
1374     return LowerSIGN_EXTEND_INREG(Op, DAG);
1375   case ISD::BUILD_VECTOR:
1376     return LowerBUILD_VECTOR(Op, DAG);
1377   case ISD::VECTOR_SHUFFLE:
1378     return LowerVECTOR_SHUFFLE(Op, DAG);
1379   case ISD::SETCC:
1380     return LowerSETCC(Op, DAG);
1381   case ISD::SHL:
1382   case ISD::SRA:
1383   case ISD::SRL:
1384     return LowerShift(Op, DAG);
1385   case ISD::FP_TO_SINT_SAT:
1386   case ISD::FP_TO_UINT_SAT:
1387     return LowerFP_TO_INT_SAT(Op, DAG);
1388   case ISD::LOAD:
1389     return LowerLoad(Op, DAG);
1390   case ISD::STORE:
1391     return LowerStore(Op, DAG);
1392   }
1393 }
1394 
1395 static bool IsWebAssemblyGlobal(SDValue Op) {
1396   if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op))
1397     return WebAssembly::isWasmVarAddressSpace(GA->getAddressSpace());
1398 
1399   return false;
1400 }
1401 
1402 static Optional<unsigned> IsWebAssemblyLocal(SDValue Op, SelectionDAG &DAG) {
1403   const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op);
1404   if (!FI)
1405     return None;
1406 
1407   auto &MF = DAG.getMachineFunction();
1408   return WebAssemblyFrameLowering::getLocalForStackObject(MF, FI->getIndex());
1409 }
1410 
1411 SDValue WebAssemblyTargetLowering::LowerStore(SDValue Op,
1412                                               SelectionDAG &DAG) const {
1413   SDLoc DL(Op);
1414   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
1415   const SDValue &Value = SN->getValue();
1416   const SDValue &Base = SN->getBasePtr();
1417   const SDValue &Offset = SN->getOffset();
1418 
1419   if (IsWebAssemblyGlobal(Base)) {
1420     if (!Offset->isUndef())
1421       report_fatal_error("unexpected offset when storing to webassembly global",
1422                          false);
1423 
1424     SDVTList Tys = DAG.getVTList(MVT::Other);
1425     SDValue Ops[] = {SN->getChain(), Value, Base};
1426     return DAG.getMemIntrinsicNode(WebAssemblyISD::GLOBAL_SET, DL, Tys, Ops,
1427                                    SN->getMemoryVT(), SN->getMemOperand());
1428   }
1429 
1430   if (Optional<unsigned> Local = IsWebAssemblyLocal(Base, DAG)) {
1431     if (!Offset->isUndef())
1432       report_fatal_error("unexpected offset when storing to webassembly local",
1433                          false);
1434 
1435     SDValue Idx = DAG.getTargetConstant(*Local, Base, MVT::i32);
1436     SDVTList Tys = DAG.getVTList(MVT::Other); // The chain.
1437     SDValue Ops[] = {SN->getChain(), Idx, Value};
1438     return DAG.getNode(WebAssemblyISD::LOCAL_SET, DL, Tys, Ops);
1439   }
1440 
1441   return Op;
1442 }
1443 
1444 SDValue WebAssemblyTargetLowering::LowerLoad(SDValue Op,
1445                                              SelectionDAG &DAG) const {
1446   SDLoc DL(Op);
1447   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
1448   const SDValue &Base = LN->getBasePtr();
1449   const SDValue &Offset = LN->getOffset();
1450 
1451   if (IsWebAssemblyGlobal(Base)) {
1452     if (!Offset->isUndef())
1453       report_fatal_error(
1454           "unexpected offset when loading from webassembly global", false);
1455 
1456     SDVTList Tys = DAG.getVTList(LN->getValueType(0), MVT::Other);
1457     SDValue Ops[] = {LN->getChain(), Base};
1458     return DAG.getMemIntrinsicNode(WebAssemblyISD::GLOBAL_GET, DL, Tys, Ops,
1459                                    LN->getMemoryVT(), LN->getMemOperand());
1460   }
1461 
1462   if (Optional<unsigned> Local = IsWebAssemblyLocal(Base, DAG)) {
1463     if (!Offset->isUndef())
1464       report_fatal_error(
1465           "unexpected offset when loading from webassembly local", false);
1466 
1467     SDValue Idx = DAG.getTargetConstant(*Local, Base, MVT::i32);
1468     EVT LocalVT = LN->getValueType(0);
1469     SDValue LocalGet = DAG.getNode(WebAssemblyISD::LOCAL_GET, DL, LocalVT,
1470                                    {LN->getChain(), Idx});
1471     SDValue Result = DAG.getMergeValues({LocalGet, LN->getChain()}, DL);
1472     assert(Result->getNumValues() == 2 && "Loads must carry a chain!");
1473     return Result;
1474   }
1475 
1476   return Op;
1477 }
1478 
1479 SDValue WebAssemblyTargetLowering::LowerCopyToReg(SDValue Op,
1480                                                   SelectionDAG &DAG) const {
1481   SDValue Src = Op.getOperand(2);
1482   if (isa<FrameIndexSDNode>(Src.getNode())) {
1483     // CopyToReg nodes don't support FrameIndex operands. Other targets select
1484     // the FI to some LEA-like instruction, but since we don't have that, we
1485     // need to insert some kind of instruction that can take an FI operand and
1486     // produces a value usable by CopyToReg (i.e. in a vreg). So insert a dummy
1487     // local.copy between Op and its FI operand.
1488     SDValue Chain = Op.getOperand(0);
1489     SDLoc DL(Op);
1490     unsigned Reg = cast<RegisterSDNode>(Op.getOperand(1))->getReg();
1491     EVT VT = Src.getValueType();
1492     SDValue Copy(DAG.getMachineNode(VT == MVT::i32 ? WebAssembly::COPY_I32
1493                                                    : WebAssembly::COPY_I64,
1494                                     DL, VT, Src),
1495                  0);
1496     return Op.getNode()->getNumValues() == 1
1497                ? DAG.getCopyToReg(Chain, DL, Reg, Copy)
1498                : DAG.getCopyToReg(Chain, DL, Reg, Copy,
1499                                   Op.getNumOperands() == 4 ? Op.getOperand(3)
1500                                                            : SDValue());
1501   }
1502   return SDValue();
1503 }
1504 
1505 SDValue WebAssemblyTargetLowering::LowerFrameIndex(SDValue Op,
1506                                                    SelectionDAG &DAG) const {
1507   int FI = cast<FrameIndexSDNode>(Op)->getIndex();
1508   return DAG.getTargetFrameIndex(FI, Op.getValueType());
1509 }
1510 
1511 SDValue WebAssemblyTargetLowering::LowerRETURNADDR(SDValue Op,
1512                                                    SelectionDAG &DAG) const {
1513   SDLoc DL(Op);
1514 
1515   if (!Subtarget->getTargetTriple().isOSEmscripten()) {
1516     fail(DL, DAG,
1517          "Non-Emscripten WebAssembly hasn't implemented "
1518          "__builtin_return_address");
1519     return SDValue();
1520   }
1521 
1522   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1523     return SDValue();
1524 
1525   unsigned Depth = Op.getConstantOperandVal(0);
1526   MakeLibCallOptions CallOptions;
1527   return makeLibCall(DAG, RTLIB::RETURN_ADDRESS, Op.getValueType(),
1528                      {DAG.getConstant(Depth, DL, MVT::i32)}, CallOptions, DL)
1529       .first;
1530 }
1531 
1532 SDValue WebAssemblyTargetLowering::LowerFRAMEADDR(SDValue Op,
1533                                                   SelectionDAG &DAG) const {
1534   // Non-zero depths are not supported by WebAssembly currently. Use the
1535   // legalizer's default expansion, which is to return 0 (what this function is
1536   // documented to do).
1537   if (Op.getConstantOperandVal(0) > 0)
1538     return SDValue();
1539 
1540   DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
1541   EVT VT = Op.getValueType();
1542   Register FP =
1543       Subtarget->getRegisterInfo()->getFrameRegister(DAG.getMachineFunction());
1544   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), FP, VT);
1545 }
1546 
1547 SDValue
1548 WebAssemblyTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1549                                                  SelectionDAG &DAG) const {
1550   SDLoc DL(Op);
1551   const auto *GA = cast<GlobalAddressSDNode>(Op);
1552 
1553   MachineFunction &MF = DAG.getMachineFunction();
1554   if (!MF.getSubtarget<WebAssemblySubtarget>().hasBulkMemory())
1555     report_fatal_error("cannot use thread-local storage without bulk memory",
1556                        false);
1557 
1558   const GlobalValue *GV = GA->getGlobal();
1559 
1560   // Currently Emscripten does not support dynamic linking with threads.
1561   // Therefore, if we have thread-local storage, only the local-exec model
1562   // is possible.
1563   // TODO: remove this and implement proper TLS models once Emscripten
1564   // supports dynamic linking with threads.
1565   if (GV->getThreadLocalMode() != GlobalValue::LocalExecTLSModel &&
1566       !Subtarget->getTargetTriple().isOSEmscripten()) {
1567     report_fatal_error("only -ftls-model=local-exec is supported for now on "
1568                        "non-Emscripten OSes: variable " +
1569                            GV->getName(),
1570                        false);
1571   }
1572 
1573   auto model = GV->getThreadLocalMode();
1574 
1575   // Unsupported TLS modes
1576   assert(model != GlobalValue::NotThreadLocal);
1577   assert(model != GlobalValue::InitialExecTLSModel);
1578 
1579   if (model == GlobalValue::LocalExecTLSModel ||
1580       model == GlobalValue::LocalDynamicTLSModel ||
1581       (model == GlobalValue::GeneralDynamicTLSModel &&
1582        getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))) {
1583     // For DSO-local TLS variables we use offset from __tls_base
1584 
1585     MVT PtrVT = getPointerTy(DAG.getDataLayout());
1586     auto GlobalGet = PtrVT == MVT::i64 ? WebAssembly::GLOBAL_GET_I64
1587                                        : WebAssembly::GLOBAL_GET_I32;
1588     const char *BaseName = MF.createExternalSymbolName("__tls_base");
1589 
1590     SDValue BaseAddr(
1591         DAG.getMachineNode(GlobalGet, DL, PtrVT,
1592                            DAG.getTargetExternalSymbol(BaseName, PtrVT)),
1593         0);
1594 
1595     SDValue TLSOffset = DAG.getTargetGlobalAddress(
1596         GV, DL, PtrVT, GA->getOffset(), WebAssemblyII::MO_TLS_BASE_REL);
1597     SDValue SymOffset =
1598         DAG.getNode(WebAssemblyISD::WrapperREL, DL, PtrVT, TLSOffset);
1599 
1600     return DAG.getNode(ISD::ADD, DL, PtrVT, BaseAddr, SymOffset);
1601   }
1602 
1603   assert(model == GlobalValue::GeneralDynamicTLSModel);
1604 
1605   EVT VT = Op.getValueType();
1606   return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1607                      DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT,
1608                                                 GA->getOffset(),
1609                                                 WebAssemblyII::MO_GOT_TLS));
1610 }
1611 
1612 SDValue WebAssemblyTargetLowering::LowerGlobalAddress(SDValue Op,
1613                                                       SelectionDAG &DAG) const {
1614   SDLoc DL(Op);
1615   const auto *GA = cast<GlobalAddressSDNode>(Op);
1616   EVT VT = Op.getValueType();
1617   assert(GA->getTargetFlags() == 0 &&
1618          "Unexpected target flags on generic GlobalAddressSDNode");
1619   if (!WebAssembly::isValidAddressSpace(GA->getAddressSpace()))
1620     fail(DL, DAG, "Invalid address space for WebAssembly target");
1621 
1622   unsigned OperandFlags = 0;
1623   if (isPositionIndependent()) {
1624     const GlobalValue *GV = GA->getGlobal();
1625     if (getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) {
1626       MachineFunction &MF = DAG.getMachineFunction();
1627       MVT PtrVT = getPointerTy(MF.getDataLayout());
1628       const char *BaseName;
1629       if (GV->getValueType()->isFunctionTy()) {
1630         BaseName = MF.createExternalSymbolName("__table_base");
1631         OperandFlags = WebAssemblyII::MO_TABLE_BASE_REL;
1632       }
1633       else {
1634         BaseName = MF.createExternalSymbolName("__memory_base");
1635         OperandFlags = WebAssemblyII::MO_MEMORY_BASE_REL;
1636       }
1637       SDValue BaseAddr =
1638           DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT,
1639                       DAG.getTargetExternalSymbol(BaseName, PtrVT));
1640 
1641       SDValue SymAddr = DAG.getNode(
1642           WebAssemblyISD::WrapperREL, DL, VT,
1643           DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT, GA->getOffset(),
1644                                      OperandFlags));
1645 
1646       return DAG.getNode(ISD::ADD, DL, VT, BaseAddr, SymAddr);
1647     }
1648     OperandFlags = WebAssemblyII::MO_GOT;
1649   }
1650 
1651   return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1652                      DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT,
1653                                                 GA->getOffset(), OperandFlags));
1654 }
1655 
1656 SDValue
1657 WebAssemblyTargetLowering::LowerExternalSymbol(SDValue Op,
1658                                                SelectionDAG &DAG) const {
1659   SDLoc DL(Op);
1660   const auto *ES = cast<ExternalSymbolSDNode>(Op);
1661   EVT VT = Op.getValueType();
1662   assert(ES->getTargetFlags() == 0 &&
1663          "Unexpected target flags on generic ExternalSymbolSDNode");
1664   return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1665                      DAG.getTargetExternalSymbol(ES->getSymbol(), VT));
1666 }
1667 
1668 SDValue WebAssemblyTargetLowering::LowerJumpTable(SDValue Op,
1669                                                   SelectionDAG &DAG) const {
1670   // There's no need for a Wrapper node because we always incorporate a jump
1671   // table operand into a BR_TABLE instruction, rather than ever
1672   // materializing it in a register.
1673   const JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1674   return DAG.getTargetJumpTable(JT->getIndex(), Op.getValueType(),
1675                                 JT->getTargetFlags());
1676 }
1677 
1678 SDValue WebAssemblyTargetLowering::LowerBR_JT(SDValue Op,
1679                                               SelectionDAG &DAG) const {
1680   SDLoc DL(Op);
1681   SDValue Chain = Op.getOperand(0);
1682   const auto *JT = cast<JumpTableSDNode>(Op.getOperand(1));
1683   SDValue Index = Op.getOperand(2);
1684   assert(JT->getTargetFlags() == 0 && "WebAssembly doesn't set target flags");
1685 
1686   SmallVector<SDValue, 8> Ops;
1687   Ops.push_back(Chain);
1688   Ops.push_back(Index);
1689 
1690   MachineJumpTableInfo *MJTI = DAG.getMachineFunction().getJumpTableInfo();
1691   const auto &MBBs = MJTI->getJumpTables()[JT->getIndex()].MBBs;
1692 
1693   // Add an operand for each case.
1694   for (auto MBB : MBBs)
1695     Ops.push_back(DAG.getBasicBlock(MBB));
1696 
1697   // Add the first MBB as a dummy default target for now. This will be replaced
1698   // with the proper default target (and the preceding range check eliminated)
1699   // if possible by WebAssemblyFixBrTableDefaults.
1700   Ops.push_back(DAG.getBasicBlock(*MBBs.begin()));
1701   return DAG.getNode(WebAssemblyISD::BR_TABLE, DL, MVT::Other, Ops);
1702 }
1703 
1704 SDValue WebAssemblyTargetLowering::LowerVASTART(SDValue Op,
1705                                                 SelectionDAG &DAG) const {
1706   SDLoc DL(Op);
1707   EVT PtrVT = getPointerTy(DAG.getMachineFunction().getDataLayout());
1708 
1709   auto *MFI = DAG.getMachineFunction().getInfo<WebAssemblyFunctionInfo>();
1710   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1711 
1712   SDValue ArgN = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1713                                     MFI->getVarargBufferVreg(), PtrVT);
1714   return DAG.getStore(Op.getOperand(0), DL, ArgN, Op.getOperand(1),
1715                       MachinePointerInfo(SV));
1716 }
1717 
1718 SDValue WebAssemblyTargetLowering::LowerIntrinsic(SDValue Op,
1719                                                   SelectionDAG &DAG) const {
1720   MachineFunction &MF = DAG.getMachineFunction();
1721   unsigned IntNo;
1722   switch (Op.getOpcode()) {
1723   case ISD::INTRINSIC_VOID:
1724   case ISD::INTRINSIC_W_CHAIN:
1725     IntNo = Op.getConstantOperandVal(1);
1726     break;
1727   case ISD::INTRINSIC_WO_CHAIN:
1728     IntNo = Op.getConstantOperandVal(0);
1729     break;
1730   default:
1731     llvm_unreachable("Invalid intrinsic");
1732   }
1733   SDLoc DL(Op);
1734 
1735   switch (IntNo) {
1736   default:
1737     return SDValue(); // Don't custom lower most intrinsics.
1738 
1739   case Intrinsic::wasm_lsda: {
1740     EVT VT = Op.getValueType();
1741     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1742     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
1743     auto &Context = MF.getMMI().getContext();
1744     MCSymbol *S = Context.getOrCreateSymbol(Twine("GCC_except_table") +
1745                                             Twine(MF.getFunctionNumber()));
1746     return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1747                        DAG.getMCSymbol(S, PtrVT));
1748   }
1749 
1750   case Intrinsic::wasm_shuffle: {
1751     // Drop in-chain and replace undefs, but otherwise pass through unchanged
1752     SDValue Ops[18];
1753     size_t OpIdx = 0;
1754     Ops[OpIdx++] = Op.getOperand(1);
1755     Ops[OpIdx++] = Op.getOperand(2);
1756     while (OpIdx < 18) {
1757       const SDValue &MaskIdx = Op.getOperand(OpIdx + 1);
1758       if (MaskIdx.isUndef() ||
1759           cast<ConstantSDNode>(MaskIdx.getNode())->getZExtValue() >= 32) {
1760         Ops[OpIdx++] = DAG.getConstant(0, DL, MVT::i32);
1761       } else {
1762         Ops[OpIdx++] = MaskIdx;
1763       }
1764     }
1765     return DAG.getNode(WebAssemblyISD::SHUFFLE, DL, Op.getValueType(), Ops);
1766   }
1767   }
1768 }
1769 
1770 SDValue
1771 WebAssemblyTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
1772                                                   SelectionDAG &DAG) const {
1773   SDLoc DL(Op);
1774   // If sign extension operations are disabled, allow sext_inreg only if operand
1775   // is a vector extract of an i8 or i16 lane. SIMD does not depend on sign
1776   // extension operations, but allowing sext_inreg in this context lets us have
1777   // simple patterns to select extract_lane_s instructions. Expanding sext_inreg
1778   // everywhere would be simpler in this file, but would necessitate large and
1779   // brittle patterns to undo the expansion and select extract_lane_s
1780   // instructions.
1781   assert(!Subtarget->hasSignExt() && Subtarget->hasSIMD128());
1782   if (Op.getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1783     return SDValue();
1784 
1785   const SDValue &Extract = Op.getOperand(0);
1786   MVT VecT = Extract.getOperand(0).getSimpleValueType();
1787   if (VecT.getVectorElementType().getSizeInBits() > 32)
1788     return SDValue();
1789   MVT ExtractedLaneT =
1790       cast<VTSDNode>(Op.getOperand(1).getNode())->getVT().getSimpleVT();
1791   MVT ExtractedVecT =
1792       MVT::getVectorVT(ExtractedLaneT, 128 / ExtractedLaneT.getSizeInBits());
1793   if (ExtractedVecT == VecT)
1794     return Op;
1795 
1796   // Bitcast vector to appropriate type to ensure ISel pattern coverage
1797   const SDNode *Index = Extract.getOperand(1).getNode();
1798   if (!isa<ConstantSDNode>(Index))
1799     return SDValue();
1800   unsigned IndexVal = cast<ConstantSDNode>(Index)->getZExtValue();
1801   unsigned Scale =
1802       ExtractedVecT.getVectorNumElements() / VecT.getVectorNumElements();
1803   assert(Scale > 1);
1804   SDValue NewIndex =
1805       DAG.getConstant(IndexVal * Scale, DL, Index->getValueType(0));
1806   SDValue NewExtract = DAG.getNode(
1807       ISD::EXTRACT_VECTOR_ELT, DL, Extract.getValueType(),
1808       DAG.getBitcast(ExtractedVecT, Extract.getOperand(0)), NewIndex);
1809   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, Op.getValueType(), NewExtract,
1810                      Op.getOperand(1));
1811 }
1812 
1813 static SDValue LowerConvertLow(SDValue Op, SelectionDAG &DAG) {
1814   SDLoc DL(Op);
1815   if (Op.getValueType() != MVT::v2f64)
1816     return SDValue();
1817 
1818   auto GetConvertedLane = [](SDValue Op, unsigned &Opcode, SDValue &SrcVec,
1819                              unsigned &Index) -> bool {
1820     switch (Op.getOpcode()) {
1821     case ISD::SINT_TO_FP:
1822       Opcode = WebAssemblyISD::CONVERT_LOW_S;
1823       break;
1824     case ISD::UINT_TO_FP:
1825       Opcode = WebAssemblyISD::CONVERT_LOW_U;
1826       break;
1827     case ISD::FP_EXTEND:
1828       Opcode = WebAssemblyISD::PROMOTE_LOW;
1829       break;
1830     default:
1831       return false;
1832     }
1833 
1834     auto ExtractVector = Op.getOperand(0);
1835     if (ExtractVector.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1836       return false;
1837 
1838     if (!isa<ConstantSDNode>(ExtractVector.getOperand(1).getNode()))
1839       return false;
1840 
1841     SrcVec = ExtractVector.getOperand(0);
1842     Index = ExtractVector.getConstantOperandVal(1);
1843     return true;
1844   };
1845 
1846   unsigned LHSOpcode, RHSOpcode, LHSIndex, RHSIndex;
1847   SDValue LHSSrcVec, RHSSrcVec;
1848   if (!GetConvertedLane(Op.getOperand(0), LHSOpcode, LHSSrcVec, LHSIndex) ||
1849       !GetConvertedLane(Op.getOperand(1), RHSOpcode, RHSSrcVec, RHSIndex))
1850     return SDValue();
1851 
1852   if (LHSOpcode != RHSOpcode)
1853     return SDValue();
1854 
1855   MVT ExpectedSrcVT;
1856   switch (LHSOpcode) {
1857   case WebAssemblyISD::CONVERT_LOW_S:
1858   case WebAssemblyISD::CONVERT_LOW_U:
1859     ExpectedSrcVT = MVT::v4i32;
1860     break;
1861   case WebAssemblyISD::PROMOTE_LOW:
1862     ExpectedSrcVT = MVT::v4f32;
1863     break;
1864   }
1865   if (LHSSrcVec.getValueType() != ExpectedSrcVT)
1866     return SDValue();
1867 
1868   auto Src = LHSSrcVec;
1869   if (LHSIndex != 0 || RHSIndex != 1 || LHSSrcVec != RHSSrcVec) {
1870     // Shuffle the source vector so that the converted lanes are the low lanes.
1871     Src = DAG.getVectorShuffle(
1872         ExpectedSrcVT, DL, LHSSrcVec, RHSSrcVec,
1873         {static_cast<int>(LHSIndex), static_cast<int>(RHSIndex) + 4, -1, -1});
1874   }
1875   return DAG.getNode(LHSOpcode, DL, MVT::v2f64, Src);
1876 }
1877 
1878 SDValue WebAssemblyTargetLowering::LowerBUILD_VECTOR(SDValue Op,
1879                                                      SelectionDAG &DAG) const {
1880   if (auto ConvertLow = LowerConvertLow(Op, DAG))
1881     return ConvertLow;
1882 
1883   SDLoc DL(Op);
1884   const EVT VecT = Op.getValueType();
1885   const EVT LaneT = Op.getOperand(0).getValueType();
1886   const size_t Lanes = Op.getNumOperands();
1887   bool CanSwizzle = VecT == MVT::v16i8;
1888 
1889   // BUILD_VECTORs are lowered to the instruction that initializes the highest
1890   // possible number of lanes at once followed by a sequence of replace_lane
1891   // instructions to individually initialize any remaining lanes.
1892 
1893   // TODO: Tune this. For example, lanewise swizzling is very expensive, so
1894   // swizzled lanes should be given greater weight.
1895 
1896   // TODO: Investigate looping rather than always extracting/replacing specific
1897   // lanes to fill gaps.
1898 
1899   auto IsConstant = [](const SDValue &V) {
1900     return V.getOpcode() == ISD::Constant || V.getOpcode() == ISD::ConstantFP;
1901   };
1902 
1903   // Returns the source vector and index vector pair if they exist. Checks for:
1904   //   (extract_vector_elt
1905   //     $src,
1906   //     (sign_extend_inreg (extract_vector_elt $indices, $i))
1907   //   )
1908   auto GetSwizzleSrcs = [](size_t I, const SDValue &Lane) {
1909     auto Bail = std::make_pair(SDValue(), SDValue());
1910     if (Lane->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1911       return Bail;
1912     const SDValue &SwizzleSrc = Lane->getOperand(0);
1913     const SDValue &IndexExt = Lane->getOperand(1);
1914     if (IndexExt->getOpcode() != ISD::SIGN_EXTEND_INREG)
1915       return Bail;
1916     const SDValue &Index = IndexExt->getOperand(0);
1917     if (Index->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1918       return Bail;
1919     const SDValue &SwizzleIndices = Index->getOperand(0);
1920     if (SwizzleSrc.getValueType() != MVT::v16i8 ||
1921         SwizzleIndices.getValueType() != MVT::v16i8 ||
1922         Index->getOperand(1)->getOpcode() != ISD::Constant ||
1923         Index->getConstantOperandVal(1) != I)
1924       return Bail;
1925     return std::make_pair(SwizzleSrc, SwizzleIndices);
1926   };
1927 
1928   // If the lane is extracted from another vector at a constant index, return
1929   // that vector. The source vector must not have more lanes than the dest
1930   // because the shufflevector indices are in terms of the destination lanes and
1931   // would not be able to address the smaller individual source lanes.
1932   auto GetShuffleSrc = [&](const SDValue &Lane) {
1933     if (Lane->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1934       return SDValue();
1935     if (!isa<ConstantSDNode>(Lane->getOperand(1).getNode()))
1936       return SDValue();
1937     if (Lane->getOperand(0).getValueType().getVectorNumElements() >
1938         VecT.getVectorNumElements())
1939       return SDValue();
1940     return Lane->getOperand(0);
1941   };
1942 
1943   using ValueEntry = std::pair<SDValue, size_t>;
1944   SmallVector<ValueEntry, 16> SplatValueCounts;
1945 
1946   using SwizzleEntry = std::pair<std::pair<SDValue, SDValue>, size_t>;
1947   SmallVector<SwizzleEntry, 16> SwizzleCounts;
1948 
1949   using ShuffleEntry = std::pair<SDValue, size_t>;
1950   SmallVector<ShuffleEntry, 16> ShuffleCounts;
1951 
1952   auto AddCount = [](auto &Counts, const auto &Val) {
1953     auto CountIt =
1954         llvm::find_if(Counts, [&Val](auto E) { return E.first == Val; });
1955     if (CountIt == Counts.end()) {
1956       Counts.emplace_back(Val, 1);
1957     } else {
1958       CountIt->second++;
1959     }
1960   };
1961 
1962   auto GetMostCommon = [](auto &Counts) {
1963     auto CommonIt =
1964         std::max_element(Counts.begin(), Counts.end(),
1965                          [](auto A, auto B) { return A.second < B.second; });
1966     assert(CommonIt != Counts.end() && "Unexpected all-undef build_vector");
1967     return *CommonIt;
1968   };
1969 
1970   size_t NumConstantLanes = 0;
1971 
1972   // Count eligible lanes for each type of vector creation op
1973   for (size_t I = 0; I < Lanes; ++I) {
1974     const SDValue &Lane = Op->getOperand(I);
1975     if (Lane.isUndef())
1976       continue;
1977 
1978     AddCount(SplatValueCounts, Lane);
1979 
1980     if (IsConstant(Lane))
1981       NumConstantLanes++;
1982     if (auto ShuffleSrc = GetShuffleSrc(Lane))
1983       AddCount(ShuffleCounts, ShuffleSrc);
1984     if (CanSwizzle) {
1985       auto SwizzleSrcs = GetSwizzleSrcs(I, Lane);
1986       if (SwizzleSrcs.first)
1987         AddCount(SwizzleCounts, SwizzleSrcs);
1988     }
1989   }
1990 
1991   SDValue SplatValue;
1992   size_t NumSplatLanes;
1993   std::tie(SplatValue, NumSplatLanes) = GetMostCommon(SplatValueCounts);
1994 
1995   SDValue SwizzleSrc;
1996   SDValue SwizzleIndices;
1997   size_t NumSwizzleLanes = 0;
1998   if (SwizzleCounts.size())
1999     std::forward_as_tuple(std::tie(SwizzleSrc, SwizzleIndices),
2000                           NumSwizzleLanes) = GetMostCommon(SwizzleCounts);
2001 
2002   // Shuffles can draw from up to two vectors, so find the two most common
2003   // sources.
2004   SDValue ShuffleSrc1, ShuffleSrc2;
2005   size_t NumShuffleLanes = 0;
2006   if (ShuffleCounts.size()) {
2007     std::tie(ShuffleSrc1, NumShuffleLanes) = GetMostCommon(ShuffleCounts);
2008     ShuffleCounts.erase(std::remove_if(ShuffleCounts.begin(),
2009                                        ShuffleCounts.end(),
2010                                        [&](const auto &Pair) {
2011                                          return Pair.first == ShuffleSrc1;
2012                                        }),
2013                         ShuffleCounts.end());
2014   }
2015   if (ShuffleCounts.size()) {
2016     size_t AdditionalShuffleLanes;
2017     std::tie(ShuffleSrc2, AdditionalShuffleLanes) =
2018         GetMostCommon(ShuffleCounts);
2019     NumShuffleLanes += AdditionalShuffleLanes;
2020   }
2021 
2022   // Predicate returning true if the lane is properly initialized by the
2023   // original instruction
2024   std::function<bool(size_t, const SDValue &)> IsLaneConstructed;
2025   SDValue Result;
2026   // Prefer swizzles over shuffles over vector consts over splats
2027   if (NumSwizzleLanes >= NumShuffleLanes &&
2028       NumSwizzleLanes >= NumConstantLanes && NumSwizzleLanes >= NumSplatLanes) {
2029     Result = DAG.getNode(WebAssemblyISD::SWIZZLE, DL, VecT, SwizzleSrc,
2030                          SwizzleIndices);
2031     auto Swizzled = std::make_pair(SwizzleSrc, SwizzleIndices);
2032     IsLaneConstructed = [&, Swizzled](size_t I, const SDValue &Lane) {
2033       return Swizzled == GetSwizzleSrcs(I, Lane);
2034     };
2035   } else if (NumShuffleLanes >= NumConstantLanes &&
2036              NumShuffleLanes >= NumSplatLanes) {
2037     size_t DestLaneSize = VecT.getVectorElementType().getFixedSizeInBits() / 8;
2038     size_t DestLaneCount = VecT.getVectorNumElements();
2039     size_t Scale1 = 1;
2040     size_t Scale2 = 1;
2041     SDValue Src1 = ShuffleSrc1;
2042     SDValue Src2 = ShuffleSrc2 ? ShuffleSrc2 : DAG.getUNDEF(VecT);
2043     if (Src1.getValueType() != VecT) {
2044       size_t LaneSize =
2045           Src1.getValueType().getVectorElementType().getFixedSizeInBits() / 8;
2046       assert(LaneSize > DestLaneSize);
2047       Scale1 = LaneSize / DestLaneSize;
2048       Src1 = DAG.getBitcast(VecT, Src1);
2049     }
2050     if (Src2.getValueType() != VecT) {
2051       size_t LaneSize =
2052           Src2.getValueType().getVectorElementType().getFixedSizeInBits() / 8;
2053       assert(LaneSize > DestLaneSize);
2054       Scale2 = LaneSize / DestLaneSize;
2055       Src2 = DAG.getBitcast(VecT, Src2);
2056     }
2057 
2058     int Mask[16];
2059     assert(DestLaneCount <= 16);
2060     for (size_t I = 0; I < DestLaneCount; ++I) {
2061       const SDValue &Lane = Op->getOperand(I);
2062       SDValue Src = GetShuffleSrc(Lane);
2063       if (Src == ShuffleSrc1) {
2064         Mask[I] = Lane->getConstantOperandVal(1) * Scale1;
2065       } else if (Src && Src == ShuffleSrc2) {
2066         Mask[I] = DestLaneCount + Lane->getConstantOperandVal(1) * Scale2;
2067       } else {
2068         Mask[I] = -1;
2069       }
2070     }
2071     ArrayRef<int> MaskRef(Mask, DestLaneCount);
2072     Result = DAG.getVectorShuffle(VecT, DL, Src1, Src2, MaskRef);
2073     IsLaneConstructed = [&](size_t, const SDValue &Lane) {
2074       auto Src = GetShuffleSrc(Lane);
2075       return Src == ShuffleSrc1 || (Src && Src == ShuffleSrc2);
2076     };
2077   } else if (NumConstantLanes >= NumSplatLanes) {
2078     SmallVector<SDValue, 16> ConstLanes;
2079     for (const SDValue &Lane : Op->op_values()) {
2080       if (IsConstant(Lane)) {
2081         // Values may need to be fixed so that they will sign extend to be
2082         // within the expected range during ISel. Check whether the value is in
2083         // bounds based on the lane bit width and if it is out of bounds, lop
2084         // off the extra bits and subtract 2^n to reflect giving the high bit
2085         // value -2^(n-1) rather than +2^(n-1). Skip the i64 case because it
2086         // cannot possibly be out of range.
2087         auto *Const = dyn_cast<ConstantSDNode>(Lane.getNode());
2088         int64_t Val = Const ? Const->getSExtValue() : 0;
2089         uint64_t LaneBits = 128 / Lanes;
2090         assert((LaneBits == 64 || Val >= -(1ll << (LaneBits - 1))) &&
2091                "Unexpected out of bounds negative value");
2092         if (Const && LaneBits != 64 && Val > (1ll << (LaneBits - 1)) - 1) {
2093           auto NewVal = ((uint64_t)Val % (1ll << LaneBits)) - (1ll << LaneBits);
2094           ConstLanes.push_back(DAG.getConstant(NewVal, SDLoc(Lane), LaneT));
2095         } else {
2096           ConstLanes.push_back(Lane);
2097         }
2098       } else if (LaneT.isFloatingPoint()) {
2099         ConstLanes.push_back(DAG.getConstantFP(0, DL, LaneT));
2100       } else {
2101         ConstLanes.push_back(DAG.getConstant(0, DL, LaneT));
2102       }
2103     }
2104     Result = DAG.getBuildVector(VecT, DL, ConstLanes);
2105     IsLaneConstructed = [&IsConstant](size_t _, const SDValue &Lane) {
2106       return IsConstant(Lane);
2107     };
2108   } else {
2109     // Use a splat, but possibly a load_splat
2110     LoadSDNode *SplattedLoad;
2111     if ((SplattedLoad = dyn_cast<LoadSDNode>(SplatValue)) &&
2112         SplattedLoad->getMemoryVT() == VecT.getVectorElementType()) {
2113       Result = DAG.getMemIntrinsicNode(
2114           WebAssemblyISD::LOAD_SPLAT, DL, DAG.getVTList(VecT),
2115           {SplattedLoad->getChain(), SplattedLoad->getBasePtr(),
2116            SplattedLoad->getOffset()},
2117           SplattedLoad->getMemoryVT(), SplattedLoad->getMemOperand());
2118     } else {
2119       Result = DAG.getSplatBuildVector(VecT, DL, SplatValue);
2120     }
2121     IsLaneConstructed = [&SplatValue](size_t _, const SDValue &Lane) {
2122       return Lane == SplatValue;
2123     };
2124   }
2125 
2126   assert(Result);
2127   assert(IsLaneConstructed);
2128 
2129   // Add replace_lane instructions for any unhandled values
2130   for (size_t I = 0; I < Lanes; ++I) {
2131     const SDValue &Lane = Op->getOperand(I);
2132     if (!Lane.isUndef() && !IsLaneConstructed(I, Lane))
2133       Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VecT, Result, Lane,
2134                            DAG.getConstant(I, DL, MVT::i32));
2135   }
2136 
2137   return Result;
2138 }
2139 
2140 SDValue
2141 WebAssemblyTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
2142                                                SelectionDAG &DAG) const {
2143   SDLoc DL(Op);
2144   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op.getNode())->getMask();
2145   MVT VecType = Op.getOperand(0).getSimpleValueType();
2146   assert(VecType.is128BitVector() && "Unexpected shuffle vector type");
2147   size_t LaneBytes = VecType.getVectorElementType().getSizeInBits() / 8;
2148 
2149   // Space for two vector args and sixteen mask indices
2150   SDValue Ops[18];
2151   size_t OpIdx = 0;
2152   Ops[OpIdx++] = Op.getOperand(0);
2153   Ops[OpIdx++] = Op.getOperand(1);
2154 
2155   // Expand mask indices to byte indices and materialize them as operands
2156   for (int M : Mask) {
2157     for (size_t J = 0; J < LaneBytes; ++J) {
2158       // Lower undefs (represented by -1 in mask) to zero
2159       uint64_t ByteIndex = M == -1 ? 0 : (uint64_t)M * LaneBytes + J;
2160       Ops[OpIdx++] = DAG.getConstant(ByteIndex, DL, MVT::i32);
2161     }
2162   }
2163 
2164   return DAG.getNode(WebAssemblyISD::SHUFFLE, DL, Op.getValueType(), Ops);
2165 }
2166 
2167 SDValue WebAssemblyTargetLowering::LowerSETCC(SDValue Op,
2168                                               SelectionDAG &DAG) const {
2169   SDLoc DL(Op);
2170   // The legalizer does not know how to expand the unsupported comparison modes
2171   // of i64x2 vectors, so we manually unroll them here.
2172   assert(Op->getOperand(0)->getSimpleValueType(0) == MVT::v2i64);
2173   SmallVector<SDValue, 2> LHS, RHS;
2174   DAG.ExtractVectorElements(Op->getOperand(0), LHS);
2175   DAG.ExtractVectorElements(Op->getOperand(1), RHS);
2176   const SDValue &CC = Op->getOperand(2);
2177   auto MakeLane = [&](unsigned I) {
2178     return DAG.getNode(ISD::SELECT_CC, DL, MVT::i64, LHS[I], RHS[I],
2179                        DAG.getConstant(uint64_t(-1), DL, MVT::i64),
2180                        DAG.getConstant(uint64_t(0), DL, MVT::i64), CC);
2181   };
2182   return DAG.getBuildVector(Op->getValueType(0), DL,
2183                             {MakeLane(0), MakeLane(1)});
2184 }
2185 
2186 SDValue
2187 WebAssemblyTargetLowering::LowerAccessVectorElement(SDValue Op,
2188                                                     SelectionDAG &DAG) const {
2189   // Allow constant lane indices, expand variable lane indices
2190   SDNode *IdxNode = Op.getOperand(Op.getNumOperands() - 1).getNode();
2191   if (isa<ConstantSDNode>(IdxNode) || IdxNode->isUndef())
2192     return Op;
2193   else
2194     // Perform default expansion
2195     return SDValue();
2196 }
2197 
2198 static SDValue unrollVectorShift(SDValue Op, SelectionDAG &DAG) {
2199   EVT LaneT = Op.getSimpleValueType().getVectorElementType();
2200   // 32-bit and 64-bit unrolled shifts will have proper semantics
2201   if (LaneT.bitsGE(MVT::i32))
2202     return DAG.UnrollVectorOp(Op.getNode());
2203   // Otherwise mask the shift value to get proper semantics from 32-bit shift
2204   SDLoc DL(Op);
2205   size_t NumLanes = Op.getSimpleValueType().getVectorNumElements();
2206   SDValue Mask = DAG.getConstant(LaneT.getSizeInBits() - 1, DL, MVT::i32);
2207   unsigned ShiftOpcode = Op.getOpcode();
2208   SmallVector<SDValue, 16> ShiftedElements;
2209   DAG.ExtractVectorElements(Op.getOperand(0), ShiftedElements, 0, 0, MVT::i32);
2210   SmallVector<SDValue, 16> ShiftElements;
2211   DAG.ExtractVectorElements(Op.getOperand(1), ShiftElements, 0, 0, MVT::i32);
2212   SmallVector<SDValue, 16> UnrolledOps;
2213   for (size_t i = 0; i < NumLanes; ++i) {
2214     SDValue MaskedShiftValue =
2215         DAG.getNode(ISD::AND, DL, MVT::i32, ShiftElements[i], Mask);
2216     SDValue ShiftedValue = ShiftedElements[i];
2217     if (ShiftOpcode == ISD::SRA)
2218       ShiftedValue = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i32,
2219                                  ShiftedValue, DAG.getValueType(LaneT));
2220     UnrolledOps.push_back(
2221         DAG.getNode(ShiftOpcode, DL, MVT::i32, ShiftedValue, MaskedShiftValue));
2222   }
2223   return DAG.getBuildVector(Op.getValueType(), DL, UnrolledOps);
2224 }
2225 
2226 SDValue WebAssemblyTargetLowering::LowerShift(SDValue Op,
2227                                               SelectionDAG &DAG) const {
2228   SDLoc DL(Op);
2229 
2230   // Only manually lower vector shifts
2231   assert(Op.getSimpleValueType().isVector());
2232 
2233   auto ShiftVal = DAG.getSplatValue(Op.getOperand(1));
2234   if (!ShiftVal)
2235     return unrollVectorShift(Op, DAG);
2236 
2237   // Use anyext because none of the high bits can affect the shift
2238   ShiftVal = DAG.getAnyExtOrTrunc(ShiftVal, DL, MVT::i32);
2239 
2240   unsigned Opcode;
2241   switch (Op.getOpcode()) {
2242   case ISD::SHL:
2243     Opcode = WebAssemblyISD::VEC_SHL;
2244     break;
2245   case ISD::SRA:
2246     Opcode = WebAssemblyISD::VEC_SHR_S;
2247     break;
2248   case ISD::SRL:
2249     Opcode = WebAssemblyISD::VEC_SHR_U;
2250     break;
2251   default:
2252     llvm_unreachable("unexpected opcode");
2253   }
2254 
2255   return DAG.getNode(Opcode, DL, Op.getValueType(), Op.getOperand(0), ShiftVal);
2256 }
2257 
2258 SDValue WebAssemblyTargetLowering::LowerFP_TO_INT_SAT(SDValue Op,
2259                                                       SelectionDAG &DAG) const {
2260   SDLoc DL(Op);
2261   EVT ResT = Op.getValueType();
2262   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2263 
2264   if ((ResT == MVT::i32 || ResT == MVT::i64) &&
2265       (SatVT == MVT::i32 || SatVT == MVT::i64))
2266     return Op;
2267 
2268   if (ResT == MVT::v4i32 && SatVT == MVT::i32)
2269     return Op;
2270 
2271   return SDValue();
2272 }
2273 
2274 //===----------------------------------------------------------------------===//
2275 //   Custom DAG combine hooks
2276 //===----------------------------------------------------------------------===//
2277 static SDValue
2278 performVECTOR_SHUFFLECombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
2279   auto &DAG = DCI.DAG;
2280   auto Shuffle = cast<ShuffleVectorSDNode>(N);
2281 
2282   // Hoist vector bitcasts that don't change the number of lanes out of unary
2283   // shuffles, where they are less likely to get in the way of other combines.
2284   // (shuffle (vNxT1 (bitcast (vNxT0 x))), undef, mask) ->
2285   //  (vNxT1 (bitcast (vNxT0 (shuffle x, undef, mask))))
2286   SDValue Bitcast = N->getOperand(0);
2287   if (Bitcast.getOpcode() != ISD::BITCAST)
2288     return SDValue();
2289   if (!N->getOperand(1).isUndef())
2290     return SDValue();
2291   SDValue CastOp = Bitcast.getOperand(0);
2292   MVT SrcType = CastOp.getSimpleValueType();
2293   MVT DstType = Bitcast.getSimpleValueType();
2294   if (!SrcType.is128BitVector() ||
2295       SrcType.getVectorNumElements() != DstType.getVectorNumElements())
2296     return SDValue();
2297   SDValue NewShuffle = DAG.getVectorShuffle(
2298       SrcType, SDLoc(N), CastOp, DAG.getUNDEF(SrcType), Shuffle->getMask());
2299   return DAG.getBitcast(DstType, NewShuffle);
2300 }
2301 
2302 static SDValue
2303 performVectorExtendCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
2304   auto &DAG = DCI.DAG;
2305   assert(N->getOpcode() == ISD::SIGN_EXTEND ||
2306          N->getOpcode() == ISD::ZERO_EXTEND);
2307 
2308   // Combine ({s,z}ext (extract_subvector src, i)) into a widening operation if
2309   // possible before the extract_subvector can be expanded.
2310   auto Extract = N->getOperand(0);
2311   if (Extract.getOpcode() != ISD::EXTRACT_SUBVECTOR)
2312     return SDValue();
2313   auto Source = Extract.getOperand(0);
2314   auto *IndexNode = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
2315   if (IndexNode == nullptr)
2316     return SDValue();
2317   auto Index = IndexNode->getZExtValue();
2318 
2319   // Only v8i8, v4i16, and v2i32 extracts can be widened, and only if the
2320   // extracted subvector is the low or high half of its source.
2321   EVT ResVT = N->getValueType(0);
2322   if (ResVT == MVT::v8i16) {
2323     if (Extract.getValueType() != MVT::v8i8 ||
2324         Source.getValueType() != MVT::v16i8 || (Index != 0 && Index != 8))
2325       return SDValue();
2326   } else if (ResVT == MVT::v4i32) {
2327     if (Extract.getValueType() != MVT::v4i16 ||
2328         Source.getValueType() != MVT::v8i16 || (Index != 0 && Index != 4))
2329       return SDValue();
2330   } else if (ResVT == MVT::v2i64) {
2331     if (Extract.getValueType() != MVT::v2i32 ||
2332         Source.getValueType() != MVT::v4i32 || (Index != 0 && Index != 2))
2333       return SDValue();
2334   } else {
2335     return SDValue();
2336   }
2337 
2338   bool IsSext = N->getOpcode() == ISD::SIGN_EXTEND;
2339   bool IsLow = Index == 0;
2340 
2341   unsigned Op = IsSext ? (IsLow ? WebAssemblyISD::EXTEND_LOW_S
2342                                 : WebAssemblyISD::EXTEND_HIGH_S)
2343                        : (IsLow ? WebAssemblyISD::EXTEND_LOW_U
2344                                 : WebAssemblyISD::EXTEND_HIGH_U);
2345 
2346   return DAG.getNode(Op, SDLoc(N), ResVT, Source);
2347 }
2348 
2349 static SDValue
2350 performVectorTruncZeroCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
2351   auto &DAG = DCI.DAG;
2352 
2353   auto GetWasmConversionOp = [](unsigned Op) {
2354     switch (Op) {
2355     case ISD::FP_TO_SINT_SAT:
2356       return WebAssemblyISD::TRUNC_SAT_ZERO_S;
2357     case ISD::FP_TO_UINT_SAT:
2358       return WebAssemblyISD::TRUNC_SAT_ZERO_U;
2359     case ISD::FP_ROUND:
2360       return WebAssemblyISD::DEMOTE_ZERO;
2361     }
2362     llvm_unreachable("unexpected op");
2363   };
2364 
2365   auto IsZeroSplat = [](SDValue SplatVal) {
2366     auto *Splat = dyn_cast<BuildVectorSDNode>(SplatVal.getNode());
2367     APInt SplatValue, SplatUndef;
2368     unsigned SplatBitSize;
2369     bool HasAnyUndefs;
2370     return Splat &&
2371            Splat->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
2372                                   HasAnyUndefs) &&
2373            SplatValue == 0;
2374   };
2375 
2376   if (N->getOpcode() == ISD::CONCAT_VECTORS) {
2377     // Combine this:
2378     //
2379     //   (concat_vectors (v2i32 (fp_to_{s,u}int_sat $x, 32)), (v2i32 (splat 0)))
2380     //
2381     // into (i32x4.trunc_sat_f64x2_zero_{s,u} $x).
2382     //
2383     // Or this:
2384     //
2385     //   (concat_vectors (v2f32 (fp_round (v2f64 $x))), (v2f32 (splat 0)))
2386     //
2387     // into (f32x4.demote_zero_f64x2 $x).
2388     EVT ResVT;
2389     EVT ExpectedConversionType;
2390     auto Conversion = N->getOperand(0);
2391     auto ConversionOp = Conversion.getOpcode();
2392     switch (ConversionOp) {
2393     case ISD::FP_TO_SINT_SAT:
2394     case ISD::FP_TO_UINT_SAT:
2395       ResVT = MVT::v4i32;
2396       ExpectedConversionType = MVT::v2i32;
2397       break;
2398     case ISD::FP_ROUND:
2399       ResVT = MVT::v4f32;
2400       ExpectedConversionType = MVT::v2f32;
2401       break;
2402     default:
2403       return SDValue();
2404     }
2405 
2406     if (N->getValueType(0) != ResVT)
2407       return SDValue();
2408 
2409     if (Conversion.getValueType() != ExpectedConversionType)
2410       return SDValue();
2411 
2412     auto Source = Conversion.getOperand(0);
2413     if (Source.getValueType() != MVT::v2f64)
2414       return SDValue();
2415 
2416     if (!IsZeroSplat(N->getOperand(1)) ||
2417         N->getOperand(1).getValueType() != ExpectedConversionType)
2418       return SDValue();
2419 
2420     unsigned Op = GetWasmConversionOp(ConversionOp);
2421     return DAG.getNode(Op, SDLoc(N), ResVT, Source);
2422   }
2423 
2424   // Combine this:
2425   //
2426   //   (fp_to_{s,u}int_sat (concat_vectors $x, (v2f64 (splat 0))), 32)
2427   //
2428   // into (i32x4.trunc_sat_f64x2_zero_{s,u} $x).
2429   //
2430   // Or this:
2431   //
2432   //   (v4f32 (fp_round (concat_vectors $x, (v2f64 (splat 0)))))
2433   //
2434   // into (f32x4.demote_zero_f64x2 $x).
2435   EVT ResVT;
2436   auto ConversionOp = N->getOpcode();
2437   switch (ConversionOp) {
2438   case ISD::FP_TO_SINT_SAT:
2439   case ISD::FP_TO_UINT_SAT:
2440     ResVT = MVT::v4i32;
2441     break;
2442   case ISD::FP_ROUND:
2443     ResVT = MVT::v4f32;
2444     break;
2445   default:
2446     llvm_unreachable("unexpected op");
2447   }
2448 
2449   if (N->getValueType(0) != ResVT)
2450     return SDValue();
2451 
2452   auto Concat = N->getOperand(0);
2453   if (Concat.getValueType() != MVT::v4f64)
2454     return SDValue();
2455 
2456   auto Source = Concat.getOperand(0);
2457   if (Source.getValueType() != MVT::v2f64)
2458     return SDValue();
2459 
2460   if (!IsZeroSplat(Concat.getOperand(1)) ||
2461       Concat.getOperand(1).getValueType() != MVT::v2f64)
2462     return SDValue();
2463 
2464   unsigned Op = GetWasmConversionOp(ConversionOp);
2465   return DAG.getNode(Op, SDLoc(N), ResVT, Source);
2466 }
2467 
2468 SDValue
2469 WebAssemblyTargetLowering::PerformDAGCombine(SDNode *N,
2470                                              DAGCombinerInfo &DCI) const {
2471   switch (N->getOpcode()) {
2472   default:
2473     return SDValue();
2474   case ISD::VECTOR_SHUFFLE:
2475     return performVECTOR_SHUFFLECombine(N, DCI);
2476   case ISD::SIGN_EXTEND:
2477   case ISD::ZERO_EXTEND:
2478     return performVectorExtendCombine(N, DCI);
2479   case ISD::FP_TO_SINT_SAT:
2480   case ISD::FP_TO_UINT_SAT:
2481   case ISD::FP_ROUND:
2482   case ISD::CONCAT_VECTORS:
2483     return performVectorTruncZeroCombine(N, DCI);
2484   }
2485 }
2486