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