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