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     // Support saturating add for i8x16 and i16x8
124     for (auto Op : {ISD::SADDSAT, ISD::UADDSAT})
125       for (auto T : {MVT::v16i8, MVT::v8i16})
126         setOperationAction(Op, T, Legal);
127 
128     // Support integer abs
129     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
130       setOperationAction(ISD::ABS, T, Legal);
131 
132     // Custom lower BUILD_VECTORs to minimize number of replace_lanes
133     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
134                    MVT::v2f64})
135       setOperationAction(ISD::BUILD_VECTOR, T, Custom);
136 
137     // We have custom shuffle lowering to expose the shuffle mask
138     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
139                    MVT::v2f64})
140       setOperationAction(ISD::VECTOR_SHUFFLE, T, Custom);
141 
142     // Custom lowering since wasm shifts must have a scalar shift amount
143     for (auto Op : {ISD::SHL, ISD::SRA, ISD::SRL})
144       for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64})
145         setOperationAction(Op, T, Custom);
146 
147     // Custom lower lane accesses to expand out variable indices
148     for (auto Op : {ISD::EXTRACT_VECTOR_ELT, ISD::INSERT_VECTOR_ELT})
149       for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
150                      MVT::v2f64})
151         setOperationAction(Op, T, Custom);
152 
153     // There is no i64x2.mul instruction
154     // TODO: Actually, there is now. Implement it.
155     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
156 
157     // There are no vector select instructions
158     for (auto Op : {ISD::VSELECT, ISD::SELECT_CC, ISD::SELECT})
159       for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
160                      MVT::v2f64})
161         setOperationAction(Op, T, Expand);
162 
163     // Expand integer operations supported for scalars but not SIMD
164     for (auto Op : {ISD::CTLZ, ISD::CTTZ, ISD::CTPOP, ISD::SDIV, ISD::UDIV,
165                     ISD::SREM, ISD::UREM, ISD::ROTL, ISD::ROTR})
166       for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64})
167         setOperationAction(Op, T, Expand);
168 
169     // But we do have integer min and max operations
170     for (auto Op : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
171       for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
172         setOperationAction(Op, T, Legal);
173 
174     // Expand float operations supported for scalars but not SIMD
175     for (auto Op : {ISD::FCEIL, ISD::FFLOOR, ISD::FTRUNC, ISD::FNEARBYINT,
176                     ISD::FCOPYSIGN, ISD::FLOG, ISD::FLOG2, ISD::FLOG10,
177                     ISD::FEXP, ISD::FEXP2, ISD::FRINT})
178       for (auto T : {MVT::v4f32, MVT::v2f64})
179         setOperationAction(Op, T, Expand);
180 
181     // Expand operations not supported for i64x2 vectors
182     for (unsigned CC = 0; CC < ISD::SETCC_INVALID; ++CC)
183       setCondCodeAction(static_cast<ISD::CondCode>(CC), MVT::v2i64, Custom);
184 
185     // 64x2 conversions are not in the spec
186     for (auto Op :
187          {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT})
188       for (auto T : {MVT::v2i64, MVT::v2f64})
189         setOperationAction(Op, T, Expand);
190   }
191 
192   // As a special case, these operators use the type to mean the type to
193   // sign-extend from.
194   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
195   if (!Subtarget->hasSignExt()) {
196     // Sign extends are legal only when extending a vector extract
197     auto Action = Subtarget->hasSIMD128() ? Custom : Expand;
198     for (auto T : {MVT::i8, MVT::i16, MVT::i32})
199       setOperationAction(ISD::SIGN_EXTEND_INREG, T, Action);
200   }
201   for (auto T : MVT::integer_fixedlen_vector_valuetypes())
202     setOperationAction(ISD::SIGN_EXTEND_INREG, T, Expand);
203 
204   // Dynamic stack allocation: use the default expansion.
205   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
206   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
207   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVTPtr, Expand);
208 
209   setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
210   setOperationAction(ISD::CopyToReg, MVT::Other, Custom);
211 
212   // Expand these forms; we pattern-match the forms that we can handle in isel.
213   for (auto T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64})
214     for (auto Op : {ISD::BR_CC, ISD::SELECT_CC})
215       setOperationAction(Op, T, Expand);
216 
217   // We have custom switch handling.
218   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
219 
220   // WebAssembly doesn't have:
221   //  - Floating-point extending loads.
222   //  - Floating-point truncating stores.
223   //  - i1 extending loads.
224   //  - truncating SIMD stores and most extending loads
225   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
226   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
227   for (auto T : MVT::integer_valuetypes())
228     for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD})
229       setLoadExtAction(Ext, T, MVT::i1, Promote);
230   if (Subtarget->hasSIMD128()) {
231     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64, MVT::v4f32,
232                    MVT::v2f64}) {
233       for (auto MemT : MVT::fixedlen_vector_valuetypes()) {
234         if (MVT(T) != MemT) {
235           setTruncStoreAction(T, MemT, Expand);
236           for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD})
237             setLoadExtAction(Ext, T, MemT, Expand);
238         }
239       }
240     }
241     // But some vector extending loads are legal
242     if (Subtarget->hasUnimplementedSIMD128()) {
243       for (auto Ext : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) {
244         setLoadExtAction(Ext, MVT::v8i16, MVT::v8i8, Legal);
245         setLoadExtAction(Ext, MVT::v4i32, MVT::v4i16, Legal);
246         setLoadExtAction(Ext, MVT::v2i64, MVT::v2i32, Legal);
247       }
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   if (!Subtarget->hasUnimplementedSIMD128())
603     return false;
604   MVT ExtT = ExtVal.getSimpleValueType();
605   MVT MemT = cast<LoadSDNode>(ExtVal->getOperand(0))->getSimpleValueType(0);
606   return (ExtT == MVT::v8i16 && MemT == MVT::v8i8) ||
607          (ExtT == MVT::v4i32 && MemT == MVT::v4i16) ||
608          (ExtT == MVT::v2i64 && MemT == MVT::v2i32);
609 }
610 
611 EVT WebAssemblyTargetLowering::getSetCCResultType(const DataLayout &DL,
612                                                   LLVMContext &C,
613                                                   EVT VT) const {
614   if (VT.isVector())
615     return VT.changeVectorElementTypeToInteger();
616 
617   return TargetLowering::getSetCCResultType(DL, C, VT);
618 }
619 
620 bool WebAssemblyTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
621                                                    const CallInst &I,
622                                                    MachineFunction &MF,
623                                                    unsigned Intrinsic) const {
624   switch (Intrinsic) {
625   case Intrinsic::wasm_atomic_notify:
626     Info.opc = ISD::INTRINSIC_W_CHAIN;
627     Info.memVT = MVT::i32;
628     Info.ptrVal = I.getArgOperand(0);
629     Info.offset = 0;
630     Info.align = Align(4);
631     // atomic.notify instruction does not really load the memory specified with
632     // this argument, but MachineMemOperand should either be load or store, so
633     // we set this to a load.
634     // FIXME Volatile isn't really correct, but currently all LLVM atomic
635     // instructions are treated as volatiles in the backend, so we should be
636     // consistent. The same applies for wasm_atomic_wait intrinsics too.
637     Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
638     return true;
639   case Intrinsic::wasm_atomic_wait_i32:
640     Info.opc = ISD::INTRINSIC_W_CHAIN;
641     Info.memVT = MVT::i32;
642     Info.ptrVal = I.getArgOperand(0);
643     Info.offset = 0;
644     Info.align = Align(4);
645     Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
646     return true;
647   case Intrinsic::wasm_atomic_wait_i64:
648     Info.opc = ISD::INTRINSIC_W_CHAIN;
649     Info.memVT = MVT::i64;
650     Info.ptrVal = I.getArgOperand(0);
651     Info.offset = 0;
652     Info.align = Align(8);
653     Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
654     return true;
655   default:
656     return false;
657   }
658 }
659 
660 //===----------------------------------------------------------------------===//
661 // WebAssembly Lowering private implementation.
662 //===----------------------------------------------------------------------===//
663 
664 //===----------------------------------------------------------------------===//
665 // Lowering Code
666 //===----------------------------------------------------------------------===//
667 
668 static void fail(const SDLoc &DL, SelectionDAG &DAG, const char *Msg) {
669   MachineFunction &MF = DAG.getMachineFunction();
670   DAG.getContext()->diagnose(
671       DiagnosticInfoUnsupported(MF.getFunction(), Msg, DL.getDebugLoc()));
672 }
673 
674 // Test whether the given calling convention is supported.
675 static bool callingConvSupported(CallingConv::ID CallConv) {
676   // We currently support the language-independent target-independent
677   // conventions. We don't yet have a way to annotate calls with properties like
678   // "cold", and we don't have any call-clobbered registers, so these are mostly
679   // all handled the same.
680   return CallConv == CallingConv::C || CallConv == CallingConv::Fast ||
681          CallConv == CallingConv::Cold ||
682          CallConv == CallingConv::PreserveMost ||
683          CallConv == CallingConv::PreserveAll ||
684          CallConv == CallingConv::CXX_FAST_TLS ||
685          CallConv == CallingConv::WASM_EmscriptenInvoke ||
686          CallConv == CallingConv::Swift;
687 }
688 
689 SDValue
690 WebAssemblyTargetLowering::LowerCall(CallLoweringInfo &CLI,
691                                      SmallVectorImpl<SDValue> &InVals) const {
692   SelectionDAG &DAG = CLI.DAG;
693   SDLoc DL = CLI.DL;
694   SDValue Chain = CLI.Chain;
695   SDValue Callee = CLI.Callee;
696   MachineFunction &MF = DAG.getMachineFunction();
697   auto Layout = MF.getDataLayout();
698 
699   CallingConv::ID CallConv = CLI.CallConv;
700   if (!callingConvSupported(CallConv))
701     fail(DL, DAG,
702          "WebAssembly doesn't support language-specific or target-specific "
703          "calling conventions yet");
704   if (CLI.IsPatchPoint)
705     fail(DL, DAG, "WebAssembly doesn't support patch point yet");
706 
707   if (CLI.IsTailCall) {
708     auto NoTail = [&](const char *Msg) {
709       if (CLI.CB && CLI.CB->isMustTailCall())
710         fail(DL, DAG, Msg);
711       CLI.IsTailCall = false;
712     };
713 
714     if (!Subtarget->hasTailCall())
715       NoTail("WebAssembly 'tail-call' feature not enabled");
716 
717     // Varargs calls cannot be tail calls because the buffer is on the stack
718     if (CLI.IsVarArg)
719       NoTail("WebAssembly does not support varargs tail calls");
720 
721     // Do not tail call unless caller and callee return types match
722     const Function &F = MF.getFunction();
723     const TargetMachine &TM = getTargetMachine();
724     Type *RetTy = F.getReturnType();
725     SmallVector<MVT, 4> CallerRetTys;
726     SmallVector<MVT, 4> CalleeRetTys;
727     computeLegalValueVTs(F, TM, RetTy, CallerRetTys);
728     computeLegalValueVTs(F, TM, CLI.RetTy, CalleeRetTys);
729     bool TypesMatch = CallerRetTys.size() == CalleeRetTys.size() &&
730                       std::equal(CallerRetTys.begin(), CallerRetTys.end(),
731                                  CalleeRetTys.begin());
732     if (!TypesMatch)
733       NoTail("WebAssembly tail call requires caller and callee return types to "
734              "match");
735 
736     // If pointers to local stack values are passed, we cannot tail call
737     if (CLI.CB) {
738       for (auto &Arg : CLI.CB->args()) {
739         Value *Val = Arg.get();
740         // Trace the value back through pointer operations
741         while (true) {
742           Value *Src = Val->stripPointerCastsAndAliases();
743           if (auto *GEP = dyn_cast<GetElementPtrInst>(Src))
744             Src = GEP->getPointerOperand();
745           if (Val == Src)
746             break;
747           Val = Src;
748         }
749         if (isa<AllocaInst>(Val)) {
750           NoTail(
751               "WebAssembly does not support tail calling with stack arguments");
752           break;
753         }
754       }
755     }
756   }
757 
758   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
759   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
760   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
761 
762   // The generic code may have added an sret argument. If we're lowering an
763   // invoke function, the ABI requires that the function pointer be the first
764   // argument, so we may have to swap the arguments.
765   if (CallConv == CallingConv::WASM_EmscriptenInvoke && Outs.size() >= 2 &&
766       Outs[0].Flags.isSRet()) {
767     std::swap(Outs[0], Outs[1]);
768     std::swap(OutVals[0], OutVals[1]);
769   }
770 
771   bool HasSwiftSelfArg = false;
772   bool HasSwiftErrorArg = false;
773   unsigned NumFixedArgs = 0;
774   for (unsigned I = 0; I < Outs.size(); ++I) {
775     const ISD::OutputArg &Out = Outs[I];
776     SDValue &OutVal = OutVals[I];
777     HasSwiftSelfArg |= Out.Flags.isSwiftSelf();
778     HasSwiftErrorArg |= Out.Flags.isSwiftError();
779     if (Out.Flags.isNest())
780       fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
781     if (Out.Flags.isInAlloca())
782       fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
783     if (Out.Flags.isInConsecutiveRegs())
784       fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
785     if (Out.Flags.isInConsecutiveRegsLast())
786       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
787     if (Out.Flags.isByVal() && Out.Flags.getByValSize() != 0) {
788       auto &MFI = MF.getFrameInfo();
789       int FI = MFI.CreateStackObject(Out.Flags.getByValSize(),
790                                      Out.Flags.getNonZeroByValAlign(),
791                                      /*isSS=*/false);
792       SDValue SizeNode =
793           DAG.getConstant(Out.Flags.getByValSize(), DL, MVT::i32);
794       SDValue FINode = DAG.getFrameIndex(FI, getPointerTy(Layout));
795       Chain = DAG.getMemcpy(
796           Chain, DL, FINode, OutVal, SizeNode, Out.Flags.getNonZeroByValAlign(),
797           /*isVolatile*/ false, /*AlwaysInline=*/false,
798           /*isTailCall*/ false, MachinePointerInfo(), MachinePointerInfo());
799       OutVal = FINode;
800     }
801     // Count the number of fixed args *after* legalization.
802     NumFixedArgs += Out.IsFixed;
803   }
804 
805   bool IsVarArg = CLI.IsVarArg;
806   auto PtrVT = getPointerTy(Layout);
807 
808   // For swiftcc, emit additional swiftself and swifterror arguments
809   // if there aren't. These additional arguments are also added for callee
810   // signature They are necessary to match callee and caller signature for
811   // indirect call.
812   if (CallConv == CallingConv::Swift) {
813     if (!HasSwiftSelfArg) {
814       NumFixedArgs++;
815       ISD::OutputArg Arg;
816       Arg.Flags.setSwiftSelf();
817       CLI.Outs.push_back(Arg);
818       SDValue ArgVal = DAG.getUNDEF(PtrVT);
819       CLI.OutVals.push_back(ArgVal);
820     }
821     if (!HasSwiftErrorArg) {
822       NumFixedArgs++;
823       ISD::OutputArg Arg;
824       Arg.Flags.setSwiftError();
825       CLI.Outs.push_back(Arg);
826       SDValue ArgVal = DAG.getUNDEF(PtrVT);
827       CLI.OutVals.push_back(ArgVal);
828     }
829   }
830 
831   // Analyze operands of the call, assigning locations to each operand.
832   SmallVector<CCValAssign, 16> ArgLocs;
833   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
834 
835   if (IsVarArg) {
836     // Outgoing non-fixed arguments are placed in a buffer. First
837     // compute their offsets and the total amount of buffer space needed.
838     for (unsigned I = NumFixedArgs; I < Outs.size(); ++I) {
839       const ISD::OutputArg &Out = Outs[I];
840       SDValue &Arg = OutVals[I];
841       EVT VT = Arg.getValueType();
842       assert(VT != MVT::iPTR && "Legalized args should be concrete");
843       Type *Ty = VT.getTypeForEVT(*DAG.getContext());
844       unsigned Align = std::max(Out.Flags.getOrigAlign(),
845                                 Layout.getABITypeAlignment(Ty));
846       unsigned Offset = CCInfo.AllocateStack(Layout.getTypeAllocSize(Ty),
847                                              Align);
848       CCInfo.addLoc(CCValAssign::getMem(ArgLocs.size(), VT.getSimpleVT(),
849                                         Offset, VT.getSimpleVT(),
850                                         CCValAssign::Full));
851     }
852   }
853 
854   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
855 
856   SDValue FINode;
857   if (IsVarArg && NumBytes) {
858     // For non-fixed arguments, next emit stores to store the argument values
859     // to the stack buffer at the offsets computed above.
860     int FI = MF.getFrameInfo().CreateStackObject(NumBytes,
861                                                  Layout.getStackAlignment(),
862                                                  /*isSS=*/false);
863     unsigned ValNo = 0;
864     SmallVector<SDValue, 8> Chains;
865     for (SDValue Arg :
866          make_range(OutVals.begin() + NumFixedArgs, OutVals.end())) {
867       assert(ArgLocs[ValNo].getValNo() == ValNo &&
868              "ArgLocs should remain in order and only hold varargs args");
869       unsigned Offset = ArgLocs[ValNo++].getLocMemOffset();
870       FINode = DAG.getFrameIndex(FI, getPointerTy(Layout));
871       SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, FINode,
872                                 DAG.getConstant(Offset, DL, PtrVT));
873       Chains.push_back(
874           DAG.getStore(Chain, DL, Arg, Add,
875                        MachinePointerInfo::getFixedStack(MF, FI, Offset), 0));
876     }
877     if (!Chains.empty())
878       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
879   } else if (IsVarArg) {
880     FINode = DAG.getIntPtrConstant(0, DL);
881   }
882 
883   if (Callee->getOpcode() == ISD::GlobalAddress) {
884     // If the callee is a GlobalAddress node (quite common, every direct call
885     // is) turn it into a TargetGlobalAddress node so that LowerGlobalAddress
886     // doesn't at MO_GOT which is not needed for direct calls.
887     GlobalAddressSDNode* GA = cast<GlobalAddressSDNode>(Callee);
888     Callee = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
889                                         getPointerTy(DAG.getDataLayout()),
890                                         GA->getOffset());
891     Callee = DAG.getNode(WebAssemblyISD::Wrapper, DL,
892                          getPointerTy(DAG.getDataLayout()), Callee);
893   }
894 
895   // Compute the operands for the CALLn node.
896   SmallVector<SDValue, 16> Ops;
897   Ops.push_back(Chain);
898   Ops.push_back(Callee);
899 
900   // Add all fixed arguments. Note that for non-varargs calls, NumFixedArgs
901   // isn't reliable.
902   Ops.append(OutVals.begin(),
903              IsVarArg ? OutVals.begin() + NumFixedArgs : OutVals.end());
904   // Add a pointer to the vararg buffer.
905   if (IsVarArg)
906     Ops.push_back(FINode);
907 
908   SmallVector<EVT, 8> InTys;
909   for (const auto &In : Ins) {
910     assert(!In.Flags.isByVal() && "byval is not valid for return values");
911     assert(!In.Flags.isNest() && "nest is not valid for return values");
912     if (In.Flags.isInAlloca())
913       fail(DL, DAG, "WebAssembly hasn't implemented inalloca return values");
914     if (In.Flags.isInConsecutiveRegs())
915       fail(DL, DAG, "WebAssembly hasn't implemented cons regs return values");
916     if (In.Flags.isInConsecutiveRegsLast())
917       fail(DL, DAG,
918            "WebAssembly hasn't implemented cons regs last return values");
919     // Ignore In.getOrigAlign() because all our arguments are passed in
920     // registers.
921     InTys.push_back(In.VT);
922   }
923 
924   if (CLI.IsTailCall) {
925     // ret_calls do not return values to the current frame
926     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
927     return DAG.getNode(WebAssemblyISD::RET_CALL, DL, NodeTys, Ops);
928   }
929 
930   InTys.push_back(MVT::Other);
931   SDVTList InTyList = DAG.getVTList(InTys);
932   SDValue Res = DAG.getNode(WebAssemblyISD::CALL, DL, InTyList, Ops);
933 
934   for (size_t I = 0; I < Ins.size(); ++I)
935     InVals.push_back(Res.getValue(I));
936 
937   // Return the chain
938   return Res.getValue(Ins.size());
939 }
940 
941 bool WebAssemblyTargetLowering::CanLowerReturn(
942     CallingConv::ID /*CallConv*/, MachineFunction & /*MF*/, bool /*IsVarArg*/,
943     const SmallVectorImpl<ISD::OutputArg> &Outs,
944     LLVMContext & /*Context*/) const {
945   // WebAssembly can only handle returning tuples with multivalue enabled
946   return Subtarget->hasMultivalue() || Outs.size() <= 1;
947 }
948 
949 SDValue WebAssemblyTargetLowering::LowerReturn(
950     SDValue Chain, CallingConv::ID CallConv, bool /*IsVarArg*/,
951     const SmallVectorImpl<ISD::OutputArg> &Outs,
952     const SmallVectorImpl<SDValue> &OutVals, const SDLoc &DL,
953     SelectionDAG &DAG) const {
954   assert((Subtarget->hasMultivalue() || Outs.size() <= 1) &&
955          "MVP WebAssembly can only return up to one value");
956   if (!callingConvSupported(CallConv))
957     fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
958 
959   SmallVector<SDValue, 4> RetOps(1, Chain);
960   RetOps.append(OutVals.begin(), OutVals.end());
961   Chain = DAG.getNode(WebAssemblyISD::RETURN, DL, MVT::Other, RetOps);
962 
963   // Record the number and types of the return values.
964   for (const ISD::OutputArg &Out : Outs) {
965     assert(!Out.Flags.isByVal() && "byval is not valid for return values");
966     assert(!Out.Flags.isNest() && "nest is not valid for return values");
967     assert(Out.IsFixed && "non-fixed return value is not valid");
968     if (Out.Flags.isInAlloca())
969       fail(DL, DAG, "WebAssembly hasn't implemented inalloca results");
970     if (Out.Flags.isInConsecutiveRegs())
971       fail(DL, DAG, "WebAssembly hasn't implemented cons regs results");
972     if (Out.Flags.isInConsecutiveRegsLast())
973       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last results");
974   }
975 
976   return Chain;
977 }
978 
979 SDValue WebAssemblyTargetLowering::LowerFormalArguments(
980     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
981     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
982     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
983   if (!callingConvSupported(CallConv))
984     fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
985 
986   MachineFunction &MF = DAG.getMachineFunction();
987   auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>();
988 
989   // Set up the incoming ARGUMENTS value, which serves to represent the liveness
990   // of the incoming values before they're represented by virtual registers.
991   MF.getRegInfo().addLiveIn(WebAssembly::ARGUMENTS);
992 
993   bool HasSwiftErrorArg = false;
994   bool HasSwiftSelfArg = false;
995   for (const ISD::InputArg &In : Ins) {
996     HasSwiftSelfArg |= In.Flags.isSwiftSelf();
997     HasSwiftErrorArg |= In.Flags.isSwiftError();
998     if (In.Flags.isInAlloca())
999       fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
1000     if (In.Flags.isNest())
1001       fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
1002     if (In.Flags.isInConsecutiveRegs())
1003       fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
1004     if (In.Flags.isInConsecutiveRegsLast())
1005       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
1006     // Ignore In.getOrigAlign() because all our arguments are passed in
1007     // registers.
1008     InVals.push_back(In.Used ? DAG.getNode(WebAssemblyISD::ARGUMENT, DL, In.VT,
1009                                            DAG.getTargetConstant(InVals.size(),
1010                                                                  DL, MVT::i32))
1011                              : DAG.getUNDEF(In.VT));
1012 
1013     // Record the number and types of arguments.
1014     MFI->addParam(In.VT);
1015   }
1016 
1017   // For swiftcc, emit additional swiftself and swifterror arguments
1018   // if there aren't. These additional arguments are also added for callee
1019   // signature They are necessary to match callee and caller signature for
1020   // indirect call.
1021   auto PtrVT = getPointerTy(MF.getDataLayout());
1022   if (CallConv == CallingConv::Swift) {
1023     if (!HasSwiftSelfArg) {
1024       MFI->addParam(PtrVT);
1025     }
1026     if (!HasSwiftErrorArg) {
1027       MFI->addParam(PtrVT);
1028     }
1029   }
1030   // Varargs are copied into a buffer allocated by the caller, and a pointer to
1031   // the buffer is passed as an argument.
1032   if (IsVarArg) {
1033     MVT PtrVT = getPointerTy(MF.getDataLayout());
1034     Register VarargVreg =
1035         MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrVT));
1036     MFI->setVarargBufferVreg(VarargVreg);
1037     Chain = DAG.getCopyToReg(
1038         Chain, DL, VarargVreg,
1039         DAG.getNode(WebAssemblyISD::ARGUMENT, DL, PtrVT,
1040                     DAG.getTargetConstant(Ins.size(), DL, MVT::i32)));
1041     MFI->addParam(PtrVT);
1042   }
1043 
1044   // Record the number and types of arguments and results.
1045   SmallVector<MVT, 4> Params;
1046   SmallVector<MVT, 4> Results;
1047   computeSignatureVTs(MF.getFunction().getFunctionType(), &MF.getFunction(),
1048                       MF.getFunction(), DAG.getTarget(), Params, Results);
1049   for (MVT VT : Results)
1050     MFI->addResult(VT);
1051   // TODO: Use signatures in WebAssemblyMachineFunctionInfo too and unify
1052   // the param logic here with ComputeSignatureVTs
1053   assert(MFI->getParams().size() == Params.size() &&
1054          std::equal(MFI->getParams().begin(), MFI->getParams().end(),
1055                     Params.begin()));
1056 
1057   return Chain;
1058 }
1059 
1060 void WebAssemblyTargetLowering::ReplaceNodeResults(
1061     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
1062   switch (N->getOpcode()) {
1063   case ISD::SIGN_EXTEND_INREG:
1064     // Do not add any results, signifying that N should not be custom lowered
1065     // after all. This happens because simd128 turns on custom lowering for
1066     // SIGN_EXTEND_INREG, but for non-vector sign extends the result might be an
1067     // illegal type.
1068     break;
1069   default:
1070     llvm_unreachable(
1071         "ReplaceNodeResults not implemented for this op for WebAssembly!");
1072   }
1073 }
1074 
1075 //===----------------------------------------------------------------------===//
1076 //  Custom lowering hooks.
1077 //===----------------------------------------------------------------------===//
1078 
1079 SDValue WebAssemblyTargetLowering::LowerOperation(SDValue Op,
1080                                                   SelectionDAG &DAG) const {
1081   SDLoc DL(Op);
1082   switch (Op.getOpcode()) {
1083   default:
1084     llvm_unreachable("unimplemented operation lowering");
1085     return SDValue();
1086   case ISD::FrameIndex:
1087     return LowerFrameIndex(Op, DAG);
1088   case ISD::GlobalAddress:
1089     return LowerGlobalAddress(Op, DAG);
1090   case ISD::ExternalSymbol:
1091     return LowerExternalSymbol(Op, DAG);
1092   case ISD::JumpTable:
1093     return LowerJumpTable(Op, DAG);
1094   case ISD::BR_JT:
1095     return LowerBR_JT(Op, DAG);
1096   case ISD::VASTART:
1097     return LowerVASTART(Op, DAG);
1098   case ISD::BlockAddress:
1099   case ISD::BRIND:
1100     fail(DL, DAG, "WebAssembly hasn't implemented computed gotos");
1101     return SDValue();
1102   case ISD::RETURNADDR:
1103     return LowerRETURNADDR(Op, DAG);
1104   case ISD::FRAMEADDR:
1105     return LowerFRAMEADDR(Op, DAG);
1106   case ISD::CopyToReg:
1107     return LowerCopyToReg(Op, DAG);
1108   case ISD::EXTRACT_VECTOR_ELT:
1109   case ISD::INSERT_VECTOR_ELT:
1110     return LowerAccessVectorElement(Op, DAG);
1111   case ISD::INTRINSIC_VOID:
1112   case ISD::INTRINSIC_WO_CHAIN:
1113   case ISD::INTRINSIC_W_CHAIN:
1114     return LowerIntrinsic(Op, DAG);
1115   case ISD::SIGN_EXTEND_INREG:
1116     return LowerSIGN_EXTEND_INREG(Op, DAG);
1117   case ISD::BUILD_VECTOR:
1118     return LowerBUILD_VECTOR(Op, DAG);
1119   case ISD::VECTOR_SHUFFLE:
1120     return LowerVECTOR_SHUFFLE(Op, DAG);
1121   case ISD::SETCC:
1122     return LowerSETCC(Op, DAG);
1123   case ISD::SHL:
1124   case ISD::SRA:
1125   case ISD::SRL:
1126     return LowerShift(Op, DAG);
1127   }
1128 }
1129 
1130 SDValue WebAssemblyTargetLowering::LowerCopyToReg(SDValue Op,
1131                                                   SelectionDAG &DAG) const {
1132   SDValue Src = Op.getOperand(2);
1133   if (isa<FrameIndexSDNode>(Src.getNode())) {
1134     // CopyToReg nodes don't support FrameIndex operands. Other targets select
1135     // the FI to some LEA-like instruction, but since we don't have that, we
1136     // need to insert some kind of instruction that can take an FI operand and
1137     // produces a value usable by CopyToReg (i.e. in a vreg). So insert a dummy
1138     // local.copy between Op and its FI operand.
1139     SDValue Chain = Op.getOperand(0);
1140     SDLoc DL(Op);
1141     unsigned Reg = cast<RegisterSDNode>(Op.getOperand(1))->getReg();
1142     EVT VT = Src.getValueType();
1143     SDValue Copy(DAG.getMachineNode(VT == MVT::i32 ? WebAssembly::COPY_I32
1144                                                    : WebAssembly::COPY_I64,
1145                                     DL, VT, Src),
1146                  0);
1147     return Op.getNode()->getNumValues() == 1
1148                ? DAG.getCopyToReg(Chain, DL, Reg, Copy)
1149                : DAG.getCopyToReg(Chain, DL, Reg, Copy,
1150                                   Op.getNumOperands() == 4 ? Op.getOperand(3)
1151                                                            : SDValue());
1152   }
1153   return SDValue();
1154 }
1155 
1156 SDValue WebAssemblyTargetLowering::LowerFrameIndex(SDValue Op,
1157                                                    SelectionDAG &DAG) const {
1158   int FI = cast<FrameIndexSDNode>(Op)->getIndex();
1159   return DAG.getTargetFrameIndex(FI, Op.getValueType());
1160 }
1161 
1162 SDValue WebAssemblyTargetLowering::LowerRETURNADDR(SDValue Op,
1163                                                    SelectionDAG &DAG) const {
1164   SDLoc DL(Op);
1165 
1166   if (!Subtarget->getTargetTriple().isOSEmscripten()) {
1167     fail(DL, DAG,
1168          "Non-Emscripten WebAssembly hasn't implemented "
1169          "__builtin_return_address");
1170     return SDValue();
1171   }
1172 
1173   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1174     return SDValue();
1175 
1176   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1177   MakeLibCallOptions CallOptions;
1178   return makeLibCall(DAG, RTLIB::RETURN_ADDRESS, Op.getValueType(),
1179                      {DAG.getConstant(Depth, DL, MVT::i32)}, CallOptions, DL)
1180       .first;
1181 }
1182 
1183 SDValue WebAssemblyTargetLowering::LowerFRAMEADDR(SDValue Op,
1184                                                   SelectionDAG &DAG) const {
1185   // Non-zero depths are not supported by WebAssembly currently. Use the
1186   // legalizer's default expansion, which is to return 0 (what this function is
1187   // documented to do).
1188   if (Op.getConstantOperandVal(0) > 0)
1189     return SDValue();
1190 
1191   DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
1192   EVT VT = Op.getValueType();
1193   Register FP =
1194       Subtarget->getRegisterInfo()->getFrameRegister(DAG.getMachineFunction());
1195   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), FP, VT);
1196 }
1197 
1198 SDValue WebAssemblyTargetLowering::LowerGlobalAddress(SDValue Op,
1199                                                       SelectionDAG &DAG) const {
1200   SDLoc DL(Op);
1201   const auto *GA = cast<GlobalAddressSDNode>(Op);
1202   EVT VT = Op.getValueType();
1203   assert(GA->getTargetFlags() == 0 &&
1204          "Unexpected target flags on generic GlobalAddressSDNode");
1205   if (GA->getAddressSpace() != 0)
1206     fail(DL, DAG, "WebAssembly only expects the 0 address space");
1207 
1208   unsigned OperandFlags = 0;
1209   if (isPositionIndependent()) {
1210     const GlobalValue *GV = GA->getGlobal();
1211     if (getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) {
1212       MachineFunction &MF = DAG.getMachineFunction();
1213       MVT PtrVT = getPointerTy(MF.getDataLayout());
1214       const char *BaseName;
1215       if (GV->getValueType()->isFunctionTy()) {
1216         BaseName = MF.createExternalSymbolName("__table_base");
1217         OperandFlags = WebAssemblyII::MO_TABLE_BASE_REL;
1218       }
1219       else {
1220         BaseName = MF.createExternalSymbolName("__memory_base");
1221         OperandFlags = WebAssemblyII::MO_MEMORY_BASE_REL;
1222       }
1223       SDValue BaseAddr =
1224           DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT,
1225                       DAG.getTargetExternalSymbol(BaseName, PtrVT));
1226 
1227       SDValue SymAddr = DAG.getNode(
1228           WebAssemblyISD::WrapperPIC, DL, VT,
1229           DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT, GA->getOffset(),
1230                                      OperandFlags));
1231 
1232       return DAG.getNode(ISD::ADD, DL, VT, BaseAddr, SymAddr);
1233     } else {
1234       OperandFlags = WebAssemblyII::MO_GOT;
1235     }
1236   }
1237 
1238   return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1239                      DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT,
1240                                                 GA->getOffset(), OperandFlags));
1241 }
1242 
1243 SDValue
1244 WebAssemblyTargetLowering::LowerExternalSymbol(SDValue Op,
1245                                                SelectionDAG &DAG) const {
1246   SDLoc DL(Op);
1247   const auto *ES = cast<ExternalSymbolSDNode>(Op);
1248   EVT VT = Op.getValueType();
1249   assert(ES->getTargetFlags() == 0 &&
1250          "Unexpected target flags on generic ExternalSymbolSDNode");
1251   return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1252                      DAG.getTargetExternalSymbol(ES->getSymbol(), VT));
1253 }
1254 
1255 SDValue WebAssemblyTargetLowering::LowerJumpTable(SDValue Op,
1256                                                   SelectionDAG &DAG) const {
1257   // There's no need for a Wrapper node because we always incorporate a jump
1258   // table operand into a BR_TABLE instruction, rather than ever
1259   // materializing it in a register.
1260   const JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1261   return DAG.getTargetJumpTable(JT->getIndex(), Op.getValueType(),
1262                                 JT->getTargetFlags());
1263 }
1264 
1265 SDValue WebAssemblyTargetLowering::LowerBR_JT(SDValue Op,
1266                                               SelectionDAG &DAG) const {
1267   SDLoc DL(Op);
1268   SDValue Chain = Op.getOperand(0);
1269   const auto *JT = cast<JumpTableSDNode>(Op.getOperand(1));
1270   SDValue Index = Op.getOperand(2);
1271   assert(JT->getTargetFlags() == 0 && "WebAssembly doesn't set target flags");
1272 
1273   SmallVector<SDValue, 8> Ops;
1274   Ops.push_back(Chain);
1275   Ops.push_back(Index);
1276 
1277   MachineJumpTableInfo *MJTI = DAG.getMachineFunction().getJumpTableInfo();
1278   const auto &MBBs = MJTI->getJumpTables()[JT->getIndex()].MBBs;
1279 
1280   // Add an operand for each case.
1281   for (auto MBB : MBBs)
1282     Ops.push_back(DAG.getBasicBlock(MBB));
1283 
1284   // TODO: For now, we just pick something arbitrary for a default case for now.
1285   // We really want to sniff out the guard and put in the real default case (and
1286   // delete the guard).
1287   Ops.push_back(DAG.getBasicBlock(MBBs[0]));
1288 
1289   return DAG.getNode(WebAssemblyISD::BR_TABLE, DL, MVT::Other, Ops);
1290 }
1291 
1292 SDValue WebAssemblyTargetLowering::LowerVASTART(SDValue Op,
1293                                                 SelectionDAG &DAG) const {
1294   SDLoc DL(Op);
1295   EVT PtrVT = getPointerTy(DAG.getMachineFunction().getDataLayout());
1296 
1297   auto *MFI = DAG.getMachineFunction().getInfo<WebAssemblyFunctionInfo>();
1298   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1299 
1300   SDValue ArgN = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1301                                     MFI->getVarargBufferVreg(), PtrVT);
1302   return DAG.getStore(Op.getOperand(0), DL, ArgN, Op.getOperand(1),
1303                       MachinePointerInfo(SV), 0);
1304 }
1305 
1306 SDValue WebAssemblyTargetLowering::LowerIntrinsic(SDValue Op,
1307                                                   SelectionDAG &DAG) const {
1308   MachineFunction &MF = DAG.getMachineFunction();
1309   unsigned IntNo;
1310   switch (Op.getOpcode()) {
1311   case ISD::INTRINSIC_VOID:
1312   case ISD::INTRINSIC_W_CHAIN:
1313     IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1314     break;
1315   case ISD::INTRINSIC_WO_CHAIN:
1316     IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1317     break;
1318   default:
1319     llvm_unreachable("Invalid intrinsic");
1320   }
1321   SDLoc DL(Op);
1322 
1323   switch (IntNo) {
1324   default:
1325     return SDValue(); // Don't custom lower most intrinsics.
1326 
1327   case Intrinsic::wasm_lsda: {
1328     EVT VT = Op.getValueType();
1329     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1330     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
1331     auto &Context = MF.getMMI().getContext();
1332     MCSymbol *S = Context.getOrCreateSymbol(Twine("GCC_except_table") +
1333                                             Twine(MF.getFunctionNumber()));
1334     return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1335                        DAG.getMCSymbol(S, PtrVT));
1336   }
1337 
1338   case Intrinsic::wasm_throw: {
1339     // We only support C++ exceptions for now
1340     int Tag = cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue();
1341     if (Tag != CPP_EXCEPTION)
1342       llvm_unreachable("Invalid tag!");
1343     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1344     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
1345     const char *SymName = MF.createExternalSymbolName("__cpp_exception");
1346     SDValue SymNode = DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT,
1347                                   DAG.getTargetExternalSymbol(SymName, PtrVT));
1348     return DAG.getNode(WebAssemblyISD::THROW, DL,
1349                        MVT::Other, // outchain type
1350                        {
1351                            Op.getOperand(0), // inchain
1352                            SymNode,          // exception symbol
1353                            Op.getOperand(3)  // thrown value
1354                        });
1355   }
1356 
1357   case Intrinsic::wasm_shuffle: {
1358     // Drop in-chain and replace undefs, but otherwise pass through unchanged
1359     SDValue Ops[18];
1360     size_t OpIdx = 0;
1361     Ops[OpIdx++] = Op.getOperand(1);
1362     Ops[OpIdx++] = Op.getOperand(2);
1363     while (OpIdx < 18) {
1364       const SDValue &MaskIdx = Op.getOperand(OpIdx + 1);
1365       if (MaskIdx.isUndef() ||
1366           cast<ConstantSDNode>(MaskIdx.getNode())->getZExtValue() >= 32) {
1367         Ops[OpIdx++] = DAG.getConstant(0, DL, MVT::i32);
1368       } else {
1369         Ops[OpIdx++] = MaskIdx;
1370       }
1371     }
1372     return DAG.getNode(WebAssemblyISD::SHUFFLE, DL, Op.getValueType(), Ops);
1373   }
1374   }
1375 }
1376 
1377 SDValue
1378 WebAssemblyTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
1379                                                   SelectionDAG &DAG) const {
1380   SDLoc DL(Op);
1381   // If sign extension operations are disabled, allow sext_inreg only if operand
1382   // is a vector extract of an i8 or i16 lane. SIMD does not depend on sign
1383   // extension operations, but allowing sext_inreg in this context lets us have
1384   // simple patterns to select extract_lane_s instructions. Expanding sext_inreg
1385   // everywhere would be simpler in this file, but would necessitate large and
1386   // brittle patterns to undo the expansion and select extract_lane_s
1387   // instructions.
1388   assert(!Subtarget->hasSignExt() && Subtarget->hasSIMD128());
1389   if (Op.getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1390     return SDValue();
1391 
1392   const SDValue &Extract = Op.getOperand(0);
1393   MVT VecT = Extract.getOperand(0).getSimpleValueType();
1394   if (VecT.getVectorElementType().getSizeInBits() > 32)
1395     return SDValue();
1396   MVT ExtractedLaneT = static_cast<VTSDNode *>(Op.getOperand(1).getNode())
1397                            ->getVT()
1398                            .getSimpleVT();
1399   MVT ExtractedVecT =
1400       MVT::getVectorVT(ExtractedLaneT, 128 / ExtractedLaneT.getSizeInBits());
1401   if (ExtractedVecT == VecT)
1402     return Op;
1403 
1404   // Bitcast vector to appropriate type to ensure ISel pattern coverage
1405   const SDValue &Index = Extract.getOperand(1);
1406   unsigned IndexVal =
1407       static_cast<ConstantSDNode *>(Index.getNode())->getZExtValue();
1408   unsigned Scale =
1409       ExtractedVecT.getVectorNumElements() / VecT.getVectorNumElements();
1410   assert(Scale > 1);
1411   SDValue NewIndex =
1412       DAG.getConstant(IndexVal * Scale, DL, Index.getValueType());
1413   SDValue NewExtract = DAG.getNode(
1414       ISD::EXTRACT_VECTOR_ELT, DL, Extract.getValueType(),
1415       DAG.getBitcast(ExtractedVecT, Extract.getOperand(0)), NewIndex);
1416   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, Op.getValueType(), NewExtract,
1417                      Op.getOperand(1));
1418 }
1419 
1420 SDValue WebAssemblyTargetLowering::LowerBUILD_VECTOR(SDValue Op,
1421                                                      SelectionDAG &DAG) const {
1422   SDLoc DL(Op);
1423   const EVT VecT = Op.getValueType();
1424   const EVT LaneT = Op.getOperand(0).getValueType();
1425   const size_t Lanes = Op.getNumOperands();
1426   bool CanSwizzle = Subtarget->hasUnimplementedSIMD128() && VecT == MVT::v16i8;
1427 
1428   // BUILD_VECTORs are lowered to the instruction that initializes the highest
1429   // possible number of lanes at once followed by a sequence of replace_lane
1430   // instructions to individually initialize any remaining lanes.
1431 
1432   // TODO: Tune this. For example, lanewise swizzling is very expensive, so
1433   // swizzled lanes should be given greater weight.
1434 
1435   // TODO: Investigate building vectors by shuffling together vectors built by
1436   // separately specialized means.
1437 
1438   auto IsConstant = [](const SDValue &V) {
1439     return V.getOpcode() == ISD::Constant || V.getOpcode() == ISD::ConstantFP;
1440   };
1441 
1442   // Returns the source vector and index vector pair if they exist. Checks for:
1443   //   (extract_vector_elt
1444   //     $src,
1445   //     (sign_extend_inreg (extract_vector_elt $indices, $i))
1446   //   )
1447   auto GetSwizzleSrcs = [](size_t I, const SDValue &Lane) {
1448     auto Bail = std::make_pair(SDValue(), SDValue());
1449     if (Lane->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1450       return Bail;
1451     const SDValue &SwizzleSrc = Lane->getOperand(0);
1452     const SDValue &IndexExt = Lane->getOperand(1);
1453     if (IndexExt->getOpcode() != ISD::SIGN_EXTEND_INREG)
1454       return Bail;
1455     const SDValue &Index = IndexExt->getOperand(0);
1456     if (Index->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1457       return Bail;
1458     const SDValue &SwizzleIndices = Index->getOperand(0);
1459     if (SwizzleSrc.getValueType() != MVT::v16i8 ||
1460         SwizzleIndices.getValueType() != MVT::v16i8 ||
1461         Index->getOperand(1)->getOpcode() != ISD::Constant ||
1462         Index->getConstantOperandVal(1) != I)
1463       return Bail;
1464     return std::make_pair(SwizzleSrc, SwizzleIndices);
1465   };
1466 
1467   using ValueEntry = std::pair<SDValue, size_t>;
1468   SmallVector<ValueEntry, 16> SplatValueCounts;
1469 
1470   using SwizzleEntry = std::pair<std::pair<SDValue, SDValue>, size_t>;
1471   SmallVector<SwizzleEntry, 16> SwizzleCounts;
1472 
1473   auto AddCount = [](auto &Counts, const auto &Val) {
1474     auto CountIt = std::find_if(Counts.begin(), Counts.end(),
1475                                 [&Val](auto E) { return E.first == Val; });
1476     if (CountIt == Counts.end()) {
1477       Counts.emplace_back(Val, 1);
1478     } else {
1479       CountIt->second++;
1480     }
1481   };
1482 
1483   auto GetMostCommon = [](auto &Counts) {
1484     auto CommonIt =
1485         std::max_element(Counts.begin(), Counts.end(),
1486                          [](auto A, auto B) { return A.second < B.second; });
1487     assert(CommonIt != Counts.end() && "Unexpected all-undef build_vector");
1488     return *CommonIt;
1489   };
1490 
1491   size_t NumConstantLanes = 0;
1492 
1493   // Count eligible lanes for each type of vector creation op
1494   for (size_t I = 0; I < Lanes; ++I) {
1495     const SDValue &Lane = Op->getOperand(I);
1496     if (Lane.isUndef())
1497       continue;
1498 
1499     AddCount(SplatValueCounts, Lane);
1500 
1501     if (IsConstant(Lane)) {
1502       NumConstantLanes++;
1503     } else if (CanSwizzle) {
1504       auto SwizzleSrcs = GetSwizzleSrcs(I, Lane);
1505       if (SwizzleSrcs.first)
1506         AddCount(SwizzleCounts, SwizzleSrcs);
1507     }
1508   }
1509 
1510   SDValue SplatValue;
1511   size_t NumSplatLanes;
1512   std::tie(SplatValue, NumSplatLanes) = GetMostCommon(SplatValueCounts);
1513 
1514   SDValue SwizzleSrc;
1515   SDValue SwizzleIndices;
1516   size_t NumSwizzleLanes = 0;
1517   if (SwizzleCounts.size())
1518     std::forward_as_tuple(std::tie(SwizzleSrc, SwizzleIndices),
1519                           NumSwizzleLanes) = GetMostCommon(SwizzleCounts);
1520 
1521   // Predicate returning true if the lane is properly initialized by the
1522   // original instruction
1523   std::function<bool(size_t, const SDValue &)> IsLaneConstructed;
1524   SDValue Result;
1525   if (Subtarget->hasUnimplementedSIMD128()) {
1526     // Prefer swizzles over vector consts over splats
1527     if (NumSwizzleLanes >= NumSplatLanes &&
1528         NumSwizzleLanes >= NumConstantLanes) {
1529       Result = DAG.getNode(WebAssemblyISD::SWIZZLE, DL, VecT, SwizzleSrc,
1530                            SwizzleIndices);
1531       auto Swizzled = std::make_pair(SwizzleSrc, SwizzleIndices);
1532       IsLaneConstructed = [&, Swizzled](size_t I, const SDValue &Lane) {
1533         return Swizzled == GetSwizzleSrcs(I, Lane);
1534       };
1535     } else if (NumConstantLanes >= NumSplatLanes) {
1536       SmallVector<SDValue, 16> ConstLanes;
1537       for (const SDValue &Lane : Op->op_values()) {
1538         if (IsConstant(Lane)) {
1539           ConstLanes.push_back(Lane);
1540         } else if (LaneT.isFloatingPoint()) {
1541           ConstLanes.push_back(DAG.getConstantFP(0, DL, LaneT));
1542         } else {
1543           ConstLanes.push_back(DAG.getConstant(0, DL, LaneT));
1544         }
1545       }
1546       Result = DAG.getBuildVector(VecT, DL, ConstLanes);
1547       IsLaneConstructed = [&](size_t _, const SDValue &Lane) {
1548         return IsConstant(Lane);
1549       };
1550     }
1551   }
1552   if (!Result) {
1553     // Use a splat, but possibly a load_splat
1554     LoadSDNode *SplattedLoad;
1555     if (Subtarget->hasUnimplementedSIMD128() &&
1556         (SplattedLoad = dyn_cast<LoadSDNode>(SplatValue)) &&
1557         SplattedLoad->getMemoryVT() == VecT.getVectorElementType()) {
1558       Result = DAG.getMemIntrinsicNode(
1559           WebAssemblyISD::LOAD_SPLAT, DL, DAG.getVTList(VecT),
1560           {SplattedLoad->getChain(), SplattedLoad->getBasePtr(),
1561            SplattedLoad->getOffset()},
1562           SplattedLoad->getMemoryVT(), SplattedLoad->getMemOperand());
1563     } else {
1564       Result = DAG.getSplatBuildVector(VecT, DL, SplatValue);
1565     }
1566     IsLaneConstructed = [&](size_t _, const SDValue &Lane) {
1567       return Lane == SplatValue;
1568     };
1569   }
1570 
1571   // Add replace_lane instructions for any unhandled values
1572   for (size_t I = 0; I < Lanes; ++I) {
1573     const SDValue &Lane = Op->getOperand(I);
1574     if (!Lane.isUndef() && !IsLaneConstructed(I, Lane))
1575       Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VecT, Result, Lane,
1576                            DAG.getConstant(I, DL, MVT::i32));
1577   }
1578 
1579   return Result;
1580 }
1581 
1582 SDValue
1583 WebAssemblyTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
1584                                                SelectionDAG &DAG) const {
1585   SDLoc DL(Op);
1586   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op.getNode())->getMask();
1587   MVT VecType = Op.getOperand(0).getSimpleValueType();
1588   assert(VecType.is128BitVector() && "Unexpected shuffle vector type");
1589   size_t LaneBytes = VecType.getVectorElementType().getSizeInBits() / 8;
1590 
1591   // Space for two vector args and sixteen mask indices
1592   SDValue Ops[18];
1593   size_t OpIdx = 0;
1594   Ops[OpIdx++] = Op.getOperand(0);
1595   Ops[OpIdx++] = Op.getOperand(1);
1596 
1597   // Expand mask indices to byte indices and materialize them as operands
1598   for (int M : Mask) {
1599     for (size_t J = 0; J < LaneBytes; ++J) {
1600       // Lower undefs (represented by -1 in mask) to zero
1601       uint64_t ByteIndex = M == -1 ? 0 : (uint64_t)M * LaneBytes + J;
1602       Ops[OpIdx++] = DAG.getConstant(ByteIndex, DL, MVT::i32);
1603     }
1604   }
1605 
1606   return DAG.getNode(WebAssemblyISD::SHUFFLE, DL, Op.getValueType(), Ops);
1607 }
1608 
1609 SDValue WebAssemblyTargetLowering::LowerSETCC(SDValue Op,
1610                                               SelectionDAG &DAG) const {
1611   SDLoc DL(Op);
1612   // The legalizer does not know how to expand the comparison modes of i64x2
1613   // vectors because no comparison modes are supported. We could solve this by
1614   // expanding all i64x2 SETCC nodes, but that seems to expand f64x2 SETCC nodes
1615   // (which return i64x2 results) as well. So instead we manually unroll i64x2
1616   // comparisons here.
1617   assert(Op->getOperand(0)->getSimpleValueType(0) == MVT::v2i64);
1618   SmallVector<SDValue, 2> LHS, RHS;
1619   DAG.ExtractVectorElements(Op->getOperand(0), LHS);
1620   DAG.ExtractVectorElements(Op->getOperand(1), RHS);
1621   const SDValue &CC = Op->getOperand(2);
1622   auto MakeLane = [&](unsigned I) {
1623     return DAG.getNode(ISD::SELECT_CC, DL, MVT::i64, LHS[I], RHS[I],
1624                        DAG.getConstant(uint64_t(-1), DL, MVT::i64),
1625                        DAG.getConstant(uint64_t(0), DL, MVT::i64), CC);
1626   };
1627   return DAG.getBuildVector(Op->getValueType(0), DL,
1628                             {MakeLane(0), MakeLane(1)});
1629 }
1630 
1631 SDValue
1632 WebAssemblyTargetLowering::LowerAccessVectorElement(SDValue Op,
1633                                                     SelectionDAG &DAG) const {
1634   // Allow constant lane indices, expand variable lane indices
1635   SDNode *IdxNode = Op.getOperand(Op.getNumOperands() - 1).getNode();
1636   if (isa<ConstantSDNode>(IdxNode) || IdxNode->isUndef())
1637     return Op;
1638   else
1639     // Perform default expansion
1640     return SDValue();
1641 }
1642 
1643 static SDValue unrollVectorShift(SDValue Op, SelectionDAG &DAG) {
1644   EVT LaneT = Op.getSimpleValueType().getVectorElementType();
1645   // 32-bit and 64-bit unrolled shifts will have proper semantics
1646   if (LaneT.bitsGE(MVT::i32))
1647     return DAG.UnrollVectorOp(Op.getNode());
1648   // Otherwise mask the shift value to get proper semantics from 32-bit shift
1649   SDLoc DL(Op);
1650   size_t NumLanes = Op.getSimpleValueType().getVectorNumElements();
1651   SDValue Mask = DAG.getConstant(LaneT.getSizeInBits() - 1, DL, MVT::i32);
1652   unsigned ShiftOpcode = Op.getOpcode();
1653   SmallVector<SDValue, 16> ShiftedElements;
1654   DAG.ExtractVectorElements(Op.getOperand(0), ShiftedElements, 0, 0, MVT::i32);
1655   SmallVector<SDValue, 16> ShiftElements;
1656   DAG.ExtractVectorElements(Op.getOperand(1), ShiftElements, 0, 0, MVT::i32);
1657   SmallVector<SDValue, 16> UnrolledOps;
1658   for (size_t i = 0; i < NumLanes; ++i) {
1659     SDValue MaskedShiftValue =
1660         DAG.getNode(ISD::AND, DL, MVT::i32, ShiftElements[i], Mask);
1661     SDValue ShiftedValue = ShiftedElements[i];
1662     if (ShiftOpcode == ISD::SRA)
1663       ShiftedValue = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i32,
1664                                  ShiftedValue, DAG.getValueType(LaneT));
1665     UnrolledOps.push_back(
1666         DAG.getNode(ShiftOpcode, DL, MVT::i32, ShiftedValue, MaskedShiftValue));
1667   }
1668   return DAG.getBuildVector(Op.getValueType(), DL, UnrolledOps);
1669 }
1670 
1671 SDValue WebAssemblyTargetLowering::LowerShift(SDValue Op,
1672                                               SelectionDAG &DAG) const {
1673   SDLoc DL(Op);
1674 
1675   // Only manually lower vector shifts
1676   assert(Op.getSimpleValueType().isVector());
1677 
1678   // Unroll non-splat vector shifts
1679   BuildVectorSDNode *ShiftVec;
1680   SDValue SplatVal;
1681   if (!(ShiftVec = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode())) ||
1682       !(SplatVal = ShiftVec->getSplatValue()))
1683     return unrollVectorShift(Op, DAG);
1684 
1685   // All splats except i64x2 const splats are handled by patterns
1686   auto *SplatConst = dyn_cast<ConstantSDNode>(SplatVal);
1687   if (!SplatConst || Op.getSimpleValueType() != MVT::v2i64)
1688     return Op;
1689 
1690   // i64x2 const splats are custom lowered to avoid unnecessary wraps
1691   unsigned Opcode;
1692   switch (Op.getOpcode()) {
1693   case ISD::SHL:
1694     Opcode = WebAssemblyISD::VEC_SHL;
1695     break;
1696   case ISD::SRA:
1697     Opcode = WebAssemblyISD::VEC_SHR_S;
1698     break;
1699   case ISD::SRL:
1700     Opcode = WebAssemblyISD::VEC_SHR_U;
1701     break;
1702   default:
1703     llvm_unreachable("unexpected opcode");
1704   }
1705   APInt Shift = SplatConst->getAPIntValue().zextOrTrunc(32);
1706   return DAG.getNode(Opcode, DL, Op.getValueType(), Op.getOperand(0),
1707                      DAG.getConstant(Shift, DL, MVT::i32));
1708 }
1709 
1710 //===----------------------------------------------------------------------===//
1711 //                          WebAssembly Optimization Hooks
1712 //===----------------------------------------------------------------------===//
1713