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/MachineJumpTableInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/SelectionDAG.h"
26 #include "llvm/IR/DiagnosticInfo.h"
27 #include "llvm/IR/DiagnosticPrinter.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/Support/CommandLine.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"
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::I32RegClass);
110 addRegisterClass(MVT::i64, &WebAssembly::I64RegClass);
111 addRegisterClass(MVT::f32, &WebAssembly::F32RegClass);
112 addRegisterClass(MVT::f64, &WebAssembly::F64RegClass);
113 // Compute derived properties from the register classes.
114 computeRegisterProperties(Subtarget->getRegisterInfo());
116 setOperationAction(ISD::GlobalAddress, MVTPtr, Custom);
117 setOperationAction(ISD::JumpTable, MVTPtr, Custom);
119 for (auto T : {MVT::f32, MVT::f64}) {
120 // Don't expand the floating-point types to constant pools.
121 setOperationAction(ISD::ConstantFP, T, Legal);
122 // Expand floating-point comparisons.
123 for (auto CC : {ISD::SETO, ISD::SETUO, ISD::SETUEQ, ISD::SETONE,
124 ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE})
125 setCondCodeAction(CC, T, Expand);
126 // Expand floating-point library function operators.
127 for (auto Op : {ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOWI, ISD::FPOW})
128 setOperationAction(Op, T, Expand);
129 // Note supported floating-point library function operators that otherwise
130 // default to expand.
131 for (auto Op : {ISD::FCEIL, ISD::FFLOOR, ISD::FTRUNC, ISD::FNEARBYINT,
133 setOperationAction(Op, T, Legal);
134 // Support minnan and maxnan, which otherwise default to expand.
135 setOperationAction(ISD::FMINNAN, T, Legal);
136 setOperationAction(ISD::FMAXNAN, T, Legal);
139 for (auto T : {MVT::i32, MVT::i64}) {
140 // Expand unavailable integer operations.
141 for (auto Op : {ISD::BSWAP, ISD::ROTL, ISD::ROTR,
142 ISD::SMUL_LOHI, ISD::UMUL_LOHI,
143 ISD::MULHS, ISD::MULHU, ISD::SDIVREM, ISD::UDIVREM,
144 ISD::SHL_PARTS, ISD::SRA_PARTS, ISD::SRL_PARTS,
145 ISD::ADDC, ISD::ADDE, ISD::SUBC, ISD::SUBE}) {
146 setOperationAction(Op, T, Expand);
150 // As a special case, these operators use the type to mean the type to
152 for (auto T : {MVT::i1, MVT::i8, MVT::i16})
153 setOperationAction(ISD::SIGN_EXTEND_INREG, T, Expand);
155 // Dynamic stack allocation: use the default expansion.
156 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
157 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
158 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVTPtr, Expand);
160 // Expand these forms; we pattern-match the forms that we can handle in isel.
161 for (auto T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64})
162 for (auto Op : {ISD::BR_CC, ISD::SELECT_CC})
163 setOperationAction(Op, T, Expand);
165 // We have custom switch handling.
166 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
168 // WebAssembly doesn't have:
169 // - Floating-point extending loads.
170 // - Floating-point truncating stores.
171 // - i1 extending loads.
172 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f64, Expand);
173 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
174 for (auto T : MVT::integer_valuetypes())
175 for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD})
176 setLoadExtAction(Ext, T, MVT::i1, Promote);
178 // Trap lowers to wasm unreachable
179 setOperationAction(ISD::TRAP, MVT::Other, Legal);
182 FastISel *WebAssemblyTargetLowering::createFastISel(
183 FunctionLoweringInfo &FuncInfo, const TargetLibraryInfo *LibInfo) const {
184 return WebAssembly::createFastISel(FuncInfo, LibInfo);
187 bool WebAssemblyTargetLowering::isOffsetFoldingLegal(
188 const GlobalAddressSDNode *GA) const {
189 // The WebAssembly target doesn't support folding offsets into global
194 MVT WebAssemblyTargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
196 return VT.getSimpleVT();
200 WebAssemblyTargetLowering::getTargetNodeName(unsigned Opcode) const {
201 switch (static_cast<WebAssemblyISD::NodeType>(Opcode)) {
202 case WebAssemblyISD::FIRST_NUMBER:
204 #define HANDLE_NODETYPE(NODE) \
205 case WebAssemblyISD::NODE: \
206 return "WebAssemblyISD::" #NODE;
207 #include "WebAssemblyISD.def"
208 #undef HANDLE_NODETYPE
213 std::pair<unsigned, const TargetRegisterClass *>
214 WebAssemblyTargetLowering::getRegForInlineAsmConstraint(
215 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
216 // First, see if this is a constraint that directly corresponds to a
217 // WebAssembly register class.
218 if (Constraint.size() == 1) {
219 switch (Constraint[0]) {
221 return std::make_pair(0U, &WebAssembly::I32RegClass);
227 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
230 bool WebAssemblyTargetLowering::isCheapToSpeculateCttz() const {
231 // Assume ctz is a relatively cheap operation.
235 bool WebAssemblyTargetLowering::isCheapToSpeculateCtlz() const {
236 // Assume clz is a relatively cheap operation.
240 //===----------------------------------------------------------------------===//
241 // WebAssembly Lowering private implementation.
242 //===----------------------------------------------------------------------===//
244 //===----------------------------------------------------------------------===//
246 //===----------------------------------------------------------------------===//
248 static void fail(SDLoc DL, SelectionDAG &DAG, const char *msg) {
249 MachineFunction &MF = DAG.getMachineFunction();
250 DAG.getContext()->diagnose(
251 DiagnosticInfoUnsupported(DL, *MF.getFunction(), msg, SDValue()));
255 WebAssemblyTargetLowering::LowerCall(CallLoweringInfo &CLI,
256 SmallVectorImpl<SDValue> &InVals) const {
257 SelectionDAG &DAG = CLI.DAG;
259 SDValue Chain = CLI.Chain;
260 SDValue Callee = CLI.Callee;
261 MachineFunction &MF = DAG.getMachineFunction();
263 CallingConv::ID CallConv = CLI.CallConv;
264 if (CallConv != CallingConv::C &&
265 CallConv != CallingConv::Fast &&
266 CallConv != CallingConv::Cold)
268 "WebAssembly doesn't support language-specific or target-specific "
269 "calling conventions yet");
270 if (CLI.IsPatchPoint)
271 fail(DL, DAG, "WebAssembly doesn't support patch point yet");
273 // WebAssembly doesn't currently support explicit tail calls. If they are
274 // required, fail. Otherwise, just disable them.
275 if ((CallConv == CallingConv::Fast && CLI.IsTailCall &&
276 MF.getTarget().Options.GuaranteedTailCallOpt) ||
277 (CLI.CS && CLI.CS->isMustTailCall()))
278 fail(DL, DAG, "WebAssembly doesn't support tail call yet");
279 CLI.IsTailCall = false;
281 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
283 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
285 fail(DL, DAG, "WebAssembly doesn't support more than 1 returned value yet");
287 bool IsVarArg = CLI.IsVarArg;
289 fail(DL, DAG, "WebAssembly doesn't support varargs yet");
291 // Analyze operands of the call, assigning locations to each operand.
292 SmallVector<CCValAssign, 16> ArgLocs;
293 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
294 unsigned NumBytes = CCInfo.getNextStackOffset();
296 auto PtrVT = getPointerTy(MF.getDataLayout());
297 auto Zero = DAG.getConstant(0, DL, PtrVT, true);
298 auto NB = DAG.getConstant(NumBytes, DL, PtrVT, true);
299 Chain = DAG.getCALLSEQ_START(Chain, NB, DL);
301 SmallVector<SDValue, 16> Ops;
302 Ops.push_back(Chain);
303 Ops.push_back(Callee);
304 Ops.append(OutVals.begin(), OutVals.end());
306 SmallVector<EVT, 8> Tys;
307 for (const auto &In : Ins)
308 Tys.push_back(In.VT);
309 Tys.push_back(MVT::Other);
310 SDVTList TyList = DAG.getVTList(Tys);
312 DAG.getNode(Ins.empty() ? WebAssemblyISD::CALL0 : WebAssemblyISD::CALL1,
317 InVals.push_back(Res);
318 Chain = Res.getValue(1);
321 Chain = DAG.getCALLSEQ_END(Chain, NB, Zero, SDValue(), DL);
326 bool WebAssemblyTargetLowering::CanLowerReturn(
327 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
328 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
329 // WebAssembly can't currently handle returning tuples.
330 return Outs.size() <= 1;
333 SDValue WebAssemblyTargetLowering::LowerReturn(
334 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
335 const SmallVectorImpl<ISD::OutputArg> &Outs,
336 const SmallVectorImpl<SDValue> &OutVals, SDLoc DL,
337 SelectionDAG &DAG) const {
338 assert(Outs.size() <= 1 && "WebAssembly can only return up to one value");
339 if (CallConv != CallingConv::C)
340 fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
342 fail(DL, DAG, "WebAssembly doesn't support varargs yet");
344 SmallVector<SDValue, 4> RetOps(1, Chain);
345 RetOps.append(OutVals.begin(), OutVals.end());
346 Chain = DAG.getNode(WebAssemblyISD::RETURN, DL, MVT::Other, RetOps);
348 // Record the number and types of the return values.
349 for (const ISD::OutputArg &Out : Outs) {
350 if (Out.Flags.isByVal())
351 fail(DL, DAG, "WebAssembly hasn't implemented byval results");
352 if (Out.Flags.isInAlloca())
353 fail(DL, DAG, "WebAssembly hasn't implemented inalloca results");
354 if (Out.Flags.isNest())
355 fail(DL, DAG, "WebAssembly hasn't implemented nest results");
356 if (Out.Flags.isInConsecutiveRegs())
357 fail(DL, DAG, "WebAssembly hasn't implemented cons regs results");
358 if (Out.Flags.isInConsecutiveRegsLast())
359 fail(DL, DAG, "WebAssembly hasn't implemented cons regs last results");
361 fail(DL, DAG, "WebAssembly doesn't support non-fixed results yet");
367 SDValue WebAssemblyTargetLowering::LowerFormalArguments(
368 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
369 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
370 SmallVectorImpl<SDValue> &InVals) const {
371 MachineFunction &MF = DAG.getMachineFunction();
373 if (CallConv != CallingConv::C)
374 fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
376 fail(DL, DAG, "WebAssembly doesn't support varargs yet");
378 for (const ISD::InputArg &In : Ins) {
379 if (In.Flags.isByVal())
380 fail(DL, DAG, "WebAssembly hasn't implemented byval arguments");
381 if (In.Flags.isInAlloca())
382 fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
383 if (In.Flags.isNest())
384 fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
385 if (In.Flags.isInConsecutiveRegs())
386 fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
387 if (In.Flags.isInConsecutiveRegsLast())
388 fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
389 // FIXME Do something with In.getOrigAlign()?
392 ? DAG.getNode(WebAssemblyISD::ARGUMENT, DL, In.VT,
393 DAG.getTargetConstant(InVals.size(), DL, MVT::i32))
394 : DAG.getNode(ISD::UNDEF, DL, In.VT));
396 // Record the number and types of arguments.
397 MF.getInfo<WebAssemblyFunctionInfo>()->addParam(In.VT);
403 //===----------------------------------------------------------------------===//
404 // Custom lowering hooks.
405 //===----------------------------------------------------------------------===//
407 SDValue WebAssemblyTargetLowering::LowerOperation(SDValue Op,
408 SelectionDAG &DAG) const {
409 switch (Op.getOpcode()) {
411 llvm_unreachable("unimplemented operation lowering");
413 case ISD::GlobalAddress:
414 return LowerGlobalAddress(Op, DAG);
416 return LowerJumpTable(Op, DAG);
418 return LowerBR_JT(Op, DAG);
422 SDValue WebAssemblyTargetLowering::LowerGlobalAddress(SDValue Op,
423 SelectionDAG &DAG) const {
425 const auto *GA = cast<GlobalAddressSDNode>(Op);
426 EVT VT = Op.getValueType();
427 assert(GA->getOffset() == 0 &&
428 "offsets on global addresses are forbidden by isOffsetFoldingLegal");
429 assert(GA->getTargetFlags() == 0 && "WebAssembly doesn't set target flags");
430 if (GA->getAddressSpace() != 0)
431 fail(DL, DAG, "WebAssembly only expects the 0 address space");
432 return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
433 DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT));
436 SDValue WebAssemblyTargetLowering::LowerJumpTable(SDValue Op,
437 SelectionDAG &DAG) const {
438 // There's no need for a Wrapper node because we always incorporate a jump
439 // table operand into a TABLESWITCH instruction, rather than ever
440 // materializing it in a register.
441 const JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
442 return DAG.getTargetJumpTable(JT->getIndex(), Op.getValueType(),
443 JT->getTargetFlags());
446 SDValue WebAssemblyTargetLowering::LowerBR_JT(SDValue Op,
447 SelectionDAG &DAG) const {
449 SDValue Chain = Op.getOperand(0);
450 const auto *JT = cast<JumpTableSDNode>(Op.getOperand(1));
451 SDValue Index = Op.getOperand(2);
452 assert(JT->getTargetFlags() == 0 && "WebAssembly doesn't set target flags");
454 SmallVector<SDValue, 8> Ops;
455 Ops.push_back(Chain);
456 Ops.push_back(Index);
458 MachineJumpTableInfo *MJTI = DAG.getMachineFunction().getJumpTableInfo();
459 const auto &MBBs = MJTI->getJumpTables()[JT->getIndex()].MBBs;
461 // TODO: For now, we just pick something arbitrary for a default case for now.
462 // We really want to sniff out the guard and put in the real default case (and
463 // delete the guard).
464 Ops.push_back(DAG.getBasicBlock(MBBs[0]));
466 // Add an operand for each case.
467 for (auto MBB : MBBs)
468 Ops.push_back(DAG.getBasicBlock(MBB));
470 return DAG.getNode(WebAssemblyISD::TABLESWITCH, DL, MVT::Other, Ops);
473 //===----------------------------------------------------------------------===//
474 // WebAssembly Optimization Hooks
475 //===----------------------------------------------------------------------===//
477 MCSection *WebAssemblyTargetObjectFile::SelectSectionForGlobal(
478 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
479 const TargetMachine &TM) const {
480 // TODO: Be more sophisticated than this.
481 return isa<Function>(GV) ? getTextSection() : getDataSection();