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