1 //=- WebAssemblyISelLowering.cpp - WebAssembly DAG Lowering Implementation -==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief This file implements the WebAssemblyTargetLowering class.
13 //===----------------------------------------------------------------------===//
15 #include "WebAssemblyISelLowering.h"
16 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
17 #include "WebAssemblyMachineFunctionInfo.h"
18 #include "WebAssemblySubtarget.h"
19 #include "WebAssemblyTargetMachine.h"
20 #include "WebAssemblyTargetObjectFile.h"
21 #include "llvm/CodeGen/Analysis.h"
22 #include "llvm/CodeGen/CallingConvLower.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/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetOptions.h"
37 #define DEBUG_TYPE "wasm-lower"
40 // Diagnostic information for unimplemented or unsupported feature reporting.
41 // FIXME copied from BPF and AMDGPU.
42 class DiagnosticInfoUnsupported : public DiagnosticInfo {
44 // Debug location where this diagnostic is triggered.
46 const Twine &Description;
52 static int getKindID() {
54 KindID = llvm::getNextAvailablePluginDiagnosticKind();
59 DiagnosticInfoUnsupported(SDLoc DLoc, const Function &Fn, const Twine &Desc,
61 : DiagnosticInfo(getKindID(), DS_Error), DLoc(DLoc.getDebugLoc()),
62 Description(Desc), Fn(Fn), Value(Value) {}
64 void print(DiagnosticPrinter &DP) const override {
66 raw_string_ostream OS(Str);
69 auto DIL = DLoc.get();
70 StringRef Filename = DIL->getFilename();
71 unsigned Line = DIL->getLine();
72 unsigned Column = DIL->getColumn();
73 OS << Filename << ':' << Line << ':' << Column << ' ';
76 OS << "in function " << Fn.getName() << ' ' << *Fn.getFunctionType() << '\n'
85 static bool classof(const DiagnosticInfo *DI) {
86 return DI->getKind() == getKindID();
90 int DiagnosticInfoUnsupported::KindID = 0;
91 } // end anonymous namespace
93 WebAssemblyTargetLowering::WebAssemblyTargetLowering(
94 const TargetMachine &TM, const WebAssemblySubtarget &STI)
95 : TargetLowering(TM), Subtarget(&STI) {
96 auto MVTPtr = Subtarget->hasAddr64() ? MVT::i64 : MVT::i32;
98 // Booleans always contain 0 or 1.
99 setBooleanContents(ZeroOrOneBooleanContent);
100 // WebAssembly does not produce floating-point exceptions on normal floating
102 setHasFloatingPointExceptions(false);
103 // We don't know the microarchitecture here, so just reduce register pressure.
104 setSchedulingPreference(Sched::RegPressure);
105 // Tell ISel that we have a stack pointer.
106 setStackPointerRegisterToSaveRestore(
107 Subtarget->hasAddr64() ? WebAssembly::SP64 : WebAssembly::SP32);
108 // Set up the register classes.
109 addRegisterClass(MVT::i32, &WebAssembly::Int32RegClass);
110 addRegisterClass(MVT::i64, &WebAssembly::Int64RegClass);
111 addRegisterClass(MVT::f32, &WebAssembly::Float32RegClass);
112 addRegisterClass(MVT::f64, &WebAssembly::Float64RegClass);
113 // Compute derived properties from the register classes.
114 computeRegisterProperties(Subtarget->getRegisterInfo());
116 setOperationAction(ISD::GlobalAddress, MVTPtr, Custom);
118 for (auto T : {MVT::f32, MVT::f64}) {
119 // Don't expand the floating-point types to constant pools.
120 setOperationAction(ISD::ConstantFP, T, Legal);
121 // Expand floating-point comparisons.
122 for (auto CC : {ISD::SETO, ISD::SETUO, ISD::SETUEQ, ISD::SETONE,
123 ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE})
124 setCondCodeAction(CC, T, Expand);
125 // Expand floating-point library function operators.
126 for (auto Op : {ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOWI, ISD::FPOW})
127 setOperationAction(Op, T, Expand);
128 // Note supported floating-point library function operators that otherwise
129 // default to expand.
130 for (auto Op : {ISD::FCEIL, ISD::FFLOOR, ISD::FTRUNC, ISD::FNEARBYINT,
132 setOperationAction(Op, T, Legal);
135 for (auto T : {MVT::i32, MVT::i64}) {
136 // Expand unavailable integer operations.
137 for (auto Op : {ISD::BSWAP, ISD::ROTL, ISD::ROTR,
138 ISD::SMUL_LOHI, ISD::UMUL_LOHI,
139 ISD::MULHS, ISD::MULHU, ISD::SDIVREM, ISD::UDIVREM,
140 ISD::SHL_PARTS, ISD::SRA_PARTS, ISD::SRL_PARTS,
141 ISD::ADDC, ISD::ADDE, ISD::SUBC, ISD::SUBE}) {
142 setOperationAction(Op, T, Expand);
146 // As a special case, these operators use the type to mean the type to
148 for (auto T : {MVT::i1, MVT::i8, MVT::i16})
149 setOperationAction(ISD::SIGN_EXTEND_INREG, T, Expand);
151 // Dynamic stack allocation: use the default expansion.
152 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
153 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
154 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVTPtr, Expand);
156 // WebAssembly doesn't have:
157 // - Floating-point extending loads.
158 // - Floating-point truncating stores.
159 // - i1 extending loads.
160 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f64, Expand);
161 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
162 for (auto T : MVT::integer_valuetypes())
163 for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD})
164 setLoadExtAction(Ext, T, MVT::i1, Promote);
167 FastISel *WebAssemblyTargetLowering::createFastISel(
168 FunctionLoweringInfo &FuncInfo, const TargetLibraryInfo *LibInfo) const {
169 return WebAssembly::createFastISel(FuncInfo, LibInfo);
172 bool WebAssemblyTargetLowering::isOffsetFoldingLegal(
173 const GlobalAddressSDNode *GA) const {
174 // The WebAssembly target doesn't support folding offsets into global
179 MVT WebAssemblyTargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
181 return VT.getSimpleVT();
185 WebAssemblyTargetLowering::getTargetNodeName(unsigned Opcode) const {
186 switch (static_cast<WebAssemblyISD::NodeType>(Opcode)) {
187 case WebAssemblyISD::FIRST_NUMBER:
189 #define HANDLE_NODETYPE(NODE) \
190 case WebAssemblyISD::NODE: \
191 return "WebAssemblyISD::" #NODE;
192 #include "WebAssemblyISD.def"
193 #undef HANDLE_NODETYPE
198 //===----------------------------------------------------------------------===//
199 // WebAssembly Lowering private implementation.
200 //===----------------------------------------------------------------------===//
202 //===----------------------------------------------------------------------===//
204 //===----------------------------------------------------------------------===//
206 static void fail(SDLoc DL, SelectionDAG &DAG, const char *msg) {
207 MachineFunction &MF = DAG.getMachineFunction();
208 DAG.getContext()->diagnose(
209 DiagnosticInfoUnsupported(DL, *MF.getFunction(), msg, SDValue()));
213 WebAssemblyTargetLowering::LowerCall(CallLoweringInfo &CLI,
214 SmallVectorImpl<SDValue> &InVals) const {
215 SelectionDAG &DAG = CLI.DAG;
217 SDValue Chain = CLI.Chain;
218 SDValue Callee = CLI.Callee;
219 MachineFunction &MF = DAG.getMachineFunction();
221 CallingConv::ID CallConv = CLI.CallConv;
222 if (CallConv != CallingConv::C)
223 fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
224 if (CLI.IsTailCall || MF.getTarget().Options.GuaranteedTailCallOpt)
225 fail(DL, DAG, "WebAssembly doesn't support tail call yet");
226 if (CLI.IsPatchPoint)
227 fail(DL, DAG, "WebAssembly doesn't support patch point yet");
229 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
230 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
231 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
233 fail(DL, DAG, "WebAssembly doesn't support struct return yet");
235 fail(DL, DAG, "WebAssembly doesn't support more than 1 returned value yet");
237 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
238 bool IsVarArg = CLI.IsVarArg;
240 fail(DL, DAG, "WebAssembly doesn't support varargs yet");
241 // Analyze operands of the call, assigning locations to each operand.
242 SmallVector<CCValAssign, 16> ArgLocs;
243 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
244 unsigned NumBytes = CCInfo.getNextStackOffset();
246 auto PtrVT = getPointerTy(MF.getDataLayout());
247 auto Zero = DAG.getConstant(0, DL, PtrVT, true);
248 auto NB = DAG.getConstant(NumBytes, DL, PtrVT, true);
249 Chain = DAG.getCALLSEQ_START(Chain, NB, DL);
251 SmallVector<SDValue, 16> Ops;
252 Ops.push_back(Chain);
253 Ops.push_back(Callee);
254 Ops.append(OutVals.begin(), OutVals.end());
256 SmallVector<EVT, 8> Tys;
257 for (const auto &In : Ins)
258 Tys.push_back(In.VT);
259 Tys.push_back(MVT::Other);
260 SDVTList TyList = DAG.getVTList(Tys);
261 SDValue Res = DAG.getNode(WebAssemblyISD::CALL, DL, TyList, Ops);
265 InVals.push_back(Res);
266 Chain = Res.getValue(1);
269 // FIXME: handle CLI.RetSExt and CLI.RetZExt?
271 Chain = DAG.getCALLSEQ_END(Chain, NB, Zero, SDValue(), DL);
276 bool WebAssemblyTargetLowering::CanLowerReturn(
277 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
278 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
279 // WebAssembly can't currently handle returning tuples.
280 return Outs.size() <= 1;
283 SDValue WebAssemblyTargetLowering::LowerReturn(
284 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
285 const SmallVectorImpl<ISD::OutputArg> &Outs,
286 const SmallVectorImpl<SDValue> &OutVals, SDLoc DL,
287 SelectionDAG &DAG) const {
289 assert(Outs.size() <= 1 && "WebAssembly can only return up to one value");
290 if (CallConv != CallingConv::C)
291 fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
293 fail(DL, DAG, "WebAssembly doesn't support varargs yet");
295 SmallVector<SDValue, 4> RetOps(1, Chain);
296 RetOps.append(OutVals.begin(), OutVals.end());
297 Chain = DAG.getNode(WebAssemblyISD::RETURN, DL, MVT::Other, RetOps);
302 SDValue WebAssemblyTargetLowering::LowerFormalArguments(
303 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
304 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
305 SmallVectorImpl<SDValue> &InVals) const {
306 MachineFunction &MF = DAG.getMachineFunction();
308 if (CallConv != CallingConv::C)
309 fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
311 fail(DL, DAG, "WebAssembly doesn't support varargs yet");
312 if (MF.getFunction()->hasStructRetAttr())
313 fail(DL, DAG, "WebAssembly doesn't support struct return yet");
316 for (const ISD::InputArg &In : Ins) {
317 if (In.Flags.isZExt())
318 fail(DL, DAG, "WebAssembly hasn't implemented zext arguments");
319 if (In.Flags.isSExt())
320 fail(DL, DAG, "WebAssembly hasn't implemented sext arguments");
321 if (In.Flags.isInReg())
322 fail(DL, DAG, "WebAssembly hasn't implemented inreg arguments");
323 if (In.Flags.isSRet())
324 fail(DL, DAG, "WebAssembly hasn't implemented sret arguments");
325 if (In.Flags.isByVal())
326 fail(DL, DAG, "WebAssembly hasn't implemented byval arguments");
327 if (In.Flags.isInAlloca())
328 fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
329 if (In.Flags.isNest())
330 fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
331 if (In.Flags.isReturned())
332 fail(DL, DAG, "WebAssembly hasn't implemented returned arguments");
333 if (In.Flags.isInConsecutiveRegs())
334 fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
335 if (In.Flags.isInConsecutiveRegsLast())
336 fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
337 if (In.Flags.isSplit())
338 fail(DL, DAG, "WebAssembly hasn't implemented split arguments");
339 // FIXME Do something with In.getOrigAlign()?
342 ? DAG.getNode(WebAssemblyISD::ARGUMENT, DL, In.VT,
343 DAG.getTargetConstant(ArgNo, DL, MVT::i32))
344 : DAG.getNode(ISD::UNDEF, DL, In.VT));
351 //===----------------------------------------------------------------------===//
352 // Custom lowering hooks.
353 //===----------------------------------------------------------------------===//
355 SDValue WebAssemblyTargetLowering::LowerOperation(SDValue Op,
356 SelectionDAG &DAG) const {
357 switch (Op.getOpcode()) {
359 llvm_unreachable("unimplemented operation lowering");
361 case ISD::GlobalAddress:
362 return LowerGlobalAddress(Op, DAG);
366 SDValue WebAssemblyTargetLowering::LowerGlobalAddress(SDValue Op,
367 SelectionDAG &DAG) const {
369 const auto *GA = cast<GlobalAddressSDNode>(Op);
370 EVT VT = Op.getValueType();
371 assert(GA->getOffset() == 0 &&
372 "offsets on global addresses are forbidden by isOffsetFoldingLegal");
373 assert(GA->getTargetFlags() == 0 && "WebAssembly doesn't set target flags");
374 if (GA->getAddressSpace() != 0)
375 fail(DL, DAG, "WebAssembly only expects the 0 address space");
376 return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
377 DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT));
380 //===----------------------------------------------------------------------===//
381 // WebAssembly Optimization Hooks
382 //===----------------------------------------------------------------------===//
384 MCSection *WebAssemblyTargetObjectFile::SelectSectionForGlobal(
385 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
386 const TargetMachine &TM) const {
387 return getDataSection();