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