1//=- WebAssemblyISelLowering.cpp - WebAssembly DAG Lowering Implementation -==//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file implements the WebAssemblyTargetLowering class.
11///
12//===----------------------------------------------------------------------===//
13
14#include "WebAssemblyISelLowering.h"
15#include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
16#include "Utils/WebAssemblyTypeUtilities.h"
17#include "WebAssemblyMachineFunctionInfo.h"
18#include "WebAssemblySubtarget.h"
19#include "WebAssemblyTargetMachine.h"
20#include "WebAssemblyUtilities.h"
21#include "llvm/CodeGen/CallingConvLower.h"
22#include "llvm/CodeGen/MachineFrameInfo.h"
23#include "llvm/CodeGen/MachineInstrBuilder.h"
24#include "llvm/CodeGen/MachineJumpTableInfo.h"
25#include "llvm/CodeGen/MachineModuleInfo.h"
26#include "llvm/CodeGen/MachineRegisterInfo.h"
27#include "llvm/CodeGen/SDPatternMatch.h"
28#include "llvm/CodeGen/SelectionDAG.h"
29#include "llvm/CodeGen/SelectionDAGNodes.h"
30#include "llvm/IR/DiagnosticInfo.h"
31#include "llvm/IR/DiagnosticPrinter.h"
32#include "llvm/IR/Function.h"
33#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/Intrinsics.h"
35#include "llvm/IR/IntrinsicsWebAssembly.h"
36#include "llvm/Support/ErrorHandling.h"
37#include "llvm/Support/KnownBits.h"
38#include "llvm/Support/MathExtras.h"
39#include "llvm/Target/TargetOptions.h"
40using namespace llvm;
41
42#define DEBUG_TYPE "wasm-lower"
43
44WebAssemblyTargetLowering::WebAssemblyTargetLowering(
45 const TargetMachine &TM, const WebAssemblySubtarget &STI)
46 : TargetLowering(TM, STI), Subtarget(&STI) {
47 auto MVTPtr = Subtarget->hasAddr64() ? MVT::i64 : MVT::i32;
48
49 // Set the load count for memcmp expand optimization
50 MaxLoadsPerMemcmp = 8;
51 MaxLoadsPerMemcmpOptSize = 4;
52
53 // Booleans always contain 0 or 1.
54 setBooleanContents(ZeroOrOneBooleanContent);
55 // Except in SIMD vectors
56 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
57 // We don't know the microarchitecture here, so just reduce register pressure.
58 setSchedulingPreference(Sched::RegPressure);
59 // Tell ISel that we have a stack pointer.
60 setStackPointerRegisterToSaveRestore(
61 Subtarget->hasAddr64() ? WebAssembly::SP64 : WebAssembly::SP32);
62 // Set up the register classes.
63 addRegisterClass(VT: MVT::i32, RC: &WebAssembly::I32RegClass);
64 addRegisterClass(VT: MVT::i64, RC: &WebAssembly::I64RegClass);
65 addRegisterClass(VT: MVT::f32, RC: &WebAssembly::F32RegClass);
66 addRegisterClass(VT: MVT::f64, RC: &WebAssembly::F64RegClass);
67 if (Subtarget->hasSIMD128()) {
68 addRegisterClass(VT: MVT::v16i8, RC: &WebAssembly::V128RegClass);
69 addRegisterClass(VT: MVT::v8i16, RC: &WebAssembly::V128RegClass);
70 addRegisterClass(VT: MVT::v4i32, RC: &WebAssembly::V128RegClass);
71 addRegisterClass(VT: MVT::v4f32, RC: &WebAssembly::V128RegClass);
72 addRegisterClass(VT: MVT::v2i64, RC: &WebAssembly::V128RegClass);
73 addRegisterClass(VT: MVT::v2f64, RC: &WebAssembly::V128RegClass);
74 }
75 if (Subtarget->hasFP16()) {
76 addRegisterClass(VT: MVT::v8f16, RC: &WebAssembly::V128RegClass);
77 }
78 if (Subtarget->hasReferenceTypes()) {
79 addRegisterClass(VT: MVT::externref, RC: &WebAssembly::EXTERNREFRegClass);
80 addRegisterClass(VT: MVT::funcref, RC: &WebAssembly::FUNCREFRegClass);
81 if (Subtarget->hasExceptionHandling()) {
82 addRegisterClass(VT: MVT::exnref, RC: &WebAssembly::EXNREFRegClass);
83 }
84 }
85 // Compute derived properties from the register classes.
86 computeRegisterProperties(TRI: Subtarget->getRegisterInfo());
87
88 // Transform loads and stores to pointers in address space 1 to loads and
89 // stores to WebAssembly global variables, outside linear memory.
90 for (auto T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64}) {
91 setOperationAction(Op: ISD::LOAD, VT: T, Action: Custom);
92 setOperationAction(Op: ISD::STORE, VT: T, Action: Custom);
93 }
94 if (Subtarget->hasSIMD128()) {
95 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
96 MVT::v2f64}) {
97 setOperationAction(Op: ISD::LOAD, VT: T, Action: Custom);
98 setOperationAction(Op: ISD::STORE, VT: T, Action: Custom);
99 }
100 }
101 if (Subtarget->hasFP16()) {
102 setOperationAction(Op: ISD::LOAD, VT: MVT::v8f16, Action: Custom);
103 setOperationAction(Op: ISD::STORE, VT: MVT::v8f16, Action: Custom);
104 }
105 if (Subtarget->hasReferenceTypes()) {
106 // We need custom load and store lowering for both externref, funcref and
107 // Other. The MVT::Other here represents tables of reference types.
108 for (auto T : {MVT::externref, MVT::funcref, MVT::Other}) {
109 setOperationAction(Op: ISD::LOAD, VT: T, Action: Custom);
110 setOperationAction(Op: ISD::STORE, VT: T, Action: Custom);
111 }
112 }
113
114 setOperationAction(Op: ISD::GlobalAddress, VT: MVTPtr, Action: Custom);
115 setOperationAction(Op: ISD::GlobalTLSAddress, VT: MVTPtr, Action: Custom);
116 setOperationAction(Op: ISD::ExternalSymbol, VT: MVTPtr, Action: Custom);
117 setOperationAction(Op: ISD::JumpTable, VT: MVTPtr, Action: Custom);
118 setOperationAction(Op: ISD::BlockAddress, VT: MVTPtr, Action: Custom);
119 setOperationAction(Op: ISD::BRIND, VT: MVT::Other, Action: Custom);
120 setOperationAction(Op: ISD::CLEAR_CACHE, VT: MVT::Other, Action: Custom);
121
122 // Take the default expansion for va_arg, va_copy, and va_end. There is no
123 // default action for va_start, so we do that custom.
124 setOperationAction(Op: ISD::VASTART, VT: MVT::Other, Action: Custom);
125 setOperationAction(Op: ISD::VAARG, VT: MVT::Other, Action: Expand);
126 setOperationAction(Op: ISD::VACOPY, VT: MVT::Other, Action: Expand);
127 setOperationAction(Op: ISD::VAEND, VT: MVT::Other, Action: Expand);
128
129 for (auto T : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64, MVT::v8f16}) {
130 if (!Subtarget->hasFP16() && T == MVT::v8f16) {
131 continue;
132 }
133 // Don't expand the floating-point types to constant pools.
134 setOperationAction(Op: ISD::ConstantFP, VT: T, Action: Legal);
135 // Expand floating-point comparisons.
136 for (auto CC : {ISD::SETO, ISD::SETUO, ISD::SETUEQ, ISD::SETONE,
137 ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE})
138 setCondCodeAction(CCs: CC, VT: T, Action: Expand);
139 // Expand floating-point library function operators.
140 for (auto Op : {ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FMA})
141 setOperationAction(Op, VT: T, Action: Expand);
142 // Expand vector FREM, but use a libcall rather than an expansion for scalar
143 if (MVT(T).isVector())
144 setOperationAction(Op: ISD::FREM, VT: T, Action: Expand);
145 else
146 setOperationAction(Op: ISD::FREM, VT: T, Action: LibCall);
147 // Note supported floating-point library function operators that otherwise
148 // default to expand.
149 for (auto Op : {ISD::FCEIL, ISD::FFLOOR, ISD::FTRUNC, ISD::FNEARBYINT,
150 ISD::FRINT, ISD::FROUNDEVEN})
151 setOperationAction(Op, VT: T, Action: Legal);
152 // Support minimum and maximum, which otherwise default to expand.
153 setOperationAction(Op: ISD::FMINIMUM, VT: T, Action: Legal);
154 setOperationAction(Op: ISD::FMAXIMUM, VT: T, Action: Legal);
155 // When experimental v8f16 support is enabled these instructions don't need
156 // to be expanded.
157 if (T != MVT::v8f16) {
158 setOperationAction(Op: ISD::FP16_TO_FP, VT: T, Action: Expand);
159 setOperationAction(Op: ISD::FP_TO_FP16, VT: T, Action: Expand);
160 }
161 setLoadExtAction(ExtType: ISD::EXTLOAD, ValVT: T, MemVT: MVT::f16, Action: Expand);
162 setTruncStoreAction(ValVT: T, MemVT: MVT::f16, Action: Expand);
163 }
164
165 // Expand unavailable integer operations.
166 for (auto Op :
167 {ISD::BSWAP, ISD::SMUL_LOHI, ISD::UMUL_LOHI, ISD::MULHS, ISD::MULHU,
168 ISD::SDIVREM, ISD::UDIVREM, ISD::SHL_PARTS, ISD::SRA_PARTS,
169 ISD::SRL_PARTS, ISD::ADDC, ISD::ADDE, ISD::SUBC, ISD::SUBE}) {
170 for (auto T : {MVT::i32, MVT::i64})
171 setOperationAction(Op, VT: T, Action: Expand);
172 if (Subtarget->hasSIMD128())
173 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64})
174 setOperationAction(Op, VT: T, Action: Expand);
175 }
176
177 if (Subtarget->hasWideArithmetic()) {
178 setOperationAction(Op: ISD::ADD, VT: MVT::i128, Action: Custom);
179 setOperationAction(Op: ISD::SUB, VT: MVT::i128, Action: Custom);
180 setOperationAction(Op: ISD::SMUL_LOHI, VT: MVT::i64, Action: Custom);
181 setOperationAction(Op: ISD::UMUL_LOHI, VT: MVT::i64, Action: Custom);
182 setOperationAction(Op: ISD::UADDO, VT: MVT::i64, Action: Custom);
183 }
184
185 if (Subtarget->hasNontrappingFPToInt())
186 for (auto Op : {ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT})
187 for (auto T : {MVT::i32, MVT::i64})
188 setOperationAction(Op, VT: T, Action: Custom);
189
190 if (Subtarget->hasRelaxedSIMD()) {
191 setOperationAction(
192 Ops: {ISD::FMINNUM, ISD::FMINIMUMNUM, ISD::FMAXNUM, ISD::FMAXIMUMNUM},
193 VTs: {MVT::v4f32, MVT::v2f64}, Action: Custom);
194 }
195 // SIMD-specific configuration
196 if (Subtarget->hasSIMD128()) {
197
198 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
199
200 // Combine wide-vector muls, with extend inputs, to extmul_half.
201 setTargetDAGCombine(ISD::MUL);
202 setTargetDAGCombine(ISD::SHL);
203
204 // Combine vector mask reductions into alltrue/anytrue
205 setTargetDAGCombine(ISD::SETCC);
206
207 // Convert vector to integer bitcasts to bitmask
208 setTargetDAGCombine(ISD::BITCAST);
209
210 // Hoist bitcasts out of shuffles
211 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
212
213 // Combine extends of extract_subvectors into widening ops
214 setTargetDAGCombine({ISD::SIGN_EXTEND, ISD::ZERO_EXTEND});
215
216 // Combine int_to_fp or fp_extend of extract_vectors and vice versa into
217 // conversions ops
218 setTargetDAGCombine({ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_EXTEND,
219 ISD::EXTRACT_SUBVECTOR});
220
221 // Combine fp_to_{s,u}int_sat or fp_round of concat_vectors or vice versa
222 // into conversion ops
223 setTargetDAGCombine({ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT,
224 ISD::FP_TO_SINT, ISD::FP_TO_UINT, ISD::FP_ROUND,
225 ISD::CONCAT_VECTORS});
226
227 setTargetDAGCombine(ISD::TRUNCATE);
228
229 // Support saturating add/sub for i8x16 and i16x8
230 for (auto Op : {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT})
231 for (auto T : {MVT::v16i8, MVT::v8i16})
232 setOperationAction(Op, VT: T, Action: Legal);
233
234 // Support integer abs
235 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64})
236 setOperationAction(Op: ISD::ABS, VT: T, Action: Legal);
237
238 // Custom lower BUILD_VECTORs to minimize number of replace_lanes
239 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
240 MVT::v2f64})
241 setOperationAction(Op: ISD::BUILD_VECTOR, VT: T, Action: Custom);
242
243 if (Subtarget->hasFP16())
244 setOperationAction(Op: ISD::BUILD_VECTOR, VT: MVT::f16, Action: Custom);
245
246 // We have custom shuffle lowering to expose the shuffle mask
247 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
248 MVT::v2f64})
249 setOperationAction(Op: ISD::VECTOR_SHUFFLE, VT: T, Action: Custom);
250
251 if (Subtarget->hasFP16())
252 setOperationAction(Op: ISD::VECTOR_SHUFFLE, VT: MVT::v8f16, Action: Custom);
253
254 // Support splatting
255 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
256 MVT::v2f64})
257 setOperationAction(Op: ISD::SPLAT_VECTOR, VT: T, Action: Legal);
258
259 setOperationAction(Ops: ISD::AVGCEILU, VTs: {MVT::v8i16, MVT::v16i8}, Action: Legal);
260
261 // Custom lowering since wasm shifts must have a scalar shift amount
262 for (auto Op : {ISD::SHL, ISD::SRA, ISD::SRL})
263 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64})
264 setOperationAction(Op, VT: T, Action: Custom);
265
266 // Custom lower lane accesses to expand out variable indices
267 for (auto Op : {ISD::EXTRACT_VECTOR_ELT, ISD::INSERT_VECTOR_ELT})
268 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
269 MVT::v2f64})
270 setOperationAction(Op, VT: T, Action: Custom);
271
272 // There is no i8x16.mul instruction
273 setOperationAction(Op: ISD::MUL, VT: MVT::v16i8, Action: Expand);
274
275 // Expand integer operations supported for scalars but not SIMD
276 for (auto Op :
277 {ISD::SDIV, ISD::UDIV, ISD::SREM, ISD::UREM, ISD::ROTL, ISD::ROTR})
278 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64})
279 setOperationAction(Op, VT: T, Action: Expand);
280
281 // But we do have integer min and max operations
282 for (auto Op : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
283 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
284 setOperationAction(Op, VT: T, Action: Legal);
285
286 // And we have popcnt for i8x16. It can be used to expand ctlz/cttz.
287 setOperationAction(Op: ISD::CTPOP, VT: MVT::v16i8, Action: Legal);
288 setOperationAction(Op: ISD::CTLZ, VT: MVT::v16i8, Action: Expand);
289 setOperationAction(Op: ISD::CTTZ, VT: MVT::v16i8, Action: Expand);
290
291 // Custom lower bit counting operations for other types to scalarize them.
292 for (auto Op : {ISD::CTLZ, ISD::CTTZ, ISD::CTPOP})
293 for (auto T : {MVT::v8i16, MVT::v4i32, MVT::v2i64})
294 setOperationAction(Op, VT: T, Action: Custom);
295
296 // Expand float operations supported for scalars but not SIMD
297 for (auto Op : {ISD::FCOPYSIGN, ISD::FLOG, ISD::FLOG2, ISD::FLOG10,
298 ISD::FEXP, ISD::FEXP2, ISD::FEXP10})
299 for (auto T : {MVT::v4f32, MVT::v2f64})
300 setOperationAction(Op, VT: T, Action: Expand);
301
302 // Unsigned comparison operations are unavailable for i64x2 vectors.
303 for (auto CC : {ISD::SETUGT, ISD::SETUGE, ISD::SETULT, ISD::SETULE})
304 setCondCodeAction(CCs: CC, VT: MVT::v2i64, Action: Custom);
305
306 // 64x2 conversions are not in the spec
307 for (auto Op :
308 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT})
309 for (auto T : {MVT::v2i64, MVT::v2f64})
310 setOperationAction(Op, VT: T, Action: Expand);
311
312 // But saturating fp_to_int converstions are
313 for (auto Op : {ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT}) {
314 setOperationAction(Op, VT: MVT::v4i32, Action: Custom);
315 if (Subtarget->hasFP16()) {
316 setOperationAction(Op, VT: MVT::v8i16, Action: Custom);
317 }
318 }
319
320 // Support vector extending
321 for (auto T : MVT::integer_fixedlen_vector_valuetypes()) {
322 setOperationAction(Op: ISD::ANY_EXTEND_VECTOR_INREG, VT: T, Action: Custom);
323 setOperationAction(Op: ISD::SIGN_EXTEND_VECTOR_INREG, VT: T, Action: Custom);
324 setOperationAction(Op: ISD::ZERO_EXTEND_VECTOR_INREG, VT: T, Action: Custom);
325 }
326
327 if (Subtarget->hasFP16()) {
328 setOperationAction(Op: ISD::FMA, VT: MVT::v8f16, Action: Legal);
329 }
330
331 if (Subtarget->hasRelaxedSIMD()) {
332 setOperationAction(Op: ISD::FMULADD, VT: MVT::v4f32, Action: Legal);
333 setOperationAction(Op: ISD::FMULADD, VT: MVT::v2f64, Action: Legal);
334 }
335
336 // Partial MLA reductions.
337 for (auto Op : {ISD::PARTIAL_REDUCE_SMLA, ISD::PARTIAL_REDUCE_UMLA}) {
338 setPartialReduceMLAAction(Opc: Op, AccVT: MVT::v4i32, InputVT: MVT::v16i8, Action: Legal);
339 setPartialReduceMLAAction(Opc: Op, AccVT: MVT::v4i32, InputVT: MVT::v8i16, Action: Legal);
340 }
341 }
342
343 // As a special case, these operators use the type to mean the type to
344 // sign-extend from.
345 setOperationAction(Op: ISD::SIGN_EXTEND_INREG, VT: MVT::i1, Action: Expand);
346 if (!Subtarget->hasSignExt()) {
347 // Sign extends are legal only when extending a vector extract
348 auto Action = Subtarget->hasSIMD128() ? Custom : Expand;
349 for (auto T : {MVT::i8, MVT::i16, MVT::i32})
350 setOperationAction(Op: ISD::SIGN_EXTEND_INREG, VT: T, Action);
351 }
352 for (auto T : MVT::integer_fixedlen_vector_valuetypes())
353 setOperationAction(Op: ISD::SIGN_EXTEND_INREG, VT: T, Action: Expand);
354
355 // Dynamic stack allocation: use the default expansion.
356 setOperationAction(Op: ISD::STACKSAVE, VT: MVT::Other, Action: Expand);
357 setOperationAction(Op: ISD::STACKRESTORE, VT: MVT::Other, Action: Expand);
358 setOperationAction(Op: ISD::DYNAMIC_STACKALLOC, VT: MVTPtr, Action: Expand);
359
360 setOperationAction(Op: ISD::FrameIndex, VT: MVT::i32, Action: Custom);
361 setOperationAction(Op: ISD::FrameIndex, VT: MVT::i64, Action: Custom);
362 setOperationAction(Op: ISD::CopyToReg, VT: MVT::Other, Action: Custom);
363
364 // Expand these forms; we pattern-match the forms that we can handle in isel.
365 for (auto T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64})
366 for (auto Op : {ISD::BR_CC, ISD::SELECT_CC})
367 setOperationAction(Op, VT: T, Action: Expand);
368
369 if (Subtarget->hasReferenceTypes())
370 for (auto Op : {ISD::BR_CC, ISD::SELECT_CC})
371 for (auto T : {MVT::externref, MVT::funcref})
372 setOperationAction(Op, VT: T, Action: Expand);
373
374 // There is no vector conditional select instruction
375 for (auto T :
376 {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64, MVT::v2f64})
377 setOperationAction(Op: ISD::SELECT_CC, VT: T, Action: Expand);
378
379 // We have custom switch handling.
380 setOperationAction(Op: ISD::BR_JT, VT: MVT::Other, Action: Custom);
381
382 // WebAssembly doesn't have:
383 // - Floating-point extending loads.
384 // - Floating-point truncating stores.
385 // - i1 extending loads.
386 // - truncating SIMD stores and most extending loads
387 setLoadExtAction(ExtType: ISD::EXTLOAD, ValVT: MVT::f64, MemVT: MVT::f32, Action: Expand);
388 setTruncStoreAction(ValVT: MVT::f64, MemVT: MVT::f32, Action: Expand);
389 for (auto T : MVT::integer_valuetypes())
390 for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD})
391 setLoadExtAction(ExtType: Ext, ValVT: T, MemVT: MVT::i1, Action: Promote);
392 if (Subtarget->hasSIMD128()) {
393 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64, MVT::v4f32,
394 MVT::v2f64}) {
395 for (auto MemT : MVT::fixedlen_vector_valuetypes()) {
396 if (MVT(T) != MemT) {
397 setTruncStoreAction(ValVT: T, MemVT: MemT, Action: Expand);
398 for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD})
399 setLoadExtAction(ExtType: Ext, ValVT: T, MemVT: MemT, Action: Expand);
400 }
401 }
402 }
403 // But some vector extending loads are legal
404 for (auto Ext : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) {
405 setLoadExtAction(ExtType: Ext, ValVT: MVT::v8i16, MemVT: MVT::v8i8, Action: Legal);
406 setLoadExtAction(ExtType: Ext, ValVT: MVT::v4i32, MemVT: MVT::v4i16, Action: Legal);
407 setLoadExtAction(ExtType: Ext, ValVT: MVT::v2i64, MemVT: MVT::v2i32, Action: Legal);
408 }
409 setLoadExtAction(ExtType: ISD::EXTLOAD, ValVT: MVT::v2f64, MemVT: MVT::v2f32, Action: Legal);
410 }
411
412 // Don't do anything clever with build_pairs
413 setOperationAction(Op: ISD::BUILD_PAIR, VT: MVT::i64, Action: Expand);
414
415 // Trap lowers to wasm unreachable
416 setOperationAction(Op: ISD::TRAP, VT: MVT::Other, Action: Legal);
417 setOperationAction(Op: ISD::DEBUGTRAP, VT: MVT::Other, Action: Legal);
418
419 // Exception handling intrinsics
420 setOperationAction(Op: ISD::INTRINSIC_WO_CHAIN, VT: MVT::Other, Action: Custom);
421 setOperationAction(Op: ISD::INTRINSIC_W_CHAIN, VT: MVT::Other, Action: Custom);
422 setOperationAction(Op: ISD::INTRINSIC_VOID, VT: MVT::Other, Action: Custom);
423
424 setMaxAtomicSizeInBitsSupported(64);
425
426 // Always convert switches to br_tables unless there is only one case, which
427 // is equivalent to a simple branch. This reduces code size for wasm, and we
428 // defer possible jump table optimizations to the VM.
429 setMinimumJumpTableEntries(2);
430}
431
432MVT WebAssemblyTargetLowering::getPointerTy(const DataLayout &DL,
433 uint32_t AS) const {
434 if (AS == WebAssembly::WasmAddressSpace::WASM_ADDRESS_SPACE_EXTERNREF)
435 return MVT::externref;
436 if (AS == WebAssembly::WasmAddressSpace::WASM_ADDRESS_SPACE_FUNCREF)
437 return MVT::funcref;
438 return TargetLowering::getPointerTy(DL, AS);
439}
440
441MVT WebAssemblyTargetLowering::getPointerMemTy(const DataLayout &DL,
442 uint32_t AS) const {
443 if (AS == WebAssembly::WasmAddressSpace::WASM_ADDRESS_SPACE_EXTERNREF)
444 return MVT::externref;
445 if (AS == WebAssembly::WasmAddressSpace::WASM_ADDRESS_SPACE_FUNCREF)
446 return MVT::funcref;
447 return TargetLowering::getPointerMemTy(DL, AS);
448}
449
450TargetLowering::AtomicExpansionKind
451WebAssemblyTargetLowering::shouldExpandAtomicRMWInIR(
452 const AtomicRMWInst *AI) const {
453 // We have wasm instructions for these
454 switch (AI->getOperation()) {
455 case AtomicRMWInst::Add:
456 case AtomicRMWInst::Sub:
457 case AtomicRMWInst::And:
458 case AtomicRMWInst::Or:
459 case AtomicRMWInst::Xor:
460 case AtomicRMWInst::Xchg:
461 return AtomicExpansionKind::None;
462 default:
463 break;
464 }
465 return AtomicExpansionKind::CmpXChg;
466}
467
468bool WebAssemblyTargetLowering::shouldScalarizeBinop(SDValue VecOp) const {
469 // Implementation copied from X86TargetLowering.
470 unsigned Opc = VecOp.getOpcode();
471
472 // Assume target opcodes can't be scalarized.
473 // TODO - do we have any exceptions?
474 if (Opc >= ISD::BUILTIN_OP_END || !isBinOp(Opcode: Opc))
475 return false;
476
477 // If the vector op is not supported, try to convert to scalar.
478 EVT VecVT = VecOp.getValueType();
479 if (!isOperationLegalOrCustomOrPromote(Op: Opc, VT: VecVT))
480 return true;
481
482 // If the vector op is supported, but the scalar op is not, the transform may
483 // not be worthwhile.
484 EVT ScalarVT = VecVT.getScalarType();
485 return isOperationLegalOrCustomOrPromote(Op: Opc, VT: ScalarVT);
486}
487
488FastISel *WebAssemblyTargetLowering::createFastISel(
489 FunctionLoweringInfo &FuncInfo, const TargetLibraryInfo *LibInfo,
490 const LibcallLoweringInfo *LibcallLowering) const {
491 return WebAssembly::createFastISel(funcInfo&: FuncInfo, libInfo: LibInfo, libcallLowering: LibcallLowering);
492}
493
494MVT WebAssemblyTargetLowering::getScalarShiftAmountTy(const DataLayout & /*DL*/,
495 EVT VT) const {
496 unsigned BitWidth = NextPowerOf2(A: VT.getSizeInBits() - 1);
497 if (BitWidth > 1 && BitWidth < 8)
498 BitWidth = 8;
499
500 if (BitWidth > 64) {
501 // The shift will be lowered to a libcall, and compiler-rt libcalls expect
502 // the count to be an i32.
503 BitWidth = 32;
504 assert(BitWidth >= Log2_32_Ceil(VT.getSizeInBits()) &&
505 "32-bit shift counts ought to be enough for anyone");
506 }
507
508 MVT Result = MVT::getIntegerVT(BitWidth);
509 assert(Result != MVT::INVALID_SIMPLE_VALUE_TYPE &&
510 "Unable to represent scalar shift amount type");
511 return Result;
512}
513
514// Lower an fp-to-int conversion operator from the LLVM opcode, which has an
515// undefined result on invalid/overflow, to the WebAssembly opcode, which
516// traps on invalid/overflow.
517static MachineBasicBlock *LowerFPToInt(MachineInstr &MI, DebugLoc DL,
518 MachineBasicBlock *BB,
519 const TargetInstrInfo &TII,
520 bool IsUnsigned, bool Int64,
521 bool Float64, unsigned LoweredOpcode) {
522 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
523
524 Register OutReg = MI.getOperand(i: 0).getReg();
525 Register InReg = MI.getOperand(i: 1).getReg();
526
527 unsigned Abs = Float64 ? WebAssembly::ABS_F64 : WebAssembly::ABS_F32;
528 unsigned FConst = Float64 ? WebAssembly::CONST_F64 : WebAssembly::CONST_F32;
529 unsigned LT = Float64 ? WebAssembly::LT_F64 : WebAssembly::LT_F32;
530 unsigned GE = Float64 ? WebAssembly::GE_F64 : WebAssembly::GE_F32;
531 unsigned IConst = Int64 ? WebAssembly::CONST_I64 : WebAssembly::CONST_I32;
532 unsigned Eqz = WebAssembly::EQZ_I32;
533 unsigned And = WebAssembly::AND_I32;
534 int64_t Limit = Int64 ? INT64_MIN : INT32_MIN;
535 int64_t Substitute = IsUnsigned ? 0 : Limit;
536 double CmpVal = IsUnsigned ? -(double)Limit * 2.0 : -(double)Limit;
537 auto &Context = BB->getParent()->getFunction().getContext();
538 Type *Ty = Float64 ? Type::getDoubleTy(C&: Context) : Type::getFloatTy(C&: Context);
539
540 const BasicBlock *LLVMBB = BB->getBasicBlock();
541 MachineFunction *F = BB->getParent();
542 MachineBasicBlock *TrueMBB = F->CreateMachineBasicBlock(BB: LLVMBB);
543 MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(BB: LLVMBB);
544 MachineBasicBlock *DoneMBB = F->CreateMachineBasicBlock(BB: LLVMBB);
545
546 MachineFunction::iterator It = ++BB->getIterator();
547 F->insert(MBBI: It, MBB: FalseMBB);
548 F->insert(MBBI: It, MBB: TrueMBB);
549 F->insert(MBBI: It, MBB: DoneMBB);
550
551 // Transfer the remainder of BB and its successor edges to DoneMBB.
552 DoneMBB->splice(Where: DoneMBB->begin(), Other: BB, From: std::next(x: MI.getIterator()), To: BB->end());
553 DoneMBB->transferSuccessorsAndUpdatePHIs(FromMBB: BB);
554
555 BB->addSuccessor(Succ: TrueMBB);
556 BB->addSuccessor(Succ: FalseMBB);
557 TrueMBB->addSuccessor(Succ: DoneMBB);
558 FalseMBB->addSuccessor(Succ: DoneMBB);
559
560 unsigned Tmp0, Tmp1, CmpReg, EqzReg, FalseReg, TrueReg;
561 Tmp0 = MRI.createVirtualRegister(RegClass: MRI.getRegClass(Reg: InReg));
562 Tmp1 = MRI.createVirtualRegister(RegClass: MRI.getRegClass(Reg: InReg));
563 CmpReg = MRI.createVirtualRegister(RegClass: &WebAssembly::I32RegClass);
564 EqzReg = MRI.createVirtualRegister(RegClass: &WebAssembly::I32RegClass);
565 FalseReg = MRI.createVirtualRegister(RegClass: MRI.getRegClass(Reg: OutReg));
566 TrueReg = MRI.createVirtualRegister(RegClass: MRI.getRegClass(Reg: OutReg));
567
568 MI.eraseFromParent();
569 // For signed numbers, we can do a single comparison to determine whether
570 // fabs(x) is within range.
571 if (IsUnsigned) {
572 Tmp0 = InReg;
573 } else {
574 BuildMI(BB, MIMD: DL, MCID: TII.get(Opcode: Abs), DestReg: Tmp0).addReg(RegNo: InReg);
575 }
576 BuildMI(BB, MIMD: DL, MCID: TII.get(Opcode: FConst), DestReg: Tmp1)
577 .addFPImm(Val: cast<ConstantFP>(Val: ConstantFP::get(Ty, V: CmpVal)));
578 BuildMI(BB, MIMD: DL, MCID: TII.get(Opcode: LT), DestReg: CmpReg).addReg(RegNo: Tmp0).addReg(RegNo: Tmp1);
579
580 // For unsigned numbers, we have to do a separate comparison with zero.
581 if (IsUnsigned) {
582 Tmp1 = MRI.createVirtualRegister(RegClass: MRI.getRegClass(Reg: InReg));
583 Register SecondCmpReg =
584 MRI.createVirtualRegister(RegClass: &WebAssembly::I32RegClass);
585 Register AndReg = MRI.createVirtualRegister(RegClass: &WebAssembly::I32RegClass);
586 BuildMI(BB, MIMD: DL, MCID: TII.get(Opcode: FConst), DestReg: Tmp1)
587 .addFPImm(Val: cast<ConstantFP>(Val: ConstantFP::get(Ty, V: 0.0)));
588 BuildMI(BB, MIMD: DL, MCID: TII.get(Opcode: GE), DestReg: SecondCmpReg).addReg(RegNo: Tmp0).addReg(RegNo: Tmp1);
589 BuildMI(BB, MIMD: DL, MCID: TII.get(Opcode: And), DestReg: AndReg).addReg(RegNo: CmpReg).addReg(RegNo: SecondCmpReg);
590 CmpReg = AndReg;
591 }
592
593 BuildMI(BB, MIMD: DL, MCID: TII.get(Opcode: Eqz), DestReg: EqzReg).addReg(RegNo: CmpReg);
594
595 // Create the CFG diamond to select between doing the conversion or using
596 // the substitute value.
597 BuildMI(BB, MIMD: DL, MCID: TII.get(Opcode: WebAssembly::BR_IF)).addMBB(MBB: TrueMBB).addReg(RegNo: EqzReg);
598 BuildMI(BB: FalseMBB, MIMD: DL, MCID: TII.get(Opcode: LoweredOpcode), DestReg: FalseReg).addReg(RegNo: InReg);
599 BuildMI(BB: FalseMBB, MIMD: DL, MCID: TII.get(Opcode: WebAssembly::BR)).addMBB(MBB: DoneMBB);
600 BuildMI(BB: TrueMBB, MIMD: DL, MCID: TII.get(Opcode: IConst), DestReg: TrueReg).addImm(Val: Substitute);
601 BuildMI(BB&: *DoneMBB, I: DoneMBB->begin(), MIMD: DL, MCID: TII.get(Opcode: TargetOpcode::PHI), DestReg: OutReg)
602 .addReg(RegNo: FalseReg)
603 .addMBB(MBB: FalseMBB)
604 .addReg(RegNo: TrueReg)
605 .addMBB(MBB: TrueMBB);
606
607 return DoneMBB;
608}
609
610// Lower a `MEMCPY` instruction into a CFG triangle around a `MEMORY_COPY`
611// instuction to handle the zero-length case.
612static MachineBasicBlock *LowerMemcpy(MachineInstr &MI, DebugLoc DL,
613 MachineBasicBlock *BB,
614 const TargetInstrInfo &TII, bool Int64) {
615 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
616
617 MachineOperand DstMem = MI.getOperand(i: 0);
618 MachineOperand SrcMem = MI.getOperand(i: 1);
619 MachineOperand Dst = MI.getOperand(i: 2);
620 MachineOperand Src = MI.getOperand(i: 3);
621 MachineOperand Len = MI.getOperand(i: 4);
622
623 // If the length is a constant, we don't actually need the check.
624 if (MachineInstr *Def = MRI.getVRegDef(Reg: Len.getReg())) {
625 if (Def->getOpcode() == WebAssembly::CONST_I32 ||
626 Def->getOpcode() == WebAssembly::CONST_I64) {
627 if (Def->getOperand(i: 1).getImm() == 0) {
628 // A zero-length memcpy is a no-op.
629 MI.eraseFromParent();
630 return BB;
631 }
632 // A non-zero-length memcpy doesn't need a zero check.
633 unsigned MemoryCopy =
634 Int64 ? WebAssembly::MEMORY_COPY_A64 : WebAssembly::MEMORY_COPY_A32;
635 BuildMI(BB&: *BB, I&: MI, MIMD: DL, MCID: TII.get(Opcode: MemoryCopy))
636 .add(MO: DstMem)
637 .add(MO: SrcMem)
638 .add(MO: Dst)
639 .add(MO: Src)
640 .add(MO: Len);
641 MI.eraseFromParent();
642 return BB;
643 }
644 }
645
646 // We're going to add an extra use to `Len` to test if it's zero; that
647 // use shouldn't be a kill, even if the original use is.
648 MachineOperand NoKillLen = Len;
649 NoKillLen.setIsKill(false);
650
651 // Decide on which `MachineInstr` opcode we're going to use.
652 unsigned Eqz = Int64 ? WebAssembly::EQZ_I64 : WebAssembly::EQZ_I32;
653 unsigned MemoryCopy =
654 Int64 ? WebAssembly::MEMORY_COPY_A64 : WebAssembly::MEMORY_COPY_A32;
655
656 // Create two new basic blocks; one for the new `memory.fill` that we can
657 // branch over, and one for the rest of the instructions after the original
658 // `memory.fill`.
659 const BasicBlock *LLVMBB = BB->getBasicBlock();
660 MachineFunction *F = BB->getParent();
661 MachineBasicBlock *TrueMBB = F->CreateMachineBasicBlock(BB: LLVMBB);
662 MachineBasicBlock *DoneMBB = F->CreateMachineBasicBlock(BB: LLVMBB);
663
664 MachineFunction::iterator It = ++BB->getIterator();
665 F->insert(MBBI: It, MBB: TrueMBB);
666 F->insert(MBBI: It, MBB: DoneMBB);
667
668 // Transfer the remainder of BB and its successor edges to DoneMBB.
669 DoneMBB->splice(Where: DoneMBB->begin(), Other: BB, From: std::next(x: MI.getIterator()), To: BB->end());
670 DoneMBB->transferSuccessorsAndUpdatePHIs(FromMBB: BB);
671
672 // Connect the CFG edges.
673 BB->addSuccessor(Succ: TrueMBB);
674 BB->addSuccessor(Succ: DoneMBB);
675 TrueMBB->addSuccessor(Succ: DoneMBB);
676
677 // Create a virtual register for the `Eqz` result.
678 unsigned EqzReg;
679 EqzReg = MRI.createVirtualRegister(RegClass: &WebAssembly::I32RegClass);
680
681 // Erase the original `memory.copy`.
682 MI.eraseFromParent();
683
684 // Test if `Len` is zero.
685 BuildMI(BB, MIMD: DL, MCID: TII.get(Opcode: Eqz), DestReg: EqzReg).add(MO: NoKillLen);
686
687 // Insert a new `memory.copy`.
688 BuildMI(BB: TrueMBB, MIMD: DL, MCID: TII.get(Opcode: MemoryCopy))
689 .add(MO: DstMem)
690 .add(MO: SrcMem)
691 .add(MO: Dst)
692 .add(MO: Src)
693 .add(MO: Len);
694
695 // Create the CFG triangle.
696 BuildMI(BB, MIMD: DL, MCID: TII.get(Opcode: WebAssembly::BR_IF)).addMBB(MBB: DoneMBB).addReg(RegNo: EqzReg);
697 BuildMI(BB: TrueMBB, MIMD: DL, MCID: TII.get(Opcode: WebAssembly::BR)).addMBB(MBB: DoneMBB);
698
699 return DoneMBB;
700}
701
702// Lower a `MEMSET` instruction into a CFG triangle around a `MEMORY_FILL`
703// instuction to handle the zero-length case.
704static MachineBasicBlock *LowerMemset(MachineInstr &MI, DebugLoc DL,
705 MachineBasicBlock *BB,
706 const TargetInstrInfo &TII, bool Int64) {
707 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
708
709 MachineOperand Mem = MI.getOperand(i: 0);
710 MachineOperand Dst = MI.getOperand(i: 1);
711 MachineOperand Val = MI.getOperand(i: 2);
712 MachineOperand Len = MI.getOperand(i: 3);
713
714 // If the length is a constant, we don't actually need the check.
715 if (MachineInstr *Def = MRI.getVRegDef(Reg: Len.getReg())) {
716 if (Def->getOpcode() == WebAssembly::CONST_I32 ||
717 Def->getOpcode() == WebAssembly::CONST_I64) {
718 if (Def->getOperand(i: 1).getImm() == 0) {
719 // A zero-length memset is a no-op.
720 MI.eraseFromParent();
721 return BB;
722 }
723 // A non-zero-length memset doesn't need a zero check.
724 unsigned MemoryFill =
725 Int64 ? WebAssembly::MEMORY_FILL_A64 : WebAssembly::MEMORY_FILL_A32;
726 BuildMI(BB&: *BB, I&: MI, MIMD: DL, MCID: TII.get(Opcode: MemoryFill))
727 .add(MO: Mem)
728 .add(MO: Dst)
729 .add(MO: Val)
730 .add(MO: Len);
731 MI.eraseFromParent();
732 return BB;
733 }
734 }
735
736 // We're going to add an extra use to `Len` to test if it's zero; that
737 // use shouldn't be a kill, even if the original use is.
738 MachineOperand NoKillLen = Len;
739 NoKillLen.setIsKill(false);
740
741 // Decide on which `MachineInstr` opcode we're going to use.
742 unsigned Eqz = Int64 ? WebAssembly::EQZ_I64 : WebAssembly::EQZ_I32;
743 unsigned MemoryFill =
744 Int64 ? WebAssembly::MEMORY_FILL_A64 : WebAssembly::MEMORY_FILL_A32;
745
746 // Create two new basic blocks; one for the new `memory.fill` that we can
747 // branch over, and one for the rest of the instructions after the original
748 // `memory.fill`.
749 const BasicBlock *LLVMBB = BB->getBasicBlock();
750 MachineFunction *F = BB->getParent();
751 MachineBasicBlock *TrueMBB = F->CreateMachineBasicBlock(BB: LLVMBB);
752 MachineBasicBlock *DoneMBB = F->CreateMachineBasicBlock(BB: LLVMBB);
753
754 MachineFunction::iterator It = ++BB->getIterator();
755 F->insert(MBBI: It, MBB: TrueMBB);
756 F->insert(MBBI: It, MBB: DoneMBB);
757
758 // Transfer the remainder of BB and its successor edges to DoneMBB.
759 DoneMBB->splice(Where: DoneMBB->begin(), Other: BB, From: std::next(x: MI.getIterator()), To: BB->end());
760 DoneMBB->transferSuccessorsAndUpdatePHIs(FromMBB: BB);
761
762 // Connect the CFG edges.
763 BB->addSuccessor(Succ: TrueMBB);
764 BB->addSuccessor(Succ: DoneMBB);
765 TrueMBB->addSuccessor(Succ: DoneMBB);
766
767 // Create a virtual register for the `Eqz` result.
768 unsigned EqzReg;
769 EqzReg = MRI.createVirtualRegister(RegClass: &WebAssembly::I32RegClass);
770
771 // Erase the original `memory.fill`.
772 MI.eraseFromParent();
773
774 // Test if `Len` is zero.
775 BuildMI(BB, MIMD: DL, MCID: TII.get(Opcode: Eqz), DestReg: EqzReg).add(MO: NoKillLen);
776
777 // Insert a new `memory.copy`.
778 BuildMI(BB: TrueMBB, MIMD: DL, MCID: TII.get(Opcode: MemoryFill)).add(MO: Mem).add(MO: Dst).add(MO: Val).add(MO: Len);
779
780 // Create the CFG triangle.
781 BuildMI(BB, MIMD: DL, MCID: TII.get(Opcode: WebAssembly::BR_IF)).addMBB(MBB: DoneMBB).addReg(RegNo: EqzReg);
782 BuildMI(BB: TrueMBB, MIMD: DL, MCID: TII.get(Opcode: WebAssembly::BR)).addMBB(MBB: DoneMBB);
783
784 return DoneMBB;
785}
786
787static MachineBasicBlock *
788LowerCallResults(MachineInstr &CallResults, DebugLoc DL, MachineBasicBlock *BB,
789 const WebAssemblySubtarget *Subtarget,
790 const TargetInstrInfo &TII) {
791 MachineInstr &CallParams = *CallResults.getPrevNode();
792 assert(CallParams.getOpcode() == WebAssembly::CALL_PARAMS);
793 assert(CallResults.getOpcode() == WebAssembly::CALL_RESULTS ||
794 CallResults.getOpcode() == WebAssembly::RET_CALL_RESULTS);
795
796 bool IsIndirect =
797 CallParams.getOperand(i: 0).isReg() || CallParams.getOperand(i: 0).isFI();
798 bool IsRetCall = CallResults.getOpcode() == WebAssembly::RET_CALL_RESULTS;
799
800 bool IsFuncrefCall = false;
801 if (IsIndirect && CallParams.getOperand(i: 0).isReg()) {
802 Register Reg = CallParams.getOperand(i: 0).getReg();
803 const MachineFunction *MF = BB->getParent();
804 const MachineRegisterInfo &MRI = MF->getRegInfo();
805 const TargetRegisterClass *TRC = MRI.getRegClass(Reg);
806 IsFuncrefCall = (TRC == &WebAssembly::FUNCREFRegClass);
807 assert(!IsFuncrefCall || Subtarget->hasReferenceTypes());
808 }
809
810 unsigned CallOp;
811 if (IsIndirect && IsRetCall) {
812 CallOp = WebAssembly::RET_CALL_INDIRECT;
813 } else if (IsIndirect) {
814 CallOp = WebAssembly::CALL_INDIRECT;
815 } else if (IsRetCall) {
816 CallOp = WebAssembly::RET_CALL;
817 } else {
818 CallOp = WebAssembly::CALL;
819 }
820
821 MachineFunction &MF = *BB->getParent();
822 const MCInstrDesc &MCID = TII.get(Opcode: CallOp);
823 MachineInstrBuilder MIB(MF, MF.CreateMachineInstr(MCID, DL));
824
825 // Move the function pointer to the end of the arguments for indirect calls
826 if (IsIndirect) {
827 auto FnPtr = CallParams.getOperand(i: 0);
828 CallParams.removeOperand(OpNo: 0);
829
830 // For funcrefs, call_indirect is done through __funcref_call_table and the
831 // funcref is always installed in slot 0 of the table, therefore instead of
832 // having the function pointer added at the end of the params list, a zero
833 // (the index in
834 // __funcref_call_table is added).
835 if (IsFuncrefCall) {
836 Register RegZero =
837 MF.getRegInfo().createVirtualRegister(RegClass: &WebAssembly::I32RegClass);
838 MachineInstrBuilder MIBC0 =
839 BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: WebAssembly::CONST_I32), DestReg: RegZero).addImm(Val: 0);
840
841 BB->insert(I: CallResults.getIterator(), M: MIBC0);
842 MachineInstrBuilder(MF, CallParams).addReg(RegNo: RegZero);
843 } else
844 CallParams.addOperand(Op: FnPtr);
845 }
846
847 for (auto Def : CallResults.defs())
848 MIB.add(MO: Def);
849
850 if (IsIndirect) {
851 // Placeholder for the type index.
852 // This gets replaced with the correct value in WebAssemblyMCInstLower.cpp
853 MIB.addImm(Val: 0);
854 // The table into which this call_indirect indexes.
855 MCSymbolWasm *Table = IsFuncrefCall
856 ? WebAssembly::getOrCreateFuncrefCallTableSymbol(
857 Ctx&: MF.getContext(), Subtarget)
858 : WebAssembly::getOrCreateFunctionTableSymbol(
859 Ctx&: MF.getContext(), Subtarget);
860 if (Subtarget->hasCallIndirectOverlong()) {
861 MIB.addSym(Sym: Table);
862 } else {
863 // For the MVP there is at most one table whose number is 0, but we can't
864 // write a table symbol or issue relocations. Instead we just ensure the
865 // table is live and write a zero.
866 Table->setNoStrip();
867 MIB.addImm(Val: 0);
868 }
869 }
870
871 for (auto Use : CallParams.uses())
872 MIB.add(MO: Use);
873
874 BB->insert(I: CallResults.getIterator(), M: MIB);
875 CallParams.eraseFromParent();
876 CallResults.eraseFromParent();
877
878 // If this is a funcref call, to avoid hidden GC roots, we need to clear the
879 // table slot with ref.null upon call_indirect return.
880 //
881 // This generates the following code, which comes right after a call_indirect
882 // of a funcref:
883 //
884 // i32.const 0
885 // ref.null func
886 // table.set __funcref_call_table
887 if (IsIndirect && IsFuncrefCall) {
888 MCSymbolWasm *Table = WebAssembly::getOrCreateFuncrefCallTableSymbol(
889 Ctx&: MF.getContext(), Subtarget);
890 Register RegZero =
891 MF.getRegInfo().createVirtualRegister(RegClass: &WebAssembly::I32RegClass);
892 MachineInstr *Const0 =
893 BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: WebAssembly::CONST_I32), DestReg: RegZero).addImm(Val: 0);
894 BB->insertAfter(I: MIB.getInstr()->getIterator(), MI: Const0);
895
896 Register RegFuncref =
897 MF.getRegInfo().createVirtualRegister(RegClass: &WebAssembly::FUNCREFRegClass);
898 MachineInstr *RefNull =
899 BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: WebAssembly::REF_NULL_FUNCREF), DestReg: RegFuncref);
900 BB->insertAfter(I: Const0->getIterator(), MI: RefNull);
901
902 MachineInstr *TableSet =
903 BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: WebAssembly::TABLE_SET_FUNCREF))
904 .addSym(Sym: Table)
905 .addReg(RegNo: RegZero)
906 .addReg(RegNo: RegFuncref);
907 BB->insertAfter(I: RefNull->getIterator(), MI: TableSet);
908 }
909
910 return BB;
911}
912
913MachineBasicBlock *WebAssemblyTargetLowering::EmitInstrWithCustomInserter(
914 MachineInstr &MI, MachineBasicBlock *BB) const {
915 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
916 DebugLoc DL = MI.getDebugLoc();
917
918 switch (MI.getOpcode()) {
919 default:
920 llvm_unreachable("Unexpected instr type to insert");
921 case WebAssembly::FP_TO_SINT_I32_F32:
922 return LowerFPToInt(MI, DL, BB, TII, IsUnsigned: false, Int64: false, Float64: false,
923 LoweredOpcode: WebAssembly::I32_TRUNC_S_F32);
924 case WebAssembly::FP_TO_UINT_I32_F32:
925 return LowerFPToInt(MI, DL, BB, TII, IsUnsigned: true, Int64: false, Float64: false,
926 LoweredOpcode: WebAssembly::I32_TRUNC_U_F32);
927 case WebAssembly::FP_TO_SINT_I64_F32:
928 return LowerFPToInt(MI, DL, BB, TII, IsUnsigned: false, Int64: true, Float64: false,
929 LoweredOpcode: WebAssembly::I64_TRUNC_S_F32);
930 case WebAssembly::FP_TO_UINT_I64_F32:
931 return LowerFPToInt(MI, DL, BB, TII, IsUnsigned: true, Int64: true, Float64: false,
932 LoweredOpcode: WebAssembly::I64_TRUNC_U_F32);
933 case WebAssembly::FP_TO_SINT_I32_F64:
934 return LowerFPToInt(MI, DL, BB, TII, IsUnsigned: false, Int64: false, Float64: true,
935 LoweredOpcode: WebAssembly::I32_TRUNC_S_F64);
936 case WebAssembly::FP_TO_UINT_I32_F64:
937 return LowerFPToInt(MI, DL, BB, TII, IsUnsigned: true, Int64: false, Float64: true,
938 LoweredOpcode: WebAssembly::I32_TRUNC_U_F64);
939 case WebAssembly::FP_TO_SINT_I64_F64:
940 return LowerFPToInt(MI, DL, BB, TII, IsUnsigned: false, Int64: true, Float64: true,
941 LoweredOpcode: WebAssembly::I64_TRUNC_S_F64);
942 case WebAssembly::FP_TO_UINT_I64_F64:
943 return LowerFPToInt(MI, DL, BB, TII, IsUnsigned: true, Int64: true, Float64: true,
944 LoweredOpcode: WebAssembly::I64_TRUNC_U_F64);
945 case WebAssembly::MEMCPY_A32:
946 return LowerMemcpy(MI, DL, BB, TII, Int64: false);
947 case WebAssembly::MEMCPY_A64:
948 return LowerMemcpy(MI, DL, BB, TII, Int64: true);
949 case WebAssembly::MEMSET_A32:
950 return LowerMemset(MI, DL, BB, TII, Int64: false);
951 case WebAssembly::MEMSET_A64:
952 return LowerMemset(MI, DL, BB, TII, Int64: true);
953 case WebAssembly::CALL_RESULTS:
954 case WebAssembly::RET_CALL_RESULTS:
955 return LowerCallResults(CallResults&: MI, DL, BB, Subtarget, TII);
956 }
957}
958
959std::pair<unsigned, const TargetRegisterClass *>
960WebAssemblyTargetLowering::getRegForInlineAsmConstraint(
961 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
962 // First, see if this is a constraint that directly corresponds to a
963 // WebAssembly register class.
964 if (Constraint.size() == 1) {
965 switch (Constraint[0]) {
966 case 'r':
967 assert(VT != MVT::iPTR && "Pointer MVT not expected here");
968 if (Subtarget->hasSIMD128() && VT.isVector()) {
969 if (VT.getSizeInBits() == 128)
970 return std::make_pair(x: 0U, y: &WebAssembly::V128RegClass);
971 }
972 if (VT.isInteger() && !VT.isVector()) {
973 if (VT.getSizeInBits() <= 32)
974 return std::make_pair(x: 0U, y: &WebAssembly::I32RegClass);
975 if (VT.getSizeInBits() <= 64)
976 return std::make_pair(x: 0U, y: &WebAssembly::I64RegClass);
977 }
978 if (VT.isFloatingPoint() && !VT.isVector()) {
979 switch (VT.getSizeInBits()) {
980 case 32:
981 return std::make_pair(x: 0U, y: &WebAssembly::F32RegClass);
982 case 64:
983 return std::make_pair(x: 0U, y: &WebAssembly::F64RegClass);
984 default:
985 break;
986 }
987 }
988 break;
989 default:
990 break;
991 }
992 }
993
994 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
995}
996
997bool WebAssemblyTargetLowering::isCheapToSpeculateCttz(Type *Ty) const {
998 // Assume ctz is a relatively cheap operation.
999 return true;
1000}
1001
1002bool WebAssemblyTargetLowering::isCheapToSpeculateCtlz(Type *Ty) const {
1003 // Assume clz is a relatively cheap operation.
1004 return true;
1005}
1006
1007bool WebAssemblyTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1008 const AddrMode &AM,
1009 Type *Ty, unsigned AS,
1010 Instruction *I) const {
1011 // WebAssembly offsets are added as unsigned without wrapping. The
1012 // isLegalAddressingMode gives us no way to determine if wrapping could be
1013 // happening, so we approximate this by accepting only non-negative offsets.
1014 if (AM.BaseOffs < 0)
1015 return false;
1016
1017 // WebAssembly has no scale register operands.
1018 if (AM.Scale != 0)
1019 return false;
1020
1021 // Everything else is legal.
1022 return true;
1023}
1024
1025bool WebAssemblyTargetLowering::allowsMisalignedMemoryAccesses(
1026 EVT /*VT*/, unsigned /*AddrSpace*/, Align /*Align*/,
1027 MachineMemOperand::Flags /*Flags*/, unsigned *Fast) const {
1028 // WebAssembly supports unaligned accesses, though it should be declared
1029 // with the p2align attribute on loads and stores which do so, and there
1030 // may be a performance impact. We tell LLVM they're "fast" because
1031 // for the kinds of things that LLVM uses this for (merging adjacent stores
1032 // of constants, etc.), WebAssembly implementations will either want the
1033 // unaligned access or they'll split anyway.
1034 if (Fast)
1035 *Fast = 1;
1036 return true;
1037}
1038
1039bool WebAssemblyTargetLowering::isIntDivCheap(EVT VT,
1040 AttributeList Attr) const {
1041 // The current thinking is that wasm engines will perform this optimization,
1042 // so we can save on code size.
1043 return true;
1044}
1045
1046bool WebAssemblyTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
1047 EVT ExtT = ExtVal.getValueType();
1048 SDValue N0 = ExtVal->getOperand(Num: 0);
1049 if (N0.getOpcode() == ISD::FREEZE)
1050 N0 = N0.getOperand(i: 0);
1051 auto *Load = dyn_cast<LoadSDNode>(Val&: N0);
1052 if (!Load)
1053 return false;
1054 EVT MemT = Load->getValueType(ResNo: 0);
1055 return (ExtT == MVT::v8i16 && MemT == MVT::v8i8) ||
1056 (ExtT == MVT::v4i32 && MemT == MVT::v4i16) ||
1057 (ExtT == MVT::v2i64 && MemT == MVT::v2i32);
1058}
1059
1060bool WebAssemblyTargetLowering::isOffsetFoldingLegal(
1061 const GlobalAddressSDNode *GA) const {
1062 // Wasm doesn't support function addresses with offsets
1063 const GlobalValue *GV = GA->getGlobal();
1064 return isa<Function>(Val: GV) ? false : TargetLowering::isOffsetFoldingLegal(GA);
1065}
1066
1067EVT WebAssemblyTargetLowering::getSetCCResultType(const DataLayout &DL,
1068 LLVMContext &C,
1069 EVT VT) const {
1070 if (VT.isVector())
1071 return VT.changeVectorElementTypeToInteger();
1072
1073 // So far, all branch instructions in Wasm take an I32 condition.
1074 // The default TargetLowering::getSetCCResultType returns the pointer size,
1075 // which would be useful to reduce instruction counts when testing
1076 // against 64-bit pointers/values if at some point Wasm supports that.
1077 return EVT::getIntegerVT(Context&: C, BitWidth: 32);
1078}
1079
1080void WebAssemblyTargetLowering::getTgtMemIntrinsic(
1081 SmallVectorImpl<IntrinsicInfo> &Infos, const CallBase &I,
1082 MachineFunction &MF, unsigned Intrinsic) const {
1083 IntrinsicInfo Info;
1084 switch (Intrinsic) {
1085 case Intrinsic::wasm_memory_atomic_notify:
1086 Info.opc = ISD::INTRINSIC_W_CHAIN;
1087 Info.memVT = MVT::i32;
1088 Info.ptrVal = I.getArgOperand(i: 0);
1089 Info.offset = 0;
1090 Info.align = Align(4);
1091 // atomic.notify instruction does not really load the memory specified with
1092 // this argument, but MachineMemOperand should either be load or store, so
1093 // we set this to a load.
1094 // FIXME Volatile isn't really correct, but currently all LLVM atomic
1095 // instructions are treated as volatiles in the backend, so we should be
1096 // consistent. The same applies for wasm_atomic_wait intrinsics too.
1097 Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
1098 Infos.push_back(Elt: Info);
1099 return;
1100 case Intrinsic::wasm_memory_atomic_wait32:
1101 Info.opc = ISD::INTRINSIC_W_CHAIN;
1102 Info.memVT = MVT::i32;
1103 Info.ptrVal = I.getArgOperand(i: 0);
1104 Info.offset = 0;
1105 Info.align = Align(4);
1106 Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
1107 Infos.push_back(Elt: Info);
1108 return;
1109 case Intrinsic::wasm_memory_atomic_wait64:
1110 Info.opc = ISD::INTRINSIC_W_CHAIN;
1111 Info.memVT = MVT::i64;
1112 Info.ptrVal = I.getArgOperand(i: 0);
1113 Info.offset = 0;
1114 Info.align = Align(8);
1115 Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
1116 Infos.push_back(Elt: Info);
1117 return;
1118 case Intrinsic::wasm_loadf16_f32:
1119 Info.opc = ISD::INTRINSIC_W_CHAIN;
1120 Info.memVT = MVT::f16;
1121 Info.ptrVal = I.getArgOperand(i: 0);
1122 Info.offset = 0;
1123 Info.align = Align(2);
1124 Info.flags = MachineMemOperand::MOLoad;
1125 Infos.push_back(Elt: Info);
1126 return;
1127 case Intrinsic::wasm_storef16_f32:
1128 Info.opc = ISD::INTRINSIC_VOID;
1129 Info.memVT = MVT::f16;
1130 Info.ptrVal = I.getArgOperand(i: 1);
1131 Info.offset = 0;
1132 Info.align = Align(2);
1133 Info.flags = MachineMemOperand::MOStore;
1134 Infos.push_back(Elt: Info);
1135 return;
1136 default:
1137 return;
1138 }
1139}
1140
1141void WebAssemblyTargetLowering::computeKnownBitsForTargetNode(
1142 const SDValue Op, KnownBits &Known, const APInt &DemandedElts,
1143 const SelectionDAG &DAG, unsigned Depth) const {
1144 switch (Op.getOpcode()) {
1145 default:
1146 break;
1147 case ISD::INTRINSIC_WO_CHAIN: {
1148 unsigned IntNo = Op.getConstantOperandVal(i: 0);
1149 switch (IntNo) {
1150 default:
1151 break;
1152 case Intrinsic::wasm_bitmask: {
1153 unsigned BitWidth = Known.getBitWidth();
1154 EVT VT = Op.getOperand(i: 1).getSimpleValueType();
1155 unsigned PossibleBits = VT.getVectorNumElements();
1156 APInt ZeroMask = APInt::getHighBitsSet(numBits: BitWidth, hiBitsSet: BitWidth - PossibleBits);
1157 Known.Zero |= ZeroMask;
1158 break;
1159 }
1160 }
1161 break;
1162 }
1163 case WebAssemblyISD::EXTEND_LOW_U:
1164 case WebAssemblyISD::EXTEND_HIGH_U: {
1165 // We know the high half, of each destination vector element, will be zero.
1166 SDValue SrcOp = Op.getOperand(i: 0);
1167 EVT VT = SrcOp.getSimpleValueType();
1168 unsigned BitWidth = Known.getBitWidth();
1169 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1170 assert(BitWidth >= 8 && "Unexpected width!");
1171 APInt Mask = APInt::getHighBitsSet(numBits: BitWidth, hiBitsSet: BitWidth - 8);
1172 Known.Zero |= Mask;
1173 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1174 assert(BitWidth >= 16 && "Unexpected width!");
1175 APInt Mask = APInt::getHighBitsSet(numBits: BitWidth, hiBitsSet: BitWidth - 16);
1176 Known.Zero |= Mask;
1177 } else if (VT == MVT::v2i32 || VT == MVT::v4i32) {
1178 assert(BitWidth >= 32 && "Unexpected width!");
1179 APInt Mask = APInt::getHighBitsSet(numBits: BitWidth, hiBitsSet: BitWidth - 32);
1180 Known.Zero |= Mask;
1181 }
1182 break;
1183 }
1184 // For 128-bit addition if the upper bits are all zero then it's known that
1185 // the upper bits of the result will have all bits guaranteed zero except the
1186 // first.
1187 case WebAssemblyISD::I64_ADD128:
1188 if (Op.getResNo() == 1) {
1189 SDValue LHS_HI = Op.getOperand(i: 1);
1190 SDValue RHS_HI = Op.getOperand(i: 3);
1191 if (isNullConstant(V: LHS_HI) && isNullConstant(V: RHS_HI))
1192 Known.Zero.setBitsFrom(1);
1193 }
1194 break;
1195 }
1196}
1197
1198TargetLoweringBase::LegalizeTypeAction
1199WebAssemblyTargetLowering::getPreferredVectorAction(MVT VT) const {
1200 if (VT.isFixedLengthVector()) {
1201 MVT EltVT = VT.getVectorElementType();
1202 // We have legal vector types with these lane types, so widening the
1203 // vector would let us use some of the lanes directly without having to
1204 // extend or truncate values.
1205 if (EltVT == MVT::i8 || EltVT == MVT::i16 || EltVT == MVT::i32 ||
1206 EltVT == MVT::i64 || EltVT == MVT::f32 || EltVT == MVT::f64)
1207 return TypeWidenVector;
1208 }
1209
1210 return TargetLoweringBase::getPreferredVectorAction(VT);
1211}
1212
1213bool WebAssemblyTargetLowering::isFMAFasterThanFMulAndFAdd(
1214 const MachineFunction &MF, EVT VT) const {
1215 if (!Subtarget->hasFP16() || !VT.isVector())
1216 return false;
1217
1218 EVT ScalarVT = VT.getScalarType();
1219 if (!ScalarVT.isSimple())
1220 return false;
1221
1222 return ScalarVT.getSimpleVT().SimpleTy == MVT::f16;
1223}
1224
1225bool WebAssemblyTargetLowering::shouldSimplifyDemandedVectorElts(
1226 SDValue Op, const TargetLoweringOpt &TLO) const {
1227 // ISel process runs DAGCombiner after legalization; this step is called
1228 // SelectionDAG optimization phase. This post-legalization combining process
1229 // runs DAGCombiner on each node, and if there was a change to be made,
1230 // re-runs legalization again on it and its user nodes to make sure
1231 // everythiing is in a legalized state.
1232 //
1233 // The legalization calls lowering routines, and we do our custom lowering for
1234 // build_vectors (LowerBUILD_VECTOR), which converts undef vector elements
1235 // into zeros. But there is a set of routines in DAGCombiner that turns unused
1236 // (= not demanded) nodes into undef, among which SimplifyDemandedVectorElts
1237 // turns unused vector elements into undefs. But this routine does not work
1238 // with our custom LowerBUILD_VECTOR, which turns undefs into zeros. This
1239 // combination can result in a infinite loop, in which undefs are converted to
1240 // zeros in legalization and back to undefs in combining.
1241 //
1242 // So after DAG is legalized, we prevent SimplifyDemandedVectorElts from
1243 // running for build_vectors.
1244 if (Op.getOpcode() == ISD::BUILD_VECTOR && TLO.LegalOps && TLO.LegalTys)
1245 return false;
1246 return true;
1247}
1248
1249//===----------------------------------------------------------------------===//
1250// WebAssembly Lowering private implementation.
1251//===----------------------------------------------------------------------===//
1252
1253//===----------------------------------------------------------------------===//
1254// Lowering Code
1255//===----------------------------------------------------------------------===//
1256
1257static void fail(const SDLoc &DL, SelectionDAG &DAG, const char *Msg) {
1258 MachineFunction &MF = DAG.getMachineFunction();
1259 DAG.getContext()->diagnose(
1260 DI: DiagnosticInfoUnsupported(MF.getFunction(), Msg, DL.getDebugLoc()));
1261}
1262
1263// Test whether the given calling convention is supported.
1264static bool callingConvSupported(CallingConv::ID CallConv) {
1265 // We currently support the language-independent target-independent
1266 // conventions. We don't yet have a way to annotate calls with properties like
1267 // "cold", and we don't have any call-clobbered registers, so these are mostly
1268 // all handled the same.
1269 return CallConv == CallingConv::C || CallConv == CallingConv::Fast ||
1270 CallConv == CallingConv::Cold ||
1271 CallConv == CallingConv::PreserveMost ||
1272 CallConv == CallingConv::PreserveAll ||
1273 CallConv == CallingConv::CXX_FAST_TLS ||
1274 CallConv == CallingConv::WASM_EmscriptenInvoke ||
1275 CallConv == CallingConv::Swift;
1276}
1277
1278SDValue
1279WebAssemblyTargetLowering::LowerCall(CallLoweringInfo &CLI,
1280 SmallVectorImpl<SDValue> &InVals) const {
1281 SelectionDAG &DAG = CLI.DAG;
1282 SDLoc DL = CLI.DL;
1283 SDValue Chain = CLI.Chain;
1284 SDValue Callee = CLI.Callee;
1285 MachineFunction &MF = DAG.getMachineFunction();
1286 auto Layout = MF.getDataLayout();
1287
1288 CallingConv::ID CallConv = CLI.CallConv;
1289 if (!callingConvSupported(CallConv))
1290 fail(DL, DAG,
1291 Msg: "WebAssembly doesn't support language-specific or target-specific "
1292 "calling conventions yet");
1293 if (CLI.IsPatchPoint)
1294 fail(DL, DAG, Msg: "WebAssembly doesn't support patch point yet");
1295
1296 if (CLI.IsTailCall) {
1297 auto NoTail = [&](const char *Msg) {
1298 if (CLI.CB && CLI.CB->isMustTailCall())
1299 fail(DL, DAG, Msg);
1300 CLI.IsTailCall = false;
1301 };
1302
1303 if (!Subtarget->hasTailCall())
1304 NoTail("WebAssembly 'tail-call' feature not enabled");
1305
1306 // Varargs calls cannot be tail calls because the buffer is on the stack
1307 if (CLI.IsVarArg)
1308 NoTail("WebAssembly does not support varargs tail calls");
1309
1310 // Do not tail call unless caller and callee return types match
1311 const Function &F = MF.getFunction();
1312 const TargetMachine &TM = getTargetMachine();
1313 Type *RetTy = F.getReturnType();
1314 SmallVector<MVT, 4> CallerRetTys;
1315 SmallVector<MVT, 4> CalleeRetTys;
1316 computeLegalValueVTs(F, TM, Ty: RetTy, ValueVTs&: CallerRetTys);
1317 computeLegalValueVTs(F, TM, Ty: CLI.RetTy, ValueVTs&: CalleeRetTys);
1318 bool TypesMatch = CallerRetTys.size() == CalleeRetTys.size() &&
1319 std::equal(first1: CallerRetTys.begin(), last1: CallerRetTys.end(),
1320 first2: CalleeRetTys.begin());
1321 if (!TypesMatch)
1322 NoTail("WebAssembly tail call requires caller and callee return types to "
1323 "match");
1324
1325 // If pointers to local stack values are passed, we cannot tail call
1326 if (CLI.CB) {
1327 for (auto &Arg : CLI.CB->args()) {
1328 Value *Val = Arg.get();
1329 // Trace the value back through pointer operations
1330 while (true) {
1331 Value *Src = Val->stripPointerCastsAndAliases();
1332 if (auto *GEP = dyn_cast<GetElementPtrInst>(Val: Src))
1333 Src = GEP->getPointerOperand();
1334 if (Val == Src)
1335 break;
1336 Val = Src;
1337 }
1338 if (isa<AllocaInst>(Val)) {
1339 NoTail(
1340 "WebAssembly does not support tail calling with stack arguments");
1341 break;
1342 }
1343 }
1344 }
1345 }
1346
1347 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1348 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1349 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1350
1351 // The generic code may have added an sret argument. If we're lowering an
1352 // invoke function, the ABI requires that the function pointer be the first
1353 // argument, so we may have to swap the arguments.
1354 if (CallConv == CallingConv::WASM_EmscriptenInvoke && Outs.size() >= 2 &&
1355 Outs[0].Flags.isSRet()) {
1356 std::swap(a&: Outs[0], b&: Outs[1]);
1357 std::swap(a&: OutVals[0], b&: OutVals[1]);
1358 }
1359
1360 bool HasSwiftSelfArg = false;
1361 bool HasSwiftErrorArg = false;
1362 unsigned NumFixedArgs = 0;
1363 for (unsigned I = 0; I < Outs.size(); ++I) {
1364 const ISD::OutputArg &Out = Outs[I];
1365 SDValue &OutVal = OutVals[I];
1366 HasSwiftSelfArg |= Out.Flags.isSwiftSelf();
1367 HasSwiftErrorArg |= Out.Flags.isSwiftError();
1368 if (Out.Flags.isNest())
1369 fail(DL, DAG, Msg: "WebAssembly hasn't implemented nest arguments");
1370 if (Out.Flags.isInAlloca())
1371 fail(DL, DAG, Msg: "WebAssembly hasn't implemented inalloca arguments");
1372 if (Out.Flags.isInConsecutiveRegs())
1373 fail(DL, DAG, Msg: "WebAssembly hasn't implemented cons regs arguments");
1374 if (Out.Flags.isInConsecutiveRegsLast())
1375 fail(DL, DAG, Msg: "WebAssembly hasn't implemented cons regs last arguments");
1376 if (Out.Flags.isByVal() && Out.Flags.getByValSize() != 0) {
1377 auto &MFI = MF.getFrameInfo();
1378 int FI = MFI.CreateStackObject(Size: Out.Flags.getByValSize(),
1379 Alignment: Out.Flags.getNonZeroByValAlign(),
1380 /*isSS=*/isSpillSlot: false);
1381 SDValue SizeNode =
1382 DAG.getConstant(Val: Out.Flags.getByValSize(), DL, VT: MVT::i32);
1383 SDValue FINode = DAG.getFrameIndex(FI, VT: getPointerTy(DL: Layout));
1384 Chain = DAG.getMemcpy(Chain, dl: DL, Dst: FINode, Src: OutVal, Size: SizeNode,
1385 Alignment: Out.Flags.getNonZeroByValAlign(),
1386 /*isVolatile*/ isVol: false, /*AlwaysInline=*/false,
1387 /*CI=*/nullptr, OverrideTailCall: std::nullopt, DstPtrInfo: MachinePointerInfo(),
1388 SrcPtrInfo: MachinePointerInfo());
1389 OutVal = FINode;
1390 }
1391 // Count the number of fixed args *after* legalization.
1392 NumFixedArgs += !Out.Flags.isVarArg();
1393 }
1394
1395 bool IsVarArg = CLI.IsVarArg;
1396 auto PtrVT = getPointerTy(DL: Layout);
1397
1398 // For swiftcc, emit additional swiftself and swifterror arguments
1399 // if there aren't. These additional arguments are also added for callee
1400 // signature They are necessary to match callee and caller signature for
1401 // indirect call.
1402 if (CallConv == CallingConv::Swift) {
1403 Type *PtrTy = PointerType::getUnqual(C&: *DAG.getContext());
1404 if (!HasSwiftSelfArg) {
1405 NumFixedArgs++;
1406 ISD::ArgFlagsTy Flags;
1407 Flags.setSwiftSelf();
1408 ISD::OutputArg Arg(Flags, PtrVT, EVT(PtrVT), PtrTy, 0, 0);
1409 CLI.Outs.push_back(Elt: Arg);
1410 SDValue ArgVal = DAG.getUNDEF(VT: PtrVT);
1411 CLI.OutVals.push_back(Elt: ArgVal);
1412 }
1413 if (!HasSwiftErrorArg) {
1414 NumFixedArgs++;
1415 ISD::ArgFlagsTy Flags;
1416 Flags.setSwiftError();
1417 ISD::OutputArg Arg(Flags, PtrVT, EVT(PtrVT), PtrTy, 0, 0);
1418 CLI.Outs.push_back(Elt: Arg);
1419 SDValue ArgVal = DAG.getUNDEF(VT: PtrVT);
1420 CLI.OutVals.push_back(Elt: ArgVal);
1421 }
1422 }
1423
1424 // Analyze operands of the call, assigning locations to each operand.
1425 SmallVector<CCValAssign, 16> ArgLocs;
1426 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
1427
1428 if (IsVarArg) {
1429 // Outgoing non-fixed arguments are placed in a buffer. First
1430 // compute their offsets and the total amount of buffer space needed.
1431 for (unsigned I = NumFixedArgs; I < Outs.size(); ++I) {
1432 const ISD::OutputArg &Out = Outs[I];
1433 SDValue &Arg = OutVals[I];
1434 EVT VT = Arg.getValueType();
1435 assert(VT != MVT::iPTR && "Legalized args should be concrete");
1436 Type *Ty = VT.getTypeForEVT(Context&: *DAG.getContext());
1437 Align Alignment =
1438 std::max(a: Out.Flags.getNonZeroOrigAlign(), b: Layout.getABITypeAlign(Ty));
1439 unsigned Offset =
1440 CCInfo.AllocateStack(Size: Layout.getTypeAllocSize(Ty), Alignment);
1441 CCInfo.addLoc(V: CCValAssign::getMem(ValNo: ArgLocs.size(), ValVT: VT.getSimpleVT(),
1442 Offset, LocVT: VT.getSimpleVT(),
1443 HTP: CCValAssign::Full));
1444 }
1445 }
1446
1447 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
1448
1449 SDValue FINode;
1450 if (IsVarArg && NumBytes) {
1451 // For non-fixed arguments, next emit stores to store the argument values
1452 // to the stack buffer at the offsets computed above.
1453 MaybeAlign StackAlign = Layout.getStackAlignment();
1454 assert(StackAlign && "data layout string is missing stack alignment");
1455 int FI = MF.getFrameInfo().CreateStackObject(Size: NumBytes, Alignment: *StackAlign,
1456 /*isSS=*/isSpillSlot: false);
1457 unsigned ValNo = 0;
1458 SmallVector<SDValue, 8> Chains;
1459 for (SDValue Arg : drop_begin(RangeOrContainer&: OutVals, N: NumFixedArgs)) {
1460 assert(ArgLocs[ValNo].getValNo() == ValNo &&
1461 "ArgLocs should remain in order and only hold varargs args");
1462 unsigned Offset = ArgLocs[ValNo++].getLocMemOffset();
1463 FINode = DAG.getFrameIndex(FI, VT: getPointerTy(DL: Layout));
1464 SDValue Add = DAG.getNode(Opcode: ISD::ADD, DL, VT: PtrVT, N1: FINode,
1465 N2: DAG.getConstant(Val: Offset, DL, VT: PtrVT));
1466 Chains.push_back(
1467 Elt: DAG.getStore(Chain, dl: DL, Val: Arg, Ptr: Add,
1468 PtrInfo: MachinePointerInfo::getFixedStack(MF, FI, Offset)));
1469 }
1470 if (!Chains.empty())
1471 Chain = DAG.getNode(Opcode: ISD::TokenFactor, DL, VT: MVT::Other, Ops: Chains);
1472 } else if (IsVarArg) {
1473 FINode = DAG.getIntPtrConstant(Val: 0, DL);
1474 }
1475
1476 if (Callee->getOpcode() == ISD::GlobalAddress) {
1477 // If the callee is a GlobalAddress node (quite common, every direct call
1478 // is) turn it into a TargetGlobalAddress node so that LowerGlobalAddress
1479 // doesn't at MO_GOT which is not needed for direct calls.
1480 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Val&: Callee);
1481 Callee = DAG.getTargetGlobalAddress(GV: GA->getGlobal(), DL,
1482 VT: getPointerTy(DL: DAG.getDataLayout()),
1483 offset: GA->getOffset());
1484 Callee = DAG.getNode(Opcode: WebAssemblyISD::Wrapper, DL,
1485 VT: getPointerTy(DL: DAG.getDataLayout()), Operand: Callee);
1486 }
1487
1488 // Compute the operands for the CALLn node.
1489 SmallVector<SDValue, 16> Ops;
1490 Ops.push_back(Elt: Chain);
1491 Ops.push_back(Elt: Callee);
1492
1493 // Add all fixed arguments. Note that for non-varargs calls, NumFixedArgs
1494 // isn't reliable.
1495 Ops.append(in_start: OutVals.begin(),
1496 in_end: IsVarArg ? OutVals.begin() + NumFixedArgs : OutVals.end());
1497 // Add a pointer to the vararg buffer.
1498 if (IsVarArg)
1499 Ops.push_back(Elt: FINode);
1500
1501 SmallVector<EVT, 8> InTys;
1502 for (const auto &In : Ins) {
1503 assert(!In.Flags.isByVal() && "byval is not valid for return values");
1504 assert(!In.Flags.isNest() && "nest is not valid for return values");
1505 if (In.Flags.isInAlloca())
1506 fail(DL, DAG, Msg: "WebAssembly hasn't implemented inalloca return values");
1507 if (In.Flags.isInConsecutiveRegs())
1508 fail(DL, DAG, Msg: "WebAssembly hasn't implemented cons regs return values");
1509 if (In.Flags.isInConsecutiveRegsLast())
1510 fail(DL, DAG,
1511 Msg: "WebAssembly hasn't implemented cons regs last return values");
1512 // Ignore In.getNonZeroOrigAlign() because all our arguments are passed in
1513 // registers.
1514 InTys.push_back(Elt: In.VT);
1515 }
1516
1517 // Lastly, if this is a call to a funcref we need to add an instruction
1518 // table.set to the chain and transform the call.
1519 if (CLI.CB && WebAssembly::isWebAssemblyFuncrefType(
1520 Ty: CLI.CB->getCalledOperand()->getType())) {
1521 // In the absence of function references proposal where a funcref call is
1522 // lowered to call_ref, using reference types we generate a table.set to set
1523 // the funcref to a special table used solely for this purpose, followed by
1524 // a call_indirect. Here we just generate the table set, and return the
1525 // SDValue of the table.set so that LowerCall can finalize the lowering by
1526 // generating the call_indirect.
1527 SDValue Chain = Ops[0];
1528
1529 MCSymbolWasm *Table = WebAssembly::getOrCreateFuncrefCallTableSymbol(
1530 Ctx&: MF.getContext(), Subtarget);
1531 SDValue Sym = DAG.getMCSymbol(Sym: Table, VT: PtrVT);
1532 SDValue TableSlot = DAG.getConstant(Val: 0, DL, VT: MVT::i32);
1533 SDValue TableSetOps[] = {Chain, Sym, TableSlot, Callee};
1534 SDValue TableSet = DAG.getMemIntrinsicNode(
1535 Opcode: WebAssemblyISD::TABLE_SET, dl: DL, VTList: DAG.getVTList(VT: MVT::Other), Ops: TableSetOps,
1536 MemVT: MVT::funcref,
1537 // Machine Mem Operand args
1538 PtrInfo: MachinePointerInfo(
1539 WebAssembly::WasmAddressSpace::WASM_ADDRESS_SPACE_FUNCREF),
1540 Alignment: CLI.CB->getCalledOperand()->getPointerAlignment(DL: DAG.getDataLayout()),
1541 Flags: MachineMemOperand::MOStore);
1542
1543 Ops[0] = TableSet; // The new chain is the TableSet itself
1544 }
1545
1546 if (CLI.IsTailCall) {
1547 // ret_calls do not return values to the current frame
1548 SDVTList NodeTys = DAG.getVTList(VT1: MVT::Other, VT2: MVT::Glue);
1549 return DAG.getNode(Opcode: WebAssemblyISD::RET_CALL, DL, VTList: NodeTys, Ops);
1550 }
1551
1552 InTys.push_back(Elt: MVT::Other);
1553 SDVTList InTyList = DAG.getVTList(VTs: InTys);
1554 SDValue Res = DAG.getNode(Opcode: WebAssemblyISD::CALL, DL, VTList: InTyList, Ops);
1555
1556 for (size_t I = 0; I < Ins.size(); ++I)
1557 InVals.push_back(Elt: Res.getValue(R: I));
1558
1559 // Return the chain
1560 return Res.getValue(R: Ins.size());
1561}
1562
1563bool WebAssemblyTargetLowering::CanLowerReturn(
1564 CallingConv::ID /*CallConv*/, MachineFunction & /*MF*/, bool /*IsVarArg*/,
1565 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext & /*Context*/,
1566 const Type *RetTy) const {
1567 // WebAssembly can only handle returning tuples with multivalue enabled
1568 return WebAssembly::canLowerReturn(ResultSize: Outs.size(), Subtarget);
1569}
1570
1571SDValue WebAssemblyTargetLowering::LowerReturn(
1572 SDValue Chain, CallingConv::ID CallConv, bool /*IsVarArg*/,
1573 const SmallVectorImpl<ISD::OutputArg> &Outs,
1574 const SmallVectorImpl<SDValue> &OutVals, const SDLoc &DL,
1575 SelectionDAG &DAG) const {
1576 assert(WebAssembly::canLowerReturn(Outs.size(), Subtarget) &&
1577 "MVP WebAssembly can only return up to one value");
1578 if (!callingConvSupported(CallConv))
1579 fail(DL, DAG, Msg: "WebAssembly doesn't support non-C calling conventions");
1580
1581 SmallVector<SDValue, 4> RetOps(1, Chain);
1582 RetOps.append(in_start: OutVals.begin(), in_end: OutVals.end());
1583 Chain = DAG.getNode(Opcode: WebAssemblyISD::RETURN, DL, VT: MVT::Other, Ops: RetOps);
1584
1585 // Record the number and types of the return values.
1586 for (const ISD::OutputArg &Out : Outs) {
1587 assert(!Out.Flags.isByVal() && "byval is not valid for return values");
1588 assert(!Out.Flags.isNest() && "nest is not valid for return values");
1589 assert(!Out.Flags.isVarArg() && "non-fixed return value is not valid");
1590 if (Out.Flags.isInAlloca())
1591 fail(DL, DAG, Msg: "WebAssembly hasn't implemented inalloca results");
1592 if (Out.Flags.isInConsecutiveRegs())
1593 fail(DL, DAG, Msg: "WebAssembly hasn't implemented cons regs results");
1594 if (Out.Flags.isInConsecutiveRegsLast())
1595 fail(DL, DAG, Msg: "WebAssembly hasn't implemented cons regs last results");
1596 }
1597
1598 return Chain;
1599}
1600
1601SDValue WebAssemblyTargetLowering::LowerFormalArguments(
1602 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
1603 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1604 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1605 if (!callingConvSupported(CallConv))
1606 fail(DL, DAG, Msg: "WebAssembly doesn't support non-C calling conventions");
1607
1608 MachineFunction &MF = DAG.getMachineFunction();
1609 auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>();
1610
1611 // Set up the incoming ARGUMENTS value, which serves to represent the liveness
1612 // of the incoming values before they're represented by virtual registers.
1613 MF.getRegInfo().addLiveIn(Reg: WebAssembly::ARGUMENTS);
1614
1615 bool HasSwiftErrorArg = false;
1616 bool HasSwiftSelfArg = false;
1617 for (const ISD::InputArg &In : Ins) {
1618 HasSwiftSelfArg |= In.Flags.isSwiftSelf();
1619 HasSwiftErrorArg |= In.Flags.isSwiftError();
1620 if (In.Flags.isInAlloca())
1621 fail(DL, DAG, Msg: "WebAssembly hasn't implemented inalloca arguments");
1622 if (In.Flags.isNest())
1623 fail(DL, DAG, Msg: "WebAssembly hasn't implemented nest arguments");
1624 if (In.Flags.isInConsecutiveRegs())
1625 fail(DL, DAG, Msg: "WebAssembly hasn't implemented cons regs arguments");
1626 if (In.Flags.isInConsecutiveRegsLast())
1627 fail(DL, DAG, Msg: "WebAssembly hasn't implemented cons regs last arguments");
1628 // Ignore In.getNonZeroOrigAlign() because all our arguments are passed in
1629 // registers.
1630 InVals.push_back(Elt: In.Used ? DAG.getNode(Opcode: WebAssemblyISD::ARGUMENT, DL, VT: In.VT,
1631 Operand: DAG.getTargetConstant(Val: InVals.size(),
1632 DL, VT: MVT::i32))
1633 : DAG.getUNDEF(VT: In.VT));
1634
1635 // Record the number and types of arguments.
1636 MFI->addParam(VT: In.VT);
1637 }
1638
1639 // For swiftcc, emit additional swiftself and swifterror arguments
1640 // if there aren't. These additional arguments are also added for callee
1641 // signature They are necessary to match callee and caller signature for
1642 // indirect call.
1643 auto PtrVT = getPointerTy(DL: MF.getDataLayout());
1644 if (CallConv == CallingConv::Swift) {
1645 if (!HasSwiftSelfArg) {
1646 MFI->addParam(VT: PtrVT);
1647 }
1648 if (!HasSwiftErrorArg) {
1649 MFI->addParam(VT: PtrVT);
1650 }
1651 }
1652 // Varargs are copied into a buffer allocated by the caller, and a pointer to
1653 // the buffer is passed as an argument.
1654 if (IsVarArg) {
1655 MVT PtrVT = getPointerTy(DL: MF.getDataLayout());
1656 Register VarargVreg =
1657 MF.getRegInfo().createVirtualRegister(RegClass: getRegClassFor(VT: PtrVT));
1658 MFI->setVarargBufferVreg(VarargVreg);
1659 Chain = DAG.getCopyToReg(
1660 Chain, dl: DL, Reg: VarargVreg,
1661 N: DAG.getNode(Opcode: WebAssemblyISD::ARGUMENT, DL, VT: PtrVT,
1662 Operand: DAG.getTargetConstant(Val: Ins.size(), DL, VT: MVT::i32)));
1663 MFI->addParam(VT: PtrVT);
1664 }
1665
1666 // Record the number and types of arguments and results.
1667 SmallVector<MVT, 4> Params;
1668 SmallVector<MVT, 4> Results;
1669 computeSignatureVTs(Ty: MF.getFunction().getFunctionType(), TargetFunc: &MF.getFunction(),
1670 ContextFunc: MF.getFunction(), TM: DAG.getTarget(), Params, Results);
1671 for (MVT VT : Results)
1672 MFI->addResult(VT);
1673 // TODO: Use signatures in WebAssemblyMachineFunctionInfo too and unify
1674 // the param logic here with ComputeSignatureVTs
1675 assert(MFI->getParams().size() == Params.size() &&
1676 std::equal(MFI->getParams().begin(), MFI->getParams().end(),
1677 Params.begin()));
1678
1679 return Chain;
1680}
1681
1682void WebAssemblyTargetLowering::ReplaceNodeResults(
1683 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
1684 switch (N->getOpcode()) {
1685 case ISD::SIGN_EXTEND_INREG:
1686 // Do not add any results, signifying that N should not be custom lowered
1687 // after all. This happens because simd128 turns on custom lowering for
1688 // SIGN_EXTEND_INREG, but for non-vector sign extends the result might be an
1689 // illegal type.
1690 break;
1691 case ISD::ANY_EXTEND_VECTOR_INREG:
1692 case ISD::SIGN_EXTEND_VECTOR_INREG:
1693 case ISD::ZERO_EXTEND_VECTOR_INREG:
1694 // Do not add any results, signifying that N should not be custom lowered.
1695 // EXTEND_VECTOR_INREG is implemented for some vectors, but not all.
1696 break;
1697 case ISD::ADD:
1698 case ISD::SUB:
1699 Results.push_back(Elt: Replace128Op(N, DAG));
1700 break;
1701 default:
1702 llvm_unreachable(
1703 "ReplaceNodeResults not implemented for this op for WebAssembly!");
1704 }
1705}
1706
1707//===----------------------------------------------------------------------===//
1708// Custom lowering hooks.
1709//===----------------------------------------------------------------------===//
1710
1711SDValue WebAssemblyTargetLowering::LowerOperation(SDValue Op,
1712 SelectionDAG &DAG) const {
1713 SDLoc DL(Op);
1714 switch (Op.getOpcode()) {
1715 default:
1716 llvm_unreachable("unimplemented operation lowering");
1717 return SDValue();
1718 case ISD::FrameIndex:
1719 return LowerFrameIndex(Op, DAG);
1720 case ISD::GlobalAddress:
1721 return LowerGlobalAddress(Op, DAG);
1722 case ISD::GlobalTLSAddress:
1723 return LowerGlobalTLSAddress(Op, DAG);
1724 case ISD::ExternalSymbol:
1725 return LowerExternalSymbol(Op, DAG);
1726 case ISD::JumpTable:
1727 return LowerJumpTable(Op, DAG);
1728 case ISD::BR_JT:
1729 return LowerBR_JT(Op, DAG);
1730 case ISD::VASTART:
1731 return LowerVASTART(Op, DAG);
1732 case ISD::BlockAddress:
1733 case ISD::BRIND:
1734 fail(DL, DAG, Msg: "WebAssembly hasn't implemented computed gotos");
1735 return SDValue();
1736 case ISD::RETURNADDR:
1737 return LowerRETURNADDR(Op, DAG);
1738 case ISD::FRAMEADDR:
1739 return LowerFRAMEADDR(Op, DAG);
1740 case ISD::CopyToReg:
1741 return LowerCopyToReg(Op, DAG);
1742 case ISD::EXTRACT_VECTOR_ELT:
1743 case ISD::INSERT_VECTOR_ELT:
1744 return LowerAccessVectorElement(Op, DAG);
1745 case ISD::INTRINSIC_VOID:
1746 case ISD::INTRINSIC_WO_CHAIN:
1747 case ISD::INTRINSIC_W_CHAIN:
1748 return LowerIntrinsic(Op, DAG);
1749 case ISD::SIGN_EXTEND_INREG:
1750 return LowerSIGN_EXTEND_INREG(Op, DAG);
1751 case ISD::ZERO_EXTEND_VECTOR_INREG:
1752 case ISD::SIGN_EXTEND_VECTOR_INREG:
1753 case ISD::ANY_EXTEND_VECTOR_INREG:
1754 return LowerEXTEND_VECTOR_INREG(Op, DAG);
1755 case ISD::BUILD_VECTOR:
1756 return LowerBUILD_VECTOR(Op, DAG);
1757 case ISD::VECTOR_SHUFFLE:
1758 return LowerVECTOR_SHUFFLE(Op, DAG);
1759 case ISD::SETCC:
1760 return LowerSETCC(Op, DAG);
1761 case ISD::SHL:
1762 case ISD::SRA:
1763 case ISD::SRL:
1764 return LowerShift(Op, DAG);
1765 case ISD::FP_TO_SINT_SAT:
1766 case ISD::FP_TO_UINT_SAT:
1767 return LowerFP_TO_INT_SAT(Op, DAG);
1768 case ISD::FMINNUM:
1769 case ISD::FMINIMUMNUM:
1770 return LowerFMIN(Op, DAG);
1771 case ISD::FMAXNUM:
1772 case ISD::FMAXIMUMNUM:
1773 return LowerFMAX(Op, DAG);
1774 case ISD::LOAD:
1775 return LowerLoad(Op, DAG);
1776 case ISD::STORE:
1777 return LowerStore(Op, DAG);
1778 case ISD::CTPOP:
1779 case ISD::CTLZ:
1780 case ISD::CTTZ:
1781 return DAG.UnrollVectorOp(N: Op.getNode());
1782 case ISD::CLEAR_CACHE:
1783 report_fatal_error(reason: "llvm.clear_cache is not supported on wasm");
1784 case ISD::SMUL_LOHI:
1785 case ISD::UMUL_LOHI:
1786 return LowerMUL_LOHI(Op, DAG);
1787 case ISD::UADDO:
1788 return LowerUADDO(Op, DAG);
1789 }
1790}
1791
1792static bool IsWebAssemblyGlobal(SDValue Op) {
1793 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Val&: Op))
1794 return WebAssembly::isWasmVarAddressSpace(AS: GA->getAddressSpace());
1795
1796 return false;
1797}
1798
1799static std::optional<unsigned> IsWebAssemblyLocal(SDValue Op,
1800 SelectionDAG &DAG) {
1801 const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Val&: Op);
1802 if (!FI)
1803 return std::nullopt;
1804
1805 auto &MF = DAG.getMachineFunction();
1806 return WebAssemblyFrameLowering::getLocalForStackObject(MF, FrameIndex: FI->getIndex());
1807}
1808
1809SDValue WebAssemblyTargetLowering::LowerStore(SDValue Op,
1810 SelectionDAG &DAG) const {
1811 SDLoc DL(Op);
1812 StoreSDNode *SN = cast<StoreSDNode>(Val: Op.getNode());
1813 const SDValue &Value = SN->getValue();
1814 const SDValue &Base = SN->getBasePtr();
1815 const SDValue &Offset = SN->getOffset();
1816
1817 if (IsWebAssemblyGlobal(Op: Base)) {
1818 if (!Offset->isUndef())
1819 report_fatal_error(reason: "unexpected offset when storing to webassembly global",
1820 gen_crash_diag: false);
1821
1822 SDVTList Tys = DAG.getVTList(VT: MVT::Other);
1823 SDValue Ops[] = {SN->getChain(), Value, Base};
1824 return DAG.getMemIntrinsicNode(Opcode: WebAssemblyISD::GLOBAL_SET, dl: DL, VTList: Tys, Ops,
1825 MemVT: SN->getMemoryVT(), MMO: SN->getMemOperand());
1826 }
1827
1828 if (std::optional<unsigned> Local = IsWebAssemblyLocal(Op: Base, DAG)) {
1829 if (!Offset->isUndef())
1830 report_fatal_error(reason: "unexpected offset when storing to webassembly local",
1831 gen_crash_diag: false);
1832
1833 SDValue Idx = DAG.getTargetConstant(Val: *Local, DL: Base, VT: MVT::i32);
1834 SDVTList Tys = DAG.getVTList(VT: MVT::Other); // The chain.
1835 SDValue Ops[] = {SN->getChain(), Idx, Value};
1836 return DAG.getNode(Opcode: WebAssemblyISD::LOCAL_SET, DL, VTList: Tys, Ops);
1837 }
1838
1839 if (WebAssembly::isWasmVarAddressSpace(AS: SN->getAddressSpace()))
1840 report_fatal_error(
1841 reason: "Encountered an unlowerable store to the wasm_var address space",
1842 gen_crash_diag: false);
1843
1844 return Op;
1845}
1846
1847SDValue WebAssemblyTargetLowering::LowerLoad(SDValue Op,
1848 SelectionDAG &DAG) const {
1849 SDLoc DL(Op);
1850 LoadSDNode *LN = cast<LoadSDNode>(Val: Op.getNode());
1851 const SDValue &Base = LN->getBasePtr();
1852 const SDValue &Offset = LN->getOffset();
1853
1854 if (IsWebAssemblyGlobal(Op: Base)) {
1855 if (!Offset->isUndef())
1856 report_fatal_error(
1857 reason: "unexpected offset when loading from webassembly global", gen_crash_diag: false);
1858
1859 SDVTList Tys = DAG.getVTList(VT1: LN->getValueType(ResNo: 0), VT2: MVT::Other);
1860 SDValue Ops[] = {LN->getChain(), Base};
1861 return DAG.getMemIntrinsicNode(Opcode: WebAssemblyISD::GLOBAL_GET, dl: DL, VTList: Tys, Ops,
1862 MemVT: LN->getMemoryVT(), MMO: LN->getMemOperand());
1863 }
1864
1865 if (std::optional<unsigned> Local = IsWebAssemblyLocal(Op: Base, DAG)) {
1866 if (!Offset->isUndef())
1867 report_fatal_error(
1868 reason: "unexpected offset when loading from webassembly local", gen_crash_diag: false);
1869
1870 SDValue Idx = DAG.getTargetConstant(Val: *Local, DL: Base, VT: MVT::i32);
1871 EVT LocalVT = LN->getValueType(ResNo: 0);
1872 return DAG.getNode(Opcode: WebAssemblyISD::LOCAL_GET, DL, ResultTys: {LocalVT, MVT::Other},
1873 Ops: {LN->getChain(), Idx});
1874 }
1875
1876 if (WebAssembly::isWasmVarAddressSpace(AS: LN->getAddressSpace()))
1877 report_fatal_error(
1878 reason: "Encountered an unlowerable load from the wasm_var address space",
1879 gen_crash_diag: false);
1880
1881 return Op;
1882}
1883
1884SDValue WebAssemblyTargetLowering::LowerMUL_LOHI(SDValue Op,
1885 SelectionDAG &DAG) const {
1886 assert(Subtarget->hasWideArithmetic());
1887 assert(Op.getValueType() == MVT::i64);
1888 SDLoc DL(Op);
1889 unsigned Opcode;
1890 switch (Op.getOpcode()) {
1891 case ISD::UMUL_LOHI:
1892 Opcode = WebAssemblyISD::I64_MUL_WIDE_U;
1893 break;
1894 case ISD::SMUL_LOHI:
1895 Opcode = WebAssemblyISD::I64_MUL_WIDE_S;
1896 break;
1897 default:
1898 llvm_unreachable("unexpected opcode");
1899 }
1900 SDValue LHS = Op.getOperand(i: 0);
1901 SDValue RHS = Op.getOperand(i: 1);
1902 SDValue Lo =
1903 DAG.getNode(Opcode, DL, VTList: DAG.getVTList(VT1: MVT::i64, VT2: MVT::i64), N1: LHS, N2: RHS);
1904 SDValue Hi(Lo.getNode(), 1);
1905 SDValue Ops[] = {Lo, Hi};
1906 return DAG.getMergeValues(Ops, dl: DL);
1907}
1908
1909// Lowers `UADDO` intrinsics to an `i64.add128` instruction when it's enabled.
1910//
1911// This enables generating a single wasm instruction for this operation where
1912// the upper half of both operands are constant zeros. The upper half of the
1913// result is then whether the overflow happened.
1914SDValue WebAssemblyTargetLowering::LowerUADDO(SDValue Op,
1915 SelectionDAG &DAG) const {
1916 assert(Subtarget->hasWideArithmetic());
1917 assert(Op.getValueType() == MVT::i64);
1918 assert(Op.getOpcode() == ISD::UADDO);
1919 SDLoc DL(Op);
1920 SDValue LHS = Op.getOperand(i: 0);
1921 SDValue RHS = Op.getOperand(i: 1);
1922 SDValue Zero = DAG.getConstant(Val: 0, DL, VT: MVT::i64);
1923 SDValue Result =
1924 DAG.getNode(Opcode: WebAssemblyISD::I64_ADD128, DL,
1925 VTList: DAG.getVTList(VT1: MVT::i64, VT2: MVT::i64), N1: LHS, N2: Zero, N3: RHS, N4: Zero);
1926 SDValue CarryI64(Result.getNode(), 1);
1927 SDValue CarryI32 = DAG.getNode(Opcode: ISD::TRUNCATE, DL, VT: MVT::i32, Operand: CarryI64);
1928 SDValue Ops[] = {Result, CarryI32};
1929 return DAG.getMergeValues(Ops, dl: DL);
1930}
1931
1932SDValue WebAssemblyTargetLowering::Replace128Op(SDNode *N,
1933 SelectionDAG &DAG) const {
1934 assert(Subtarget->hasWideArithmetic());
1935 assert(N->getValueType(0) == MVT::i128);
1936 SDLoc DL(N);
1937 unsigned Opcode;
1938 switch (N->getOpcode()) {
1939 case ISD::ADD:
1940 Opcode = WebAssemblyISD::I64_ADD128;
1941 break;
1942 case ISD::SUB:
1943 Opcode = WebAssemblyISD::I64_SUB128;
1944 break;
1945 default:
1946 llvm_unreachable("unexpected opcode");
1947 }
1948 SDValue LHS = N->getOperand(Num: 0);
1949 SDValue RHS = N->getOperand(Num: 1);
1950
1951 SDValue C0 = DAG.getConstant(Val: 0, DL, VT: MVT::i64);
1952 SDValue C1 = DAG.getConstant(Val: 1, DL, VT: MVT::i64);
1953 SDValue LHS_0 = DAG.getNode(Opcode: ISD::EXTRACT_ELEMENT, DL, VT: MVT::i64, N1: LHS, N2: C0);
1954 SDValue LHS_1 = DAG.getNode(Opcode: ISD::EXTRACT_ELEMENT, DL, VT: MVT::i64, N1: LHS, N2: C1);
1955 SDValue RHS_0 = DAG.getNode(Opcode: ISD::EXTRACT_ELEMENT, DL, VT: MVT::i64, N1: RHS, N2: C0);
1956 SDValue RHS_1 = DAG.getNode(Opcode: ISD::EXTRACT_ELEMENT, DL, VT: MVT::i64, N1: RHS, N2: C1);
1957 SDValue Result_LO = DAG.getNode(Opcode, DL, VTList: DAG.getVTList(VT1: MVT::i64, VT2: MVT::i64),
1958 N1: LHS_0, N2: LHS_1, N3: RHS_0, N4: RHS_1);
1959 SDValue Result_HI(Result_LO.getNode(), 1);
1960 return DAG.getNode(Opcode: ISD::BUILD_PAIR, DL, VTList: N->getVTList(), N1: Result_LO, N2: Result_HI);
1961}
1962
1963SDValue WebAssemblyTargetLowering::LowerCopyToReg(SDValue Op,
1964 SelectionDAG &DAG) const {
1965 SDValue Src = Op.getOperand(i: 2);
1966 if (isa<FrameIndexSDNode>(Val: Src.getNode())) {
1967 // CopyToReg nodes don't support FrameIndex operands. Other targets select
1968 // the FI to some LEA-like instruction, but since we don't have that, we
1969 // need to insert some kind of instruction that can take an FI operand and
1970 // produces a value usable by CopyToReg (i.e. in a vreg). So insert a dummy
1971 // local.copy between Op and its FI operand.
1972 SDValue Chain = Op.getOperand(i: 0);
1973 SDLoc DL(Op);
1974 Register Reg = cast<RegisterSDNode>(Val: Op.getOperand(i: 1))->getReg();
1975 EVT VT = Src.getValueType();
1976 SDValue Copy(DAG.getMachineNode(Opcode: VT == MVT::i32 ? WebAssembly::COPY_I32
1977 : WebAssembly::COPY_I64,
1978 dl: DL, VT, Op1: Src),
1979 0);
1980 return Op.getNode()->getNumValues() == 1
1981 ? DAG.getCopyToReg(Chain, dl: DL, Reg, N: Copy)
1982 : DAG.getCopyToReg(Chain, dl: DL, Reg, N: Copy,
1983 Glue: Op.getNumOperands() == 4 ? Op.getOperand(i: 3)
1984 : SDValue());
1985 }
1986 return SDValue();
1987}
1988
1989SDValue WebAssemblyTargetLowering::LowerFrameIndex(SDValue Op,
1990 SelectionDAG &DAG) const {
1991 int FI = cast<FrameIndexSDNode>(Val&: Op)->getIndex();
1992 return DAG.getTargetFrameIndex(FI, VT: Op.getValueType());
1993}
1994
1995SDValue WebAssemblyTargetLowering::LowerRETURNADDR(SDValue Op,
1996 SelectionDAG &DAG) const {
1997 SDLoc DL(Op);
1998
1999 if (!Subtarget->getTargetTriple().isOSEmscripten()) {
2000 fail(DL, DAG,
2001 Msg: "Non-Emscripten WebAssembly hasn't implemented "
2002 "__builtin_return_address");
2003 return SDValue();
2004 }
2005
2006 unsigned Depth = Op.getConstantOperandVal(i: 0);
2007 MakeLibCallOptions CallOptions;
2008 return makeLibCall(DAG, LC: RTLIB::RETURN_ADDRESS, RetVT: Op.getValueType(),
2009 Ops: {DAG.getConstant(Val: Depth, DL, VT: MVT::i32)}, CallOptions, dl: DL)
2010 .first;
2011}
2012
2013SDValue WebAssemblyTargetLowering::LowerFRAMEADDR(SDValue Op,
2014 SelectionDAG &DAG) const {
2015 // Non-zero depths are not supported by WebAssembly currently. Use the
2016 // legalizer's default expansion, which is to return 0 (what this function is
2017 // documented to do).
2018 if (Op.getConstantOperandVal(i: 0) > 0)
2019 return SDValue();
2020
2021 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
2022 EVT VT = Op.getValueType();
2023 Register FP =
2024 Subtarget->getRegisterInfo()->getFrameRegister(MF: DAG.getMachineFunction());
2025 return DAG.getCopyFromReg(Chain: DAG.getEntryNode(), dl: SDLoc(Op), Reg: FP, VT);
2026}
2027
2028SDValue
2029WebAssemblyTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2030 SelectionDAG &DAG) const {
2031 SDLoc DL(Op);
2032 const auto *GA = cast<GlobalAddressSDNode>(Val&: Op);
2033
2034 MachineFunction &MF = DAG.getMachineFunction();
2035 if (!MF.getSubtarget<WebAssemblySubtarget>().hasBulkMemory())
2036 report_fatal_error(reason: "cannot use thread-local storage without bulk memory",
2037 gen_crash_diag: false);
2038
2039 const GlobalValue *GV = GA->getGlobal();
2040
2041 // Currently only Emscripten supports dynamic linking with threads. Therefore,
2042 // on other targets, if we have thread-local storage, only the local-exec
2043 // model is possible.
2044 auto model = Subtarget->getTargetTriple().isOSEmscripten()
2045 ? GV->getThreadLocalMode()
2046 : GlobalValue::LocalExecTLSModel;
2047
2048 // Unsupported TLS modes
2049 assert(model != GlobalValue::NotThreadLocal);
2050 assert(model != GlobalValue::InitialExecTLSModel);
2051
2052 if (model == GlobalValue::LocalExecTLSModel ||
2053 model == GlobalValue::LocalDynamicTLSModel ||
2054 (model == GlobalValue::GeneralDynamicTLSModel &&
2055 getTargetMachine().shouldAssumeDSOLocal(GV))) {
2056 // For DSO-local TLS variables we use offset from __tls_base
2057
2058 MVT PtrVT = getPointerTy(DL: DAG.getDataLayout());
2059 auto GlobalGet = PtrVT == MVT::i64 ? WebAssembly::GLOBAL_GET_I64
2060 : WebAssembly::GLOBAL_GET_I32;
2061 const char *BaseName = MF.createExternalSymbolName(Name: "__tls_base");
2062
2063 SDValue BaseAddr(
2064 DAG.getMachineNode(Opcode: GlobalGet, dl: DL, VT: PtrVT,
2065 Op1: DAG.getTargetExternalSymbol(Sym: BaseName, VT: PtrVT)),
2066 0);
2067
2068 SDValue TLSOffset = DAG.getTargetGlobalAddress(
2069 GV, DL, VT: PtrVT, offset: GA->getOffset(), TargetFlags: WebAssemblyII::MO_TLS_BASE_REL);
2070 SDValue SymOffset =
2071 DAG.getNode(Opcode: WebAssemblyISD::WrapperREL, DL, VT: PtrVT, Operand: TLSOffset);
2072
2073 return DAG.getNode(Opcode: ISD::ADD, DL, VT: PtrVT, N1: BaseAddr, N2: SymOffset);
2074 }
2075
2076 assert(model == GlobalValue::GeneralDynamicTLSModel);
2077
2078 EVT VT = Op.getValueType();
2079 return DAG.getNode(Opcode: WebAssemblyISD::Wrapper, DL, VT,
2080 Operand: DAG.getTargetGlobalAddress(GV: GA->getGlobal(), DL, VT,
2081 offset: GA->getOffset(),
2082 TargetFlags: WebAssemblyII::MO_GOT_TLS));
2083}
2084
2085SDValue WebAssemblyTargetLowering::LowerGlobalAddress(SDValue Op,
2086 SelectionDAG &DAG) const {
2087 SDLoc DL(Op);
2088 const auto *GA = cast<GlobalAddressSDNode>(Val&: Op);
2089 EVT VT = Op.getValueType();
2090 assert(GA->getTargetFlags() == 0 &&
2091 "Unexpected target flags on generic GlobalAddressSDNode");
2092 if (!WebAssembly::isValidAddressSpace(AS: GA->getAddressSpace()))
2093 fail(DL, DAG, Msg: "Invalid address space for WebAssembly target");
2094
2095 unsigned OperandFlags = 0;
2096 const GlobalValue *GV = GA->getGlobal();
2097 // Since WebAssembly tables cannot yet be shared accross modules, we don't
2098 // need special treatment for tables in PIC mode.
2099 if (isPositionIndependent() &&
2100 !WebAssembly::isWebAssemblyTableType(Ty: GV->getValueType())) {
2101 if (getTargetMachine().shouldAssumeDSOLocal(GV)) {
2102 MachineFunction &MF = DAG.getMachineFunction();
2103 MVT PtrVT = getPointerTy(DL: MF.getDataLayout());
2104 const char *BaseName;
2105 if (GV->getValueType()->isFunctionTy()) {
2106 BaseName = MF.createExternalSymbolName(Name: "__table_base");
2107 OperandFlags = WebAssemblyII::MO_TABLE_BASE_REL;
2108 } else {
2109 BaseName = MF.createExternalSymbolName(Name: "__memory_base");
2110 OperandFlags = WebAssemblyII::MO_MEMORY_BASE_REL;
2111 }
2112 SDValue BaseAddr =
2113 DAG.getNode(Opcode: WebAssemblyISD::Wrapper, DL, VT: PtrVT,
2114 Operand: DAG.getTargetExternalSymbol(Sym: BaseName, VT: PtrVT));
2115
2116 SDValue SymAddr = DAG.getNode(
2117 Opcode: WebAssemblyISD::WrapperREL, DL, VT,
2118 Operand: DAG.getTargetGlobalAddress(GV: GA->getGlobal(), DL, VT, offset: GA->getOffset(),
2119 TargetFlags: OperandFlags));
2120
2121 return DAG.getNode(Opcode: ISD::ADD, DL, VT, N1: BaseAddr, N2: SymAddr);
2122 }
2123 OperandFlags = WebAssemblyII::MO_GOT;
2124 }
2125
2126 return DAG.getNode(Opcode: WebAssemblyISD::Wrapper, DL, VT,
2127 Operand: DAG.getTargetGlobalAddress(GV: GA->getGlobal(), DL, VT,
2128 offset: GA->getOffset(), TargetFlags: OperandFlags));
2129}
2130
2131SDValue
2132WebAssemblyTargetLowering::LowerExternalSymbol(SDValue Op,
2133 SelectionDAG &DAG) const {
2134 SDLoc DL(Op);
2135 const auto *ES = cast<ExternalSymbolSDNode>(Val&: Op);
2136 EVT VT = Op.getValueType();
2137 assert(ES->getTargetFlags() == 0 &&
2138 "Unexpected target flags on generic ExternalSymbolSDNode");
2139 return DAG.getNode(Opcode: WebAssemblyISD::Wrapper, DL, VT,
2140 Operand: DAG.getTargetExternalSymbol(Sym: ES->getSymbol(), VT));
2141}
2142
2143SDValue WebAssemblyTargetLowering::LowerJumpTable(SDValue Op,
2144 SelectionDAG &DAG) const {
2145 // There's no need for a Wrapper node because we always incorporate a jump
2146 // table operand into a BR_TABLE instruction, rather than ever
2147 // materializing it in a register.
2148 const JumpTableSDNode *JT = cast<JumpTableSDNode>(Val&: Op);
2149 return DAG.getTargetJumpTable(JTI: JT->getIndex(), VT: Op.getValueType(),
2150 TargetFlags: JT->getTargetFlags());
2151}
2152
2153SDValue WebAssemblyTargetLowering::LowerBR_JT(SDValue Op,
2154 SelectionDAG &DAG) const {
2155 SDLoc DL(Op);
2156 SDValue Chain = Op.getOperand(i: 0);
2157 const auto *JT = cast<JumpTableSDNode>(Val: Op.getOperand(i: 1));
2158 SDValue Index = Op.getOperand(i: 2);
2159 assert(JT->getTargetFlags() == 0 && "WebAssembly doesn't set target flags");
2160
2161 SmallVector<SDValue, 8> Ops;
2162 Ops.push_back(Elt: Chain);
2163 Ops.push_back(Elt: Index);
2164
2165 MachineJumpTableInfo *MJTI = DAG.getMachineFunction().getJumpTableInfo();
2166 const auto &MBBs = MJTI->getJumpTables()[JT->getIndex()].MBBs;
2167
2168 // Add an operand for each case.
2169 for (auto *MBB : MBBs)
2170 Ops.push_back(Elt: DAG.getBasicBlock(MBB));
2171
2172 // Add the first MBB as a dummy default target for now. This will be replaced
2173 // with the proper default target (and the preceding range check eliminated)
2174 // if possible by WebAssemblyFixBrTableDefaults.
2175 Ops.push_back(Elt: DAG.getBasicBlock(MBB: *MBBs.begin()));
2176 return DAG.getNode(Opcode: WebAssemblyISD::BR_TABLE, DL, VT: MVT::Other, Ops);
2177}
2178
2179SDValue WebAssemblyTargetLowering::LowerVASTART(SDValue Op,
2180 SelectionDAG &DAG) const {
2181 SDLoc DL(Op);
2182 EVT PtrVT = getPointerTy(DL: DAG.getMachineFunction().getDataLayout());
2183
2184 auto *MFI = DAG.getMachineFunction().getInfo<WebAssemblyFunctionInfo>();
2185 const Value *SV = cast<SrcValueSDNode>(Val: Op.getOperand(i: 2))->getValue();
2186
2187 SDValue ArgN = DAG.getCopyFromReg(Chain: DAG.getEntryNode(), dl: DL,
2188 Reg: MFI->getVarargBufferVreg(), VT: PtrVT);
2189 return DAG.getStore(Chain: Op.getOperand(i: 0), dl: DL, Val: ArgN, Ptr: Op.getOperand(i: 1),
2190 PtrInfo: MachinePointerInfo(SV));
2191}
2192
2193SDValue WebAssemblyTargetLowering::LowerIntrinsic(SDValue Op,
2194 SelectionDAG &DAG) const {
2195 MachineFunction &MF = DAG.getMachineFunction();
2196 unsigned IntNo;
2197 switch (Op.getOpcode()) {
2198 case ISD::INTRINSIC_VOID:
2199 case ISD::INTRINSIC_W_CHAIN:
2200 IntNo = Op.getConstantOperandVal(i: 1);
2201 break;
2202 case ISD::INTRINSIC_WO_CHAIN:
2203 IntNo = Op.getConstantOperandVal(i: 0);
2204 break;
2205 default:
2206 llvm_unreachable("Invalid intrinsic");
2207 }
2208 SDLoc DL(Op);
2209
2210 switch (IntNo) {
2211 default:
2212 return SDValue(); // Don't custom lower most intrinsics.
2213
2214 case Intrinsic::wasm_lsda: {
2215 auto PtrVT = getPointerTy(DL: MF.getDataLayout());
2216 const char *SymName = MF.createExternalSymbolName(
2217 Name: "GCC_except_table" + std::to_string(val: MF.getFunctionNumber()));
2218 if (isPositionIndependent()) {
2219 SDValue Node = DAG.getTargetExternalSymbol(
2220 Sym: SymName, VT: PtrVT, TargetFlags: WebAssemblyII::MO_MEMORY_BASE_REL);
2221 const char *BaseName = MF.createExternalSymbolName(Name: "__memory_base");
2222 SDValue BaseAddr =
2223 DAG.getNode(Opcode: WebAssemblyISD::Wrapper, DL, VT: PtrVT,
2224 Operand: DAG.getTargetExternalSymbol(Sym: BaseName, VT: PtrVT));
2225 SDValue SymAddr =
2226 DAG.getNode(Opcode: WebAssemblyISD::WrapperREL, DL, VT: PtrVT, Operand: Node);
2227 return DAG.getNode(Opcode: ISD::ADD, DL, VT: PtrVT, N1: BaseAddr, N2: SymAddr);
2228 }
2229 SDValue Node = DAG.getTargetExternalSymbol(Sym: SymName, VT: PtrVT);
2230 return DAG.getNode(Opcode: WebAssemblyISD::Wrapper, DL, VT: PtrVT, Operand: Node);
2231 }
2232
2233 case Intrinsic::wasm_shuffle: {
2234 // Drop in-chain and replace undefs, but otherwise pass through unchanged
2235 SDValue Ops[18];
2236 size_t OpIdx = 0;
2237 Ops[OpIdx++] = Op.getOperand(i: 1);
2238 Ops[OpIdx++] = Op.getOperand(i: 2);
2239 while (OpIdx < 18) {
2240 const SDValue &MaskIdx = Op.getOperand(i: OpIdx + 1);
2241 if (MaskIdx.isUndef() || MaskIdx.getNode()->getAsZExtVal() >= 32) {
2242 bool isTarget = MaskIdx.getNode()->getOpcode() == ISD::TargetConstant;
2243 Ops[OpIdx++] = DAG.getConstant(Val: 0, DL, VT: MVT::i32, isTarget);
2244 } else {
2245 Ops[OpIdx++] = MaskIdx;
2246 }
2247 }
2248 return DAG.getNode(Opcode: WebAssemblyISD::SHUFFLE, DL, VT: Op.getValueType(), Ops);
2249 }
2250
2251 case Intrinsic::thread_pointer: {
2252 MVT PtrVT = getPointerTy(DL: DAG.getDataLayout());
2253 auto GlobalGet = PtrVT == MVT::i64 ? WebAssembly::GLOBAL_GET_I64
2254 : WebAssembly::GLOBAL_GET_I32;
2255 const char *TlsBase = MF.createExternalSymbolName(Name: "__tls_base");
2256 return SDValue(
2257 DAG.getMachineNode(Opcode: GlobalGet, dl: DL, VT: PtrVT,
2258 Op1: DAG.getTargetExternalSymbol(Sym: TlsBase, VT: PtrVT)),
2259 0);
2260 }
2261 }
2262}
2263
2264SDValue
2265WebAssemblyTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
2266 SelectionDAG &DAG) const {
2267 SDLoc DL(Op);
2268 // If sign extension operations are disabled, allow sext_inreg only if operand
2269 // is a vector extract of an i8 or i16 lane. SIMD does not depend on sign
2270 // extension operations, but allowing sext_inreg in this context lets us have
2271 // simple patterns to select extract_lane_s instructions. Expanding sext_inreg
2272 // everywhere would be simpler in this file, but would necessitate large and
2273 // brittle patterns to undo the expansion and select extract_lane_s
2274 // instructions.
2275 assert(!Subtarget->hasSignExt() && Subtarget->hasSIMD128());
2276 if (Op.getOperand(i: 0).getOpcode() != ISD::EXTRACT_VECTOR_ELT)
2277 return SDValue();
2278
2279 const SDValue &Extract = Op.getOperand(i: 0);
2280 MVT VecT = Extract.getOperand(i: 0).getSimpleValueType();
2281 if (VecT.getVectorElementType().getSizeInBits() > 32)
2282 return SDValue();
2283 MVT ExtractedLaneT =
2284 cast<VTSDNode>(Val: Op.getOperand(i: 1).getNode())->getVT().getSimpleVT();
2285 MVT ExtractedVecT =
2286 MVT::getVectorVT(VT: ExtractedLaneT, NumElements: 128 / ExtractedLaneT.getSizeInBits());
2287 if (ExtractedVecT == VecT)
2288 return Op;
2289
2290 // Bitcast vector to appropriate type to ensure ISel pattern coverage
2291 const SDNode *Index = Extract.getOperand(i: 1).getNode();
2292 if (!isa<ConstantSDNode>(Val: Index))
2293 return SDValue();
2294 unsigned IndexVal = Index->getAsZExtVal();
2295 unsigned Scale =
2296 ExtractedVecT.getVectorNumElements() / VecT.getVectorNumElements();
2297 assert(Scale > 1);
2298 SDValue NewIndex =
2299 DAG.getConstant(Val: IndexVal * Scale, DL, VT: Index->getValueType(ResNo: 0));
2300 SDValue NewExtract = DAG.getNode(
2301 Opcode: ISD::EXTRACT_VECTOR_ELT, DL, VT: Extract.getValueType(),
2302 N1: DAG.getBitcast(VT: ExtractedVecT, V: Extract.getOperand(i: 0)), N2: NewIndex);
2303 return DAG.getNode(Opcode: ISD::SIGN_EXTEND_INREG, DL, VT: Op.getValueType(), N1: NewExtract,
2304 N2: Op.getOperand(i: 1));
2305}
2306
2307static SDValue GetExtendHigh(SDValue Op, unsigned UserOpc, EVT VT,
2308 SelectionDAG &DAG) {
2309 SDValue Source = peekThroughBitcasts(V: Op);
2310 if (Source.getOpcode() != ISD::VECTOR_SHUFFLE)
2311 return SDValue();
2312
2313 assert((UserOpc == WebAssemblyISD::EXTEND_LOW_U ||
2314 UserOpc == WebAssemblyISD::EXTEND_LOW_S) &&
2315 "expected extend_low");
2316 auto *Shuffle = cast<ShuffleVectorSDNode>(Val: Source.getNode());
2317
2318 ArrayRef<int> Mask = Shuffle->getMask();
2319 // Look for a shuffle which moves from the high half to the low half.
2320 size_t FirstIdx = Mask.size() / 2;
2321 for (size_t i = 0; i < Mask.size() / 2; ++i) {
2322 if (Mask[i] != static_cast<int>(FirstIdx + i)) {
2323 return SDValue();
2324 }
2325 }
2326
2327 SDLoc DL(Op);
2328 unsigned Opc = UserOpc == WebAssemblyISD::EXTEND_LOW_S
2329 ? WebAssemblyISD::EXTEND_HIGH_S
2330 : WebAssemblyISD::EXTEND_HIGH_U;
2331 SDValue ShuffleSrc = Shuffle->getOperand(Num: 0);
2332 if (Op.getOpcode() == ISD::BITCAST)
2333 ShuffleSrc = DAG.getBitcast(VT: Op.getValueType(), V: ShuffleSrc);
2334
2335 return DAG.getNode(Opcode: Opc, DL, VT, Operand: ShuffleSrc);
2336}
2337
2338SDValue
2339WebAssemblyTargetLowering::LowerEXTEND_VECTOR_INREG(SDValue Op,
2340 SelectionDAG &DAG) const {
2341 SDLoc DL(Op);
2342 EVT VT = Op.getValueType();
2343 SDValue Src = Op.getOperand(i: 0);
2344 EVT SrcVT = Src.getValueType();
2345
2346 if (SrcVT.getVectorElementType() == MVT::i1 ||
2347 SrcVT.getVectorElementType() == MVT::i64)
2348 return SDValue();
2349
2350 assert(VT.getScalarSizeInBits() % SrcVT.getScalarSizeInBits() == 0 &&
2351 "Unexpected extension factor.");
2352 unsigned Scale = VT.getScalarSizeInBits() / SrcVT.getScalarSizeInBits();
2353
2354 if (Scale != 2 && Scale != 4 && Scale != 8)
2355 return SDValue();
2356
2357 unsigned Ext;
2358 switch (Op.getOpcode()) {
2359 default:
2360 llvm_unreachable("unexpected opcode");
2361 case ISD::ANY_EXTEND_VECTOR_INREG:
2362 case ISD::ZERO_EXTEND_VECTOR_INREG:
2363 Ext = WebAssemblyISD::EXTEND_LOW_U;
2364 break;
2365 case ISD::SIGN_EXTEND_VECTOR_INREG:
2366 Ext = WebAssemblyISD::EXTEND_LOW_S;
2367 break;
2368 }
2369
2370 if (Scale == 2) {
2371 // See if we can use EXTEND_HIGH.
2372 if (auto ExtendHigh = GetExtendHigh(Op: Op.getOperand(i: 0), UserOpc: Ext, VT, DAG))
2373 return ExtendHigh;
2374 }
2375
2376 SDValue Ret = Src;
2377 while (Scale != 1) {
2378 Ret = DAG.getNode(Opcode: Ext, DL,
2379 VT: Ret.getValueType()
2380 .widenIntegerVectorElementType(Context&: *DAG.getContext())
2381 .getHalfNumVectorElementsVT(Context&: *DAG.getContext()),
2382 Operand: Ret);
2383 Scale /= 2;
2384 }
2385 assert(Ret.getValueType() == VT);
2386 return Ret;
2387}
2388
2389static SDValue LowerConvertLow(SDValue Op, SelectionDAG &DAG) {
2390 SDLoc DL(Op);
2391 if (Op.getValueType() != MVT::v2f64)
2392 return SDValue();
2393
2394 auto GetConvertedLane = [](SDValue Op, unsigned &Opcode, SDValue &SrcVec,
2395 unsigned &Index) -> bool {
2396 switch (Op.getOpcode()) {
2397 case ISD::SINT_TO_FP:
2398 Opcode = WebAssemblyISD::CONVERT_LOW_S;
2399 break;
2400 case ISD::UINT_TO_FP:
2401 Opcode = WebAssemblyISD::CONVERT_LOW_U;
2402 break;
2403 case ISD::FP_EXTEND:
2404 Opcode = WebAssemblyISD::PROMOTE_LOW;
2405 break;
2406 default:
2407 return false;
2408 }
2409
2410 auto ExtractVector = Op.getOperand(i: 0);
2411 if (ExtractVector.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
2412 return false;
2413
2414 if (!isa<ConstantSDNode>(Val: ExtractVector.getOperand(i: 1).getNode()))
2415 return false;
2416
2417 SrcVec = ExtractVector.getOperand(i: 0);
2418 Index = ExtractVector.getConstantOperandVal(i: 1);
2419 return true;
2420 };
2421
2422 unsigned LHSOpcode, RHSOpcode, LHSIndex, RHSIndex;
2423 SDValue LHSSrcVec, RHSSrcVec;
2424 if (!GetConvertedLane(Op.getOperand(i: 0), LHSOpcode, LHSSrcVec, LHSIndex) ||
2425 !GetConvertedLane(Op.getOperand(i: 1), RHSOpcode, RHSSrcVec, RHSIndex))
2426 return SDValue();
2427
2428 if (LHSOpcode != RHSOpcode)
2429 return SDValue();
2430
2431 MVT ExpectedSrcVT;
2432 switch (LHSOpcode) {
2433 case WebAssemblyISD::CONVERT_LOW_S:
2434 case WebAssemblyISD::CONVERT_LOW_U:
2435 ExpectedSrcVT = MVT::v4i32;
2436 break;
2437 case WebAssemblyISD::PROMOTE_LOW:
2438 ExpectedSrcVT = MVT::v4f32;
2439 break;
2440 }
2441 if (LHSSrcVec.getValueType() != ExpectedSrcVT)
2442 return SDValue();
2443
2444 auto Src = LHSSrcVec;
2445 if (LHSIndex != 0 || RHSIndex != 1 || LHSSrcVec != RHSSrcVec) {
2446 // Shuffle the source vector so that the converted lanes are the low lanes.
2447 Src = DAG.getVectorShuffle(
2448 VT: ExpectedSrcVT, dl: DL, N1: LHSSrcVec, N2: RHSSrcVec,
2449 Mask: {static_cast<int>(LHSIndex), static_cast<int>(RHSIndex) + 4, -1, -1});
2450 }
2451 return DAG.getNode(Opcode: LHSOpcode, DL, VT: MVT::v2f64, Operand: Src);
2452}
2453
2454SDValue WebAssemblyTargetLowering::LowerBUILD_VECTOR(SDValue Op,
2455 SelectionDAG &DAG) const {
2456 MVT VT = Op.getSimpleValueType();
2457 if (VT == MVT::v8f16) {
2458 // BUILD_VECTOR can't handle FP16 operands since Wasm doesn't have a scaler
2459 // FP16 type, so cast them to I16s.
2460 MVT IVT = VT.changeVectorElementType(EltVT: MVT::i16);
2461 SmallVector<SDValue, 8> NewOps;
2462 for (unsigned I = 0, E = Op.getNumOperands(); I < E; ++I)
2463 NewOps.push_back(Elt: DAG.getBitcast(VT: MVT::i16, V: Op.getOperand(i: I)));
2464 SDValue Res = DAG.getNode(Opcode: ISD::BUILD_VECTOR, DL: SDLoc(), VT: IVT, Ops: NewOps);
2465 return DAG.getBitcast(VT, V: Res);
2466 }
2467
2468 if (auto ConvertLow = LowerConvertLow(Op, DAG))
2469 return ConvertLow;
2470
2471 SDLoc DL(Op);
2472 const EVT VecT = Op.getValueType();
2473 const EVT LaneT = Op.getOperand(i: 0).getValueType();
2474 const size_t Lanes = Op.getNumOperands();
2475 bool CanSwizzle = VecT == MVT::v16i8;
2476
2477 // BUILD_VECTORs are lowered to the instruction that initializes the highest
2478 // possible number of lanes at once followed by a sequence of replace_lane
2479 // instructions to individually initialize any remaining lanes.
2480
2481 // TODO: Tune this. For example, lanewise swizzling is very expensive, so
2482 // swizzled lanes should be given greater weight.
2483
2484 // TODO: Investigate looping rather than always extracting/replacing specific
2485 // lanes to fill gaps.
2486
2487 auto IsConstant = [](const SDValue &V) {
2488 return V.getOpcode() == ISD::Constant || V.getOpcode() == ISD::ConstantFP;
2489 };
2490
2491 // Returns the source vector and index vector pair if they exist. Checks for:
2492 // (extract_vector_elt
2493 // $src,
2494 // (sign_extend_inreg (extract_vector_elt $indices, $i))
2495 // )
2496 auto GetSwizzleSrcs = [](size_t I, const SDValue &Lane) {
2497 auto Bail = std::make_pair(x: SDValue(), y: SDValue());
2498 if (Lane->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
2499 return Bail;
2500 const SDValue &SwizzleSrc = Lane->getOperand(Num: 0);
2501 const SDValue &IndexExt = Lane->getOperand(Num: 1);
2502 if (IndexExt->getOpcode() != ISD::SIGN_EXTEND_INREG)
2503 return Bail;
2504 const SDValue &Index = IndexExt->getOperand(Num: 0);
2505 if (Index->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
2506 return Bail;
2507 const SDValue &SwizzleIndices = Index->getOperand(Num: 0);
2508 if (SwizzleSrc.getValueType() != MVT::v16i8 ||
2509 SwizzleIndices.getValueType() != MVT::v16i8 ||
2510 Index->getOperand(Num: 1)->getOpcode() != ISD::Constant ||
2511 Index->getConstantOperandVal(Num: 1) != I)
2512 return Bail;
2513 return std::make_pair(x: SwizzleSrc, y: SwizzleIndices);
2514 };
2515
2516 // If the lane is extracted from another vector at a constant index, return
2517 // that vector. The source vector must not have more lanes than the dest
2518 // because the shufflevector indices are in terms of the destination lanes and
2519 // would not be able to address the smaller individual source lanes.
2520 auto GetShuffleSrc = [&](const SDValue &Lane) {
2521 if (Lane->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
2522 return SDValue();
2523 if (!isa<ConstantSDNode>(Val: Lane->getOperand(Num: 1).getNode()))
2524 return SDValue();
2525 if (Lane->getOperand(Num: 0).getValueType().getVectorNumElements() >
2526 VecT.getVectorNumElements())
2527 return SDValue();
2528 return Lane->getOperand(Num: 0);
2529 };
2530
2531 using ValueEntry = std::pair<SDValue, size_t>;
2532 SmallVector<ValueEntry, 16> SplatValueCounts;
2533
2534 using SwizzleEntry = std::pair<std::pair<SDValue, SDValue>, size_t>;
2535 SmallVector<SwizzleEntry, 16> SwizzleCounts;
2536
2537 using ShuffleEntry = std::pair<SDValue, size_t>;
2538 SmallVector<ShuffleEntry, 16> ShuffleCounts;
2539
2540 auto AddCount = [](auto &Counts, const auto &Val) {
2541 auto CountIt =
2542 llvm::find_if(Counts, [&Val](auto E) { return E.first == Val; });
2543 if (CountIt == Counts.end()) {
2544 Counts.emplace_back(Val, 1);
2545 } else {
2546 CountIt->second++;
2547 }
2548 };
2549
2550 auto GetMostCommon = [](auto &Counts) {
2551 auto CommonIt = llvm::max_element(Counts, llvm::less_second());
2552 assert(CommonIt != Counts.end() && "Unexpected all-undef build_vector");
2553 return *CommonIt;
2554 };
2555
2556 size_t NumConstantLanes = 0;
2557
2558 // Count eligible lanes for each type of vector creation op
2559 for (size_t I = 0; I < Lanes; ++I) {
2560 const SDValue &Lane = Op->getOperand(Num: I);
2561 if (Lane.isUndef())
2562 continue;
2563
2564 AddCount(SplatValueCounts, Lane);
2565
2566 if (IsConstant(Lane))
2567 NumConstantLanes++;
2568 if (auto ShuffleSrc = GetShuffleSrc(Lane))
2569 AddCount(ShuffleCounts, ShuffleSrc);
2570 if (CanSwizzle) {
2571 auto SwizzleSrcs = GetSwizzleSrcs(I, Lane);
2572 if (SwizzleSrcs.first)
2573 AddCount(SwizzleCounts, SwizzleSrcs);
2574 }
2575 }
2576
2577 SDValue SplatValue;
2578 size_t NumSplatLanes;
2579 std::tie(args&: SplatValue, args&: NumSplatLanes) = GetMostCommon(SplatValueCounts);
2580
2581 SDValue SwizzleSrc;
2582 SDValue SwizzleIndices;
2583 size_t NumSwizzleLanes = 0;
2584 if (SwizzleCounts.size())
2585 std::forward_as_tuple(args: std::tie(args&: SwizzleSrc, args&: SwizzleIndices),
2586 args&: NumSwizzleLanes) = GetMostCommon(SwizzleCounts);
2587
2588 // Shuffles can draw from up to two vectors, so find the two most common
2589 // sources.
2590 SDValue ShuffleSrc1, ShuffleSrc2;
2591 size_t NumShuffleLanes = 0;
2592 if (ShuffleCounts.size()) {
2593 std::tie(args&: ShuffleSrc1, args&: NumShuffleLanes) = GetMostCommon(ShuffleCounts);
2594 llvm::erase_if(C&: ShuffleCounts,
2595 P: [&](const auto &Pair) { return Pair.first == ShuffleSrc1; });
2596 }
2597 if (ShuffleCounts.size()) {
2598 size_t AdditionalShuffleLanes;
2599 std::tie(args&: ShuffleSrc2, args&: AdditionalShuffleLanes) =
2600 GetMostCommon(ShuffleCounts);
2601 NumShuffleLanes += AdditionalShuffleLanes;
2602 }
2603
2604 // Predicate returning true if the lane is properly initialized by the
2605 // original instruction
2606 std::function<bool(size_t, const SDValue &)> IsLaneConstructed;
2607 SDValue Result;
2608 // Prefer swizzles over shuffles over vector consts over splats
2609 if (NumSwizzleLanes >= NumShuffleLanes &&
2610 NumSwizzleLanes >= NumConstantLanes && NumSwizzleLanes >= NumSplatLanes) {
2611 Result = DAG.getNode(Opcode: WebAssemblyISD::SWIZZLE, DL, VT: VecT, N1: SwizzleSrc,
2612 N2: SwizzleIndices);
2613 auto Swizzled = std::make_pair(x&: SwizzleSrc, y&: SwizzleIndices);
2614 IsLaneConstructed = [&, Swizzled](size_t I, const SDValue &Lane) {
2615 return Swizzled == GetSwizzleSrcs(I, Lane);
2616 };
2617 } else if (NumShuffleLanes >= NumConstantLanes &&
2618 NumShuffleLanes >= NumSplatLanes) {
2619 size_t DestLaneSize = VecT.getVectorElementType().getFixedSizeInBits() / 8;
2620 size_t DestLaneCount = VecT.getVectorNumElements();
2621 size_t Scale1 = 1;
2622 size_t Scale2 = 1;
2623 SDValue Src1 = ShuffleSrc1;
2624 SDValue Src2 = ShuffleSrc2 ? ShuffleSrc2 : DAG.getUNDEF(VT: VecT);
2625 if (Src1.getValueType() != VecT) {
2626 size_t LaneSize =
2627 Src1.getValueType().getVectorElementType().getFixedSizeInBits() / 8;
2628 assert(LaneSize > DestLaneSize);
2629 Scale1 = LaneSize / DestLaneSize;
2630 Src1 = DAG.getBitcast(VT: VecT, V: Src1);
2631 }
2632 if (Src2.getValueType() != VecT) {
2633 size_t LaneSize =
2634 Src2.getValueType().getVectorElementType().getFixedSizeInBits() / 8;
2635 assert(LaneSize > DestLaneSize);
2636 Scale2 = LaneSize / DestLaneSize;
2637 Src2 = DAG.getBitcast(VT: VecT, V: Src2);
2638 }
2639
2640 int Mask[16];
2641 assert(DestLaneCount <= 16);
2642 for (size_t I = 0; I < DestLaneCount; ++I) {
2643 const SDValue &Lane = Op->getOperand(Num: I);
2644 SDValue Src = GetShuffleSrc(Lane);
2645 if (Src == ShuffleSrc1) {
2646 Mask[I] = Lane->getConstantOperandVal(Num: 1) * Scale1;
2647 } else if (Src && Src == ShuffleSrc2) {
2648 Mask[I] = DestLaneCount + Lane->getConstantOperandVal(Num: 1) * Scale2;
2649 } else {
2650 Mask[I] = -1;
2651 }
2652 }
2653 ArrayRef<int> MaskRef(Mask, DestLaneCount);
2654 Result = DAG.getVectorShuffle(VT: VecT, dl: DL, N1: Src1, N2: Src2, Mask: MaskRef);
2655 IsLaneConstructed = [&](size_t, const SDValue &Lane) {
2656 auto Src = GetShuffleSrc(Lane);
2657 return Src == ShuffleSrc1 || (Src && Src == ShuffleSrc2);
2658 };
2659 } else if (NumConstantLanes >= NumSplatLanes) {
2660 SmallVector<SDValue, 16> ConstLanes;
2661 for (const SDValue &Lane : Op->op_values()) {
2662 if (IsConstant(Lane)) {
2663 // Values may need to be fixed so that they will sign extend to be
2664 // within the expected range during ISel. Check whether the value is in
2665 // bounds based on the lane bit width and if it is out of bounds, lop
2666 // off the extra bits.
2667 uint64_t LaneBits = 128 / Lanes;
2668 if (auto *Const = dyn_cast<ConstantSDNode>(Val: Lane.getNode())) {
2669 ConstLanes.push_back(Elt: DAG.getConstant(
2670 Val: Const->getAPIntValue().trunc(width: LaneBits).getZExtValue(),
2671 DL: SDLoc(Lane), VT: LaneT));
2672 } else {
2673 ConstLanes.push_back(Elt: Lane);
2674 }
2675 } else if (LaneT.isFloatingPoint()) {
2676 ConstLanes.push_back(Elt: DAG.getConstantFP(Val: 0, DL, VT: LaneT));
2677 } else {
2678 ConstLanes.push_back(Elt: DAG.getConstant(Val: 0, DL, VT: LaneT));
2679 }
2680 }
2681 Result = DAG.getBuildVector(VT: VecT, DL, Ops: ConstLanes);
2682 IsLaneConstructed = [&IsConstant](size_t _, const SDValue &Lane) {
2683 return IsConstant(Lane);
2684 };
2685 } else {
2686 size_t DestLaneSize = VecT.getVectorElementType().getFixedSizeInBits();
2687 if (NumSplatLanes == 1 && Op->getOperand(Num: 0) == SplatValue &&
2688 (DestLaneSize == 32 || DestLaneSize == 64)) {
2689 // Could be selected to load_zero.
2690 Result = DAG.getNode(Opcode: ISD::SCALAR_TO_VECTOR, DL, VT: VecT, Operand: SplatValue);
2691 } else {
2692 // Use a splat (which might be selected as a load splat)
2693 Result = DAG.getSplatBuildVector(VT: VecT, DL, Op: SplatValue);
2694 }
2695 IsLaneConstructed = [&SplatValue](size_t _, const SDValue &Lane) {
2696 return Lane == SplatValue;
2697 };
2698 }
2699
2700 assert(Result);
2701 assert(IsLaneConstructed);
2702
2703 // Add replace_lane instructions for any unhandled values
2704 for (size_t I = 0; I < Lanes; ++I) {
2705 const SDValue &Lane = Op->getOperand(Num: I);
2706 if (!Lane.isUndef() && !IsLaneConstructed(I, Lane))
2707 Result = DAG.getNode(Opcode: ISD::INSERT_VECTOR_ELT, DL, VT: VecT, N1: Result, N2: Lane,
2708 N3: DAG.getConstant(Val: I, DL, VT: MVT::i32));
2709 }
2710
2711 return Result;
2712}
2713
2714SDValue
2715WebAssemblyTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
2716 SelectionDAG &DAG) const {
2717 SDLoc DL(Op);
2718 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Val: Op.getNode())->getMask();
2719 MVT VecType = Op.getOperand(i: 0).getSimpleValueType();
2720 assert(VecType.is128BitVector() && "Unexpected shuffle vector type");
2721 size_t LaneBytes = VecType.getVectorElementType().getSizeInBits() / 8;
2722
2723 // Space for two vector args and sixteen mask indices
2724 SDValue Ops[18];
2725 size_t OpIdx = 0;
2726 Ops[OpIdx++] = Op.getOperand(i: 0);
2727 Ops[OpIdx++] = Op.getOperand(i: 1);
2728
2729 // Expand mask indices to byte indices and materialize them as operands
2730 for (int M : Mask) {
2731 for (size_t J = 0; J < LaneBytes; ++J) {
2732 // Lower undefs (represented by -1 in mask) to {0..J}, which use a
2733 // whole lane of vector input, to allow further reduction at VM. E.g.
2734 // match an 8x16 byte shuffle to an equivalent cheaper 32x4 shuffle.
2735 uint64_t ByteIndex = M == -1 ? J : (uint64_t)M * LaneBytes + J;
2736 Ops[OpIdx++] = DAG.getConstant(Val: ByteIndex, DL, VT: MVT::i32);
2737 }
2738 }
2739
2740 return DAG.getNode(Opcode: WebAssemblyISD::SHUFFLE, DL, VT: Op.getValueType(), Ops);
2741}
2742
2743SDValue WebAssemblyTargetLowering::LowerSETCC(SDValue Op,
2744 SelectionDAG &DAG) const {
2745 SDLoc DL(Op);
2746 // The legalizer does not know how to expand the unsupported comparison modes
2747 // of i64x2 vectors, so we manually unroll them here.
2748 assert(Op->getOperand(0)->getSimpleValueType(0) == MVT::v2i64);
2749 SmallVector<SDValue, 2> LHS, RHS;
2750 DAG.ExtractVectorElements(Op: Op->getOperand(Num: 0), Args&: LHS);
2751 DAG.ExtractVectorElements(Op: Op->getOperand(Num: 1), Args&: RHS);
2752 const SDValue &CC = Op->getOperand(Num: 2);
2753 auto MakeLane = [&](unsigned I) {
2754 return DAG.getNode(Opcode: ISD::SELECT_CC, DL, VT: MVT::i64, N1: LHS[I], N2: RHS[I],
2755 N3: DAG.getConstant(Val: uint64_t(-1), DL, VT: MVT::i64),
2756 N4: DAG.getConstant(Val: uint64_t(0), DL, VT: MVT::i64), N5: CC);
2757 };
2758 return DAG.getBuildVector(VT: Op->getValueType(ResNo: 0), DL,
2759 Ops: {MakeLane(0), MakeLane(1)});
2760}
2761
2762SDValue
2763WebAssemblyTargetLowering::LowerAccessVectorElement(SDValue Op,
2764 SelectionDAG &DAG) const {
2765 // Allow constant lane indices, expand variable lane indices
2766 SDNode *IdxNode = Op.getOperand(i: Op.getNumOperands() - 1).getNode();
2767 if (isa<ConstantSDNode>(Val: IdxNode)) {
2768 // Ensure the index type is i32 to match the tablegen patterns
2769 uint64_t Idx = IdxNode->getAsZExtVal();
2770 SmallVector<SDValue, 3> Ops(Op.getNode()->ops());
2771 Ops[Op.getNumOperands() - 1] =
2772 DAG.getConstant(Val: Idx, DL: SDLoc(IdxNode), VT: MVT::i32);
2773 return DAG.getNode(Opcode: Op.getOpcode(), DL: SDLoc(Op), VT: Op.getValueType(), Ops);
2774 }
2775 // Perform default expansion
2776 return SDValue();
2777}
2778
2779static SDValue unrollVectorShift(SDValue Op, SelectionDAG &DAG) {
2780 EVT LaneT = Op.getSimpleValueType().getVectorElementType();
2781 // 32-bit and 64-bit unrolled shifts will have proper semantics
2782 if (LaneT.bitsGE(VT: MVT::i32))
2783 return DAG.UnrollVectorOp(N: Op.getNode());
2784 // Otherwise mask the shift value to get proper semantics from 32-bit shift
2785 SDLoc DL(Op);
2786 size_t NumLanes = Op.getSimpleValueType().getVectorNumElements();
2787 SDValue Mask = DAG.getConstant(Val: LaneT.getSizeInBits() - 1, DL, VT: MVT::i32);
2788 unsigned ShiftOpcode = Op.getOpcode();
2789 SmallVector<SDValue, 16> ShiftedElements;
2790 DAG.ExtractVectorElements(Op: Op.getOperand(i: 0), Args&: ShiftedElements, Start: 0, Count: 0, EltVT: MVT::i32);
2791 SmallVector<SDValue, 16> ShiftElements;
2792 DAG.ExtractVectorElements(Op: Op.getOperand(i: 1), Args&: ShiftElements, Start: 0, Count: 0, EltVT: MVT::i32);
2793 SmallVector<SDValue, 16> UnrolledOps;
2794 for (size_t i = 0; i < NumLanes; ++i) {
2795 SDValue MaskedShiftValue =
2796 DAG.getNode(Opcode: ISD::AND, DL, VT: MVT::i32, N1: ShiftElements[i], N2: Mask);
2797 SDValue ShiftedValue = ShiftedElements[i];
2798 if (ShiftOpcode == ISD::SRA)
2799 ShiftedValue = DAG.getNode(Opcode: ISD::SIGN_EXTEND_INREG, DL, VT: MVT::i32,
2800 N1: ShiftedValue, N2: DAG.getValueType(LaneT));
2801 UnrolledOps.push_back(
2802 Elt: DAG.getNode(Opcode: ShiftOpcode, DL, VT: MVT::i32, N1: ShiftedValue, N2: MaskedShiftValue));
2803 }
2804 return DAG.getBuildVector(VT: Op.getValueType(), DL, Ops: UnrolledOps);
2805}
2806
2807SDValue WebAssemblyTargetLowering::LowerShift(SDValue Op,
2808 SelectionDAG &DAG) const {
2809 SDLoc DL(Op);
2810 // Only manually lower vector shifts
2811 assert(Op.getSimpleValueType().isVector());
2812
2813 uint64_t LaneBits = Op.getValueType().getScalarSizeInBits();
2814 auto ShiftVal = Op.getOperand(i: 1);
2815
2816 // Try to skip bitmask operation since it is implied inside shift instruction
2817 auto SkipImpliedMask = [](SDValue MaskOp, uint64_t MaskBits) {
2818 if (MaskOp.getOpcode() != ISD::AND)
2819 return MaskOp;
2820 SDValue LHS = MaskOp.getOperand(i: 0);
2821 SDValue RHS = MaskOp.getOperand(i: 1);
2822 if (MaskOp.getValueType().isVector()) {
2823 APInt MaskVal;
2824 if (!ISD::isConstantSplatVector(N: RHS.getNode(), SplatValue&: MaskVal))
2825 std::swap(a&: LHS, b&: RHS);
2826
2827 if (ISD::isConstantSplatVector(N: RHS.getNode(), SplatValue&: MaskVal) &&
2828 MaskVal == MaskBits)
2829 MaskOp = LHS;
2830 } else {
2831 if (!isa<ConstantSDNode>(Val: RHS.getNode()))
2832 std::swap(a&: LHS, b&: RHS);
2833
2834 auto ConstantRHS = dyn_cast<ConstantSDNode>(Val: RHS.getNode());
2835 if (ConstantRHS && ConstantRHS->getAPIntValue() == MaskBits)
2836 MaskOp = LHS;
2837 }
2838
2839 return MaskOp;
2840 };
2841
2842 // Skip vector and operation
2843 ShiftVal = SkipImpliedMask(ShiftVal, LaneBits - 1);
2844 ShiftVal = DAG.getSplatValue(V: ShiftVal);
2845 if (!ShiftVal)
2846 return unrollVectorShift(Op, DAG);
2847
2848 // Skip scalar and operation
2849 ShiftVal = SkipImpliedMask(ShiftVal, LaneBits - 1);
2850 // Use anyext because none of the high bits can affect the shift
2851 ShiftVal = DAG.getAnyExtOrTrunc(Op: ShiftVal, DL, VT: MVT::i32);
2852
2853 unsigned Opcode;
2854 switch (Op.getOpcode()) {
2855 case ISD::SHL:
2856 Opcode = WebAssemblyISD::VEC_SHL;
2857 break;
2858 case ISD::SRA:
2859 Opcode = WebAssemblyISD::VEC_SHR_S;
2860 break;
2861 case ISD::SRL:
2862 Opcode = WebAssemblyISD::VEC_SHR_U;
2863 break;
2864 default:
2865 llvm_unreachable("unexpected opcode");
2866 }
2867
2868 return DAG.getNode(Opcode, DL, VT: Op.getValueType(), N1: Op.getOperand(i: 0), N2: ShiftVal);
2869}
2870
2871SDValue WebAssemblyTargetLowering::LowerFP_TO_INT_SAT(SDValue Op,
2872 SelectionDAG &DAG) const {
2873 EVT ResT = Op.getValueType();
2874 EVT SatVT = cast<VTSDNode>(Val: Op.getOperand(i: 1))->getVT();
2875
2876 if ((ResT == MVT::i32 || ResT == MVT::i64) &&
2877 (SatVT == MVT::i32 || SatVT == MVT::i64))
2878 return Op;
2879
2880 if (ResT == MVT::v4i32 && SatVT == MVT::i32)
2881 return Op;
2882
2883 if (ResT == MVT::v8i16 && SatVT == MVT::i16)
2884 return Op;
2885
2886 return SDValue();
2887}
2888
2889static bool HasNoSignedZerosOrNaNs(SDValue Op, SelectionDAG &DAG) {
2890 return (Op->getFlags().hasNoNaNs() ||
2891 (DAG.isKnownNeverNaN(Op: Op->getOperand(Num: 0)) &&
2892 DAG.isKnownNeverNaN(Op: Op->getOperand(Num: 1)))) &&
2893 (Op->getFlags().hasNoSignedZeros() ||
2894 DAG.isKnownNeverZeroFloat(Op: Op->getOperand(Num: 0)) ||
2895 DAG.isKnownNeverZeroFloat(Op: Op->getOperand(Num: 1)));
2896}
2897
2898SDValue WebAssemblyTargetLowering::LowerFMIN(SDValue Op,
2899 SelectionDAG &DAG) const {
2900 if (Subtarget->hasRelaxedSIMD() && HasNoSignedZerosOrNaNs(Op, DAG)) {
2901 return DAG.getNode(Opcode: WebAssemblyISD::RELAXED_FMIN, DL: SDLoc(Op),
2902 VT: Op.getValueType(), N1: Op.getOperand(i: 0), N2: Op.getOperand(i: 1));
2903 }
2904 return SDValue();
2905}
2906
2907SDValue WebAssemblyTargetLowering::LowerFMAX(SDValue Op,
2908 SelectionDAG &DAG) const {
2909 if (Subtarget->hasRelaxedSIMD() && HasNoSignedZerosOrNaNs(Op, DAG)) {
2910 return DAG.getNode(Opcode: WebAssemblyISD::RELAXED_FMAX, DL: SDLoc(Op),
2911 VT: Op.getValueType(), N1: Op.getOperand(i: 0), N2: Op.getOperand(i: 1));
2912 }
2913 return SDValue();
2914}
2915
2916//===----------------------------------------------------------------------===//
2917// Custom DAG combine hooks
2918//===----------------------------------------------------------------------===//
2919static SDValue
2920performVECTOR_SHUFFLECombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
2921 auto &DAG = DCI.DAG;
2922 auto Shuffle = cast<ShuffleVectorSDNode>(Val: N);
2923
2924 // Hoist vector bitcasts that don't change the number of lanes out of unary
2925 // shuffles, where they are less likely to get in the way of other combines.
2926 // (shuffle (vNxT1 (bitcast (vNxT0 x))), undef, mask) ->
2927 // (vNxT1 (bitcast (vNxT0 (shuffle x, undef, mask))))
2928 SDValue Bitcast = N->getOperand(Num: 0);
2929 if (Bitcast.getOpcode() != ISD::BITCAST)
2930 return SDValue();
2931 if (!N->getOperand(Num: 1).isUndef())
2932 return SDValue();
2933 SDValue CastOp = Bitcast.getOperand(i: 0);
2934 EVT SrcType = CastOp.getValueType();
2935 EVT DstType = Bitcast.getValueType();
2936 if (!SrcType.is128BitVector() ||
2937 SrcType.getVectorNumElements() != DstType.getVectorNumElements())
2938 return SDValue();
2939 SDValue NewShuffle = DAG.getVectorShuffle(
2940 VT: SrcType, dl: SDLoc(N), N1: CastOp, N2: DAG.getUNDEF(VT: SrcType), Mask: Shuffle->getMask());
2941 return DAG.getBitcast(VT: DstType, V: NewShuffle);
2942}
2943
2944/// Convert ({u,s}itofp vec) --> ({u,s}itofp ({s,z}ext vec)) so it doesn't get
2945/// split up into scalar instructions during legalization, and the vector
2946/// extending instructions are selected in performVectorExtendCombine below.
2947static SDValue
2948performVectorExtendToFPCombine(SDNode *N,
2949 TargetLowering::DAGCombinerInfo &DCI) {
2950 auto &DAG = DCI.DAG;
2951 assert(N->getOpcode() == ISD::UINT_TO_FP ||
2952 N->getOpcode() == ISD::SINT_TO_FP);
2953
2954 EVT InVT = N->getOperand(Num: 0)->getValueType(ResNo: 0);
2955 EVT ResVT = N->getValueType(ResNo: 0);
2956 MVT ExtVT;
2957 if (ResVT == MVT::v4f32 && (InVT == MVT::v4i16 || InVT == MVT::v4i8))
2958 ExtVT = MVT::v4i32;
2959 else if (ResVT == MVT::v2f64 && (InVT == MVT::v2i16 || InVT == MVT::v2i8))
2960 ExtVT = MVT::v2i32;
2961 else
2962 return SDValue();
2963
2964 unsigned Op =
2965 N->getOpcode() == ISD::UINT_TO_FP ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
2966 SDValue Conv = DAG.getNode(Opcode: Op, DL: SDLoc(N), VT: ExtVT, Operand: N->getOperand(Num: 0));
2967 return DAG.getNode(Opcode: N->getOpcode(), DL: SDLoc(N), VT: ResVT, Operand: Conv);
2968}
2969
2970static SDValue
2971performVectorNonNegToFPCombine(SDNode *N,
2972 TargetLowering::DAGCombinerInfo &DCI) {
2973 auto &DAG = DCI.DAG;
2974
2975 SDNodeFlags Flags = N->getFlags();
2976 SDValue Op0 = N->getOperand(Num: 0);
2977 EVT VT = N->getValueType(ResNo: 0);
2978
2979 // Optimize uitofp to sitofp when the sign bit is known to be zero.
2980 // Depending on the target (runtime) backend, this might be performance
2981 // neutral (e.g. AArch64) or a significant improvement (e.g. x86_64).
2982 if (VT.isVector() && (Flags.hasNonNeg() || DAG.SignBitIsZero(Op: Op0))) {
2983 return DAG.getNode(Opcode: ISD::SINT_TO_FP, DL: SDLoc(N), VT, Operand: Op0);
2984 }
2985
2986 return SDValue();
2987}
2988
2989static SDValue
2990performVectorExtendCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
2991 auto &DAG = DCI.DAG;
2992 assert(N->getOpcode() == ISD::SIGN_EXTEND ||
2993 N->getOpcode() == ISD::ZERO_EXTEND);
2994
2995 // Combine ({s,z}ext (extract_subvector src, i)) into a widening operation if
2996 // possible before the extract_subvector can be expanded.
2997 auto Extract = N->getOperand(Num: 0);
2998 if (Extract.getOpcode() != ISD::EXTRACT_SUBVECTOR)
2999 return SDValue();
3000 auto Source = Extract.getOperand(i: 0);
3001 auto *IndexNode = dyn_cast<ConstantSDNode>(Val: Extract.getOperand(i: 1));
3002 if (IndexNode == nullptr)
3003 return SDValue();
3004 auto Index = IndexNode->getZExtValue();
3005
3006 // Only v8i8, v4i16, and v2i32 extracts can be widened, and only if the
3007 // extracted subvector is the low or high half of its source.
3008 EVT ResVT = N->getValueType(ResNo: 0);
3009 if (ResVT == MVT::v8i16) {
3010 if (Extract.getValueType() != MVT::v8i8 ||
3011 Source.getValueType() != MVT::v16i8 || (Index != 0 && Index != 8))
3012 return SDValue();
3013 } else if (ResVT == MVT::v4i32) {
3014 if (Extract.getValueType() != MVT::v4i16 ||
3015 Source.getValueType() != MVT::v8i16 || (Index != 0 && Index != 4))
3016 return SDValue();
3017 } else if (ResVT == MVT::v2i64) {
3018 if (Extract.getValueType() != MVT::v2i32 ||
3019 Source.getValueType() != MVT::v4i32 || (Index != 0 && Index != 2))
3020 return SDValue();
3021 } else {
3022 return SDValue();
3023 }
3024
3025 bool IsSext = N->getOpcode() == ISD::SIGN_EXTEND;
3026 bool IsLow = Index == 0;
3027
3028 unsigned Op = IsSext ? (IsLow ? WebAssemblyISD::EXTEND_LOW_S
3029 : WebAssemblyISD::EXTEND_HIGH_S)
3030 : (IsLow ? WebAssemblyISD::EXTEND_LOW_U
3031 : WebAssemblyISD::EXTEND_HIGH_U);
3032
3033 return DAG.getNode(Opcode: Op, DL: SDLoc(N), VT: ResVT, Operand: Source);
3034}
3035
3036static SDValue
3037performVectorTruncZeroCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
3038 auto &DAG = DCI.DAG;
3039
3040 auto GetWasmConversionOp = [](unsigned Op) {
3041 switch (Op) {
3042 case ISD::FP_TO_SINT_SAT:
3043 return WebAssemblyISD::TRUNC_SAT_ZERO_S;
3044 case ISD::FP_TO_UINT_SAT:
3045 return WebAssemblyISD::TRUNC_SAT_ZERO_U;
3046 case ISD::FP_ROUND:
3047 return WebAssemblyISD::DEMOTE_ZERO;
3048 }
3049 llvm_unreachable("unexpected op");
3050 };
3051
3052 auto IsZeroSplat = [](SDValue SplatVal) {
3053 auto *Splat = dyn_cast<BuildVectorSDNode>(Val: SplatVal.getNode());
3054 APInt SplatValue, SplatUndef;
3055 unsigned SplatBitSize;
3056 bool HasAnyUndefs;
3057 // Endianness doesn't matter in this context because we are looking for
3058 // an all-zero value.
3059 return Splat &&
3060 Splat->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
3061 HasAnyUndefs) &&
3062 SplatValue == 0;
3063 };
3064
3065 if (N->getOpcode() == ISD::CONCAT_VECTORS) {
3066 // Combine this:
3067 //
3068 // (concat_vectors (v2i32 (fp_to_{s,u}int_sat $x, 32)), (v2i32 (splat 0)))
3069 //
3070 // into (i32x4.trunc_sat_f64x2_zero_{s,u} $x).
3071 //
3072 // Or this:
3073 //
3074 // (concat_vectors (v2f32 (fp_round (v2f64 $x))), (v2f32 (splat 0)))
3075 //
3076 // into (f32x4.demote_zero_f64x2 $x).
3077 EVT ResVT;
3078 EVT ExpectedConversionType;
3079 auto Conversion = N->getOperand(Num: 0);
3080 auto ConversionOp = Conversion.getOpcode();
3081 switch (ConversionOp) {
3082 case ISD::FP_TO_SINT_SAT:
3083 case ISD::FP_TO_UINT_SAT:
3084 ResVT = MVT::v4i32;
3085 ExpectedConversionType = MVT::v2i32;
3086 break;
3087 case ISD::FP_ROUND:
3088 ResVT = MVT::v4f32;
3089 ExpectedConversionType = MVT::v2f32;
3090 break;
3091 default:
3092 return SDValue();
3093 }
3094
3095 if (N->getValueType(ResNo: 0) != ResVT)
3096 return SDValue();
3097
3098 if (Conversion.getValueType() != ExpectedConversionType)
3099 return SDValue();
3100
3101 auto Source = Conversion.getOperand(i: 0);
3102 if (Source.getValueType() != MVT::v2f64)
3103 return SDValue();
3104
3105 if (!IsZeroSplat(N->getOperand(Num: 1)) ||
3106 N->getOperand(Num: 1).getValueType() != ExpectedConversionType)
3107 return SDValue();
3108
3109 unsigned Op = GetWasmConversionOp(ConversionOp);
3110 return DAG.getNode(Opcode: Op, DL: SDLoc(N), VT: ResVT, Operand: Source);
3111 }
3112
3113 // Combine this:
3114 //
3115 // (fp_to_{s,u}int_sat (concat_vectors $x, (v2f64 (splat 0))), 32)
3116 //
3117 // into (i32x4.trunc_sat_f64x2_zero_{s,u} $x).
3118 //
3119 // Or this:
3120 //
3121 // (v4f32 (fp_round (concat_vectors $x, (v2f64 (splat 0)))))
3122 //
3123 // into (f32x4.demote_zero_f64x2 $x).
3124 EVT ResVT;
3125 auto ConversionOp = N->getOpcode();
3126 switch (ConversionOp) {
3127 case ISD::FP_TO_SINT_SAT:
3128 case ISD::FP_TO_UINT_SAT:
3129 ResVT = MVT::v4i32;
3130 break;
3131 case ISD::FP_ROUND:
3132 ResVT = MVT::v4f32;
3133 break;
3134 default:
3135 llvm_unreachable("unexpected op");
3136 }
3137
3138 if (N->getValueType(ResNo: 0) != ResVT)
3139 return SDValue();
3140
3141 auto Concat = N->getOperand(Num: 0);
3142 if (Concat.getValueType() != MVT::v4f64)
3143 return SDValue();
3144
3145 auto Source = Concat.getOperand(i: 0);
3146 if (Source.getValueType() != MVT::v2f64)
3147 return SDValue();
3148
3149 if (!IsZeroSplat(Concat.getOperand(i: 1)) ||
3150 Concat.getOperand(i: 1).getValueType() != MVT::v2f64)
3151 return SDValue();
3152
3153 unsigned Op = GetWasmConversionOp(ConversionOp);
3154 return DAG.getNode(Opcode: Op, DL: SDLoc(N), VT: ResVT, Operand: Source);
3155}
3156
3157// Helper to extract VectorWidth bits from Vec, starting from IdxVal.
3158static SDValue extractSubVector(SDValue Vec, unsigned IdxVal, SelectionDAG &DAG,
3159 const SDLoc &DL, unsigned VectorWidth) {
3160 EVT VT = Vec.getValueType();
3161 EVT ElVT = VT.getVectorElementType();
3162 unsigned Factor = VT.getSizeInBits() / VectorWidth;
3163 EVT ResultVT = EVT::getVectorVT(Context&: *DAG.getContext(), VT: ElVT,
3164 NumElements: VT.getVectorNumElements() / Factor);
3165
3166 // Extract the relevant VectorWidth bits. Generate an EXTRACT_SUBVECTOR
3167 unsigned ElemsPerChunk = VectorWidth / ElVT.getSizeInBits();
3168 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
3169
3170 // This is the index of the first element of the VectorWidth-bit chunk
3171 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
3172 IdxVal &= ~(ElemsPerChunk - 1);
3173
3174 // If the input is a buildvector just emit a smaller one.
3175 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
3176 return DAG.getBuildVector(VT: ResultVT, DL,
3177 Ops: Vec->ops().slice(N: IdxVal, M: ElemsPerChunk));
3178
3179 SDValue VecIdx = DAG.getIntPtrConstant(Val: IdxVal, DL);
3180 return DAG.getNode(Opcode: ISD::EXTRACT_SUBVECTOR, DL, VT: ResultVT, N1: Vec, N2: VecIdx);
3181}
3182
3183// Helper to recursively truncate vector elements in half with NARROW_U. DstVT
3184// is the expected destination value type after recursion. In is the initial
3185// input. Note that the input should have enough leading zero bits to prevent
3186// NARROW_U from saturating results.
3187static SDValue truncateVectorWithNARROW(EVT DstVT, SDValue In, const SDLoc &DL,
3188 SelectionDAG &DAG) {
3189 EVT SrcVT = In.getValueType();
3190
3191 // No truncation required, we might get here due to recursive calls.
3192 if (SrcVT == DstVT)
3193 return In;
3194
3195 unsigned SrcSizeInBits = SrcVT.getSizeInBits();
3196 unsigned NumElems = SrcVT.getVectorNumElements();
3197 if (!isPowerOf2_32(Value: NumElems))
3198 return SDValue();
3199 assert(DstVT.getVectorNumElements() == NumElems && "Illegal truncation");
3200 assert(SrcSizeInBits > DstVT.getSizeInBits() && "Illegal truncation");
3201
3202 LLVMContext &Ctx = *DAG.getContext();
3203 EVT PackedSVT = EVT::getIntegerVT(Context&: Ctx, BitWidth: SrcVT.getScalarSizeInBits() / 2);
3204
3205 // Narrow to the largest type possible:
3206 // vXi64/vXi32 -> i16x8.narrow_i32x4_u and vXi16 -> i8x16.narrow_i16x8_u.
3207 EVT InVT = MVT::i16, OutVT = MVT::i8;
3208 if (SrcVT.getScalarSizeInBits() > 16) {
3209 InVT = MVT::i32;
3210 OutVT = MVT::i16;
3211 }
3212 unsigned SubSizeInBits = SrcSizeInBits / 2;
3213 InVT = EVT::getVectorVT(Context&: Ctx, VT: InVT, NumElements: SubSizeInBits / InVT.getSizeInBits());
3214 OutVT = EVT::getVectorVT(Context&: Ctx, VT: OutVT, NumElements: SubSizeInBits / OutVT.getSizeInBits());
3215
3216 // Split lower/upper subvectors.
3217 SDValue Lo = extractSubVector(Vec: In, IdxVal: 0, DAG, DL, VectorWidth: SubSizeInBits);
3218 SDValue Hi = extractSubVector(Vec: In, IdxVal: NumElems / 2, DAG, DL, VectorWidth: SubSizeInBits);
3219
3220 // 256bit -> 128bit truncate - Narrow lower/upper 128-bit subvectors.
3221 if (SrcVT.is256BitVector() && DstVT.is128BitVector()) {
3222 Lo = DAG.getBitcast(VT: InVT, V: Lo);
3223 Hi = DAG.getBitcast(VT: InVT, V: Hi);
3224 SDValue Res = DAG.getNode(Opcode: WebAssemblyISD::NARROW_U, DL, VT: OutVT, N1: Lo, N2: Hi);
3225 return DAG.getBitcast(VT: DstVT, V: Res);
3226 }
3227
3228 // Recursively narrow lower/upper subvectors, concat result and narrow again.
3229 EVT PackedVT = EVT::getVectorVT(Context&: Ctx, VT: PackedSVT, NumElements: NumElems / 2);
3230 Lo = truncateVectorWithNARROW(DstVT: PackedVT, In: Lo, DL, DAG);
3231 Hi = truncateVectorWithNARROW(DstVT: PackedVT, In: Hi, DL, DAG);
3232
3233 PackedVT = EVT::getVectorVT(Context&: Ctx, VT: PackedSVT, NumElements: NumElems);
3234 SDValue Res = DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT: PackedVT, N1: Lo, N2: Hi);
3235 return truncateVectorWithNARROW(DstVT, In: Res, DL, DAG);
3236}
3237
3238static SDValue performTruncateCombine(SDNode *N,
3239 TargetLowering::DAGCombinerInfo &DCI) {
3240 auto &DAG = DCI.DAG;
3241
3242 SDValue In = N->getOperand(Num: 0);
3243 EVT InVT = In.getValueType();
3244 if (!InVT.isSimple())
3245 return SDValue();
3246
3247 EVT OutVT = N->getValueType(ResNo: 0);
3248 if (!OutVT.isVector())
3249 return SDValue();
3250
3251 EVT OutSVT = OutVT.getVectorElementType();
3252 EVT InSVT = InVT.getVectorElementType();
3253 // Currently only cover truncate to v16i8 or v8i16.
3254 if (!((InSVT == MVT::i16 || InSVT == MVT::i32 || InSVT == MVT::i64) &&
3255 (OutSVT == MVT::i8 || OutSVT == MVT::i16) && OutVT.is128BitVector()))
3256 return SDValue();
3257
3258 SDLoc DL(N);
3259 APInt Mask = APInt::getLowBitsSet(numBits: InVT.getScalarSizeInBits(),
3260 loBitsSet: OutVT.getScalarSizeInBits());
3261 In = DAG.getNode(Opcode: ISD::AND, DL, VT: InVT, N1: In, N2: DAG.getConstant(Val: Mask, DL, VT: InVT));
3262 return truncateVectorWithNARROW(DstVT: OutVT, In, DL, DAG);
3263}
3264
3265static SDValue performBitcastCombine(SDNode *N,
3266 TargetLowering::DAGCombinerInfo &DCI) {
3267 using namespace llvm::SDPatternMatch;
3268 auto &DAG = DCI.DAG;
3269 SDLoc DL(N);
3270 SDValue Src = N->getOperand(Num: 0);
3271 EVT VT = N->getValueType(ResNo: 0);
3272 EVT SrcVT = Src.getValueType();
3273
3274 if (!(DCI.isBeforeLegalize() && VT.isScalarInteger() &&
3275 SrcVT.isFixedLengthVector() && SrcVT.getScalarType() == MVT::i1))
3276 return SDValue();
3277
3278 unsigned NumElts = SrcVT.getVectorNumElements();
3279 EVT Width = MVT::getIntegerVT(BitWidth: 128 / NumElts);
3280
3281 // bitcast <N x i1> to iN, where N = 2, 4, 8, 16 (legal)
3282 // ==> bitmask
3283 if (NumElts == 2 || NumElts == 4 || NumElts == 8 || NumElts == 16) {
3284 return DAG.getZExtOrTrunc(
3285 Op: DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL, VT: MVT::i32,
3286 Ops: {DAG.getConstant(Val: Intrinsic::wasm_bitmask, DL, VT: MVT::i32),
3287 DAG.getSExtOrTrunc(Op: N->getOperand(Num: 0), DL,
3288 VT: SrcVT.changeVectorElementType(
3289 Context&: *DAG.getContext(), EltVT: Width))}),
3290 DL, VT);
3291 }
3292
3293 // bitcast <N x i1>(setcc ...) to concat iN, where N = 32 and 64 (illegal)
3294 if (NumElts == 32 || NumElts == 64) {
3295 // Strategy: We will setcc them separately in v16i8 -> v16i1
3296 // Bitcast them to i16, extend them to either i32 or i64.
3297 // Add them together, shifting left 1 by 1.
3298 SDValue Concat, SetCCVector;
3299 ISD::CondCode SetCond;
3300
3301 if (!sd_match(N, P: m_BitCast(Op: m_c_SetCC(LHS: m_Value(N&: Concat), RHS: m_Value(N&: SetCCVector),
3302 CC: m_CondCode(CC&: SetCond)))))
3303 return SDValue();
3304 if (Concat.getOpcode() != ISD::CONCAT_VECTORS)
3305 return SDValue();
3306
3307 uint64_t ElementWidth =
3308 SetCCVector.getValueType().getVectorElementType().getFixedSizeInBits();
3309
3310 SmallVector<SDValue> VectorsToShuffle;
3311 for (size_t I = 0; I < Concat->ops().size(); I++) {
3312 VectorsToShuffle.push_back(Elt: DAG.getBitcast(
3313 VT: MVT::i16,
3314 V: DAG.getSetCC(DL, VT: MVT::v16i1, LHS: Concat->ops()[I],
3315 RHS: extractSubVector(Vec: SetCCVector, IdxVal: I * (128 / ElementWidth),
3316 DAG, DL, VectorWidth: 128),
3317 Cond: SetCond)));
3318 }
3319
3320 MVT ReturnType = VectorsToShuffle.size() == 2 ? MVT::i32 : MVT::i64;
3321 SDValue ReturningInteger = DAG.getConstant(Val: 0, DL, VT: ReturnType);
3322
3323 for (SDValue V : VectorsToShuffle) {
3324 ReturningInteger = DAG.getNode(
3325 Opcode: ISD::SHL, DL, VT: ReturnType,
3326 Ops: {DAG.getShiftAmountConstant(Val: 16, VT: ReturnType, DL), ReturningInteger});
3327
3328 SDValue ExtendedV = DAG.getZExtOrTrunc(Op: V, DL, VT: ReturnType);
3329 ReturningInteger =
3330 DAG.getNode(Opcode: ISD::ADD, DL, VT: ReturnType, Ops: {ReturningInteger, ExtendedV});
3331 }
3332
3333 return ReturningInteger;
3334 }
3335
3336 return SDValue();
3337}
3338
3339static SDValue performBitmaskCombine(SDNode *N, SelectionDAG &DAG) {
3340 // bitmask (setcc <X>, 0, setlt) => bitmask X
3341 assert(N->getOpcode() == ISD::INTRINSIC_WO_CHAIN);
3342 using namespace llvm::SDPatternMatch;
3343
3344 if (N->getConstantOperandVal(Num: 0) != Intrinsic::wasm_bitmask)
3345 return SDValue();
3346
3347 SDValue LHS;
3348 if (!sd_match(N: N->getOperand(Num: 1), P: m_c_SetCC(LHS: m_Value(N&: LHS), RHS: m_Zero(),
3349 CC: m_SpecificCondCode(CC: ISD::SETLT))))
3350 return SDValue();
3351
3352 SDLoc DL(N);
3353 return DAG.getNode(
3354 Opcode: ISD::INTRINSIC_WO_CHAIN, DL, VT: N->getValueType(ResNo: 0),
3355 Ops: {DAG.getConstant(Val: Intrinsic::wasm_bitmask, DL, VT: MVT::i32), LHS});
3356}
3357
3358static SDValue performAnyAllCombine(SDNode *N, SelectionDAG &DAG) {
3359 // any_true (setcc <X>, 0, eq) => (not (all_true X))
3360 // all_true (setcc <X>, 0, eq) => (not (any_true X))
3361 // any_true (setcc <X>, 0, ne) => (any_true X)
3362 // all_true (setcc <X>, 0, ne) => (all_true X)
3363 assert(N->getOpcode() == ISD::INTRINSIC_WO_CHAIN);
3364 using namespace llvm::SDPatternMatch;
3365
3366 SDValue LHS;
3367 if (N->getNumOperands() < 2 ||
3368 !sd_match(N: N->getOperand(Num: 1),
3369 P: m_c_SetCC(LHS: m_Value(N&: LHS), RHS: m_Zero(), CC: m_CondCode())))
3370 return SDValue();
3371 EVT LT = LHS.getValueType();
3372 if (LT.getScalarSizeInBits() > 128 / LT.getVectorNumElements())
3373 return SDValue();
3374
3375 auto CombineSetCC = [&N, &DAG](Intrinsic::WASMIntrinsics InPre,
3376 ISD::CondCode SetType,
3377 Intrinsic::WASMIntrinsics InPost) {
3378 if (N->getConstantOperandVal(Num: 0) != InPre)
3379 return SDValue();
3380
3381 SDValue LHS;
3382 if (!sd_match(N: N->getOperand(Num: 1), P: m_c_SetCC(LHS: m_Value(N&: LHS), RHS: m_Zero(),
3383 CC: m_SpecificCondCode(CC: SetType))))
3384 return SDValue();
3385
3386 SDLoc DL(N);
3387 SDValue Ret = DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL, VT: MVT::i32,
3388 Ops: {DAG.getConstant(Val: InPost, DL, VT: MVT::i32), LHS});
3389 if (SetType == ISD::SETEQ)
3390 Ret = DAG.getNode(Opcode: ISD::XOR, DL, VT: MVT::i32, N1: Ret,
3391 N2: DAG.getConstant(Val: 1, DL, VT: MVT::i32));
3392 return DAG.getZExtOrTrunc(Op: Ret, DL, VT: N->getValueType(ResNo: 0));
3393 };
3394
3395 if (SDValue AnyTrueEQ = CombineSetCC(Intrinsic::wasm_anytrue, ISD::SETEQ,
3396 Intrinsic::wasm_alltrue))
3397 return AnyTrueEQ;
3398 if (SDValue AllTrueEQ = CombineSetCC(Intrinsic::wasm_alltrue, ISD::SETEQ,
3399 Intrinsic::wasm_anytrue))
3400 return AllTrueEQ;
3401 if (SDValue AnyTrueNE = CombineSetCC(Intrinsic::wasm_anytrue, ISD::SETNE,
3402 Intrinsic::wasm_anytrue))
3403 return AnyTrueNE;
3404 if (SDValue AllTrueNE = CombineSetCC(Intrinsic::wasm_alltrue, ISD::SETNE,
3405 Intrinsic::wasm_alltrue))
3406 return AllTrueNE;
3407
3408 return SDValue();
3409}
3410
3411template <int MatchRHS, ISD::CondCode MatchCond, bool RequiresNegate,
3412 Intrinsic::ID Intrin>
3413static SDValue TryMatchTrue(SDNode *N, EVT VecVT, SelectionDAG &DAG) {
3414 SDValue LHS = N->getOperand(Num: 0);
3415 SDValue RHS = N->getOperand(Num: 1);
3416 SDValue Cond = N->getOperand(Num: 2);
3417 if (MatchCond != cast<CondCodeSDNode>(Val&: Cond)->get())
3418 return SDValue();
3419
3420 if (MatchRHS != cast<ConstantSDNode>(Val&: RHS)->getSExtValue())
3421 return SDValue();
3422
3423 SDLoc DL(N);
3424 SDValue Ret =
3425 DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL, VT: MVT::i32,
3426 Ops: {DAG.getConstant(Val: Intrin, DL, VT: MVT::i32),
3427 DAG.getSExtOrTrunc(Op: LHS->getOperand(Num: 0), DL, VT: VecVT)});
3428 if (RequiresNegate)
3429 Ret = DAG.getNode(Opcode: ISD::XOR, DL, VT: MVT::i32, N1: Ret,
3430 N2: DAG.getConstant(Val: 1, DL, VT: MVT::i32));
3431 return DAG.getZExtOrTrunc(Op: Ret, DL, VT: N->getValueType(ResNo: 0));
3432}
3433
3434/// Try to convert a i128 comparison to a v16i8 comparison before type
3435/// legalization splits it up into chunks
3436static SDValue
3437combineVectorSizedSetCCEquality(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
3438 const WebAssemblySubtarget *Subtarget) {
3439
3440 SDLoc DL(N);
3441 SDValue X = N->getOperand(Num: 0);
3442 SDValue Y = N->getOperand(Num: 1);
3443 EVT VT = N->getValueType(ResNo: 0);
3444 EVT OpVT = X.getValueType();
3445
3446 SelectionDAG &DAG = DCI.DAG;
3447 if (DCI.DAG.getMachineFunction().getFunction().hasFnAttribute(
3448 Kind: Attribute::NoImplicitFloat))
3449 return SDValue();
3450
3451 ISD::CondCode CC = cast<CondCodeSDNode>(Val: N->getOperand(Num: 2))->get();
3452 // We're looking for an oversized integer equality comparison with SIMD
3453 if (!OpVT.isScalarInteger() || !OpVT.isByteSized() || OpVT != MVT::i128 ||
3454 !Subtarget->hasSIMD128() || !isIntEqualitySetCC(Code: CC))
3455 return SDValue();
3456
3457 // Don't perform this combine if constructing the vector will be expensive.
3458 auto IsVectorBitCastCheap = [](SDValue X) {
3459 X = peekThroughBitcasts(V: X);
3460 return isa<ConstantSDNode>(Val: X) || X.getOpcode() == ISD::LOAD;
3461 };
3462
3463 if (!IsVectorBitCastCheap(X) || !IsVectorBitCastCheap(Y))
3464 return SDValue();
3465
3466 SDValue VecX = DAG.getBitcast(VT: MVT::v16i8, V: X);
3467 SDValue VecY = DAG.getBitcast(VT: MVT::v16i8, V: Y);
3468 SDValue Cmp = DAG.getSetCC(DL, VT: MVT::v16i8, LHS: VecX, RHS: VecY, Cond: CC);
3469
3470 SDValue Intr =
3471 DAG.getNode(Opcode: ISD::INTRINSIC_WO_CHAIN, DL, VT: MVT::i32,
3472 Ops: {DAG.getConstant(Val: CC == ISD::SETEQ ? Intrinsic::wasm_alltrue
3473 : Intrinsic::wasm_anytrue,
3474 DL, VT: MVT::i32),
3475 Cmp});
3476
3477 return DAG.getSetCC(DL, VT, LHS: Intr, RHS: DAG.getConstant(Val: 0, DL, VT: MVT::i32),
3478 Cond: ISD::SETNE);
3479}
3480
3481static SDValue performSETCCCombine(SDNode *N,
3482 TargetLowering::DAGCombinerInfo &DCI,
3483 const WebAssemblySubtarget *Subtarget) {
3484 if (!DCI.isBeforeLegalize())
3485 return SDValue();
3486
3487 EVT VT = N->getValueType(ResNo: 0);
3488 if (!VT.isScalarInteger())
3489 return SDValue();
3490
3491 if (SDValue V = combineVectorSizedSetCCEquality(N, DCI, Subtarget))
3492 return V;
3493
3494 SDValue LHS = N->getOperand(Num: 0);
3495 if (LHS->getOpcode() != ISD::BITCAST)
3496 return SDValue();
3497
3498 EVT FromVT = LHS->getOperand(Num: 0).getValueType();
3499 if (!FromVT.isFixedLengthVector() || FromVT.getVectorElementType() != MVT::i1)
3500 return SDValue();
3501
3502 unsigned NumElts = FromVT.getVectorNumElements();
3503 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3504 return SDValue();
3505
3506 if (!cast<ConstantSDNode>(Val: N->getOperand(Num: 1)))
3507 return SDValue();
3508
3509 auto &DAG = DCI.DAG;
3510 EVT VecVT = FromVT.changeVectorElementType(Context&: *DAG.getContext(),
3511 EltVT: MVT::getIntegerVT(BitWidth: 128 / NumElts));
3512 // setcc (iN (bitcast (vNi1 X))), 0, ne
3513 // ==> any_true (vNi1 X)
3514 if (auto Match = TryMatchTrue<0, ISD::SETNE, false, Intrinsic::wasm_anytrue>(
3515 N, VecVT, DAG)) {
3516 return Match;
3517 }
3518 // setcc (iN (bitcast (vNi1 X))), 0, eq
3519 // ==> xor (any_true (vNi1 X)), -1
3520 if (auto Match = TryMatchTrue<0, ISD::SETEQ, true, Intrinsic::wasm_anytrue>(
3521 N, VecVT, DAG)) {
3522 return Match;
3523 }
3524 // setcc (iN (bitcast (vNi1 X))), -1, eq
3525 // ==> all_true (vNi1 X)
3526 if (auto Match = TryMatchTrue<-1, ISD::SETEQ, false, Intrinsic::wasm_alltrue>(
3527 N, VecVT, DAG)) {
3528 return Match;
3529 }
3530 // setcc (iN (bitcast (vNi1 X))), -1, ne
3531 // ==> xor (all_true (vNi1 X)), -1
3532 if (auto Match = TryMatchTrue<-1, ISD::SETNE, true, Intrinsic::wasm_alltrue>(
3533 N, VecVT, DAG)) {
3534 return Match;
3535 }
3536 return SDValue();
3537}
3538
3539static SDValue TryWideExtMulCombine(SDNode *N, SelectionDAG &DAG) {
3540 EVT VT = N->getValueType(ResNo: 0);
3541 if (VT != MVT::v8i32 && VT != MVT::v16i32)
3542 return SDValue();
3543
3544 // Mul with extending inputs.
3545 SDValue LHS = N->getOperand(Num: 0);
3546 SDValue RHS = N->getOperand(Num: 1);
3547 if (LHS.getOpcode() != RHS.getOpcode())
3548 return SDValue();
3549
3550 if (LHS.getOpcode() != ISD::SIGN_EXTEND &&
3551 LHS.getOpcode() != ISD::ZERO_EXTEND)
3552 return SDValue();
3553
3554 if (LHS->getOperand(Num: 0).getValueType() != RHS->getOperand(Num: 0).getValueType())
3555 return SDValue();
3556
3557 EVT FromVT = LHS->getOperand(Num: 0).getValueType();
3558 EVT EltTy = FromVT.getVectorElementType();
3559 if (EltTy != MVT::i8)
3560 return SDValue();
3561
3562 // For an input DAG that looks like this
3563 // %a = input_type
3564 // %b = input_type
3565 // %lhs = extend %a to output_type
3566 // %rhs = extend %b to output_type
3567 // %mul = mul %lhs, %rhs
3568
3569 // input_type | output_type | instructions
3570 // v16i8 | v16i32 | %low = i16x8.extmul_low_i8x16_ %a, %b
3571 // | | %high = i16x8.extmul_high_i8x16_, %a, %b
3572 // | | %low_low = i32x4.ext_low_i16x8_ %low
3573 // | | %low_high = i32x4.ext_high_i16x8_ %low
3574 // | | %high_low = i32x4.ext_low_i16x8_ %high
3575 // | | %high_high = i32x4.ext_high_i16x8_ %high
3576 // | | %res = concat_vector(...)
3577 // v8i8 | v8i32 | %low = i16x8.extmul_low_i8x16_ %a, %b
3578 // | | %low_low = i32x4.ext_low_i16x8_ %low
3579 // | | %low_high = i32x4.ext_high_i16x8_ %low
3580 // | | %res = concat_vector(%low_low, %low_high)
3581
3582 SDLoc DL(N);
3583 unsigned NumElts = VT.getVectorNumElements();
3584 SDValue ExtendInLHS = LHS->getOperand(Num: 0);
3585 SDValue ExtendInRHS = RHS->getOperand(Num: 0);
3586 bool IsSigned = LHS->getOpcode() == ISD::SIGN_EXTEND;
3587 unsigned ExtendLowOpc =
3588 IsSigned ? WebAssemblyISD::EXTEND_LOW_S : WebAssemblyISD::EXTEND_LOW_U;
3589 unsigned ExtendHighOpc =
3590 IsSigned ? WebAssemblyISD::EXTEND_HIGH_S : WebAssemblyISD::EXTEND_HIGH_U;
3591
3592 auto GetExtendLow = [&DAG, &DL, &ExtendLowOpc](EVT VT, SDValue Op) {
3593 return DAG.getNode(Opcode: ExtendLowOpc, DL, VT, Operand: Op);
3594 };
3595 auto GetExtendHigh = [&DAG, &DL, &ExtendHighOpc](EVT VT, SDValue Op) {
3596 return DAG.getNode(Opcode: ExtendHighOpc, DL, VT, Operand: Op);
3597 };
3598
3599 if (NumElts == 16) {
3600 SDValue LowLHS = GetExtendLow(MVT::v8i16, ExtendInLHS);
3601 SDValue LowRHS = GetExtendLow(MVT::v8i16, ExtendInRHS);
3602 SDValue MulLow = DAG.getNode(Opcode: ISD::MUL, DL, VT: MVT::v8i16, N1: LowLHS, N2: LowRHS);
3603 SDValue HighLHS = GetExtendHigh(MVT::v8i16, ExtendInLHS);
3604 SDValue HighRHS = GetExtendHigh(MVT::v8i16, ExtendInRHS);
3605 SDValue MulHigh = DAG.getNode(Opcode: ISD::MUL, DL, VT: MVT::v8i16, N1: HighLHS, N2: HighRHS);
3606 SDValue SubVectors[] = {
3607 GetExtendLow(MVT::v4i32, MulLow),
3608 GetExtendHigh(MVT::v4i32, MulLow),
3609 GetExtendLow(MVT::v4i32, MulHigh),
3610 GetExtendHigh(MVT::v4i32, MulHigh),
3611 };
3612 return DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT, Ops: SubVectors);
3613 } else {
3614 assert(NumElts == 8);
3615 SDValue LowLHS = DAG.getNode(Opcode: LHS->getOpcode(), DL, VT: MVT::v8i16, Operand: ExtendInLHS);
3616 SDValue LowRHS = DAG.getNode(Opcode: RHS->getOpcode(), DL, VT: MVT::v8i16, Operand: ExtendInRHS);
3617 SDValue MulLow = DAG.getNode(Opcode: ISD::MUL, DL, VT: MVT::v8i16, N1: LowLHS, N2: LowRHS);
3618 SDValue Lo = GetExtendLow(MVT::v4i32, MulLow);
3619 SDValue Hi = GetExtendHigh(MVT::v4i32, MulLow);
3620 return DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT, N1: Lo, N2: Hi);
3621 }
3622 return SDValue();
3623}
3624
3625static SDValue performMulCombine(SDNode *N,
3626 TargetLowering::DAGCombinerInfo &DCI) {
3627 assert(N->getOpcode() == ISD::MUL);
3628 EVT VT = N->getValueType(ResNo: 0);
3629 if (!VT.isVector())
3630 return SDValue();
3631
3632 if (auto Res = TryWideExtMulCombine(N, DAG&: DCI.DAG))
3633 return Res;
3634
3635 // We don't natively support v16i8 or v8i8 mul, but we do support v8i16. So,
3636 // extend them to v8i16.
3637 if (VT != MVT::v8i8 && VT != MVT::v16i8)
3638 return SDValue();
3639
3640 SDLoc DL(N);
3641 SelectionDAG &DAG = DCI.DAG;
3642 SDValue LHS = N->getOperand(Num: 0);
3643 SDValue RHS = N->getOperand(Num: 1);
3644 EVT MulVT = MVT::v8i16;
3645
3646 if (VT == MVT::v8i8) {
3647 SDValue PromotedLHS = DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT: MVT::v16i8, N1: LHS,
3648 N2: DAG.getUNDEF(VT: MVT::v8i8));
3649 SDValue PromotedRHS = DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT: MVT::v16i8, N1: RHS,
3650 N2: DAG.getUNDEF(VT: MVT::v8i8));
3651 SDValue LowLHS =
3652 DAG.getNode(Opcode: WebAssemblyISD::EXTEND_LOW_U, DL, VT: MulVT, Operand: PromotedLHS);
3653 SDValue LowRHS =
3654 DAG.getNode(Opcode: WebAssemblyISD::EXTEND_LOW_U, DL, VT: MulVT, Operand: PromotedRHS);
3655 SDValue MulLow = DAG.getBitcast(
3656 VT: MVT::v16i8, V: DAG.getNode(Opcode: ISD::MUL, DL, VT: MulVT, N1: LowLHS, N2: LowRHS));
3657 // Take the low byte of each lane.
3658 SDValue Shuffle = DAG.getVectorShuffle(
3659 VT: MVT::v16i8, dl: DL, N1: MulLow, N2: DAG.getUNDEF(VT: MVT::v16i8),
3660 Mask: {0, 2, 4, 6, 8, 10, 12, 14, -1, -1, -1, -1, -1, -1, -1, -1});
3661 return extractSubVector(Vec: Shuffle, IdxVal: 0, DAG, DL, VectorWidth: 64);
3662 } else {
3663 assert(VT == MVT::v16i8 && "Expected v16i8");
3664 SDValue LowLHS = DAG.getNode(Opcode: WebAssemblyISD::EXTEND_LOW_U, DL, VT: MulVT, Operand: LHS);
3665 SDValue LowRHS = DAG.getNode(Opcode: WebAssemblyISD::EXTEND_LOW_U, DL, VT: MulVT, Operand: RHS);
3666 SDValue HighLHS =
3667 DAG.getNode(Opcode: WebAssemblyISD::EXTEND_HIGH_U, DL, VT: MulVT, Operand: LHS);
3668 SDValue HighRHS =
3669 DAG.getNode(Opcode: WebAssemblyISD::EXTEND_HIGH_U, DL, VT: MulVT, Operand: RHS);
3670
3671 SDValue MulLow =
3672 DAG.getBitcast(VT, V: DAG.getNode(Opcode: ISD::MUL, DL, VT: MulVT, N1: LowLHS, N2: LowRHS));
3673 SDValue MulHigh =
3674 DAG.getBitcast(VT, V: DAG.getNode(Opcode: ISD::MUL, DL, VT: MulVT, N1: HighLHS, N2: HighRHS));
3675
3676 // Take the low byte of each lane.
3677 return DAG.getVectorShuffle(
3678 VT, dl: DL, N1: MulLow, N2: MulHigh,
3679 Mask: {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30});
3680 }
3681}
3682
3683SDValue DoubleVectorWidth(SDValue In, unsigned RequiredNumElems,
3684 SelectionDAG &DAG) {
3685 SDLoc DL(In);
3686 LLVMContext &Ctx = *DAG.getContext();
3687 EVT InVT = In.getValueType();
3688 unsigned NumElems = InVT.getVectorNumElements() * 2;
3689 EVT OutVT = EVT::getVectorVT(Context&: Ctx, VT: InVT.getVectorElementType(), NumElements: NumElems);
3690 SDValue Concat =
3691 DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT: OutVT, N1: In, N2: DAG.getPOISON(VT: InVT));
3692 if (NumElems < RequiredNumElems) {
3693 return DoubleVectorWidth(In: Concat, RequiredNumElems, DAG);
3694 }
3695 return Concat;
3696}
3697
3698SDValue performConvertFPCombine(SDNode *N, SelectionDAG &DAG) {
3699 EVT OutVT = N->getValueType(ResNo: 0);
3700 if (!OutVT.isVector())
3701 return SDValue();
3702
3703 EVT OutElTy = OutVT.getVectorElementType();
3704 if (OutElTy != MVT::i8 && OutElTy != MVT::i16)
3705 return SDValue();
3706
3707 unsigned NumElems = OutVT.getVectorNumElements();
3708 if (!isPowerOf2_32(Value: NumElems))
3709 return SDValue();
3710
3711 EVT FPVT = N->getOperand(Num: 0)->getValueType(ResNo: 0);
3712 if (FPVT.getVectorElementType() != MVT::f32)
3713 return SDValue();
3714
3715 SDLoc DL(N);
3716
3717 // First, convert to i32.
3718 LLVMContext &Ctx = *DAG.getContext();
3719 EVT IntVT = EVT::getVectorVT(Context&: Ctx, VT: MVT::i32, NumElements: NumElems);
3720 SDValue ToInt = DAG.getNode(Opcode: N->getOpcode(), DL, VT: IntVT, Operand: N->getOperand(Num: 0));
3721 APInt Mask = APInt::getLowBitsSet(numBits: IntVT.getScalarSizeInBits(),
3722 loBitsSet: OutVT.getScalarSizeInBits());
3723 // Mask out the top MSBs.
3724 SDValue Masked =
3725 DAG.getNode(Opcode: ISD::AND, DL, VT: IntVT, N1: ToInt, N2: DAG.getConstant(Val: Mask, DL, VT: IntVT));
3726
3727 if (OutVT.getSizeInBits() < 128) {
3728 // Create a wide enough vector that we can use narrow.
3729 EVT NarrowedVT = OutElTy == MVT::i8 ? MVT::v16i8 : MVT::v8i16;
3730 unsigned NumRequiredElems = NarrowedVT.getVectorNumElements();
3731 SDValue WideVector = DoubleVectorWidth(In: Masked, RequiredNumElems: NumRequiredElems, DAG);
3732 SDValue Trunc = truncateVectorWithNARROW(DstVT: NarrowedVT, In: WideVector, DL, DAG);
3733 return DAG.getBitcast(
3734 VT: OutVT, V: extractSubVector(Vec: Trunc, IdxVal: 0, DAG, DL, VectorWidth: OutVT.getSizeInBits()));
3735 } else {
3736 return truncateVectorWithNARROW(DstVT: OutVT, In: Masked, DL, DAG);
3737 }
3738 return SDValue();
3739}
3740
3741// Wide vector shift operations such as v8i32 with sign-extended
3742// operands cause Type Legalizer crashes because the target-specific
3743// extension nodes cannot be directly mapped to the 256-bit size.
3744//
3745// To resolve the crash and optimize performance, we intercept the
3746// illegal v8i32 shift in DAGCombine. We convert the shift amounts
3747// into multipliers and manually split the vector into two v4i32 halves.
3748//
3749// Before: t1: v8i32 = shl (sign_extend v8i16), const_vec
3750// After : t2: v4i32 = mul (ext_low_s v8i16), (ext_low_s narrow_vec)
3751// t3: v4i32 = mul (ext_high_s v8i16), (ext_high_s narrow_vec)
3752// t4: v8i32 = concat_vectors t2, t3
3753static SDValue performShiftCombine(SDNode *N,
3754 TargetLowering::DAGCombinerInfo &DCI) {
3755 SelectionDAG &DAG = DCI.DAG;
3756 assert(N->getOpcode() == ISD::SHL);
3757 EVT VT = N->getValueType(ResNo: 0);
3758 if (VT != MVT::v8i32)
3759 return SDValue();
3760
3761 SDValue LHS = N->getOperand(Num: 0);
3762 SDValue RHS = N->getOperand(Num: 1);
3763 unsigned ExtOpc = LHS.getOpcode();
3764 if (ExtOpc != ISD::SIGN_EXTEND && ExtOpc != ISD::ZERO_EXTEND)
3765 return SDValue();
3766
3767 if (RHS.getOpcode() != ISD::BUILD_VECTOR)
3768 return SDValue();
3769
3770 SDLoc DL(N);
3771 SDValue ExtendIn = LHS.getOperand(i: 0);
3772 EVT FromVT = ExtendIn.getValueType();
3773 if (FromVT != MVT::v8i16)
3774 return SDValue();
3775
3776 unsigned NumElts = VT.getVectorNumElements();
3777 unsigned BitWidth = FromVT.getScalarSizeInBits();
3778 bool IsSigned = (ExtOpc == ISD::SIGN_EXTEND);
3779 unsigned MaxValidShift = IsSigned ? (BitWidth - 1) : BitWidth;
3780 SmallVector<SDValue, 16> MulConsts;
3781 for (unsigned I = 0; I < NumElts; ++I) {
3782 auto *C = dyn_cast<ConstantSDNode>(Val: RHS.getOperand(i: I));
3783 if (!C)
3784 return SDValue();
3785
3786 const APInt &ShiftAmt = C->getAPIntValue();
3787 if (ShiftAmt.uge(RHS: MaxValidShift))
3788 return SDValue();
3789
3790 APInt MulAmt = APInt(BitWidth, 1).shl(ShiftAmt);
3791 MulConsts.push_back(Elt: DAG.getConstant(Val: MulAmt, DL, VT: FromVT.getScalarType(),
3792 /*isTarget=*/false, /*isOpaque=*/true));
3793 }
3794
3795 SDValue NarrowConst = DAG.getBuildVector(VT: FromVT, DL, Ops: MulConsts);
3796 unsigned ExtLowOpc =
3797 IsSigned ? WebAssemblyISD::EXTEND_LOW_S : WebAssemblyISD::EXTEND_LOW_U;
3798 unsigned ExtHighOpc =
3799 IsSigned ? WebAssemblyISD::EXTEND_HIGH_S : WebAssemblyISD::EXTEND_HIGH_U;
3800
3801 EVT HalfVT = MVT::v4i32;
3802 SDValue LHSLo = DAG.getNode(Opcode: ExtLowOpc, DL, VT: HalfVT, Operand: ExtendIn);
3803 SDValue LHSHi = DAG.getNode(Opcode: ExtHighOpc, DL, VT: HalfVT, Operand: ExtendIn);
3804 SDValue RHSLo = DAG.getNode(Opcode: ExtLowOpc, DL, VT: HalfVT, Operand: NarrowConst);
3805 SDValue RHSHi = DAG.getNode(Opcode: ExtHighOpc, DL, VT: HalfVT, Operand: NarrowConst);
3806 SDValue MulLo = DAG.getNode(Opcode: ISD::MUL, DL, VT: HalfVT, N1: LHSLo, N2: RHSLo);
3807 SDValue MulHi = DAG.getNode(Opcode: ISD::MUL, DL, VT: HalfVT, N1: LHSHi, N2: RHSHi);
3808 return DAG.getNode(Opcode: ISD::CONCAT_VECTORS, DL, VT, N1: MulLo, N2: MulHi);
3809}
3810
3811SDValue
3812WebAssemblyTargetLowering::PerformDAGCombine(SDNode *N,
3813 DAGCombinerInfo &DCI) const {
3814 switch (N->getOpcode()) {
3815 default:
3816 return SDValue();
3817 case ISD::BITCAST:
3818 return performBitcastCombine(N, DCI);
3819 case ISD::SETCC:
3820 return performSETCCCombine(N, DCI, Subtarget);
3821 case ISD::VECTOR_SHUFFLE:
3822 return performVECTOR_SHUFFLECombine(N, DCI);
3823 case ISD::SIGN_EXTEND:
3824 case ISD::ZERO_EXTEND:
3825 return performVectorExtendCombine(N, DCI);
3826 case ISD::UINT_TO_FP:
3827 if (auto ExtCombine = performVectorExtendToFPCombine(N, DCI))
3828 return ExtCombine;
3829 return performVectorNonNegToFPCombine(N, DCI);
3830 case ISD::SINT_TO_FP:
3831 return performVectorExtendToFPCombine(N, DCI);
3832 case ISD::FP_TO_SINT_SAT:
3833 case ISD::FP_TO_UINT_SAT:
3834 case ISD::FP_ROUND:
3835 case ISD::CONCAT_VECTORS:
3836 return performVectorTruncZeroCombine(N, DCI);
3837 case ISD::FP_TO_SINT:
3838 case ISD::FP_TO_UINT:
3839 return performConvertFPCombine(N, DAG&: DCI.DAG);
3840 case ISD::TRUNCATE:
3841 return performTruncateCombine(N, DCI);
3842 case ISD::INTRINSIC_WO_CHAIN: {
3843 if (SDValue V = performBitmaskCombine(N, DAG&: DCI.DAG))
3844 return V;
3845 return performAnyAllCombine(N, DAG&: DCI.DAG);
3846 }
3847 case ISD::MUL:
3848 return performMulCombine(N, DCI);
3849 case ISD::SHL:
3850 return performShiftCombine(N, DCI);
3851 }
3852}
3853