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 /// \brief 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/MachineJumpTableInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/SelectionDAG.h"
25 #include "llvm/IR/DiagnosticInfo.h"
26 #include "llvm/IR/DiagnosticPrinter.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Target/TargetOptions.h"
33 using namespace llvm;
34 
35 #define DEBUG_TYPE "wasm-lower"
36 
37 WebAssemblyTargetLowering::WebAssemblyTargetLowering(
38     const TargetMachine &TM, const WebAssemblySubtarget &STI)
39     : TargetLowering(TM), Subtarget(&STI) {
40   auto MVTPtr = Subtarget->hasAddr64() ? MVT::i64 : MVT::i32;
41 
42   // Booleans always contain 0 or 1.
43   setBooleanContents(ZeroOrOneBooleanContent);
44   // WebAssembly does not produce floating-point exceptions on normal floating
45   // point operations.
46   setHasFloatingPointExceptions(false);
47   // We don't know the microarchitecture here, so just reduce register pressure.
48   setSchedulingPreference(Sched::RegPressure);
49   // Tell ISel that we have a stack pointer.
50   setStackPointerRegisterToSaveRestore(
51       Subtarget->hasAddr64() ? WebAssembly::SP64 : WebAssembly::SP32);
52   // Set up the register classes.
53   addRegisterClass(MVT::i32, &WebAssembly::I32RegClass);
54   addRegisterClass(MVT::i64, &WebAssembly::I64RegClass);
55   addRegisterClass(MVT::f32, &WebAssembly::F32RegClass);
56   addRegisterClass(MVT::f64, &WebAssembly::F64RegClass);
57   // Compute derived properties from the register classes.
58   computeRegisterProperties(Subtarget->getRegisterInfo());
59 
60   setOperationAction(ISD::GlobalAddress, MVTPtr, Custom);
61   setOperationAction(ISD::ExternalSymbol, MVTPtr, Custom);
62   setOperationAction(ISD::JumpTable, MVTPtr, Custom);
63   setOperationAction(ISD::BlockAddress, MVTPtr, Custom);
64   setOperationAction(ISD::BRIND, MVT::Other, Custom);
65 
66   // Take the default expansion for va_arg, va_copy, and va_end. There is no
67   // default action for va_start, so we do that custom.
68   setOperationAction(ISD::VASTART, MVT::Other, Custom);
69   setOperationAction(ISD::VAARG, MVT::Other, Expand);
70   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
71   setOperationAction(ISD::VAEND, MVT::Other, Expand);
72 
73   for (auto T : {MVT::f32, MVT::f64}) {
74     // Don't expand the floating-point types to constant pools.
75     setOperationAction(ISD::ConstantFP, T, Legal);
76     // Expand floating-point comparisons.
77     for (auto CC : {ISD::SETO, ISD::SETUO, ISD::SETUEQ, ISD::SETONE,
78                     ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE})
79       setCondCodeAction(CC, T, Expand);
80     // Expand floating-point library function operators.
81     for (auto Op : {ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOWI, ISD::FPOW,
82                     ISD::FREM, ISD::FMA})
83       setOperationAction(Op, T, Expand);
84     // Note supported floating-point library function operators that otherwise
85     // default to expand.
86     for (auto Op :
87          {ISD::FCEIL, ISD::FFLOOR, ISD::FTRUNC, ISD::FNEARBYINT, ISD::FRINT})
88       setOperationAction(Op, T, Legal);
89     // Support minnan and maxnan, which otherwise default to expand.
90     setOperationAction(ISD::FMINNAN, T, Legal);
91     setOperationAction(ISD::FMAXNAN, T, Legal);
92   }
93 
94   for (auto T : {MVT::i32, MVT::i64}) {
95     // Expand unavailable integer operations.
96     for (auto Op :
97          {ISD::BSWAP, ISD::SMUL_LOHI, ISD::UMUL_LOHI,
98           ISD::MULHS, ISD::MULHU, ISD::SDIVREM, ISD::UDIVREM, ISD::SHL_PARTS,
99           ISD::SRA_PARTS, ISD::SRL_PARTS, ISD::ADDC, ISD::ADDE, ISD::SUBC,
100           ISD::SUBE}) {
101       setOperationAction(Op, T, Expand);
102     }
103   }
104 
105   // As a special case, these operators use the type to mean the type to
106   // sign-extend from.
107   for (auto T : {MVT::i1, MVT::i8, MVT::i16, MVT::i32})
108     setOperationAction(ISD::SIGN_EXTEND_INREG, T, Expand);
109 
110   // Dynamic stack allocation: use the default expansion.
111   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
112   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
113   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVTPtr, Expand);
114 
115   setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
116   setOperationAction(ISD::CopyToReg, MVT::Other, Custom);
117 
118   // Expand these forms; we pattern-match the forms that we can handle in isel.
119   for (auto T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64})
120     for (auto Op : {ISD::BR_CC, ISD::SELECT_CC})
121       setOperationAction(Op, T, Expand);
122 
123   // We have custom switch handling.
124   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
125 
126   // WebAssembly doesn't have:
127   //  - Floating-point extending loads.
128   //  - Floating-point truncating stores.
129   //  - i1 extending loads.
130   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
131   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
132   for (auto T : MVT::integer_valuetypes())
133     for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD})
134       setLoadExtAction(Ext, T, MVT::i1, Promote);
135 
136   // Trap lowers to wasm unreachable
137   setOperationAction(ISD::TRAP, MVT::Other, Legal);
138 
139   // Disable 128-bit shift libcalls. Currently the signature of the functions
140   // i128(i128, i32) aka void(i32, i64, i64, i32) doesn't match the signature
141   // of the call emitted by the default lowering, void(i32, i64, i64).
142   setLibcallName(RTLIB::SRL_I128, nullptr);
143   setLibcallName(RTLIB::SRA_I128, nullptr);
144   setLibcallName(RTLIB::SHL_I128, nullptr);
145 }
146 
147 FastISel *WebAssemblyTargetLowering::createFastISel(
148     FunctionLoweringInfo &FuncInfo, const TargetLibraryInfo *LibInfo) const {
149   return WebAssembly::createFastISel(FuncInfo, LibInfo);
150 }
151 
152 bool WebAssemblyTargetLowering::isOffsetFoldingLegal(
153     const GlobalAddressSDNode * /*GA*/) const {
154   // All offsets can be folded.
155   return true;
156 }
157 
158 MVT WebAssemblyTargetLowering::getScalarShiftAmountTy(const DataLayout & /*DL*/,
159                                                       EVT VT) const {
160   unsigned BitWidth = NextPowerOf2(VT.getSizeInBits() - 1);
161   if (BitWidth > 1 && BitWidth < 8) BitWidth = 8;
162 
163   if (BitWidth > 64) {
164     BitWidth = 64;
165     assert(BitWidth >= Log2_32_Ceil(VT.getSizeInBits()) &&
166            "64-bit shift counts ought to be enough for anyone");
167   }
168 
169   MVT Result = MVT::getIntegerVT(BitWidth);
170   assert(Result != MVT::INVALID_SIMPLE_VALUE_TYPE &&
171          "Unable to represent scalar shift amount type");
172   return Result;
173 }
174 
175 const char *WebAssemblyTargetLowering::getTargetNodeName(
176     unsigned Opcode) const {
177   switch (static_cast<WebAssemblyISD::NodeType>(Opcode)) {
178     case WebAssemblyISD::FIRST_NUMBER:
179       break;
180 #define HANDLE_NODETYPE(NODE) \
181   case WebAssemblyISD::NODE:  \
182     return "WebAssemblyISD::" #NODE;
183 #include "WebAssemblyISD.def"
184 #undef HANDLE_NODETYPE
185   }
186   return nullptr;
187 }
188 
189 std::pair<unsigned, const TargetRegisterClass *>
190 WebAssemblyTargetLowering::getRegForInlineAsmConstraint(
191     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
192   // First, see if this is a constraint that directly corresponds to a
193   // WebAssembly register class.
194   if (Constraint.size() == 1) {
195     switch (Constraint[0]) {
196       case 'r':
197         assert(VT != MVT::iPTR && "Pointer MVT not expected here");
198         if (VT.isInteger() && !VT.isVector()) {
199           if (VT.getSizeInBits() <= 32)
200             return std::make_pair(0U, &WebAssembly::I32RegClass);
201           if (VT.getSizeInBits() <= 64)
202             return std::make_pair(0U, &WebAssembly::I64RegClass);
203         }
204         break;
205       default:
206         break;
207     }
208   }
209 
210   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
211 }
212 
213 bool WebAssemblyTargetLowering::isCheapToSpeculateCttz() const {
214   // Assume ctz is a relatively cheap operation.
215   return true;
216 }
217 
218 bool WebAssemblyTargetLowering::isCheapToSpeculateCtlz() const {
219   // Assume clz is a relatively cheap operation.
220   return true;
221 }
222 
223 bool WebAssemblyTargetLowering::isLegalAddressingMode(const DataLayout &DL,
224                                                       const AddrMode &AM,
225                                                       Type *Ty,
226                                                       unsigned AS) const {
227   // WebAssembly offsets are added as unsigned without wrapping. The
228   // isLegalAddressingMode gives us no way to determine if wrapping could be
229   // happening, so we approximate this by accepting only non-negative offsets.
230   if (AM.BaseOffs < 0) return false;
231 
232   // WebAssembly has no scale register operands.
233   if (AM.Scale != 0) return false;
234 
235   // Everything else is legal.
236   return true;
237 }
238 
239 bool WebAssemblyTargetLowering::allowsMisalignedMemoryAccesses(
240     EVT /*VT*/, unsigned /*AddrSpace*/, unsigned /*Align*/, bool *Fast) const {
241   // WebAssembly supports unaligned accesses, though it should be declared
242   // with the p2align attribute on loads and stores which do so, and there
243   // may be a performance impact. We tell LLVM they're "fast" because
244   // for the kinds of things that LLVM uses this for (merging adjacent stores
245   // of constants, etc.), WebAssembly implementations will either want the
246   // unaligned access or they'll split anyway.
247   if (Fast) *Fast = true;
248   return true;
249 }
250 
251 //===----------------------------------------------------------------------===//
252 // WebAssembly Lowering private implementation.
253 //===----------------------------------------------------------------------===//
254 
255 //===----------------------------------------------------------------------===//
256 // Lowering Code
257 //===----------------------------------------------------------------------===//
258 
259 static void fail(SDLoc DL, SelectionDAG &DAG, const char *msg) {
260   MachineFunction &MF = DAG.getMachineFunction();
261   DAG.getContext()->diagnose(
262       DiagnosticInfoUnsupported(*MF.getFunction(), msg, DL.getDebugLoc()));
263 }
264 
265 // Test whether the given calling convention is supported.
266 static bool CallingConvSupported(CallingConv::ID CallConv) {
267   // We currently support the language-independent target-independent
268   // conventions. We don't yet have a way to annotate calls with properties like
269   // "cold", and we don't have any call-clobbered registers, so these are mostly
270   // all handled the same.
271   return CallConv == CallingConv::C || CallConv == CallingConv::Fast ||
272          CallConv == CallingConv::Cold ||
273          CallConv == CallingConv::PreserveMost ||
274          CallConv == CallingConv::PreserveAll ||
275          CallConv == CallingConv::CXX_FAST_TLS;
276 }
277 
278 SDValue WebAssemblyTargetLowering::LowerCall(
279     CallLoweringInfo &CLI, SmallVectorImpl<SDValue> &InVals) const {
280   SelectionDAG &DAG = CLI.DAG;
281   SDLoc DL = CLI.DL;
282   SDValue Chain = CLI.Chain;
283   SDValue Callee = CLI.Callee;
284   MachineFunction &MF = DAG.getMachineFunction();
285   auto Layout = MF.getDataLayout();
286 
287   CallingConv::ID CallConv = CLI.CallConv;
288   if (!CallingConvSupported(CallConv))
289     fail(DL, DAG,
290          "WebAssembly doesn't support language-specific or target-specific "
291          "calling conventions yet");
292   if (CLI.IsPatchPoint)
293     fail(DL, DAG, "WebAssembly doesn't support patch point yet");
294 
295   // WebAssembly doesn't currently support explicit tail calls. If they are
296   // required, fail. Otherwise, just disable them.
297   if ((CallConv == CallingConv::Fast && CLI.IsTailCall &&
298        MF.getTarget().Options.GuaranteedTailCallOpt) ||
299       (CLI.CS && CLI.CS->isMustTailCall()))
300     fail(DL, DAG, "WebAssembly doesn't support tail call yet");
301   CLI.IsTailCall = false;
302 
303   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
304   if (Ins.size() > 1)
305     fail(DL, DAG, "WebAssembly doesn't support more than 1 returned value yet");
306 
307   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
308   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
309   for (unsigned i = 0; i < Outs.size(); ++i) {
310     const ISD::OutputArg &Out = Outs[i];
311     SDValue &OutVal = OutVals[i];
312     if (Out.Flags.isNest())
313       fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
314     if (Out.Flags.isInAlloca())
315       fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
316     if (Out.Flags.isInConsecutiveRegs())
317       fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
318     if (Out.Flags.isInConsecutiveRegsLast())
319       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
320     if (Out.Flags.isByVal() && Out.Flags.getByValSize() != 0) {
321       auto *MFI = MF.getFrameInfo();
322       int FI = MFI->CreateStackObject(Out.Flags.getByValSize(),
323                                       Out.Flags.getByValAlign(),
324                                       /*isSS=*/false);
325       SDValue SizeNode =
326           DAG.getConstant(Out.Flags.getByValSize(), DL, MVT::i32);
327       SDValue FINode = DAG.getFrameIndex(FI, getPointerTy(Layout));
328       Chain = DAG.getMemcpy(
329           Chain, DL, FINode, OutVal, SizeNode, Out.Flags.getByValAlign(),
330           /*isVolatile*/ false, /*AlwaysInline=*/false,
331           /*isTailCall*/ false, MachinePointerInfo(), MachinePointerInfo());
332       OutVal = FINode;
333     }
334   }
335 
336   bool IsVarArg = CLI.IsVarArg;
337   unsigned NumFixedArgs = CLI.NumFixedArgs;
338 
339   auto PtrVT = getPointerTy(Layout);
340 
341   // Analyze operands of the call, assigning locations to each operand.
342   SmallVector<CCValAssign, 16> ArgLocs;
343   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
344 
345   if (IsVarArg) {
346     // Outgoing non-fixed arguments are placed in a buffer. First
347     // compute their offsets and the total amount of buffer space needed.
348     for (SDValue Arg :
349          make_range(OutVals.begin() + NumFixedArgs, OutVals.end())) {
350       EVT VT = Arg.getValueType();
351       assert(VT != MVT::iPTR && "Legalized args should be concrete");
352       Type *Ty = VT.getTypeForEVT(*DAG.getContext());
353       unsigned Offset = CCInfo.AllocateStack(Layout.getTypeAllocSize(Ty),
354                                              Layout.getABITypeAlignment(Ty));
355       CCInfo.addLoc(CCValAssign::getMem(ArgLocs.size(), VT.getSimpleVT(),
356                                         Offset, VT.getSimpleVT(),
357                                         CCValAssign::Full));
358     }
359   }
360 
361   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
362 
363   SDValue FINode;
364   if (IsVarArg && NumBytes) {
365     // For non-fixed arguments, next emit stores to store the argument values
366     // to the stack buffer at the offsets computed above.
367     int FI = MF.getFrameInfo()->CreateStackObject(NumBytes,
368                                                   Layout.getStackAlignment(),
369                                                   /*isSS=*/false);
370     unsigned ValNo = 0;
371     SmallVector<SDValue, 8> Chains;
372     for (SDValue Arg :
373          make_range(OutVals.begin() + NumFixedArgs, OutVals.end())) {
374       assert(ArgLocs[ValNo].getValNo() == ValNo &&
375              "ArgLocs should remain in order and only hold varargs args");
376       unsigned Offset = ArgLocs[ValNo++].getLocMemOffset();
377       FINode = DAG.getFrameIndex(FI, getPointerTy(Layout));
378       SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, FINode,
379                                 DAG.getConstant(Offset, DL, PtrVT));
380       Chains.push_back(DAG.getStore(
381           Chain, DL, Arg, Add,
382           MachinePointerInfo::getFixedStack(MF, FI, Offset), false, false, 0));
383     }
384     if (!Chains.empty())
385       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
386   } else if (IsVarArg) {
387     FINode = DAG.getIntPtrConstant(0, DL);
388   }
389 
390   // Compute the operands for the CALLn node.
391   SmallVector<SDValue, 16> Ops;
392   Ops.push_back(Chain);
393   Ops.push_back(Callee);
394 
395   // Add all fixed arguments. Note that for non-varargs calls, NumFixedArgs
396   // isn't reliable.
397   Ops.append(OutVals.begin(),
398              IsVarArg ? OutVals.begin() + NumFixedArgs : OutVals.end());
399   // Add a pointer to the vararg buffer.
400   if (IsVarArg) Ops.push_back(FINode);
401 
402   SmallVector<EVT, 8> InTys;
403   for (const auto &In : Ins) {
404     assert(!In.Flags.isByVal() && "byval is not valid for return values");
405     assert(!In.Flags.isNest() && "nest is not valid for return values");
406     if (In.Flags.isInAlloca())
407       fail(DL, DAG, "WebAssembly hasn't implemented inalloca return values");
408     if (In.Flags.isInConsecutiveRegs())
409       fail(DL, DAG, "WebAssembly hasn't implemented cons regs return values");
410     if (In.Flags.isInConsecutiveRegsLast())
411       fail(DL, DAG,
412            "WebAssembly hasn't implemented cons regs last return values");
413     // Ignore In.getOrigAlign() because all our arguments are passed in
414     // registers.
415     InTys.push_back(In.VT);
416   }
417   InTys.push_back(MVT::Other);
418   SDVTList InTyList = DAG.getVTList(InTys);
419   SDValue Res =
420       DAG.getNode(Ins.empty() ? WebAssemblyISD::CALL0 : WebAssemblyISD::CALL1,
421                   DL, InTyList, Ops);
422   if (Ins.empty()) {
423     Chain = Res;
424   } else {
425     InVals.push_back(Res);
426     Chain = Res.getValue(1);
427   }
428 
429   return Chain;
430 }
431 
432 bool WebAssemblyTargetLowering::CanLowerReturn(
433     CallingConv::ID /*CallConv*/, MachineFunction & /*MF*/, bool /*IsVarArg*/,
434     const SmallVectorImpl<ISD::OutputArg> &Outs,
435     LLVMContext & /*Context*/) const {
436   // WebAssembly can't currently handle returning tuples.
437   return Outs.size() <= 1;
438 }
439 
440 SDValue WebAssemblyTargetLowering::LowerReturn(
441     SDValue Chain, CallingConv::ID CallConv, bool /*IsVarArg*/,
442     const SmallVectorImpl<ISD::OutputArg> &Outs,
443     const SmallVectorImpl<SDValue> &OutVals, SDLoc DL,
444     SelectionDAG &DAG) const {
445   assert(Outs.size() <= 1 && "WebAssembly can only return up to one value");
446   if (!CallingConvSupported(CallConv))
447     fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
448 
449   SmallVector<SDValue, 4> RetOps(1, Chain);
450   RetOps.append(OutVals.begin(), OutVals.end());
451   Chain = DAG.getNode(WebAssemblyISD::RETURN, DL, MVT::Other, RetOps);
452 
453   // Record the number and types of the return values.
454   for (const ISD::OutputArg &Out : Outs) {
455     assert(!Out.Flags.isByVal() && "byval is not valid for return values");
456     assert(!Out.Flags.isNest() && "nest is not valid for return values");
457     assert(Out.IsFixed && "non-fixed return value is not valid");
458     if (Out.Flags.isInAlloca())
459       fail(DL, DAG, "WebAssembly hasn't implemented inalloca results");
460     if (Out.Flags.isInConsecutiveRegs())
461       fail(DL, DAG, "WebAssembly hasn't implemented cons regs results");
462     if (Out.Flags.isInConsecutiveRegsLast())
463       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last results");
464   }
465 
466   return Chain;
467 }
468 
469 SDValue WebAssemblyTargetLowering::LowerFormalArguments(
470     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
471     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
472     SmallVectorImpl<SDValue> &InVals) const {
473   MachineFunction &MF = DAG.getMachineFunction();
474   auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>();
475 
476   if (!CallingConvSupported(CallConv))
477     fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
478 
479   // Set up the incoming ARGUMENTS value, which serves to represent the liveness
480   // of the incoming values before they're represented by virtual registers.
481   MF.getRegInfo().addLiveIn(WebAssembly::ARGUMENTS);
482 
483   for (const ISD::InputArg &In : Ins) {
484     if (In.Flags.isInAlloca())
485       fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
486     if (In.Flags.isNest())
487       fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
488     if (In.Flags.isInConsecutiveRegs())
489       fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
490     if (In.Flags.isInConsecutiveRegsLast())
491       fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
492     // Ignore In.getOrigAlign() because all our arguments are passed in
493     // registers.
494     InVals.push_back(
495         In.Used
496             ? DAG.getNode(WebAssemblyISD::ARGUMENT, DL, In.VT,
497                           DAG.getTargetConstant(InVals.size(), DL, MVT::i32))
498             : DAG.getUNDEF(In.VT));
499 
500     // Record the number and types of arguments.
501     MFI->addParam(In.VT);
502   }
503 
504   // Varargs are copied into a buffer allocated by the caller, and a pointer to
505   // the buffer is passed as an argument.
506   if (IsVarArg) {
507     MVT PtrVT = getPointerTy(MF.getDataLayout());
508     unsigned VarargVreg =
509         MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrVT));
510     MFI->setVarargBufferVreg(VarargVreg);
511     Chain = DAG.getCopyToReg(
512         Chain, DL, VarargVreg,
513         DAG.getNode(WebAssemblyISD::ARGUMENT, DL, PtrVT,
514                     DAG.getTargetConstant(Ins.size(), DL, MVT::i32)));
515     MFI->addParam(PtrVT);
516   }
517 
518   return Chain;
519 }
520 
521 //===----------------------------------------------------------------------===//
522 //  Custom lowering hooks.
523 //===----------------------------------------------------------------------===//
524 
525 SDValue WebAssemblyTargetLowering::LowerOperation(SDValue Op,
526                                                   SelectionDAG &DAG) const {
527   SDLoc DL(Op);
528   switch (Op.getOpcode()) {
529     default:
530       llvm_unreachable("unimplemented operation lowering");
531       return SDValue();
532     case ISD::FrameIndex:
533       return LowerFrameIndex(Op, DAG);
534     case ISD::GlobalAddress:
535       return LowerGlobalAddress(Op, DAG);
536     case ISD::ExternalSymbol:
537       return LowerExternalSymbol(Op, DAG);
538     case ISD::JumpTable:
539       return LowerJumpTable(Op, DAG);
540     case ISD::BR_JT:
541       return LowerBR_JT(Op, DAG);
542     case ISD::VASTART:
543       return LowerVASTART(Op, DAG);
544     case ISD::BlockAddress:
545     case ISD::BRIND:
546       fail(DL, DAG, "WebAssembly hasn't implemented computed gotos");
547       return SDValue();
548     case ISD::RETURNADDR: // Probably nothing meaningful can be returned here.
549       fail(DL, DAG, "WebAssembly hasn't implemented __builtin_return_address");
550       return SDValue();
551     case ISD::FRAMEADDR:
552       return LowerFRAMEADDR(Op, DAG);
553     case ISD::CopyToReg:
554       return LowerCopyToReg(Op, DAG);
555   }
556 }
557 
558 SDValue WebAssemblyTargetLowering::LowerCopyToReg(SDValue Op,
559                                                   SelectionDAG &DAG) const {
560   SDValue Src = Op.getOperand(2);
561   if (isa<FrameIndexSDNode>(Src.getNode())) {
562     // CopyToReg nodes don't support FrameIndex operands. Other targets select
563     // the FI to some LEA-like instruction, but since we don't have that, we
564     // need to insert some kind of instruction that can take an FI operand and
565     // produces a value usable by CopyToReg (i.e. in a vreg). So insert a dummy
566     // copy_local between Op and its FI operand.
567     SDValue Chain = Op.getOperand(0);
568     SDLoc DL(Op);
569     unsigned Reg = cast<RegisterSDNode>(Op.getOperand(1))->getReg();
570     EVT VT = Src.getValueType();
571     SDValue Copy(
572         DAG.getMachineNode(VT == MVT::i32 ? WebAssembly::COPY_LOCAL_I32
573                                           : WebAssembly::COPY_LOCAL_I64,
574                            DL, VT, Src),
575         0);
576     return Op.getNode()->getNumValues() == 1
577                ? DAG.getCopyToReg(Chain, DL, Reg, Copy)
578                : DAG.getCopyToReg(Chain, DL, Reg, Copy, Op.getNumOperands() == 4
579                                                             ? Op.getOperand(3)
580                                                             : SDValue());
581   }
582   return SDValue();
583 }
584 
585 SDValue WebAssemblyTargetLowering::LowerFrameIndex(SDValue Op,
586                                                    SelectionDAG &DAG) const {
587   int FI = cast<FrameIndexSDNode>(Op)->getIndex();
588   return DAG.getTargetFrameIndex(FI, Op.getValueType());
589 }
590 
591 SDValue WebAssemblyTargetLowering::LowerFRAMEADDR(SDValue Op,
592                                                   SelectionDAG &DAG) const {
593   // Non-zero depths are not supported by WebAssembly currently. Use the
594   // legalizer's default expansion, which is to return 0 (what this function is
595   // documented to do).
596   if (Op.getConstantOperandVal(0) > 0)
597     return SDValue();
598 
599   DAG.getMachineFunction().getFrameInfo()->setFrameAddressIsTaken(true);
600   EVT VT = Op.getValueType();
601   unsigned FP =
602       Subtarget->getRegisterInfo()->getFrameRegister(DAG.getMachineFunction());
603   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), FP, VT);
604 }
605 
606 SDValue WebAssemblyTargetLowering::LowerGlobalAddress(SDValue Op,
607                                                       SelectionDAG &DAG) const {
608   SDLoc DL(Op);
609   const auto *GA = cast<GlobalAddressSDNode>(Op);
610   EVT VT = Op.getValueType();
611   assert(GA->getTargetFlags() == 0 &&
612          "Unexpected target flags on generic GlobalAddressSDNode");
613   if (GA->getAddressSpace() != 0)
614     fail(DL, DAG, "WebAssembly only expects the 0 address space");
615   return DAG.getNode(
616       WebAssemblyISD::Wrapper, DL, VT,
617       DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT, GA->getOffset()));
618 }
619 
620 SDValue WebAssemblyTargetLowering::LowerExternalSymbol(
621     SDValue Op, SelectionDAG &DAG) const {
622   SDLoc DL(Op);
623   const auto *ES = cast<ExternalSymbolSDNode>(Op);
624   EVT VT = Op.getValueType();
625   assert(ES->getTargetFlags() == 0 &&
626          "Unexpected target flags on generic ExternalSymbolSDNode");
627   // Set the TargetFlags to 0x1 which indicates that this is a "function"
628   // symbol rather than a data symbol. We do this unconditionally even though
629   // we don't know anything about the symbol other than its name, because all
630   // external symbols used in target-independent SelectionDAG code are for
631   // functions.
632   return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
633                      DAG.getTargetExternalSymbol(ES->getSymbol(), VT,
634                                                  /*TargetFlags=*/0x1));
635 }
636 
637 SDValue WebAssemblyTargetLowering::LowerJumpTable(SDValue Op,
638                                                   SelectionDAG &DAG) const {
639   // There's no need for a Wrapper node because we always incorporate a jump
640   // table operand into a BR_TABLE instruction, rather than ever
641   // materializing it in a register.
642   const JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
643   return DAG.getTargetJumpTable(JT->getIndex(), Op.getValueType(),
644                                 JT->getTargetFlags());
645 }
646 
647 SDValue WebAssemblyTargetLowering::LowerBR_JT(SDValue Op,
648                                               SelectionDAG &DAG) const {
649   SDLoc DL(Op);
650   SDValue Chain = Op.getOperand(0);
651   const auto *JT = cast<JumpTableSDNode>(Op.getOperand(1));
652   SDValue Index = Op.getOperand(2);
653   assert(JT->getTargetFlags() == 0 && "WebAssembly doesn't set target flags");
654 
655   SmallVector<SDValue, 8> Ops;
656   Ops.push_back(Chain);
657   Ops.push_back(Index);
658 
659   MachineJumpTableInfo *MJTI = DAG.getMachineFunction().getJumpTableInfo();
660   const auto &MBBs = MJTI->getJumpTables()[JT->getIndex()].MBBs;
661 
662   // Add an operand for each case.
663   for (auto MBB : MBBs) Ops.push_back(DAG.getBasicBlock(MBB));
664 
665   // TODO: For now, we just pick something arbitrary for a default case for now.
666   // We really want to sniff out the guard and put in the real default case (and
667   // delete the guard).
668   Ops.push_back(DAG.getBasicBlock(MBBs[0]));
669 
670   return DAG.getNode(WebAssemblyISD::BR_TABLE, DL, MVT::Other, Ops);
671 }
672 
673 SDValue WebAssemblyTargetLowering::LowerVASTART(SDValue Op,
674                                                 SelectionDAG &DAG) const {
675   SDLoc DL(Op);
676   EVT PtrVT = getPointerTy(DAG.getMachineFunction().getDataLayout());
677 
678   auto *MFI = DAG.getMachineFunction().getInfo<WebAssemblyFunctionInfo>();
679   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
680 
681   SDValue ArgN = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
682                                     MFI->getVarargBufferVreg(), PtrVT);
683   return DAG.getStore(Op.getOperand(0), DL, ArgN, Op.getOperand(1),
684                       MachinePointerInfo(SV), false, false, 0);
685 }
686 
687 //===----------------------------------------------------------------------===//
688 //                          WebAssembly Optimization Hooks
689 //===----------------------------------------------------------------------===//
690