1 //=- WebAssemblyISelLowering.cpp - WebAssembly DAG Lowering Implementation -==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// This file implements the WebAssemblyTargetLowering class.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "WebAssemblyISelLowering.h"
16 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
17 #include "WebAssemblyMachineFunctionInfo.h"
18 #include "WebAssemblySubtarget.h"
19 #include "WebAssemblyTargetMachine.h"
20 #include "llvm/CodeGen/Analysis.h"
21 #include "llvm/CodeGen/CallingConvLower.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineJumpTableInfo.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAG.h"
27 #include "llvm/CodeGen/WasmEHFuncInfo.h"
28 #include "llvm/IR/DiagnosticInfo.h"
29 #include "llvm/IR/DiagnosticPrinter.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/Intrinsics.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 // Emit proposed instructions that may not have been implemented in engines
41 cl::opt<bool> EnableUnimplementedWasmSIMDInstrs(
42     "wasm-enable-unimplemented-simd",
43     cl::desc("Emit potentially-unimplemented WebAssembly SIMD instructions"),
44     cl::init(false));
45 
46 WebAssemblyTargetLowering::WebAssemblyTargetLowering(
47     const TargetMachine &TM, const WebAssemblySubtarget &STI)
48     : TargetLowering(TM), Subtarget(&STI) {
49   auto MVTPtr = Subtarget->hasAddr64() ? MVT::i64 : MVT::i32;
50 
51   // Booleans always contain 0 or 1.
52   setBooleanContents(ZeroOrOneBooleanContent);
53   // Except in SIMD vectors
54   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
55   // WebAssembly does not produce floating-point exceptions on normal floating
56   // point operations.
57   setHasFloatingPointExceptions(false);
58   // We don't know the microarchitecture here, so just reduce register pressure.
59   setSchedulingPreference(Sched::RegPressure);
60   // Tell ISel that we have a stack pointer.
61   setStackPointerRegisterToSaveRestore(
62       Subtarget->hasAddr64() ? WebAssembly::SP64 : WebAssembly::SP32);
63   // Set up the register classes.
64   addRegisterClass(MVT::i32, &WebAssembly::I32RegClass);
65   addRegisterClass(MVT::i64, &WebAssembly::I64RegClass);
66   addRegisterClass(MVT::f32, &WebAssembly::F32RegClass);
67   addRegisterClass(MVT::f64, &WebAssembly::F64RegClass);
68   if (Subtarget->hasSIMD128()) {
69     addRegisterClass(MVT::v16i8, &WebAssembly::V128RegClass);
70     addRegisterClass(MVT::v8i16, &WebAssembly::V128RegClass);
71     addRegisterClass(MVT::v4i32, &WebAssembly::V128RegClass);
72     addRegisterClass(MVT::v4f32, &WebAssembly::V128RegClass);
73     if (EnableUnimplementedWasmSIMDInstrs) {
74       addRegisterClass(MVT::v2i64, &WebAssembly::V128RegClass);
75       addRegisterClass(MVT::v2f64, &WebAssembly::V128RegClass);
76     }
77   }
78   // Compute derived properties from the register classes.
79   computeRegisterProperties(Subtarget->getRegisterInfo());
80 
81   setOperationAction(ISD::GlobalAddress, MVTPtr, Custom);
82   setOperationAction(ISD::ExternalSymbol, MVTPtr, Custom);
83   setOperationAction(ISD::JumpTable, MVTPtr, Custom);
84   setOperationAction(ISD::BlockAddress, MVTPtr, Custom);
85   setOperationAction(ISD::BRIND, MVT::Other, Custom);
86 
87   // Take the default expansion for va_arg, va_copy, and va_end. There is no
88   // default action for va_start, so we do that custom.
89   setOperationAction(ISD::VASTART, MVT::Other, Custom);
90   setOperationAction(ISD::VAARG, MVT::Other, Expand);
91   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
92   setOperationAction(ISD::VAEND, MVT::Other, Expand);
93 
94   for (auto T : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
95     // Don't expand the floating-point types to constant pools.
96     setOperationAction(ISD::ConstantFP, T, Legal);
97     // Expand floating-point comparisons.
98     for (auto CC : {ISD::SETO, ISD::SETUO, ISD::SETUEQ, ISD::SETONE,
99                     ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE})
100       setCondCodeAction(CC, T, Expand);
101     // Expand floating-point library function operators.
102     for (auto Op :
103          {ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FREM, ISD::FMA})
104       setOperationAction(Op, T, Expand);
105     // Note supported floating-point library function operators that otherwise
106     // default to expand.
107     for (auto Op :
108          {ISD::FCEIL, ISD::FFLOOR, ISD::FTRUNC, ISD::FNEARBYINT, ISD::FRINT})
109       setOperationAction(Op, T, Legal);
110     // Support minimum and maximum, which otherwise default to expand.
111     setOperationAction(ISD::FMINIMUM, T, Legal);
112     setOperationAction(ISD::FMAXIMUM, T, Legal);
113     // WebAssembly currently has no builtin f16 support.
114     setOperationAction(ISD::FP16_TO_FP, T, Expand);
115     setOperationAction(ISD::FP_TO_FP16, T, Expand);
116     setLoadExtAction(ISD::EXTLOAD, T, MVT::f16, Expand);
117     setTruncStoreAction(T, MVT::f16, Expand);
118   }
119 
120   // Support saturating add for i8x16 and i16x8
121   if (Subtarget->hasSIMD128())
122     for (auto T : {MVT::v16i8, MVT::v8i16})
123       for (auto Op : {ISD::SADDSAT, ISD::UADDSAT})
124         setOperationAction(Op, T, Legal);
125 
126   for (auto T : {MVT::i32, MVT::i64}) {
127     // Expand unavailable integer operations.
128     for (auto Op :
129          {ISD::BSWAP, ISD::SMUL_LOHI, ISD::UMUL_LOHI, ISD::MULHS, ISD::MULHU,
130           ISD::SDIVREM, ISD::UDIVREM, ISD::SHL_PARTS, ISD::SRA_PARTS,
131           ISD::SRL_PARTS, ISD::ADDC, ISD::ADDE, ISD::SUBC, ISD::SUBE}) {
132       setOperationAction(Op, T, Expand);
133     }
134   }
135 
136   // There is no i64x2.mul instruction
137   setOperationAction(ISD::MUL, MVT::v2i64, Expand);
138 
139   // We have custom shuffle lowering to expose the shuffle mask
140   if (Subtarget->hasSIMD128()) {
141     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32}) {
142       setOperationAction(ISD::VECTOR_SHUFFLE, T, Custom);
143     }
144     if (EnableUnimplementedWasmSIMDInstrs) {
145       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
146       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
147     }
148   }
149 
150   // Custom lowering since wasm shifts must have a scalar shift amount
151   if (Subtarget->hasSIMD128()) {
152     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
153       for (auto Op : {ISD::SHL, ISD::SRA, ISD::SRL})
154         setOperationAction(Op, T, Custom);
155     if (EnableUnimplementedWasmSIMDInstrs)
156       for (auto Op : {ISD::SHL, ISD::SRA, ISD::SRL})
157         setOperationAction(Op, MVT::v2i64, Custom);
158   }
159 
160   // There are no select instructions for vectors
161   if (Subtarget->hasSIMD128())
162     for (auto Op : {ISD::VSELECT, ISD::SELECT_CC, ISD::SELECT}) {
163       for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32})
164         setOperationAction(Op, T, Expand);
165       if (EnableUnimplementedWasmSIMDInstrs)
166         for (auto T : {MVT::v2i64, MVT::v2f64})
167           setOperationAction(Op, T, Expand);
168     }
169 
170   // As a special case, these operators use the type to mean the type to
171   // sign-extend from.
172   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
173   if (!Subtarget->hasSignExt()) {
174     for (auto T : {MVT::i8, MVT::i16, MVT::i32})
175       setOperationAction(ISD::SIGN_EXTEND_INREG, T, Expand);
176   }
177   for (auto T : MVT::integer_vector_valuetypes())
178     setOperationAction(ISD::SIGN_EXTEND_INREG, T, Expand);
179 
180   // Dynamic stack allocation: use the default expansion.
181   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
182   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
183   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVTPtr, Expand);
184 
185   setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
186   setOperationAction(ISD::CopyToReg, MVT::Other, Custom);
187 
188   // Expand these forms; we pattern-match the forms that we can handle in isel.
189   for (auto T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64})
190     for (auto Op : {ISD::BR_CC, ISD::SELECT_CC})
191       setOperationAction(Op, T, Expand);
192 
193   // We have custom switch handling.
194   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
195 
196   // WebAssembly doesn't have:
197   //  - Floating-point extending loads.
198   //  - Floating-point truncating stores.
199   //  - i1 extending loads.
200   //  - extending/truncating SIMD loads/stores
201   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
202   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
203   for (auto T : MVT::integer_valuetypes())
204     for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD})
205       setLoadExtAction(Ext, T, MVT::i1, Promote);
206   if (Subtarget->hasSIMD128()) {
207     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64, MVT::v4f32,
208                    MVT::v2f64}) {
209       for (auto MemT : MVT::vector_valuetypes()) {
210         if (MVT(T) != MemT) {
211           setTruncStoreAction(T, MemT, Expand);
212           for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD})
213             setLoadExtAction(Ext, T, MemT, Expand);
214         }
215       }
216     }
217   }
218 
219   // Custom lower lane accesses to expand out variable indices
220   if (Subtarget->hasSIMD128()) {
221     for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32}) {
222       setOperationAction(ISD::EXTRACT_VECTOR_ELT, T, Custom);
223       setOperationAction(ISD::INSERT_VECTOR_ELT, T, Custom);
224     }
225     if (EnableUnimplementedWasmSIMDInstrs) {
226       for (auto T : {MVT::v2i64, MVT::v2f64}) {
227         setOperationAction(ISD::EXTRACT_VECTOR_ELT, T, Custom);
228         setOperationAction(ISD::INSERT_VECTOR_ELT, T, Custom);
229       }
230     }
231   }
232 
233   // Trap lowers to wasm unreachable
234   setOperationAction(ISD::TRAP, MVT::Other, Legal);
235 
236   // Exception handling intrinsics
237   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
238   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
239 
240   setMaxAtomicSizeInBitsSupported(64);
241 }
242 
243 TargetLowering::AtomicExpansionKind
244 WebAssemblyTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
245   // We have wasm instructions for these
246   switch (AI->getOperation()) {
247   case AtomicRMWInst::Add:
248   case AtomicRMWInst::Sub:
249   case AtomicRMWInst::And:
250   case AtomicRMWInst::Or:
251   case AtomicRMWInst::Xor:
252   case AtomicRMWInst::Xchg:
253     return AtomicExpansionKind::None;
254   default:
255     break;
256   }
257   return AtomicExpansionKind::CmpXChg;
258 }
259 
260 FastISel *WebAssemblyTargetLowering::createFastISel(
261     FunctionLoweringInfo &FuncInfo, const TargetLibraryInfo *LibInfo) const {
262   return WebAssembly::createFastISel(FuncInfo, LibInfo);
263 }
264 
265 bool WebAssemblyTargetLowering::isOffsetFoldingLegal(
266     const GlobalAddressSDNode * /*GA*/) const {
267   // All offsets can be folded.
268   return true;
269 }
270 
271 MVT WebAssemblyTargetLowering::getScalarShiftAmountTy(const DataLayout & /*DL*/,
272                                                       EVT VT) const {
273   unsigned BitWidth = NextPowerOf2(VT.getSizeInBits() - 1);
274   if (BitWidth > 1 && BitWidth < 8)
275     BitWidth = 8;
276 
277   if (BitWidth > 64) {
278     // The shift will be lowered to a libcall, and compiler-rt libcalls expect
279     // the count to be an i32.
280     BitWidth = 32;
281     assert(BitWidth >= Log2_32_Ceil(VT.getSizeInBits()) &&
282            "32-bit shift counts ought to be enough for anyone");
283   }
284 
285   MVT Result = MVT::getIntegerVT(BitWidth);
286   assert(Result != MVT::INVALID_SIMPLE_VALUE_TYPE &&
287          "Unable to represent scalar shift amount type");
288   return Result;
289 }
290 
291 // Lower an fp-to-int conversion operator from the LLVM opcode, which has an
292 // undefined result on invalid/overflow, to the WebAssembly opcode, which
293 // traps on invalid/overflow.
294 static MachineBasicBlock *LowerFPToInt(MachineInstr &MI, DebugLoc DL,
295                                        MachineBasicBlock *BB,
296                                        const TargetInstrInfo &TII,
297                                        bool IsUnsigned, bool Int64,
298                                        bool Float64, unsigned LoweredOpcode) {
299   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
300 
301   unsigned OutReg = MI.getOperand(0).getReg();
302   unsigned InReg = MI.getOperand(1).getReg();
303 
304   unsigned Abs = Float64 ? WebAssembly::ABS_F64 : WebAssembly::ABS_F32;
305   unsigned FConst = Float64 ? WebAssembly::CONST_F64 : WebAssembly::CONST_F32;
306   unsigned LT = Float64 ? WebAssembly::LT_F64 : WebAssembly::LT_F32;
307   unsigned GE = Float64 ? WebAssembly::GE_F64 : WebAssembly::GE_F32;
308   unsigned IConst = Int64 ? WebAssembly::CONST_I64 : WebAssembly::CONST_I32;
309   unsigned Eqz = WebAssembly::EQZ_I32;
310   unsigned And = WebAssembly::AND_I32;
311   int64_t Limit = Int64 ? INT64_MIN : INT32_MIN;
312   int64_t Substitute = IsUnsigned ? 0 : Limit;
313   double CmpVal = IsUnsigned ? -(double)Limit * 2.0 : -(double)Limit;
314   auto &Context = BB->getParent()->getFunction().getContext();
315   Type *Ty = Float64 ? Type::getDoubleTy(Context) : Type::getFloatTy(Context);
316 
317   const BasicBlock *LLVM_BB = BB->getBasicBlock();
318   MachineFunction *F = BB->getParent();
319   MachineBasicBlock *TrueMBB = F->CreateMachineBasicBlock(LLVM_BB);
320   MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
321   MachineBasicBlock *DoneMBB = F->CreateMachineBasicBlock(LLVM_BB);
322 
323   MachineFunction::iterator It = ++BB->getIterator();
324   F->insert(It, FalseMBB);
325   F->insert(It, TrueMBB);
326   F->insert(It, DoneMBB);
327 
328   // Transfer the remainder of BB and its successor edges to DoneMBB.
329   DoneMBB->splice(DoneMBB->begin(), BB,
330                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
331   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
332 
333   BB->addSuccessor(TrueMBB);
334   BB->addSuccessor(FalseMBB);
335   TrueMBB->addSuccessor(DoneMBB);
336   FalseMBB->addSuccessor(DoneMBB);
337 
338   unsigned Tmp0, Tmp1, CmpReg, EqzReg, FalseReg, TrueReg;
339   Tmp0 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
340   Tmp1 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
341   CmpReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
342   EqzReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
343   FalseReg = MRI.createVirtualRegister(MRI.getRegClass(OutReg));
344   TrueReg = MRI.createVirtualRegister(MRI.getRegClass(OutReg));
345 
346   MI.eraseFromParent();
347   // For signed numbers, we can do a single comparison to determine whether
348   // fabs(x) is within range.
349   if (IsUnsigned) {
350     Tmp0 = InReg;
351   } else {
352     BuildMI(BB, DL, TII.get(Abs), Tmp0).addReg(InReg);
353   }
354   BuildMI(BB, DL, TII.get(FConst), Tmp1)
355       .addFPImm(cast<ConstantFP>(ConstantFP::get(Ty, CmpVal)));
356   BuildMI(BB, DL, TII.get(LT), CmpReg).addReg(Tmp0).addReg(Tmp1);
357 
358   // For unsigned numbers, we have to do a separate comparison with zero.
359   if (IsUnsigned) {
360     Tmp1 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
361     unsigned SecondCmpReg =
362         MRI.createVirtualRegister(&WebAssembly::I32RegClass);
363     unsigned AndReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
364     BuildMI(BB, DL, TII.get(FConst), Tmp1)
365         .addFPImm(cast<ConstantFP>(ConstantFP::get(Ty, 0.0)));
366     BuildMI(BB, DL, TII.get(GE), SecondCmpReg).addReg(Tmp0).addReg(Tmp1);
367     BuildMI(BB, DL, TII.get(And), AndReg).addReg(CmpReg).addReg(SecondCmpReg);
368     CmpReg = AndReg;
369   }
370 
371   BuildMI(BB, DL, TII.get(Eqz), EqzReg).addReg(CmpReg);
372 
373   // Create the CFG diamond to select between doing the conversion or using
374   // the substitute value.
375   BuildMI(BB, DL, TII.get(WebAssembly::BR_IF)).addMBB(TrueMBB).addReg(EqzReg);
376   BuildMI(FalseMBB, DL, TII.get(LoweredOpcode), FalseReg).addReg(InReg);
377   BuildMI(FalseMBB, DL, TII.get(WebAssembly::BR)).addMBB(DoneMBB);
378   BuildMI(TrueMBB, DL, TII.get(IConst), TrueReg).addImm(Substitute);
379   BuildMI(*DoneMBB, DoneMBB->begin(), DL, TII.get(TargetOpcode::PHI), OutReg)
380       .addReg(FalseReg)
381       .addMBB(FalseMBB)
382       .addReg(TrueReg)
383       .addMBB(TrueMBB);
384 
385   return DoneMBB;
386 }
387 
388 MachineBasicBlock *WebAssemblyTargetLowering::EmitInstrWithCustomInserter(
389     MachineInstr &MI, MachineBasicBlock *BB) const {
390   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
391   DebugLoc DL = MI.getDebugLoc();
392 
393   switch (MI.getOpcode()) {
394   default:
395     llvm_unreachable("Unexpected instr type to insert");
396   case WebAssembly::FP_TO_SINT_I32_F32:
397     return LowerFPToInt(MI, DL, BB, TII, false, false, false,
398                         WebAssembly::I32_TRUNC_S_F32);
399   case WebAssembly::FP_TO_UINT_I32_F32:
400     return LowerFPToInt(MI, DL, BB, TII, true, false, false,
401                         WebAssembly::I32_TRUNC_U_F32);
402   case WebAssembly::FP_TO_SINT_I64_F32:
403     return LowerFPToInt(MI, DL, BB, TII, false, true, false,
404                         WebAssembly::I64_TRUNC_S_F32);
405   case WebAssembly::FP_TO_UINT_I64_F32:
406     return LowerFPToInt(MI, DL, BB, TII, true, true, false,
407                         WebAssembly::I64_TRUNC_U_F32);
408   case WebAssembly::FP_TO_SINT_I32_F64:
409     return LowerFPToInt(MI, DL, BB, TII, false, false, true,
410                         WebAssembly::I32_TRUNC_S_F64);
411   case WebAssembly::FP_TO_UINT_I32_F64:
412     return LowerFPToInt(MI, DL, BB, TII, true, false, true,
413                         WebAssembly::I32_TRUNC_U_F64);
414   case WebAssembly::FP_TO_SINT_I64_F64:
415     return LowerFPToInt(MI, DL, BB, TII, false, true, true,
416                         WebAssembly::I64_TRUNC_S_F64);
417   case WebAssembly::FP_TO_UINT_I64_F64:
418     return LowerFPToInt(MI, DL, BB, TII, true, true, true,
419                         WebAssembly::I64_TRUNC_U_F64);
420     llvm_unreachable("Unexpected instruction to emit with custom inserter");
421   }
422 }
423 
424 const char *
425 WebAssemblyTargetLowering::getTargetNodeName(unsigned Opcode) const {
426   switch (static_cast<WebAssemblyISD::NodeType>(Opcode)) {
427   case WebAssemblyISD::FIRST_NUMBER:
428     break;
429 #define HANDLE_NODETYPE(NODE)                                                  \
430   case WebAssemblyISD::NODE:                                                   \
431     return "WebAssemblyISD::" #NODE;
432 #include "WebAssemblyISD.def"
433 #undef HANDLE_NODETYPE
434   }
435   return nullptr;
436 }
437 
438 std::pair<unsigned, const TargetRegisterClass *>
439 WebAssemblyTargetLowering::getRegForInlineAsmConstraint(
440     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
441   // First, see if this is a constraint that directly corresponds to a
442   // WebAssembly register class.
443   if (Constraint.size() == 1) {
444     switch (Constraint[0]) {
445     case 'r':
446       assert(VT != MVT::iPTR && "Pointer MVT not expected here");
447       if (Subtarget->hasSIMD128() && VT.isVector()) {
448         if (VT.getSizeInBits() == 128)
449           return std::make_pair(0U, &WebAssembly::V128RegClass);
450       }
451       if (VT.isInteger() && !VT.isVector()) {
452         if (VT.getSizeInBits() <= 32)
453           return std::make_pair(0U, &WebAssembly::I32RegClass);
454         if (VT.getSizeInBits() <= 64)
455           return std::make_pair(0U, &WebAssembly::I64RegClass);
456       }
457       break;
458     default:
459       break;
460     }
461   }
462 
463   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
464 }
465 
466 bool WebAssemblyTargetLowering::isCheapToSpeculateCttz() const {
467   // Assume ctz is a relatively cheap operation.
468   return true;
469 }
470 
471 bool WebAssemblyTargetLowering::isCheapToSpeculateCtlz() const {
472   // Assume clz is a relatively cheap operation.
473   return true;
474 }
475 
476 bool WebAssemblyTargetLowering::isLegalAddressingMode(const DataLayout &DL,
477                                                       const AddrMode &AM,
478                                                       Type *Ty, unsigned AS,
479                                                       Instruction *I) const {
480   // WebAssembly offsets are added as unsigned without wrapping. The
481   // isLegalAddressingMode gives us no way to determine if wrapping could be
482   // happening, so we approximate this by accepting only non-negative offsets.
483   if (AM.BaseOffs < 0)
484     return false;
485 
486   // WebAssembly has no scale register operands.
487   if (AM.Scale != 0)
488     return false;
489 
490   // Everything else is legal.
491   return true;
492 }
493 
494 bool WebAssemblyTargetLowering::allowsMisalignedMemoryAccesses(
495     EVT /*VT*/, unsigned /*AddrSpace*/, unsigned /*Align*/, bool *Fast) const {
496   // WebAssembly supports unaligned accesses, though it should be declared
497   // with the p2align attribute on loads and stores which do so, and there
498   // may be a performance impact. We tell LLVM they're "fast" because
499   // for the kinds of things that LLVM uses this for (merging adjacent stores
500   // of constants, etc.), WebAssembly implementations will either want the
501   // unaligned access or they'll split anyway.
502   if (Fast)
503     *Fast = true;
504   return true;
505 }
506 
507 bool WebAssemblyTargetLowering::isIntDivCheap(EVT VT,
508                                               AttributeList Attr) const {
509   // The current thinking is that wasm engines will perform this optimization,
510   // so we can save on code size.
511   return true;
512 }
513 
514 EVT WebAssemblyTargetLowering::getSetCCResultType(const DataLayout &DL,
515                                                   LLVMContext &C,
516                                                   EVT VT) const {
517   if (VT.isVector())
518     return VT.changeVectorElementTypeToInteger();
519 
520   return TargetLowering::getSetCCResultType(DL, C, VT);
521 }
522 
523 bool WebAssemblyTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
524                                                    const CallInst &I,
525                                                    MachineFunction &MF,
526                                                    unsigned Intrinsic) const {
527   switch (Intrinsic) {
528   case Intrinsic::wasm_atomic_notify:
529     Info.opc = ISD::INTRINSIC_W_CHAIN;
530     Info.memVT = MVT::i32;
531     Info.ptrVal = I.getArgOperand(0);
532     Info.offset = 0;
533     Info.align = 4;
534     // atomic.notify instruction does not really load the memory specified with
535     // this argument, but MachineMemOperand should either be load or store, so
536     // we set this to a load.
537     // FIXME Volatile isn't really correct, but currently all LLVM atomic
538     // instructions are treated as volatiles in the backend, so we should be
539     // consistent. The same applies for wasm_atomic_wait intrinsics too.
540     Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
541     return true;
542   case Intrinsic::wasm_atomic_wait_i32:
543     Info.opc = ISD::INTRINSIC_W_CHAIN;
544     Info.memVT = MVT::i32;
545     Info.ptrVal = I.getArgOperand(0);
546     Info.offset = 0;
547     Info.align = 4;
548     Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
549     return true;
550   case Intrinsic::wasm_atomic_wait_i64:
551     Info.opc = ISD::INTRINSIC_W_CHAIN;
552     Info.memVT = MVT::i64;
553     Info.ptrVal = I.getArgOperand(0);
554     Info.offset = 0;
555     Info.align = 8;
556     Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
557     return true;
558   default:
559     return false;
560   }
561 }
562 
563 //===----------------------------------------------------------------------===//
564 // WebAssembly Lowering private implementation.
565 //===----------------------------------------------------------------------===//
566 
567 //===----------------------------------------------------------------------===//
568 // Lowering Code
569 //===----------------------------------------------------------------------===//
570 
571 static void fail(const SDLoc &DL, SelectionDAG &DAG, const char *msg) {
572   MachineFunction &MF = DAG.getMachineFunction();
573   DAG.getContext()->diagnose(
574       DiagnosticInfoUnsupported(MF.getFunction(), msg, DL.getDebugLoc()));
575 }
576 
577 // Test whether the given calling convention is supported.
578 static bool CallingConvSupported(CallingConv::ID CallConv) {
579   // We currently support the language-independent target-independent
580   // conventions. We don't yet have a way to annotate calls with properties like
581   // "cold", and we don't have any call-clobbered registers, so these are mostly
582   // all handled the same.
583   return CallConv == CallingConv::C || CallConv == CallingConv::Fast ||
584          CallConv == CallingConv::Cold ||
585          CallConv == CallingConv::PreserveMost ||
586          CallConv == CallingConv::PreserveAll ||
587          CallConv == CallingConv::CXX_FAST_TLS;
588 }
589 
590 SDValue
591 WebAssemblyTargetLowering::LowerCall(CallLoweringInfo &CLI,
592                                      SmallVectorImpl<SDValue> &InVals) const {
593   SelectionDAG &DAG = CLI.DAG;
594   SDLoc DL = CLI.DL;
595   SDValue Chain = CLI.Chain;
596   SDValue Callee = CLI.Callee;
597   MachineFunction &MF = DAG.getMachineFunction();
598   auto Layout = MF.getDataLayout();
599 
600   CallingConv::ID CallConv = CLI.CallConv;
601   if (!CallingConvSupported(CallConv))
602     fail(DL, DAG,
603          "WebAssembly doesn't support language-specific or target-specific "
604          "calling conventions yet");
605   if (CLI.IsPatchPoint)
606     fail(DL, DAG, "WebAssembly doesn't support patch point yet");
607 
608   // WebAssembly doesn't currently support explicit tail calls. If they are
609   // required, fail. Otherwise, just disable them.
610   if ((CallConv == CallingConv::Fast && CLI.IsTailCall &&
611        MF.getTarget().Options.GuaranteedTailCallOpt) ||
612       (CLI.CS && CLI.CS.isMustTailCall()))
613     fail(DL, DAG, "WebAssembly doesn't support tail call yet");
614   CLI.IsTailCall = false;
615 
616   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
617   if (Ins.size() > 1)
618     fail(DL, DAG, "WebAssembly doesn't support more than 1 returned value yet");
619 
620   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
621   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
622   unsigned NumFixedArgs = 0;
623   for (unsigned i = 0; i < Outs.size(); ++i) {
624     const ISD::OutputArg &Out = Outs[i];
625     SDValue &OutVal = OutVals[i];
626     if (Out.Flags.isNest())
627       fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
628     if (Out.Flags.isInAlloca())
629       fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
630     if (Out.Flags.isInConsecutiveRegs())
631       fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
632     if (Out.Flags.isInConsecutiveRegsLast())
633       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
634     if (Out.Flags.isByVal() && Out.Flags.getByValSize() != 0) {
635       auto &MFI = MF.getFrameInfo();
636       int FI = MFI.CreateStackObject(Out.Flags.getByValSize(),
637                                      Out.Flags.getByValAlign(),
638                                      /*isSS=*/false);
639       SDValue SizeNode =
640           DAG.getConstant(Out.Flags.getByValSize(), DL, MVT::i32);
641       SDValue FINode = DAG.getFrameIndex(FI, getPointerTy(Layout));
642       Chain = DAG.getMemcpy(
643           Chain, DL, FINode, OutVal, SizeNode, Out.Flags.getByValAlign(),
644           /*isVolatile*/ false, /*AlwaysInline=*/false,
645           /*isTailCall*/ false, MachinePointerInfo(), MachinePointerInfo());
646       OutVal = FINode;
647     }
648     // Count the number of fixed args *after* legalization.
649     NumFixedArgs += Out.IsFixed;
650   }
651 
652   bool IsVarArg = CLI.IsVarArg;
653   auto PtrVT = getPointerTy(Layout);
654 
655   // Analyze operands of the call, assigning locations to each operand.
656   SmallVector<CCValAssign, 16> ArgLocs;
657   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
658 
659   if (IsVarArg) {
660     // Outgoing non-fixed arguments are placed in a buffer. First
661     // compute their offsets and the total amount of buffer space needed.
662     for (SDValue Arg :
663          make_range(OutVals.begin() + NumFixedArgs, OutVals.end())) {
664       EVT VT = Arg.getValueType();
665       assert(VT != MVT::iPTR && "Legalized args should be concrete");
666       Type *Ty = VT.getTypeForEVT(*DAG.getContext());
667       unsigned Offset = CCInfo.AllocateStack(Layout.getTypeAllocSize(Ty),
668                                              Layout.getABITypeAlignment(Ty));
669       CCInfo.addLoc(CCValAssign::getMem(ArgLocs.size(), VT.getSimpleVT(),
670                                         Offset, VT.getSimpleVT(),
671                                         CCValAssign::Full));
672     }
673   }
674 
675   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
676 
677   SDValue FINode;
678   if (IsVarArg && NumBytes) {
679     // For non-fixed arguments, next emit stores to store the argument values
680     // to the stack buffer at the offsets computed above.
681     int FI = MF.getFrameInfo().CreateStackObject(NumBytes,
682                                                  Layout.getStackAlignment(),
683                                                  /*isSS=*/false);
684     unsigned ValNo = 0;
685     SmallVector<SDValue, 8> Chains;
686     for (SDValue Arg :
687          make_range(OutVals.begin() + NumFixedArgs, OutVals.end())) {
688       assert(ArgLocs[ValNo].getValNo() == ValNo &&
689              "ArgLocs should remain in order and only hold varargs args");
690       unsigned Offset = ArgLocs[ValNo++].getLocMemOffset();
691       FINode = DAG.getFrameIndex(FI, getPointerTy(Layout));
692       SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, FINode,
693                                 DAG.getConstant(Offset, DL, PtrVT));
694       Chains.push_back(
695           DAG.getStore(Chain, DL, Arg, Add,
696                        MachinePointerInfo::getFixedStack(MF, FI, Offset), 0));
697     }
698     if (!Chains.empty())
699       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
700   } else if (IsVarArg) {
701     FINode = DAG.getIntPtrConstant(0, DL);
702   }
703 
704   // Compute the operands for the CALLn node.
705   SmallVector<SDValue, 16> Ops;
706   Ops.push_back(Chain);
707   Ops.push_back(Callee);
708 
709   // Add all fixed arguments. Note that for non-varargs calls, NumFixedArgs
710   // isn't reliable.
711   Ops.append(OutVals.begin(),
712              IsVarArg ? OutVals.begin() + NumFixedArgs : OutVals.end());
713   // Add a pointer to the vararg buffer.
714   if (IsVarArg)
715     Ops.push_back(FINode);
716 
717   SmallVector<EVT, 8> InTys;
718   for (const auto &In : Ins) {
719     assert(!In.Flags.isByVal() && "byval is not valid for return values");
720     assert(!In.Flags.isNest() && "nest is not valid for return values");
721     if (In.Flags.isInAlloca())
722       fail(DL, DAG, "WebAssembly hasn't implemented inalloca return values");
723     if (In.Flags.isInConsecutiveRegs())
724       fail(DL, DAG, "WebAssembly hasn't implemented cons regs return values");
725     if (In.Flags.isInConsecutiveRegsLast())
726       fail(DL, DAG,
727            "WebAssembly hasn't implemented cons regs last return values");
728     // Ignore In.getOrigAlign() because all our arguments are passed in
729     // registers.
730     InTys.push_back(In.VT);
731   }
732   InTys.push_back(MVT::Other);
733   SDVTList InTyList = DAG.getVTList(InTys);
734   SDValue Res =
735       DAG.getNode(Ins.empty() ? WebAssemblyISD::CALL0 : WebAssemblyISD::CALL1,
736                   DL, InTyList, Ops);
737   if (Ins.empty()) {
738     Chain = Res;
739   } else {
740     InVals.push_back(Res);
741     Chain = Res.getValue(1);
742   }
743 
744   return Chain;
745 }
746 
747 bool WebAssemblyTargetLowering::CanLowerReturn(
748     CallingConv::ID /*CallConv*/, MachineFunction & /*MF*/, bool /*IsVarArg*/,
749     const SmallVectorImpl<ISD::OutputArg> &Outs,
750     LLVMContext & /*Context*/) const {
751   // WebAssembly can't currently handle returning tuples.
752   return Outs.size() <= 1;
753 }
754 
755 SDValue WebAssemblyTargetLowering::LowerReturn(
756     SDValue Chain, CallingConv::ID CallConv, bool /*IsVarArg*/,
757     const SmallVectorImpl<ISD::OutputArg> &Outs,
758     const SmallVectorImpl<SDValue> &OutVals, const SDLoc &DL,
759     SelectionDAG &DAG) const {
760   assert(Outs.size() <= 1 && "WebAssembly can only return up to one value");
761   if (!CallingConvSupported(CallConv))
762     fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
763 
764   SmallVector<SDValue, 4> RetOps(1, Chain);
765   RetOps.append(OutVals.begin(), OutVals.end());
766   Chain = DAG.getNode(WebAssemblyISD::RETURN, DL, MVT::Other, RetOps);
767 
768   // Record the number and types of the return values.
769   for (const ISD::OutputArg &Out : Outs) {
770     assert(!Out.Flags.isByVal() && "byval is not valid for return values");
771     assert(!Out.Flags.isNest() && "nest is not valid for return values");
772     assert(Out.IsFixed && "non-fixed return value is not valid");
773     if (Out.Flags.isInAlloca())
774       fail(DL, DAG, "WebAssembly hasn't implemented inalloca results");
775     if (Out.Flags.isInConsecutiveRegs())
776       fail(DL, DAG, "WebAssembly hasn't implemented cons regs results");
777     if (Out.Flags.isInConsecutiveRegsLast())
778       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last results");
779   }
780 
781   return Chain;
782 }
783 
784 SDValue WebAssemblyTargetLowering::LowerFormalArguments(
785     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
786     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
787     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
788   if (!CallingConvSupported(CallConv))
789     fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
790 
791   MachineFunction &MF = DAG.getMachineFunction();
792   auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>();
793 
794   // Set up the incoming ARGUMENTS value, which serves to represent the liveness
795   // of the incoming values before they're represented by virtual registers.
796   MF.getRegInfo().addLiveIn(WebAssembly::ARGUMENTS);
797 
798   for (const ISD::InputArg &In : Ins) {
799     if (In.Flags.isInAlloca())
800       fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
801     if (In.Flags.isNest())
802       fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
803     if (In.Flags.isInConsecutiveRegs())
804       fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
805     if (In.Flags.isInConsecutiveRegsLast())
806       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
807     // Ignore In.getOrigAlign() because all our arguments are passed in
808     // registers.
809     InVals.push_back(In.Used ? DAG.getNode(WebAssemblyISD::ARGUMENT, DL, In.VT,
810                                            DAG.getTargetConstant(InVals.size(),
811                                                                  DL, MVT::i32))
812                              : DAG.getUNDEF(In.VT));
813 
814     // Record the number and types of arguments.
815     MFI->addParam(In.VT);
816   }
817 
818   // Varargs are copied into a buffer allocated by the caller, and a pointer to
819   // the buffer is passed as an argument.
820   if (IsVarArg) {
821     MVT PtrVT = getPointerTy(MF.getDataLayout());
822     unsigned VarargVreg =
823         MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrVT));
824     MFI->setVarargBufferVreg(VarargVreg);
825     Chain = DAG.getCopyToReg(
826         Chain, DL, VarargVreg,
827         DAG.getNode(WebAssemblyISD::ARGUMENT, DL, PtrVT,
828                     DAG.getTargetConstant(Ins.size(), DL, MVT::i32)));
829     MFI->addParam(PtrVT);
830   }
831 
832   // Record the number and types of arguments and results.
833   SmallVector<MVT, 4> Params;
834   SmallVector<MVT, 4> Results;
835   ComputeSignatureVTs(MF.getFunction().getFunctionType(), MF.getFunction(),
836                       DAG.getTarget(), Params, Results);
837   for (MVT VT : Results)
838     MFI->addResult(VT);
839   // TODO: Use signatures in WebAssemblyMachineFunctionInfo too and unify
840   // the param logic here with ComputeSignatureVTs
841   assert(MFI->getParams().size() == Params.size() &&
842          std::equal(MFI->getParams().begin(), MFI->getParams().end(),
843                     Params.begin()));
844 
845   return Chain;
846 }
847 
848 //===----------------------------------------------------------------------===//
849 //  Custom lowering hooks.
850 //===----------------------------------------------------------------------===//
851 
852 SDValue WebAssemblyTargetLowering::LowerOperation(SDValue Op,
853                                                   SelectionDAG &DAG) const {
854   SDLoc DL(Op);
855   switch (Op.getOpcode()) {
856   default:
857     llvm_unreachable("unimplemented operation lowering");
858     return SDValue();
859   case ISD::FrameIndex:
860     return LowerFrameIndex(Op, DAG);
861   case ISD::GlobalAddress:
862     return LowerGlobalAddress(Op, DAG);
863   case ISD::ExternalSymbol:
864     return LowerExternalSymbol(Op, DAG);
865   case ISD::JumpTable:
866     return LowerJumpTable(Op, DAG);
867   case ISD::BR_JT:
868     return LowerBR_JT(Op, DAG);
869   case ISD::VASTART:
870     return LowerVASTART(Op, DAG);
871   case ISD::BlockAddress:
872   case ISD::BRIND:
873     fail(DL, DAG, "WebAssembly hasn't implemented computed gotos");
874     return SDValue();
875   case ISD::RETURNADDR: // Probably nothing meaningful can be returned here.
876     fail(DL, DAG, "WebAssembly hasn't implemented __builtin_return_address");
877     return SDValue();
878   case ISD::FRAMEADDR:
879     return LowerFRAMEADDR(Op, DAG);
880   case ISD::CopyToReg:
881     return LowerCopyToReg(Op, DAG);
882   case ISD::INTRINSIC_WO_CHAIN:
883     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
884   case ISD::EXTRACT_VECTOR_ELT:
885   case ISD::INSERT_VECTOR_ELT:
886     return LowerAccessVectorElement(Op, DAG);
887   case ISD::INTRINSIC_VOID:
888     return LowerINTRINSIC_VOID(Op, DAG);
889   case ISD::VECTOR_SHUFFLE:
890     return LowerVECTOR_SHUFFLE(Op, DAG);
891   case ISD::SHL:
892   case ISD::SRA:
893   case ISD::SRL:
894     return LowerShift(Op, DAG);
895   }
896 }
897 
898 SDValue WebAssemblyTargetLowering::LowerCopyToReg(SDValue Op,
899                                                   SelectionDAG &DAG) const {
900   SDValue Src = Op.getOperand(2);
901   if (isa<FrameIndexSDNode>(Src.getNode())) {
902     // CopyToReg nodes don't support FrameIndex operands. Other targets select
903     // the FI to some LEA-like instruction, but since we don't have that, we
904     // need to insert some kind of instruction that can take an FI operand and
905     // produces a value usable by CopyToReg (i.e. in a vreg). So insert a dummy
906     // copy_local between Op and its FI operand.
907     SDValue Chain = Op.getOperand(0);
908     SDLoc DL(Op);
909     unsigned Reg = cast<RegisterSDNode>(Op.getOperand(1))->getReg();
910     EVT VT = Src.getValueType();
911     SDValue Copy(DAG.getMachineNode(VT == MVT::i32 ? WebAssembly::COPY_I32
912                                                    : WebAssembly::COPY_I64,
913                                     DL, VT, Src),
914                  0);
915     return Op.getNode()->getNumValues() == 1
916                ? DAG.getCopyToReg(Chain, DL, Reg, Copy)
917                : DAG.getCopyToReg(Chain, DL, Reg, Copy,
918                                   Op.getNumOperands() == 4 ? Op.getOperand(3)
919                                                            : SDValue());
920   }
921   return SDValue();
922 }
923 
924 SDValue WebAssemblyTargetLowering::LowerFrameIndex(SDValue Op,
925                                                    SelectionDAG &DAG) const {
926   int FI = cast<FrameIndexSDNode>(Op)->getIndex();
927   return DAG.getTargetFrameIndex(FI, Op.getValueType());
928 }
929 
930 SDValue WebAssemblyTargetLowering::LowerFRAMEADDR(SDValue Op,
931                                                   SelectionDAG &DAG) const {
932   // Non-zero depths are not supported by WebAssembly currently. Use the
933   // legalizer's default expansion, which is to return 0 (what this function is
934   // documented to do).
935   if (Op.getConstantOperandVal(0) > 0)
936     return SDValue();
937 
938   DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
939   EVT VT = Op.getValueType();
940   unsigned FP =
941       Subtarget->getRegisterInfo()->getFrameRegister(DAG.getMachineFunction());
942   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), FP, VT);
943 }
944 
945 SDValue WebAssemblyTargetLowering::LowerGlobalAddress(SDValue Op,
946                                                       SelectionDAG &DAG) const {
947   SDLoc DL(Op);
948   const auto *GA = cast<GlobalAddressSDNode>(Op);
949   EVT VT = Op.getValueType();
950   assert(GA->getTargetFlags() == 0 &&
951          "Unexpected target flags on generic GlobalAddressSDNode");
952   if (GA->getAddressSpace() != 0)
953     fail(DL, DAG, "WebAssembly only expects the 0 address space");
954   return DAG.getNode(
955       WebAssemblyISD::Wrapper, DL, VT,
956       DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT, GA->getOffset()));
957 }
958 
959 SDValue
960 WebAssemblyTargetLowering::LowerExternalSymbol(SDValue Op,
961                                                SelectionDAG &DAG) const {
962   SDLoc DL(Op);
963   const auto *ES = cast<ExternalSymbolSDNode>(Op);
964   EVT VT = Op.getValueType();
965   assert(ES->getTargetFlags() == 0 &&
966          "Unexpected target flags on generic ExternalSymbolSDNode");
967   // Set the TargetFlags to 0x1 which indicates that this is a "function"
968   // symbol rather than a data symbol. We do this unconditionally even though
969   // we don't know anything about the symbol other than its name, because all
970   // external symbols used in target-independent SelectionDAG code are for
971   // functions.
972   return DAG.getNode(
973       WebAssemblyISD::Wrapper, DL, VT,
974       DAG.getTargetExternalSymbol(ES->getSymbol(), VT,
975                                   WebAssemblyII::MO_SYMBOL_FUNCTION));
976 }
977 
978 SDValue WebAssemblyTargetLowering::LowerJumpTable(SDValue Op,
979                                                   SelectionDAG &DAG) const {
980   // There's no need for a Wrapper node because we always incorporate a jump
981   // table operand into a BR_TABLE instruction, rather than ever
982   // materializing it in a register.
983   const JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
984   return DAG.getTargetJumpTable(JT->getIndex(), Op.getValueType(),
985                                 JT->getTargetFlags());
986 }
987 
988 SDValue WebAssemblyTargetLowering::LowerBR_JT(SDValue Op,
989                                               SelectionDAG &DAG) const {
990   SDLoc DL(Op);
991   SDValue Chain = Op.getOperand(0);
992   const auto *JT = cast<JumpTableSDNode>(Op.getOperand(1));
993   SDValue Index = Op.getOperand(2);
994   assert(JT->getTargetFlags() == 0 && "WebAssembly doesn't set target flags");
995 
996   SmallVector<SDValue, 8> Ops;
997   Ops.push_back(Chain);
998   Ops.push_back(Index);
999 
1000   MachineJumpTableInfo *MJTI = DAG.getMachineFunction().getJumpTableInfo();
1001   const auto &MBBs = MJTI->getJumpTables()[JT->getIndex()].MBBs;
1002 
1003   // Add an operand for each case.
1004   for (auto MBB : MBBs)
1005     Ops.push_back(DAG.getBasicBlock(MBB));
1006 
1007   // TODO: For now, we just pick something arbitrary for a default case for now.
1008   // We really want to sniff out the guard and put in the real default case (and
1009   // delete the guard).
1010   Ops.push_back(DAG.getBasicBlock(MBBs[0]));
1011 
1012   return DAG.getNode(WebAssemblyISD::BR_TABLE, DL, MVT::Other, Ops);
1013 }
1014 
1015 SDValue WebAssemblyTargetLowering::LowerVASTART(SDValue Op,
1016                                                 SelectionDAG &DAG) const {
1017   SDLoc DL(Op);
1018   EVT PtrVT = getPointerTy(DAG.getMachineFunction().getDataLayout());
1019 
1020   auto *MFI = DAG.getMachineFunction().getInfo<WebAssemblyFunctionInfo>();
1021   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1022 
1023   SDValue ArgN = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1024                                     MFI->getVarargBufferVreg(), PtrVT);
1025   return DAG.getStore(Op.getOperand(0), DL, ArgN, Op.getOperand(1),
1026                       MachinePointerInfo(SV), 0);
1027 }
1028 
1029 SDValue
1030 WebAssemblyTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
1031                                                    SelectionDAG &DAG) const {
1032   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1033   SDLoc DL(Op);
1034   switch (IntNo) {
1035   default:
1036     return {}; // Don't custom lower most intrinsics.
1037 
1038   case Intrinsic::wasm_lsda: {
1039     MachineFunction &MF = DAG.getMachineFunction();
1040     EVT VT = Op.getValueType();
1041     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1042     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
1043     auto &Context = MF.getMMI().getContext();
1044     MCSymbol *S = Context.getOrCreateSymbol(Twine("GCC_except_table") +
1045                                             Twine(MF.getFunctionNumber()));
1046     return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1047                        DAG.getMCSymbol(S, PtrVT));
1048   }
1049   }
1050 }
1051 
1052 SDValue
1053 WebAssemblyTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
1054                                                SelectionDAG &DAG) const {
1055   MachineFunction &MF = DAG.getMachineFunction();
1056   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1057   SDLoc DL(Op);
1058 
1059   switch (IntNo) {
1060   default:
1061     return {}; // Don't custom lower most intrinsics.
1062 
1063   case Intrinsic::wasm_throw: {
1064     int Tag = cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue();
1065     switch (Tag) {
1066     case CPP_EXCEPTION: {
1067       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1068       MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
1069       const char *SymName = MF.createExternalSymbolName("__cpp_exception");
1070       SDValue SymNode =
1071           DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT,
1072                       DAG.getTargetExternalSymbol(
1073                           SymName, PtrVT, WebAssemblyII::MO_SYMBOL_EVENT));
1074       return DAG.getNode(WebAssemblyISD::THROW, DL,
1075                          MVT::Other, // outchain type
1076                          {
1077                              Op.getOperand(0), // inchain
1078                              SymNode,          // exception symbol
1079                              Op.getOperand(3)  // thrown value
1080                          });
1081     }
1082     default:
1083       llvm_unreachable("Invalid tag!");
1084     }
1085     break;
1086   }
1087   }
1088 }
1089 
1090 SDValue
1091 WebAssemblyTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
1092                                                SelectionDAG &DAG) const {
1093   SDLoc DL(Op);
1094   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op.getNode())->getMask();
1095   MVT VecType = Op.getOperand(0).getSimpleValueType();
1096   assert(VecType.is128BitVector() && "Unexpected shuffle vector type");
1097   size_t LaneBytes = VecType.getVectorElementType().getSizeInBits() / 8;
1098 
1099   // Space for two vector args and sixteen mask indices
1100   SDValue Ops[18];
1101   size_t OpIdx = 0;
1102   Ops[OpIdx++] = Op.getOperand(0);
1103   Ops[OpIdx++] = Op.getOperand(1);
1104 
1105   // Expand mask indices to byte indices and materialize them as operands
1106   for (size_t I = 0, Lanes = Mask.size(); I < Lanes; ++I) {
1107     for (size_t J = 0; J < LaneBytes; ++J) {
1108       // Lower undefs (represented by -1 in mask) to zero
1109       uint64_t ByteIndex =
1110           Mask[I] == -1 ? 0 : (uint64_t)Mask[I] * LaneBytes + J;
1111       Ops[OpIdx++] = DAG.getConstant(ByteIndex, DL, MVT::i32);
1112     }
1113   }
1114 
1115   return DAG.getNode(WebAssemblyISD::SHUFFLE, DL, Op.getValueType(), Ops);
1116 }
1117 
1118 SDValue
1119 WebAssemblyTargetLowering::LowerAccessVectorElement(SDValue Op,
1120                                                     SelectionDAG &DAG) const {
1121   // Allow constant lane indices, expand variable lane indices
1122   SDNode *IdxNode = Op.getOperand(Op.getNumOperands() - 1).getNode();
1123   if (isa<ConstantSDNode>(IdxNode) || IdxNode->isUndef())
1124     return Op;
1125   else
1126     // Perform default expansion
1127     return SDValue();
1128 }
1129 
1130 SDValue WebAssemblyTargetLowering::LowerShift(SDValue Op,
1131                                               SelectionDAG &DAG) const {
1132   SDLoc DL(Op);
1133 
1134   // Only manually lower vector shifts
1135   assert(Op.getSimpleValueType().isVector());
1136 
1137   // Unroll non-splat vector shifts
1138   BuildVectorSDNode *ShiftVec;
1139   SDValue SplatVal;
1140   if (!(ShiftVec = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode())) ||
1141       !(SplatVal = ShiftVec->getSplatValue()))
1142     return DAG.UnrollVectorOp(Op.getNode());
1143 
1144   // All splats except i64x2 const splats are handled by patterns
1145   ConstantSDNode *SplatConst = dyn_cast<ConstantSDNode>(SplatVal);
1146   if (!SplatConst || Op.getSimpleValueType() != MVT::v2i64)
1147     return Op;
1148 
1149   // i64x2 const splats are custom lowered to avoid unnecessary wraps
1150   unsigned Opcode;
1151   switch (Op.getOpcode()) {
1152   case ISD::SHL:
1153     Opcode = WebAssemblyISD::VEC_SHL;
1154     break;
1155   case ISD::SRA:
1156     Opcode = WebAssemblyISD::VEC_SHR_S;
1157     break;
1158   case ISD::SRL:
1159     Opcode = WebAssemblyISD::VEC_SHR_U;
1160     break;
1161   default:
1162     llvm_unreachable("unexpected opcode");
1163   }
1164   APInt Shift = SplatConst->getAPIntValue().zextOrTrunc(32);
1165   return DAG.getNode(Opcode, DL, Op.getValueType(), Op.getOperand(0),
1166                      DAG.getConstant(Shift, DL, MVT::i32));
1167 }
1168 
1169 //===----------------------------------------------------------------------===//
1170 //                          WebAssembly Optimization Hooks
1171 //===----------------------------------------------------------------------===//
1172