blob: e71290608ce9f17b49fe24ce94257ecf30397937 [file] [log] [blame]
Dan Gohman10e730a2015-06-29 23:51:55 +00001//=- WebAssemblyISelLowering.cpp - WebAssembly DAG Lowering Implementation -==//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Dan Gohman10e730a2015-06-29 23:51:55 +00006//
7//===----------------------------------------------------------------------===//
8///
9/// \file
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000010/// This file implements the WebAssemblyTargetLowering class.
Dan Gohman10e730a2015-06-29 23:51:55 +000011///
12//===----------------------------------------------------------------------===//
13
14#include "WebAssemblyISelLowering.h"
15#include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
16#include "WebAssemblyMachineFunctionInfo.h"
17#include "WebAssemblySubtarget.h"
18#include "WebAssemblyTargetMachine.h"
Dan Gohman10e730a2015-06-29 23:51:55 +000019#include "llvm/CodeGen/Analysis.h"
JF Bastienaf111db2015-08-24 22:16:48 +000020#include "llvm/CodeGen/CallingConvLower.h"
Dan Gohmancdd48b82017-11-28 01:13:40 +000021#include "llvm/CodeGen/MachineInstrBuilder.h"
Dan Gohman950a13c2015-09-16 16:51:30 +000022#include "llvm/CodeGen/MachineJumpTableInfo.h"
Heejin Ahn24faf852018-10-25 23:55:10 +000023#include "llvm/CodeGen/MachineModuleInfo.h"
Dan Gohman10e730a2015-06-29 23:51:55 +000024#include "llvm/CodeGen/MachineRegisterInfo.h"
25#include "llvm/CodeGen/SelectionDAG.h"
Heejin Ahnda419bd2018-11-14 02:46:21 +000026#include "llvm/CodeGen/WasmEHFuncInfo.h"
Oliver Stannard02fa1c82016-01-28 13:19:47 +000027#include "llvm/IR/DiagnosticInfo.h"
JF Bastienb9073fb2015-07-22 21:28:15 +000028#include "llvm/IR/DiagnosticPrinter.h"
Dan Gohman10e730a2015-06-29 23:51:55 +000029#include "llvm/IR/Function.h"
30#include "llvm/IR/Intrinsics.h"
Reid Kleckner5d986952019-12-11 07:55:26 -080031#include "llvm/IR/IntrinsicsWebAssembly.h"
Dan Gohman10e730a2015-06-29 23:51:55 +000032#include "llvm/Support/Debug.h"
33#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/raw_ostream.h"
35#include "llvm/Target/TargetOptions.h"
36using namespace llvm;
37
38#define DEBUG_TYPE "wasm-lower"
39
40WebAssemblyTargetLowering::WebAssemblyTargetLowering(
41 const TargetMachine &TM, const WebAssemblySubtarget &STI)
Dan Gohmanbfaf7e12015-07-02 21:36:25 +000042 : TargetLowering(TM), Subtarget(&STI) {
JF Bastienaf111db2015-08-24 22:16:48 +000043 auto MVTPtr = Subtarget->hasAddr64() ? MVT::i64 : MVT::i32;
44
JF Bastien71d29ac2015-08-12 17:53:29 +000045 // Booleans always contain 0 or 1.
46 setBooleanContents(ZeroOrOneBooleanContent);
Thomas Lively5ea17d42018-10-20 01:35:23 +000047 // Except in SIMD vectors
48 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
Dan Gohman489abd72015-07-07 22:38:06 +000049 // We don't know the microarchitecture here, so just reduce register pressure.
50 setSchedulingPreference(Sched::RegPressure);
JF Bastienb9073fb2015-07-22 21:28:15 +000051 // Tell ISel that we have a stack pointer.
52 setStackPointerRegisterToSaveRestore(
53 Subtarget->hasAddr64() ? WebAssembly::SP64 : WebAssembly::SP32);
54 // Set up the register classes.
Dan Gohmand0bf9812015-09-26 01:09:44 +000055 addRegisterClass(MVT::i32, &WebAssembly::I32RegClass);
56 addRegisterClass(MVT::i64, &WebAssembly::I64RegClass);
57 addRegisterClass(MVT::f32, &WebAssembly::F32RegClass);
58 addRegisterClass(MVT::f64, &WebAssembly::F64RegClass);
Derek Schuff39bf39f2016-08-02 23:16:09 +000059 if (Subtarget->hasSIMD128()) {
60 addRegisterClass(MVT::v16i8, &WebAssembly::V128RegClass);
61 addRegisterClass(MVT::v8i16, &WebAssembly::V128RegClass);
62 addRegisterClass(MVT::v4i32, &WebAssembly::V128RegClass);
63 addRegisterClass(MVT::v4f32, &WebAssembly::V128RegClass);
Thomas Lively2b8b2972019-01-26 01:25:37 +000064 addRegisterClass(MVT::v2i64, &WebAssembly::V128RegClass);
65 addRegisterClass(MVT::v2f64, &WebAssembly::V128RegClass);
Derek Schuff39bf39f2016-08-02 23:16:09 +000066 }
JF Bastienb9073fb2015-07-22 21:28:15 +000067 // Compute derived properties from the register classes.
68 computeRegisterProperties(Subtarget->getRegisterInfo());
69
JF Bastienaf111db2015-08-24 22:16:48 +000070 setOperationAction(ISD::GlobalAddress, MVTPtr, Custom);
Dan Gohman2c8fe6a2015-11-25 16:44:29 +000071 setOperationAction(ISD::ExternalSymbol, MVTPtr, Custom);
Dan Gohman950a13c2015-09-16 16:51:30 +000072 setOperationAction(ISD::JumpTable, MVTPtr, Custom);
Derek Schuff51699a82016-02-12 22:56:03 +000073 setOperationAction(ISD::BlockAddress, MVTPtr, Custom);
74 setOperationAction(ISD::BRIND, MVT::Other, Custom);
JF Bastienaf111db2015-08-24 22:16:48 +000075
Dan Gohman35bfb242015-12-04 23:22:35 +000076 // Take the default expansion for va_arg, va_copy, and va_end. There is no
77 // default action for va_start, so we do that custom.
78 setOperationAction(ISD::VASTART, MVT::Other, Custom);
79 setOperationAction(ISD::VAARG, MVT::Other, Expand);
80 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
81 setOperationAction(ISD::VAEND, MVT::Other, Expand);
82
Thomas Livelyebd4c902018-09-12 17:56:00 +000083 for (auto T : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
JF Bastienda06bce2015-08-11 21:02:46 +000084 // Don't expand the floating-point types to constant pools.
85 setOperationAction(ISD::ConstantFP, T, Legal);
86 // Expand floating-point comparisons.
87 for (auto CC : {ISD::SETO, ISD::SETUO, ISD::SETUEQ, ISD::SETONE,
88 ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE})
89 setCondCodeAction(CC, T, Expand);
Dan Gohman32907a62015-08-20 22:57:13 +000090 // Expand floating-point library function operators.
Heejin Ahnf208f632018-09-05 01:27:38 +000091 for (auto Op :
92 {ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FREM, ISD::FMA})
Dan Gohman32907a62015-08-20 22:57:13 +000093 setOperationAction(Op, T, Expand);
Dan Gohman896e53f2015-08-24 18:23:13 +000094 // Note supported floating-point library function operators that otherwise
95 // default to expand.
Dan Gohman7a6b9822015-11-29 22:32:02 +000096 for (auto Op :
97 {ISD::FCEIL, ISD::FFLOOR, ISD::FTRUNC, ISD::FNEARBYINT, ISD::FRINT})
Dan Gohman896e53f2015-08-24 18:23:13 +000098 setOperationAction(Op, T, Legal);
Thomas Lively30f1d692018-10-24 22:49:55 +000099 // Support minimum and maximum, which otherwise default to expand.
100 setOperationAction(ISD::FMINIMUM, T, Legal);
101 setOperationAction(ISD::FMAXIMUM, T, Legal);
Dan Gohmana63e8eb2017-02-22 16:28:00 +0000102 // WebAssembly currently has no builtin f16 support.
103 setOperationAction(ISD::FP16_TO_FP, T, Expand);
104 setOperationAction(ISD::FP_TO_FP16, T, Expand);
105 setLoadExtAction(ISD::EXTLOAD, T, MVT::f16, Expand);
106 setTruncStoreAction(T, MVT::f16, Expand);
JF Bastienda06bce2015-08-11 21:02:46 +0000107 }
Dan Gohman32907a62015-08-20 22:57:13 +0000108
Thomas Lively66ea30c2018-11-29 22:01:01 +0000109 // Expand unavailable integer operations.
110 for (auto Op :
111 {ISD::BSWAP, ISD::SMUL_LOHI, ISD::UMUL_LOHI, ISD::MULHS, ISD::MULHU,
112 ISD::SDIVREM, ISD::UDIVREM, ISD::SHL_PARTS, ISD::SRA_PARTS,
113 ISD::SRL_PARTS, ISD::ADDC, ISD::ADDE, ISD::SUBC, ISD::SUBE}) {
Thomas Lively2b8b2972019-01-26 01:25:37 +0000114 for (auto T : {MVT::i32, MVT::i64})
Dan Gohman32907a62015-08-20 22:57:13 +0000115 setOperationAction(Op, T, Expand);
Thomas Lively2b8b2972019-01-26 01:25:37 +0000116 if (Subtarget->hasSIMD128())
Thomas Lively27748362020-01-30 18:23:14 -0800117 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64})
Thomas Lively66ea30c2018-11-29 22:01:01 +0000118 setOperationAction(Op, T, Expand);
Thomas Livelyb2382c82018-11-02 00:39:57 +0000119 }
Thomas Lively55735d52018-10-20 01:31:18 +0000120
Thomas Lively2b8b2972019-01-26 01:25:37 +0000121 // SIMD-specific configuration
122 if (Subtarget->hasSIMD128()) {
123 // Support saturating add for i8x16 and i16x8
124 for (auto Op : {ISD::SADDSAT, ISD::UADDSAT})
125 for (auto T : {MVT::v16i8, MVT::v8i16})
126 setOperationAction(Op, T, Legal);
127
Thomas Lively079816e2019-01-30 02:23:29 +0000128 // Custom lower BUILD_VECTORs to minimize number of replace_lanes
Thomas Lively27748362020-01-30 18:23:14 -0800129 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
130 MVT::v2f64})
Thomas Lively079816e2019-01-30 02:23:29 +0000131 setOperationAction(ISD::BUILD_VECTOR, T, Custom);
Thomas Lively079816e2019-01-30 02:23:29 +0000132
Thomas Lively2b8b2972019-01-26 01:25:37 +0000133 // We have custom shuffle lowering to expose the shuffle mask
Thomas Lively27748362020-01-30 18:23:14 -0800134 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
135 MVT::v2f64})
Thomas Lively2b8b2972019-01-26 01:25:37 +0000136 setOperationAction(ISD::VECTOR_SHUFFLE, T, Custom);
Thomas Lively2b8b2972019-01-26 01:25:37 +0000137
138 // Custom lowering since wasm shifts must have a scalar shift amount
Thomas Lively27748362020-01-30 18:23:14 -0800139 for (auto Op : {ISD::SHL, ISD::SRA, ISD::SRL})
140 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64})
Thomas Lively2b8b2972019-01-26 01:25:37 +0000141 setOperationAction(Op, T, Custom);
Thomas Lively2b8b2972019-01-26 01:25:37 +0000142
143 // Custom lower lane accesses to expand out variable indices
Thomas Lively27748362020-01-30 18:23:14 -0800144 for (auto Op : {ISD::EXTRACT_VECTOR_ELT, ISD::INSERT_VECTOR_ELT})
145 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
146 MVT::v2f64})
Thomas Lively2b8b2972019-01-26 01:25:37 +0000147 setOperationAction(Op, T, Custom);
Thomas Lively2b8b2972019-01-26 01:25:37 +0000148
149 // There is no i64x2.mul instruction
Thomas Lively27748362020-01-30 18:23:14 -0800150 // TODO: Actually, there is now. Implement it.
Thomas Lively2b8b2972019-01-26 01:25:37 +0000151 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
152
153 // There are no vector select instructions
Thomas Lively27748362020-01-30 18:23:14 -0800154 for (auto Op : {ISD::VSELECT, ISD::SELECT_CC, ISD::SELECT})
155 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
156 MVT::v2f64})
Thomas Lively38c902b2018-11-09 01:38:44 +0000157 setOperationAction(Op, T, Expand);
Thomas Livelyd4891a12018-11-01 00:01:02 +0000158
Thomas Lively43876ae72019-03-02 03:32:25 +0000159 // Expand integer operations supported for scalars but not SIMD
160 for (auto Op : {ISD::CTLZ, ISD::CTTZ, ISD::CTPOP, ISD::SDIV, ISD::UDIV,
Thomas Lively27748362020-01-30 18:23:14 -0800161 ISD::SREM, ISD::UREM, ISD::ROTL, ISD::ROTR})
162 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64})
Thomas Lively43876ae72019-03-02 03:32:25 +0000163 setOperationAction(Op, T, Expand);
Thomas Lively43876ae72019-03-02 03:32:25 +0000164
Thomas Lively3a937562019-12-13 17:08:04 -0800165 // But we do have integer min and max operations
Thomas Lively27748362020-01-30 18:23:14 -0800166 for (auto Op : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
167 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
168 setOperationAction(Op, T, Legal);
Thomas Lively3a937562019-12-13 17:08:04 -0800169
Thomas Lively43876ae72019-03-02 03:32:25 +0000170 // Expand float operations supported for scalars but not SIMD
171 for (auto Op : {ISD::FCEIL, ISD::FFLOOR, ISD::FTRUNC, ISD::FNEARBYINT,
Thomas Lively55229f62019-05-24 00:15:04 +0000172 ISD::FCOPYSIGN, ISD::FLOG, ISD::FLOG2, ISD::FLOG10,
Thomas Lively27748362020-01-30 18:23:14 -0800173 ISD::FEXP, ISD::FEXP2, ISD::FRINT})
174 for (auto T : {MVT::v4f32, MVT::v2f64})
175 setOperationAction(Op, T, Expand);
Thomas Lively43876ae72019-03-02 03:32:25 +0000176
Thomas Livelyecb7daf2019-11-01 10:21:00 -0700177 // Expand operations not supported for i64x2 vectors
Thomas Lively27748362020-01-30 18:23:14 -0800178 for (unsigned CC = 0; CC < ISD::SETCC_INVALID; ++CC)
179 setCondCodeAction(static_cast<ISD::CondCode>(CC), MVT::v2i64, Custom);
Thomas Livelyecb7daf2019-11-01 10:21:00 -0700180
Thomas Lively27748362020-01-30 18:23:14 -0800181 // 64x2 conversions are not in the spec
182 if (!Subtarget->hasUnimplementedSIMD128())
183 for (auto Op :
184 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT})
185 for (auto T : {MVT::v2i64, MVT::v2f64})
186 setOperationAction(Op, T, Expand);
Thomas Lively2b8b2972019-01-26 01:25:37 +0000187 }
188
Dan Gohman32907a62015-08-20 22:57:13 +0000189 // As a special case, these operators use the type to mean the type to
190 // sign-extend from.
Derek Schuffa519fe52017-09-13 00:29:06 +0000191 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
Dan Gohman5d2b9352018-01-19 17:16:24 +0000192 if (!Subtarget->hasSignExt()) {
Thomas Lively64a39a12019-01-10 22:32:11 +0000193 // Sign extends are legal only when extending a vector extract
194 auto Action = Subtarget->hasSIMD128() ? Custom : Expand;
Derek Schuffa519fe52017-09-13 00:29:06 +0000195 for (auto T : {MVT::i8, MVT::i16, MVT::i32})
Thomas Lively64a39a12019-01-10 22:32:11 +0000196 setOperationAction(ISD::SIGN_EXTEND_INREG, T, Action);
Derek Schuffa519fe52017-09-13 00:29:06 +0000197 }
Graham Hunter1a9195d2019-09-17 10:19:23 +0000198 for (auto T : MVT::integer_fixedlen_vector_valuetypes())
Thomas Lively5ea17d42018-10-20 01:35:23 +0000199 setOperationAction(ISD::SIGN_EXTEND_INREG, T, Expand);
Dan Gohman32907a62015-08-20 22:57:13 +0000200
201 // Dynamic stack allocation: use the default expansion.
202 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
203 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
Dan Gohman2683a552015-08-24 22:31:52 +0000204 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVTPtr, Expand);
JF Bastien73ff6af2015-08-31 22:24:11 +0000205
Derek Schuff9769deb2015-12-11 23:49:46 +0000206 setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
Derek Schuffaadc89c2016-02-16 18:18:36 +0000207 setOperationAction(ISD::CopyToReg, MVT::Other, Custom);
Derek Schuff9769deb2015-12-11 23:49:46 +0000208
Dan Gohman950a13c2015-09-16 16:51:30 +0000209 // Expand these forms; we pattern-match the forms that we can handle in isel.
210 for (auto T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64})
211 for (auto Op : {ISD::BR_CC, ISD::SELECT_CC})
212 setOperationAction(Op, T, Expand);
213
214 // We have custom switch handling.
215 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
216
JF Bastien73ff6af2015-08-31 22:24:11 +0000217 // WebAssembly doesn't have:
218 // - Floating-point extending loads.
219 // - Floating-point truncating stores.
220 // - i1 extending loads.
Thomas Lively81125f72019-09-27 02:06:50 +0000221 // - truncating SIMD stores and most extending loads
Dan Gohman60bddf12015-12-10 02:07:53 +0000222 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
JF Bastien73ff6af2015-08-31 22:24:11 +0000223 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
224 for (auto T : MVT::integer_valuetypes())
225 for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD})
226 setLoadExtAction(Ext, T, MVT::i1, Promote);
Thomas Lively325c9c52018-10-25 01:46:07 +0000227 if (Subtarget->hasSIMD128()) {
228 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64, MVT::v4f32,
229 MVT::v2f64}) {
Graham Hunter1a9195d2019-09-17 10:19:23 +0000230 for (auto MemT : MVT::fixedlen_vector_valuetypes()) {
Thomas Lively325c9c52018-10-25 01:46:07 +0000231 if (MVT(T) != MemT) {
232 setTruncStoreAction(T, MemT, Expand);
233 for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD})
234 setLoadExtAction(Ext, T, MemT, Expand);
235 }
236 }
237 }
Thomas Lively81125f72019-09-27 02:06:50 +0000238 // But some vector extending loads are legal
239 if (Subtarget->hasUnimplementedSIMD128()) {
240 for (auto Ext : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) {
241 setLoadExtAction(Ext, MVT::v8i16, MVT::v8i8, Legal);
242 setLoadExtAction(Ext, MVT::v4i32, MVT::v4i16, Legal);
243 setLoadExtAction(Ext, MVT::v2i64, MVT::v2i32, Legal);
244 }
245 }
Thomas Lively325c9c52018-10-25 01:46:07 +0000246 }
Derek Schuffffa143c2015-11-10 00:30:57 +0000247
Thomas Lively33f87b82019-01-28 23:44:31 +0000248 // Don't do anything clever with build_pairs
249 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
250
Derek Schuffffa143c2015-11-10 00:30:57 +0000251 // Trap lowers to wasm unreachable
252 setOperationAction(ISD::TRAP, MVT::Other, Legal);
Derek Schuff18ba1922017-08-30 18:07:45 +0000253
Heejin Ahn5ef4d5f2018-05-31 22:25:54 +0000254 // Exception handling intrinsics
255 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
Heejin Ahnda419bd2018-11-14 02:46:21 +0000256 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
Heejin Ahn5ef4d5f2018-05-31 22:25:54 +0000257
Derek Schuff18ba1922017-08-30 18:07:45 +0000258 setMaxAtomicSizeInBitsSupported(64);
Thomas Livelyd99af232019-02-05 00:49:55 +0000259
Dan Gohman3a7532e2019-04-30 19:17:59 +0000260 // Override the __gnu_f2h_ieee/__gnu_h2f_ieee names so that the f32 name is
261 // consistent with the f64 and f128 names.
262 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
263 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
264
Thomas Lively1a3cbe72019-05-23 01:24:01 +0000265 // Define the emscripten name for return address helper.
266 // TODO: when implementing other WASM backends, make this generic or only do
267 // this on emscripten depending on what they end up doing.
268 setLibcallName(RTLIB::RETURN_ADDRESS, "emscripten_return_address");
269
Heejin Ahnb9f282d2019-04-23 21:30:30 +0000270 // Always convert switches to br_tables unless there is only one case, which
271 // is equivalent to a simple branch. This reduces code size for wasm, and we
272 // defer possible jump table optimizations to the VM.
273 setMinimumJumpTableEntries(2);
Dan Gohmanbfaf7e12015-07-02 21:36:25 +0000274}
Dan Gohman10e730a2015-06-29 23:51:55 +0000275
Heejin Ahne8653bb2018-08-07 00:22:22 +0000276TargetLowering::AtomicExpansionKind
277WebAssemblyTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
278 // We have wasm instructions for these
279 switch (AI->getOperation()) {
280 case AtomicRMWInst::Add:
281 case AtomicRMWInst::Sub:
282 case AtomicRMWInst::And:
283 case AtomicRMWInst::Or:
284 case AtomicRMWInst::Xor:
285 case AtomicRMWInst::Xchg:
286 return AtomicExpansionKind::None;
287 default:
288 break;
289 }
290 return AtomicExpansionKind::CmpXChg;
291}
292
Dan Gohman7b634842015-08-24 18:44:37 +0000293FastISel *WebAssemblyTargetLowering::createFastISel(
294 FunctionLoweringInfo &FuncInfo, const TargetLibraryInfo *LibInfo) const {
295 return WebAssembly::createFastISel(FuncInfo, LibInfo);
296}
297
Dan Gohman7a6b9822015-11-29 22:32:02 +0000298MVT WebAssemblyTargetLowering::getScalarShiftAmountTy(const DataLayout & /*DL*/,
JF Bastienfda53372015-08-03 00:00:11 +0000299 EVT VT) const {
Dan Gohmana8483752015-12-10 00:26:26 +0000300 unsigned BitWidth = NextPowerOf2(VT.getSizeInBits() - 1);
Heejin Ahnf208f632018-09-05 01:27:38 +0000301 if (BitWidth > 1 && BitWidth < 8)
302 BitWidth = 8;
Dan Gohman41729532015-12-16 23:25:51 +0000303
304 if (BitWidth > 64) {
Dan Gohmana01e8bd2016-05-14 02:15:47 +0000305 // The shift will be lowered to a libcall, and compiler-rt libcalls expect
306 // the count to be an i32.
307 BitWidth = 32;
Dan Gohman41729532015-12-16 23:25:51 +0000308 assert(BitWidth >= Log2_32_Ceil(VT.getSizeInBits()) &&
Dan Gohmana01e8bd2016-05-14 02:15:47 +0000309 "32-bit shift counts ought to be enough for anyone");
Dan Gohman41729532015-12-16 23:25:51 +0000310 }
311
Dan Gohmana8483752015-12-10 00:26:26 +0000312 MVT Result = MVT::getIntegerVT(BitWidth);
313 assert(Result != MVT::INVALID_SIMPLE_VALUE_TYPE &&
314 "Unable to represent scalar shift amount type");
315 return Result;
JF Bastienfda53372015-08-03 00:00:11 +0000316}
317
Dan Gohmancdd48b82017-11-28 01:13:40 +0000318// Lower an fp-to-int conversion operator from the LLVM opcode, which has an
319// undefined result on invalid/overflow, to the WebAssembly opcode, which
320// traps on invalid/overflow.
Heejin Ahnf208f632018-09-05 01:27:38 +0000321static MachineBasicBlock *LowerFPToInt(MachineInstr &MI, DebugLoc DL,
322 MachineBasicBlock *BB,
323 const TargetInstrInfo &TII,
324 bool IsUnsigned, bool Int64,
325 bool Float64, unsigned LoweredOpcode) {
Dan Gohmancdd48b82017-11-28 01:13:40 +0000326 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
327
Daniel Sanders05c145d2019-08-12 22:40:45 +0000328 Register OutReg = MI.getOperand(0).getReg();
329 Register InReg = MI.getOperand(1).getReg();
Dan Gohmancdd48b82017-11-28 01:13:40 +0000330
331 unsigned Abs = Float64 ? WebAssembly::ABS_F64 : WebAssembly::ABS_F32;
332 unsigned FConst = Float64 ? WebAssembly::CONST_F64 : WebAssembly::CONST_F32;
333 unsigned LT = Float64 ? WebAssembly::LT_F64 : WebAssembly::LT_F32;
Dan Gohman580c1022017-11-29 20:20:11 +0000334 unsigned GE = Float64 ? WebAssembly::GE_F64 : WebAssembly::GE_F32;
Dan Gohmancdd48b82017-11-28 01:13:40 +0000335 unsigned IConst = Int64 ? WebAssembly::CONST_I64 : WebAssembly::CONST_I32;
Dan Gohman580c1022017-11-29 20:20:11 +0000336 unsigned Eqz = WebAssembly::EQZ_I32;
337 unsigned And = WebAssembly::AND_I32;
Dan Gohmancdd48b82017-11-28 01:13:40 +0000338 int64_t Limit = Int64 ? INT64_MIN : INT32_MIN;
339 int64_t Substitute = IsUnsigned ? 0 : Limit;
340 double CmpVal = IsUnsigned ? -(double)Limit * 2.0 : -(double)Limit;
David Blaikie21109242017-12-15 23:52:06 +0000341 auto &Context = BB->getParent()->getFunction().getContext();
Dan Gohmancdd48b82017-11-28 01:13:40 +0000342 Type *Ty = Float64 ? Type::getDoubleTy(Context) : Type::getFloatTy(Context);
343
Heejin Ahn18c56a02019-02-04 19:13:39 +0000344 const BasicBlock *LLVMBB = BB->getBasicBlock();
Dan Gohmancdd48b82017-11-28 01:13:40 +0000345 MachineFunction *F = BB->getParent();
Heejin Ahn18c56a02019-02-04 19:13:39 +0000346 MachineBasicBlock *TrueMBB = F->CreateMachineBasicBlock(LLVMBB);
347 MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(LLVMBB);
348 MachineBasicBlock *DoneMBB = F->CreateMachineBasicBlock(LLVMBB);
Dan Gohmancdd48b82017-11-28 01:13:40 +0000349
350 MachineFunction::iterator It = ++BB->getIterator();
351 F->insert(It, FalseMBB);
352 F->insert(It, TrueMBB);
353 F->insert(It, DoneMBB);
354
355 // Transfer the remainder of BB and its successor edges to DoneMBB.
Heejin Ahn5c644c92019-03-05 21:05:09 +0000356 DoneMBB->splice(DoneMBB->begin(), BB, std::next(MI.getIterator()), BB->end());
Dan Gohmancdd48b82017-11-28 01:13:40 +0000357 DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
358
359 BB->addSuccessor(TrueMBB);
360 BB->addSuccessor(FalseMBB);
361 TrueMBB->addSuccessor(DoneMBB);
362 FalseMBB->addSuccessor(DoneMBB);
363
Dan Gohman580c1022017-11-29 20:20:11 +0000364 unsigned Tmp0, Tmp1, CmpReg, EqzReg, FalseReg, TrueReg;
Dan Gohmancdd48b82017-11-28 01:13:40 +0000365 Tmp0 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
366 Tmp1 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
Dan Gohman580c1022017-11-29 20:20:11 +0000367 CmpReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
368 EqzReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
369 FalseReg = MRI.createVirtualRegister(MRI.getRegClass(OutReg));
370 TrueReg = MRI.createVirtualRegister(MRI.getRegClass(OutReg));
Dan Gohmancdd48b82017-11-28 01:13:40 +0000371
372 MI.eraseFromParent();
Dan Gohman580c1022017-11-29 20:20:11 +0000373 // For signed numbers, we can do a single comparison to determine whether
374 // fabs(x) is within range.
Dan Gohmancdd48b82017-11-28 01:13:40 +0000375 if (IsUnsigned) {
376 Tmp0 = InReg;
377 } else {
Heejin Ahnf208f632018-09-05 01:27:38 +0000378 BuildMI(BB, DL, TII.get(Abs), Tmp0).addReg(InReg);
Dan Gohmancdd48b82017-11-28 01:13:40 +0000379 }
380 BuildMI(BB, DL, TII.get(FConst), Tmp1)
381 .addFPImm(cast<ConstantFP>(ConstantFP::get(Ty, CmpVal)));
Heejin Ahnf208f632018-09-05 01:27:38 +0000382 BuildMI(BB, DL, TII.get(LT), CmpReg).addReg(Tmp0).addReg(Tmp1);
Dan Gohman580c1022017-11-29 20:20:11 +0000383
384 // For unsigned numbers, we have to do a separate comparison with zero.
385 if (IsUnsigned) {
386 Tmp1 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
Daniel Sanders05c145d2019-08-12 22:40:45 +0000387 Register SecondCmpReg =
Heejin Ahnf208f632018-09-05 01:27:38 +0000388 MRI.createVirtualRegister(&WebAssembly::I32RegClass);
Daniel Sanders05c145d2019-08-12 22:40:45 +0000389 Register AndReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
Dan Gohman580c1022017-11-29 20:20:11 +0000390 BuildMI(BB, DL, TII.get(FConst), Tmp1)
391 .addFPImm(cast<ConstantFP>(ConstantFP::get(Ty, 0.0)));
Heejin Ahnf208f632018-09-05 01:27:38 +0000392 BuildMI(BB, DL, TII.get(GE), SecondCmpReg).addReg(Tmp0).addReg(Tmp1);
393 BuildMI(BB, DL, TII.get(And), AndReg).addReg(CmpReg).addReg(SecondCmpReg);
Dan Gohman580c1022017-11-29 20:20:11 +0000394 CmpReg = AndReg;
395 }
396
Heejin Ahnf208f632018-09-05 01:27:38 +0000397 BuildMI(BB, DL, TII.get(Eqz), EqzReg).addReg(CmpReg);
Dan Gohman580c1022017-11-29 20:20:11 +0000398
399 // Create the CFG diamond to select between doing the conversion or using
400 // the substitute value.
Heejin Ahnf208f632018-09-05 01:27:38 +0000401 BuildMI(BB, DL, TII.get(WebAssembly::BR_IF)).addMBB(TrueMBB).addReg(EqzReg);
402 BuildMI(FalseMBB, DL, TII.get(LoweredOpcode), FalseReg).addReg(InReg);
403 BuildMI(FalseMBB, DL, TII.get(WebAssembly::BR)).addMBB(DoneMBB);
404 BuildMI(TrueMBB, DL, TII.get(IConst), TrueReg).addImm(Substitute);
Dan Gohmancdd48b82017-11-28 01:13:40 +0000405 BuildMI(*DoneMBB, DoneMBB->begin(), DL, TII.get(TargetOpcode::PHI), OutReg)
Dan Gohman580c1022017-11-29 20:20:11 +0000406 .addReg(FalseReg)
Dan Gohmancdd48b82017-11-28 01:13:40 +0000407 .addMBB(FalseMBB)
Dan Gohman580c1022017-11-29 20:20:11 +0000408 .addReg(TrueReg)
Dan Gohmancdd48b82017-11-28 01:13:40 +0000409 .addMBB(TrueMBB);
410
411 return DoneMBB;
412}
413
Heejin Ahnf208f632018-09-05 01:27:38 +0000414MachineBasicBlock *WebAssemblyTargetLowering::EmitInstrWithCustomInserter(
415 MachineInstr &MI, MachineBasicBlock *BB) const {
Dan Gohmancdd48b82017-11-28 01:13:40 +0000416 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
417 DebugLoc DL = MI.getDebugLoc();
418
419 switch (MI.getOpcode()) {
Heejin Ahnf208f632018-09-05 01:27:38 +0000420 default:
421 llvm_unreachable("Unexpected instr type to insert");
Dan Gohmancdd48b82017-11-28 01:13:40 +0000422 case WebAssembly::FP_TO_SINT_I32_F32:
423 return LowerFPToInt(MI, DL, BB, TII, false, false, false,
424 WebAssembly::I32_TRUNC_S_F32);
425 case WebAssembly::FP_TO_UINT_I32_F32:
426 return LowerFPToInt(MI, DL, BB, TII, true, false, false,
427 WebAssembly::I32_TRUNC_U_F32);
428 case WebAssembly::FP_TO_SINT_I64_F32:
429 return LowerFPToInt(MI, DL, BB, TII, false, true, false,
430 WebAssembly::I64_TRUNC_S_F32);
431 case WebAssembly::FP_TO_UINT_I64_F32:
432 return LowerFPToInt(MI, DL, BB, TII, true, true, false,
433 WebAssembly::I64_TRUNC_U_F32);
434 case WebAssembly::FP_TO_SINT_I32_F64:
435 return LowerFPToInt(MI, DL, BB, TII, false, false, true,
436 WebAssembly::I32_TRUNC_S_F64);
437 case WebAssembly::FP_TO_UINT_I32_F64:
438 return LowerFPToInt(MI, DL, BB, TII, true, false, true,
439 WebAssembly::I32_TRUNC_U_F64);
440 case WebAssembly::FP_TO_SINT_I64_F64:
441 return LowerFPToInt(MI, DL, BB, TII, false, true, true,
442 WebAssembly::I64_TRUNC_S_F64);
443 case WebAssembly::FP_TO_UINT_I64_F64:
444 return LowerFPToInt(MI, DL, BB, TII, true, true, true,
445 WebAssembly::I64_TRUNC_U_F64);
Thomas Lively8acedb52020-02-03 14:27:03 -0800446 llvm_unreachable("Unexpected instruction to emit with custom inserter");
Dan Gohmancdd48b82017-11-28 01:13:40 +0000447 }
448}
449
Heejin Ahnf208f632018-09-05 01:27:38 +0000450const char *
451WebAssemblyTargetLowering::getTargetNodeName(unsigned Opcode) const {
JF Bastien480c8402015-08-11 20:13:18 +0000452 switch (static_cast<WebAssemblyISD::NodeType>(Opcode)) {
Heejin Ahnf208f632018-09-05 01:27:38 +0000453 case WebAssemblyISD::FIRST_NUMBER:
Thomas Lively3479fd22019-10-31 20:01:02 -0700454 case WebAssemblyISD::FIRST_MEM_OPCODE:
Heejin Ahnf208f632018-09-05 01:27:38 +0000455 break;
456#define HANDLE_NODETYPE(NODE) \
457 case WebAssemblyISD::NODE: \
JF Bastienaf111db2015-08-24 22:16:48 +0000458 return "WebAssemblyISD::" #NODE;
Thomas Lively3479fd22019-10-31 20:01:02 -0700459#define HANDLE_MEM_NODETYPE(NODE) HANDLE_NODETYPE(NODE)
JF Bastienaf111db2015-08-24 22:16:48 +0000460#include "WebAssemblyISD.def"
Thomas Lively3479fd22019-10-31 20:01:02 -0700461#undef HANDLE_MEM_NODETYPE
JF Bastienaf111db2015-08-24 22:16:48 +0000462#undef HANDLE_NODETYPE
JF Bastien480c8402015-08-11 20:13:18 +0000463 }
464 return nullptr;
465}
466
Dan Gohmanf19ed562015-11-13 01:42:29 +0000467std::pair<unsigned, const TargetRegisterClass *>
468WebAssemblyTargetLowering::getRegForInlineAsmConstraint(
469 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
470 // First, see if this is a constraint that directly corresponds to a
471 // WebAssembly register class.
472 if (Constraint.size() == 1) {
473 switch (Constraint[0]) {
Heejin Ahnf208f632018-09-05 01:27:38 +0000474 case 'r':
475 assert(VT != MVT::iPTR && "Pointer MVT not expected here");
476 if (Subtarget->hasSIMD128() && VT.isVector()) {
477 if (VT.getSizeInBits() == 128)
478 return std::make_pair(0U, &WebAssembly::V128RegClass);
479 }
480 if (VT.isInteger() && !VT.isVector()) {
481 if (VT.getSizeInBits() <= 32)
482 return std::make_pair(0U, &WebAssembly::I32RegClass);
483 if (VT.getSizeInBits() <= 64)
484 return std::make_pair(0U, &WebAssembly::I64RegClass);
485 }
486 break;
487 default:
488 break;
Dan Gohmanf19ed562015-11-13 01:42:29 +0000489 }
490 }
491
492 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
493}
494
Dan Gohman3192ddf2015-11-19 23:04:59 +0000495bool WebAssemblyTargetLowering::isCheapToSpeculateCttz() const {
496 // Assume ctz is a relatively cheap operation.
497 return true;
498}
499
500bool WebAssemblyTargetLowering::isCheapToSpeculateCtlz() const {
501 // Assume clz is a relatively cheap operation.
502 return true;
503}
504
Dan Gohman4b9d7912015-12-15 22:01:29 +0000505bool WebAssemblyTargetLowering::isLegalAddressingMode(const DataLayout &DL,
506 const AddrMode &AM,
Heejin Ahnf208f632018-09-05 01:27:38 +0000507 Type *Ty, unsigned AS,
Jonas Paulsson024e3192017-07-21 11:59:37 +0000508 Instruction *I) const {
Dan Gohman4b9d7912015-12-15 22:01:29 +0000509 // WebAssembly offsets are added as unsigned without wrapping. The
510 // isLegalAddressingMode gives us no way to determine if wrapping could be
511 // happening, so we approximate this by accepting only non-negative offsets.
Heejin Ahnf208f632018-09-05 01:27:38 +0000512 if (AM.BaseOffs < 0)
513 return false;
Dan Gohman4b9d7912015-12-15 22:01:29 +0000514
515 // WebAssembly has no scale register operands.
Heejin Ahnf208f632018-09-05 01:27:38 +0000516 if (AM.Scale != 0)
517 return false;
Dan Gohman4b9d7912015-12-15 22:01:29 +0000518
519 // Everything else is legal.
520 return true;
521}
522
Dan Gohmanbb372242016-01-26 03:39:31 +0000523bool WebAssemblyTargetLowering::allowsMisalignedMemoryAccesses(
Simon Pilgrim4e0648a2019-06-12 17:14:03 +0000524 EVT /*VT*/, unsigned /*AddrSpace*/, unsigned /*Align*/,
525 MachineMemOperand::Flags /*Flags*/, bool *Fast) const {
Dan Gohmanbb372242016-01-26 03:39:31 +0000526 // WebAssembly supports unaligned accesses, though it should be declared
527 // with the p2align attribute on loads and stores which do so, and there
528 // may be a performance impact. We tell LLVM they're "fast" because
Dan Gohmanfb619e92016-01-26 14:55:17 +0000529 // for the kinds of things that LLVM uses this for (merging adjacent stores
Dan Gohmanbb372242016-01-26 03:39:31 +0000530 // of constants, etc.), WebAssembly implementations will either want the
531 // unaligned access or they'll split anyway.
Heejin Ahnf208f632018-09-05 01:27:38 +0000532 if (Fast)
533 *Fast = true;
Dan Gohmanbb372242016-01-26 03:39:31 +0000534 return true;
535}
536
Reid Klecknerb5180542017-03-21 16:57:19 +0000537bool WebAssemblyTargetLowering::isIntDivCheap(EVT VT,
538 AttributeList Attr) const {
Dan Gohmanb4c3c382016-05-18 14:29:42 +0000539 // The current thinking is that wasm engines will perform this optimization,
540 // so we can save on code size.
541 return true;
542}
543
Thomas Lively81125f72019-09-27 02:06:50 +0000544bool WebAssemblyTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
545 if (!Subtarget->hasUnimplementedSIMD128())
546 return false;
547 MVT ExtT = ExtVal.getSimpleValueType();
548 MVT MemT = cast<LoadSDNode>(ExtVal->getOperand(0))->getSimpleValueType(0);
549 return (ExtT == MVT::v8i16 && MemT == MVT::v8i8) ||
550 (ExtT == MVT::v4i32 && MemT == MVT::v4i16) ||
551 (ExtT == MVT::v2i64 && MemT == MVT::v2i32);
552}
553
Simon Pilgrim99f70162018-06-28 17:27:09 +0000554EVT WebAssemblyTargetLowering::getSetCCResultType(const DataLayout &DL,
555 LLVMContext &C,
556 EVT VT) const {
557 if (VT.isVector())
558 return VT.changeVectorElementTypeToInteger();
559
560 return TargetLowering::getSetCCResultType(DL, C, VT);
561}
562
Heejin Ahn4128cb02018-08-02 21:44:24 +0000563bool WebAssemblyTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
564 const CallInst &I,
565 MachineFunction &MF,
566 unsigned Intrinsic) const {
567 switch (Intrinsic) {
568 case Intrinsic::wasm_atomic_notify:
569 Info.opc = ISD::INTRINSIC_W_CHAIN;
570 Info.memVT = MVT::i32;
571 Info.ptrVal = I.getArgOperand(0);
572 Info.offset = 0;
Guillaume Chateletc97a3d12019-08-05 11:02:05 +0000573 Info.align = Align(4);
Heejin Ahn4128cb02018-08-02 21:44:24 +0000574 // atomic.notify instruction does not really load the memory specified with
575 // this argument, but MachineMemOperand should either be load or store, so
576 // we set this to a load.
577 // FIXME Volatile isn't really correct, but currently all LLVM atomic
578 // instructions are treated as volatiles in the backend, so we should be
579 // consistent. The same applies for wasm_atomic_wait intrinsics too.
580 Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
581 return true;
582 case Intrinsic::wasm_atomic_wait_i32:
583 Info.opc = ISD::INTRINSIC_W_CHAIN;
584 Info.memVT = MVT::i32;
585 Info.ptrVal = I.getArgOperand(0);
586 Info.offset = 0;
Guillaume Chateletc97a3d12019-08-05 11:02:05 +0000587 Info.align = Align(4);
Heejin Ahn4128cb02018-08-02 21:44:24 +0000588 Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
589 return true;
590 case Intrinsic::wasm_atomic_wait_i64:
591 Info.opc = ISD::INTRINSIC_W_CHAIN;
592 Info.memVT = MVT::i64;
593 Info.ptrVal = I.getArgOperand(0);
594 Info.offset = 0;
Guillaume Chateletc97a3d12019-08-05 11:02:05 +0000595 Info.align = Align(8);
Heejin Ahn4128cb02018-08-02 21:44:24 +0000596 Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
597 return true;
598 default:
599 return false;
600 }
601}
602
Dan Gohman10e730a2015-06-29 23:51:55 +0000603//===----------------------------------------------------------------------===//
604// WebAssembly Lowering private implementation.
605//===----------------------------------------------------------------------===//
606
607//===----------------------------------------------------------------------===//
608// Lowering Code
609//===----------------------------------------------------------------------===//
610
Heejin Ahn18c56a02019-02-04 19:13:39 +0000611static void fail(const SDLoc &DL, SelectionDAG &DAG, const char *Msg) {
JF Bastienb9073fb2015-07-22 21:28:15 +0000612 MachineFunction &MF = DAG.getMachineFunction();
613 DAG.getContext()->diagnose(
Heejin Ahn18c56a02019-02-04 19:13:39 +0000614 DiagnosticInfoUnsupported(MF.getFunction(), Msg, DL.getDebugLoc()));
JF Bastienb9073fb2015-07-22 21:28:15 +0000615}
616
Dan Gohman85dbdda2015-12-04 17:16:07 +0000617// Test whether the given calling convention is supported.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000618static bool callingConvSupported(CallingConv::ID CallConv) {
Dan Gohman85dbdda2015-12-04 17:16:07 +0000619 // We currently support the language-independent target-independent
Dan Gohman1ce2b1a2015-12-04 18:27:03 +0000620 // conventions. We don't yet have a way to annotate calls with properties like
621 // "cold", and we don't have any call-clobbered registers, so these are mostly
622 // all handled the same.
Dan Gohmana3f5ce52015-12-04 17:18:32 +0000623 return CallConv == CallingConv::C || CallConv == CallingConv::Fast ||
Dan Gohman1ce2b1a2015-12-04 18:27:03 +0000624 CallConv == CallingConv::Cold ||
625 CallConv == CallingConv::PreserveMost ||
626 CallConv == CallingConv::PreserveAll ||
Keno Fischer5c3cdef2019-08-05 21:36:09 +0000627 CallConv == CallingConv::CXX_FAST_TLS ||
Yuta Saitoc5bd3d02020-01-24 10:20:07 -0800628 CallConv == CallingConv::WASM_EmscriptenInvoke ||
629 CallConv == CallingConv::Swift;
Dan Gohman85dbdda2015-12-04 17:16:07 +0000630}
631
Heejin Ahnf208f632018-09-05 01:27:38 +0000632SDValue
633WebAssemblyTargetLowering::LowerCall(CallLoweringInfo &CLI,
634 SmallVectorImpl<SDValue> &InVals) const {
JF Bastiend8a9d662015-08-24 21:59:51 +0000635 SelectionDAG &DAG = CLI.DAG;
636 SDLoc DL = CLI.DL;
637 SDValue Chain = CLI.Chain;
638 SDValue Callee = CLI.Callee;
639 MachineFunction &MF = DAG.getMachineFunction();
Derek Schuff992d83f2016-02-10 20:14:15 +0000640 auto Layout = MF.getDataLayout();
JF Bastiend8a9d662015-08-24 21:59:51 +0000641
642 CallingConv::ID CallConv = CLI.CallConv;
Heejin Ahn18c56a02019-02-04 19:13:39 +0000643 if (!callingConvSupported(CallConv))
Dan Gohman9cc692b2015-10-02 20:54:23 +0000644 fail(DL, DAG,
645 "WebAssembly doesn't support language-specific or target-specific "
646 "calling conventions yet");
JF Bastiend8a9d662015-08-24 21:59:51 +0000647 if (CLI.IsPatchPoint)
648 fail(DL, DAG, "WebAssembly doesn't support patch point yet");
649
Thomas Livelye0a9dce2019-07-30 18:08:39 +0000650 if (CLI.IsTailCall) {
651 bool MustTail = CLI.CS && CLI.CS.isMustTailCall();
652 if (Subtarget->hasTailCall() && !CLI.IsVarArg) {
653 // Do not tail call unless caller and callee return types match
654 const Function &F = MF.getFunction();
655 const TargetMachine &TM = getTargetMachine();
656 Type *RetTy = F.getReturnType();
657 SmallVector<MVT, 4> CallerRetTys;
658 SmallVector<MVT, 4> CalleeRetTys;
659 computeLegalValueVTs(F, TM, RetTy, CallerRetTys);
660 computeLegalValueVTs(F, TM, CLI.RetTy, CalleeRetTys);
661 bool TypesMatch = CallerRetTys.size() == CalleeRetTys.size() &&
662 std::equal(CallerRetTys.begin(), CallerRetTys.end(),
663 CalleeRetTys.begin());
664 if (!TypesMatch) {
665 // musttail in this case would be an LLVM IR validation failure
666 assert(!MustTail);
667 CLI.IsTailCall = false;
668 }
669 } else {
670 CLI.IsTailCall = false;
671 if (MustTail) {
672 if (CLI.IsVarArg) {
673 // The return would pop the argument buffer
674 fail(DL, DAG, "WebAssembly does not support varargs tail calls");
675 } else {
676 fail(DL, DAG, "WebAssembly 'tail-call' feature not enabled");
677 }
678 }
679 }
Thomas Livelya1d97a92019-06-26 16:17:15 +0000680 }
Dan Gohman9cc692b2015-10-02 20:54:23 +0000681
JF Bastiend8a9d662015-08-24 21:59:51 +0000682 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
Thomas Lively649aba92020-02-03 14:37:10 -0800683 if (Ins.size() > 1)
684 fail(DL, DAG, "WebAssembly doesn't support more than 1 returned value yet");
685
Dan Gohman2d822e72015-12-04 17:12:52 +0000686 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
Derek Schuff4dd67782016-01-27 21:17:39 +0000687 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
Keno Fischer5c3cdef2019-08-05 21:36:09 +0000688
689 // The generic code may have added an sret argument. If we're lowering an
690 // invoke function, the ABI requires that the function pointer be the first
691 // argument, so we may have to swap the arguments.
692 if (CallConv == CallingConv::WASM_EmscriptenInvoke && Outs.size() >= 2 &&
693 Outs[0].Flags.isSRet()) {
694 std::swap(Outs[0], Outs[1]);
695 std::swap(OutVals[0], OutVals[1]);
696 }
697
Dan Gohman910ba332018-06-26 03:18:38 +0000698 unsigned NumFixedArgs = 0;
Heejin Ahn18c56a02019-02-04 19:13:39 +0000699 for (unsigned I = 0; I < Outs.size(); ++I) {
700 const ISD::OutputArg &Out = Outs[I];
701 SDValue &OutVal = OutVals[I];
Dan Gohman7935fa32015-12-10 00:22:40 +0000702 if (Out.Flags.isNest())
703 fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
Dan Gohman2d822e72015-12-04 17:12:52 +0000704 if (Out.Flags.isInAlloca())
Dan Gohman7935fa32015-12-10 00:22:40 +0000705 fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
Dan Gohman2d822e72015-12-04 17:12:52 +0000706 if (Out.Flags.isInConsecutiveRegs())
Dan Gohman7935fa32015-12-10 00:22:40 +0000707 fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
Dan Gohman2d822e72015-12-04 17:12:52 +0000708 if (Out.Flags.isInConsecutiveRegsLast())
Dan Gohman7935fa32015-12-10 00:22:40 +0000709 fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
Dan Gohmana6771b32016-02-12 21:30:18 +0000710 if (Out.Flags.isByVal() && Out.Flags.getByValSize() != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +0000711 auto &MFI = MF.getFrameInfo();
712 int FI = MFI.CreateStackObject(Out.Flags.getByValSize(),
Guillaume Chatelet333f2ad2020-02-03 14:49:01 +0100713 Out.Flags.getNonZeroByValAlign(),
Matthias Braun941a7052016-07-28 18:40:00 +0000714 /*isSS=*/false);
Derek Schuff4dd67782016-01-27 21:17:39 +0000715 SDValue SizeNode =
716 DAG.getConstant(Out.Flags.getByValSize(), DL, MVT::i32);
Derek Schuff992d83f2016-02-10 20:14:15 +0000717 SDValue FINode = DAG.getFrameIndex(FI, getPointerTy(Layout));
Derek Schuff4dd67782016-01-27 21:17:39 +0000718 Chain = DAG.getMemcpy(
Guillaume Chatelet333f2ad2020-02-03 14:49:01 +0100719 Chain, DL, FINode, OutVal, SizeNode, Out.Flags.getNonZeroByValAlign(),
Dan Gohman476ffce2016-02-17 01:43:37 +0000720 /*isVolatile*/ false, /*AlwaysInline=*/false,
Derek Schuff4dd67782016-01-27 21:17:39 +0000721 /*isTailCall*/ false, MachinePointerInfo(), MachinePointerInfo());
722 OutVal = FINode;
723 }
Dan Gohman910ba332018-06-26 03:18:38 +0000724 // Count the number of fixed args *after* legalization.
725 NumFixedArgs += Out.IsFixed;
Dan Gohman2d822e72015-12-04 17:12:52 +0000726 }
727
JF Bastiend8a9d662015-08-24 21:59:51 +0000728 bool IsVarArg = CLI.IsVarArg;
Derek Schuff992d83f2016-02-10 20:14:15 +0000729 auto PtrVT = getPointerTy(Layout);
Dan Gohmane590b332015-09-09 01:52:45 +0000730
JF Bastiend8a9d662015-08-24 21:59:51 +0000731 // Analyze operands of the call, assigning locations to each operand.
732 SmallVector<CCValAssign, 16> ArgLocs;
733 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
JF Bastiend8a9d662015-08-24 21:59:51 +0000734
Dan Gohman35bfb242015-12-04 23:22:35 +0000735 if (IsVarArg) {
Derek Schuff27501e22016-02-10 19:51:04 +0000736 // Outgoing non-fixed arguments are placed in a buffer. First
737 // compute their offsets and the total amount of buffer space needed.
Dan Gohmanc71132c2019-02-26 05:20:19 +0000738 for (unsigned I = NumFixedArgs; I < Outs.size(); ++I) {
739 const ISD::OutputArg &Out = Outs[I];
740 SDValue &Arg = OutVals[I];
Dan Gohman35bfb242015-12-04 23:22:35 +0000741 EVT VT = Arg.getValueType();
742 assert(VT != MVT::iPTR && "Legalized args should be concrete");
743 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
Dan Gohmanc71132c2019-02-26 05:20:19 +0000744 unsigned Align = std::max(Out.Flags.getOrigAlign(),
745 Layout.getABITypeAlignment(Ty));
Derek Schuff992d83f2016-02-10 20:14:15 +0000746 unsigned Offset = CCInfo.AllocateStack(Layout.getTypeAllocSize(Ty),
Dan Gohmanc71132c2019-02-26 05:20:19 +0000747 Align);
Dan Gohman35bfb242015-12-04 23:22:35 +0000748 CCInfo.addLoc(CCValAssign::getMem(ArgLocs.size(), VT.getSimpleVT(),
749 Offset, VT.getSimpleVT(),
750 CCValAssign::Full));
751 }
752 }
753
754 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
755
Derek Schuff27501e22016-02-10 19:51:04 +0000756 SDValue FINode;
757 if (IsVarArg && NumBytes) {
Dan Gohman35bfb242015-12-04 23:22:35 +0000758 // For non-fixed arguments, next emit stores to store the argument values
Derek Schuff27501e22016-02-10 19:51:04 +0000759 // to the stack buffer at the offsets computed above.
Matthias Braun941a7052016-07-28 18:40:00 +0000760 int FI = MF.getFrameInfo().CreateStackObject(NumBytes,
761 Layout.getStackAlignment(),
762 /*isSS=*/false);
Dan Gohman35bfb242015-12-04 23:22:35 +0000763 unsigned ValNo = 0;
764 SmallVector<SDValue, 8> Chains;
765 for (SDValue Arg :
766 make_range(OutVals.begin() + NumFixedArgs, OutVals.end())) {
767 assert(ArgLocs[ValNo].getValNo() == ValNo &&
768 "ArgLocs should remain in order and only hold varargs args");
769 unsigned Offset = ArgLocs[ValNo++].getLocMemOffset();
Derek Schuff992d83f2016-02-10 20:14:15 +0000770 FINode = DAG.getFrameIndex(FI, getPointerTy(Layout));
Derek Schuff27501e22016-02-10 19:51:04 +0000771 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, FINode,
Dan Gohman35bfb242015-12-04 23:22:35 +0000772 DAG.getConstant(Offset, DL, PtrVT));
Heejin Ahnf208f632018-09-05 01:27:38 +0000773 Chains.push_back(
774 DAG.getStore(Chain, DL, Arg, Add,
775 MachinePointerInfo::getFixedStack(MF, FI, Offset), 0));
Dan Gohman35bfb242015-12-04 23:22:35 +0000776 }
777 if (!Chains.empty())
778 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
Derek Schuff27501e22016-02-10 19:51:04 +0000779 } else if (IsVarArg) {
780 FINode = DAG.getIntPtrConstant(0, DL);
Dan Gohman35bfb242015-12-04 23:22:35 +0000781 }
782
Sam Clegg492f7522019-03-26 19:46:15 +0000783 if (Callee->getOpcode() == ISD::GlobalAddress) {
784 // If the callee is a GlobalAddress node (quite common, every direct call
785 // is) turn it into a TargetGlobalAddress node so that LowerGlobalAddress
786 // doesn't at MO_GOT which is not needed for direct calls.
787 GlobalAddressSDNode* GA = cast<GlobalAddressSDNode>(Callee);
788 Callee = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
789 getPointerTy(DAG.getDataLayout()),
790 GA->getOffset());
791 Callee = DAG.getNode(WebAssemblyISD::Wrapper, DL,
792 getPointerTy(DAG.getDataLayout()), Callee);
793 }
794
Dan Gohman35bfb242015-12-04 23:22:35 +0000795 // Compute the operands for the CALLn node.
JF Bastiend8a9d662015-08-24 21:59:51 +0000796 SmallVector<SDValue, 16> Ops;
797 Ops.push_back(Chain);
JF Bastienaf111db2015-08-24 22:16:48 +0000798 Ops.push_back(Callee);
Dan Gohman35bfb242015-12-04 23:22:35 +0000799
800 // Add all fixed arguments. Note that for non-varargs calls, NumFixedArgs
801 // isn't reliable.
802 Ops.append(OutVals.begin(),
803 IsVarArg ? OutVals.begin() + NumFixedArgs : OutVals.end());
Derek Schuff27501e22016-02-10 19:51:04 +0000804 // Add a pointer to the vararg buffer.
Heejin Ahnf208f632018-09-05 01:27:38 +0000805 if (IsVarArg)
806 Ops.push_back(FINode);
JF Bastiend8a9d662015-08-24 21:59:51 +0000807
Derek Schuff27501e22016-02-10 19:51:04 +0000808 SmallVector<EVT, 8> InTys;
Dan Gohman2d822e72015-12-04 17:12:52 +0000809 for (const auto &In : Ins) {
Dan Gohman7935fa32015-12-10 00:22:40 +0000810 assert(!In.Flags.isByVal() && "byval is not valid for return values");
811 assert(!In.Flags.isNest() && "nest is not valid for return values");
Dan Gohman2d822e72015-12-04 17:12:52 +0000812 if (In.Flags.isInAlloca())
Dan Gohman7935fa32015-12-10 00:22:40 +0000813 fail(DL, DAG, "WebAssembly hasn't implemented inalloca return values");
Dan Gohman2d822e72015-12-04 17:12:52 +0000814 if (In.Flags.isInConsecutiveRegs())
Dan Gohman7935fa32015-12-10 00:22:40 +0000815 fail(DL, DAG, "WebAssembly hasn't implemented cons regs return values");
Dan Gohman2d822e72015-12-04 17:12:52 +0000816 if (In.Flags.isInConsecutiveRegsLast())
Dan Gohman4b9d7912015-12-15 22:01:29 +0000817 fail(DL, DAG,
818 "WebAssembly hasn't implemented cons regs last return values");
Dan Gohman2d822e72015-12-04 17:12:52 +0000819 // Ignore In.getOrigAlign() because all our arguments are passed in
820 // registers.
Derek Schuff27501e22016-02-10 19:51:04 +0000821 InTys.push_back(In.VT);
Dan Gohman2d822e72015-12-04 17:12:52 +0000822 }
Thomas Livelya1d97a92019-06-26 16:17:15 +0000823
824 if (CLI.IsTailCall) {
825 // ret_calls do not return values to the current frame
826 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
827 return DAG.getNode(WebAssemblyISD::RET_CALL, DL, NodeTys, Ops);
828 }
829
Derek Schuff27501e22016-02-10 19:51:04 +0000830 InTys.push_back(MVT::Other);
Thomas Lively3ef169e2019-12-13 10:41:25 -0800831 SDVTList InTyList = DAG.getVTList(InTys);
Thomas Lively649aba92020-02-03 14:37:10 -0800832 SDValue Res =
833 DAG.getNode(Ins.empty() ? WebAssemblyISD::CALL0 : WebAssemblyISD::CALL1,
834 DL, InTyList, Ops);
835 if (Ins.empty()) {
836 Chain = Res;
837 } else {
838 InVals.push_back(Res);
839 Chain = Res.getValue(1);
840 }
JF Bastiend8a9d662015-08-24 21:59:51 +0000841
Thomas Lively649aba92020-02-03 14:37:10 -0800842 return Chain;
JF Bastiend8a9d662015-08-24 21:59:51 +0000843}
844
JF Bastienb9073fb2015-07-22 21:28:15 +0000845bool WebAssemblyTargetLowering::CanLowerReturn(
Dan Gohman7a6b9822015-11-29 22:32:02 +0000846 CallingConv::ID /*CallConv*/, MachineFunction & /*MF*/, bool /*IsVarArg*/,
847 const SmallVectorImpl<ISD::OutputArg> &Outs,
848 LLVMContext & /*Context*/) const {
Thomas Lively00f9e5a2019-10-09 21:42:08 +0000849 // WebAssembly can only handle returning tuples with multivalue enabled
850 return Subtarget->hasMultivalue() || Outs.size() <= 1;
JF Bastienb9073fb2015-07-22 21:28:15 +0000851}
852
853SDValue WebAssemblyTargetLowering::LowerReturn(
Dan Gohman35bfb242015-12-04 23:22:35 +0000854 SDValue Chain, CallingConv::ID CallConv, bool /*IsVarArg*/,
JF Bastienb9073fb2015-07-22 21:28:15 +0000855 const SmallVectorImpl<ISD::OutputArg> &Outs,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000856 const SmallVectorImpl<SDValue> &OutVals, const SDLoc &DL,
JF Bastienb9073fb2015-07-22 21:28:15 +0000857 SelectionDAG &DAG) const {
Simon Pilgrim788ba152019-10-10 12:21:52 +0000858 assert((Subtarget->hasMultivalue() || Outs.size() <= 1) &&
859 "MVP WebAssembly can only return up to one value");
Heejin Ahn18c56a02019-02-04 19:13:39 +0000860 if (!callingConvSupported(CallConv))
JF Bastienb9073fb2015-07-22 21:28:15 +0000861 fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
862
JF Bastien600aee92015-07-31 17:53:38 +0000863 SmallVector<SDValue, 4> RetOps(1, Chain);
864 RetOps.append(OutVals.begin(), OutVals.end());
JF Bastien4a2d5602015-07-31 21:04:18 +0000865 Chain = DAG.getNode(WebAssemblyISD::RETURN, DL, MVT::Other, RetOps);
JF Bastienb9073fb2015-07-22 21:28:15 +0000866
Dan Gohman754cd112015-11-11 01:33:02 +0000867 // Record the number and types of the return values.
868 for (const ISD::OutputArg &Out : Outs) {
Dan Gohmanac132e92015-12-02 23:40:03 +0000869 assert(!Out.Flags.isByVal() && "byval is not valid for return values");
870 assert(!Out.Flags.isNest() && "nest is not valid for return values");
Dan Gohman35bfb242015-12-04 23:22:35 +0000871 assert(Out.IsFixed && "non-fixed return value is not valid");
Dan Gohman754cd112015-11-11 01:33:02 +0000872 if (Out.Flags.isInAlloca())
873 fail(DL, DAG, "WebAssembly hasn't implemented inalloca results");
Dan Gohman754cd112015-11-11 01:33:02 +0000874 if (Out.Flags.isInConsecutiveRegs())
875 fail(DL, DAG, "WebAssembly hasn't implemented cons regs results");
876 if (Out.Flags.isInConsecutiveRegsLast())
877 fail(DL, DAG, "WebAssembly hasn't implemented cons regs last results");
Dan Gohman754cd112015-11-11 01:33:02 +0000878 }
879
JF Bastienb9073fb2015-07-22 21:28:15 +0000880 return Chain;
881}
882
883SDValue WebAssemblyTargetLowering::LowerFormalArguments(
Derek Schuff27501e22016-02-10 19:51:04 +0000884 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000885 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
886 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
Heejin Ahn18c56a02019-02-04 19:13:39 +0000887 if (!callingConvSupported(CallConv))
JF Bastienb9073fb2015-07-22 21:28:15 +0000888 fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
JF Bastienb9073fb2015-07-22 21:28:15 +0000889
Dan Gohman2726b882016-10-06 22:29:32 +0000890 MachineFunction &MF = DAG.getMachineFunction();
891 auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>();
892
Dan Gohmanfb3e0592015-11-25 19:36:19 +0000893 // Set up the incoming ARGUMENTS value, which serves to represent the liveness
894 // of the incoming values before they're represented by virtual registers.
895 MF.getRegInfo().addLiveIn(WebAssembly::ARGUMENTS);
896
JF Bastien600aee92015-07-31 17:53:38 +0000897 for (const ISD::InputArg &In : Ins) {
JF Bastien600aee92015-07-31 17:53:38 +0000898 if (In.Flags.isInAlloca())
899 fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
900 if (In.Flags.isNest())
901 fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
JF Bastien600aee92015-07-31 17:53:38 +0000902 if (In.Flags.isInConsecutiveRegs())
903 fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
904 if (In.Flags.isInConsecutiveRegsLast())
905 fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
Dan Gohman9c54d3b2015-11-25 18:13:18 +0000906 // Ignore In.getOrigAlign() because all our arguments are passed in
907 // registers.
Heejin Ahnf208f632018-09-05 01:27:38 +0000908 InVals.push_back(In.Used ? DAG.getNode(WebAssemblyISD::ARGUMENT, DL, In.VT,
909 DAG.getTargetConstant(InVals.size(),
910 DL, MVT::i32))
911 : DAG.getUNDEF(In.VT));
Dan Gohman754cd112015-11-11 01:33:02 +0000912
913 // Record the number and types of arguments.
Derek Schuff27501e22016-02-10 19:51:04 +0000914 MFI->addParam(In.VT);
JF Bastien600aee92015-07-31 17:53:38 +0000915 }
JF Bastienb9073fb2015-07-22 21:28:15 +0000916
Derek Schuff27501e22016-02-10 19:51:04 +0000917 // Varargs are copied into a buffer allocated by the caller, and a pointer to
918 // the buffer is passed as an argument.
919 if (IsVarArg) {
920 MVT PtrVT = getPointerTy(MF.getDataLayout());
Daniel Sanders05c145d2019-08-12 22:40:45 +0000921 Register VarargVreg =
Derek Schuff27501e22016-02-10 19:51:04 +0000922 MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrVT));
923 MFI->setVarargBufferVreg(VarargVreg);
924 Chain = DAG.getCopyToReg(
925 Chain, DL, VarargVreg,
926 DAG.getNode(WebAssemblyISD::ARGUMENT, DL, PtrVT,
927 DAG.getTargetConstant(Ins.size(), DL, MVT::i32)));
928 MFI->addParam(PtrVT);
929 }
Dan Gohman35bfb242015-12-04 23:22:35 +0000930
Derek Schuff77a7a382018-10-03 22:22:48 +0000931 // Record the number and types of arguments and results.
Dan Gohman2726b882016-10-06 22:29:32 +0000932 SmallVector<MVT, 4> Params;
933 SmallVector<MVT, 4> Results;
Heejin Ahn18c56a02019-02-04 19:13:39 +0000934 computeSignatureVTs(MF.getFunction().getFunctionType(), MF.getFunction(),
Derek Schuff77a7a382018-10-03 22:22:48 +0000935 DAG.getTarget(), Params, Results);
Dan Gohman2726b882016-10-06 22:29:32 +0000936 for (MVT VT : Results)
937 MFI->addResult(VT);
Derek Schuff77a7a382018-10-03 22:22:48 +0000938 // TODO: Use signatures in WebAssemblyMachineFunctionInfo too and unify
939 // the param logic here with ComputeSignatureVTs
940 assert(MFI->getParams().size() == Params.size() &&
941 std::equal(MFI->getParams().begin(), MFI->getParams().end(),
942 Params.begin()));
Dan Gohman2726b882016-10-06 22:29:32 +0000943
JF Bastienb9073fb2015-07-22 21:28:15 +0000944 return Chain;
945}
946
Thomas Livelye18b5c62019-05-23 18:09:26 +0000947void WebAssemblyTargetLowering::ReplaceNodeResults(
948 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
949 switch (N->getOpcode()) {
950 case ISD::SIGN_EXTEND_INREG:
951 // Do not add any results, signifying that N should not be custom lowered
952 // after all. This happens because simd128 turns on custom lowering for
953 // SIGN_EXTEND_INREG, but for non-vector sign extends the result might be an
954 // illegal type.
955 break;
956 default:
957 llvm_unreachable(
958 "ReplaceNodeResults not implemented for this op for WebAssembly!");
959 }
960}
961
Dan Gohman10e730a2015-06-29 23:51:55 +0000962//===----------------------------------------------------------------------===//
JF Bastienaf111db2015-08-24 22:16:48 +0000963// Custom lowering hooks.
Dan Gohman10e730a2015-06-29 23:51:55 +0000964//===----------------------------------------------------------------------===//
965
JF Bastienaf111db2015-08-24 22:16:48 +0000966SDValue WebAssemblyTargetLowering::LowerOperation(SDValue Op,
967 SelectionDAG &DAG) const {
Derek Schuff51699a82016-02-12 22:56:03 +0000968 SDLoc DL(Op);
JF Bastienaf111db2015-08-24 22:16:48 +0000969 switch (Op.getOpcode()) {
Heejin Ahnf208f632018-09-05 01:27:38 +0000970 default:
971 llvm_unreachable("unimplemented operation lowering");
972 return SDValue();
973 case ISD::FrameIndex:
974 return LowerFrameIndex(Op, DAG);
975 case ISD::GlobalAddress:
976 return LowerGlobalAddress(Op, DAG);
977 case ISD::ExternalSymbol:
978 return LowerExternalSymbol(Op, DAG);
979 case ISD::JumpTable:
980 return LowerJumpTable(Op, DAG);
981 case ISD::BR_JT:
982 return LowerBR_JT(Op, DAG);
983 case ISD::VASTART:
984 return LowerVASTART(Op, DAG);
985 case ISD::BlockAddress:
986 case ISD::BRIND:
987 fail(DL, DAG, "WebAssembly hasn't implemented computed gotos");
988 return SDValue();
Thomas Lively1a3cbe72019-05-23 01:24:01 +0000989 case ISD::RETURNADDR:
990 return LowerRETURNADDR(Op, DAG);
Heejin Ahnf208f632018-09-05 01:27:38 +0000991 case ISD::FRAMEADDR:
992 return LowerFRAMEADDR(Op, DAG);
993 case ISD::CopyToReg:
994 return LowerCopyToReg(Op, DAG);
Thomas Livelyfb84fd72018-11-02 00:06:56 +0000995 case ISD::EXTRACT_VECTOR_ELT:
996 case ISD::INSERT_VECTOR_ELT:
997 return LowerAccessVectorElement(Op, DAG);
Heejin Ahnda419bd2018-11-14 02:46:21 +0000998 case ISD::INTRINSIC_VOID:
Heejin Ahnd6f48782019-01-30 03:21:57 +0000999 case ISD::INTRINSIC_WO_CHAIN:
1000 case ISD::INTRINSIC_W_CHAIN:
1001 return LowerIntrinsic(Op, DAG);
Thomas Lively64a39a12019-01-10 22:32:11 +00001002 case ISD::SIGN_EXTEND_INREG:
1003 return LowerSIGN_EXTEND_INREG(Op, DAG);
Thomas Lively079816e2019-01-30 02:23:29 +00001004 case ISD::BUILD_VECTOR:
1005 return LowerBUILD_VECTOR(Op, DAG);
Thomas Livelya0d25812018-09-07 21:54:46 +00001006 case ISD::VECTOR_SHUFFLE:
1007 return LowerVECTOR_SHUFFLE(Op, DAG);
Thomas Livelyecb7daf2019-11-01 10:21:00 -07001008 case ISD::SETCC:
1009 return LowerSETCC(Op, DAG);
Thomas Lively55735d52018-10-20 01:31:18 +00001010 case ISD::SHL:
1011 case ISD::SRA:
1012 case ISD::SRL:
1013 return LowerShift(Op, DAG);
JF Bastienaf111db2015-08-24 22:16:48 +00001014 }
1015}
1016
Derek Schuffaadc89c2016-02-16 18:18:36 +00001017SDValue WebAssemblyTargetLowering::LowerCopyToReg(SDValue Op,
1018 SelectionDAG &DAG) const {
1019 SDValue Src = Op.getOperand(2);
1020 if (isa<FrameIndexSDNode>(Src.getNode())) {
1021 // CopyToReg nodes don't support FrameIndex operands. Other targets select
1022 // the FI to some LEA-like instruction, but since we don't have that, we
1023 // need to insert some kind of instruction that can take an FI operand and
1024 // produces a value usable by CopyToReg (i.e. in a vreg). So insert a dummy
Thomas Lively6a87dda2019-01-08 06:25:55 +00001025 // local.copy between Op and its FI operand.
Dan Gohman02c08712016-02-20 23:09:44 +00001026 SDValue Chain = Op.getOperand(0);
Derek Schuffaadc89c2016-02-16 18:18:36 +00001027 SDLoc DL(Op);
Dan Gohman02c08712016-02-20 23:09:44 +00001028 unsigned Reg = cast<RegisterSDNode>(Op.getOperand(1))->getReg();
Derek Schuffaadc89c2016-02-16 18:18:36 +00001029 EVT VT = Src.getValueType();
Heejin Ahnf208f632018-09-05 01:27:38 +00001030 SDValue Copy(DAG.getMachineNode(VT == MVT::i32 ? WebAssembly::COPY_I32
1031 : WebAssembly::COPY_I64,
1032 DL, VT, Src),
1033 0);
Dan Gohman02c08712016-02-20 23:09:44 +00001034 return Op.getNode()->getNumValues() == 1
1035 ? DAG.getCopyToReg(Chain, DL, Reg, Copy)
Heejin Ahnf208f632018-09-05 01:27:38 +00001036 : DAG.getCopyToReg(Chain, DL, Reg, Copy,
1037 Op.getNumOperands() == 4 ? Op.getOperand(3)
1038 : SDValue());
Derek Schuffaadc89c2016-02-16 18:18:36 +00001039 }
1040 return SDValue();
1041}
1042
Derek Schuff9769deb2015-12-11 23:49:46 +00001043SDValue WebAssemblyTargetLowering::LowerFrameIndex(SDValue Op,
1044 SelectionDAG &DAG) const {
1045 int FI = cast<FrameIndexSDNode>(Op)->getIndex();
1046 return DAG.getTargetFrameIndex(FI, Op.getValueType());
1047}
1048
Thomas Lively1a3cbe72019-05-23 01:24:01 +00001049SDValue WebAssemblyTargetLowering::LowerRETURNADDR(SDValue Op,
1050 SelectionDAG &DAG) const {
1051 SDLoc DL(Op);
1052
1053 if (!Subtarget->getTargetTriple().isOSEmscripten()) {
1054 fail(DL, DAG,
1055 "Non-Emscripten WebAssembly hasn't implemented "
1056 "__builtin_return_address");
1057 return SDValue();
1058 }
1059
1060 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1061 return SDValue();
1062
1063 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
Shiva Chen72a41e72019-08-22 04:59:43 +00001064 MakeLibCallOptions CallOptions;
Thomas Lively1a3cbe72019-05-23 01:24:01 +00001065 return makeLibCall(DAG, RTLIB::RETURN_ADDRESS, Op.getValueType(),
Shiva Chen72a41e72019-08-22 04:59:43 +00001066 {DAG.getConstant(Depth, DL, MVT::i32)}, CallOptions, DL)
Thomas Lively1a3cbe72019-05-23 01:24:01 +00001067 .first;
1068}
1069
Dan Gohman94c65662016-02-16 23:48:04 +00001070SDValue WebAssemblyTargetLowering::LowerFRAMEADDR(SDValue Op,
1071 SelectionDAG &DAG) const {
1072 // Non-zero depths are not supported by WebAssembly currently. Use the
1073 // legalizer's default expansion, which is to return 0 (what this function is
1074 // documented to do).
Dan Gohman1d547bf2016-02-17 00:14:03 +00001075 if (Op.getConstantOperandVal(0) > 0)
Dan Gohman94c65662016-02-16 23:48:04 +00001076 return SDValue();
1077
Matthias Braun941a7052016-07-28 18:40:00 +00001078 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
Dan Gohman94c65662016-02-16 23:48:04 +00001079 EVT VT = Op.getValueType();
Daniel Sanders05c145d2019-08-12 22:40:45 +00001080 Register FP =
Dan Gohman94c65662016-02-16 23:48:04 +00001081 Subtarget->getRegisterInfo()->getFrameRegister(DAG.getMachineFunction());
1082 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), FP, VT);
1083}
1084
JF Bastienaf111db2015-08-24 22:16:48 +00001085SDValue WebAssemblyTargetLowering::LowerGlobalAddress(SDValue Op,
1086 SelectionDAG &DAG) const {
1087 SDLoc DL(Op);
1088 const auto *GA = cast<GlobalAddressSDNode>(Op);
1089 EVT VT = Op.getValueType();
Dan Gohman26c67652016-01-11 23:38:05 +00001090 assert(GA->getTargetFlags() == 0 &&
1091 "Unexpected target flags on generic GlobalAddressSDNode");
JF Bastienaf111db2015-08-24 22:16:48 +00001092 if (GA->getAddressSpace() != 0)
1093 fail(DL, DAG, "WebAssembly only expects the 0 address space");
Sam Clegg492f7522019-03-26 19:46:15 +00001094
Sam Cleggef4c66c2019-04-03 00:17:29 +00001095 unsigned OperandFlags = 0;
Sam Clegg492f7522019-03-26 19:46:15 +00001096 if (isPositionIndependent()) {
1097 const GlobalValue *GV = GA->getGlobal();
1098 if (getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) {
1099 MachineFunction &MF = DAG.getMachineFunction();
1100 MVT PtrVT = getPointerTy(MF.getDataLayout());
1101 const char *BaseName;
Sam Clegg2a7cac92019-04-04 17:43:50 +00001102 if (GV->getValueType()->isFunctionTy()) {
Sam Clegg492f7522019-03-26 19:46:15 +00001103 BaseName = MF.createExternalSymbolName("__table_base");
Sam Clegg2a7cac92019-04-04 17:43:50 +00001104 OperandFlags = WebAssemblyII::MO_TABLE_BASE_REL;
1105 }
1106 else {
Sam Clegg492f7522019-03-26 19:46:15 +00001107 BaseName = MF.createExternalSymbolName("__memory_base");
Sam Clegg2a7cac92019-04-04 17:43:50 +00001108 OperandFlags = WebAssemblyII::MO_MEMORY_BASE_REL;
1109 }
Sam Clegg492f7522019-03-26 19:46:15 +00001110 SDValue BaseAddr =
1111 DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT,
1112 DAG.getTargetExternalSymbol(BaseName, PtrVT));
1113
1114 SDValue SymAddr = DAG.getNode(
1115 WebAssemblyISD::WrapperPIC, DL, VT,
Sam Clegg2a7cac92019-04-04 17:43:50 +00001116 DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT, GA->getOffset(),
1117 OperandFlags));
Sam Clegg492f7522019-03-26 19:46:15 +00001118
1119 return DAG.getNode(ISD::ADD, DL, VT, BaseAddr, SymAddr);
1120 } else {
Sam Cleggef4c66c2019-04-03 00:17:29 +00001121 OperandFlags = WebAssemblyII::MO_GOT;
Sam Clegg492f7522019-03-26 19:46:15 +00001122 }
1123 }
1124
1125 return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1126 DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT,
Sam Cleggef4c66c2019-04-03 00:17:29 +00001127 GA->getOffset(), OperandFlags));
JF Bastienaf111db2015-08-24 22:16:48 +00001128}
1129
Heejin Ahnf208f632018-09-05 01:27:38 +00001130SDValue
1131WebAssemblyTargetLowering::LowerExternalSymbol(SDValue Op,
1132 SelectionDAG &DAG) const {
Dan Gohman2c8fe6a2015-11-25 16:44:29 +00001133 SDLoc DL(Op);
1134 const auto *ES = cast<ExternalSymbolSDNode>(Op);
1135 EVT VT = Op.getValueType();
Dan Gohman26c67652016-01-11 23:38:05 +00001136 assert(ES->getTargetFlags() == 0 &&
1137 "Unexpected target flags on generic ExternalSymbolSDNode");
Sam Cleggef4c66c2019-04-03 00:17:29 +00001138 return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1139 DAG.getTargetExternalSymbol(ES->getSymbol(), VT));
Dan Gohman2c8fe6a2015-11-25 16:44:29 +00001140}
1141
Dan Gohman950a13c2015-09-16 16:51:30 +00001142SDValue WebAssemblyTargetLowering::LowerJumpTable(SDValue Op,
1143 SelectionDAG &DAG) const {
1144 // There's no need for a Wrapper node because we always incorporate a jump
Dan Gohman14026062016-03-08 03:18:12 +00001145 // table operand into a BR_TABLE instruction, rather than ever
Dan Gohmanbb7ce8e2015-11-20 03:02:49 +00001146 // materializing it in a register.
Dan Gohman950a13c2015-09-16 16:51:30 +00001147 const JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1148 return DAG.getTargetJumpTable(JT->getIndex(), Op.getValueType(),
1149 JT->getTargetFlags());
1150}
1151
1152SDValue WebAssemblyTargetLowering::LowerBR_JT(SDValue Op,
1153 SelectionDAG &DAG) const {
1154 SDLoc DL(Op);
1155 SDValue Chain = Op.getOperand(0);
1156 const auto *JT = cast<JumpTableSDNode>(Op.getOperand(1));
1157 SDValue Index = Op.getOperand(2);
1158 assert(JT->getTargetFlags() == 0 && "WebAssembly doesn't set target flags");
1159
1160 SmallVector<SDValue, 8> Ops;
1161 Ops.push_back(Chain);
1162 Ops.push_back(Index);
1163
1164 MachineJumpTableInfo *MJTI = DAG.getMachineFunction().getJumpTableInfo();
1165 const auto &MBBs = MJTI->getJumpTables()[JT->getIndex()].MBBs;
1166
Dan Gohman14026062016-03-08 03:18:12 +00001167 // Add an operand for each case.
Heejin Ahnf208f632018-09-05 01:27:38 +00001168 for (auto MBB : MBBs)
1169 Ops.push_back(DAG.getBasicBlock(MBB));
Dan Gohman14026062016-03-08 03:18:12 +00001170
Dan Gohman950a13c2015-09-16 16:51:30 +00001171 // TODO: For now, we just pick something arbitrary for a default case for now.
1172 // We really want to sniff out the guard and put in the real default case (and
1173 // delete the guard).
1174 Ops.push_back(DAG.getBasicBlock(MBBs[0]));
1175
Dan Gohman14026062016-03-08 03:18:12 +00001176 return DAG.getNode(WebAssemblyISD::BR_TABLE, DL, MVT::Other, Ops);
Dan Gohman950a13c2015-09-16 16:51:30 +00001177}
1178
Dan Gohman35bfb242015-12-04 23:22:35 +00001179SDValue WebAssemblyTargetLowering::LowerVASTART(SDValue Op,
1180 SelectionDAG &DAG) const {
1181 SDLoc DL(Op);
1182 EVT PtrVT = getPointerTy(DAG.getMachineFunction().getDataLayout());
1183
Derek Schuff27501e22016-02-10 19:51:04 +00001184 auto *MFI = DAG.getMachineFunction().getInfo<WebAssemblyFunctionInfo>();
Dan Gohman35bfb242015-12-04 23:22:35 +00001185 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
Derek Schuff27501e22016-02-10 19:51:04 +00001186
1187 SDValue ArgN = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1188 MFI->getVarargBufferVreg(), PtrVT);
1189 return DAG.getStore(Op.getOperand(0), DL, ArgN, Op.getOperand(1),
Derek Schuff1a946e42016-07-15 19:35:43 +00001190 MachinePointerInfo(SV), 0);
Dan Gohman35bfb242015-12-04 23:22:35 +00001191}
1192
Heejin Ahnd6f48782019-01-30 03:21:57 +00001193SDValue WebAssemblyTargetLowering::LowerIntrinsic(SDValue Op,
1194 SelectionDAG &DAG) const {
1195 MachineFunction &MF = DAG.getMachineFunction();
1196 unsigned IntNo;
1197 switch (Op.getOpcode()) {
1198 case ISD::INTRINSIC_VOID:
1199 case ISD::INTRINSIC_W_CHAIN:
1200 IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1201 break;
1202 case ISD::INTRINSIC_WO_CHAIN:
1203 IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1204 break;
1205 default:
1206 llvm_unreachable("Invalid intrinsic");
1207 }
Heejin Ahn5ef4d5f2018-05-31 22:25:54 +00001208 SDLoc DL(Op);
Heejin Ahnd6f48782019-01-30 03:21:57 +00001209
Heejin Ahn5ef4d5f2018-05-31 22:25:54 +00001210 switch (IntNo) {
1211 default:
Heejin Ahn18c56a02019-02-04 19:13:39 +00001212 return SDValue(); // Don't custom lower most intrinsics.
Thomas Lively5d461c92018-10-03 23:02:23 +00001213
Heejin Ahn24faf852018-10-25 23:55:10 +00001214 case Intrinsic::wasm_lsda: {
Heejin Ahn24faf852018-10-25 23:55:10 +00001215 EVT VT = Op.getValueType();
1216 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1217 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
1218 auto &Context = MF.getMMI().getContext();
1219 MCSymbol *S = Context.getOrCreateSymbol(Twine("GCC_except_table") +
1220 Twine(MF.getFunctionNumber()));
1221 return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1222 DAG.getMCSymbol(S, PtrVT));
1223 }
Heejin Ahnda419bd2018-11-14 02:46:21 +00001224
1225 case Intrinsic::wasm_throw: {
Heejin Ahnd6f48782019-01-30 03:21:57 +00001226 // We only support C++ exceptions for now
Heejin Ahnda419bd2018-11-14 02:46:21 +00001227 int Tag = cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue();
Heejin Ahnd6f48782019-01-30 03:21:57 +00001228 if (Tag != CPP_EXCEPTION)
Heejin Ahnda419bd2018-11-14 02:46:21 +00001229 llvm_unreachable("Invalid tag!");
Heejin Ahnd6f48782019-01-30 03:21:57 +00001230 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1231 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
1232 const char *SymName = MF.createExternalSymbolName("__cpp_exception");
Sam Cleggef4c66c2019-04-03 00:17:29 +00001233 SDValue SymNode = DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT,
1234 DAG.getTargetExternalSymbol(SymName, PtrVT));
Heejin Ahnd6f48782019-01-30 03:21:57 +00001235 return DAG.getNode(WebAssemblyISD::THROW, DL,
1236 MVT::Other, // outchain type
1237 {
1238 Op.getOperand(0), // inchain
1239 SymNode, // exception symbol
1240 Op.getOperand(3) // thrown value
1241 });
Heejin Ahnda419bd2018-11-14 02:46:21 +00001242 }
1243 }
1244}
1245
1246SDValue
Thomas Lively64a39a12019-01-10 22:32:11 +00001247WebAssemblyTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
1248 SelectionDAG &DAG) const {
Thomas Lively3d9ca002019-06-04 21:08:20 +00001249 SDLoc DL(Op);
Thomas Lively64a39a12019-01-10 22:32:11 +00001250 // If sign extension operations are disabled, allow sext_inreg only if operand
1251 // is a vector extract. SIMD does not depend on sign extension operations, but
1252 // allowing sext_inreg in this context lets us have simple patterns to select
1253 // extract_lane_s instructions. Expanding sext_inreg everywhere would be
1254 // simpler in this file, but would necessitate large and brittle patterns to
1255 // undo the expansion and select extract_lane_s instructions.
1256 assert(!Subtarget->hasSignExt() && Subtarget->hasSIMD128());
Thomas Lively3d9ca002019-06-04 21:08:20 +00001257 if (Op.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
1258 const SDValue &Extract = Op.getOperand(0);
1259 MVT VecT = Extract.getOperand(0).getSimpleValueType();
1260 MVT ExtractedLaneT = static_cast<VTSDNode *>(Op.getOperand(1).getNode())
1261 ->getVT()
1262 .getSimpleVT();
1263 MVT ExtractedVecT =
1264 MVT::getVectorVT(ExtractedLaneT, 128 / ExtractedLaneT.getSizeInBits());
1265 if (ExtractedVecT == VecT)
1266 return Op;
1267 // Bitcast vector to appropriate type to ensure ISel pattern coverage
1268 const SDValue &Index = Extract.getOperand(1);
1269 unsigned IndexVal =
1270 static_cast<ConstantSDNode *>(Index.getNode())->getZExtValue();
1271 unsigned Scale =
1272 ExtractedVecT.getVectorNumElements() / VecT.getVectorNumElements();
1273 assert(Scale > 1);
1274 SDValue NewIndex =
1275 DAG.getConstant(IndexVal * Scale, DL, Index.getValueType());
1276 SDValue NewExtract = DAG.getNode(
1277 ISD::EXTRACT_VECTOR_ELT, DL, Extract.getValueType(),
1278 DAG.getBitcast(ExtractedVecT, Extract.getOperand(0)), NewIndex);
1279 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, Op.getValueType(),
1280 NewExtract, Op.getOperand(1));
1281 }
Thomas Lively64a39a12019-01-10 22:32:11 +00001282 // Otherwise expand
1283 return SDValue();
1284}
1285
Thomas Lively079816e2019-01-30 02:23:29 +00001286SDValue WebAssemblyTargetLowering::LowerBUILD_VECTOR(SDValue Op,
1287 SelectionDAG &DAG) const {
1288 SDLoc DL(Op);
1289 const EVT VecT = Op.getValueType();
1290 const EVT LaneT = Op.getOperand(0).getValueType();
1291 const size_t Lanes = Op.getNumOperands();
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001292 bool CanSwizzle = Subtarget->hasUnimplementedSIMD128() && VecT == MVT::v16i8;
1293
1294 // BUILD_VECTORs are lowered to the instruction that initializes the highest
1295 // possible number of lanes at once followed by a sequence of replace_lane
1296 // instructions to individually initialize any remaining lanes.
1297
1298 // TODO: Tune this. For example, lanewise swizzling is very expensive, so
1299 // swizzled lanes should be given greater weight.
1300
1301 // TODO: Investigate building vectors by shuffling together vectors built by
1302 // separately specialized means.
1303
Thomas Lively079816e2019-01-30 02:23:29 +00001304 auto IsConstant = [](const SDValue &V) {
1305 return V.getOpcode() == ISD::Constant || V.getOpcode() == ISD::ConstantFP;
1306 };
1307
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001308 // Returns the source vector and index vector pair if they exist. Checks for:
1309 // (extract_vector_elt
1310 // $src,
1311 // (sign_extend_inreg (extract_vector_elt $indices, $i))
1312 // )
1313 auto GetSwizzleSrcs = [](size_t I, const SDValue &Lane) {
1314 auto Bail = std::make_pair(SDValue(), SDValue());
1315 if (Lane->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1316 return Bail;
1317 const SDValue &SwizzleSrc = Lane->getOperand(0);
1318 const SDValue &IndexExt = Lane->getOperand(1);
1319 if (IndexExt->getOpcode() != ISD::SIGN_EXTEND_INREG)
1320 return Bail;
1321 const SDValue &Index = IndexExt->getOperand(0);
1322 if (Index->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1323 return Bail;
1324 const SDValue &SwizzleIndices = Index->getOperand(0);
1325 if (SwizzleSrc.getValueType() != MVT::v16i8 ||
1326 SwizzleIndices.getValueType() != MVT::v16i8 ||
1327 Index->getOperand(1)->getOpcode() != ISD::Constant ||
1328 Index->getConstantOperandVal(1) != I)
1329 return Bail;
1330 return std::make_pair(SwizzleSrc, SwizzleIndices);
1331 };
1332
1333 using ValueEntry = std::pair<SDValue, size_t>;
1334 SmallVector<ValueEntry, 16> SplatValueCounts;
1335
1336 using SwizzleEntry = std::pair<std::pair<SDValue, SDValue>, size_t>;
1337 SmallVector<SwizzleEntry, 16> SwizzleCounts;
1338
1339 auto AddCount = [](auto &Counts, const auto &Val) {
1340 auto CountIt = std::find_if(Counts.begin(), Counts.end(),
1341 [&Val](auto E) { return E.first == Val; });
1342 if (CountIt == Counts.end()) {
1343 Counts.emplace_back(Val, 1);
Thomas Lively079816e2019-01-30 02:23:29 +00001344 } else {
1345 CountIt->second++;
1346 }
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001347 };
Thomas Lively079816e2019-01-30 02:23:29 +00001348
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001349 auto GetMostCommon = [](auto &Counts) {
1350 auto CommonIt =
1351 std::max_element(Counts.begin(), Counts.end(),
1352 [](auto A, auto B) { return A.second < B.second; });
1353 assert(CommonIt != Counts.end() && "Unexpected all-undef build_vector");
1354 return *CommonIt;
1355 };
1356
1357 size_t NumConstantLanes = 0;
1358
1359 // Count eligible lanes for each type of vector creation op
1360 for (size_t I = 0; I < Lanes; ++I) {
1361 const SDValue &Lane = Op->getOperand(I);
1362 if (Lane.isUndef())
1363 continue;
1364
1365 AddCount(SplatValueCounts, Lane);
1366
1367 if (IsConstant(Lane)) {
1368 NumConstantLanes++;
1369 } else if (CanSwizzle) {
1370 auto SwizzleSrcs = GetSwizzleSrcs(I, Lane);
1371 if (SwizzleSrcs.first)
1372 AddCount(SwizzleCounts, SwizzleSrcs);
1373 }
1374 }
1375
1376 SDValue SplatValue;
1377 size_t NumSplatLanes;
1378 std::tie(SplatValue, NumSplatLanes) = GetMostCommon(SplatValueCounts);
1379
1380 SDValue SwizzleSrc;
1381 SDValue SwizzleIndices;
1382 size_t NumSwizzleLanes = 0;
1383 if (SwizzleCounts.size())
1384 std::forward_as_tuple(std::tie(SwizzleSrc, SwizzleIndices),
1385 NumSwizzleLanes) = GetMostCommon(SwizzleCounts);
1386
1387 // Predicate returning true if the lane is properly initialized by the
1388 // original instruction
1389 std::function<bool(size_t, const SDValue &)> IsLaneConstructed;
1390 SDValue Result;
Thomas Lively079816e2019-01-30 02:23:29 +00001391 if (Subtarget->hasUnimplementedSIMD128()) {
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001392 // Prefer swizzles over vector consts over splats
1393 if (NumSwizzleLanes >= NumSplatLanes &&
1394 NumSwizzleLanes >= NumConstantLanes) {
1395 Result = DAG.getNode(WebAssemblyISD::SWIZZLE, DL, VecT, SwizzleSrc,
1396 SwizzleIndices);
1397 auto Swizzled = std::make_pair(SwizzleSrc, SwizzleIndices);
1398 IsLaneConstructed = [&, Swizzled](size_t I, const SDValue &Lane) {
1399 return Swizzled == GetSwizzleSrcs(I, Lane);
1400 };
1401 } else if (NumConstantLanes >= NumSplatLanes) {
Thomas Lively079816e2019-01-30 02:23:29 +00001402 SmallVector<SDValue, 16> ConstLanes;
1403 for (const SDValue &Lane : Op->op_values()) {
1404 if (IsConstant(Lane)) {
1405 ConstLanes.push_back(Lane);
1406 } else if (LaneT.isFloatingPoint()) {
1407 ConstLanes.push_back(DAG.getConstantFP(0, DL, LaneT));
1408 } else {
1409 ConstLanes.push_back(DAG.getConstant(0, DL, LaneT));
1410 }
1411 }
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001412 Result = DAG.getBuildVector(VecT, DL, ConstLanes);
1413 IsLaneConstructed = [&](size_t _, const SDValue &Lane) {
1414 return IsConstant(Lane);
1415 };
Thomas Lively079816e2019-01-30 02:23:29 +00001416 }
1417 }
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001418 if (!Result) {
1419 // Use a splat, but possibly a load_splat
1420 LoadSDNode *SplattedLoad;
1421 if (Subtarget->hasUnimplementedSIMD128() &&
1422 (SplattedLoad = dyn_cast<LoadSDNode>(SplatValue)) &&
1423 SplattedLoad->getMemoryVT() == VecT.getVectorElementType()) {
Thomas Lively3479fd22019-10-31 20:01:02 -07001424 Result = DAG.getMemIntrinsicNode(
1425 WebAssemblyISD::LOAD_SPLAT, DL, DAG.getVTList(VecT),
1426 {SplattedLoad->getChain(), SplattedLoad->getBasePtr(),
1427 SplattedLoad->getOffset()},
1428 SplattedLoad->getMemoryVT(), SplattedLoad->getMemOperand());
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001429 } else {
1430 Result = DAG.getSplatBuildVector(VecT, DL, SplatValue);
1431 }
1432 IsLaneConstructed = [&](size_t _, const SDValue &Lane) {
1433 return Lane == SplatValue;
1434 };
Thomas Lively99d3dd22019-09-23 20:42:12 +00001435 }
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001436
1437 // Add replace_lane instructions for any unhandled values
Thomas Lively079816e2019-01-30 02:23:29 +00001438 for (size_t I = 0; I < Lanes; ++I) {
1439 const SDValue &Lane = Op->getOperand(I);
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001440 if (!Lane.isUndef() && !IsLaneConstructed(I, Lane))
Thomas Lively079816e2019-01-30 02:23:29 +00001441 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VecT, Result, Lane,
1442 DAG.getConstant(I, DL, MVT::i32));
1443 }
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001444
Thomas Lively079816e2019-01-30 02:23:29 +00001445 return Result;
1446}
1447
Thomas Lively64a39a12019-01-10 22:32:11 +00001448SDValue
Thomas Livelya0d25812018-09-07 21:54:46 +00001449WebAssemblyTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
1450 SelectionDAG &DAG) const {
1451 SDLoc DL(Op);
1452 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op.getNode())->getMask();
1453 MVT VecType = Op.getOperand(0).getSimpleValueType();
1454 assert(VecType.is128BitVector() && "Unexpected shuffle vector type");
1455 size_t LaneBytes = VecType.getVectorElementType().getSizeInBits() / 8;
1456
1457 // Space for two vector args and sixteen mask indices
1458 SDValue Ops[18];
1459 size_t OpIdx = 0;
1460 Ops[OpIdx++] = Op.getOperand(0);
1461 Ops[OpIdx++] = Op.getOperand(1);
1462
1463 // Expand mask indices to byte indices and materialize them as operands
Heejin Ahn18c56a02019-02-04 19:13:39 +00001464 for (int M : Mask) {
Thomas Livelya0d25812018-09-07 21:54:46 +00001465 for (size_t J = 0; J < LaneBytes; ++J) {
Thomas Lively11a332d02018-10-19 19:08:06 +00001466 // Lower undefs (represented by -1 in mask) to zero
Heejin Ahn18c56a02019-02-04 19:13:39 +00001467 uint64_t ByteIndex = M == -1 ? 0 : (uint64_t)M * LaneBytes + J;
Thomas Lively11a332d02018-10-19 19:08:06 +00001468 Ops[OpIdx++] = DAG.getConstant(ByteIndex, DL, MVT::i32);
Thomas Livelya0d25812018-09-07 21:54:46 +00001469 }
1470 }
1471
Thomas Livelyed951342018-10-24 23:27:40 +00001472 return DAG.getNode(WebAssemblyISD::SHUFFLE, DL, Op.getValueType(), Ops);
Thomas Livelya0d25812018-09-07 21:54:46 +00001473}
1474
Thomas Livelyecb7daf2019-11-01 10:21:00 -07001475SDValue WebAssemblyTargetLowering::LowerSETCC(SDValue Op,
1476 SelectionDAG &DAG) const {
1477 SDLoc DL(Op);
1478 // The legalizer does not know how to expand the comparison modes of i64x2
1479 // vectors because no comparison modes are supported. We could solve this by
1480 // expanding all i64x2 SETCC nodes, but that seems to expand f64x2 SETCC nodes
1481 // (which return i64x2 results) as well. So instead we manually unroll i64x2
1482 // comparisons here.
Thomas Livelyecb7daf2019-11-01 10:21:00 -07001483 assert(Op->getOperand(0)->getSimpleValueType(0) == MVT::v2i64);
1484 SmallVector<SDValue, 2> LHS, RHS;
1485 DAG.ExtractVectorElements(Op->getOperand(0), LHS);
1486 DAG.ExtractVectorElements(Op->getOperand(1), RHS);
1487 const SDValue &CC = Op->getOperand(2);
1488 auto MakeLane = [&](unsigned I) {
1489 return DAG.getNode(ISD::SELECT_CC, DL, MVT::i64, LHS[I], RHS[I],
1490 DAG.getConstant(uint64_t(-1), DL, MVT::i64),
1491 DAG.getConstant(uint64_t(0), DL, MVT::i64), CC);
1492 };
1493 return DAG.getBuildVector(Op->getValueType(0), DL,
1494 {MakeLane(0), MakeLane(1)});
1495}
1496
Thomas Livelyfb84fd72018-11-02 00:06:56 +00001497SDValue
1498WebAssemblyTargetLowering::LowerAccessVectorElement(SDValue Op,
1499 SelectionDAG &DAG) const {
1500 // Allow constant lane indices, expand variable lane indices
1501 SDNode *IdxNode = Op.getOperand(Op.getNumOperands() - 1).getNode();
1502 if (isa<ConstantSDNode>(IdxNode) || IdxNode->isUndef())
1503 return Op;
1504 else
1505 // Perform default expansion
1506 return SDValue();
1507}
1508
Heejin Ahn18c56a02019-02-04 19:13:39 +00001509static SDValue unrollVectorShift(SDValue Op, SelectionDAG &DAG) {
Thomas Lively6bf2b402019-01-15 02:16:03 +00001510 EVT LaneT = Op.getSimpleValueType().getVectorElementType();
1511 // 32-bit and 64-bit unrolled shifts will have proper semantics
1512 if (LaneT.bitsGE(MVT::i32))
1513 return DAG.UnrollVectorOp(Op.getNode());
1514 // Otherwise mask the shift value to get proper semantics from 32-bit shift
1515 SDLoc DL(Op);
1516 SDValue ShiftVal = Op.getOperand(1);
1517 uint64_t MaskVal = LaneT.getSizeInBits() - 1;
1518 SDValue MaskedShiftVal = DAG.getNode(
1519 ISD::AND, // mask opcode
1520 DL, ShiftVal.getValueType(), // masked value type
1521 ShiftVal, // original shift value operand
1522 DAG.getConstant(MaskVal, DL, ShiftVal.getValueType()) // mask operand
1523 );
1524
1525 return DAG.UnrollVectorOp(
1526 DAG.getNode(Op.getOpcode(), // original shift opcode
1527 DL, Op.getValueType(), // original return type
1528 Op.getOperand(0), // original vector operand,
1529 MaskedShiftVal // new masked shift value operand
1530 )
1531 .getNode());
1532}
1533
Thomas Lively55735d52018-10-20 01:31:18 +00001534SDValue WebAssemblyTargetLowering::LowerShift(SDValue Op,
1535 SelectionDAG &DAG) const {
1536 SDLoc DL(Op);
Thomas Livelyb2382c82018-11-02 00:39:57 +00001537
1538 // Only manually lower vector shifts
1539 assert(Op.getSimpleValueType().isVector());
1540
1541 // Unroll non-splat vector shifts
1542 BuildVectorSDNode *ShiftVec;
1543 SDValue SplatVal;
1544 if (!(ShiftVec = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode())) ||
1545 !(SplatVal = ShiftVec->getSplatValue()))
Heejin Ahn18c56a02019-02-04 19:13:39 +00001546 return unrollVectorShift(Op, DAG);
Thomas Livelyb2382c82018-11-02 00:39:57 +00001547
1548 // All splats except i64x2 const splats are handled by patterns
Heejin Ahn18c56a02019-02-04 19:13:39 +00001549 auto *SplatConst = dyn_cast<ConstantSDNode>(SplatVal);
Thomas Livelyb2382c82018-11-02 00:39:57 +00001550 if (!SplatConst || Op.getSimpleValueType() != MVT::v2i64)
Thomas Lively55735d52018-10-20 01:31:18 +00001551 return Op;
Thomas Livelyb2382c82018-11-02 00:39:57 +00001552
1553 // i64x2 const splats are custom lowered to avoid unnecessary wraps
Thomas Lively55735d52018-10-20 01:31:18 +00001554 unsigned Opcode;
1555 switch (Op.getOpcode()) {
1556 case ISD::SHL:
1557 Opcode = WebAssemblyISD::VEC_SHL;
1558 break;
1559 case ISD::SRA:
1560 Opcode = WebAssemblyISD::VEC_SHR_S;
1561 break;
1562 case ISD::SRL:
1563 Opcode = WebAssemblyISD::VEC_SHR_U;
1564 break;
1565 default:
1566 llvm_unreachable("unexpected opcode");
Thomas Lively55735d52018-10-20 01:31:18 +00001567 }
Thomas Livelyb2382c82018-11-02 00:39:57 +00001568 APInt Shift = SplatConst->getAPIntValue().zextOrTrunc(32);
Thomas Lively55735d52018-10-20 01:31:18 +00001569 return DAG.getNode(Opcode, DL, Op.getValueType(), Op.getOperand(0),
Thomas Livelyb2382c82018-11-02 00:39:57 +00001570 DAG.getConstant(Shift, DL, MVT::i32));
Thomas Lively55735d52018-10-20 01:31:18 +00001571}
1572
Dan Gohman10e730a2015-06-29 23:51:55 +00001573//===----------------------------------------------------------------------===//
1574// WebAssembly Optimization Hooks
1575//===----------------------------------------------------------------------===//