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