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 }
677 
678 SDValue
679 WebAssemblyTargetLowering::LowerCall(CallLoweringInfo &CLI,
680                                      SmallVectorImpl<SDValue> &InVals) const {
681   SelectionDAG &DAG = CLI.DAG;
682   SDLoc DL = CLI.DL;
683   SDValue Chain = CLI.Chain;
684   SDValue Callee = CLI.Callee;
685   MachineFunction &MF = DAG.getMachineFunction();
686   auto Layout = MF.getDataLayout();
687 
688   CallingConv::ID CallConv = CLI.CallConv;
689   if (!callingConvSupported(CallConv))
690     fail(DL, DAG,
691          "WebAssembly doesn't support language-specific or target-specific "
692          "calling conventions yet");
693   if (CLI.IsPatchPoint)
694     fail(DL, DAG, "WebAssembly doesn't support patch point yet");
695 
696   if (CLI.IsTailCall) {
697     bool MustTail = CLI.CS && CLI.CS.isMustTailCall();
698     if (Subtarget->hasTailCall() && !CLI.IsVarArg) {
699       // Do not tail call unless caller and callee return types match
700       const Function &F = MF.getFunction();
701       const TargetMachine &TM = getTargetMachine();
702       Type *RetTy = F.getReturnType();
703       SmallVector<MVT, 4> CallerRetTys;
704       SmallVector<MVT, 4> CalleeRetTys;
705       computeLegalValueVTs(F, TM, RetTy, CallerRetTys);
706       computeLegalValueVTs(F, TM, CLI.RetTy, CalleeRetTys);
707       bool TypesMatch = CallerRetTys.size() == CalleeRetTys.size() &&
708                         std::equal(CallerRetTys.begin(), CallerRetTys.end(),
709                                    CalleeRetTys.begin());
710       if (!TypesMatch) {
711         // musttail in this case would be an LLVM IR validation failure
712         assert(!MustTail);
713         CLI.IsTailCall = false;
714       }
715     } else {
716       CLI.IsTailCall = false;
717       if (MustTail) {
718         if (CLI.IsVarArg) {
719           // The return would pop the argument buffer
720           fail(DL, DAG, "WebAssembly does not support varargs tail calls");
721         } else {
722           fail(DL, DAG, "WebAssembly 'tail-call' feature not enabled");
723         }
724       }
725     }
726   }
727 
728   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
729   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
730   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
731 
732   // The generic code may have added an sret argument. If we're lowering an
733   // invoke function, the ABI requires that the function pointer be the first
734   // argument, so we may have to swap the arguments.
735   if (CallConv == CallingConv::WASM_EmscriptenInvoke && Outs.size() >= 2 &&
736       Outs[0].Flags.isSRet()) {
737     std::swap(Outs[0], Outs[1]);
738     std::swap(OutVals[0], OutVals[1]);
739   }
740 
741   unsigned NumFixedArgs = 0;
742   for (unsigned I = 0; I < Outs.size(); ++I) {
743     const ISD::OutputArg &Out = Outs[I];
744     SDValue &OutVal = OutVals[I];
745     if (Out.Flags.isNest())
746       fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
747     if (Out.Flags.isInAlloca())
748       fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
749     if (Out.Flags.isInConsecutiveRegs())
750       fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
751     if (Out.Flags.isInConsecutiveRegsLast())
752       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
753     if (Out.Flags.isByVal() && Out.Flags.getByValSize() != 0) {
754       auto &MFI = MF.getFrameInfo();
755       int FI = MFI.CreateStackObject(Out.Flags.getByValSize(),
756                                      Out.Flags.getByValAlign(),
757                                      /*isSS=*/false);
758       SDValue SizeNode =
759           DAG.getConstant(Out.Flags.getByValSize(), DL, MVT::i32);
760       SDValue FINode = DAG.getFrameIndex(FI, getPointerTy(Layout));
761       Chain = DAG.getMemcpy(
762           Chain, DL, FINode, OutVal, SizeNode, Out.Flags.getByValAlign(),
763           /*isVolatile*/ false, /*AlwaysInline=*/false,
764           /*isTailCall*/ false, MachinePointerInfo(), MachinePointerInfo());
765       OutVal = FINode;
766     }
767     // Count the number of fixed args *after* legalization.
768     NumFixedArgs += Out.IsFixed;
769   }
770 
771   bool IsVarArg = CLI.IsVarArg;
772   auto PtrVT = getPointerTy(Layout);
773 
774   // Analyze operands of the call, assigning locations to each operand.
775   SmallVector<CCValAssign, 16> ArgLocs;
776   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
777 
778   if (IsVarArg) {
779     // Outgoing non-fixed arguments are placed in a buffer. First
780     // compute their offsets and the total amount of buffer space needed.
781     for (unsigned I = NumFixedArgs; I < Outs.size(); ++I) {
782       const ISD::OutputArg &Out = Outs[I];
783       SDValue &Arg = OutVals[I];
784       EVT VT = Arg.getValueType();
785       assert(VT != MVT::iPTR && "Legalized args should be concrete");
786       Type *Ty = VT.getTypeForEVT(*DAG.getContext());
787       unsigned Align = std::max(Out.Flags.getOrigAlign(),
788                                 Layout.getABITypeAlignment(Ty));
789       unsigned Offset = CCInfo.AllocateStack(Layout.getTypeAllocSize(Ty),
790                                              Align);
791       CCInfo.addLoc(CCValAssign::getMem(ArgLocs.size(), VT.getSimpleVT(),
792                                         Offset, VT.getSimpleVT(),
793                                         CCValAssign::Full));
794     }
795   }
796 
797   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
798 
799   SDValue FINode;
800   if (IsVarArg && NumBytes) {
801     // For non-fixed arguments, next emit stores to store the argument values
802     // to the stack buffer at the offsets computed above.
803     int FI = MF.getFrameInfo().CreateStackObject(NumBytes,
804                                                  Layout.getStackAlignment(),
805                                                  /*isSS=*/false);
806     unsigned ValNo = 0;
807     SmallVector<SDValue, 8> Chains;
808     for (SDValue Arg :
809          make_range(OutVals.begin() + NumFixedArgs, OutVals.end())) {
810       assert(ArgLocs[ValNo].getValNo() == ValNo &&
811              "ArgLocs should remain in order and only hold varargs args");
812       unsigned Offset = ArgLocs[ValNo++].getLocMemOffset();
813       FINode = DAG.getFrameIndex(FI, getPointerTy(Layout));
814       SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, FINode,
815                                 DAG.getConstant(Offset, DL, PtrVT));
816       Chains.push_back(
817           DAG.getStore(Chain, DL, Arg, Add,
818                        MachinePointerInfo::getFixedStack(MF, FI, Offset), 0));
819     }
820     if (!Chains.empty())
821       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
822   } else if (IsVarArg) {
823     FINode = DAG.getIntPtrConstant(0, DL);
824   }
825 
826   if (Callee->getOpcode() == ISD::GlobalAddress) {
827     // If the callee is a GlobalAddress node (quite common, every direct call
828     // is) turn it into a TargetGlobalAddress node so that LowerGlobalAddress
829     // doesn't at MO_GOT which is not needed for direct calls.
830     GlobalAddressSDNode* GA = cast<GlobalAddressSDNode>(Callee);
831     Callee = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
832                                         getPointerTy(DAG.getDataLayout()),
833                                         GA->getOffset());
834     Callee = DAG.getNode(WebAssemblyISD::Wrapper, DL,
835                          getPointerTy(DAG.getDataLayout()), Callee);
836   }
837 
838   // Compute the operands for the CALLn node.
839   SmallVector<SDValue, 16> Ops;
840   Ops.push_back(Chain);
841   Ops.push_back(Callee);
842 
843   // Add all fixed arguments. Note that for non-varargs calls, NumFixedArgs
844   // isn't reliable.
845   Ops.append(OutVals.begin(),
846              IsVarArg ? OutVals.begin() + NumFixedArgs : OutVals.end());
847   // Add a pointer to the vararg buffer.
848   if (IsVarArg)
849     Ops.push_back(FINode);
850 
851   SmallVector<EVT, 8> InTys;
852   for (const auto &In : Ins) {
853     assert(!In.Flags.isByVal() && "byval is not valid for return values");
854     assert(!In.Flags.isNest() && "nest is not valid for return values");
855     if (In.Flags.isInAlloca())
856       fail(DL, DAG, "WebAssembly hasn't implemented inalloca return values");
857     if (In.Flags.isInConsecutiveRegs())
858       fail(DL, DAG, "WebAssembly hasn't implemented cons regs return values");
859     if (In.Flags.isInConsecutiveRegsLast())
860       fail(DL, DAG,
861            "WebAssembly hasn't implemented cons regs last return values");
862     // Ignore In.getOrigAlign() because all our arguments are passed in
863     // registers.
864     InTys.push_back(In.VT);
865   }
866 
867   if (CLI.IsTailCall) {
868     // ret_calls do not return values to the current frame
869     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
870     return DAG.getNode(WebAssemblyISD::RET_CALL, DL, NodeTys, Ops);
871   }
872 
873   InTys.push_back(MVT::Other);
874   unsigned Opc;
875   // TODO: Remove CALL0 and CALL1 in favor of CALL
876   switch (Ins.size()) {
877   case 0:
878     Opc = WebAssemblyISD::CALL0;
879     break;
880   case 1:
881     Opc = WebAssemblyISD::CALL1;
882     break;
883   default:
884     Opc = WebAssemblyISD::CALL;
885     break;
886   }
887   SDVTList InTyList = DAG.getVTList(InTys);
888   SDValue Res = DAG.getNode(Opc, DL, InTyList, Ops);
889 
890   for (size_t I = 0; I < Ins.size(); ++I)
891     InVals.push_back(Res.getValue(I));
892 
893   // Return the chain
894   return Res.getValue(Ins.size());
895 }
896 
897 bool WebAssemblyTargetLowering::CanLowerReturn(
898     CallingConv::ID /*CallConv*/, MachineFunction & /*MF*/, bool /*IsVarArg*/,
899     const SmallVectorImpl<ISD::OutputArg> &Outs,
900     LLVMContext & /*Context*/) const {
901   // WebAssembly can only handle returning tuples with multivalue enabled
902   return Subtarget->hasMultivalue() || Outs.size() <= 1;
903 }
904 
905 SDValue WebAssemblyTargetLowering::LowerReturn(
906     SDValue Chain, CallingConv::ID CallConv, bool /*IsVarArg*/,
907     const SmallVectorImpl<ISD::OutputArg> &Outs,
908     const SmallVectorImpl<SDValue> &OutVals, const SDLoc &DL,
909     SelectionDAG &DAG) const {
910   assert((Subtarget->hasMultivalue() || Outs.size() <= 1) &&
911          "MVP WebAssembly can only return up to one value");
912   if (!callingConvSupported(CallConv))
913     fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
914 
915   SmallVector<SDValue, 4> RetOps(1, Chain);
916   RetOps.append(OutVals.begin(), OutVals.end());
917   Chain = DAG.getNode(WebAssemblyISD::RETURN, DL, MVT::Other, RetOps);
918 
919   // Record the number and types of the return values.
920   for (const ISD::OutputArg &Out : Outs) {
921     assert(!Out.Flags.isByVal() && "byval is not valid for return values");
922     assert(!Out.Flags.isNest() && "nest is not valid for return values");
923     assert(Out.IsFixed && "non-fixed return value is not valid");
924     if (Out.Flags.isInAlloca())
925       fail(DL, DAG, "WebAssembly hasn't implemented inalloca results");
926     if (Out.Flags.isInConsecutiveRegs())
927       fail(DL, DAG, "WebAssembly hasn't implemented cons regs results");
928     if (Out.Flags.isInConsecutiveRegsLast())
929       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last results");
930   }
931 
932   return Chain;
933 }
934 
935 SDValue WebAssemblyTargetLowering::LowerFormalArguments(
936     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
937     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
938     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
939   if (!callingConvSupported(CallConv))
940     fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
941 
942   MachineFunction &MF = DAG.getMachineFunction();
943   auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>();
944 
945   // Set up the incoming ARGUMENTS value, which serves to represent the liveness
946   // of the incoming values before they're represented by virtual registers.
947   MF.getRegInfo().addLiveIn(WebAssembly::ARGUMENTS);
948 
949   for (const ISD::InputArg &In : Ins) {
950     if (In.Flags.isInAlloca())
951       fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
952     if (In.Flags.isNest())
953       fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
954     if (In.Flags.isInConsecutiveRegs())
955       fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
956     if (In.Flags.isInConsecutiveRegsLast())
957       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
958     // Ignore In.getOrigAlign() because all our arguments are passed in
959     // registers.
960     InVals.push_back(In.Used ? DAG.getNode(WebAssemblyISD::ARGUMENT, DL, In.VT,
961                                            DAG.getTargetConstant(InVals.size(),
962                                                                  DL, MVT::i32))
963                              : DAG.getUNDEF(In.VT));
964 
965     // Record the number and types of arguments.
966     MFI->addParam(In.VT);
967   }
968 
969   // Varargs are copied into a buffer allocated by the caller, and a pointer to
970   // the buffer is passed as an argument.
971   if (IsVarArg) {
972     MVT PtrVT = getPointerTy(MF.getDataLayout());
973     Register VarargVreg =
974         MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrVT));
975     MFI->setVarargBufferVreg(VarargVreg);
976     Chain = DAG.getCopyToReg(
977         Chain, DL, VarargVreg,
978         DAG.getNode(WebAssemblyISD::ARGUMENT, DL, PtrVT,
979                     DAG.getTargetConstant(Ins.size(), DL, MVT::i32)));
980     MFI->addParam(PtrVT);
981   }
982 
983   // Record the number and types of arguments and results.
984   SmallVector<MVT, 4> Params;
985   SmallVector<MVT, 4> Results;
986   computeSignatureVTs(MF.getFunction().getFunctionType(), MF.getFunction(),
987                       DAG.getTarget(), Params, Results);
988   for (MVT VT : Results)
989     MFI->addResult(VT);
990   // TODO: Use signatures in WebAssemblyMachineFunctionInfo too and unify
991   // the param logic here with ComputeSignatureVTs
992   assert(MFI->getParams().size() == Params.size() &&
993          std::equal(MFI->getParams().begin(), MFI->getParams().end(),
994                     Params.begin()));
995 
996   return Chain;
997 }
998 
999 void WebAssemblyTargetLowering::ReplaceNodeResults(
1000     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
1001   switch (N->getOpcode()) {
1002   case ISD::SIGN_EXTEND_INREG:
1003     // Do not add any results, signifying that N should not be custom lowered
1004     // after all. This happens because simd128 turns on custom lowering for
1005     // SIGN_EXTEND_INREG, but for non-vector sign extends the result might be an
1006     // illegal type.
1007     break;
1008   default:
1009     llvm_unreachable(
1010         "ReplaceNodeResults not implemented for this op for WebAssembly!");
1011   }
1012 }
1013 
1014 //===----------------------------------------------------------------------===//
1015 //  Custom lowering hooks.
1016 //===----------------------------------------------------------------------===//
1017 
1018 SDValue WebAssemblyTargetLowering::LowerOperation(SDValue Op,
1019                                                   SelectionDAG &DAG) const {
1020   SDLoc DL(Op);
1021   switch (Op.getOpcode()) {
1022   default:
1023     llvm_unreachable("unimplemented operation lowering");
1024     return SDValue();
1025   case ISD::FrameIndex:
1026     return LowerFrameIndex(Op, DAG);
1027   case ISD::GlobalAddress:
1028     return LowerGlobalAddress(Op, DAG);
1029   case ISD::ExternalSymbol:
1030     return LowerExternalSymbol(Op, DAG);
1031   case ISD::JumpTable:
1032     return LowerJumpTable(Op, DAG);
1033   case ISD::BR_JT:
1034     return LowerBR_JT(Op, DAG);
1035   case ISD::VASTART:
1036     return LowerVASTART(Op, DAG);
1037   case ISD::BlockAddress:
1038   case ISD::BRIND:
1039     fail(DL, DAG, "WebAssembly hasn't implemented computed gotos");
1040     return SDValue();
1041   case ISD::RETURNADDR:
1042     return LowerRETURNADDR(Op, DAG);
1043   case ISD::FRAMEADDR:
1044     return LowerFRAMEADDR(Op, DAG);
1045   case ISD::CopyToReg:
1046     return LowerCopyToReg(Op, DAG);
1047   case ISD::EXTRACT_VECTOR_ELT:
1048   case ISD::INSERT_VECTOR_ELT:
1049     return LowerAccessVectorElement(Op, DAG);
1050   case ISD::INTRINSIC_VOID:
1051   case ISD::INTRINSIC_WO_CHAIN:
1052   case ISD::INTRINSIC_W_CHAIN:
1053     return LowerIntrinsic(Op, DAG);
1054   case ISD::SIGN_EXTEND_INREG:
1055     return LowerSIGN_EXTEND_INREG(Op, DAG);
1056   case ISD::BUILD_VECTOR:
1057     return LowerBUILD_VECTOR(Op, DAG);
1058   case ISD::VECTOR_SHUFFLE:
1059     return LowerVECTOR_SHUFFLE(Op, DAG);
1060   case ISD::SETCC:
1061     return LowerSETCC(Op, DAG);
1062   case ISD::SHL:
1063   case ISD::SRA:
1064   case ISD::SRL:
1065     return LowerShift(Op, DAG);
1066   }
1067 }
1068 
1069 SDValue WebAssemblyTargetLowering::LowerCopyToReg(SDValue Op,
1070                                                   SelectionDAG &DAG) const {
1071   SDValue Src = Op.getOperand(2);
1072   if (isa<FrameIndexSDNode>(Src.getNode())) {
1073     // CopyToReg nodes don't support FrameIndex operands. Other targets select
1074     // the FI to some LEA-like instruction, but since we don't have that, we
1075     // need to insert some kind of instruction that can take an FI operand and
1076     // produces a value usable by CopyToReg (i.e. in a vreg). So insert a dummy
1077     // local.copy between Op and its FI operand.
1078     SDValue Chain = Op.getOperand(0);
1079     SDLoc DL(Op);
1080     unsigned Reg = cast<RegisterSDNode>(Op.getOperand(1))->getReg();
1081     EVT VT = Src.getValueType();
1082     SDValue Copy(DAG.getMachineNode(VT == MVT::i32 ? WebAssembly::COPY_I32
1083                                                    : WebAssembly::COPY_I64,
1084                                     DL, VT, Src),
1085                  0);
1086     return Op.getNode()->getNumValues() == 1
1087                ? DAG.getCopyToReg(Chain, DL, Reg, Copy)
1088                : DAG.getCopyToReg(Chain, DL, Reg, Copy,
1089                                   Op.getNumOperands() == 4 ? Op.getOperand(3)
1090                                                            : SDValue());
1091   }
1092   return SDValue();
1093 }
1094 
1095 SDValue WebAssemblyTargetLowering::LowerFrameIndex(SDValue Op,
1096                                                    SelectionDAG &DAG) const {
1097   int FI = cast<FrameIndexSDNode>(Op)->getIndex();
1098   return DAG.getTargetFrameIndex(FI, Op.getValueType());
1099 }
1100 
1101 SDValue WebAssemblyTargetLowering::LowerRETURNADDR(SDValue Op,
1102                                                    SelectionDAG &DAG) const {
1103   SDLoc DL(Op);
1104 
1105   if (!Subtarget->getTargetTriple().isOSEmscripten()) {
1106     fail(DL, DAG,
1107          "Non-Emscripten WebAssembly hasn't implemented "
1108          "__builtin_return_address");
1109     return SDValue();
1110   }
1111 
1112   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1113     return SDValue();
1114 
1115   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1116   MakeLibCallOptions CallOptions;
1117   return makeLibCall(DAG, RTLIB::RETURN_ADDRESS, Op.getValueType(),
1118                      {DAG.getConstant(Depth, DL, MVT::i32)}, CallOptions, DL)
1119       .first;
1120 }
1121 
1122 SDValue WebAssemblyTargetLowering::LowerFRAMEADDR(SDValue Op,
1123                                                   SelectionDAG &DAG) const {
1124   // Non-zero depths are not supported by WebAssembly currently. Use the
1125   // legalizer's default expansion, which is to return 0 (what this function is
1126   // documented to do).
1127   if (Op.getConstantOperandVal(0) > 0)
1128     return SDValue();
1129 
1130   DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
1131   EVT VT = Op.getValueType();
1132   Register FP =
1133       Subtarget->getRegisterInfo()->getFrameRegister(DAG.getMachineFunction());
1134   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), FP, VT);
1135 }
1136 
1137 SDValue WebAssemblyTargetLowering::LowerGlobalAddress(SDValue Op,
1138                                                       SelectionDAG &DAG) const {
1139   SDLoc DL(Op);
1140   const auto *GA = cast<GlobalAddressSDNode>(Op);
1141   EVT VT = Op.getValueType();
1142   assert(GA->getTargetFlags() == 0 &&
1143          "Unexpected target flags on generic GlobalAddressSDNode");
1144   if (GA->getAddressSpace() != 0)
1145     fail(DL, DAG, "WebAssembly only expects the 0 address space");
1146 
1147   unsigned OperandFlags = 0;
1148   if (isPositionIndependent()) {
1149     const GlobalValue *GV = GA->getGlobal();
1150     if (getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) {
1151       MachineFunction &MF = DAG.getMachineFunction();
1152       MVT PtrVT = getPointerTy(MF.getDataLayout());
1153       const char *BaseName;
1154       if (GV->getValueType()->isFunctionTy()) {
1155         BaseName = MF.createExternalSymbolName("__table_base");
1156         OperandFlags = WebAssemblyII::MO_TABLE_BASE_REL;
1157       }
1158       else {
1159         BaseName = MF.createExternalSymbolName("__memory_base");
1160         OperandFlags = WebAssemblyII::MO_MEMORY_BASE_REL;
1161       }
1162       SDValue BaseAddr =
1163           DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT,
1164                       DAG.getTargetExternalSymbol(BaseName, PtrVT));
1165 
1166       SDValue SymAddr = DAG.getNode(
1167           WebAssemblyISD::WrapperPIC, DL, VT,
1168           DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT, GA->getOffset(),
1169                                      OperandFlags));
1170 
1171       return DAG.getNode(ISD::ADD, DL, VT, BaseAddr, SymAddr);
1172     } else {
1173       OperandFlags = WebAssemblyII::MO_GOT;
1174     }
1175   }
1176 
1177   return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1178                      DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT,
1179                                                 GA->getOffset(), OperandFlags));
1180 }
1181 
1182 SDValue
1183 WebAssemblyTargetLowering::LowerExternalSymbol(SDValue Op,
1184                                                SelectionDAG &DAG) const {
1185   SDLoc DL(Op);
1186   const auto *ES = cast<ExternalSymbolSDNode>(Op);
1187   EVT VT = Op.getValueType();
1188   assert(ES->getTargetFlags() == 0 &&
1189          "Unexpected target flags on generic ExternalSymbolSDNode");
1190   return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1191                      DAG.getTargetExternalSymbol(ES->getSymbol(), VT));
1192 }
1193 
1194 SDValue WebAssemblyTargetLowering::LowerJumpTable(SDValue Op,
1195                                                   SelectionDAG &DAG) const {
1196   // There's no need for a Wrapper node because we always incorporate a jump
1197   // table operand into a BR_TABLE instruction, rather than ever
1198   // materializing it in a register.
1199   const JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1200   return DAG.getTargetJumpTable(JT->getIndex(), Op.getValueType(),
1201                                 JT->getTargetFlags());
1202 }
1203 
1204 SDValue WebAssemblyTargetLowering::LowerBR_JT(SDValue Op,
1205                                               SelectionDAG &DAG) const {
1206   SDLoc DL(Op);
1207   SDValue Chain = Op.getOperand(0);
1208   const auto *JT = cast<JumpTableSDNode>(Op.getOperand(1));
1209   SDValue Index = Op.getOperand(2);
1210   assert(JT->getTargetFlags() == 0 && "WebAssembly doesn't set target flags");
1211 
1212   SmallVector<SDValue, 8> Ops;
1213   Ops.push_back(Chain);
1214   Ops.push_back(Index);
1215 
1216   MachineJumpTableInfo *MJTI = DAG.getMachineFunction().getJumpTableInfo();
1217   const auto &MBBs = MJTI->getJumpTables()[JT->getIndex()].MBBs;
1218 
1219   // Add an operand for each case.
1220   for (auto MBB : MBBs)
1221     Ops.push_back(DAG.getBasicBlock(MBB));
1222 
1223   // TODO: For now, we just pick something arbitrary for a default case for now.
1224   // We really want to sniff out the guard and put in the real default case (and
1225   // delete the guard).
1226   Ops.push_back(DAG.getBasicBlock(MBBs[0]));
1227 
1228   return DAG.getNode(WebAssemblyISD::BR_TABLE, DL, MVT::Other, Ops);
1229 }
1230 
1231 SDValue WebAssemblyTargetLowering::LowerVASTART(SDValue Op,
1232                                                 SelectionDAG &DAG) const {
1233   SDLoc DL(Op);
1234   EVT PtrVT = getPointerTy(DAG.getMachineFunction().getDataLayout());
1235 
1236   auto *MFI = DAG.getMachineFunction().getInfo<WebAssemblyFunctionInfo>();
1237   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1238 
1239   SDValue ArgN = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1240                                     MFI->getVarargBufferVreg(), PtrVT);
1241   return DAG.getStore(Op.getOperand(0), DL, ArgN, Op.getOperand(1),
1242                       MachinePointerInfo(SV), 0);
1243 }
1244 
1245 SDValue WebAssemblyTargetLowering::LowerIntrinsic(SDValue Op,
1246                                                   SelectionDAG &DAG) const {
1247   MachineFunction &MF = DAG.getMachineFunction();
1248   unsigned IntNo;
1249   switch (Op.getOpcode()) {
1250   case ISD::INTRINSIC_VOID:
1251   case ISD::INTRINSIC_W_CHAIN:
1252     IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1253     break;
1254   case ISD::INTRINSIC_WO_CHAIN:
1255     IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1256     break;
1257   default:
1258     llvm_unreachable("Invalid intrinsic");
1259   }
1260   SDLoc DL(Op);
1261 
1262   switch (IntNo) {
1263   default:
1264     return SDValue(); // Don't custom lower most intrinsics.
1265 
1266   case Intrinsic::wasm_lsda: {
1267     EVT VT = Op.getValueType();
1268     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1269     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
1270     auto &Context = MF.getMMI().getContext();
1271     MCSymbol *S = Context.getOrCreateSymbol(Twine("GCC_except_table") +
1272                                             Twine(MF.getFunctionNumber()));
1273     return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1274                        DAG.getMCSymbol(S, PtrVT));
1275   }
1276 
1277   case Intrinsic::wasm_throw: {
1278     // We only support C++ exceptions for now
1279     int Tag = cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue();
1280     if (Tag != CPP_EXCEPTION)
1281       llvm_unreachable("Invalid tag!");
1282     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1283     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
1284     const char *SymName = MF.createExternalSymbolName("__cpp_exception");
1285     SDValue SymNode = DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT,
1286                                   DAG.getTargetExternalSymbol(SymName, PtrVT));
1287     return DAG.getNode(WebAssemblyISD::THROW, DL,
1288                        MVT::Other, // outchain type
1289                        {
1290                            Op.getOperand(0), // inchain
1291                            SymNode,          // exception symbol
1292                            Op.getOperand(3)  // thrown value
1293                        });
1294   }
1295   }
1296 }
1297 
1298 SDValue
1299 WebAssemblyTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
1300                                                   SelectionDAG &DAG) const {
1301   SDLoc DL(Op);
1302   // If sign extension operations are disabled, allow sext_inreg only if operand
1303   // is a vector extract. SIMD does not depend on sign extension operations, but
1304   // allowing sext_inreg in this context lets us have simple patterns to select
1305   // extract_lane_s instructions. Expanding sext_inreg everywhere would be
1306   // simpler in this file, but would necessitate large and brittle patterns to
1307   // undo the expansion and select extract_lane_s instructions.
1308   assert(!Subtarget->hasSignExt() && Subtarget->hasSIMD128());
1309   if (Op.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
1310     const SDValue &Extract = Op.getOperand(0);
1311     MVT VecT = Extract.getOperand(0).getSimpleValueType();
1312     MVT ExtractedLaneT = static_cast<VTSDNode *>(Op.getOperand(1).getNode())
1313                              ->getVT()
1314                              .getSimpleVT();
1315     MVT ExtractedVecT =
1316         MVT::getVectorVT(ExtractedLaneT, 128 / ExtractedLaneT.getSizeInBits());
1317     if (ExtractedVecT == VecT)
1318       return Op;
1319     // Bitcast vector to appropriate type to ensure ISel pattern coverage
1320     const SDValue &Index = Extract.getOperand(1);
1321     unsigned IndexVal =
1322         static_cast<ConstantSDNode *>(Index.getNode())->getZExtValue();
1323     unsigned Scale =
1324         ExtractedVecT.getVectorNumElements() / VecT.getVectorNumElements();
1325     assert(Scale > 1);
1326     SDValue NewIndex =
1327         DAG.getConstant(IndexVal * Scale, DL, Index.getValueType());
1328     SDValue NewExtract = DAG.getNode(
1329         ISD::EXTRACT_VECTOR_ELT, DL, Extract.getValueType(),
1330         DAG.getBitcast(ExtractedVecT, Extract.getOperand(0)), NewIndex);
1331     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, Op.getValueType(),
1332                        NewExtract, Op.getOperand(1));
1333   }
1334   // Otherwise expand
1335   return SDValue();
1336 }
1337 
1338 SDValue WebAssemblyTargetLowering::LowerBUILD_VECTOR(SDValue Op,
1339                                                      SelectionDAG &DAG) const {
1340   SDLoc DL(Op);
1341   const EVT VecT = Op.getValueType();
1342   const EVT LaneT = Op.getOperand(0).getValueType();
1343   const size_t Lanes = Op.getNumOperands();
1344   bool CanSwizzle = Subtarget->hasUnimplementedSIMD128() && VecT == MVT::v16i8;
1345 
1346   // BUILD_VECTORs are lowered to the instruction that initializes the highest
1347   // possible number of lanes at once followed by a sequence of replace_lane
1348   // instructions to individually initialize any remaining lanes.
1349 
1350   // TODO: Tune this. For example, lanewise swizzling is very expensive, so
1351   // swizzled lanes should be given greater weight.
1352 
1353   // TODO: Investigate building vectors by shuffling together vectors built by
1354   // separately specialized means.
1355 
1356   auto IsConstant = [](const SDValue &V) {
1357     return V.getOpcode() == ISD::Constant || V.getOpcode() == ISD::ConstantFP;
1358   };
1359 
1360   // Returns the source vector and index vector pair if they exist. Checks for:
1361   //   (extract_vector_elt
1362   //     $src,
1363   //     (sign_extend_inreg (extract_vector_elt $indices, $i))
1364   //   )
1365   auto GetSwizzleSrcs = [](size_t I, const SDValue &Lane) {
1366     auto Bail = std::make_pair(SDValue(), SDValue());
1367     if (Lane->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1368       return Bail;
1369     const SDValue &SwizzleSrc = Lane->getOperand(0);
1370     const SDValue &IndexExt = Lane->getOperand(1);
1371     if (IndexExt->getOpcode() != ISD::SIGN_EXTEND_INREG)
1372       return Bail;
1373     const SDValue &Index = IndexExt->getOperand(0);
1374     if (Index->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1375       return Bail;
1376     const SDValue &SwizzleIndices = Index->getOperand(0);
1377     if (SwizzleSrc.getValueType() != MVT::v16i8 ||
1378         SwizzleIndices.getValueType() != MVT::v16i8 ||
1379         Index->getOperand(1)->getOpcode() != ISD::Constant ||
1380         Index->getConstantOperandVal(1) != I)
1381       return Bail;
1382     return std::make_pair(SwizzleSrc, SwizzleIndices);
1383   };
1384 
1385   using ValueEntry = std::pair<SDValue, size_t>;
1386   SmallVector<ValueEntry, 16> SplatValueCounts;
1387 
1388   using SwizzleEntry = std::pair<std::pair<SDValue, SDValue>, size_t>;
1389   SmallVector<SwizzleEntry, 16> SwizzleCounts;
1390 
1391   auto AddCount = [](auto &Counts, const auto &Val) {
1392     auto CountIt = std::find_if(Counts.begin(), Counts.end(),
1393                                 [&Val](auto E) { return E.first == Val; });
1394     if (CountIt == Counts.end()) {
1395       Counts.emplace_back(Val, 1);
1396     } else {
1397       CountIt->second++;
1398     }
1399   };
1400 
1401   auto GetMostCommon = [](auto &Counts) {
1402     auto CommonIt =
1403         std::max_element(Counts.begin(), Counts.end(),
1404                          [](auto A, auto B) { return A.second < B.second; });
1405     assert(CommonIt != Counts.end() && "Unexpected all-undef build_vector");
1406     return *CommonIt;
1407   };
1408 
1409   size_t NumConstantLanes = 0;
1410 
1411   // Count eligible lanes for each type of vector creation op
1412   for (size_t I = 0; I < Lanes; ++I) {
1413     const SDValue &Lane = Op->getOperand(I);
1414     if (Lane.isUndef())
1415       continue;
1416 
1417     AddCount(SplatValueCounts, Lane);
1418 
1419     if (IsConstant(Lane)) {
1420       NumConstantLanes++;
1421     } else if (CanSwizzle) {
1422       auto SwizzleSrcs = GetSwizzleSrcs(I, Lane);
1423       if (SwizzleSrcs.first)
1424         AddCount(SwizzleCounts, SwizzleSrcs);
1425     }
1426   }
1427 
1428   SDValue SplatValue;
1429   size_t NumSplatLanes;
1430   std::tie(SplatValue, NumSplatLanes) = GetMostCommon(SplatValueCounts);
1431 
1432   SDValue SwizzleSrc;
1433   SDValue SwizzleIndices;
1434   size_t NumSwizzleLanes = 0;
1435   if (SwizzleCounts.size())
1436     std::forward_as_tuple(std::tie(SwizzleSrc, SwizzleIndices),
1437                           NumSwizzleLanes) = GetMostCommon(SwizzleCounts);
1438 
1439   // Predicate returning true if the lane is properly initialized by the
1440   // original instruction
1441   std::function<bool(size_t, const SDValue &)> IsLaneConstructed;
1442   SDValue Result;
1443   if (Subtarget->hasUnimplementedSIMD128()) {
1444     // Prefer swizzles over vector consts over splats
1445     if (NumSwizzleLanes >= NumSplatLanes &&
1446         NumSwizzleLanes >= NumConstantLanes) {
1447       Result = DAG.getNode(WebAssemblyISD::SWIZZLE, DL, VecT, SwizzleSrc,
1448                            SwizzleIndices);
1449       auto Swizzled = std::make_pair(SwizzleSrc, SwizzleIndices);
1450       IsLaneConstructed = [&, Swizzled](size_t I, const SDValue &Lane) {
1451         return Swizzled == GetSwizzleSrcs(I, Lane);
1452       };
1453     } else if (NumConstantLanes >= NumSplatLanes) {
1454       SmallVector<SDValue, 16> ConstLanes;
1455       for (const SDValue &Lane : Op->op_values()) {
1456         if (IsConstant(Lane)) {
1457           ConstLanes.push_back(Lane);
1458         } else if (LaneT.isFloatingPoint()) {
1459           ConstLanes.push_back(DAG.getConstantFP(0, DL, LaneT));
1460         } else {
1461           ConstLanes.push_back(DAG.getConstant(0, DL, LaneT));
1462         }
1463       }
1464       Result = DAG.getBuildVector(VecT, DL, ConstLanes);
1465       IsLaneConstructed = [&](size_t _, const SDValue &Lane) {
1466         return IsConstant(Lane);
1467       };
1468     }
1469   }
1470   if (!Result) {
1471     // Use a splat, but possibly a load_splat
1472     LoadSDNode *SplattedLoad;
1473     if (Subtarget->hasUnimplementedSIMD128() &&
1474         (SplattedLoad = dyn_cast<LoadSDNode>(SplatValue)) &&
1475         SplattedLoad->getMemoryVT() == VecT.getVectorElementType()) {
1476       Result = DAG.getMemIntrinsicNode(
1477           WebAssemblyISD::LOAD_SPLAT, DL, DAG.getVTList(VecT),
1478           {SplattedLoad->getChain(), SplattedLoad->getBasePtr(),
1479            SplattedLoad->getOffset()},
1480           SplattedLoad->getMemoryVT(), SplattedLoad->getMemOperand());
1481     } else {
1482       Result = DAG.getSplatBuildVector(VecT, DL, SplatValue);
1483     }
1484     IsLaneConstructed = [&](size_t _, const SDValue &Lane) {
1485       return Lane == SplatValue;
1486     };
1487   }
1488 
1489   // Add replace_lane instructions for any unhandled values
1490   for (size_t I = 0; I < Lanes; ++I) {
1491     const SDValue &Lane = Op->getOperand(I);
1492     if (!Lane.isUndef() && !IsLaneConstructed(I, Lane))
1493       Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VecT, Result, Lane,
1494                            DAG.getConstant(I, DL, MVT::i32));
1495   }
1496 
1497   return Result;
1498 }
1499 
1500 SDValue
1501 WebAssemblyTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
1502                                                SelectionDAG &DAG) const {
1503   SDLoc DL(Op);
1504   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op.getNode())->getMask();
1505   MVT VecType = Op.getOperand(0).getSimpleValueType();
1506   assert(VecType.is128BitVector() && "Unexpected shuffle vector type");
1507   size_t LaneBytes = VecType.getVectorElementType().getSizeInBits() / 8;
1508 
1509   // Space for two vector args and sixteen mask indices
1510   SDValue Ops[18];
1511   size_t OpIdx = 0;
1512   Ops[OpIdx++] = Op.getOperand(0);
1513   Ops[OpIdx++] = Op.getOperand(1);
1514 
1515   // Expand mask indices to byte indices and materialize them as operands
1516   for (int M : Mask) {
1517     for (size_t J = 0; J < LaneBytes; ++J) {
1518       // Lower undefs (represented by -1 in mask) to zero
1519       uint64_t ByteIndex = M == -1 ? 0 : (uint64_t)M * LaneBytes + J;
1520       Ops[OpIdx++] = DAG.getConstant(ByteIndex, DL, MVT::i32);
1521     }
1522   }
1523 
1524   return DAG.getNode(WebAssemblyISD::SHUFFLE, DL, Op.getValueType(), Ops);
1525 }
1526 
1527 SDValue WebAssemblyTargetLowering::LowerSETCC(SDValue Op,
1528                                               SelectionDAG &DAG) const {
1529   SDLoc DL(Op);
1530   // The legalizer does not know how to expand the comparison modes of i64x2
1531   // vectors because no comparison modes are supported. We could solve this by
1532   // expanding all i64x2 SETCC nodes, but that seems to expand f64x2 SETCC nodes
1533   // (which return i64x2 results) as well. So instead we manually unroll i64x2
1534   // comparisons here.
1535   assert(Subtarget->hasUnimplementedSIMD128());
1536   assert(Op->getOperand(0)->getSimpleValueType(0) == MVT::v2i64);
1537   SmallVector<SDValue, 2> LHS, RHS;
1538   DAG.ExtractVectorElements(Op->getOperand(0), LHS);
1539   DAG.ExtractVectorElements(Op->getOperand(1), RHS);
1540   const SDValue &CC = Op->getOperand(2);
1541   auto MakeLane = [&](unsigned I) {
1542     return DAG.getNode(ISD::SELECT_CC, DL, MVT::i64, LHS[I], RHS[I],
1543                        DAG.getConstant(uint64_t(-1), DL, MVT::i64),
1544                        DAG.getConstant(uint64_t(0), DL, MVT::i64), CC);
1545   };
1546   return DAG.getBuildVector(Op->getValueType(0), DL,
1547                             {MakeLane(0), MakeLane(1)});
1548 }
1549 
1550 SDValue
1551 WebAssemblyTargetLowering::LowerAccessVectorElement(SDValue Op,
1552                                                     SelectionDAG &DAG) const {
1553   // Allow constant lane indices, expand variable lane indices
1554   SDNode *IdxNode = Op.getOperand(Op.getNumOperands() - 1).getNode();
1555   if (isa<ConstantSDNode>(IdxNode) || IdxNode->isUndef())
1556     return Op;
1557   else
1558     // Perform default expansion
1559     return SDValue();
1560 }
1561 
1562 static SDValue unrollVectorShift(SDValue Op, SelectionDAG &DAG) {
1563   EVT LaneT = Op.getSimpleValueType().getVectorElementType();
1564   // 32-bit and 64-bit unrolled shifts will have proper semantics
1565   if (LaneT.bitsGE(MVT::i32))
1566     return DAG.UnrollVectorOp(Op.getNode());
1567   // Otherwise mask the shift value to get proper semantics from 32-bit shift
1568   SDLoc DL(Op);
1569   SDValue ShiftVal = Op.getOperand(1);
1570   uint64_t MaskVal = LaneT.getSizeInBits() - 1;
1571   SDValue MaskedShiftVal = DAG.getNode(
1572       ISD::AND,                    // mask opcode
1573       DL, ShiftVal.getValueType(), // masked value type
1574       ShiftVal,                    // original shift value operand
1575       DAG.getConstant(MaskVal, DL, ShiftVal.getValueType()) // mask operand
1576   );
1577 
1578   return DAG.UnrollVectorOp(
1579       DAG.getNode(Op.getOpcode(),        // original shift opcode
1580                   DL, Op.getValueType(), // original return type
1581                   Op.getOperand(0),      // original vector operand,
1582                   MaskedShiftVal         // new masked shift value operand
1583                   )
1584           .getNode());
1585 }
1586 
1587 SDValue WebAssemblyTargetLowering::LowerShift(SDValue Op,
1588                                               SelectionDAG &DAG) const {
1589   SDLoc DL(Op);
1590 
1591   // Only manually lower vector shifts
1592   assert(Op.getSimpleValueType().isVector());
1593 
1594   // Unroll non-splat vector shifts
1595   BuildVectorSDNode *ShiftVec;
1596   SDValue SplatVal;
1597   if (!(ShiftVec = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode())) ||
1598       !(SplatVal = ShiftVec->getSplatValue()))
1599     return unrollVectorShift(Op, DAG);
1600 
1601   // All splats except i64x2 const splats are handled by patterns
1602   auto *SplatConst = dyn_cast<ConstantSDNode>(SplatVal);
1603   if (!SplatConst || Op.getSimpleValueType() != MVT::v2i64)
1604     return Op;
1605 
1606   // i64x2 const splats are custom lowered to avoid unnecessary wraps
1607   unsigned Opcode;
1608   switch (Op.getOpcode()) {
1609   case ISD::SHL:
1610     Opcode = WebAssemblyISD::VEC_SHL;
1611     break;
1612   case ISD::SRA:
1613     Opcode = WebAssemblyISD::VEC_SHR_S;
1614     break;
1615   case ISD::SRL:
1616     Opcode = WebAssemblyISD::VEC_SHR_U;
1617     break;
1618   default:
1619     llvm_unreachable("unexpected opcode");
1620   }
1621   APInt Shift = SplatConst->getAPIntValue().zextOrTrunc(32);
1622   return DAG.getNode(Opcode, DL, Op.getValueType(), Op.getOperand(0),
1623                      DAG.getConstant(Shift, DL, MVT::i32));
1624 }
1625 
1626 //===----------------------------------------------------------------------===//
1627 //                          WebAssembly Optimization Hooks
1628 //===----------------------------------------------------------------------===//
1629