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