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