blob: 7e3e09d90030be39cb54851e6258ebb519336e49 [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 }
65 if (Subtarget->hasUnimplementedSIMD128()) {
66 addRegisterClass(MVT::v2i64, &WebAssembly::V128RegClass);
67 addRegisterClass(MVT::v2f64, &WebAssembly::V128RegClass);
Derek Schuff39bf39f2016-08-02 23:16:09 +000068 }
JF Bastienb9073fb2015-07-22 21:28:15 +000069 // Compute derived properties from the register classes.
70 computeRegisterProperties(Subtarget->getRegisterInfo());
71
JF Bastienaf111db2015-08-24 22:16:48 +000072 setOperationAction(ISD::GlobalAddress, MVTPtr, Custom);
Dan Gohman2c8fe6a2015-11-25 16:44:29 +000073 setOperationAction(ISD::ExternalSymbol, MVTPtr, Custom);
Dan Gohman950a13c2015-09-16 16:51:30 +000074 setOperationAction(ISD::JumpTable, MVTPtr, Custom);
Derek Schuff51699a82016-02-12 22:56:03 +000075 setOperationAction(ISD::BlockAddress, MVTPtr, Custom);
76 setOperationAction(ISD::BRIND, MVT::Other, Custom);
JF Bastienaf111db2015-08-24 22:16:48 +000077
Dan Gohman35bfb242015-12-04 23:22:35 +000078 // Take the default expansion for va_arg, va_copy, and va_end. There is no
79 // default action for va_start, so we do that custom.
80 setOperationAction(ISD::VASTART, MVT::Other, Custom);
81 setOperationAction(ISD::VAARG, MVT::Other, Expand);
82 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
83 setOperationAction(ISD::VAEND, MVT::Other, Expand);
84
Thomas Livelyebd4c902018-09-12 17:56:00 +000085 for (auto T : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
JF Bastienda06bce2015-08-11 21:02:46 +000086 // Don't expand the floating-point types to constant pools.
87 setOperationAction(ISD::ConstantFP, T, Legal);
88 // Expand floating-point comparisons.
89 for (auto CC : {ISD::SETO, ISD::SETUO, ISD::SETUEQ, ISD::SETONE,
90 ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE})
91 setCondCodeAction(CC, T, Expand);
Dan Gohman32907a62015-08-20 22:57:13 +000092 // Expand floating-point library function operators.
Heejin Ahnf208f632018-09-05 01:27:38 +000093 for (auto Op :
94 {ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FREM, ISD::FMA})
Dan Gohman32907a62015-08-20 22:57:13 +000095 setOperationAction(Op, T, Expand);
Dan Gohman896e53f2015-08-24 18:23:13 +000096 // Note supported floating-point library function operators that otherwise
97 // default to expand.
Dan Gohman7a6b9822015-11-29 22:32:02 +000098 for (auto Op :
99 {ISD::FCEIL, ISD::FFLOOR, ISD::FTRUNC, ISD::FNEARBYINT, ISD::FRINT})
Dan Gohman896e53f2015-08-24 18:23:13 +0000100 setOperationAction(Op, T, Legal);
Thomas Lively30f1d692018-10-24 22:49:55 +0000101 // Support minimum and maximum, which otherwise default to expand.
102 setOperationAction(ISD::FMINIMUM, T, Legal);
103 setOperationAction(ISD::FMAXIMUM, T, Legal);
Dan Gohmana63e8eb2017-02-22 16:28:00 +0000104 // WebAssembly currently has no builtin f16 support.
105 setOperationAction(ISD::FP16_TO_FP, T, Expand);
106 setOperationAction(ISD::FP_TO_FP16, T, Expand);
107 setLoadExtAction(ISD::EXTLOAD, T, MVT::f16, Expand);
108 setTruncStoreAction(T, MVT::f16, Expand);
JF Bastienda06bce2015-08-11 21:02:46 +0000109 }
Dan Gohman32907a62015-08-20 22:57:13 +0000110
Thomas Lively66ea30c2018-11-29 22:01:01 +0000111 // Expand unavailable integer operations.
112 for (auto Op :
113 {ISD::BSWAP, ISD::SMUL_LOHI, ISD::UMUL_LOHI, ISD::MULHS, ISD::MULHU,
114 ISD::SDIVREM, ISD::UDIVREM, ISD::SHL_PARTS, ISD::SRA_PARTS,
115 ISD::SRL_PARTS, ISD::ADDC, ISD::ADDE, ISD::SUBC, ISD::SUBE}) {
Thomas Lively2b8b2972019-01-26 01:25:37 +0000116 for (auto T : {MVT::i32, MVT::i64})
Dan Gohman32907a62015-08-20 22:57:13 +0000117 setOperationAction(Op, T, Expand);
Thomas Lively2b8b2972019-01-26 01:25:37 +0000118 if (Subtarget->hasSIMD128())
119 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
Thomas Lively66ea30c2018-11-29 22:01:01 +0000120 setOperationAction(Op, T, Expand);
Thomas Lively64a39a12019-01-10 22:32:11 +0000121 if (Subtarget->hasUnimplementedSIMD128())
Thomas Lively2b8b2972019-01-26 01:25:37 +0000122 setOperationAction(Op, MVT::v2i64, Expand);
Thomas Livelyb2382c82018-11-02 00:39:57 +0000123 }
Thomas Lively55735d52018-10-20 01:31:18 +0000124
Thomas Lively2b8b2972019-01-26 01:25:37 +0000125 // SIMD-specific configuration
126 if (Subtarget->hasSIMD128()) {
127 // Support saturating add for i8x16 and i16x8
128 for (auto Op : {ISD::SADDSAT, ISD::UADDSAT})
129 for (auto T : {MVT::v16i8, MVT::v8i16})
130 setOperationAction(Op, T, Legal);
131
Thomas Lively079816e2019-01-30 02:23:29 +0000132 // Custom lower BUILD_VECTORs to minimize number of replace_lanes
133 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32})
134 setOperationAction(ISD::BUILD_VECTOR, T, Custom);
135 if (Subtarget->hasUnimplementedSIMD128())
136 for (auto T : {MVT::v2i64, MVT::v2f64})
137 setOperationAction(ISD::BUILD_VECTOR, T, Custom);
138
Thomas Lively2b8b2972019-01-26 01:25:37 +0000139 // We have custom shuffle lowering to expose the shuffle mask
140 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32})
141 setOperationAction(ISD::VECTOR_SHUFFLE, T, Custom);
142 if (Subtarget->hasUnimplementedSIMD128())
143 for (auto T: {MVT::v2i64, MVT::v2f64})
144 setOperationAction(ISD::VECTOR_SHUFFLE, T, Custom);
145
146 // Custom lowering since wasm shifts must have a scalar shift amount
147 for (auto Op : {ISD::SHL, ISD::SRA, ISD::SRL}) {
148 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
149 setOperationAction(Op, T, Custom);
150 if (Subtarget->hasUnimplementedSIMD128())
151 setOperationAction(Op, MVT::v2i64, Custom);
152 }
153
154 // Custom lower lane accesses to expand out variable indices
155 for (auto Op : {ISD::EXTRACT_VECTOR_ELT, ISD::INSERT_VECTOR_ELT}) {
156 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32})
157 setOperationAction(Op, T, Custom);
158 if (Subtarget->hasUnimplementedSIMD128())
159 for (auto T : {MVT::v2i64, MVT::v2f64})
160 setOperationAction(Op, T, Custom);
161 }
162
163 // There is no i64x2.mul instruction
164 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
165
166 // There are no vector select instructions
Thomas Lively38c902b2018-11-09 01:38:44 +0000167 for (auto Op : {ISD::VSELECT, ISD::SELECT_CC, ISD::SELECT}) {
168 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32})
169 setOperationAction(Op, T, Expand);
Thomas Lively64a39a12019-01-10 22:32:11 +0000170 if (Subtarget->hasUnimplementedSIMD128())
Thomas Lively38c902b2018-11-09 01:38:44 +0000171 for (auto T : {MVT::v2i64, MVT::v2f64})
172 setOperationAction(Op, T, Expand);
173 }
Thomas Livelyd4891a12018-11-01 00:01:02 +0000174
Thomas Lively43876ae72019-03-02 03:32:25 +0000175 // Expand integer operations supported for scalars but not SIMD
176 for (auto Op : {ISD::CTLZ, ISD::CTTZ, ISD::CTPOP, ISD::SDIV, ISD::UDIV,
177 ISD::SREM, ISD::UREM, ISD::ROTL, ISD::ROTR}) {
178 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
179 setOperationAction(Op, T, Expand);
180 if (Subtarget->hasUnimplementedSIMD128())
181 setOperationAction(Op, MVT::v2i64, Expand);
182 }
183
Thomas Lively3a937562019-12-13 17:08:04 -0800184 // But we do have integer min and max operations
185 if (Subtarget->hasUnimplementedSIMD128()) {
186 for (auto Op : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
187 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
188 setOperationAction(Op, T, Legal);
189 }
190
Thomas Lively43876ae72019-03-02 03:32:25 +0000191 // Expand float operations supported for scalars but not SIMD
192 for (auto Op : {ISD::FCEIL, ISD::FFLOOR, ISD::FTRUNC, ISD::FNEARBYINT,
Thomas Lively55229f62019-05-24 00:15:04 +0000193 ISD::FCOPYSIGN, ISD::FLOG, ISD::FLOG2, ISD::FLOG10,
194 ISD::FEXP, ISD::FEXP2, ISD::FRINT}) {
Thomas Lively43876ae72019-03-02 03:32:25 +0000195 setOperationAction(Op, MVT::v4f32, Expand);
196 if (Subtarget->hasUnimplementedSIMD128())
197 setOperationAction(Op, MVT::v2f64, Expand);
198 }
199
Thomas Livelyecb7daf2019-11-01 10:21:00 -0700200 // Expand operations not supported for i64x2 vectors
201 if (Subtarget->hasUnimplementedSIMD128())
202 for (unsigned CC = 0; CC < ISD::SETCC_INVALID; ++CC)
203 setCondCodeAction(static_cast<ISD::CondCode>(CC), MVT::v2i64, Custom);
204
Thomas Lively2b8b2972019-01-26 01:25:37 +0000205 // Expand additional SIMD ops that V8 hasn't implemented yet
206 if (!Subtarget->hasUnimplementedSIMD128()) {
207 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
208 setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
209 }
210 }
211
Dan Gohman32907a62015-08-20 22:57:13 +0000212 // As a special case, these operators use the type to mean the type to
213 // sign-extend from.
Derek Schuffa519fe52017-09-13 00:29:06 +0000214 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
Dan Gohman5d2b9352018-01-19 17:16:24 +0000215 if (!Subtarget->hasSignExt()) {
Thomas Lively64a39a12019-01-10 22:32:11 +0000216 // Sign extends are legal only when extending a vector extract
217 auto Action = Subtarget->hasSIMD128() ? Custom : Expand;
Derek Schuffa519fe52017-09-13 00:29:06 +0000218 for (auto T : {MVT::i8, MVT::i16, MVT::i32})
Thomas Lively64a39a12019-01-10 22:32:11 +0000219 setOperationAction(ISD::SIGN_EXTEND_INREG, T, Action);
Derek Schuffa519fe52017-09-13 00:29:06 +0000220 }
Graham Hunter1a9195d2019-09-17 10:19:23 +0000221 for (auto T : MVT::integer_fixedlen_vector_valuetypes())
Thomas Lively5ea17d42018-10-20 01:35:23 +0000222 setOperationAction(ISD::SIGN_EXTEND_INREG, T, Expand);
Dan Gohman32907a62015-08-20 22:57:13 +0000223
224 // Dynamic stack allocation: use the default expansion.
225 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
226 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
Dan Gohman2683a552015-08-24 22:31:52 +0000227 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVTPtr, Expand);
JF Bastien73ff6af2015-08-31 22:24:11 +0000228
Derek Schuff9769deb2015-12-11 23:49:46 +0000229 setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
Derek Schuffaadc89c2016-02-16 18:18:36 +0000230 setOperationAction(ISD::CopyToReg, MVT::Other, Custom);
Derek Schuff9769deb2015-12-11 23:49:46 +0000231
Dan Gohman950a13c2015-09-16 16:51:30 +0000232 // Expand these forms; we pattern-match the forms that we can handle in isel.
233 for (auto T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64})
234 for (auto Op : {ISD::BR_CC, ISD::SELECT_CC})
235 setOperationAction(Op, T, Expand);
236
237 // We have custom switch handling.
238 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
239
JF Bastien73ff6af2015-08-31 22:24:11 +0000240 // WebAssembly doesn't have:
241 // - Floating-point extending loads.
242 // - Floating-point truncating stores.
243 // - i1 extending loads.
Thomas Lively81125f72019-09-27 02:06:50 +0000244 // - truncating SIMD stores and most extending loads
Dan Gohman60bddf12015-12-10 02:07:53 +0000245 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
JF Bastien73ff6af2015-08-31 22:24:11 +0000246 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
247 for (auto T : MVT::integer_valuetypes())
248 for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD})
249 setLoadExtAction(Ext, T, MVT::i1, Promote);
Thomas Lively325c9c52018-10-25 01:46:07 +0000250 if (Subtarget->hasSIMD128()) {
251 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64, MVT::v4f32,
252 MVT::v2f64}) {
Graham Hunter1a9195d2019-09-17 10:19:23 +0000253 for (auto MemT : MVT::fixedlen_vector_valuetypes()) {
Thomas Lively325c9c52018-10-25 01:46:07 +0000254 if (MVT(T) != MemT) {
255 setTruncStoreAction(T, MemT, Expand);
256 for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD})
257 setLoadExtAction(Ext, T, MemT, Expand);
258 }
259 }
260 }
Thomas Lively81125f72019-09-27 02:06:50 +0000261 // But some vector extending loads are legal
262 if (Subtarget->hasUnimplementedSIMD128()) {
263 for (auto Ext : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) {
264 setLoadExtAction(Ext, MVT::v8i16, MVT::v8i8, Legal);
265 setLoadExtAction(Ext, MVT::v4i32, MVT::v4i16, Legal);
266 setLoadExtAction(Ext, MVT::v2i64, MVT::v2i32, Legal);
267 }
268 }
Thomas Lively325c9c52018-10-25 01:46:07 +0000269 }
Derek Schuffffa143c2015-11-10 00:30:57 +0000270
Thomas Lively33f87b82019-01-28 23:44:31 +0000271 // Don't do anything clever with build_pairs
272 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
273
Derek Schuffffa143c2015-11-10 00:30:57 +0000274 // Trap lowers to wasm unreachable
275 setOperationAction(ISD::TRAP, MVT::Other, Legal);
Derek Schuff18ba1922017-08-30 18:07:45 +0000276
Heejin Ahn5ef4d5f2018-05-31 22:25:54 +0000277 // Exception handling intrinsics
278 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
Heejin Ahnda419bd2018-11-14 02:46:21 +0000279 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
Heejin Ahn5ef4d5f2018-05-31 22:25:54 +0000280
Derek Schuff18ba1922017-08-30 18:07:45 +0000281 setMaxAtomicSizeInBitsSupported(64);
Thomas Livelyd99af232019-02-05 00:49:55 +0000282
Dan Gohman3a7532e2019-04-30 19:17:59 +0000283 // Override the __gnu_f2h_ieee/__gnu_h2f_ieee names so that the f32 name is
284 // consistent with the f64 and f128 names.
285 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
286 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
287
Thomas Lively1a3cbe72019-05-23 01:24:01 +0000288 // Define the emscripten name for return address helper.
289 // TODO: when implementing other WASM backends, make this generic or only do
290 // this on emscripten depending on what they end up doing.
291 setLibcallName(RTLIB::RETURN_ADDRESS, "emscripten_return_address");
292
Heejin Ahnb9f282d2019-04-23 21:30:30 +0000293 // Always convert switches to br_tables unless there is only one case, which
294 // is equivalent to a simple branch. This reduces code size for wasm, and we
295 // defer possible jump table optimizations to the VM.
296 setMinimumJumpTableEntries(2);
Dan Gohmanbfaf7e12015-07-02 21:36:25 +0000297}
Dan Gohman10e730a2015-06-29 23:51:55 +0000298
Heejin Ahne8653bb2018-08-07 00:22:22 +0000299TargetLowering::AtomicExpansionKind
300WebAssemblyTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
301 // We have wasm instructions for these
302 switch (AI->getOperation()) {
303 case AtomicRMWInst::Add:
304 case AtomicRMWInst::Sub:
305 case AtomicRMWInst::And:
306 case AtomicRMWInst::Or:
307 case AtomicRMWInst::Xor:
308 case AtomicRMWInst::Xchg:
309 return AtomicExpansionKind::None;
310 default:
311 break;
312 }
313 return AtomicExpansionKind::CmpXChg;
314}
315
Dan Gohman7b634842015-08-24 18:44:37 +0000316FastISel *WebAssemblyTargetLowering::createFastISel(
317 FunctionLoweringInfo &FuncInfo, const TargetLibraryInfo *LibInfo) const {
318 return WebAssembly::createFastISel(FuncInfo, LibInfo);
319}
320
Dan Gohman7a6b9822015-11-29 22:32:02 +0000321MVT WebAssemblyTargetLowering::getScalarShiftAmountTy(const DataLayout & /*DL*/,
JF Bastienfda53372015-08-03 00:00:11 +0000322 EVT VT) const {
Dan Gohmana8483752015-12-10 00:26:26 +0000323 unsigned BitWidth = NextPowerOf2(VT.getSizeInBits() - 1);
Heejin Ahnf208f632018-09-05 01:27:38 +0000324 if (BitWidth > 1 && BitWidth < 8)
325 BitWidth = 8;
Dan Gohman41729532015-12-16 23:25:51 +0000326
327 if (BitWidth > 64) {
Dan Gohmana01e8bd2016-05-14 02:15:47 +0000328 // The shift will be lowered to a libcall, and compiler-rt libcalls expect
329 // the count to be an i32.
330 BitWidth = 32;
Dan Gohman41729532015-12-16 23:25:51 +0000331 assert(BitWidth >= Log2_32_Ceil(VT.getSizeInBits()) &&
Dan Gohmana01e8bd2016-05-14 02:15:47 +0000332 "32-bit shift counts ought to be enough for anyone");
Dan Gohman41729532015-12-16 23:25:51 +0000333 }
334
Dan Gohmana8483752015-12-10 00:26:26 +0000335 MVT Result = MVT::getIntegerVT(BitWidth);
336 assert(Result != MVT::INVALID_SIMPLE_VALUE_TYPE &&
337 "Unable to represent scalar shift amount type");
338 return Result;
JF Bastienfda53372015-08-03 00:00:11 +0000339}
340
Dan Gohmancdd48b82017-11-28 01:13:40 +0000341// Lower an fp-to-int conversion operator from the LLVM opcode, which has an
342// undefined result on invalid/overflow, to the WebAssembly opcode, which
343// traps on invalid/overflow.
Heejin Ahnf208f632018-09-05 01:27:38 +0000344static MachineBasicBlock *LowerFPToInt(MachineInstr &MI, DebugLoc DL,
345 MachineBasicBlock *BB,
346 const TargetInstrInfo &TII,
347 bool IsUnsigned, bool Int64,
348 bool Float64, unsigned LoweredOpcode) {
Dan Gohmancdd48b82017-11-28 01:13:40 +0000349 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
350
Daniel Sanders05c145d2019-08-12 22:40:45 +0000351 Register OutReg = MI.getOperand(0).getReg();
352 Register InReg = MI.getOperand(1).getReg();
Dan Gohmancdd48b82017-11-28 01:13:40 +0000353
354 unsigned Abs = Float64 ? WebAssembly::ABS_F64 : WebAssembly::ABS_F32;
355 unsigned FConst = Float64 ? WebAssembly::CONST_F64 : WebAssembly::CONST_F32;
356 unsigned LT = Float64 ? WebAssembly::LT_F64 : WebAssembly::LT_F32;
Dan Gohman580c1022017-11-29 20:20:11 +0000357 unsigned GE = Float64 ? WebAssembly::GE_F64 : WebAssembly::GE_F32;
Dan Gohmancdd48b82017-11-28 01:13:40 +0000358 unsigned IConst = Int64 ? WebAssembly::CONST_I64 : WebAssembly::CONST_I32;
Dan Gohman580c1022017-11-29 20:20:11 +0000359 unsigned Eqz = WebAssembly::EQZ_I32;
360 unsigned And = WebAssembly::AND_I32;
Dan Gohmancdd48b82017-11-28 01:13:40 +0000361 int64_t Limit = Int64 ? INT64_MIN : INT32_MIN;
362 int64_t Substitute = IsUnsigned ? 0 : Limit;
363 double CmpVal = IsUnsigned ? -(double)Limit * 2.0 : -(double)Limit;
David Blaikie21109242017-12-15 23:52:06 +0000364 auto &Context = BB->getParent()->getFunction().getContext();
Dan Gohmancdd48b82017-11-28 01:13:40 +0000365 Type *Ty = Float64 ? Type::getDoubleTy(Context) : Type::getFloatTy(Context);
366
Heejin Ahn18c56a02019-02-04 19:13:39 +0000367 const BasicBlock *LLVMBB = BB->getBasicBlock();
Dan Gohmancdd48b82017-11-28 01:13:40 +0000368 MachineFunction *F = BB->getParent();
Heejin Ahn18c56a02019-02-04 19:13:39 +0000369 MachineBasicBlock *TrueMBB = F->CreateMachineBasicBlock(LLVMBB);
370 MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(LLVMBB);
371 MachineBasicBlock *DoneMBB = F->CreateMachineBasicBlock(LLVMBB);
Dan Gohmancdd48b82017-11-28 01:13:40 +0000372
373 MachineFunction::iterator It = ++BB->getIterator();
374 F->insert(It, FalseMBB);
375 F->insert(It, TrueMBB);
376 F->insert(It, DoneMBB);
377
378 // Transfer the remainder of BB and its successor edges to DoneMBB.
Heejin Ahn5c644c92019-03-05 21:05:09 +0000379 DoneMBB->splice(DoneMBB->begin(), BB, std::next(MI.getIterator()), BB->end());
Dan Gohmancdd48b82017-11-28 01:13:40 +0000380 DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
381
382 BB->addSuccessor(TrueMBB);
383 BB->addSuccessor(FalseMBB);
384 TrueMBB->addSuccessor(DoneMBB);
385 FalseMBB->addSuccessor(DoneMBB);
386
Dan Gohman580c1022017-11-29 20:20:11 +0000387 unsigned Tmp0, Tmp1, CmpReg, EqzReg, FalseReg, TrueReg;
Dan Gohmancdd48b82017-11-28 01:13:40 +0000388 Tmp0 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
389 Tmp1 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
Dan Gohman580c1022017-11-29 20:20:11 +0000390 CmpReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
391 EqzReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
392 FalseReg = MRI.createVirtualRegister(MRI.getRegClass(OutReg));
393 TrueReg = MRI.createVirtualRegister(MRI.getRegClass(OutReg));
Dan Gohmancdd48b82017-11-28 01:13:40 +0000394
395 MI.eraseFromParent();
Dan Gohman580c1022017-11-29 20:20:11 +0000396 // For signed numbers, we can do a single comparison to determine whether
397 // fabs(x) is within range.
Dan Gohmancdd48b82017-11-28 01:13:40 +0000398 if (IsUnsigned) {
399 Tmp0 = InReg;
400 } else {
Heejin Ahnf208f632018-09-05 01:27:38 +0000401 BuildMI(BB, DL, TII.get(Abs), Tmp0).addReg(InReg);
Dan Gohmancdd48b82017-11-28 01:13:40 +0000402 }
403 BuildMI(BB, DL, TII.get(FConst), Tmp1)
404 .addFPImm(cast<ConstantFP>(ConstantFP::get(Ty, CmpVal)));
Heejin Ahnf208f632018-09-05 01:27:38 +0000405 BuildMI(BB, DL, TII.get(LT), CmpReg).addReg(Tmp0).addReg(Tmp1);
Dan Gohman580c1022017-11-29 20:20:11 +0000406
407 // For unsigned numbers, we have to do a separate comparison with zero.
408 if (IsUnsigned) {
409 Tmp1 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
Daniel Sanders05c145d2019-08-12 22:40:45 +0000410 Register SecondCmpReg =
Heejin Ahnf208f632018-09-05 01:27:38 +0000411 MRI.createVirtualRegister(&WebAssembly::I32RegClass);
Daniel Sanders05c145d2019-08-12 22:40:45 +0000412 Register AndReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
Dan Gohman580c1022017-11-29 20:20:11 +0000413 BuildMI(BB, DL, TII.get(FConst), Tmp1)
414 .addFPImm(cast<ConstantFP>(ConstantFP::get(Ty, 0.0)));
Heejin Ahnf208f632018-09-05 01:27:38 +0000415 BuildMI(BB, DL, TII.get(GE), SecondCmpReg).addReg(Tmp0).addReg(Tmp1);
416 BuildMI(BB, DL, TII.get(And), AndReg).addReg(CmpReg).addReg(SecondCmpReg);
Dan Gohman580c1022017-11-29 20:20:11 +0000417 CmpReg = AndReg;
418 }
419
Heejin Ahnf208f632018-09-05 01:27:38 +0000420 BuildMI(BB, DL, TII.get(Eqz), EqzReg).addReg(CmpReg);
Dan Gohman580c1022017-11-29 20:20:11 +0000421
422 // Create the CFG diamond to select between doing the conversion or using
423 // the substitute value.
Heejin Ahnf208f632018-09-05 01:27:38 +0000424 BuildMI(BB, DL, TII.get(WebAssembly::BR_IF)).addMBB(TrueMBB).addReg(EqzReg);
425 BuildMI(FalseMBB, DL, TII.get(LoweredOpcode), FalseReg).addReg(InReg);
426 BuildMI(FalseMBB, DL, TII.get(WebAssembly::BR)).addMBB(DoneMBB);
427 BuildMI(TrueMBB, DL, TII.get(IConst), TrueReg).addImm(Substitute);
Dan Gohmancdd48b82017-11-28 01:13:40 +0000428 BuildMI(*DoneMBB, DoneMBB->begin(), DL, TII.get(TargetOpcode::PHI), OutReg)
Dan Gohman580c1022017-11-29 20:20:11 +0000429 .addReg(FalseReg)
Dan Gohmancdd48b82017-11-28 01:13:40 +0000430 .addMBB(FalseMBB)
Dan Gohman580c1022017-11-29 20:20:11 +0000431 .addReg(TrueReg)
Dan Gohmancdd48b82017-11-28 01:13:40 +0000432 .addMBB(TrueMBB);
433
434 return DoneMBB;
435}
436
Heejin Ahnf208f632018-09-05 01:27:38 +0000437MachineBasicBlock *WebAssemblyTargetLowering::EmitInstrWithCustomInserter(
438 MachineInstr &MI, MachineBasicBlock *BB) const {
Dan Gohmancdd48b82017-11-28 01:13:40 +0000439 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
440 DebugLoc DL = MI.getDebugLoc();
441
442 switch (MI.getOpcode()) {
Heejin Ahnf208f632018-09-05 01:27:38 +0000443 default:
444 llvm_unreachable("Unexpected instr type to insert");
Dan Gohmancdd48b82017-11-28 01:13:40 +0000445 case WebAssembly::FP_TO_SINT_I32_F32:
446 return LowerFPToInt(MI, DL, BB, TII, false, false, false,
447 WebAssembly::I32_TRUNC_S_F32);
448 case WebAssembly::FP_TO_UINT_I32_F32:
449 return LowerFPToInt(MI, DL, BB, TII, true, false, false,
450 WebAssembly::I32_TRUNC_U_F32);
451 case WebAssembly::FP_TO_SINT_I64_F32:
452 return LowerFPToInt(MI, DL, BB, TII, false, true, false,
453 WebAssembly::I64_TRUNC_S_F32);
454 case WebAssembly::FP_TO_UINT_I64_F32:
455 return LowerFPToInt(MI, DL, BB, TII, true, true, false,
456 WebAssembly::I64_TRUNC_U_F32);
457 case WebAssembly::FP_TO_SINT_I32_F64:
458 return LowerFPToInt(MI, DL, BB, TII, false, false, true,
459 WebAssembly::I32_TRUNC_S_F64);
460 case WebAssembly::FP_TO_UINT_I32_F64:
461 return LowerFPToInt(MI, DL, BB, TII, true, false, true,
462 WebAssembly::I32_TRUNC_U_F64);
463 case WebAssembly::FP_TO_SINT_I64_F64:
464 return LowerFPToInt(MI, DL, BB, TII, false, true, true,
465 WebAssembly::I64_TRUNC_S_F64);
466 case WebAssembly::FP_TO_UINT_I64_F64:
467 return LowerFPToInt(MI, DL, BB, TII, true, true, true,
468 WebAssembly::I64_TRUNC_U_F64);
Heejin Ahnf208f632018-09-05 01:27:38 +0000469 llvm_unreachable("Unexpected instruction to emit with custom inserter");
Dan Gohmancdd48b82017-11-28 01:13:40 +0000470 }
471}
472
Heejin Ahnf208f632018-09-05 01:27:38 +0000473const char *
474WebAssemblyTargetLowering::getTargetNodeName(unsigned Opcode) const {
JF Bastien480c8402015-08-11 20:13:18 +0000475 switch (static_cast<WebAssemblyISD::NodeType>(Opcode)) {
Heejin Ahnf208f632018-09-05 01:27:38 +0000476 case WebAssemblyISD::FIRST_NUMBER:
Thomas Lively3479fd22019-10-31 20:01:02 -0700477 case WebAssemblyISD::FIRST_MEM_OPCODE:
Heejin Ahnf208f632018-09-05 01:27:38 +0000478 break;
479#define HANDLE_NODETYPE(NODE) \
480 case WebAssemblyISD::NODE: \
JF Bastienaf111db2015-08-24 22:16:48 +0000481 return "WebAssemblyISD::" #NODE;
Thomas Lively3479fd22019-10-31 20:01:02 -0700482#define HANDLE_MEM_NODETYPE(NODE) HANDLE_NODETYPE(NODE)
JF Bastienaf111db2015-08-24 22:16:48 +0000483#include "WebAssemblyISD.def"
Thomas Lively3479fd22019-10-31 20:01:02 -0700484#undef HANDLE_MEM_NODETYPE
JF Bastienaf111db2015-08-24 22:16:48 +0000485#undef HANDLE_NODETYPE
JF Bastien480c8402015-08-11 20:13:18 +0000486 }
487 return nullptr;
488}
489
Dan Gohmanf19ed562015-11-13 01:42:29 +0000490std::pair<unsigned, const TargetRegisterClass *>
491WebAssemblyTargetLowering::getRegForInlineAsmConstraint(
492 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
493 // First, see if this is a constraint that directly corresponds to a
494 // WebAssembly register class.
495 if (Constraint.size() == 1) {
496 switch (Constraint[0]) {
Heejin Ahnf208f632018-09-05 01:27:38 +0000497 case 'r':
498 assert(VT != MVT::iPTR && "Pointer MVT not expected here");
499 if (Subtarget->hasSIMD128() && VT.isVector()) {
500 if (VT.getSizeInBits() == 128)
501 return std::make_pair(0U, &WebAssembly::V128RegClass);
502 }
503 if (VT.isInteger() && !VT.isVector()) {
504 if (VT.getSizeInBits() <= 32)
505 return std::make_pair(0U, &WebAssembly::I32RegClass);
506 if (VT.getSizeInBits() <= 64)
507 return std::make_pair(0U, &WebAssembly::I64RegClass);
508 }
509 break;
510 default:
511 break;
Dan Gohmanf19ed562015-11-13 01:42:29 +0000512 }
513 }
514
515 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
516}
517
Dan Gohman3192ddf2015-11-19 23:04:59 +0000518bool WebAssemblyTargetLowering::isCheapToSpeculateCttz() const {
519 // Assume ctz is a relatively cheap operation.
520 return true;
521}
522
523bool WebAssemblyTargetLowering::isCheapToSpeculateCtlz() const {
524 // Assume clz is a relatively cheap operation.
525 return true;
526}
527
Dan Gohman4b9d7912015-12-15 22:01:29 +0000528bool WebAssemblyTargetLowering::isLegalAddressingMode(const DataLayout &DL,
529 const AddrMode &AM,
Heejin Ahnf208f632018-09-05 01:27:38 +0000530 Type *Ty, unsigned AS,
Jonas Paulsson024e3192017-07-21 11:59:37 +0000531 Instruction *I) const {
Dan Gohman4b9d7912015-12-15 22:01:29 +0000532 // WebAssembly offsets are added as unsigned without wrapping. The
533 // isLegalAddressingMode gives us no way to determine if wrapping could be
534 // happening, so we approximate this by accepting only non-negative offsets.
Heejin Ahnf208f632018-09-05 01:27:38 +0000535 if (AM.BaseOffs < 0)
536 return false;
Dan Gohman4b9d7912015-12-15 22:01:29 +0000537
538 // WebAssembly has no scale register operands.
Heejin Ahnf208f632018-09-05 01:27:38 +0000539 if (AM.Scale != 0)
540 return false;
Dan Gohman4b9d7912015-12-15 22:01:29 +0000541
542 // Everything else is legal.
543 return true;
544}
545
Dan Gohmanbb372242016-01-26 03:39:31 +0000546bool WebAssemblyTargetLowering::allowsMisalignedMemoryAccesses(
Simon Pilgrim4e0648a2019-06-12 17:14:03 +0000547 EVT /*VT*/, unsigned /*AddrSpace*/, unsigned /*Align*/,
548 MachineMemOperand::Flags /*Flags*/, bool *Fast) const {
Dan Gohmanbb372242016-01-26 03:39:31 +0000549 // WebAssembly supports unaligned accesses, though it should be declared
550 // with the p2align attribute on loads and stores which do so, and there
551 // may be a performance impact. We tell LLVM they're "fast" because
Dan Gohmanfb619e92016-01-26 14:55:17 +0000552 // for the kinds of things that LLVM uses this for (merging adjacent stores
Dan Gohmanbb372242016-01-26 03:39:31 +0000553 // of constants, etc.), WebAssembly implementations will either want the
554 // unaligned access or they'll split anyway.
Heejin Ahnf208f632018-09-05 01:27:38 +0000555 if (Fast)
556 *Fast = true;
Dan Gohmanbb372242016-01-26 03:39:31 +0000557 return true;
558}
559
Reid Klecknerb5180542017-03-21 16:57:19 +0000560bool WebAssemblyTargetLowering::isIntDivCheap(EVT VT,
561 AttributeList Attr) const {
Dan Gohmanb4c3c382016-05-18 14:29:42 +0000562 // The current thinking is that wasm engines will perform this optimization,
563 // so we can save on code size.
564 return true;
565}
566
Thomas Lively81125f72019-09-27 02:06:50 +0000567bool WebAssemblyTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
568 if (!Subtarget->hasUnimplementedSIMD128())
569 return false;
570 MVT ExtT = ExtVal.getSimpleValueType();
571 MVT MemT = cast<LoadSDNode>(ExtVal->getOperand(0))->getSimpleValueType(0);
572 return (ExtT == MVT::v8i16 && MemT == MVT::v8i8) ||
573 (ExtT == MVT::v4i32 && MemT == MVT::v4i16) ||
574 (ExtT == MVT::v2i64 && MemT == MVT::v2i32);
575}
576
Simon Pilgrim99f70162018-06-28 17:27:09 +0000577EVT WebAssemblyTargetLowering::getSetCCResultType(const DataLayout &DL,
578 LLVMContext &C,
579 EVT VT) const {
580 if (VT.isVector())
581 return VT.changeVectorElementTypeToInteger();
582
583 return TargetLowering::getSetCCResultType(DL, C, VT);
584}
585
Heejin Ahn4128cb02018-08-02 21:44:24 +0000586bool WebAssemblyTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
587 const CallInst &I,
588 MachineFunction &MF,
589 unsigned Intrinsic) const {
590 switch (Intrinsic) {
591 case Intrinsic::wasm_atomic_notify:
592 Info.opc = ISD::INTRINSIC_W_CHAIN;
593 Info.memVT = MVT::i32;
594 Info.ptrVal = I.getArgOperand(0);
595 Info.offset = 0;
Guillaume Chateletc97a3d12019-08-05 11:02:05 +0000596 Info.align = Align(4);
Heejin Ahn4128cb02018-08-02 21:44:24 +0000597 // atomic.notify instruction does not really load the memory specified with
598 // this argument, but MachineMemOperand should either be load or store, so
599 // we set this to a load.
600 // FIXME Volatile isn't really correct, but currently all LLVM atomic
601 // instructions are treated as volatiles in the backend, so we should be
602 // consistent. The same applies for wasm_atomic_wait intrinsics too.
603 Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
604 return true;
605 case Intrinsic::wasm_atomic_wait_i32:
606 Info.opc = ISD::INTRINSIC_W_CHAIN;
607 Info.memVT = MVT::i32;
608 Info.ptrVal = I.getArgOperand(0);
609 Info.offset = 0;
Guillaume Chateletc97a3d12019-08-05 11:02:05 +0000610 Info.align = Align(4);
Heejin Ahn4128cb02018-08-02 21:44:24 +0000611 Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
612 return true;
613 case Intrinsic::wasm_atomic_wait_i64:
614 Info.opc = ISD::INTRINSIC_W_CHAIN;
615 Info.memVT = MVT::i64;
616 Info.ptrVal = I.getArgOperand(0);
617 Info.offset = 0;
Guillaume Chateletc97a3d12019-08-05 11:02:05 +0000618 Info.align = Align(8);
Heejin Ahn4128cb02018-08-02 21:44:24 +0000619 Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
620 return true;
621 default:
622 return false;
623 }
624}
625
Dan Gohman10e730a2015-06-29 23:51:55 +0000626//===----------------------------------------------------------------------===//
627// WebAssembly Lowering private implementation.
628//===----------------------------------------------------------------------===//
629
630//===----------------------------------------------------------------------===//
631// Lowering Code
632//===----------------------------------------------------------------------===//
633
Heejin Ahn18c56a02019-02-04 19:13:39 +0000634static void fail(const SDLoc &DL, SelectionDAG &DAG, const char *Msg) {
JF Bastienb9073fb2015-07-22 21:28:15 +0000635 MachineFunction &MF = DAG.getMachineFunction();
636 DAG.getContext()->diagnose(
Heejin Ahn18c56a02019-02-04 19:13:39 +0000637 DiagnosticInfoUnsupported(MF.getFunction(), Msg, DL.getDebugLoc()));
JF Bastienb9073fb2015-07-22 21:28:15 +0000638}
639
Dan Gohman85dbdda2015-12-04 17:16:07 +0000640// Test whether the given calling convention is supported.
Heejin Ahn18c56a02019-02-04 19:13:39 +0000641static bool callingConvSupported(CallingConv::ID CallConv) {
Dan Gohman85dbdda2015-12-04 17:16:07 +0000642 // We currently support the language-independent target-independent
Dan Gohman1ce2b1a2015-12-04 18:27:03 +0000643 // conventions. We don't yet have a way to annotate calls with properties like
644 // "cold", and we don't have any call-clobbered registers, so these are mostly
645 // all handled the same.
Dan Gohmana3f5ce52015-12-04 17:18:32 +0000646 return CallConv == CallingConv::C || CallConv == CallingConv::Fast ||
Dan Gohman1ce2b1a2015-12-04 18:27:03 +0000647 CallConv == CallingConv::Cold ||
648 CallConv == CallingConv::PreserveMost ||
649 CallConv == CallingConv::PreserveAll ||
Keno Fischer5c3cdef2019-08-05 21:36:09 +0000650 CallConv == CallingConv::CXX_FAST_TLS ||
651 CallConv == CallingConv::WASM_EmscriptenInvoke;
Dan Gohman85dbdda2015-12-04 17:16:07 +0000652}
653
Heejin Ahnf208f632018-09-05 01:27:38 +0000654SDValue
655WebAssemblyTargetLowering::LowerCall(CallLoweringInfo &CLI,
656 SmallVectorImpl<SDValue> &InVals) const {
JF Bastiend8a9d662015-08-24 21:59:51 +0000657 SelectionDAG &DAG = CLI.DAG;
658 SDLoc DL = CLI.DL;
659 SDValue Chain = CLI.Chain;
660 SDValue Callee = CLI.Callee;
661 MachineFunction &MF = DAG.getMachineFunction();
Derek Schuff992d83f2016-02-10 20:14:15 +0000662 auto Layout = MF.getDataLayout();
JF Bastiend8a9d662015-08-24 21:59:51 +0000663
664 CallingConv::ID CallConv = CLI.CallConv;
Heejin Ahn18c56a02019-02-04 19:13:39 +0000665 if (!callingConvSupported(CallConv))
Dan Gohman9cc692b2015-10-02 20:54:23 +0000666 fail(DL, DAG,
667 "WebAssembly doesn't support language-specific or target-specific "
668 "calling conventions yet");
JF Bastiend8a9d662015-08-24 21:59:51 +0000669 if (CLI.IsPatchPoint)
670 fail(DL, DAG, "WebAssembly doesn't support patch point yet");
671
Thomas Livelye0a9dce2019-07-30 18:08:39 +0000672 if (CLI.IsTailCall) {
673 bool MustTail = CLI.CS && CLI.CS.isMustTailCall();
674 if (Subtarget->hasTailCall() && !CLI.IsVarArg) {
675 // Do not tail call unless caller and callee return types match
676 const Function &F = MF.getFunction();
677 const TargetMachine &TM = getTargetMachine();
678 Type *RetTy = F.getReturnType();
679 SmallVector<MVT, 4> CallerRetTys;
680 SmallVector<MVT, 4> CalleeRetTys;
681 computeLegalValueVTs(F, TM, RetTy, CallerRetTys);
682 computeLegalValueVTs(F, TM, CLI.RetTy, CalleeRetTys);
683 bool TypesMatch = CallerRetTys.size() == CalleeRetTys.size() &&
684 std::equal(CallerRetTys.begin(), CallerRetTys.end(),
685 CalleeRetTys.begin());
686 if (!TypesMatch) {
687 // musttail in this case would be an LLVM IR validation failure
688 assert(!MustTail);
689 CLI.IsTailCall = false;
690 }
691 } else {
692 CLI.IsTailCall = false;
693 if (MustTail) {
694 if (CLI.IsVarArg) {
695 // The return would pop the argument buffer
696 fail(DL, DAG, "WebAssembly does not support varargs tail calls");
697 } else {
698 fail(DL, DAG, "WebAssembly 'tail-call' feature not enabled");
699 }
700 }
701 }
Thomas Livelya1d97a92019-06-26 16:17:15 +0000702 }
Dan Gohman9cc692b2015-10-02 20:54:23 +0000703
JF Bastiend8a9d662015-08-24 21:59:51 +0000704 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
Dan Gohman2d822e72015-12-04 17:12:52 +0000705 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
Derek Schuff4dd67782016-01-27 21:17:39 +0000706 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
Keno Fischer5c3cdef2019-08-05 21:36:09 +0000707
708 // The generic code may have added an sret argument. If we're lowering an
709 // invoke function, the ABI requires that the function pointer be the first
710 // argument, so we may have to swap the arguments.
711 if (CallConv == CallingConv::WASM_EmscriptenInvoke && Outs.size() >= 2 &&
712 Outs[0].Flags.isSRet()) {
713 std::swap(Outs[0], Outs[1]);
714 std::swap(OutVals[0], OutVals[1]);
715 }
716
Dan Gohman910ba332018-06-26 03:18:38 +0000717 unsigned NumFixedArgs = 0;
Heejin Ahn18c56a02019-02-04 19:13:39 +0000718 for (unsigned I = 0; I < Outs.size(); ++I) {
719 const ISD::OutputArg &Out = Outs[I];
720 SDValue &OutVal = OutVals[I];
Dan Gohman7935fa32015-12-10 00:22:40 +0000721 if (Out.Flags.isNest())
722 fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
Dan Gohman2d822e72015-12-04 17:12:52 +0000723 if (Out.Flags.isInAlloca())
Dan Gohman7935fa32015-12-10 00:22:40 +0000724 fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
Dan Gohman2d822e72015-12-04 17:12:52 +0000725 if (Out.Flags.isInConsecutiveRegs())
Dan Gohman7935fa32015-12-10 00:22:40 +0000726 fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
Dan Gohman2d822e72015-12-04 17:12:52 +0000727 if (Out.Flags.isInConsecutiveRegsLast())
Dan Gohman7935fa32015-12-10 00:22:40 +0000728 fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
Dan Gohmana6771b32016-02-12 21:30:18 +0000729 if (Out.Flags.isByVal() && Out.Flags.getByValSize() != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +0000730 auto &MFI = MF.getFrameInfo();
731 int FI = MFI.CreateStackObject(Out.Flags.getByValSize(),
732 Out.Flags.getByValAlign(),
733 /*isSS=*/false);
Derek Schuff4dd67782016-01-27 21:17:39 +0000734 SDValue SizeNode =
735 DAG.getConstant(Out.Flags.getByValSize(), DL, MVT::i32);
Derek Schuff992d83f2016-02-10 20:14:15 +0000736 SDValue FINode = DAG.getFrameIndex(FI, getPointerTy(Layout));
Derek Schuff4dd67782016-01-27 21:17:39 +0000737 Chain = DAG.getMemcpy(
738 Chain, DL, FINode, OutVal, SizeNode, Out.Flags.getByValAlign(),
Dan Gohman476ffce2016-02-17 01:43:37 +0000739 /*isVolatile*/ false, /*AlwaysInline=*/false,
Derek Schuff4dd67782016-01-27 21:17:39 +0000740 /*isTailCall*/ false, MachinePointerInfo(), MachinePointerInfo());
741 OutVal = FINode;
742 }
Dan Gohman910ba332018-06-26 03:18:38 +0000743 // Count the number of fixed args *after* legalization.
744 NumFixedArgs += Out.IsFixed;
Dan Gohman2d822e72015-12-04 17:12:52 +0000745 }
746
JF Bastiend8a9d662015-08-24 21:59:51 +0000747 bool IsVarArg = CLI.IsVarArg;
Derek Schuff992d83f2016-02-10 20:14:15 +0000748 auto PtrVT = getPointerTy(Layout);
Dan Gohmane590b332015-09-09 01:52:45 +0000749
JF Bastiend8a9d662015-08-24 21:59:51 +0000750 // Analyze operands of the call, assigning locations to each operand.
751 SmallVector<CCValAssign, 16> ArgLocs;
752 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
JF Bastiend8a9d662015-08-24 21:59:51 +0000753
Dan Gohman35bfb242015-12-04 23:22:35 +0000754 if (IsVarArg) {
Derek Schuff27501e22016-02-10 19:51:04 +0000755 // Outgoing non-fixed arguments are placed in a buffer. First
756 // compute their offsets and the total amount of buffer space needed.
Dan Gohmanc71132c2019-02-26 05:20:19 +0000757 for (unsigned I = NumFixedArgs; I < Outs.size(); ++I) {
758 const ISD::OutputArg &Out = Outs[I];
759 SDValue &Arg = OutVals[I];
Dan Gohman35bfb242015-12-04 23:22:35 +0000760 EVT VT = Arg.getValueType();
761 assert(VT != MVT::iPTR && "Legalized args should be concrete");
762 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
Dan Gohmanc71132c2019-02-26 05:20:19 +0000763 unsigned Align = std::max(Out.Flags.getOrigAlign(),
764 Layout.getABITypeAlignment(Ty));
Derek Schuff992d83f2016-02-10 20:14:15 +0000765 unsigned Offset = CCInfo.AllocateStack(Layout.getTypeAllocSize(Ty),
Dan Gohmanc71132c2019-02-26 05:20:19 +0000766 Align);
Dan Gohman35bfb242015-12-04 23:22:35 +0000767 CCInfo.addLoc(CCValAssign::getMem(ArgLocs.size(), VT.getSimpleVT(),
768 Offset, VT.getSimpleVT(),
769 CCValAssign::Full));
770 }
771 }
772
773 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
774
Derek Schuff27501e22016-02-10 19:51:04 +0000775 SDValue FINode;
776 if (IsVarArg && NumBytes) {
Dan Gohman35bfb242015-12-04 23:22:35 +0000777 // For non-fixed arguments, next emit stores to store the argument values
Derek Schuff27501e22016-02-10 19:51:04 +0000778 // to the stack buffer at the offsets computed above.
Matthias Braun941a7052016-07-28 18:40:00 +0000779 int FI = MF.getFrameInfo().CreateStackObject(NumBytes,
780 Layout.getStackAlignment(),
781 /*isSS=*/false);
Dan Gohman35bfb242015-12-04 23:22:35 +0000782 unsigned ValNo = 0;
783 SmallVector<SDValue, 8> Chains;
784 for (SDValue Arg :
785 make_range(OutVals.begin() + NumFixedArgs, OutVals.end())) {
786 assert(ArgLocs[ValNo].getValNo() == ValNo &&
787 "ArgLocs should remain in order and only hold varargs args");
788 unsigned Offset = ArgLocs[ValNo++].getLocMemOffset();
Derek Schuff992d83f2016-02-10 20:14:15 +0000789 FINode = DAG.getFrameIndex(FI, getPointerTy(Layout));
Derek Schuff27501e22016-02-10 19:51:04 +0000790 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, FINode,
Dan Gohman35bfb242015-12-04 23:22:35 +0000791 DAG.getConstant(Offset, DL, PtrVT));
Heejin Ahnf208f632018-09-05 01:27:38 +0000792 Chains.push_back(
793 DAG.getStore(Chain, DL, Arg, Add,
794 MachinePointerInfo::getFixedStack(MF, FI, Offset), 0));
Dan Gohman35bfb242015-12-04 23:22:35 +0000795 }
796 if (!Chains.empty())
797 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
Derek Schuff27501e22016-02-10 19:51:04 +0000798 } else if (IsVarArg) {
799 FINode = DAG.getIntPtrConstant(0, DL);
Dan Gohman35bfb242015-12-04 23:22:35 +0000800 }
801
Sam Clegg492f7522019-03-26 19:46:15 +0000802 if (Callee->getOpcode() == ISD::GlobalAddress) {
803 // If the callee is a GlobalAddress node (quite common, every direct call
804 // is) turn it into a TargetGlobalAddress node so that LowerGlobalAddress
805 // doesn't at MO_GOT which is not needed for direct calls.
806 GlobalAddressSDNode* GA = cast<GlobalAddressSDNode>(Callee);
807 Callee = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
808 getPointerTy(DAG.getDataLayout()),
809 GA->getOffset());
810 Callee = DAG.getNode(WebAssemblyISD::Wrapper, DL,
811 getPointerTy(DAG.getDataLayout()), Callee);
812 }
813
Dan Gohman35bfb242015-12-04 23:22:35 +0000814 // Compute the operands for the CALLn node.
JF Bastiend8a9d662015-08-24 21:59:51 +0000815 SmallVector<SDValue, 16> Ops;
816 Ops.push_back(Chain);
JF Bastienaf111db2015-08-24 22:16:48 +0000817 Ops.push_back(Callee);
Dan Gohman35bfb242015-12-04 23:22:35 +0000818
819 // Add all fixed arguments. Note that for non-varargs calls, NumFixedArgs
820 // isn't reliable.
821 Ops.append(OutVals.begin(),
822 IsVarArg ? OutVals.begin() + NumFixedArgs : OutVals.end());
Derek Schuff27501e22016-02-10 19:51:04 +0000823 // Add a pointer to the vararg buffer.
Heejin Ahnf208f632018-09-05 01:27:38 +0000824 if (IsVarArg)
825 Ops.push_back(FINode);
JF Bastiend8a9d662015-08-24 21:59:51 +0000826
Derek Schuff27501e22016-02-10 19:51:04 +0000827 SmallVector<EVT, 8> InTys;
Dan Gohman2d822e72015-12-04 17:12:52 +0000828 for (const auto &In : Ins) {
Dan Gohman7935fa32015-12-10 00:22:40 +0000829 assert(!In.Flags.isByVal() && "byval is not valid for return values");
830 assert(!In.Flags.isNest() && "nest is not valid for return values");
Dan Gohman2d822e72015-12-04 17:12:52 +0000831 if (In.Flags.isInAlloca())
Dan Gohman7935fa32015-12-10 00:22:40 +0000832 fail(DL, DAG, "WebAssembly hasn't implemented inalloca return values");
Dan Gohman2d822e72015-12-04 17:12:52 +0000833 if (In.Flags.isInConsecutiveRegs())
Dan Gohman7935fa32015-12-10 00:22:40 +0000834 fail(DL, DAG, "WebAssembly hasn't implemented cons regs return values");
Dan Gohman2d822e72015-12-04 17:12:52 +0000835 if (In.Flags.isInConsecutiveRegsLast())
Dan Gohman4b9d7912015-12-15 22:01:29 +0000836 fail(DL, DAG,
837 "WebAssembly hasn't implemented cons regs last return values");
Dan Gohman2d822e72015-12-04 17:12:52 +0000838 // Ignore In.getOrigAlign() because all our arguments are passed in
839 // registers.
Derek Schuff27501e22016-02-10 19:51:04 +0000840 InTys.push_back(In.VT);
Dan Gohman2d822e72015-12-04 17:12:52 +0000841 }
Thomas Livelya1d97a92019-06-26 16:17:15 +0000842
843 if (CLI.IsTailCall) {
844 // ret_calls do not return values to the current frame
845 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
846 return DAG.getNode(WebAssemblyISD::RET_CALL, DL, NodeTys, Ops);
847 }
848
Derek Schuff27501e22016-02-10 19:51:04 +0000849 InTys.push_back(MVT::Other);
Thomas Lively3ef169e2019-12-13 10:41:25 -0800850 unsigned Opc;
851 // TODO: Remove CALL0 and CALL1 in favor of CALL
852 switch (Ins.size()) {
853 case 0:
854 Opc = WebAssemblyISD::CALL0;
855 break;
856 case 1:
857 Opc = WebAssemblyISD::CALL1;
858 break;
859 default:
860 Opc = WebAssemblyISD::CALL;
861 break;
JF Bastienaf111db2015-08-24 22:16:48 +0000862 }
Thomas Lively3ef169e2019-12-13 10:41:25 -0800863 SDVTList InTyList = DAG.getVTList(InTys);
864 SDValue Res = DAG.getNode(Opc, DL, InTyList, Ops);
JF Bastiend8a9d662015-08-24 21:59:51 +0000865
Thomas Lively3ef169e2019-12-13 10:41:25 -0800866 for (size_t I = 0; I < Ins.size(); ++I)
867 InVals.push_back(Res.getValue(I));
868
869 // Return the chain
870 return Res.getValue(Ins.size());
JF Bastiend8a9d662015-08-24 21:59:51 +0000871}
872
JF Bastienb9073fb2015-07-22 21:28:15 +0000873bool WebAssemblyTargetLowering::CanLowerReturn(
Dan Gohman7a6b9822015-11-29 22:32:02 +0000874 CallingConv::ID /*CallConv*/, MachineFunction & /*MF*/, bool /*IsVarArg*/,
875 const SmallVectorImpl<ISD::OutputArg> &Outs,
876 LLVMContext & /*Context*/) const {
Thomas Lively00f9e5a2019-10-09 21:42:08 +0000877 // WebAssembly can only handle returning tuples with multivalue enabled
878 return Subtarget->hasMultivalue() || Outs.size() <= 1;
JF Bastienb9073fb2015-07-22 21:28:15 +0000879}
880
881SDValue WebAssemblyTargetLowering::LowerReturn(
Dan Gohman35bfb242015-12-04 23:22:35 +0000882 SDValue Chain, CallingConv::ID CallConv, bool /*IsVarArg*/,
JF Bastienb9073fb2015-07-22 21:28:15 +0000883 const SmallVectorImpl<ISD::OutputArg> &Outs,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000884 const SmallVectorImpl<SDValue> &OutVals, const SDLoc &DL,
JF Bastienb9073fb2015-07-22 21:28:15 +0000885 SelectionDAG &DAG) const {
Simon Pilgrim788ba152019-10-10 12:21:52 +0000886 assert((Subtarget->hasMultivalue() || Outs.size() <= 1) &&
887 "MVP WebAssembly can only return up to one value");
Heejin Ahn18c56a02019-02-04 19:13:39 +0000888 if (!callingConvSupported(CallConv))
JF Bastienb9073fb2015-07-22 21:28:15 +0000889 fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
890
JF Bastien600aee92015-07-31 17:53:38 +0000891 SmallVector<SDValue, 4> RetOps(1, Chain);
892 RetOps.append(OutVals.begin(), OutVals.end());
JF Bastien4a2d5602015-07-31 21:04:18 +0000893 Chain = DAG.getNode(WebAssemblyISD::RETURN, DL, MVT::Other, RetOps);
JF Bastienb9073fb2015-07-22 21:28:15 +0000894
Dan Gohman754cd112015-11-11 01:33:02 +0000895 // Record the number and types of the return values.
896 for (const ISD::OutputArg &Out : Outs) {
Dan Gohmanac132e92015-12-02 23:40:03 +0000897 assert(!Out.Flags.isByVal() && "byval is not valid for return values");
898 assert(!Out.Flags.isNest() && "nest is not valid for return values");
Dan Gohman35bfb242015-12-04 23:22:35 +0000899 assert(Out.IsFixed && "non-fixed return value is not valid");
Dan Gohman754cd112015-11-11 01:33:02 +0000900 if (Out.Flags.isInAlloca())
901 fail(DL, DAG, "WebAssembly hasn't implemented inalloca results");
Dan Gohman754cd112015-11-11 01:33:02 +0000902 if (Out.Flags.isInConsecutiveRegs())
903 fail(DL, DAG, "WebAssembly hasn't implemented cons regs results");
904 if (Out.Flags.isInConsecutiveRegsLast())
905 fail(DL, DAG, "WebAssembly hasn't implemented cons regs last results");
Dan Gohman754cd112015-11-11 01:33:02 +0000906 }
907
JF Bastienb9073fb2015-07-22 21:28:15 +0000908 return Chain;
909}
910
911SDValue WebAssemblyTargetLowering::LowerFormalArguments(
Derek Schuff27501e22016-02-10 19:51:04 +0000912 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000913 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
914 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
Heejin Ahn18c56a02019-02-04 19:13:39 +0000915 if (!callingConvSupported(CallConv))
JF Bastienb9073fb2015-07-22 21:28:15 +0000916 fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
JF Bastienb9073fb2015-07-22 21:28:15 +0000917
Dan Gohman2726b882016-10-06 22:29:32 +0000918 MachineFunction &MF = DAG.getMachineFunction();
919 auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>();
920
Dan Gohmanfb3e0592015-11-25 19:36:19 +0000921 // Set up the incoming ARGUMENTS value, which serves to represent the liveness
922 // of the incoming values before they're represented by virtual registers.
923 MF.getRegInfo().addLiveIn(WebAssembly::ARGUMENTS);
924
JF Bastien600aee92015-07-31 17:53:38 +0000925 for (const ISD::InputArg &In : Ins) {
JF Bastien600aee92015-07-31 17:53:38 +0000926 if (In.Flags.isInAlloca())
927 fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
928 if (In.Flags.isNest())
929 fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
JF Bastien600aee92015-07-31 17:53:38 +0000930 if (In.Flags.isInConsecutiveRegs())
931 fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
932 if (In.Flags.isInConsecutiveRegsLast())
933 fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
Dan Gohman9c54d3b2015-11-25 18:13:18 +0000934 // Ignore In.getOrigAlign() because all our arguments are passed in
935 // registers.
Heejin Ahnf208f632018-09-05 01:27:38 +0000936 InVals.push_back(In.Used ? DAG.getNode(WebAssemblyISD::ARGUMENT, DL, In.VT,
937 DAG.getTargetConstant(InVals.size(),
938 DL, MVT::i32))
939 : DAG.getUNDEF(In.VT));
Dan Gohman754cd112015-11-11 01:33:02 +0000940
941 // Record the number and types of arguments.
Derek Schuff27501e22016-02-10 19:51:04 +0000942 MFI->addParam(In.VT);
JF Bastien600aee92015-07-31 17:53:38 +0000943 }
JF Bastienb9073fb2015-07-22 21:28:15 +0000944
Derek Schuff27501e22016-02-10 19:51:04 +0000945 // Varargs are copied into a buffer allocated by the caller, and a pointer to
946 // the buffer is passed as an argument.
947 if (IsVarArg) {
948 MVT PtrVT = getPointerTy(MF.getDataLayout());
Daniel Sanders05c145d2019-08-12 22:40:45 +0000949 Register VarargVreg =
Derek Schuff27501e22016-02-10 19:51:04 +0000950 MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrVT));
951 MFI->setVarargBufferVreg(VarargVreg);
952 Chain = DAG.getCopyToReg(
953 Chain, DL, VarargVreg,
954 DAG.getNode(WebAssemblyISD::ARGUMENT, DL, PtrVT,
955 DAG.getTargetConstant(Ins.size(), DL, MVT::i32)));
956 MFI->addParam(PtrVT);
957 }
Dan Gohman35bfb242015-12-04 23:22:35 +0000958
Derek Schuff77a7a382018-10-03 22:22:48 +0000959 // Record the number and types of arguments and results.
Dan Gohman2726b882016-10-06 22:29:32 +0000960 SmallVector<MVT, 4> Params;
961 SmallVector<MVT, 4> Results;
Heejin Ahn18c56a02019-02-04 19:13:39 +0000962 computeSignatureVTs(MF.getFunction().getFunctionType(), MF.getFunction(),
Derek Schuff77a7a382018-10-03 22:22:48 +0000963 DAG.getTarget(), Params, Results);
Dan Gohman2726b882016-10-06 22:29:32 +0000964 for (MVT VT : Results)
965 MFI->addResult(VT);
Derek Schuff77a7a382018-10-03 22:22:48 +0000966 // TODO: Use signatures in WebAssemblyMachineFunctionInfo too and unify
967 // the param logic here with ComputeSignatureVTs
968 assert(MFI->getParams().size() == Params.size() &&
969 std::equal(MFI->getParams().begin(), MFI->getParams().end(),
970 Params.begin()));
Dan Gohman2726b882016-10-06 22:29:32 +0000971
JF Bastienb9073fb2015-07-22 21:28:15 +0000972 return Chain;
973}
974
Thomas Livelye18b5c62019-05-23 18:09:26 +0000975void WebAssemblyTargetLowering::ReplaceNodeResults(
976 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
977 switch (N->getOpcode()) {
978 case ISD::SIGN_EXTEND_INREG:
979 // Do not add any results, signifying that N should not be custom lowered
980 // after all. This happens because simd128 turns on custom lowering for
981 // SIGN_EXTEND_INREG, but for non-vector sign extends the result might be an
982 // illegal type.
983 break;
984 default:
985 llvm_unreachable(
986 "ReplaceNodeResults not implemented for this op for WebAssembly!");
987 }
988}
989
Dan Gohman10e730a2015-06-29 23:51:55 +0000990//===----------------------------------------------------------------------===//
JF Bastienaf111db2015-08-24 22:16:48 +0000991// Custom lowering hooks.
Dan Gohman10e730a2015-06-29 23:51:55 +0000992//===----------------------------------------------------------------------===//
993
JF Bastienaf111db2015-08-24 22:16:48 +0000994SDValue WebAssemblyTargetLowering::LowerOperation(SDValue Op,
995 SelectionDAG &DAG) const {
Derek Schuff51699a82016-02-12 22:56:03 +0000996 SDLoc DL(Op);
JF Bastienaf111db2015-08-24 22:16:48 +0000997 switch (Op.getOpcode()) {
Heejin Ahnf208f632018-09-05 01:27:38 +0000998 default:
999 llvm_unreachable("unimplemented operation lowering");
1000 return SDValue();
1001 case ISD::FrameIndex:
1002 return LowerFrameIndex(Op, DAG);
1003 case ISD::GlobalAddress:
1004 return LowerGlobalAddress(Op, DAG);
1005 case ISD::ExternalSymbol:
1006 return LowerExternalSymbol(Op, DAG);
1007 case ISD::JumpTable:
1008 return LowerJumpTable(Op, DAG);
1009 case ISD::BR_JT:
1010 return LowerBR_JT(Op, DAG);
1011 case ISD::VASTART:
1012 return LowerVASTART(Op, DAG);
1013 case ISD::BlockAddress:
1014 case ISD::BRIND:
1015 fail(DL, DAG, "WebAssembly hasn't implemented computed gotos");
1016 return SDValue();
Thomas Lively1a3cbe72019-05-23 01:24:01 +00001017 case ISD::RETURNADDR:
1018 return LowerRETURNADDR(Op, DAG);
Heejin Ahnf208f632018-09-05 01:27:38 +00001019 case ISD::FRAMEADDR:
1020 return LowerFRAMEADDR(Op, DAG);
1021 case ISD::CopyToReg:
1022 return LowerCopyToReg(Op, DAG);
Thomas Livelyfb84fd72018-11-02 00:06:56 +00001023 case ISD::EXTRACT_VECTOR_ELT:
1024 case ISD::INSERT_VECTOR_ELT:
1025 return LowerAccessVectorElement(Op, DAG);
Heejin Ahnda419bd2018-11-14 02:46:21 +00001026 case ISD::INTRINSIC_VOID:
Heejin Ahnd6f48782019-01-30 03:21:57 +00001027 case ISD::INTRINSIC_WO_CHAIN:
1028 case ISD::INTRINSIC_W_CHAIN:
1029 return LowerIntrinsic(Op, DAG);
Thomas Lively64a39a12019-01-10 22:32:11 +00001030 case ISD::SIGN_EXTEND_INREG:
1031 return LowerSIGN_EXTEND_INREG(Op, DAG);
Thomas Lively079816e2019-01-30 02:23:29 +00001032 case ISD::BUILD_VECTOR:
1033 return LowerBUILD_VECTOR(Op, DAG);
Thomas Livelya0d25812018-09-07 21:54:46 +00001034 case ISD::VECTOR_SHUFFLE:
1035 return LowerVECTOR_SHUFFLE(Op, DAG);
Thomas Livelyecb7daf2019-11-01 10:21:00 -07001036 case ISD::SETCC:
1037 return LowerSETCC(Op, DAG);
Thomas Lively55735d52018-10-20 01:31:18 +00001038 case ISD::SHL:
1039 case ISD::SRA:
1040 case ISD::SRL:
1041 return LowerShift(Op, DAG);
JF Bastienaf111db2015-08-24 22:16:48 +00001042 }
1043}
1044
Derek Schuffaadc89c2016-02-16 18:18:36 +00001045SDValue WebAssemblyTargetLowering::LowerCopyToReg(SDValue Op,
1046 SelectionDAG &DAG) const {
1047 SDValue Src = Op.getOperand(2);
1048 if (isa<FrameIndexSDNode>(Src.getNode())) {
1049 // CopyToReg nodes don't support FrameIndex operands. Other targets select
1050 // the FI to some LEA-like instruction, but since we don't have that, we
1051 // need to insert some kind of instruction that can take an FI operand and
1052 // produces a value usable by CopyToReg (i.e. in a vreg). So insert a dummy
Thomas Lively6a87dda2019-01-08 06:25:55 +00001053 // local.copy between Op and its FI operand.
Dan Gohman02c08712016-02-20 23:09:44 +00001054 SDValue Chain = Op.getOperand(0);
Derek Schuffaadc89c2016-02-16 18:18:36 +00001055 SDLoc DL(Op);
Dan Gohman02c08712016-02-20 23:09:44 +00001056 unsigned Reg = cast<RegisterSDNode>(Op.getOperand(1))->getReg();
Derek Schuffaadc89c2016-02-16 18:18:36 +00001057 EVT VT = Src.getValueType();
Heejin Ahnf208f632018-09-05 01:27:38 +00001058 SDValue Copy(DAG.getMachineNode(VT == MVT::i32 ? WebAssembly::COPY_I32
1059 : WebAssembly::COPY_I64,
1060 DL, VT, Src),
1061 0);
Dan Gohman02c08712016-02-20 23:09:44 +00001062 return Op.getNode()->getNumValues() == 1
1063 ? DAG.getCopyToReg(Chain, DL, Reg, Copy)
Heejin Ahnf208f632018-09-05 01:27:38 +00001064 : DAG.getCopyToReg(Chain, DL, Reg, Copy,
1065 Op.getNumOperands() == 4 ? Op.getOperand(3)
1066 : SDValue());
Derek Schuffaadc89c2016-02-16 18:18:36 +00001067 }
1068 return SDValue();
1069}
1070
Derek Schuff9769deb2015-12-11 23:49:46 +00001071SDValue WebAssemblyTargetLowering::LowerFrameIndex(SDValue Op,
1072 SelectionDAG &DAG) const {
1073 int FI = cast<FrameIndexSDNode>(Op)->getIndex();
1074 return DAG.getTargetFrameIndex(FI, Op.getValueType());
1075}
1076
Thomas Lively1a3cbe72019-05-23 01:24:01 +00001077SDValue WebAssemblyTargetLowering::LowerRETURNADDR(SDValue Op,
1078 SelectionDAG &DAG) const {
1079 SDLoc DL(Op);
1080
1081 if (!Subtarget->getTargetTriple().isOSEmscripten()) {
1082 fail(DL, DAG,
1083 "Non-Emscripten WebAssembly hasn't implemented "
1084 "__builtin_return_address");
1085 return SDValue();
1086 }
1087
1088 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1089 return SDValue();
1090
1091 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
Shiva Chen72a41e72019-08-22 04:59:43 +00001092 MakeLibCallOptions CallOptions;
Thomas Lively1a3cbe72019-05-23 01:24:01 +00001093 return makeLibCall(DAG, RTLIB::RETURN_ADDRESS, Op.getValueType(),
Shiva Chen72a41e72019-08-22 04:59:43 +00001094 {DAG.getConstant(Depth, DL, MVT::i32)}, CallOptions, DL)
Thomas Lively1a3cbe72019-05-23 01:24:01 +00001095 .first;
1096}
1097
Dan Gohman94c65662016-02-16 23:48:04 +00001098SDValue WebAssemblyTargetLowering::LowerFRAMEADDR(SDValue Op,
1099 SelectionDAG &DAG) const {
1100 // Non-zero depths are not supported by WebAssembly currently. Use the
1101 // legalizer's default expansion, which is to return 0 (what this function is
1102 // documented to do).
Dan Gohman1d547bf2016-02-17 00:14:03 +00001103 if (Op.getConstantOperandVal(0) > 0)
Dan Gohman94c65662016-02-16 23:48:04 +00001104 return SDValue();
1105
Matthias Braun941a7052016-07-28 18:40:00 +00001106 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
Dan Gohman94c65662016-02-16 23:48:04 +00001107 EVT VT = Op.getValueType();
Daniel Sanders05c145d2019-08-12 22:40:45 +00001108 Register FP =
Dan Gohman94c65662016-02-16 23:48:04 +00001109 Subtarget->getRegisterInfo()->getFrameRegister(DAG.getMachineFunction());
1110 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), FP, VT);
1111}
1112
JF Bastienaf111db2015-08-24 22:16:48 +00001113SDValue WebAssemblyTargetLowering::LowerGlobalAddress(SDValue Op,
1114 SelectionDAG &DAG) const {
1115 SDLoc DL(Op);
1116 const auto *GA = cast<GlobalAddressSDNode>(Op);
1117 EVT VT = Op.getValueType();
Dan Gohman26c67652016-01-11 23:38:05 +00001118 assert(GA->getTargetFlags() == 0 &&
1119 "Unexpected target flags on generic GlobalAddressSDNode");
JF Bastienaf111db2015-08-24 22:16:48 +00001120 if (GA->getAddressSpace() != 0)
1121 fail(DL, DAG, "WebAssembly only expects the 0 address space");
Sam Clegg492f7522019-03-26 19:46:15 +00001122
Sam Cleggef4c66c2019-04-03 00:17:29 +00001123 unsigned OperandFlags = 0;
Sam Clegg492f7522019-03-26 19:46:15 +00001124 if (isPositionIndependent()) {
1125 const GlobalValue *GV = GA->getGlobal();
1126 if (getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) {
1127 MachineFunction &MF = DAG.getMachineFunction();
1128 MVT PtrVT = getPointerTy(MF.getDataLayout());
1129 const char *BaseName;
Sam Clegg2a7cac92019-04-04 17:43:50 +00001130 if (GV->getValueType()->isFunctionTy()) {
Sam Clegg492f7522019-03-26 19:46:15 +00001131 BaseName = MF.createExternalSymbolName("__table_base");
Sam Clegg2a7cac92019-04-04 17:43:50 +00001132 OperandFlags = WebAssemblyII::MO_TABLE_BASE_REL;
1133 }
1134 else {
Sam Clegg492f7522019-03-26 19:46:15 +00001135 BaseName = MF.createExternalSymbolName("__memory_base");
Sam Clegg2a7cac92019-04-04 17:43:50 +00001136 OperandFlags = WebAssemblyII::MO_MEMORY_BASE_REL;
1137 }
Sam Clegg492f7522019-03-26 19:46:15 +00001138 SDValue BaseAddr =
1139 DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT,
1140 DAG.getTargetExternalSymbol(BaseName, PtrVT));
1141
1142 SDValue SymAddr = DAG.getNode(
1143 WebAssemblyISD::WrapperPIC, DL, VT,
Sam Clegg2a7cac92019-04-04 17:43:50 +00001144 DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT, GA->getOffset(),
1145 OperandFlags));
Sam Clegg492f7522019-03-26 19:46:15 +00001146
1147 return DAG.getNode(ISD::ADD, DL, VT, BaseAddr, SymAddr);
1148 } else {
Sam Cleggef4c66c2019-04-03 00:17:29 +00001149 OperandFlags = WebAssemblyII::MO_GOT;
Sam Clegg492f7522019-03-26 19:46:15 +00001150 }
1151 }
1152
1153 return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1154 DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT,
Sam Cleggef4c66c2019-04-03 00:17:29 +00001155 GA->getOffset(), OperandFlags));
JF Bastienaf111db2015-08-24 22:16:48 +00001156}
1157
Heejin Ahnf208f632018-09-05 01:27:38 +00001158SDValue
1159WebAssemblyTargetLowering::LowerExternalSymbol(SDValue Op,
1160 SelectionDAG &DAG) const {
Dan Gohman2c8fe6a2015-11-25 16:44:29 +00001161 SDLoc DL(Op);
1162 const auto *ES = cast<ExternalSymbolSDNode>(Op);
1163 EVT VT = Op.getValueType();
Dan Gohman26c67652016-01-11 23:38:05 +00001164 assert(ES->getTargetFlags() == 0 &&
1165 "Unexpected target flags on generic ExternalSymbolSDNode");
Sam Cleggef4c66c2019-04-03 00:17:29 +00001166 return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1167 DAG.getTargetExternalSymbol(ES->getSymbol(), VT));
Dan Gohman2c8fe6a2015-11-25 16:44:29 +00001168}
1169
Dan Gohman950a13c2015-09-16 16:51:30 +00001170SDValue WebAssemblyTargetLowering::LowerJumpTable(SDValue Op,
1171 SelectionDAG &DAG) const {
1172 // There's no need for a Wrapper node because we always incorporate a jump
Dan Gohman14026062016-03-08 03:18:12 +00001173 // table operand into a BR_TABLE instruction, rather than ever
Dan Gohmanbb7ce8e2015-11-20 03:02:49 +00001174 // materializing it in a register.
Dan Gohman950a13c2015-09-16 16:51:30 +00001175 const JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1176 return DAG.getTargetJumpTable(JT->getIndex(), Op.getValueType(),
1177 JT->getTargetFlags());
1178}
1179
1180SDValue WebAssemblyTargetLowering::LowerBR_JT(SDValue Op,
1181 SelectionDAG &DAG) const {
1182 SDLoc DL(Op);
1183 SDValue Chain = Op.getOperand(0);
1184 const auto *JT = cast<JumpTableSDNode>(Op.getOperand(1));
1185 SDValue Index = Op.getOperand(2);
1186 assert(JT->getTargetFlags() == 0 && "WebAssembly doesn't set target flags");
1187
1188 SmallVector<SDValue, 8> Ops;
1189 Ops.push_back(Chain);
1190 Ops.push_back(Index);
1191
1192 MachineJumpTableInfo *MJTI = DAG.getMachineFunction().getJumpTableInfo();
1193 const auto &MBBs = MJTI->getJumpTables()[JT->getIndex()].MBBs;
1194
Dan Gohman14026062016-03-08 03:18:12 +00001195 // Add an operand for each case.
Heejin Ahnf208f632018-09-05 01:27:38 +00001196 for (auto MBB : MBBs)
1197 Ops.push_back(DAG.getBasicBlock(MBB));
Dan Gohman14026062016-03-08 03:18:12 +00001198
Dan Gohman950a13c2015-09-16 16:51:30 +00001199 // TODO: For now, we just pick something arbitrary for a default case for now.
1200 // We really want to sniff out the guard and put in the real default case (and
1201 // delete the guard).
1202 Ops.push_back(DAG.getBasicBlock(MBBs[0]));
1203
Dan Gohman14026062016-03-08 03:18:12 +00001204 return DAG.getNode(WebAssemblyISD::BR_TABLE, DL, MVT::Other, Ops);
Dan Gohman950a13c2015-09-16 16:51:30 +00001205}
1206
Dan Gohman35bfb242015-12-04 23:22:35 +00001207SDValue WebAssemblyTargetLowering::LowerVASTART(SDValue Op,
1208 SelectionDAG &DAG) const {
1209 SDLoc DL(Op);
1210 EVT PtrVT = getPointerTy(DAG.getMachineFunction().getDataLayout());
1211
Derek Schuff27501e22016-02-10 19:51:04 +00001212 auto *MFI = DAG.getMachineFunction().getInfo<WebAssemblyFunctionInfo>();
Dan Gohman35bfb242015-12-04 23:22:35 +00001213 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
Derek Schuff27501e22016-02-10 19:51:04 +00001214
1215 SDValue ArgN = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1216 MFI->getVarargBufferVreg(), PtrVT);
1217 return DAG.getStore(Op.getOperand(0), DL, ArgN, Op.getOperand(1),
Derek Schuff1a946e42016-07-15 19:35:43 +00001218 MachinePointerInfo(SV), 0);
Dan Gohman35bfb242015-12-04 23:22:35 +00001219}
1220
Heejin Ahnd6f48782019-01-30 03:21:57 +00001221SDValue WebAssemblyTargetLowering::LowerIntrinsic(SDValue Op,
1222 SelectionDAG &DAG) const {
1223 MachineFunction &MF = DAG.getMachineFunction();
1224 unsigned IntNo;
1225 switch (Op.getOpcode()) {
1226 case ISD::INTRINSIC_VOID:
1227 case ISD::INTRINSIC_W_CHAIN:
1228 IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1229 break;
1230 case ISD::INTRINSIC_WO_CHAIN:
1231 IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1232 break;
1233 default:
1234 llvm_unreachable("Invalid intrinsic");
1235 }
Heejin Ahn5ef4d5f2018-05-31 22:25:54 +00001236 SDLoc DL(Op);
Heejin Ahnd6f48782019-01-30 03:21:57 +00001237
Heejin Ahn5ef4d5f2018-05-31 22:25:54 +00001238 switch (IntNo) {
1239 default:
Heejin Ahn18c56a02019-02-04 19:13:39 +00001240 return SDValue(); // Don't custom lower most intrinsics.
Thomas Lively5d461c92018-10-03 23:02:23 +00001241
Heejin Ahn24faf852018-10-25 23:55:10 +00001242 case Intrinsic::wasm_lsda: {
Heejin Ahn24faf852018-10-25 23:55:10 +00001243 EVT VT = Op.getValueType();
1244 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1245 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
1246 auto &Context = MF.getMMI().getContext();
1247 MCSymbol *S = Context.getOrCreateSymbol(Twine("GCC_except_table") +
1248 Twine(MF.getFunctionNumber()));
1249 return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1250 DAG.getMCSymbol(S, PtrVT));
1251 }
Heejin Ahnda419bd2018-11-14 02:46:21 +00001252
1253 case Intrinsic::wasm_throw: {
Heejin Ahnd6f48782019-01-30 03:21:57 +00001254 // We only support C++ exceptions for now
Heejin Ahnda419bd2018-11-14 02:46:21 +00001255 int Tag = cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue();
Heejin Ahnd6f48782019-01-30 03:21:57 +00001256 if (Tag != CPP_EXCEPTION)
Heejin Ahnda419bd2018-11-14 02:46:21 +00001257 llvm_unreachable("Invalid tag!");
Heejin Ahnd6f48782019-01-30 03:21:57 +00001258 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1259 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
1260 const char *SymName = MF.createExternalSymbolName("__cpp_exception");
Sam Cleggef4c66c2019-04-03 00:17:29 +00001261 SDValue SymNode = DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT,
1262 DAG.getTargetExternalSymbol(SymName, PtrVT));
Heejin Ahnd6f48782019-01-30 03:21:57 +00001263 return DAG.getNode(WebAssemblyISD::THROW, DL,
1264 MVT::Other, // outchain type
1265 {
1266 Op.getOperand(0), // inchain
1267 SymNode, // exception symbol
1268 Op.getOperand(3) // thrown value
1269 });
Heejin Ahnda419bd2018-11-14 02:46:21 +00001270 }
1271 }
1272}
1273
1274SDValue
Thomas Lively64a39a12019-01-10 22:32:11 +00001275WebAssemblyTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
1276 SelectionDAG &DAG) const {
Thomas Lively3d9ca002019-06-04 21:08:20 +00001277 SDLoc DL(Op);
Thomas Lively64a39a12019-01-10 22:32:11 +00001278 // If sign extension operations are disabled, allow sext_inreg only if operand
1279 // is a vector extract. SIMD does not depend on sign extension operations, but
1280 // allowing sext_inreg in this context lets us have simple patterns to select
1281 // extract_lane_s instructions. Expanding sext_inreg everywhere would be
1282 // simpler in this file, but would necessitate large and brittle patterns to
1283 // undo the expansion and select extract_lane_s instructions.
1284 assert(!Subtarget->hasSignExt() && Subtarget->hasSIMD128());
Thomas Lively3d9ca002019-06-04 21:08:20 +00001285 if (Op.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
1286 const SDValue &Extract = Op.getOperand(0);
1287 MVT VecT = Extract.getOperand(0).getSimpleValueType();
1288 MVT ExtractedLaneT = static_cast<VTSDNode *>(Op.getOperand(1).getNode())
1289 ->getVT()
1290 .getSimpleVT();
1291 MVT ExtractedVecT =
1292 MVT::getVectorVT(ExtractedLaneT, 128 / ExtractedLaneT.getSizeInBits());
1293 if (ExtractedVecT == VecT)
1294 return Op;
1295 // Bitcast vector to appropriate type to ensure ISel pattern coverage
1296 const SDValue &Index = Extract.getOperand(1);
1297 unsigned IndexVal =
1298 static_cast<ConstantSDNode *>(Index.getNode())->getZExtValue();
1299 unsigned Scale =
1300 ExtractedVecT.getVectorNumElements() / VecT.getVectorNumElements();
1301 assert(Scale > 1);
1302 SDValue NewIndex =
1303 DAG.getConstant(IndexVal * Scale, DL, Index.getValueType());
1304 SDValue NewExtract = DAG.getNode(
1305 ISD::EXTRACT_VECTOR_ELT, DL, Extract.getValueType(),
1306 DAG.getBitcast(ExtractedVecT, Extract.getOperand(0)), NewIndex);
1307 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, Op.getValueType(),
1308 NewExtract, Op.getOperand(1));
1309 }
Thomas Lively64a39a12019-01-10 22:32:11 +00001310 // Otherwise expand
1311 return SDValue();
1312}
1313
Thomas Lively079816e2019-01-30 02:23:29 +00001314SDValue WebAssemblyTargetLowering::LowerBUILD_VECTOR(SDValue Op,
1315 SelectionDAG &DAG) const {
1316 SDLoc DL(Op);
1317 const EVT VecT = Op.getValueType();
1318 const EVT LaneT = Op.getOperand(0).getValueType();
1319 const size_t Lanes = Op.getNumOperands();
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001320 bool CanSwizzle = Subtarget->hasUnimplementedSIMD128() && VecT == MVT::v16i8;
1321
1322 // BUILD_VECTORs are lowered to the instruction that initializes the highest
1323 // possible number of lanes at once followed by a sequence of replace_lane
1324 // instructions to individually initialize any remaining lanes.
1325
1326 // TODO: Tune this. For example, lanewise swizzling is very expensive, so
1327 // swizzled lanes should be given greater weight.
1328
1329 // TODO: Investigate building vectors by shuffling together vectors built by
1330 // separately specialized means.
1331
Thomas Lively079816e2019-01-30 02:23:29 +00001332 auto IsConstant = [](const SDValue &V) {
1333 return V.getOpcode() == ISD::Constant || V.getOpcode() == ISD::ConstantFP;
1334 };
1335
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001336 // Returns the source vector and index vector pair if they exist. Checks for:
1337 // (extract_vector_elt
1338 // $src,
1339 // (sign_extend_inreg (extract_vector_elt $indices, $i))
1340 // )
1341 auto GetSwizzleSrcs = [](size_t I, const SDValue &Lane) {
1342 auto Bail = std::make_pair(SDValue(), SDValue());
1343 if (Lane->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1344 return Bail;
1345 const SDValue &SwizzleSrc = Lane->getOperand(0);
1346 const SDValue &IndexExt = Lane->getOperand(1);
1347 if (IndexExt->getOpcode() != ISD::SIGN_EXTEND_INREG)
1348 return Bail;
1349 const SDValue &Index = IndexExt->getOperand(0);
1350 if (Index->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1351 return Bail;
1352 const SDValue &SwizzleIndices = Index->getOperand(0);
1353 if (SwizzleSrc.getValueType() != MVT::v16i8 ||
1354 SwizzleIndices.getValueType() != MVT::v16i8 ||
1355 Index->getOperand(1)->getOpcode() != ISD::Constant ||
1356 Index->getConstantOperandVal(1) != I)
1357 return Bail;
1358 return std::make_pair(SwizzleSrc, SwizzleIndices);
1359 };
1360
1361 using ValueEntry = std::pair<SDValue, size_t>;
1362 SmallVector<ValueEntry, 16> SplatValueCounts;
1363
1364 using SwizzleEntry = std::pair<std::pair<SDValue, SDValue>, size_t>;
1365 SmallVector<SwizzleEntry, 16> SwizzleCounts;
1366
1367 auto AddCount = [](auto &Counts, const auto &Val) {
1368 auto CountIt = std::find_if(Counts.begin(), Counts.end(),
1369 [&Val](auto E) { return E.first == Val; });
1370 if (CountIt == Counts.end()) {
1371 Counts.emplace_back(Val, 1);
Thomas Lively079816e2019-01-30 02:23:29 +00001372 } else {
1373 CountIt->second++;
1374 }
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001375 };
Thomas Lively079816e2019-01-30 02:23:29 +00001376
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001377 auto GetMostCommon = [](auto &Counts) {
1378 auto CommonIt =
1379 std::max_element(Counts.begin(), Counts.end(),
1380 [](auto A, auto B) { return A.second < B.second; });
1381 assert(CommonIt != Counts.end() && "Unexpected all-undef build_vector");
1382 return *CommonIt;
1383 };
1384
1385 size_t NumConstantLanes = 0;
1386
1387 // Count eligible lanes for each type of vector creation op
1388 for (size_t I = 0; I < Lanes; ++I) {
1389 const SDValue &Lane = Op->getOperand(I);
1390 if (Lane.isUndef())
1391 continue;
1392
1393 AddCount(SplatValueCounts, Lane);
1394
1395 if (IsConstant(Lane)) {
1396 NumConstantLanes++;
1397 } else if (CanSwizzle) {
1398 auto SwizzleSrcs = GetSwizzleSrcs(I, Lane);
1399 if (SwizzleSrcs.first)
1400 AddCount(SwizzleCounts, SwizzleSrcs);
1401 }
1402 }
1403
1404 SDValue SplatValue;
1405 size_t NumSplatLanes;
1406 std::tie(SplatValue, NumSplatLanes) = GetMostCommon(SplatValueCounts);
1407
1408 SDValue SwizzleSrc;
1409 SDValue SwizzleIndices;
1410 size_t NumSwizzleLanes = 0;
1411 if (SwizzleCounts.size())
1412 std::forward_as_tuple(std::tie(SwizzleSrc, SwizzleIndices),
1413 NumSwizzleLanes) = GetMostCommon(SwizzleCounts);
1414
1415 // Predicate returning true if the lane is properly initialized by the
1416 // original instruction
1417 std::function<bool(size_t, const SDValue &)> IsLaneConstructed;
1418 SDValue Result;
Thomas Lively079816e2019-01-30 02:23:29 +00001419 if (Subtarget->hasUnimplementedSIMD128()) {
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001420 // Prefer swizzles over vector consts over splats
1421 if (NumSwizzleLanes >= NumSplatLanes &&
1422 NumSwizzleLanes >= NumConstantLanes) {
1423 Result = DAG.getNode(WebAssemblyISD::SWIZZLE, DL, VecT, SwizzleSrc,
1424 SwizzleIndices);
1425 auto Swizzled = std::make_pair(SwizzleSrc, SwizzleIndices);
1426 IsLaneConstructed = [&, Swizzled](size_t I, const SDValue &Lane) {
1427 return Swizzled == GetSwizzleSrcs(I, Lane);
1428 };
1429 } else if (NumConstantLanes >= NumSplatLanes) {
Thomas Lively079816e2019-01-30 02:23:29 +00001430 SmallVector<SDValue, 16> ConstLanes;
1431 for (const SDValue &Lane : Op->op_values()) {
1432 if (IsConstant(Lane)) {
1433 ConstLanes.push_back(Lane);
1434 } else if (LaneT.isFloatingPoint()) {
1435 ConstLanes.push_back(DAG.getConstantFP(0, DL, LaneT));
1436 } else {
1437 ConstLanes.push_back(DAG.getConstant(0, DL, LaneT));
1438 }
1439 }
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001440 Result = DAG.getBuildVector(VecT, DL, ConstLanes);
1441 IsLaneConstructed = [&](size_t _, const SDValue &Lane) {
1442 return IsConstant(Lane);
1443 };
Thomas Lively079816e2019-01-30 02:23:29 +00001444 }
1445 }
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001446 if (!Result) {
1447 // Use a splat, but possibly a load_splat
1448 LoadSDNode *SplattedLoad;
1449 if (Subtarget->hasUnimplementedSIMD128() &&
1450 (SplattedLoad = dyn_cast<LoadSDNode>(SplatValue)) &&
1451 SplattedLoad->getMemoryVT() == VecT.getVectorElementType()) {
Thomas Lively3479fd22019-10-31 20:01:02 -07001452 Result = DAG.getMemIntrinsicNode(
1453 WebAssemblyISD::LOAD_SPLAT, DL, DAG.getVTList(VecT),
1454 {SplattedLoad->getChain(), SplattedLoad->getBasePtr(),
1455 SplattedLoad->getOffset()},
1456 SplattedLoad->getMemoryVT(), SplattedLoad->getMemOperand());
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001457 } else {
1458 Result = DAG.getSplatBuildVector(VecT, DL, SplatValue);
1459 }
1460 IsLaneConstructed = [&](size_t _, const SDValue &Lane) {
1461 return Lane == SplatValue;
1462 };
Thomas Lively99d3dd22019-09-23 20:42:12 +00001463 }
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001464
1465 // Add replace_lane instructions for any unhandled values
Thomas Lively079816e2019-01-30 02:23:29 +00001466 for (size_t I = 0; I < Lanes; ++I) {
1467 const SDValue &Lane = Op->getOperand(I);
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001468 if (!Lane.isUndef() && !IsLaneConstructed(I, Lane))
Thomas Lively079816e2019-01-30 02:23:29 +00001469 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VecT, Result, Lane,
1470 DAG.getConstant(I, DL, MVT::i32));
1471 }
Thomas Livelyd5b7a4e2019-10-09 17:39:19 +00001472
Thomas Lively079816e2019-01-30 02:23:29 +00001473 return Result;
1474}
1475
Thomas Lively64a39a12019-01-10 22:32:11 +00001476SDValue
Thomas Livelya0d25812018-09-07 21:54:46 +00001477WebAssemblyTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
1478 SelectionDAG &DAG) const {
1479 SDLoc DL(Op);
1480 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op.getNode())->getMask();
1481 MVT VecType = Op.getOperand(0).getSimpleValueType();
1482 assert(VecType.is128BitVector() && "Unexpected shuffle vector type");
1483 size_t LaneBytes = VecType.getVectorElementType().getSizeInBits() / 8;
1484
1485 // Space for two vector args and sixteen mask indices
1486 SDValue Ops[18];
1487 size_t OpIdx = 0;
1488 Ops[OpIdx++] = Op.getOperand(0);
1489 Ops[OpIdx++] = Op.getOperand(1);
1490
1491 // Expand mask indices to byte indices and materialize them as operands
Heejin Ahn18c56a02019-02-04 19:13:39 +00001492 for (int M : Mask) {
Thomas Livelya0d25812018-09-07 21:54:46 +00001493 for (size_t J = 0; J < LaneBytes; ++J) {
Thomas Lively11a332d02018-10-19 19:08:06 +00001494 // Lower undefs (represented by -1 in mask) to zero
Heejin Ahn18c56a02019-02-04 19:13:39 +00001495 uint64_t ByteIndex = M == -1 ? 0 : (uint64_t)M * LaneBytes + J;
Thomas Lively11a332d02018-10-19 19:08:06 +00001496 Ops[OpIdx++] = DAG.getConstant(ByteIndex, DL, MVT::i32);
Thomas Livelya0d25812018-09-07 21:54:46 +00001497 }
1498 }
1499
Thomas Livelyed951342018-10-24 23:27:40 +00001500 return DAG.getNode(WebAssemblyISD::SHUFFLE, DL, Op.getValueType(), Ops);
Thomas Livelya0d25812018-09-07 21:54:46 +00001501}
1502
Thomas Livelyecb7daf2019-11-01 10:21:00 -07001503SDValue WebAssemblyTargetLowering::LowerSETCC(SDValue Op,
1504 SelectionDAG &DAG) const {
1505 SDLoc DL(Op);
1506 // The legalizer does not know how to expand the comparison modes of i64x2
1507 // vectors because no comparison modes are supported. We could solve this by
1508 // expanding all i64x2 SETCC nodes, but that seems to expand f64x2 SETCC nodes
1509 // (which return i64x2 results) as well. So instead we manually unroll i64x2
1510 // comparisons here.
1511 assert(Subtarget->hasUnimplementedSIMD128());
1512 assert(Op->getOperand(0)->getSimpleValueType(0) == MVT::v2i64);
1513 SmallVector<SDValue, 2> LHS, RHS;
1514 DAG.ExtractVectorElements(Op->getOperand(0), LHS);
1515 DAG.ExtractVectorElements(Op->getOperand(1), RHS);
1516 const SDValue &CC = Op->getOperand(2);
1517 auto MakeLane = [&](unsigned I) {
1518 return DAG.getNode(ISD::SELECT_CC, DL, MVT::i64, LHS[I], RHS[I],
1519 DAG.getConstant(uint64_t(-1), DL, MVT::i64),
1520 DAG.getConstant(uint64_t(0), DL, MVT::i64), CC);
1521 };
1522 return DAG.getBuildVector(Op->getValueType(0), DL,
1523 {MakeLane(0), MakeLane(1)});
1524}
1525
Thomas Livelyfb84fd72018-11-02 00:06:56 +00001526SDValue
1527WebAssemblyTargetLowering::LowerAccessVectorElement(SDValue Op,
1528 SelectionDAG &DAG) const {
1529 // Allow constant lane indices, expand variable lane indices
1530 SDNode *IdxNode = Op.getOperand(Op.getNumOperands() - 1).getNode();
1531 if (isa<ConstantSDNode>(IdxNode) || IdxNode->isUndef())
1532 return Op;
1533 else
1534 // Perform default expansion
1535 return SDValue();
1536}
1537
Heejin Ahn18c56a02019-02-04 19:13:39 +00001538static SDValue unrollVectorShift(SDValue Op, SelectionDAG &DAG) {
Thomas Lively6bf2b402019-01-15 02:16:03 +00001539 EVT LaneT = Op.getSimpleValueType().getVectorElementType();
1540 // 32-bit and 64-bit unrolled shifts will have proper semantics
1541 if (LaneT.bitsGE(MVT::i32))
1542 return DAG.UnrollVectorOp(Op.getNode());
1543 // Otherwise mask the shift value to get proper semantics from 32-bit shift
1544 SDLoc DL(Op);
1545 SDValue ShiftVal = Op.getOperand(1);
1546 uint64_t MaskVal = LaneT.getSizeInBits() - 1;
1547 SDValue MaskedShiftVal = DAG.getNode(
1548 ISD::AND, // mask opcode
1549 DL, ShiftVal.getValueType(), // masked value type
1550 ShiftVal, // original shift value operand
1551 DAG.getConstant(MaskVal, DL, ShiftVal.getValueType()) // mask operand
1552 );
1553
1554 return DAG.UnrollVectorOp(
1555 DAG.getNode(Op.getOpcode(), // original shift opcode
1556 DL, Op.getValueType(), // original return type
1557 Op.getOperand(0), // original vector operand,
1558 MaskedShiftVal // new masked shift value operand
1559 )
1560 .getNode());
1561}
1562
Thomas Lively55735d52018-10-20 01:31:18 +00001563SDValue WebAssemblyTargetLowering::LowerShift(SDValue Op,
1564 SelectionDAG &DAG) const {
1565 SDLoc DL(Op);
Thomas Livelyb2382c82018-11-02 00:39:57 +00001566
1567 // Only manually lower vector shifts
1568 assert(Op.getSimpleValueType().isVector());
1569
1570 // Unroll non-splat vector shifts
1571 BuildVectorSDNode *ShiftVec;
1572 SDValue SplatVal;
1573 if (!(ShiftVec = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode())) ||
1574 !(SplatVal = ShiftVec->getSplatValue()))
Heejin Ahn18c56a02019-02-04 19:13:39 +00001575 return unrollVectorShift(Op, DAG);
Thomas Livelyb2382c82018-11-02 00:39:57 +00001576
1577 // All splats except i64x2 const splats are handled by patterns
Heejin Ahn18c56a02019-02-04 19:13:39 +00001578 auto *SplatConst = dyn_cast<ConstantSDNode>(SplatVal);
Thomas Livelyb2382c82018-11-02 00:39:57 +00001579 if (!SplatConst || Op.getSimpleValueType() != MVT::v2i64)
Thomas Lively55735d52018-10-20 01:31:18 +00001580 return Op;
Thomas Livelyb2382c82018-11-02 00:39:57 +00001581
1582 // i64x2 const splats are custom lowered to avoid unnecessary wraps
Thomas Lively55735d52018-10-20 01:31:18 +00001583 unsigned Opcode;
1584 switch (Op.getOpcode()) {
1585 case ISD::SHL:
1586 Opcode = WebAssemblyISD::VEC_SHL;
1587 break;
1588 case ISD::SRA:
1589 Opcode = WebAssemblyISD::VEC_SHR_S;
1590 break;
1591 case ISD::SRL:
1592 Opcode = WebAssemblyISD::VEC_SHR_U;
1593 break;
1594 default:
1595 llvm_unreachable("unexpected opcode");
Thomas Lively55735d52018-10-20 01:31:18 +00001596 }
Thomas Livelyb2382c82018-11-02 00:39:57 +00001597 APInt Shift = SplatConst->getAPIntValue().zextOrTrunc(32);
Thomas Lively55735d52018-10-20 01:31:18 +00001598 return DAG.getNode(Opcode, DL, Op.getValueType(), Op.getOperand(0),
Thomas Livelyb2382c82018-11-02 00:39:57 +00001599 DAG.getConstant(Shift, DL, MVT::i32));
Thomas Lively55735d52018-10-20 01:31:18 +00001600}
1601
Dan Gohman10e730a2015-06-29 23:51:55 +00001602//===----------------------------------------------------------------------===//
1603// WebAssembly Optimization Hooks
1604//===----------------------------------------------------------------------===//