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