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/WebAssemblyUtilities.h"
17 #include "WebAssemblyMachineFunctionInfo.h"
18 #include "WebAssemblySubtarget.h"
19 #include "WebAssemblyTargetMachine.h"
20 #include "llvm/CodeGen/CallingConvLower.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineJumpTableInfo.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/SelectionDAG.h"
26 #include "llvm/CodeGen/SelectionDAGNodes.h"
27 #include "llvm/CodeGen/WasmEHFuncInfo.h"
28 #include "llvm/IR/DiagnosticInfo.h"
29 #include "llvm/IR/DiagnosticPrinter.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/IR/IntrinsicsWebAssembly.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetOptions.h"
38 using namespace llvm;
39
40 #define DEBUG_TYPE "wasm-lower"
41
WebAssemblyTargetLowering(const TargetMachine & TM,const WebAssemblySubtarget & STI)42 WebAssemblyTargetLowering::WebAssemblyTargetLowering(
43 const TargetMachine &TM, const WebAssemblySubtarget &STI)
44 : TargetLowering(TM), Subtarget(&STI) {
45 auto MVTPtr = Subtarget->hasAddr64() ? MVT::i64 : MVT::i32;
46
47 // Booleans always contain 0 or 1.
48 setBooleanContents(ZeroOrOneBooleanContent);
49 // Except in SIMD vectors
50 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
51 // We don't know the microarchitecture here, so just reduce register pressure.
52 setSchedulingPreference(Sched::RegPressure);
53 // Tell ISel that we have a stack pointer.
54 setStackPointerRegisterToSaveRestore(
55 Subtarget->hasAddr64() ? WebAssembly::SP64 : WebAssembly::SP32);
56 // Set up the register classes.
57 addRegisterClass(MVT::i32, &WebAssembly::I32RegClass);
58 addRegisterClass(MVT::i64, &WebAssembly::I64RegClass);
59 addRegisterClass(MVT::f32, &WebAssembly::F32RegClass);
60 addRegisterClass(MVT::f64, &WebAssembly::F64RegClass);
61 if (Subtarget->hasSIMD128()) {
62 addRegisterClass(MVT::v16i8, &WebAssembly::V128RegClass);
63 addRegisterClass(MVT::v8i16, &WebAssembly::V128RegClass);
64 addRegisterClass(MVT::v4i32, &WebAssembly::V128RegClass);
65 addRegisterClass(MVT::v4f32, &WebAssembly::V128RegClass);
66 addRegisterClass(MVT::v2i64, &WebAssembly::V128RegClass);
67 addRegisterClass(MVT::v2f64, &WebAssembly::V128RegClass);
68 }
69 // Compute derived properties from the register classes.
70 computeRegisterProperties(Subtarget->getRegisterInfo());
71
72 // Transform loads and stores to pointers in address space 1 to loads and
73 // stores to WebAssembly global variables, outside linear memory.
74 for (auto T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64}) {
75 setOperationAction(ISD::LOAD, T, Custom);
76 setOperationAction(ISD::STORE, T, Custom);
77 }
78 if (Subtarget->hasSIMD128()) {
79 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
80 MVT::v2f64}) {
81 setOperationAction(ISD::LOAD, T, Custom);
82 setOperationAction(ISD::STORE, T, Custom);
83 }
84 }
85
86 setOperationAction(ISD::GlobalAddress, MVTPtr, Custom);
87 setOperationAction(ISD::GlobalTLSAddress, MVTPtr, Custom);
88 setOperationAction(ISD::ExternalSymbol, MVTPtr, Custom);
89 setOperationAction(ISD::JumpTable, MVTPtr, Custom);
90 setOperationAction(ISD::BlockAddress, MVTPtr, Custom);
91 setOperationAction(ISD::BRIND, MVT::Other, Custom);
92
93 // Take the default expansion for va_arg, va_copy, and va_end. There is no
94 // default action for va_start, so we do that custom.
95 setOperationAction(ISD::VASTART, MVT::Other, Custom);
96 setOperationAction(ISD::VAARG, MVT::Other, Expand);
97 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
98 setOperationAction(ISD::VAEND, MVT::Other, Expand);
99
100 for (auto T : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
101 // Don't expand the floating-point types to constant pools.
102 setOperationAction(ISD::ConstantFP, T, Legal);
103 // Expand floating-point comparisons.
104 for (auto CC : {ISD::SETO, ISD::SETUO, ISD::SETUEQ, ISD::SETONE,
105 ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE})
106 setCondCodeAction(CC, T, Expand);
107 // Expand floating-point library function operators.
108 for (auto Op :
109 {ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FREM, ISD::FMA})
110 setOperationAction(Op, T, Expand);
111 // Note supported floating-point library function operators that otherwise
112 // default to expand.
113 for (auto Op :
114 {ISD::FCEIL, ISD::FFLOOR, ISD::FTRUNC, ISD::FNEARBYINT, ISD::FRINT})
115 setOperationAction(Op, T, Legal);
116 // Support minimum and maximum, which otherwise default to expand.
117 setOperationAction(ISD::FMINIMUM, T, Legal);
118 setOperationAction(ISD::FMAXIMUM, T, Legal);
119 // WebAssembly currently has no builtin f16 support.
120 setOperationAction(ISD::FP16_TO_FP, T, Expand);
121 setOperationAction(ISD::FP_TO_FP16, T, Expand);
122 setLoadExtAction(ISD::EXTLOAD, T, MVT::f16, Expand);
123 setTruncStoreAction(T, MVT::f16, Expand);
124 }
125
126 // Expand unavailable integer operations.
127 for (auto Op :
128 {ISD::BSWAP, ISD::SMUL_LOHI, ISD::UMUL_LOHI, ISD::MULHS, ISD::MULHU,
129 ISD::SDIVREM, ISD::UDIVREM, ISD::SHL_PARTS, ISD::SRA_PARTS,
130 ISD::SRL_PARTS, ISD::ADDC, ISD::ADDE, ISD::SUBC, ISD::SUBE}) {
131 for (auto T : {MVT::i32, MVT::i64})
132 setOperationAction(Op, T, Expand);
133 if (Subtarget->hasSIMD128())
134 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64})
135 setOperationAction(Op, T, Expand);
136 }
137
138 if (Subtarget->hasNontrappingFPToInt())
139 for (auto Op : {ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT})
140 for (auto T : {MVT::i32, MVT::i64})
141 setOperationAction(Op, T, Custom);
142
143 // SIMD-specific configuration
144 if (Subtarget->hasSIMD128()) {
145 // Hoist bitcasts out of shuffles
146 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
147
148 // Combine extends of extract_subvectors into widening ops
149 setTargetDAGCombine(ISD::SIGN_EXTEND);
150 setTargetDAGCombine(ISD::ZERO_EXTEND);
151
152 // Combine int_to_fp of extract_vectors and vice versa into conversions ops
153 setTargetDAGCombine(ISD::SINT_TO_FP);
154 setTargetDAGCombine(ISD::UINT_TO_FP);
155 setTargetDAGCombine(ISD::EXTRACT_SUBVECTOR);
156
157 // Combine concat of {s,u}int_to_fp_sat to i32x4.trunc_sat_f64x2_zero_{s,u}
158 setTargetDAGCombine(ISD::CONCAT_VECTORS);
159
160 // Support saturating add for i8x16 and i16x8
161 for (auto Op : {ISD::SADDSAT, ISD::UADDSAT})
162 for (auto T : {MVT::v16i8, MVT::v8i16})
163 setOperationAction(Op, T, Legal);
164
165 // Support integer abs
166 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64})
167 setOperationAction(ISD::ABS, T, Legal);
168
169 // Custom lower BUILD_VECTORs to minimize number of replace_lanes
170 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
171 MVT::v2f64})
172 setOperationAction(ISD::BUILD_VECTOR, T, Custom);
173
174 // We have custom shuffle lowering to expose the shuffle mask
175 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
176 MVT::v2f64})
177 setOperationAction(ISD::VECTOR_SHUFFLE, T, Custom);
178
179 // Custom lowering since wasm shifts must have a scalar shift amount
180 for (auto Op : {ISD::SHL, ISD::SRA, ISD::SRL})
181 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64})
182 setOperationAction(Op, T, Custom);
183
184 // Custom lower lane accesses to expand out variable indices
185 for (auto Op : {ISD::EXTRACT_VECTOR_ELT, ISD::INSERT_VECTOR_ELT})
186 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
187 MVT::v2f64})
188 setOperationAction(Op, T, Custom);
189
190 // There is no i8x16.mul instruction
191 setOperationAction(ISD::MUL, MVT::v16i8, Expand);
192
193 // There is no vector conditional select instruction
194 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64,
195 MVT::v2f64})
196 setOperationAction(ISD::SELECT_CC, T, Expand);
197
198 // Expand integer operations supported for scalars but not SIMD
199 for (auto Op : {ISD::CTLZ, ISD::CTTZ, ISD::CTPOP, ISD::SDIV, ISD::UDIV,
200 ISD::SREM, ISD::UREM, ISD::ROTL, ISD::ROTR})
201 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64})
202 setOperationAction(Op, T, Expand);
203
204 // But we do have integer min and max operations
205 for (auto Op : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
206 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
207 setOperationAction(Op, T, Legal);
208
209 // Expand float operations supported for scalars but not SIMD
210 for (auto Op : {ISD::FCOPYSIGN, ISD::FLOG, ISD::FLOG2, ISD::FLOG10,
211 ISD::FEXP, ISD::FEXP2, ISD::FRINT})
212 for (auto T : {MVT::v4f32, MVT::v2f64})
213 setOperationAction(Op, T, Expand);
214
215 // Unsigned comparison operations are unavailable for i64x2 vectors.
216 for (auto CC : {ISD::SETUGT, ISD::SETUGE, ISD::SETULT, ISD::SETULE})
217 setCondCodeAction(CC, MVT::v2i64, Custom);
218
219 // 64x2 conversions are not in the spec
220 for (auto Op :
221 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT})
222 for (auto T : {MVT::v2i64, MVT::v2f64})
223 setOperationAction(Op, T, Expand);
224
225 // But saturating fp_to_int converstions are
226 for (auto Op : {ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT})
227 setOperationAction(Op, MVT::v4i32, Custom);
228 }
229
230 // As a special case, these operators use the type to mean the type to
231 // sign-extend from.
232 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
233 if (!Subtarget->hasSignExt()) {
234 // Sign extends are legal only when extending a vector extract
235 auto Action = Subtarget->hasSIMD128() ? Custom : Expand;
236 for (auto T : {MVT::i8, MVT::i16, MVT::i32})
237 setOperationAction(ISD::SIGN_EXTEND_INREG, T, Action);
238 }
239 for (auto T : MVT::integer_fixedlen_vector_valuetypes())
240 setOperationAction(ISD::SIGN_EXTEND_INREG, T, Expand);
241
242 // Dynamic stack allocation: use the default expansion.
243 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
244 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
245 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVTPtr, Expand);
246
247 setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
248 setOperationAction(ISD::FrameIndex, MVT::i64, Custom);
249 setOperationAction(ISD::CopyToReg, MVT::Other, Custom);
250
251 // Expand these forms; we pattern-match the forms that we can handle in isel.
252 for (auto T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64})
253 for (auto Op : {ISD::BR_CC, ISD::SELECT_CC})
254 setOperationAction(Op, T, Expand);
255
256 // We have custom switch handling.
257 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
258
259 // WebAssembly doesn't have:
260 // - Floating-point extending loads.
261 // - Floating-point truncating stores.
262 // - i1 extending loads.
263 // - truncating SIMD stores and most extending loads
264 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
265 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
266 for (auto T : MVT::integer_valuetypes())
267 for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD})
268 setLoadExtAction(Ext, T, MVT::i1, Promote);
269 if (Subtarget->hasSIMD128()) {
270 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64, MVT::v4f32,
271 MVT::v2f64}) {
272 for (auto MemT : MVT::fixedlen_vector_valuetypes()) {
273 if (MVT(T) != MemT) {
274 setTruncStoreAction(T, MemT, Expand);
275 for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD})
276 setLoadExtAction(Ext, T, MemT, Expand);
277 }
278 }
279 }
280 // But some vector extending loads are legal
281 for (auto Ext : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) {
282 setLoadExtAction(Ext, MVT::v8i16, MVT::v8i8, Legal);
283 setLoadExtAction(Ext, MVT::v4i32, MVT::v4i16, Legal);
284 setLoadExtAction(Ext, MVT::v2i64, MVT::v2i32, Legal);
285 }
286 // And some truncating stores are legal as well
287 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
288 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
289 }
290
291 // Don't do anything clever with build_pairs
292 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
293
294 // Trap lowers to wasm unreachable
295 setOperationAction(ISD::TRAP, MVT::Other, Legal);
296 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
297
298 // Exception handling intrinsics
299 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
300 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
301 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
302
303 setMaxAtomicSizeInBitsSupported(64);
304
305 // Override the __gnu_f2h_ieee/__gnu_h2f_ieee names so that the f32 name is
306 // consistent with the f64 and f128 names.
307 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
308 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
309
310 // Define the emscripten name for return address helper.
311 // TODO: when implementing other Wasm backends, make this generic or only do
312 // this on emscripten depending on what they end up doing.
313 setLibcallName(RTLIB::RETURN_ADDRESS, "emscripten_return_address");
314
315 // Always convert switches to br_tables unless there is only one case, which
316 // is equivalent to a simple branch. This reduces code size for wasm, and we
317 // defer possible jump table optimizations to the VM.
318 setMinimumJumpTableEntries(2);
319 }
320
321 TargetLowering::AtomicExpansionKind
shouldExpandAtomicRMWInIR(AtomicRMWInst * AI) const322 WebAssemblyTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
323 // We have wasm instructions for these
324 switch (AI->getOperation()) {
325 case AtomicRMWInst::Add:
326 case AtomicRMWInst::Sub:
327 case AtomicRMWInst::And:
328 case AtomicRMWInst::Or:
329 case AtomicRMWInst::Xor:
330 case AtomicRMWInst::Xchg:
331 return AtomicExpansionKind::None;
332 default:
333 break;
334 }
335 return AtomicExpansionKind::CmpXChg;
336 }
337
createFastISel(FunctionLoweringInfo & FuncInfo,const TargetLibraryInfo * LibInfo) const338 FastISel *WebAssemblyTargetLowering::createFastISel(
339 FunctionLoweringInfo &FuncInfo, const TargetLibraryInfo *LibInfo) const {
340 return WebAssembly::createFastISel(FuncInfo, LibInfo);
341 }
342
getScalarShiftAmountTy(const DataLayout &,EVT VT) const343 MVT WebAssemblyTargetLowering::getScalarShiftAmountTy(const DataLayout & /*DL*/,
344 EVT VT) const {
345 unsigned BitWidth = NextPowerOf2(VT.getSizeInBits() - 1);
346 if (BitWidth > 1 && BitWidth < 8)
347 BitWidth = 8;
348
349 if (BitWidth > 64) {
350 // The shift will be lowered to a libcall, and compiler-rt libcalls expect
351 // the count to be an i32.
352 BitWidth = 32;
353 assert(BitWidth >= Log2_32_Ceil(VT.getSizeInBits()) &&
354 "32-bit shift counts ought to be enough for anyone");
355 }
356
357 MVT Result = MVT::getIntegerVT(BitWidth);
358 assert(Result != MVT::INVALID_SIMPLE_VALUE_TYPE &&
359 "Unable to represent scalar shift amount type");
360 return Result;
361 }
362
363 // Lower an fp-to-int conversion operator from the LLVM opcode, which has an
364 // undefined result on invalid/overflow, to the WebAssembly opcode, which
365 // traps on invalid/overflow.
LowerFPToInt(MachineInstr & MI,DebugLoc DL,MachineBasicBlock * BB,const TargetInstrInfo & TII,bool IsUnsigned,bool Int64,bool Float64,unsigned LoweredOpcode)366 static MachineBasicBlock *LowerFPToInt(MachineInstr &MI, DebugLoc DL,
367 MachineBasicBlock *BB,
368 const TargetInstrInfo &TII,
369 bool IsUnsigned, bool Int64,
370 bool Float64, unsigned LoweredOpcode) {
371 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
372
373 Register OutReg = MI.getOperand(0).getReg();
374 Register InReg = MI.getOperand(1).getReg();
375
376 unsigned Abs = Float64 ? WebAssembly::ABS_F64 : WebAssembly::ABS_F32;
377 unsigned FConst = Float64 ? WebAssembly::CONST_F64 : WebAssembly::CONST_F32;
378 unsigned LT = Float64 ? WebAssembly::LT_F64 : WebAssembly::LT_F32;
379 unsigned GE = Float64 ? WebAssembly::GE_F64 : WebAssembly::GE_F32;
380 unsigned IConst = Int64 ? WebAssembly::CONST_I64 : WebAssembly::CONST_I32;
381 unsigned Eqz = WebAssembly::EQZ_I32;
382 unsigned And = WebAssembly::AND_I32;
383 int64_t Limit = Int64 ? INT64_MIN : INT32_MIN;
384 int64_t Substitute = IsUnsigned ? 0 : Limit;
385 double CmpVal = IsUnsigned ? -(double)Limit * 2.0 : -(double)Limit;
386 auto &Context = BB->getParent()->getFunction().getContext();
387 Type *Ty = Float64 ? Type::getDoubleTy(Context) : Type::getFloatTy(Context);
388
389 const BasicBlock *LLVMBB = BB->getBasicBlock();
390 MachineFunction *F = BB->getParent();
391 MachineBasicBlock *TrueMBB = F->CreateMachineBasicBlock(LLVMBB);
392 MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(LLVMBB);
393 MachineBasicBlock *DoneMBB = F->CreateMachineBasicBlock(LLVMBB);
394
395 MachineFunction::iterator It = ++BB->getIterator();
396 F->insert(It, FalseMBB);
397 F->insert(It, TrueMBB);
398 F->insert(It, DoneMBB);
399
400 // Transfer the remainder of BB and its successor edges to DoneMBB.
401 DoneMBB->splice(DoneMBB->begin(), BB, std::next(MI.getIterator()), BB->end());
402 DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
403
404 BB->addSuccessor(TrueMBB);
405 BB->addSuccessor(FalseMBB);
406 TrueMBB->addSuccessor(DoneMBB);
407 FalseMBB->addSuccessor(DoneMBB);
408
409 unsigned Tmp0, Tmp1, CmpReg, EqzReg, FalseReg, TrueReg;
410 Tmp0 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
411 Tmp1 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
412 CmpReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
413 EqzReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
414 FalseReg = MRI.createVirtualRegister(MRI.getRegClass(OutReg));
415 TrueReg = MRI.createVirtualRegister(MRI.getRegClass(OutReg));
416
417 MI.eraseFromParent();
418 // For signed numbers, we can do a single comparison to determine whether
419 // fabs(x) is within range.
420 if (IsUnsigned) {
421 Tmp0 = InReg;
422 } else {
423 BuildMI(BB, DL, TII.get(Abs), Tmp0).addReg(InReg);
424 }
425 BuildMI(BB, DL, TII.get(FConst), Tmp1)
426 .addFPImm(cast<ConstantFP>(ConstantFP::get(Ty, CmpVal)));
427 BuildMI(BB, DL, TII.get(LT), CmpReg).addReg(Tmp0).addReg(Tmp1);
428
429 // For unsigned numbers, we have to do a separate comparison with zero.
430 if (IsUnsigned) {
431 Tmp1 = MRI.createVirtualRegister(MRI.getRegClass(InReg));
432 Register SecondCmpReg =
433 MRI.createVirtualRegister(&WebAssembly::I32RegClass);
434 Register AndReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
435 BuildMI(BB, DL, TII.get(FConst), Tmp1)
436 .addFPImm(cast<ConstantFP>(ConstantFP::get(Ty, 0.0)));
437 BuildMI(BB, DL, TII.get(GE), SecondCmpReg).addReg(Tmp0).addReg(Tmp1);
438 BuildMI(BB, DL, TII.get(And), AndReg).addReg(CmpReg).addReg(SecondCmpReg);
439 CmpReg = AndReg;
440 }
441
442 BuildMI(BB, DL, TII.get(Eqz), EqzReg).addReg(CmpReg);
443
444 // Create the CFG diamond to select between doing the conversion or using
445 // the substitute value.
446 BuildMI(BB, DL, TII.get(WebAssembly::BR_IF)).addMBB(TrueMBB).addReg(EqzReg);
447 BuildMI(FalseMBB, DL, TII.get(LoweredOpcode), FalseReg).addReg(InReg);
448 BuildMI(FalseMBB, DL, TII.get(WebAssembly::BR)).addMBB(DoneMBB);
449 BuildMI(TrueMBB, DL, TII.get(IConst), TrueReg).addImm(Substitute);
450 BuildMI(*DoneMBB, DoneMBB->begin(), DL, TII.get(TargetOpcode::PHI), OutReg)
451 .addReg(FalseReg)
452 .addMBB(FalseMBB)
453 .addReg(TrueReg)
454 .addMBB(TrueMBB);
455
456 return DoneMBB;
457 }
458
459 static MachineBasicBlock *
LowerCallResults(MachineInstr & CallResults,DebugLoc DL,MachineBasicBlock * BB,const WebAssemblySubtarget * Subtarget,const TargetInstrInfo & TII)460 LowerCallResults(MachineInstr &CallResults, DebugLoc DL, MachineBasicBlock *BB,
461 const WebAssemblySubtarget *Subtarget,
462 const TargetInstrInfo &TII) {
463 MachineInstr &CallParams = *CallResults.getPrevNode();
464 assert(CallParams.getOpcode() == WebAssembly::CALL_PARAMS);
465 assert(CallResults.getOpcode() == WebAssembly::CALL_RESULTS ||
466 CallResults.getOpcode() == WebAssembly::RET_CALL_RESULTS);
467
468 bool IsIndirect = CallParams.getOperand(0).isReg();
469 bool IsRetCall = CallResults.getOpcode() == WebAssembly::RET_CALL_RESULTS;
470
471 unsigned CallOp;
472 if (IsIndirect && IsRetCall) {
473 CallOp = WebAssembly::RET_CALL_INDIRECT;
474 } else if (IsIndirect) {
475 CallOp = WebAssembly::CALL_INDIRECT;
476 } else if (IsRetCall) {
477 CallOp = WebAssembly::RET_CALL;
478 } else {
479 CallOp = WebAssembly::CALL;
480 }
481
482 MachineFunction &MF = *BB->getParent();
483 const MCInstrDesc &MCID = TII.get(CallOp);
484 MachineInstrBuilder MIB(MF, MF.CreateMachineInstr(MCID, DL));
485
486 // See if we must truncate the function pointer.
487 // CALL_INDIRECT takes an i32, but in wasm64 we represent function pointers
488 // as 64-bit for uniformity with other pointer types.
489 // See also: WebAssemblyFastISel::selectCall
490 if (IsIndirect && MF.getSubtarget<WebAssemblySubtarget>().hasAddr64()) {
491 Register Reg32 =
492 MF.getRegInfo().createVirtualRegister(&WebAssembly::I32RegClass);
493 auto &FnPtr = CallParams.getOperand(0);
494 BuildMI(*BB, CallResults.getIterator(), DL,
495 TII.get(WebAssembly::I32_WRAP_I64), Reg32)
496 .addReg(FnPtr.getReg());
497 FnPtr.setReg(Reg32);
498 }
499
500 // Move the function pointer to the end of the arguments for indirect calls
501 if (IsIndirect) {
502 auto FnPtr = CallParams.getOperand(0);
503 CallParams.RemoveOperand(0);
504 CallParams.addOperand(FnPtr);
505 }
506
507 for (auto Def : CallResults.defs())
508 MIB.add(Def);
509
510 if (IsIndirect) {
511 // Placeholder for the type index.
512 MIB.addImm(0);
513 // The table into which this call_indirect indexes.
514 MCSymbolWasm *Table =
515 WebAssembly::getOrCreateFunctionTableSymbol(MF.getContext(), Subtarget);
516 if (Subtarget->hasReferenceTypes()) {
517 MIB.addSym(Table);
518 } else {
519 // For the MVP there is at most one table whose number is 0, but we can't
520 // write a table symbol or issue relocations. Instead we just ensure the
521 // table is live and write a zero.
522 Table->setNoStrip();
523 MIB.addImm(0);
524 }
525 }
526
527 for (auto Use : CallParams.uses())
528 MIB.add(Use);
529
530 BB->insert(CallResults.getIterator(), MIB);
531 CallParams.eraseFromParent();
532 CallResults.eraseFromParent();
533
534 return BB;
535 }
536
EmitInstrWithCustomInserter(MachineInstr & MI,MachineBasicBlock * BB) const537 MachineBasicBlock *WebAssemblyTargetLowering::EmitInstrWithCustomInserter(
538 MachineInstr &MI, MachineBasicBlock *BB) const {
539 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
540 DebugLoc DL = MI.getDebugLoc();
541
542 switch (MI.getOpcode()) {
543 default:
544 llvm_unreachable("Unexpected instr type to insert");
545 case WebAssembly::FP_TO_SINT_I32_F32:
546 return LowerFPToInt(MI, DL, BB, TII, false, false, false,
547 WebAssembly::I32_TRUNC_S_F32);
548 case WebAssembly::FP_TO_UINT_I32_F32:
549 return LowerFPToInt(MI, DL, BB, TII, true, false, false,
550 WebAssembly::I32_TRUNC_U_F32);
551 case WebAssembly::FP_TO_SINT_I64_F32:
552 return LowerFPToInt(MI, DL, BB, TII, false, true, false,
553 WebAssembly::I64_TRUNC_S_F32);
554 case WebAssembly::FP_TO_UINT_I64_F32:
555 return LowerFPToInt(MI, DL, BB, TII, true, true, false,
556 WebAssembly::I64_TRUNC_U_F32);
557 case WebAssembly::FP_TO_SINT_I32_F64:
558 return LowerFPToInt(MI, DL, BB, TII, false, false, true,
559 WebAssembly::I32_TRUNC_S_F64);
560 case WebAssembly::FP_TO_UINT_I32_F64:
561 return LowerFPToInt(MI, DL, BB, TII, true, false, true,
562 WebAssembly::I32_TRUNC_U_F64);
563 case WebAssembly::FP_TO_SINT_I64_F64:
564 return LowerFPToInt(MI, DL, BB, TII, false, true, true,
565 WebAssembly::I64_TRUNC_S_F64);
566 case WebAssembly::FP_TO_UINT_I64_F64:
567 return LowerFPToInt(MI, DL, BB, TII, true, true, true,
568 WebAssembly::I64_TRUNC_U_F64);
569 case WebAssembly::CALL_RESULTS:
570 case WebAssembly::RET_CALL_RESULTS:
571 return LowerCallResults(MI, DL, BB, Subtarget, TII);
572 }
573 }
574
575 const char *
getTargetNodeName(unsigned Opcode) const576 WebAssemblyTargetLowering::getTargetNodeName(unsigned Opcode) const {
577 switch (static_cast<WebAssemblyISD::NodeType>(Opcode)) {
578 case WebAssemblyISD::FIRST_NUMBER:
579 case WebAssemblyISD::FIRST_MEM_OPCODE:
580 break;
581 #define HANDLE_NODETYPE(NODE) \
582 case WebAssemblyISD::NODE: \
583 return "WebAssemblyISD::" #NODE;
584 #define HANDLE_MEM_NODETYPE(NODE) HANDLE_NODETYPE(NODE)
585 #include "WebAssemblyISD.def"
586 #undef HANDLE_MEM_NODETYPE
587 #undef HANDLE_NODETYPE
588 }
589 return nullptr;
590 }
591
592 std::pair<unsigned, const TargetRegisterClass *>
getRegForInlineAsmConstraint(const TargetRegisterInfo * TRI,StringRef Constraint,MVT VT) const593 WebAssemblyTargetLowering::getRegForInlineAsmConstraint(
594 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
595 // First, see if this is a constraint that directly corresponds to a
596 // WebAssembly register class.
597 if (Constraint.size() == 1) {
598 switch (Constraint[0]) {
599 case 'r':
600 assert(VT != MVT::iPTR && "Pointer MVT not expected here");
601 if (Subtarget->hasSIMD128() && VT.isVector()) {
602 if (VT.getSizeInBits() == 128)
603 return std::make_pair(0U, &WebAssembly::V128RegClass);
604 }
605 if (VT.isInteger() && !VT.isVector()) {
606 if (VT.getSizeInBits() <= 32)
607 return std::make_pair(0U, &WebAssembly::I32RegClass);
608 if (VT.getSizeInBits() <= 64)
609 return std::make_pair(0U, &WebAssembly::I64RegClass);
610 }
611 if (VT.isFloatingPoint() && !VT.isVector()) {
612 switch (VT.getSizeInBits()) {
613 case 32:
614 return std::make_pair(0U, &WebAssembly::F32RegClass);
615 case 64:
616 return std::make_pair(0U, &WebAssembly::F64RegClass);
617 default:
618 break;
619 }
620 }
621 break;
622 default:
623 break;
624 }
625 }
626
627 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
628 }
629
isCheapToSpeculateCttz() const630 bool WebAssemblyTargetLowering::isCheapToSpeculateCttz() const {
631 // Assume ctz is a relatively cheap operation.
632 return true;
633 }
634
isCheapToSpeculateCtlz() const635 bool WebAssemblyTargetLowering::isCheapToSpeculateCtlz() const {
636 // Assume clz is a relatively cheap operation.
637 return true;
638 }
639
isLegalAddressingMode(const DataLayout & DL,const AddrMode & AM,Type * Ty,unsigned AS,Instruction * I) const640 bool WebAssemblyTargetLowering::isLegalAddressingMode(const DataLayout &DL,
641 const AddrMode &AM,
642 Type *Ty, unsigned AS,
643 Instruction *I) const {
644 // WebAssembly offsets are added as unsigned without wrapping. The
645 // isLegalAddressingMode gives us no way to determine if wrapping could be
646 // happening, so we approximate this by accepting only non-negative offsets.
647 if (AM.BaseOffs < 0)
648 return false;
649
650 // WebAssembly has no scale register operands.
651 if (AM.Scale != 0)
652 return false;
653
654 // Everything else is legal.
655 return true;
656 }
657
allowsMisalignedMemoryAccesses(EVT,unsigned,Align,MachineMemOperand::Flags,bool * Fast) const658 bool WebAssemblyTargetLowering::allowsMisalignedMemoryAccesses(
659 EVT /*VT*/, unsigned /*AddrSpace*/, Align /*Align*/,
660 MachineMemOperand::Flags /*Flags*/, bool *Fast) const {
661 // WebAssembly supports unaligned accesses, though it should be declared
662 // with the p2align attribute on loads and stores which do so, and there
663 // may be a performance impact. We tell LLVM they're "fast" because
664 // for the kinds of things that LLVM uses this for (merging adjacent stores
665 // of constants, etc.), WebAssembly implementations will either want the
666 // unaligned access or they'll split anyway.
667 if (Fast)
668 *Fast = true;
669 return true;
670 }
671
isIntDivCheap(EVT VT,AttributeList Attr) const672 bool WebAssemblyTargetLowering::isIntDivCheap(EVT VT,
673 AttributeList Attr) const {
674 // The current thinking is that wasm engines will perform this optimization,
675 // so we can save on code size.
676 return true;
677 }
678
isVectorLoadExtDesirable(SDValue ExtVal) const679 bool WebAssemblyTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
680 EVT ExtT = ExtVal.getValueType();
681 EVT MemT = cast<LoadSDNode>(ExtVal->getOperand(0))->getValueType(0);
682 return (ExtT == MVT::v8i16 && MemT == MVT::v8i8) ||
683 (ExtT == MVT::v4i32 && MemT == MVT::v4i16) ||
684 (ExtT == MVT::v2i64 && MemT == MVT::v2i32);
685 }
686
getSetCCResultType(const DataLayout & DL,LLVMContext & C,EVT VT) const687 EVT WebAssemblyTargetLowering::getSetCCResultType(const DataLayout &DL,
688 LLVMContext &C,
689 EVT VT) const {
690 if (VT.isVector())
691 return VT.changeVectorElementTypeToInteger();
692
693 // So far, all branch instructions in Wasm take an I32 condition.
694 // The default TargetLowering::getSetCCResultType returns the pointer size,
695 // which would be useful to reduce instruction counts when testing
696 // against 64-bit pointers/values if at some point Wasm supports that.
697 return EVT::getIntegerVT(C, 32);
698 }
699
getTgtMemIntrinsic(IntrinsicInfo & Info,const CallInst & I,MachineFunction & MF,unsigned Intrinsic) const700 bool WebAssemblyTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
701 const CallInst &I,
702 MachineFunction &MF,
703 unsigned Intrinsic) const {
704 switch (Intrinsic) {
705 case Intrinsic::wasm_memory_atomic_notify:
706 Info.opc = ISD::INTRINSIC_W_CHAIN;
707 Info.memVT = MVT::i32;
708 Info.ptrVal = I.getArgOperand(0);
709 Info.offset = 0;
710 Info.align = Align(4);
711 // atomic.notify instruction does not really load the memory specified with
712 // this argument, but MachineMemOperand should either be load or store, so
713 // we set this to a load.
714 // FIXME Volatile isn't really correct, but currently all LLVM atomic
715 // instructions are treated as volatiles in the backend, so we should be
716 // consistent. The same applies for wasm_atomic_wait intrinsics too.
717 Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
718 return true;
719 case Intrinsic::wasm_memory_atomic_wait32:
720 Info.opc = ISD::INTRINSIC_W_CHAIN;
721 Info.memVT = MVT::i32;
722 Info.ptrVal = I.getArgOperand(0);
723 Info.offset = 0;
724 Info.align = Align(4);
725 Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
726 return true;
727 case Intrinsic::wasm_memory_atomic_wait64:
728 Info.opc = ISD::INTRINSIC_W_CHAIN;
729 Info.memVT = MVT::i64;
730 Info.ptrVal = I.getArgOperand(0);
731 Info.offset = 0;
732 Info.align = Align(8);
733 Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad;
734 return true;
735 case Intrinsic::wasm_load32_zero:
736 case Intrinsic::wasm_load64_zero:
737 Info.opc = ISD::INTRINSIC_W_CHAIN;
738 Info.memVT = Intrinsic == Intrinsic::wasm_load32_zero ? MVT::i32 : MVT::i64;
739 Info.ptrVal = I.getArgOperand(0);
740 Info.offset = 0;
741 Info.align = Align(1);
742 Info.flags = MachineMemOperand::MOLoad;
743 return true;
744 case Intrinsic::wasm_load8_lane:
745 case Intrinsic::wasm_load16_lane:
746 case Intrinsic::wasm_load32_lane:
747 case Intrinsic::wasm_load64_lane:
748 case Intrinsic::wasm_store8_lane:
749 case Intrinsic::wasm_store16_lane:
750 case Intrinsic::wasm_store32_lane:
751 case Intrinsic::wasm_store64_lane: {
752 MVT MemVT;
753 switch (Intrinsic) {
754 case Intrinsic::wasm_load8_lane:
755 case Intrinsic::wasm_store8_lane:
756 MemVT = MVT::i8;
757 break;
758 case Intrinsic::wasm_load16_lane:
759 case Intrinsic::wasm_store16_lane:
760 MemVT = MVT::i16;
761 break;
762 case Intrinsic::wasm_load32_lane:
763 case Intrinsic::wasm_store32_lane:
764 MemVT = MVT::i32;
765 break;
766 case Intrinsic::wasm_load64_lane:
767 case Intrinsic::wasm_store64_lane:
768 MemVT = MVT::i64;
769 break;
770 default:
771 llvm_unreachable("unexpected intrinsic");
772 }
773 if (Intrinsic == Intrinsic::wasm_load8_lane ||
774 Intrinsic == Intrinsic::wasm_load16_lane ||
775 Intrinsic == Intrinsic::wasm_load32_lane ||
776 Intrinsic == Intrinsic::wasm_load64_lane) {
777 Info.opc = ISD::INTRINSIC_W_CHAIN;
778 Info.flags = MachineMemOperand::MOLoad;
779 } else {
780 Info.opc = ISD::INTRINSIC_VOID;
781 Info.flags = MachineMemOperand::MOStore;
782 }
783 Info.ptrVal = I.getArgOperand(0);
784 Info.memVT = MemVT;
785 Info.offset = 0;
786 Info.align = Align(1);
787 return true;
788 }
789 default:
790 return false;
791 }
792 }
793
794 //===----------------------------------------------------------------------===//
795 // WebAssembly Lowering private implementation.
796 //===----------------------------------------------------------------------===//
797
798 //===----------------------------------------------------------------------===//
799 // Lowering Code
800 //===----------------------------------------------------------------------===//
801
fail(const SDLoc & DL,SelectionDAG & DAG,const char * Msg)802 static void fail(const SDLoc &DL, SelectionDAG &DAG, const char *Msg) {
803 MachineFunction &MF = DAG.getMachineFunction();
804 DAG.getContext()->diagnose(
805 DiagnosticInfoUnsupported(MF.getFunction(), Msg, DL.getDebugLoc()));
806 }
807
808 // Test whether the given calling convention is supported.
callingConvSupported(CallingConv::ID CallConv)809 static bool callingConvSupported(CallingConv::ID CallConv) {
810 // We currently support the language-independent target-independent
811 // conventions. We don't yet have a way to annotate calls with properties like
812 // "cold", and we don't have any call-clobbered registers, so these are mostly
813 // all handled the same.
814 return CallConv == CallingConv::C || CallConv == CallingConv::Fast ||
815 CallConv == CallingConv::Cold ||
816 CallConv == CallingConv::PreserveMost ||
817 CallConv == CallingConv::PreserveAll ||
818 CallConv == CallingConv::CXX_FAST_TLS ||
819 CallConv == CallingConv::WASM_EmscriptenInvoke ||
820 CallConv == CallingConv::Swift;
821 }
822
823 SDValue
LowerCall(CallLoweringInfo & CLI,SmallVectorImpl<SDValue> & InVals) const824 WebAssemblyTargetLowering::LowerCall(CallLoweringInfo &CLI,
825 SmallVectorImpl<SDValue> &InVals) const {
826 SelectionDAG &DAG = CLI.DAG;
827 SDLoc DL = CLI.DL;
828 SDValue Chain = CLI.Chain;
829 SDValue Callee = CLI.Callee;
830 MachineFunction &MF = DAG.getMachineFunction();
831 auto Layout = MF.getDataLayout();
832
833 CallingConv::ID CallConv = CLI.CallConv;
834 if (!callingConvSupported(CallConv))
835 fail(DL, DAG,
836 "WebAssembly doesn't support language-specific or target-specific "
837 "calling conventions yet");
838 if (CLI.IsPatchPoint)
839 fail(DL, DAG, "WebAssembly doesn't support patch point yet");
840
841 if (CLI.IsTailCall) {
842 auto NoTail = [&](const char *Msg) {
843 if (CLI.CB && CLI.CB->isMustTailCall())
844 fail(DL, DAG, Msg);
845 CLI.IsTailCall = false;
846 };
847
848 if (!Subtarget->hasTailCall())
849 NoTail("WebAssembly 'tail-call' feature not enabled");
850
851 // Varargs calls cannot be tail calls because the buffer is on the stack
852 if (CLI.IsVarArg)
853 NoTail("WebAssembly does not support varargs tail calls");
854
855 // Do not tail call unless caller and callee return types match
856 const Function &F = MF.getFunction();
857 const TargetMachine &TM = getTargetMachine();
858 Type *RetTy = F.getReturnType();
859 SmallVector<MVT, 4> CallerRetTys;
860 SmallVector<MVT, 4> CalleeRetTys;
861 computeLegalValueVTs(F, TM, RetTy, CallerRetTys);
862 computeLegalValueVTs(F, TM, CLI.RetTy, CalleeRetTys);
863 bool TypesMatch = CallerRetTys.size() == CalleeRetTys.size() &&
864 std::equal(CallerRetTys.begin(), CallerRetTys.end(),
865 CalleeRetTys.begin());
866 if (!TypesMatch)
867 NoTail("WebAssembly tail call requires caller and callee return types to "
868 "match");
869
870 // If pointers to local stack values are passed, we cannot tail call
871 if (CLI.CB) {
872 for (auto &Arg : CLI.CB->args()) {
873 Value *Val = Arg.get();
874 // Trace the value back through pointer operations
875 while (true) {
876 Value *Src = Val->stripPointerCastsAndAliases();
877 if (auto *GEP = dyn_cast<GetElementPtrInst>(Src))
878 Src = GEP->getPointerOperand();
879 if (Val == Src)
880 break;
881 Val = Src;
882 }
883 if (isa<AllocaInst>(Val)) {
884 NoTail(
885 "WebAssembly does not support tail calling with stack arguments");
886 break;
887 }
888 }
889 }
890 }
891
892 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
893 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
894 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
895
896 // The generic code may have added an sret argument. If we're lowering an
897 // invoke function, the ABI requires that the function pointer be the first
898 // argument, so we may have to swap the arguments.
899 if (CallConv == CallingConv::WASM_EmscriptenInvoke && Outs.size() >= 2 &&
900 Outs[0].Flags.isSRet()) {
901 std::swap(Outs[0], Outs[1]);
902 std::swap(OutVals[0], OutVals[1]);
903 }
904
905 bool HasSwiftSelfArg = false;
906 bool HasSwiftErrorArg = false;
907 unsigned NumFixedArgs = 0;
908 for (unsigned I = 0; I < Outs.size(); ++I) {
909 const ISD::OutputArg &Out = Outs[I];
910 SDValue &OutVal = OutVals[I];
911 HasSwiftSelfArg |= Out.Flags.isSwiftSelf();
912 HasSwiftErrorArg |= Out.Flags.isSwiftError();
913 if (Out.Flags.isNest())
914 fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
915 if (Out.Flags.isInAlloca())
916 fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
917 if (Out.Flags.isInConsecutiveRegs())
918 fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
919 if (Out.Flags.isInConsecutiveRegsLast())
920 fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
921 if (Out.Flags.isByVal() && Out.Flags.getByValSize() != 0) {
922 auto &MFI = MF.getFrameInfo();
923 int FI = MFI.CreateStackObject(Out.Flags.getByValSize(),
924 Out.Flags.getNonZeroByValAlign(),
925 /*isSS=*/false);
926 SDValue SizeNode =
927 DAG.getConstant(Out.Flags.getByValSize(), DL, MVT::i32);
928 SDValue FINode = DAG.getFrameIndex(FI, getPointerTy(Layout));
929 Chain = DAG.getMemcpy(
930 Chain, DL, FINode, OutVal, SizeNode, Out.Flags.getNonZeroByValAlign(),
931 /*isVolatile*/ false, /*AlwaysInline=*/false,
932 /*isTailCall*/ false, MachinePointerInfo(), MachinePointerInfo());
933 OutVal = FINode;
934 }
935 // Count the number of fixed args *after* legalization.
936 NumFixedArgs += Out.IsFixed;
937 }
938
939 bool IsVarArg = CLI.IsVarArg;
940 auto PtrVT = getPointerTy(Layout);
941
942 // For swiftcc, emit additional swiftself and swifterror arguments
943 // if there aren't. These additional arguments are also added for callee
944 // signature They are necessary to match callee and caller signature for
945 // indirect call.
946 if (CallConv == CallingConv::Swift) {
947 if (!HasSwiftSelfArg) {
948 NumFixedArgs++;
949 ISD::OutputArg Arg;
950 Arg.Flags.setSwiftSelf();
951 CLI.Outs.push_back(Arg);
952 SDValue ArgVal = DAG.getUNDEF(PtrVT);
953 CLI.OutVals.push_back(ArgVal);
954 }
955 if (!HasSwiftErrorArg) {
956 NumFixedArgs++;
957 ISD::OutputArg Arg;
958 Arg.Flags.setSwiftError();
959 CLI.Outs.push_back(Arg);
960 SDValue ArgVal = DAG.getUNDEF(PtrVT);
961 CLI.OutVals.push_back(ArgVal);
962 }
963 }
964
965 // Analyze operands of the call, assigning locations to each operand.
966 SmallVector<CCValAssign, 16> ArgLocs;
967 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
968
969 if (IsVarArg) {
970 // Outgoing non-fixed arguments are placed in a buffer. First
971 // compute their offsets and the total amount of buffer space needed.
972 for (unsigned I = NumFixedArgs; I < Outs.size(); ++I) {
973 const ISD::OutputArg &Out = Outs[I];
974 SDValue &Arg = OutVals[I];
975 EVT VT = Arg.getValueType();
976 assert(VT != MVT::iPTR && "Legalized args should be concrete");
977 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
978 Align Alignment =
979 std::max(Out.Flags.getNonZeroOrigAlign(), Layout.getABITypeAlign(Ty));
980 unsigned Offset =
981 CCInfo.AllocateStack(Layout.getTypeAllocSize(Ty), Alignment);
982 CCInfo.addLoc(CCValAssign::getMem(ArgLocs.size(), VT.getSimpleVT(),
983 Offset, VT.getSimpleVT(),
984 CCValAssign::Full));
985 }
986 }
987
988 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
989
990 SDValue FINode;
991 if (IsVarArg && NumBytes) {
992 // For non-fixed arguments, next emit stores to store the argument values
993 // to the stack buffer at the offsets computed above.
994 int FI = MF.getFrameInfo().CreateStackObject(NumBytes,
995 Layout.getStackAlignment(),
996 /*isSS=*/false);
997 unsigned ValNo = 0;
998 SmallVector<SDValue, 8> Chains;
999 for (SDValue Arg : drop_begin(OutVals, NumFixedArgs)) {
1000 assert(ArgLocs[ValNo].getValNo() == ValNo &&
1001 "ArgLocs should remain in order and only hold varargs args");
1002 unsigned Offset = ArgLocs[ValNo++].getLocMemOffset();
1003 FINode = DAG.getFrameIndex(FI, getPointerTy(Layout));
1004 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, FINode,
1005 DAG.getConstant(Offset, DL, PtrVT));
1006 Chains.push_back(
1007 DAG.getStore(Chain, DL, Arg, Add,
1008 MachinePointerInfo::getFixedStack(MF, FI, Offset)));
1009 }
1010 if (!Chains.empty())
1011 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
1012 } else if (IsVarArg) {
1013 FINode = DAG.getIntPtrConstant(0, DL);
1014 }
1015
1016 if (Callee->getOpcode() == ISD::GlobalAddress) {
1017 // If the callee is a GlobalAddress node (quite common, every direct call
1018 // is) turn it into a TargetGlobalAddress node so that LowerGlobalAddress
1019 // doesn't at MO_GOT which is not needed for direct calls.
1020 GlobalAddressSDNode* GA = cast<GlobalAddressSDNode>(Callee);
1021 Callee = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
1022 getPointerTy(DAG.getDataLayout()),
1023 GA->getOffset());
1024 Callee = DAG.getNode(WebAssemblyISD::Wrapper, DL,
1025 getPointerTy(DAG.getDataLayout()), Callee);
1026 }
1027
1028 // Compute the operands for the CALLn node.
1029 SmallVector<SDValue, 16> Ops;
1030 Ops.push_back(Chain);
1031 Ops.push_back(Callee);
1032
1033 // Add all fixed arguments. Note that for non-varargs calls, NumFixedArgs
1034 // isn't reliable.
1035 Ops.append(OutVals.begin(),
1036 IsVarArg ? OutVals.begin() + NumFixedArgs : OutVals.end());
1037 // Add a pointer to the vararg buffer.
1038 if (IsVarArg)
1039 Ops.push_back(FINode);
1040
1041 SmallVector<EVT, 8> InTys;
1042 for (const auto &In : Ins) {
1043 assert(!In.Flags.isByVal() && "byval is not valid for return values");
1044 assert(!In.Flags.isNest() && "nest is not valid for return values");
1045 if (In.Flags.isInAlloca())
1046 fail(DL, DAG, "WebAssembly hasn't implemented inalloca return values");
1047 if (In.Flags.isInConsecutiveRegs())
1048 fail(DL, DAG, "WebAssembly hasn't implemented cons regs return values");
1049 if (In.Flags.isInConsecutiveRegsLast())
1050 fail(DL, DAG,
1051 "WebAssembly hasn't implemented cons regs last return values");
1052 // Ignore In.getNonZeroOrigAlign() because all our arguments are passed in
1053 // registers.
1054 InTys.push_back(In.VT);
1055 }
1056
1057 if (CLI.IsTailCall) {
1058 // ret_calls do not return values to the current frame
1059 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1060 return DAG.getNode(WebAssemblyISD::RET_CALL, DL, NodeTys, Ops);
1061 }
1062
1063 InTys.push_back(MVT::Other);
1064 SDVTList InTyList = DAG.getVTList(InTys);
1065 SDValue Res = DAG.getNode(WebAssemblyISD::CALL, DL, InTyList, Ops);
1066
1067 for (size_t I = 0; I < Ins.size(); ++I)
1068 InVals.push_back(Res.getValue(I));
1069
1070 // Return the chain
1071 return Res.getValue(Ins.size());
1072 }
1073
CanLowerReturn(CallingConv::ID,MachineFunction &,bool,const SmallVectorImpl<ISD::OutputArg> & Outs,LLVMContext &) const1074 bool WebAssemblyTargetLowering::CanLowerReturn(
1075 CallingConv::ID /*CallConv*/, MachineFunction & /*MF*/, bool /*IsVarArg*/,
1076 const SmallVectorImpl<ISD::OutputArg> &Outs,
1077 LLVMContext & /*Context*/) const {
1078 // WebAssembly can only handle returning tuples with multivalue enabled
1079 return Subtarget->hasMultivalue() || Outs.size() <= 1;
1080 }
1081
LowerReturn(SDValue Chain,CallingConv::ID CallConv,bool,const SmallVectorImpl<ISD::OutputArg> & Outs,const SmallVectorImpl<SDValue> & OutVals,const SDLoc & DL,SelectionDAG & DAG) const1082 SDValue WebAssemblyTargetLowering::LowerReturn(
1083 SDValue Chain, CallingConv::ID CallConv, bool /*IsVarArg*/,
1084 const SmallVectorImpl<ISD::OutputArg> &Outs,
1085 const SmallVectorImpl<SDValue> &OutVals, const SDLoc &DL,
1086 SelectionDAG &DAG) const {
1087 assert((Subtarget->hasMultivalue() || Outs.size() <= 1) &&
1088 "MVP WebAssembly can only return up to one value");
1089 if (!callingConvSupported(CallConv))
1090 fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
1091
1092 SmallVector<SDValue, 4> RetOps(1, Chain);
1093 RetOps.append(OutVals.begin(), OutVals.end());
1094 Chain = DAG.getNode(WebAssemblyISD::RETURN, DL, MVT::Other, RetOps);
1095
1096 // Record the number and types of the return values.
1097 for (const ISD::OutputArg &Out : Outs) {
1098 assert(!Out.Flags.isByVal() && "byval is not valid for return values");
1099 assert(!Out.Flags.isNest() && "nest is not valid for return values");
1100 assert(Out.IsFixed && "non-fixed return value is not valid");
1101 if (Out.Flags.isInAlloca())
1102 fail(DL, DAG, "WebAssembly hasn't implemented inalloca results");
1103 if (Out.Flags.isInConsecutiveRegs())
1104 fail(DL, DAG, "WebAssembly hasn't implemented cons regs results");
1105 if (Out.Flags.isInConsecutiveRegsLast())
1106 fail(DL, DAG, "WebAssembly hasn't implemented cons regs last results");
1107 }
1108
1109 return Chain;
1110 }
1111
LowerFormalArguments(SDValue Chain,CallingConv::ID CallConv,bool IsVarArg,const SmallVectorImpl<ISD::InputArg> & Ins,const SDLoc & DL,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals) const1112 SDValue WebAssemblyTargetLowering::LowerFormalArguments(
1113 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
1114 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1115 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1116 if (!callingConvSupported(CallConv))
1117 fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions");
1118
1119 MachineFunction &MF = DAG.getMachineFunction();
1120 auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>();
1121
1122 // Set up the incoming ARGUMENTS value, which serves to represent the liveness
1123 // of the incoming values before they're represented by virtual registers.
1124 MF.getRegInfo().addLiveIn(WebAssembly::ARGUMENTS);
1125
1126 bool HasSwiftErrorArg = false;
1127 bool HasSwiftSelfArg = false;
1128 for (const ISD::InputArg &In : Ins) {
1129 HasSwiftSelfArg |= In.Flags.isSwiftSelf();
1130 HasSwiftErrorArg |= In.Flags.isSwiftError();
1131 if (In.Flags.isInAlloca())
1132 fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments");
1133 if (In.Flags.isNest())
1134 fail(DL, DAG, "WebAssembly hasn't implemented nest arguments");
1135 if (In.Flags.isInConsecutiveRegs())
1136 fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments");
1137 if (In.Flags.isInConsecutiveRegsLast())
1138 fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments");
1139 // Ignore In.getNonZeroOrigAlign() because all our arguments are passed in
1140 // registers.
1141 InVals.push_back(In.Used ? DAG.getNode(WebAssemblyISD::ARGUMENT, DL, In.VT,
1142 DAG.getTargetConstant(InVals.size(),
1143 DL, MVT::i32))
1144 : DAG.getUNDEF(In.VT));
1145
1146 // Record the number and types of arguments.
1147 MFI->addParam(In.VT);
1148 }
1149
1150 // For swiftcc, emit additional swiftself and swifterror arguments
1151 // if there aren't. These additional arguments are also added for callee
1152 // signature They are necessary to match callee and caller signature for
1153 // indirect call.
1154 auto PtrVT = getPointerTy(MF.getDataLayout());
1155 if (CallConv == CallingConv::Swift) {
1156 if (!HasSwiftSelfArg) {
1157 MFI->addParam(PtrVT);
1158 }
1159 if (!HasSwiftErrorArg) {
1160 MFI->addParam(PtrVT);
1161 }
1162 }
1163 // Varargs are copied into a buffer allocated by the caller, and a pointer to
1164 // the buffer is passed as an argument.
1165 if (IsVarArg) {
1166 MVT PtrVT = getPointerTy(MF.getDataLayout());
1167 Register VarargVreg =
1168 MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrVT));
1169 MFI->setVarargBufferVreg(VarargVreg);
1170 Chain = DAG.getCopyToReg(
1171 Chain, DL, VarargVreg,
1172 DAG.getNode(WebAssemblyISD::ARGUMENT, DL, PtrVT,
1173 DAG.getTargetConstant(Ins.size(), DL, MVT::i32)));
1174 MFI->addParam(PtrVT);
1175 }
1176
1177 // Record the number and types of arguments and results.
1178 SmallVector<MVT, 4> Params;
1179 SmallVector<MVT, 4> Results;
1180 computeSignatureVTs(MF.getFunction().getFunctionType(), &MF.getFunction(),
1181 MF.getFunction(), DAG.getTarget(), Params, Results);
1182 for (MVT VT : Results)
1183 MFI->addResult(VT);
1184 // TODO: Use signatures in WebAssemblyMachineFunctionInfo too and unify
1185 // the param logic here with ComputeSignatureVTs
1186 assert(MFI->getParams().size() == Params.size() &&
1187 std::equal(MFI->getParams().begin(), MFI->getParams().end(),
1188 Params.begin()));
1189
1190 return Chain;
1191 }
1192
ReplaceNodeResults(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG) const1193 void WebAssemblyTargetLowering::ReplaceNodeResults(
1194 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
1195 switch (N->getOpcode()) {
1196 case ISD::SIGN_EXTEND_INREG:
1197 // Do not add any results, signifying that N should not be custom lowered
1198 // after all. This happens because simd128 turns on custom lowering for
1199 // SIGN_EXTEND_INREG, but for non-vector sign extends the result might be an
1200 // illegal type.
1201 break;
1202 default:
1203 llvm_unreachable(
1204 "ReplaceNodeResults not implemented for this op for WebAssembly!");
1205 }
1206 }
1207
1208 //===----------------------------------------------------------------------===//
1209 // Custom lowering hooks.
1210 //===----------------------------------------------------------------------===//
1211
LowerOperation(SDValue Op,SelectionDAG & DAG) const1212 SDValue WebAssemblyTargetLowering::LowerOperation(SDValue Op,
1213 SelectionDAG &DAG) const {
1214 SDLoc DL(Op);
1215 switch (Op.getOpcode()) {
1216 default:
1217 llvm_unreachable("unimplemented operation lowering");
1218 return SDValue();
1219 case ISD::FrameIndex:
1220 return LowerFrameIndex(Op, DAG);
1221 case ISD::GlobalAddress:
1222 return LowerGlobalAddress(Op, DAG);
1223 case ISD::GlobalTLSAddress:
1224 return LowerGlobalTLSAddress(Op, DAG);
1225 case ISD::ExternalSymbol:
1226 return LowerExternalSymbol(Op, DAG);
1227 case ISD::JumpTable:
1228 return LowerJumpTable(Op, DAG);
1229 case ISD::BR_JT:
1230 return LowerBR_JT(Op, DAG);
1231 case ISD::VASTART:
1232 return LowerVASTART(Op, DAG);
1233 case ISD::BlockAddress:
1234 case ISD::BRIND:
1235 fail(DL, DAG, "WebAssembly hasn't implemented computed gotos");
1236 return SDValue();
1237 case ISD::RETURNADDR:
1238 return LowerRETURNADDR(Op, DAG);
1239 case ISD::FRAMEADDR:
1240 return LowerFRAMEADDR(Op, DAG);
1241 case ISD::CopyToReg:
1242 return LowerCopyToReg(Op, DAG);
1243 case ISD::EXTRACT_VECTOR_ELT:
1244 case ISD::INSERT_VECTOR_ELT:
1245 return LowerAccessVectorElement(Op, DAG);
1246 case ISD::INTRINSIC_VOID:
1247 case ISD::INTRINSIC_WO_CHAIN:
1248 case ISD::INTRINSIC_W_CHAIN:
1249 return LowerIntrinsic(Op, DAG);
1250 case ISD::SIGN_EXTEND_INREG:
1251 return LowerSIGN_EXTEND_INREG(Op, DAG);
1252 case ISD::BUILD_VECTOR:
1253 return LowerBUILD_VECTOR(Op, DAG);
1254 case ISD::VECTOR_SHUFFLE:
1255 return LowerVECTOR_SHUFFLE(Op, DAG);
1256 case ISD::SETCC:
1257 return LowerSETCC(Op, DAG);
1258 case ISD::SHL:
1259 case ISD::SRA:
1260 case ISD::SRL:
1261 return LowerShift(Op, DAG);
1262 case ISD::FP_TO_SINT_SAT:
1263 case ISD::FP_TO_UINT_SAT:
1264 return LowerFP_TO_INT_SAT(Op, DAG);
1265 case ISD::LOAD:
1266 return LowerLoad(Op, DAG);
1267 case ISD::STORE:
1268 return LowerStore(Op, DAG);
1269 }
1270 }
1271
IsWebAssemblyGlobal(SDValue Op)1272 static bool IsWebAssemblyGlobal(SDValue Op) {
1273 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op))
1274 return WebAssembly::isWasmVarAddressSpace(GA->getAddressSpace());
1275
1276 return false;
1277 }
1278
LowerStore(SDValue Op,SelectionDAG & DAG) const1279 SDValue WebAssemblyTargetLowering::LowerStore(SDValue Op,
1280 SelectionDAG &DAG) const {
1281 SDLoc DL(Op);
1282 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
1283 const SDValue &Value = SN->getValue();
1284 const SDValue &Base = SN->getBasePtr();
1285 const SDValue &Offset = SN->getOffset();
1286
1287 if (IsWebAssemblyGlobal(Base)) {
1288 if (!Offset->isUndef())
1289 report_fatal_error("unexpected offset when storing to webassembly global",
1290 false);
1291
1292 SDVTList Tys = DAG.getVTList(MVT::Other);
1293 SDValue Ops[] = {SN->getChain(), Value, Base};
1294 return DAG.getMemIntrinsicNode(WebAssemblyISD::GLOBAL_SET, DL, Tys, Ops,
1295 SN->getMemoryVT(), SN->getMemOperand());
1296 }
1297
1298 return Op;
1299 }
1300
LowerLoad(SDValue Op,SelectionDAG & DAG) const1301 SDValue WebAssemblyTargetLowering::LowerLoad(SDValue Op,
1302 SelectionDAG &DAG) const {
1303 SDLoc DL(Op);
1304 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
1305 const SDValue &Base = LN->getBasePtr();
1306 const SDValue &Offset = LN->getOffset();
1307
1308 if (IsWebAssemblyGlobal(Base)) {
1309 if (!Offset->isUndef())
1310 report_fatal_error(
1311 "unexpected offset when loading from webassembly global", false);
1312
1313 SDVTList Tys = DAG.getVTList(LN->getValueType(0), MVT::Other);
1314 SDValue Ops[] = {LN->getChain(), Base};
1315 return DAG.getMemIntrinsicNode(WebAssemblyISD::GLOBAL_GET, DL, Tys, Ops,
1316 LN->getMemoryVT(), LN->getMemOperand());
1317 }
1318
1319 return Op;
1320 }
1321
LowerCopyToReg(SDValue Op,SelectionDAG & DAG) const1322 SDValue WebAssemblyTargetLowering::LowerCopyToReg(SDValue Op,
1323 SelectionDAG &DAG) const {
1324 SDValue Src = Op.getOperand(2);
1325 if (isa<FrameIndexSDNode>(Src.getNode())) {
1326 // CopyToReg nodes don't support FrameIndex operands. Other targets select
1327 // the FI to some LEA-like instruction, but since we don't have that, we
1328 // need to insert some kind of instruction that can take an FI operand and
1329 // produces a value usable by CopyToReg (i.e. in a vreg). So insert a dummy
1330 // local.copy between Op and its FI operand.
1331 SDValue Chain = Op.getOperand(0);
1332 SDLoc DL(Op);
1333 unsigned Reg = cast<RegisterSDNode>(Op.getOperand(1))->getReg();
1334 EVT VT = Src.getValueType();
1335 SDValue Copy(DAG.getMachineNode(VT == MVT::i32 ? WebAssembly::COPY_I32
1336 : WebAssembly::COPY_I64,
1337 DL, VT, Src),
1338 0);
1339 return Op.getNode()->getNumValues() == 1
1340 ? DAG.getCopyToReg(Chain, DL, Reg, Copy)
1341 : DAG.getCopyToReg(Chain, DL, Reg, Copy,
1342 Op.getNumOperands() == 4 ? Op.getOperand(3)
1343 : SDValue());
1344 }
1345 return SDValue();
1346 }
1347
LowerFrameIndex(SDValue Op,SelectionDAG & DAG) const1348 SDValue WebAssemblyTargetLowering::LowerFrameIndex(SDValue Op,
1349 SelectionDAG &DAG) const {
1350 int FI = cast<FrameIndexSDNode>(Op)->getIndex();
1351 return DAG.getTargetFrameIndex(FI, Op.getValueType());
1352 }
1353
LowerRETURNADDR(SDValue Op,SelectionDAG & DAG) const1354 SDValue WebAssemblyTargetLowering::LowerRETURNADDR(SDValue Op,
1355 SelectionDAG &DAG) const {
1356 SDLoc DL(Op);
1357
1358 if (!Subtarget->getTargetTriple().isOSEmscripten()) {
1359 fail(DL, DAG,
1360 "Non-Emscripten WebAssembly hasn't implemented "
1361 "__builtin_return_address");
1362 return SDValue();
1363 }
1364
1365 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1366 return SDValue();
1367
1368 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1369 MakeLibCallOptions CallOptions;
1370 return makeLibCall(DAG, RTLIB::RETURN_ADDRESS, Op.getValueType(),
1371 {DAG.getConstant(Depth, DL, MVT::i32)}, CallOptions, DL)
1372 .first;
1373 }
1374
LowerFRAMEADDR(SDValue Op,SelectionDAG & DAG) const1375 SDValue WebAssemblyTargetLowering::LowerFRAMEADDR(SDValue Op,
1376 SelectionDAG &DAG) const {
1377 // Non-zero depths are not supported by WebAssembly currently. Use the
1378 // legalizer's default expansion, which is to return 0 (what this function is
1379 // documented to do).
1380 if (Op.getConstantOperandVal(0) > 0)
1381 return SDValue();
1382
1383 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
1384 EVT VT = Op.getValueType();
1385 Register FP =
1386 Subtarget->getRegisterInfo()->getFrameRegister(DAG.getMachineFunction());
1387 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), FP, VT);
1388 }
1389
1390 SDValue
LowerGlobalTLSAddress(SDValue Op,SelectionDAG & DAG) const1391 WebAssemblyTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1392 SelectionDAG &DAG) const {
1393 SDLoc DL(Op);
1394 const auto *GA = cast<GlobalAddressSDNode>(Op);
1395 MVT PtrVT = getPointerTy(DAG.getDataLayout());
1396
1397 MachineFunction &MF = DAG.getMachineFunction();
1398 if (!MF.getSubtarget<WebAssemblySubtarget>().hasBulkMemory())
1399 report_fatal_error("cannot use thread-local storage without bulk memory",
1400 false);
1401
1402 const GlobalValue *GV = GA->getGlobal();
1403
1404 // Currently Emscripten does not support dynamic linking with threads.
1405 // Therefore, if we have thread-local storage, only the local-exec model
1406 // is possible.
1407 // TODO: remove this and implement proper TLS models once Emscripten
1408 // supports dynamic linking with threads.
1409 if (GV->getThreadLocalMode() != GlobalValue::LocalExecTLSModel &&
1410 !Subtarget->getTargetTriple().isOSEmscripten()) {
1411 report_fatal_error("only -ftls-model=local-exec is supported for now on "
1412 "non-Emscripten OSes: variable " +
1413 GV->getName(),
1414 false);
1415 }
1416
1417 auto GlobalGet = PtrVT == MVT::i64 ? WebAssembly::GLOBAL_GET_I64
1418 : WebAssembly::GLOBAL_GET_I32;
1419 const char *BaseName = MF.createExternalSymbolName("__tls_base");
1420
1421 SDValue BaseAddr(
1422 DAG.getMachineNode(GlobalGet, DL, PtrVT,
1423 DAG.getTargetExternalSymbol(BaseName, PtrVT)),
1424 0);
1425
1426 SDValue TLSOffset = DAG.getTargetGlobalAddress(
1427 GV, DL, PtrVT, GA->getOffset(), WebAssemblyII::MO_TLS_BASE_REL);
1428 SDValue SymAddr = DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT, TLSOffset);
1429
1430 return DAG.getNode(ISD::ADD, DL, PtrVT, BaseAddr, SymAddr);
1431 }
1432
LowerGlobalAddress(SDValue Op,SelectionDAG & DAG) const1433 SDValue WebAssemblyTargetLowering::LowerGlobalAddress(SDValue Op,
1434 SelectionDAG &DAG) const {
1435 SDLoc DL(Op);
1436 const auto *GA = cast<GlobalAddressSDNode>(Op);
1437 EVT VT = Op.getValueType();
1438 assert(GA->getTargetFlags() == 0 &&
1439 "Unexpected target flags on generic GlobalAddressSDNode");
1440 if (!WebAssembly::isValidAddressSpace(GA->getAddressSpace()))
1441 fail(DL, DAG, "Invalid address space for WebAssembly target");
1442
1443 unsigned OperandFlags = 0;
1444 if (isPositionIndependent()) {
1445 const GlobalValue *GV = GA->getGlobal();
1446 if (getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) {
1447 MachineFunction &MF = DAG.getMachineFunction();
1448 MVT PtrVT = getPointerTy(MF.getDataLayout());
1449 const char *BaseName;
1450 if (GV->getValueType()->isFunctionTy()) {
1451 BaseName = MF.createExternalSymbolName("__table_base");
1452 OperandFlags = WebAssemblyII::MO_TABLE_BASE_REL;
1453 }
1454 else {
1455 BaseName = MF.createExternalSymbolName("__memory_base");
1456 OperandFlags = WebAssemblyII::MO_MEMORY_BASE_REL;
1457 }
1458 SDValue BaseAddr =
1459 DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT,
1460 DAG.getTargetExternalSymbol(BaseName, PtrVT));
1461
1462 SDValue SymAddr = DAG.getNode(
1463 WebAssemblyISD::WrapperPIC, DL, VT,
1464 DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT, GA->getOffset(),
1465 OperandFlags));
1466
1467 return DAG.getNode(ISD::ADD, DL, VT, BaseAddr, SymAddr);
1468 } else {
1469 OperandFlags = WebAssemblyII::MO_GOT;
1470 }
1471 }
1472
1473 return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1474 DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT,
1475 GA->getOffset(), OperandFlags));
1476 }
1477
1478 SDValue
LowerExternalSymbol(SDValue Op,SelectionDAG & DAG) const1479 WebAssemblyTargetLowering::LowerExternalSymbol(SDValue Op,
1480 SelectionDAG &DAG) const {
1481 SDLoc DL(Op);
1482 const auto *ES = cast<ExternalSymbolSDNode>(Op);
1483 EVT VT = Op.getValueType();
1484 assert(ES->getTargetFlags() == 0 &&
1485 "Unexpected target flags on generic ExternalSymbolSDNode");
1486 return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1487 DAG.getTargetExternalSymbol(ES->getSymbol(), VT));
1488 }
1489
LowerJumpTable(SDValue Op,SelectionDAG & DAG) const1490 SDValue WebAssemblyTargetLowering::LowerJumpTable(SDValue Op,
1491 SelectionDAG &DAG) const {
1492 // There's no need for a Wrapper node because we always incorporate a jump
1493 // table operand into a BR_TABLE instruction, rather than ever
1494 // materializing it in a register.
1495 const JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1496 return DAG.getTargetJumpTable(JT->getIndex(), Op.getValueType(),
1497 JT->getTargetFlags());
1498 }
1499
LowerBR_JT(SDValue Op,SelectionDAG & DAG) const1500 SDValue WebAssemblyTargetLowering::LowerBR_JT(SDValue Op,
1501 SelectionDAG &DAG) const {
1502 SDLoc DL(Op);
1503 SDValue Chain = Op.getOperand(0);
1504 const auto *JT = cast<JumpTableSDNode>(Op.getOperand(1));
1505 SDValue Index = Op.getOperand(2);
1506 assert(JT->getTargetFlags() == 0 && "WebAssembly doesn't set target flags");
1507
1508 SmallVector<SDValue, 8> Ops;
1509 Ops.push_back(Chain);
1510 Ops.push_back(Index);
1511
1512 MachineJumpTableInfo *MJTI = DAG.getMachineFunction().getJumpTableInfo();
1513 const auto &MBBs = MJTI->getJumpTables()[JT->getIndex()].MBBs;
1514
1515 // Add an operand for each case.
1516 for (auto MBB : MBBs)
1517 Ops.push_back(DAG.getBasicBlock(MBB));
1518
1519 // Add the first MBB as a dummy default target for now. This will be replaced
1520 // with the proper default target (and the preceding range check eliminated)
1521 // if possible by WebAssemblyFixBrTableDefaults.
1522 Ops.push_back(DAG.getBasicBlock(*MBBs.begin()));
1523 return DAG.getNode(WebAssemblyISD::BR_TABLE, DL, MVT::Other, Ops);
1524 }
1525
LowerVASTART(SDValue Op,SelectionDAG & DAG) const1526 SDValue WebAssemblyTargetLowering::LowerVASTART(SDValue Op,
1527 SelectionDAG &DAG) const {
1528 SDLoc DL(Op);
1529 EVT PtrVT = getPointerTy(DAG.getMachineFunction().getDataLayout());
1530
1531 auto *MFI = DAG.getMachineFunction().getInfo<WebAssemblyFunctionInfo>();
1532 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1533
1534 SDValue ArgN = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1535 MFI->getVarargBufferVreg(), PtrVT);
1536 return DAG.getStore(Op.getOperand(0), DL, ArgN, Op.getOperand(1),
1537 MachinePointerInfo(SV));
1538 }
1539
getCppExceptionSymNode(SDValue Op,unsigned TagIndex,SelectionDAG & DAG)1540 static SDValue getCppExceptionSymNode(SDValue Op, unsigned TagIndex,
1541 SelectionDAG &DAG) {
1542 // We only support C++ exceptions for now
1543 int Tag =
1544 cast<ConstantSDNode>(Op.getOperand(TagIndex).getNode())->getZExtValue();
1545 if (Tag != WebAssembly::CPP_EXCEPTION)
1546 llvm_unreachable("Invalid tag: We only support C++ exceptions for now");
1547 auto &MF = DAG.getMachineFunction();
1548 const auto &TLI = DAG.getTargetLoweringInfo();
1549 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
1550 const char *SymName = MF.createExternalSymbolName("__cpp_exception");
1551 return DAG.getNode(WebAssemblyISD::Wrapper, SDLoc(Op), PtrVT,
1552 DAG.getTargetExternalSymbol(SymName, PtrVT));
1553 }
1554
LowerIntrinsic(SDValue Op,SelectionDAG & DAG) const1555 SDValue WebAssemblyTargetLowering::LowerIntrinsic(SDValue Op,
1556 SelectionDAG &DAG) const {
1557 MachineFunction &MF = DAG.getMachineFunction();
1558 unsigned IntNo;
1559 switch (Op.getOpcode()) {
1560 case ISD::INTRINSIC_VOID:
1561 case ISD::INTRINSIC_W_CHAIN:
1562 IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1563 break;
1564 case ISD::INTRINSIC_WO_CHAIN:
1565 IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1566 break;
1567 default:
1568 llvm_unreachable("Invalid intrinsic");
1569 }
1570 SDLoc DL(Op);
1571
1572 switch (IntNo) {
1573 default:
1574 return SDValue(); // Don't custom lower most intrinsics.
1575
1576 case Intrinsic::wasm_lsda: {
1577 EVT VT = Op.getValueType();
1578 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1579 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
1580 auto &Context = MF.getMMI().getContext();
1581 MCSymbol *S = Context.getOrCreateSymbol(Twine("GCC_except_table") +
1582 Twine(MF.getFunctionNumber()));
1583 return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT,
1584 DAG.getMCSymbol(S, PtrVT));
1585 }
1586
1587 case Intrinsic::wasm_throw: {
1588 SDValue SymNode = getCppExceptionSymNode(Op, 2, DAG);
1589 return DAG.getNode(WebAssemblyISD::THROW, DL,
1590 MVT::Other, // outchain type
1591 {
1592 Op.getOperand(0), // inchain
1593 SymNode, // exception symbol
1594 Op.getOperand(3) // thrown value
1595 });
1596 }
1597
1598 case Intrinsic::wasm_catch: {
1599 SDValue SymNode = getCppExceptionSymNode(Op, 2, DAG);
1600 return DAG.getNode(WebAssemblyISD::CATCH, DL,
1601 {
1602 MVT::i32, // outchain type
1603 MVT::Other // return value
1604 },
1605 {
1606 Op.getOperand(0), // inchain
1607 SymNode // exception symbol
1608 });
1609 }
1610
1611 case Intrinsic::wasm_shuffle: {
1612 // Drop in-chain and replace undefs, but otherwise pass through unchanged
1613 SDValue Ops[18];
1614 size_t OpIdx = 0;
1615 Ops[OpIdx++] = Op.getOperand(1);
1616 Ops[OpIdx++] = Op.getOperand(2);
1617 while (OpIdx < 18) {
1618 const SDValue &MaskIdx = Op.getOperand(OpIdx + 1);
1619 if (MaskIdx.isUndef() ||
1620 cast<ConstantSDNode>(MaskIdx.getNode())->getZExtValue() >= 32) {
1621 Ops[OpIdx++] = DAG.getConstant(0, DL, MVT::i32);
1622 } else {
1623 Ops[OpIdx++] = MaskIdx;
1624 }
1625 }
1626 return DAG.getNode(WebAssemblyISD::SHUFFLE, DL, Op.getValueType(), Ops);
1627 }
1628 }
1629 }
1630
1631 SDValue
LowerSIGN_EXTEND_INREG(SDValue Op,SelectionDAG & DAG) const1632 WebAssemblyTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
1633 SelectionDAG &DAG) const {
1634 SDLoc DL(Op);
1635 // If sign extension operations are disabled, allow sext_inreg only if operand
1636 // is a vector extract of an i8 or i16 lane. SIMD does not depend on sign
1637 // extension operations, but allowing sext_inreg in this context lets us have
1638 // simple patterns to select extract_lane_s instructions. Expanding sext_inreg
1639 // everywhere would be simpler in this file, but would necessitate large and
1640 // brittle patterns to undo the expansion and select extract_lane_s
1641 // instructions.
1642 assert(!Subtarget->hasSignExt() && Subtarget->hasSIMD128());
1643 if (Op.getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1644 return SDValue();
1645
1646 const SDValue &Extract = Op.getOperand(0);
1647 MVT VecT = Extract.getOperand(0).getSimpleValueType();
1648 if (VecT.getVectorElementType().getSizeInBits() > 32)
1649 return SDValue();
1650 MVT ExtractedLaneT =
1651 cast<VTSDNode>(Op.getOperand(1).getNode())->getVT().getSimpleVT();
1652 MVT ExtractedVecT =
1653 MVT::getVectorVT(ExtractedLaneT, 128 / ExtractedLaneT.getSizeInBits());
1654 if (ExtractedVecT == VecT)
1655 return Op;
1656
1657 // Bitcast vector to appropriate type to ensure ISel pattern coverage
1658 const SDNode *Index = Extract.getOperand(1).getNode();
1659 if (!isa<ConstantSDNode>(Index))
1660 return SDValue();
1661 unsigned IndexVal = cast<ConstantSDNode>(Index)->getZExtValue();
1662 unsigned Scale =
1663 ExtractedVecT.getVectorNumElements() / VecT.getVectorNumElements();
1664 assert(Scale > 1);
1665 SDValue NewIndex =
1666 DAG.getConstant(IndexVal * Scale, DL, Index->getValueType(0));
1667 SDValue NewExtract = DAG.getNode(
1668 ISD::EXTRACT_VECTOR_ELT, DL, Extract.getValueType(),
1669 DAG.getBitcast(ExtractedVecT, Extract.getOperand(0)), NewIndex);
1670 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, Op.getValueType(), NewExtract,
1671 Op.getOperand(1));
1672 }
1673
LowerBUILD_VECTOR(SDValue Op,SelectionDAG & DAG) const1674 SDValue WebAssemblyTargetLowering::LowerBUILD_VECTOR(SDValue Op,
1675 SelectionDAG &DAG) const {
1676 SDLoc DL(Op);
1677 const EVT VecT = Op.getValueType();
1678 const EVT LaneT = Op.getOperand(0).getValueType();
1679 const size_t Lanes = Op.getNumOperands();
1680 bool CanSwizzle = VecT == MVT::v16i8;
1681
1682 // BUILD_VECTORs are lowered to the instruction that initializes the highest
1683 // possible number of lanes at once followed by a sequence of replace_lane
1684 // instructions to individually initialize any remaining lanes.
1685
1686 // TODO: Tune this. For example, lanewise swizzling is very expensive, so
1687 // swizzled lanes should be given greater weight.
1688
1689 // TODO: Investigate looping rather than always extracting/replacing specific
1690 // lanes to fill gaps.
1691
1692 auto IsConstant = [](const SDValue &V) {
1693 return V.getOpcode() == ISD::Constant || V.getOpcode() == ISD::ConstantFP;
1694 };
1695
1696 // Returns the source vector and index vector pair if they exist. Checks for:
1697 // (extract_vector_elt
1698 // $src,
1699 // (sign_extend_inreg (extract_vector_elt $indices, $i))
1700 // )
1701 auto GetSwizzleSrcs = [](size_t I, const SDValue &Lane) {
1702 auto Bail = std::make_pair(SDValue(), SDValue());
1703 if (Lane->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1704 return Bail;
1705 const SDValue &SwizzleSrc = Lane->getOperand(0);
1706 const SDValue &IndexExt = Lane->getOperand(1);
1707 if (IndexExt->getOpcode() != ISD::SIGN_EXTEND_INREG)
1708 return Bail;
1709 const SDValue &Index = IndexExt->getOperand(0);
1710 if (Index->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1711 return Bail;
1712 const SDValue &SwizzleIndices = Index->getOperand(0);
1713 if (SwizzleSrc.getValueType() != MVT::v16i8 ||
1714 SwizzleIndices.getValueType() != MVT::v16i8 ||
1715 Index->getOperand(1)->getOpcode() != ISD::Constant ||
1716 Index->getConstantOperandVal(1) != I)
1717 return Bail;
1718 return std::make_pair(SwizzleSrc, SwizzleIndices);
1719 };
1720
1721 // If the lane is extracted from another vector at a constant index, return
1722 // that vector. The source vector must not have more lanes than the dest
1723 // because the shufflevector indices are in terms of the destination lanes and
1724 // would not be able to address the smaller individual source lanes.
1725 auto GetShuffleSrc = [&](const SDValue &Lane) {
1726 if (Lane->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1727 return SDValue();
1728 if (!isa<ConstantSDNode>(Lane->getOperand(1).getNode()))
1729 return SDValue();
1730 if (Lane->getOperand(0).getValueType().getVectorNumElements() >
1731 VecT.getVectorNumElements())
1732 return SDValue();
1733 return Lane->getOperand(0);
1734 };
1735
1736 using ValueEntry = std::pair<SDValue, size_t>;
1737 SmallVector<ValueEntry, 16> SplatValueCounts;
1738
1739 using SwizzleEntry = std::pair<std::pair<SDValue, SDValue>, size_t>;
1740 SmallVector<SwizzleEntry, 16> SwizzleCounts;
1741
1742 using ShuffleEntry = std::pair<SDValue, size_t>;
1743 SmallVector<ShuffleEntry, 16> ShuffleCounts;
1744
1745 auto AddCount = [](auto &Counts, const auto &Val) {
1746 auto CountIt =
1747 llvm::find_if(Counts, [&Val](auto E) { return E.first == Val; });
1748 if (CountIt == Counts.end()) {
1749 Counts.emplace_back(Val, 1);
1750 } else {
1751 CountIt->second++;
1752 }
1753 };
1754
1755 auto GetMostCommon = [](auto &Counts) {
1756 auto CommonIt =
1757 std::max_element(Counts.begin(), Counts.end(),
1758 [](auto A, auto B) { return A.second < B.second; });
1759 assert(CommonIt != Counts.end() && "Unexpected all-undef build_vector");
1760 return *CommonIt;
1761 };
1762
1763 size_t NumConstantLanes = 0;
1764
1765 // Count eligible lanes for each type of vector creation op
1766 for (size_t I = 0; I < Lanes; ++I) {
1767 const SDValue &Lane = Op->getOperand(I);
1768 if (Lane.isUndef())
1769 continue;
1770
1771 AddCount(SplatValueCounts, Lane);
1772
1773 if (IsConstant(Lane))
1774 NumConstantLanes++;
1775 if (auto ShuffleSrc = GetShuffleSrc(Lane))
1776 AddCount(ShuffleCounts, ShuffleSrc);
1777 if (CanSwizzle) {
1778 auto SwizzleSrcs = GetSwizzleSrcs(I, Lane);
1779 if (SwizzleSrcs.first)
1780 AddCount(SwizzleCounts, SwizzleSrcs);
1781 }
1782 }
1783
1784 SDValue SplatValue;
1785 size_t NumSplatLanes;
1786 std::tie(SplatValue, NumSplatLanes) = GetMostCommon(SplatValueCounts);
1787
1788 SDValue SwizzleSrc;
1789 SDValue SwizzleIndices;
1790 size_t NumSwizzleLanes = 0;
1791 if (SwizzleCounts.size())
1792 std::forward_as_tuple(std::tie(SwizzleSrc, SwizzleIndices),
1793 NumSwizzleLanes) = GetMostCommon(SwizzleCounts);
1794
1795 // Shuffles can draw from up to two vectors, so find the two most common
1796 // sources.
1797 SDValue ShuffleSrc1, ShuffleSrc2;
1798 size_t NumShuffleLanes = 0;
1799 if (ShuffleCounts.size()) {
1800 std::tie(ShuffleSrc1, NumShuffleLanes) = GetMostCommon(ShuffleCounts);
1801 ShuffleCounts.erase(std::remove_if(ShuffleCounts.begin(),
1802 ShuffleCounts.end(),
1803 [&](const auto &Pair) {
1804 return Pair.first == ShuffleSrc1;
1805 }),
1806 ShuffleCounts.end());
1807 }
1808 if (ShuffleCounts.size()) {
1809 size_t AdditionalShuffleLanes;
1810 std::tie(ShuffleSrc2, AdditionalShuffleLanes) =
1811 GetMostCommon(ShuffleCounts);
1812 NumShuffleLanes += AdditionalShuffleLanes;
1813 }
1814
1815 // Predicate returning true if the lane is properly initialized by the
1816 // original instruction
1817 std::function<bool(size_t, const SDValue &)> IsLaneConstructed;
1818 SDValue Result;
1819 // Prefer swizzles over shuffles over vector consts over splats
1820 if (NumSwizzleLanes >= NumShuffleLanes &&
1821 NumSwizzleLanes >= NumConstantLanes && NumSwizzleLanes >= NumSplatLanes) {
1822 Result = DAG.getNode(WebAssemblyISD::SWIZZLE, DL, VecT, SwizzleSrc,
1823 SwizzleIndices);
1824 auto Swizzled = std::make_pair(SwizzleSrc, SwizzleIndices);
1825 IsLaneConstructed = [&, Swizzled](size_t I, const SDValue &Lane) {
1826 return Swizzled == GetSwizzleSrcs(I, Lane);
1827 };
1828 } else if (NumShuffleLanes >= NumConstantLanes &&
1829 NumShuffleLanes >= NumSplatLanes) {
1830 size_t DestLaneSize = VecT.getVectorElementType().getFixedSizeInBits() / 8;
1831 size_t DestLaneCount = VecT.getVectorNumElements();
1832 size_t Scale1 = 1;
1833 size_t Scale2 = 1;
1834 SDValue Src1 = ShuffleSrc1;
1835 SDValue Src2 = ShuffleSrc2 ? ShuffleSrc2 : DAG.getUNDEF(VecT);
1836 if (Src1.getValueType() != VecT) {
1837 size_t LaneSize =
1838 Src1.getValueType().getVectorElementType().getFixedSizeInBits() / 8;
1839 assert(LaneSize > DestLaneSize);
1840 Scale1 = LaneSize / DestLaneSize;
1841 Src1 = DAG.getBitcast(VecT, Src1);
1842 }
1843 if (Src2.getValueType() != VecT) {
1844 size_t LaneSize =
1845 Src2.getValueType().getVectorElementType().getFixedSizeInBits() / 8;
1846 assert(LaneSize > DestLaneSize);
1847 Scale2 = LaneSize / DestLaneSize;
1848 Src2 = DAG.getBitcast(VecT, Src2);
1849 }
1850
1851 int Mask[16];
1852 assert(DestLaneCount <= 16);
1853 for (size_t I = 0; I < DestLaneCount; ++I) {
1854 const SDValue &Lane = Op->getOperand(I);
1855 SDValue Src = GetShuffleSrc(Lane);
1856 if (Src == ShuffleSrc1) {
1857 Mask[I] = Lane->getConstantOperandVal(1) * Scale1;
1858 } else if (Src && Src == ShuffleSrc2) {
1859 Mask[I] = DestLaneCount + Lane->getConstantOperandVal(1) * Scale2;
1860 } else {
1861 Mask[I] = -1;
1862 }
1863 }
1864 ArrayRef<int> MaskRef(Mask, DestLaneCount);
1865 Result = DAG.getVectorShuffle(VecT, DL, Src1, Src2, MaskRef);
1866 IsLaneConstructed = [&](size_t, const SDValue &Lane) {
1867 auto Src = GetShuffleSrc(Lane);
1868 return Src == ShuffleSrc1 || (Src && Src == ShuffleSrc2);
1869 };
1870 } else if (NumConstantLanes >= NumSplatLanes) {
1871 SmallVector<SDValue, 16> ConstLanes;
1872 for (const SDValue &Lane : Op->op_values()) {
1873 if (IsConstant(Lane)) {
1874 ConstLanes.push_back(Lane);
1875 } else if (LaneT.isFloatingPoint()) {
1876 ConstLanes.push_back(DAG.getConstantFP(0, DL, LaneT));
1877 } else {
1878 ConstLanes.push_back(DAG.getConstant(0, DL, LaneT));
1879 }
1880 }
1881 Result = DAG.getBuildVector(VecT, DL, ConstLanes);
1882 IsLaneConstructed = [&IsConstant](size_t _, const SDValue &Lane) {
1883 return IsConstant(Lane);
1884 };
1885 } else {
1886 // Use a splat, but possibly a load_splat
1887 LoadSDNode *SplattedLoad;
1888 if ((SplattedLoad = dyn_cast<LoadSDNode>(SplatValue)) &&
1889 SplattedLoad->getMemoryVT() == VecT.getVectorElementType()) {
1890 Result = DAG.getMemIntrinsicNode(
1891 WebAssemblyISD::LOAD_SPLAT, DL, DAG.getVTList(VecT),
1892 {SplattedLoad->getChain(), SplattedLoad->getBasePtr(),
1893 SplattedLoad->getOffset()},
1894 SplattedLoad->getMemoryVT(), SplattedLoad->getMemOperand());
1895 } else {
1896 Result = DAG.getSplatBuildVector(VecT, DL, SplatValue);
1897 }
1898 IsLaneConstructed = [&SplatValue](size_t _, const SDValue &Lane) {
1899 return Lane == SplatValue;
1900 };
1901 }
1902
1903 assert(Result);
1904 assert(IsLaneConstructed);
1905
1906 // Add replace_lane instructions for any unhandled values
1907 for (size_t I = 0; I < Lanes; ++I) {
1908 const SDValue &Lane = Op->getOperand(I);
1909 if (!Lane.isUndef() && !IsLaneConstructed(I, Lane))
1910 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VecT, Result, Lane,
1911 DAG.getConstant(I, DL, MVT::i32));
1912 }
1913
1914 return Result;
1915 }
1916
1917 SDValue
LowerVECTOR_SHUFFLE(SDValue Op,SelectionDAG & DAG) const1918 WebAssemblyTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
1919 SelectionDAG &DAG) const {
1920 SDLoc DL(Op);
1921 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op.getNode())->getMask();
1922 MVT VecType = Op.getOperand(0).getSimpleValueType();
1923 assert(VecType.is128BitVector() && "Unexpected shuffle vector type");
1924 size_t LaneBytes = VecType.getVectorElementType().getSizeInBits() / 8;
1925
1926 // Space for two vector args and sixteen mask indices
1927 SDValue Ops[18];
1928 size_t OpIdx = 0;
1929 Ops[OpIdx++] = Op.getOperand(0);
1930 Ops[OpIdx++] = Op.getOperand(1);
1931
1932 // Expand mask indices to byte indices and materialize them as operands
1933 for (int M : Mask) {
1934 for (size_t J = 0; J < LaneBytes; ++J) {
1935 // Lower undefs (represented by -1 in mask) to zero
1936 uint64_t ByteIndex = M == -1 ? 0 : (uint64_t)M * LaneBytes + J;
1937 Ops[OpIdx++] = DAG.getConstant(ByteIndex, DL, MVT::i32);
1938 }
1939 }
1940
1941 return DAG.getNode(WebAssemblyISD::SHUFFLE, DL, Op.getValueType(), Ops);
1942 }
1943
LowerSETCC(SDValue Op,SelectionDAG & DAG) const1944 SDValue WebAssemblyTargetLowering::LowerSETCC(SDValue Op,
1945 SelectionDAG &DAG) const {
1946 SDLoc DL(Op);
1947 // The legalizer does not know how to expand the unsupported comparison modes
1948 // of i64x2 vectors, so we manually unroll them here.
1949 assert(Op->getOperand(0)->getSimpleValueType(0) == MVT::v2i64);
1950 SmallVector<SDValue, 2> LHS, RHS;
1951 DAG.ExtractVectorElements(Op->getOperand(0), LHS);
1952 DAG.ExtractVectorElements(Op->getOperand(1), RHS);
1953 const SDValue &CC = Op->getOperand(2);
1954 auto MakeLane = [&](unsigned I) {
1955 return DAG.getNode(ISD::SELECT_CC, DL, MVT::i64, LHS[I], RHS[I],
1956 DAG.getConstant(uint64_t(-1), DL, MVT::i64),
1957 DAG.getConstant(uint64_t(0), DL, MVT::i64), CC);
1958 };
1959 return DAG.getBuildVector(Op->getValueType(0), DL,
1960 {MakeLane(0), MakeLane(1)});
1961 }
1962
1963 SDValue
LowerAccessVectorElement(SDValue Op,SelectionDAG & DAG) const1964 WebAssemblyTargetLowering::LowerAccessVectorElement(SDValue Op,
1965 SelectionDAG &DAG) const {
1966 // Allow constant lane indices, expand variable lane indices
1967 SDNode *IdxNode = Op.getOperand(Op.getNumOperands() - 1).getNode();
1968 if (isa<ConstantSDNode>(IdxNode) || IdxNode->isUndef())
1969 return Op;
1970 else
1971 // Perform default expansion
1972 return SDValue();
1973 }
1974
unrollVectorShift(SDValue Op,SelectionDAG & DAG)1975 static SDValue unrollVectorShift(SDValue Op, SelectionDAG &DAG) {
1976 EVT LaneT = Op.getSimpleValueType().getVectorElementType();
1977 // 32-bit and 64-bit unrolled shifts will have proper semantics
1978 if (LaneT.bitsGE(MVT::i32))
1979 return DAG.UnrollVectorOp(Op.getNode());
1980 // Otherwise mask the shift value to get proper semantics from 32-bit shift
1981 SDLoc DL(Op);
1982 size_t NumLanes = Op.getSimpleValueType().getVectorNumElements();
1983 SDValue Mask = DAG.getConstant(LaneT.getSizeInBits() - 1, DL, MVT::i32);
1984 unsigned ShiftOpcode = Op.getOpcode();
1985 SmallVector<SDValue, 16> ShiftedElements;
1986 DAG.ExtractVectorElements(Op.getOperand(0), ShiftedElements, 0, 0, MVT::i32);
1987 SmallVector<SDValue, 16> ShiftElements;
1988 DAG.ExtractVectorElements(Op.getOperand(1), ShiftElements, 0, 0, MVT::i32);
1989 SmallVector<SDValue, 16> UnrolledOps;
1990 for (size_t i = 0; i < NumLanes; ++i) {
1991 SDValue MaskedShiftValue =
1992 DAG.getNode(ISD::AND, DL, MVT::i32, ShiftElements[i], Mask);
1993 SDValue ShiftedValue = ShiftedElements[i];
1994 if (ShiftOpcode == ISD::SRA)
1995 ShiftedValue = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i32,
1996 ShiftedValue, DAG.getValueType(LaneT));
1997 UnrolledOps.push_back(
1998 DAG.getNode(ShiftOpcode, DL, MVT::i32, ShiftedValue, MaskedShiftValue));
1999 }
2000 return DAG.getBuildVector(Op.getValueType(), DL, UnrolledOps);
2001 }
2002
LowerShift(SDValue Op,SelectionDAG & DAG) const2003 SDValue WebAssemblyTargetLowering::LowerShift(SDValue Op,
2004 SelectionDAG &DAG) const {
2005 SDLoc DL(Op);
2006
2007 // Only manually lower vector shifts
2008 assert(Op.getSimpleValueType().isVector());
2009
2010 auto ShiftVal = DAG.getSplatValue(Op.getOperand(1));
2011 if (!ShiftVal)
2012 return unrollVectorShift(Op, DAG);
2013
2014 // Use anyext because none of the high bits can affect the shift
2015 ShiftVal = DAG.getAnyExtOrTrunc(ShiftVal, DL, MVT::i32);
2016
2017 unsigned Opcode;
2018 switch (Op.getOpcode()) {
2019 case ISD::SHL:
2020 Opcode = WebAssemblyISD::VEC_SHL;
2021 break;
2022 case ISD::SRA:
2023 Opcode = WebAssemblyISD::VEC_SHR_S;
2024 break;
2025 case ISD::SRL:
2026 Opcode = WebAssemblyISD::VEC_SHR_U;
2027 break;
2028 default:
2029 llvm_unreachable("unexpected opcode");
2030 }
2031
2032 return DAG.getNode(Opcode, DL, Op.getValueType(), Op.getOperand(0), ShiftVal);
2033 }
2034
LowerFP_TO_INT_SAT(SDValue Op,SelectionDAG & DAG) const2035 SDValue WebAssemblyTargetLowering::LowerFP_TO_INT_SAT(SDValue Op,
2036 SelectionDAG &DAG) const {
2037 SDLoc DL(Op);
2038 EVT ResT = Op.getValueType();
2039 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2040
2041 if ((ResT == MVT::i32 || ResT == MVT::i64) &&
2042 (SatVT == MVT::i32 || SatVT == MVT::i64))
2043 return Op;
2044
2045 if (ResT == MVT::v4i32 && SatVT == MVT::i32)
2046 return Op;
2047
2048 return SDValue();
2049 }
2050
2051 //===----------------------------------------------------------------------===//
2052 // Custom DAG combine hooks
2053 //===----------------------------------------------------------------------===//
2054 static SDValue
performVECTOR_SHUFFLECombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)2055 performVECTOR_SHUFFLECombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
2056 auto &DAG = DCI.DAG;
2057 auto Shuffle = cast<ShuffleVectorSDNode>(N);
2058
2059 // Hoist vector bitcasts that don't change the number of lanes out of unary
2060 // shuffles, where they are less likely to get in the way of other combines.
2061 // (shuffle (vNxT1 (bitcast (vNxT0 x))), undef, mask) ->
2062 // (vNxT1 (bitcast (vNxT0 (shuffle x, undef, mask))))
2063 SDValue Bitcast = N->getOperand(0);
2064 if (Bitcast.getOpcode() != ISD::BITCAST)
2065 return SDValue();
2066 if (!N->getOperand(1).isUndef())
2067 return SDValue();
2068 SDValue CastOp = Bitcast.getOperand(0);
2069 MVT SrcType = CastOp.getSimpleValueType();
2070 MVT DstType = Bitcast.getSimpleValueType();
2071 if (!SrcType.is128BitVector() ||
2072 SrcType.getVectorNumElements() != DstType.getVectorNumElements())
2073 return SDValue();
2074 SDValue NewShuffle = DAG.getVectorShuffle(
2075 SrcType, SDLoc(N), CastOp, DAG.getUNDEF(SrcType), Shuffle->getMask());
2076 return DAG.getBitcast(DstType, NewShuffle);
2077 }
2078
2079 static SDValue
performVectorExtendCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)2080 performVectorExtendCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
2081 auto &DAG = DCI.DAG;
2082 assert(N->getOpcode() == ISD::SIGN_EXTEND ||
2083 N->getOpcode() == ISD::ZERO_EXTEND);
2084
2085 // Combine ({s,z}ext (extract_subvector src, i)) into a widening operation if
2086 // possible before the extract_subvector can be expanded.
2087 auto Extract = N->getOperand(0);
2088 if (Extract.getOpcode() != ISD::EXTRACT_SUBVECTOR)
2089 return SDValue();
2090 auto Source = Extract.getOperand(0);
2091 auto *IndexNode = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
2092 if (IndexNode == nullptr)
2093 return SDValue();
2094 auto Index = IndexNode->getZExtValue();
2095
2096 // Only v8i8, v4i16, and v2i32 extracts can be widened, and only if the
2097 // extracted subvector is the low or high half of its source.
2098 EVT ResVT = N->getValueType(0);
2099 if (ResVT == MVT::v8i16) {
2100 if (Extract.getValueType() != MVT::v8i8 ||
2101 Source.getValueType() != MVT::v16i8 || (Index != 0 && Index != 8))
2102 return SDValue();
2103 } else if (ResVT == MVT::v4i32) {
2104 if (Extract.getValueType() != MVT::v4i16 ||
2105 Source.getValueType() != MVT::v8i16 || (Index != 0 && Index != 4))
2106 return SDValue();
2107 } else if (ResVT == MVT::v2i64) {
2108 if (Extract.getValueType() != MVT::v2i32 ||
2109 Source.getValueType() != MVT::v4i32 || (Index != 0 && Index != 2))
2110 return SDValue();
2111 } else {
2112 return SDValue();
2113 }
2114
2115 bool IsSext = N->getOpcode() == ISD::SIGN_EXTEND;
2116 bool IsLow = Index == 0;
2117
2118 unsigned Op = IsSext ? (IsLow ? WebAssemblyISD::EXTEND_LOW_S
2119 : WebAssemblyISD::EXTEND_HIGH_S)
2120 : (IsLow ? WebAssemblyISD::EXTEND_LOW_U
2121 : WebAssemblyISD::EXTEND_HIGH_U);
2122
2123 return DAG.getNode(Op, SDLoc(N), ResVT, Source);
2124 }
2125
2126 static SDValue
performVectorConvertLowCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)2127 performVectorConvertLowCombine(SDNode *N,
2128 TargetLowering::DAGCombinerInfo &DCI) {
2129 auto &DAG = DCI.DAG;
2130
2131 EVT ResVT = N->getValueType(0);
2132 if (ResVT != MVT::v2f64)
2133 return SDValue();
2134
2135 if (N->getOpcode() == ISD::SINT_TO_FP || N->getOpcode() == ISD::UINT_TO_FP) {
2136 // Combine this:
2137 //
2138 // (v2f64 ({s,u}int_to_fp
2139 // (v2i32 (extract_subvector (v4i32 $x), 0))))
2140 //
2141 // into (f64x2.convert_low_i32x4_{s,u} $x).
2142 auto Extract = N->getOperand(0);
2143 if (Extract.getOpcode() != ISD::EXTRACT_SUBVECTOR)
2144 return SDValue();
2145 if (Extract.getValueType() != MVT::v2i32)
2146 return SDValue();
2147 auto Source = Extract.getOperand(0);
2148 if (Source.getValueType() != MVT::v4i32)
2149 return SDValue();
2150 auto *IndexNode = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
2151 if (IndexNode == nullptr || IndexNode->getZExtValue() != 0)
2152 return SDValue();
2153
2154 unsigned Op = N->getOpcode() == ISD::SINT_TO_FP
2155 ? WebAssemblyISD::CONVERT_LOW_S
2156 : WebAssemblyISD::CONVERT_LOW_U;
2157
2158 return DAG.getNode(Op, SDLoc(N), ResVT, Source);
2159
2160 } else if (N->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
2161 // Combine this:
2162 //
2163 // (v2f64 (extract_subvector
2164 // (v4f64 ({s,u}int_to_fp (v4i32 $x))), 0))
2165 //
2166 // into (f64x2.convert_low_i32x4_{s,u} $x).
2167 auto IntToFP = N->getOperand(0);
2168 if (IntToFP.getOpcode() != ISD::SINT_TO_FP &&
2169 IntToFP.getOpcode() != ISD::UINT_TO_FP)
2170 return SDValue();
2171 if (IntToFP.getValueType() != MVT::v4f64)
2172 return SDValue();
2173 auto Source = IntToFP.getOperand(0);
2174 if (Source.getValueType() != MVT::v4i32)
2175 return SDValue();
2176 auto IndexNode = dyn_cast<ConstantSDNode>(N->getOperand(1));
2177 if (IndexNode == nullptr || IndexNode->getZExtValue() != 0)
2178 return SDValue();
2179
2180 unsigned Op = IntToFP->getOpcode() == ISD::SINT_TO_FP
2181 ? WebAssemblyISD::CONVERT_LOW_S
2182 : WebAssemblyISD::CONVERT_LOW_U;
2183
2184 return DAG.getNode(Op, SDLoc(N), ResVT, Source);
2185
2186 } else {
2187 llvm_unreachable("unexpected opcode");
2188 }
2189 }
2190
2191 static SDValue
performVectorTruncSatLowCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)2192 performVectorTruncSatLowCombine(SDNode *N,
2193 TargetLowering::DAGCombinerInfo &DCI) {
2194 auto &DAG = DCI.DAG;
2195 assert(N->getOpcode() == ISD::CONCAT_VECTORS);
2196
2197 // Combine this:
2198 //
2199 // (concat_vectors (v2i32 (fp_to_{s,u}int_sat $x, 32)), (v2i32 (splat 0)))
2200 //
2201 // into (i32x4.trunc_sat_f64x2_zero_{s,u} $x).
2202 EVT ResVT = N->getValueType(0);
2203 if (ResVT != MVT::v4i32)
2204 return SDValue();
2205
2206 auto FPToInt = N->getOperand(0);
2207 auto FPToIntOp = FPToInt.getOpcode();
2208 if (FPToIntOp != ISD::FP_TO_SINT_SAT && FPToIntOp != ISD::FP_TO_UINT_SAT)
2209 return SDValue();
2210 if (cast<VTSDNode>(FPToInt.getOperand(1))->getVT() != MVT::i32)
2211 return SDValue();
2212
2213 auto Source = FPToInt.getOperand(0);
2214 if (Source.getValueType() != MVT::v2f64)
2215 return SDValue();
2216
2217 auto *Splat = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
2218 APInt SplatValue, SplatUndef;
2219 unsigned SplatBitSize;
2220 bool HasAnyUndefs;
2221 if (!Splat || !Splat->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
2222 HasAnyUndefs))
2223 return SDValue();
2224 if (SplatValue != 0)
2225 return SDValue();
2226
2227 unsigned Op = FPToIntOp == ISD::FP_TO_SINT_SAT
2228 ? WebAssemblyISD::TRUNC_SAT_ZERO_S
2229 : WebAssemblyISD::TRUNC_SAT_ZERO_U;
2230
2231 return DAG.getNode(Op, SDLoc(N), ResVT, Source);
2232 }
2233
2234 SDValue
PerformDAGCombine(SDNode * N,DAGCombinerInfo & DCI) const2235 WebAssemblyTargetLowering::PerformDAGCombine(SDNode *N,
2236 DAGCombinerInfo &DCI) const {
2237 switch (N->getOpcode()) {
2238 default:
2239 return SDValue();
2240 case ISD::VECTOR_SHUFFLE:
2241 return performVECTOR_SHUFFLECombine(N, DCI);
2242 case ISD::SIGN_EXTEND:
2243 case ISD::ZERO_EXTEND:
2244 return performVectorExtendCombine(N, DCI);
2245 case ISD::SINT_TO_FP:
2246 case ISD::UINT_TO_FP:
2247 case ISD::EXTRACT_SUBVECTOR:
2248 return performVectorConvertLowCombine(N, DCI);
2249 case ISD::CONCAT_VECTORS:
2250 return performVectorTruncSatLowCombine(N, DCI);
2251 }
2252 }
2253