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/MachineFunctionPass.h" 24 #include "llvm/CodeGen/MachineInstrBuilder.h" 25 #include "llvm/CodeGen/MachineJumpTableInfo.h" 26 #include "llvm/CodeGen/MachineModuleInfo.h" 27 #include "llvm/CodeGen/MachineRegisterInfo.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/Intrinsics.h" 34 #include "llvm/IR/IntrinsicsWebAssembly.h" 35 #include "llvm/IR/PatternMatch.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Support/ErrorHandling.h" 38 #include "llvm/Support/KnownBits.h" 39 #include "llvm/Support/MathExtras.h" 40 #include "llvm/Support/raw_ostream.h" 41 #include "llvm/Target/TargetOptions.h" 42 using namespace llvm; 43 44 #define DEBUG_TYPE "wasm-lower" 45 46 WebAssemblyTargetLowering::WebAssemblyTargetLowering( 47 const TargetMachine &TM, const WebAssemblySubtarget &STI) 48 : TargetLowering(TM), Subtarget(&STI) { 49 auto MVTPtr = Subtarget->hasAddr64() ? MVT::i64 : MVT::i32; 50 51 // Booleans always contain 0 or 1. 52 setBooleanContents(ZeroOrOneBooleanContent); 53 // Except in SIMD vectors 54 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 55 // We don't know the microarchitecture here, so just reduce register pressure. 56 setSchedulingPreference(Sched::RegPressure); 57 // Tell ISel that we have a stack pointer. 58 setStackPointerRegisterToSaveRestore( 59 Subtarget->hasAddr64() ? WebAssembly::SP64 : WebAssembly::SP32); 60 // Set up the register classes. 61 addRegisterClass(MVT::i32, &WebAssembly::I32RegClass); 62 addRegisterClass(MVT::i64, &WebAssembly::I64RegClass); 63 addRegisterClass(MVT::f32, &WebAssembly::F32RegClass); 64 addRegisterClass(MVT::f64, &WebAssembly::F64RegClass); 65 if (Subtarget->hasSIMD128()) { 66 addRegisterClass(MVT::v16i8, &WebAssembly::V128RegClass); 67 addRegisterClass(MVT::v8i16, &WebAssembly::V128RegClass); 68 addRegisterClass(MVT::v4i32, &WebAssembly::V128RegClass); 69 addRegisterClass(MVT::v4f32, &WebAssembly::V128RegClass); 70 addRegisterClass(MVT::v2i64, &WebAssembly::V128RegClass); 71 addRegisterClass(MVT::v2f64, &WebAssembly::V128RegClass); 72 } 73 if (Subtarget->hasFP16()) { 74 addRegisterClass(MVT::v8f16, &WebAssembly::V128RegClass); 75 } 76 if (Subtarget->hasReferenceTypes()) { 77 addRegisterClass(MVT::externref, &WebAssembly::EXTERNREFRegClass); 78 addRegisterClass(MVT::funcref, &WebAssembly::FUNCREFRegClass); 79 if (Subtarget->hasExceptionHandling()) { 80 addRegisterClass(MVT::exnref, &WebAssembly::EXNREFRegClass); 81 } 82 } 83 // Compute derived properties from the register classes. 84 computeRegisterProperties(Subtarget->getRegisterInfo()); 85 86 // Transform loads and stores to pointers in address space 1 to loads and 87 // stores to WebAssembly global variables, outside linear memory. 88 for (auto T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64}) { 89 setOperationAction(ISD::LOAD, T, Custom); 90 setOperationAction(ISD::STORE, T, Custom); 91 } 92 if (Subtarget->hasSIMD128()) { 93 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64, 94 MVT::v2f64}) { 95 setOperationAction(ISD::LOAD, T, Custom); 96 setOperationAction(ISD::STORE, T, Custom); 97 } 98 } 99 if (Subtarget->hasReferenceTypes()) { 100 // We need custom load and store lowering for both externref, funcref and 101 // Other. The MVT::Other here represents tables of reference types. 102 for (auto T : {MVT::externref, MVT::funcref, MVT::Other}) { 103 setOperationAction(ISD::LOAD, T, Custom); 104 setOperationAction(ISD::STORE, T, Custom); 105 } 106 } 107 108 setOperationAction(ISD::GlobalAddress, MVTPtr, Custom); 109 setOperationAction(ISD::GlobalTLSAddress, MVTPtr, Custom); 110 setOperationAction(ISD::ExternalSymbol, MVTPtr, Custom); 111 setOperationAction(ISD::JumpTable, MVTPtr, Custom); 112 setOperationAction(ISD::BlockAddress, MVTPtr, Custom); 113 setOperationAction(ISD::BRIND, MVT::Other, Custom); 114 setOperationAction(ISD::CLEAR_CACHE, MVT::Other, Custom); 115 116 // Take the default expansion for va_arg, va_copy, and va_end. There is no 117 // default action for va_start, so we do that custom. 118 setOperationAction(ISD::VASTART, MVT::Other, Custom); 119 setOperationAction(ISD::VAARG, MVT::Other, Expand); 120 setOperationAction(ISD::VACOPY, MVT::Other, Expand); 121 setOperationAction(ISD::VAEND, MVT::Other, Expand); 122 123 for (auto T : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) { 124 // Don't expand the floating-point types to constant pools. 125 setOperationAction(ISD::ConstantFP, T, Legal); 126 // Expand floating-point comparisons. 127 for (auto CC : {ISD::SETO, ISD::SETUO, ISD::SETUEQ, ISD::SETONE, 128 ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE}) 129 setCondCodeAction(CC, T, Expand); 130 // Expand floating-point library function operators. 131 for (auto Op : 132 {ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FREM, ISD::FMA}) 133 setOperationAction(Op, T, Expand); 134 // Note supported floating-point library function operators that otherwise 135 // default to expand. 136 for (auto Op : {ISD::FCEIL, ISD::FFLOOR, ISD::FTRUNC, ISD::FNEARBYINT, 137 ISD::FRINT, ISD::FROUNDEVEN}) 138 setOperationAction(Op, T, Legal); 139 // Support minimum and maximum, which otherwise default to expand. 140 setOperationAction(ISD::FMINIMUM, T, Legal); 141 setOperationAction(ISD::FMAXIMUM, T, Legal); 142 // WebAssembly currently has no builtin f16 support. 143 setOperationAction(ISD::FP16_TO_FP, T, Expand); 144 setOperationAction(ISD::FP_TO_FP16, T, Expand); 145 setLoadExtAction(ISD::EXTLOAD, T, MVT::f16, Expand); 146 setTruncStoreAction(T, MVT::f16, Expand); 147 } 148 149 if (Subtarget->hasFP16()) { 150 setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal); 151 setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal); 152 } 153 154 // Expand unavailable integer operations. 155 for (auto Op : 156 {ISD::BSWAP, ISD::SMUL_LOHI, ISD::UMUL_LOHI, ISD::MULHS, ISD::MULHU, 157 ISD::SDIVREM, ISD::UDIVREM, ISD::SHL_PARTS, ISD::SRA_PARTS, 158 ISD::SRL_PARTS, ISD::ADDC, ISD::ADDE, ISD::SUBC, ISD::SUBE}) { 159 for (auto T : {MVT::i32, MVT::i64}) 160 setOperationAction(Op, T, Expand); 161 if (Subtarget->hasSIMD128()) 162 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64}) 163 setOperationAction(Op, T, Expand); 164 } 165 166 if (Subtarget->hasNontrappingFPToInt()) 167 for (auto Op : {ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT}) 168 for (auto T : {MVT::i32, MVT::i64}) 169 setOperationAction(Op, T, Custom); 170 171 // SIMD-specific configuration 172 if (Subtarget->hasSIMD128()) { 173 // Combine vector mask reductions into alltrue/anytrue 174 setTargetDAGCombine(ISD::SETCC); 175 176 // Convert vector to integer bitcasts to bitmask 177 setTargetDAGCombine(ISD::BITCAST); 178 179 // Hoist bitcasts out of shuffles 180 setTargetDAGCombine(ISD::VECTOR_SHUFFLE); 181 182 // Combine extends of extract_subvectors into widening ops 183 setTargetDAGCombine({ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}); 184 185 // Combine int_to_fp or fp_extend of extract_vectors and vice versa into 186 // conversions ops 187 setTargetDAGCombine({ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_EXTEND, 188 ISD::EXTRACT_SUBVECTOR}); 189 190 // Combine fp_to_{s,u}int_sat or fp_round of concat_vectors or vice versa 191 // into conversion ops 192 setTargetDAGCombine({ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT, 193 ISD::FP_ROUND, ISD::CONCAT_VECTORS}); 194 195 setTargetDAGCombine(ISD::TRUNCATE); 196 197 // Support saturating add for i8x16 and i16x8 198 for (auto Op : {ISD::SADDSAT, ISD::UADDSAT}) 199 for (auto T : {MVT::v16i8, MVT::v8i16}) 200 setOperationAction(Op, T, Legal); 201 202 // Support integer abs 203 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64}) 204 setOperationAction(ISD::ABS, T, Legal); 205 206 // Custom lower BUILD_VECTORs to minimize number of replace_lanes 207 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64, 208 MVT::v2f64}) 209 setOperationAction(ISD::BUILD_VECTOR, T, Custom); 210 211 // We have custom shuffle lowering to expose the shuffle mask 212 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64, 213 MVT::v2f64}) 214 setOperationAction(ISD::VECTOR_SHUFFLE, T, Custom); 215 216 // Support splatting 217 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64, 218 MVT::v2f64}) 219 setOperationAction(ISD::SPLAT_VECTOR, T, Legal); 220 221 // Custom lowering since wasm shifts must have a scalar shift amount 222 for (auto Op : {ISD::SHL, ISD::SRA, ISD::SRL}) 223 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64}) 224 setOperationAction(Op, T, Custom); 225 226 // Custom lower lane accesses to expand out variable indices 227 for (auto Op : {ISD::EXTRACT_VECTOR_ELT, ISD::INSERT_VECTOR_ELT}) 228 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64, 229 MVT::v2f64}) 230 setOperationAction(Op, T, Custom); 231 232 // There is no i8x16.mul instruction 233 setOperationAction(ISD::MUL, MVT::v16i8, Expand); 234 235 // There is no vector conditional select instruction 236 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v4f32, MVT::v2i64, 237 MVT::v2f64}) 238 setOperationAction(ISD::SELECT_CC, T, Expand); 239 240 // Expand integer operations supported for scalars but not SIMD 241 for (auto Op : 242 {ISD::SDIV, ISD::UDIV, ISD::SREM, ISD::UREM, ISD::ROTL, ISD::ROTR}) 243 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64}) 244 setOperationAction(Op, T, Expand); 245 246 // But we do have integer min and max operations 247 for (auto Op : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 248 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32}) 249 setOperationAction(Op, T, Legal); 250 251 // And we have popcnt for i8x16. It can be used to expand ctlz/cttz. 252 setOperationAction(ISD::CTPOP, MVT::v16i8, Legal); 253 setOperationAction(ISD::CTLZ, MVT::v16i8, Expand); 254 setOperationAction(ISD::CTTZ, MVT::v16i8, Expand); 255 256 // Custom lower bit counting operations for other types to scalarize them. 257 for (auto Op : {ISD::CTLZ, ISD::CTTZ, ISD::CTPOP}) 258 for (auto T : {MVT::v8i16, MVT::v4i32, MVT::v2i64}) 259 setOperationAction(Op, T, Custom); 260 261 // Expand float operations supported for scalars but not SIMD 262 for (auto Op : {ISD::FCOPYSIGN, ISD::FLOG, ISD::FLOG2, ISD::FLOG10, 263 ISD::FEXP, ISD::FEXP2}) 264 for (auto T : {MVT::v4f32, MVT::v2f64}) 265 setOperationAction(Op, T, Expand); 266 267 // Unsigned comparison operations are unavailable for i64x2 vectors. 268 for (auto CC : {ISD::SETUGT, ISD::SETUGE, ISD::SETULT, ISD::SETULE}) 269 setCondCodeAction(CC, MVT::v2i64, Custom); 270 271 // 64x2 conversions are not in the spec 272 for (auto Op : 273 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT}) 274 for (auto T : {MVT::v2i64, MVT::v2f64}) 275 setOperationAction(Op, T, Expand); 276 277 // But saturating fp_to_int converstions are 278 for (auto Op : {ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT}) 279 setOperationAction(Op, MVT::v4i32, Custom); 280 281 // Support vector extending 282 for (auto T : MVT::integer_fixedlen_vector_valuetypes()) { 283 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, T, Custom); 284 setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, T, Custom); 285 } 286 } 287 288 // As a special case, these operators use the type to mean the type to 289 // sign-extend from. 290 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 291 if (!Subtarget->hasSignExt()) { 292 // Sign extends are legal only when extending a vector extract 293 auto Action = Subtarget->hasSIMD128() ? Custom : Expand; 294 for (auto T : {MVT::i8, MVT::i16, MVT::i32}) 295 setOperationAction(ISD::SIGN_EXTEND_INREG, T, Action); 296 } 297 for (auto T : MVT::integer_fixedlen_vector_valuetypes()) 298 setOperationAction(ISD::SIGN_EXTEND_INREG, T, Expand); 299 300 // Dynamic stack allocation: use the default expansion. 301 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 302 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 303 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVTPtr, Expand); 304 305 setOperationAction(ISD::FrameIndex, MVT::i32, Custom); 306 setOperationAction(ISD::FrameIndex, MVT::i64, Custom); 307 setOperationAction(ISD::CopyToReg, MVT::Other, Custom); 308 309 // Expand these forms; we pattern-match the forms that we can handle in isel. 310 for (auto T : {MVT::i32, MVT::i64, MVT::f32, MVT::f64}) 311 for (auto Op : {ISD::BR_CC, ISD::SELECT_CC}) 312 setOperationAction(Op, T, Expand); 313 314 // We have custom switch handling. 315 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 316 317 // WebAssembly doesn't have: 318 // - Floating-point extending loads. 319 // - Floating-point truncating stores. 320 // - i1 extending loads. 321 // - truncating SIMD stores and most extending loads 322 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 323 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 324 for (auto T : MVT::integer_valuetypes()) 325 for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD}) 326 setLoadExtAction(Ext, T, MVT::i1, Promote); 327 if (Subtarget->hasSIMD128()) { 328 for (auto T : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64, MVT::v4f32, 329 MVT::v2f64}) { 330 for (auto MemT : MVT::fixedlen_vector_valuetypes()) { 331 if (MVT(T) != MemT) { 332 setTruncStoreAction(T, MemT, Expand); 333 for (auto Ext : {ISD::EXTLOAD, ISD::ZEXTLOAD, ISD::SEXTLOAD}) 334 setLoadExtAction(Ext, T, MemT, Expand); 335 } 336 } 337 } 338 // But some vector extending loads are legal 339 for (auto Ext : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}) { 340 setLoadExtAction(Ext, MVT::v8i16, MVT::v8i8, Legal); 341 setLoadExtAction(Ext, MVT::v4i32, MVT::v4i16, Legal); 342 setLoadExtAction(Ext, MVT::v2i64, MVT::v2i32, Legal); 343 } 344 setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f32, Legal); 345 } 346 347 // Don't do anything clever with build_pairs 348 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 349 350 // Trap lowers to wasm unreachable 351 setOperationAction(ISD::TRAP, MVT::Other, Legal); 352 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 353 354 // Exception handling intrinsics 355 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 356 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 357 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 358 359 setMaxAtomicSizeInBitsSupported(64); 360 361 // Override the __gnu_f2h_ieee/__gnu_h2f_ieee names so that the f32 name is 362 // consistent with the f64 and f128 names. 363 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 364 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 365 366 // Define the emscripten name for return address helper. 367 // TODO: when implementing other Wasm backends, make this generic or only do 368 // this on emscripten depending on what they end up doing. 369 setLibcallName(RTLIB::RETURN_ADDRESS, "emscripten_return_address"); 370 371 // Always convert switches to br_tables unless there is only one case, which 372 // is equivalent to a simple branch. This reduces code size for wasm, and we 373 // defer possible jump table optimizations to the VM. 374 setMinimumJumpTableEntries(2); 375 } 376 377 MVT WebAssemblyTargetLowering::getPointerTy(const DataLayout &DL, 378 uint32_t AS) const { 379 if (AS == WebAssembly::WasmAddressSpace::WASM_ADDRESS_SPACE_EXTERNREF) 380 return MVT::externref; 381 if (AS == WebAssembly::WasmAddressSpace::WASM_ADDRESS_SPACE_FUNCREF) 382 return MVT::funcref; 383 return TargetLowering::getPointerTy(DL, AS); 384 } 385 386 MVT WebAssemblyTargetLowering::getPointerMemTy(const DataLayout &DL, 387 uint32_t AS) const { 388 if (AS == WebAssembly::WasmAddressSpace::WASM_ADDRESS_SPACE_EXTERNREF) 389 return MVT::externref; 390 if (AS == WebAssembly::WasmAddressSpace::WASM_ADDRESS_SPACE_FUNCREF) 391 return MVT::funcref; 392 return TargetLowering::getPointerMemTy(DL, AS); 393 } 394 395 TargetLowering::AtomicExpansionKind 396 WebAssemblyTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 397 // We have wasm instructions for these 398 switch (AI->getOperation()) { 399 case AtomicRMWInst::Add: 400 case AtomicRMWInst::Sub: 401 case AtomicRMWInst::And: 402 case AtomicRMWInst::Or: 403 case AtomicRMWInst::Xor: 404 case AtomicRMWInst::Xchg: 405 return AtomicExpansionKind::None; 406 default: 407 break; 408 } 409 return AtomicExpansionKind::CmpXChg; 410 } 411 412 bool WebAssemblyTargetLowering::shouldScalarizeBinop(SDValue VecOp) const { 413 // Implementation copied from X86TargetLowering. 414 unsigned Opc = VecOp.getOpcode(); 415 416 // Assume target opcodes can't be scalarized. 417 // TODO - do we have any exceptions? 418 if (Opc >= ISD::BUILTIN_OP_END) 419 return false; 420 421 // If the vector op is not supported, try to convert to scalar. 422 EVT VecVT = VecOp.getValueType(); 423 if (!isOperationLegalOrCustomOrPromote(Opc, VecVT)) 424 return true; 425 426 // If the vector op is supported, but the scalar op is not, the transform may 427 // not be worthwhile. 428 EVT ScalarVT = VecVT.getScalarType(); 429 return isOperationLegalOrCustomOrPromote(Opc, ScalarVT); 430 } 431 432 FastISel *WebAssemblyTargetLowering::createFastISel( 433 FunctionLoweringInfo &FuncInfo, const TargetLibraryInfo *LibInfo) const { 434 return WebAssembly::createFastISel(FuncInfo, LibInfo); 435 } 436 437 MVT WebAssemblyTargetLowering::getScalarShiftAmountTy(const DataLayout & /*DL*/, 438 EVT VT) const { 439 unsigned BitWidth = NextPowerOf2(VT.getSizeInBits() - 1); 440 if (BitWidth > 1 && BitWidth < 8) 441 BitWidth = 8; 442 443 if (BitWidth > 64) { 444 // The shift will be lowered to a libcall, and compiler-rt libcalls expect 445 // the count to be an i32. 446 BitWidth = 32; 447 assert(BitWidth >= Log2_32_Ceil(VT.getSizeInBits()) && 448 "32-bit shift counts ought to be enough for anyone"); 449 } 450 451 MVT Result = MVT::getIntegerVT(BitWidth); 452 assert(Result != MVT::INVALID_SIMPLE_VALUE_TYPE && 453 "Unable to represent scalar shift amount type"); 454 return Result; 455 } 456 457 // Lower an fp-to-int conversion operator from the LLVM opcode, which has an 458 // undefined result on invalid/overflow, to the WebAssembly opcode, which 459 // traps on invalid/overflow. 460 static MachineBasicBlock *LowerFPToInt(MachineInstr &MI, DebugLoc DL, 461 MachineBasicBlock *BB, 462 const TargetInstrInfo &TII, 463 bool IsUnsigned, bool Int64, 464 bool Float64, unsigned LoweredOpcode) { 465 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 466 467 Register OutReg = MI.getOperand(0).getReg(); 468 Register InReg = MI.getOperand(1).getReg(); 469 470 unsigned Abs = Float64 ? WebAssembly::ABS_F64 : WebAssembly::ABS_F32; 471 unsigned FConst = Float64 ? WebAssembly::CONST_F64 : WebAssembly::CONST_F32; 472 unsigned LT = Float64 ? WebAssembly::LT_F64 : WebAssembly::LT_F32; 473 unsigned GE = Float64 ? WebAssembly::GE_F64 : WebAssembly::GE_F32; 474 unsigned IConst = Int64 ? WebAssembly::CONST_I64 : WebAssembly::CONST_I32; 475 unsigned Eqz = WebAssembly::EQZ_I32; 476 unsigned And = WebAssembly::AND_I32; 477 int64_t Limit = Int64 ? INT64_MIN : INT32_MIN; 478 int64_t Substitute = IsUnsigned ? 0 : Limit; 479 double CmpVal = IsUnsigned ? -(double)Limit * 2.0 : -(double)Limit; 480 auto &Context = BB->getParent()->getFunction().getContext(); 481 Type *Ty = Float64 ? Type::getDoubleTy(Context) : Type::getFloatTy(Context); 482 483 const BasicBlock *LLVMBB = BB->getBasicBlock(); 484 MachineFunction *F = BB->getParent(); 485 MachineBasicBlock *TrueMBB = F->CreateMachineBasicBlock(LLVMBB); 486 MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(LLVMBB); 487 MachineBasicBlock *DoneMBB = F->CreateMachineBasicBlock(LLVMBB); 488 489 MachineFunction::iterator It = ++BB->getIterator(); 490 F->insert(It, FalseMBB); 491 F->insert(It, TrueMBB); 492 F->insert(It, DoneMBB); 493 494 // Transfer the remainder of BB and its successor edges to DoneMBB. 495 DoneMBB->splice(DoneMBB->begin(), BB, std::next(MI.getIterator()), BB->end()); 496 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 497 498 BB->addSuccessor(TrueMBB); 499 BB->addSuccessor(FalseMBB); 500 TrueMBB->addSuccessor(DoneMBB); 501 FalseMBB->addSuccessor(DoneMBB); 502 503 unsigned Tmp0, Tmp1, CmpReg, EqzReg, FalseReg, TrueReg; 504 Tmp0 = MRI.createVirtualRegister(MRI.getRegClass(InReg)); 505 Tmp1 = MRI.createVirtualRegister(MRI.getRegClass(InReg)); 506 CmpReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass); 507 EqzReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass); 508 FalseReg = MRI.createVirtualRegister(MRI.getRegClass(OutReg)); 509 TrueReg = MRI.createVirtualRegister(MRI.getRegClass(OutReg)); 510 511 MI.eraseFromParent(); 512 // For signed numbers, we can do a single comparison to determine whether 513 // fabs(x) is within range. 514 if (IsUnsigned) { 515 Tmp0 = InReg; 516 } else { 517 BuildMI(BB, DL, TII.get(Abs), Tmp0).addReg(InReg); 518 } 519 BuildMI(BB, DL, TII.get(FConst), Tmp1) 520 .addFPImm(cast<ConstantFP>(ConstantFP::get(Ty, CmpVal))); 521 BuildMI(BB, DL, TII.get(LT), CmpReg).addReg(Tmp0).addReg(Tmp1); 522 523 // For unsigned numbers, we have to do a separate comparison with zero. 524 if (IsUnsigned) { 525 Tmp1 = MRI.createVirtualRegister(MRI.getRegClass(InReg)); 526 Register SecondCmpReg = 527 MRI.createVirtualRegister(&WebAssembly::I32RegClass); 528 Register AndReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass); 529 BuildMI(BB, DL, TII.get(FConst), Tmp1) 530 .addFPImm(cast<ConstantFP>(ConstantFP::get(Ty, 0.0))); 531 BuildMI(BB, DL, TII.get(GE), SecondCmpReg).addReg(Tmp0).addReg(Tmp1); 532 BuildMI(BB, DL, TII.get(And), AndReg).addReg(CmpReg).addReg(SecondCmpReg); 533 CmpReg = AndReg; 534 } 535 536 BuildMI(BB, DL, TII.get(Eqz), EqzReg).addReg(CmpReg); 537 538 // Create the CFG diamond to select between doing the conversion or using 539 // the substitute value. 540 BuildMI(BB, DL, TII.get(WebAssembly::BR_IF)).addMBB(TrueMBB).addReg(EqzReg); 541 BuildMI(FalseMBB, DL, TII.get(LoweredOpcode), FalseReg).addReg(InReg); 542 BuildMI(FalseMBB, DL, TII.get(WebAssembly::BR)).addMBB(DoneMBB); 543 BuildMI(TrueMBB, DL, TII.get(IConst), TrueReg).addImm(Substitute); 544 BuildMI(*DoneMBB, DoneMBB->begin(), DL, TII.get(TargetOpcode::PHI), OutReg) 545 .addReg(FalseReg) 546 .addMBB(FalseMBB) 547 .addReg(TrueReg) 548 .addMBB(TrueMBB); 549 550 return DoneMBB; 551 } 552 553 static MachineBasicBlock * 554 LowerCallResults(MachineInstr &CallResults, DebugLoc DL, MachineBasicBlock *BB, 555 const WebAssemblySubtarget *Subtarget, 556 const TargetInstrInfo &TII) { 557 MachineInstr &CallParams = *CallResults.getPrevNode(); 558 assert(CallParams.getOpcode() == WebAssembly::CALL_PARAMS); 559 assert(CallResults.getOpcode() == WebAssembly::CALL_RESULTS || 560 CallResults.getOpcode() == WebAssembly::RET_CALL_RESULTS); 561 562 bool IsIndirect = 563 CallParams.getOperand(0).isReg() || CallParams.getOperand(0).isFI(); 564 bool IsRetCall = CallResults.getOpcode() == WebAssembly::RET_CALL_RESULTS; 565 566 bool IsFuncrefCall = false; 567 if (IsIndirect && CallParams.getOperand(0).isReg()) { 568 Register Reg = CallParams.getOperand(0).getReg(); 569 const MachineFunction *MF = BB->getParent(); 570 const MachineRegisterInfo &MRI = MF->getRegInfo(); 571 const TargetRegisterClass *TRC = MRI.getRegClass(Reg); 572 IsFuncrefCall = (TRC == &WebAssembly::FUNCREFRegClass); 573 assert(!IsFuncrefCall || Subtarget->hasReferenceTypes()); 574 } 575 576 unsigned CallOp; 577 if (IsIndirect && IsRetCall) { 578 CallOp = WebAssembly::RET_CALL_INDIRECT; 579 } else if (IsIndirect) { 580 CallOp = WebAssembly::CALL_INDIRECT; 581 } else if (IsRetCall) { 582 CallOp = WebAssembly::RET_CALL; 583 } else { 584 CallOp = WebAssembly::CALL; 585 } 586 587 MachineFunction &MF = *BB->getParent(); 588 const MCInstrDesc &MCID = TII.get(CallOp); 589 MachineInstrBuilder MIB(MF, MF.CreateMachineInstr(MCID, DL)); 590 591 // Move the function pointer to the end of the arguments for indirect calls 592 if (IsIndirect) { 593 auto FnPtr = CallParams.getOperand(0); 594 CallParams.removeOperand(0); 595 596 // For funcrefs, call_indirect is done through __funcref_call_table and the 597 // funcref is always installed in slot 0 of the table, therefore instead of 598 // having the function pointer added at the end of the params list, a zero 599 // (the index in 600 // __funcref_call_table is added). 601 if (IsFuncrefCall) { 602 Register RegZero = 603 MF.getRegInfo().createVirtualRegister(&WebAssembly::I32RegClass); 604 MachineInstrBuilder MIBC0 = 605 BuildMI(MF, DL, TII.get(WebAssembly::CONST_I32), RegZero).addImm(0); 606 607 BB->insert(CallResults.getIterator(), MIBC0); 608 MachineInstrBuilder(MF, CallParams).addReg(RegZero); 609 } else 610 CallParams.addOperand(FnPtr); 611 } 612 613 for (auto Def : CallResults.defs()) 614 MIB.add(Def); 615 616 if (IsIndirect) { 617 // Placeholder for the type index. 618 MIB.addImm(0); 619 // The table into which this call_indirect indexes. 620 MCSymbolWasm *Table = IsFuncrefCall 621 ? WebAssembly::getOrCreateFuncrefCallTableSymbol( 622 MF.getContext(), Subtarget) 623 : WebAssembly::getOrCreateFunctionTableSymbol( 624 MF.getContext(), Subtarget); 625 if (Subtarget->hasReferenceTypes()) { 626 MIB.addSym(Table); 627 } else { 628 // For the MVP there is at most one table whose number is 0, but we can't 629 // write a table symbol or issue relocations. Instead we just ensure the 630 // table is live and write a zero. 631 Table->setNoStrip(); 632 MIB.addImm(0); 633 } 634 } 635 636 for (auto Use : CallParams.uses()) 637 MIB.add(Use); 638 639 BB->insert(CallResults.getIterator(), MIB); 640 CallParams.eraseFromParent(); 641 CallResults.eraseFromParent(); 642 643 // If this is a funcref call, to avoid hidden GC roots, we need to clear the 644 // table slot with ref.null upon call_indirect return. 645 // 646 // This generates the following code, which comes right after a call_indirect 647 // of a funcref: 648 // 649 // i32.const 0 650 // ref.null func 651 // table.set __funcref_call_table 652 if (IsIndirect && IsFuncrefCall) { 653 MCSymbolWasm *Table = WebAssembly::getOrCreateFuncrefCallTableSymbol( 654 MF.getContext(), Subtarget); 655 Register RegZero = 656 MF.getRegInfo().createVirtualRegister(&WebAssembly::I32RegClass); 657 MachineInstr *Const0 = 658 BuildMI(MF, DL, TII.get(WebAssembly::CONST_I32), RegZero).addImm(0); 659 BB->insertAfter(MIB.getInstr()->getIterator(), Const0); 660 661 Register RegFuncref = 662 MF.getRegInfo().createVirtualRegister(&WebAssembly::FUNCREFRegClass); 663 MachineInstr *RefNull = 664 BuildMI(MF, DL, TII.get(WebAssembly::REF_NULL_FUNCREF), RegFuncref); 665 BB->insertAfter(Const0->getIterator(), RefNull); 666 667 MachineInstr *TableSet = 668 BuildMI(MF, DL, TII.get(WebAssembly::TABLE_SET_FUNCREF)) 669 .addSym(Table) 670 .addReg(RegZero) 671 .addReg(RegFuncref); 672 BB->insertAfter(RefNull->getIterator(), TableSet); 673 } 674 675 return BB; 676 } 677 678 MachineBasicBlock *WebAssemblyTargetLowering::EmitInstrWithCustomInserter( 679 MachineInstr &MI, MachineBasicBlock *BB) const { 680 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 681 DebugLoc DL = MI.getDebugLoc(); 682 683 switch (MI.getOpcode()) { 684 default: 685 llvm_unreachable("Unexpected instr type to insert"); 686 case WebAssembly::FP_TO_SINT_I32_F32: 687 return LowerFPToInt(MI, DL, BB, TII, false, false, false, 688 WebAssembly::I32_TRUNC_S_F32); 689 case WebAssembly::FP_TO_UINT_I32_F32: 690 return LowerFPToInt(MI, DL, BB, TII, true, false, false, 691 WebAssembly::I32_TRUNC_U_F32); 692 case WebAssembly::FP_TO_SINT_I64_F32: 693 return LowerFPToInt(MI, DL, BB, TII, false, true, false, 694 WebAssembly::I64_TRUNC_S_F32); 695 case WebAssembly::FP_TO_UINT_I64_F32: 696 return LowerFPToInt(MI, DL, BB, TII, true, true, false, 697 WebAssembly::I64_TRUNC_U_F32); 698 case WebAssembly::FP_TO_SINT_I32_F64: 699 return LowerFPToInt(MI, DL, BB, TII, false, false, true, 700 WebAssembly::I32_TRUNC_S_F64); 701 case WebAssembly::FP_TO_UINT_I32_F64: 702 return LowerFPToInt(MI, DL, BB, TII, true, false, true, 703 WebAssembly::I32_TRUNC_U_F64); 704 case WebAssembly::FP_TO_SINT_I64_F64: 705 return LowerFPToInt(MI, DL, BB, TII, false, true, true, 706 WebAssembly::I64_TRUNC_S_F64); 707 case WebAssembly::FP_TO_UINT_I64_F64: 708 return LowerFPToInt(MI, DL, BB, TII, true, true, true, 709 WebAssembly::I64_TRUNC_U_F64); 710 case WebAssembly::CALL_RESULTS: 711 case WebAssembly::RET_CALL_RESULTS: 712 return LowerCallResults(MI, DL, BB, Subtarget, TII); 713 } 714 } 715 716 const char * 717 WebAssemblyTargetLowering::getTargetNodeName(unsigned Opcode) const { 718 switch (static_cast<WebAssemblyISD::NodeType>(Opcode)) { 719 case WebAssemblyISD::FIRST_NUMBER: 720 case WebAssemblyISD::FIRST_MEM_OPCODE: 721 break; 722 #define HANDLE_NODETYPE(NODE) \ 723 case WebAssemblyISD::NODE: \ 724 return "WebAssemblyISD::" #NODE; 725 #define HANDLE_MEM_NODETYPE(NODE) HANDLE_NODETYPE(NODE) 726 #include "WebAssemblyISD.def" 727 #undef HANDLE_MEM_NODETYPE 728 #undef HANDLE_NODETYPE 729 } 730 return nullptr; 731 } 732 733 std::pair<unsigned, const TargetRegisterClass *> 734 WebAssemblyTargetLowering::getRegForInlineAsmConstraint( 735 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 736 // First, see if this is a constraint that directly corresponds to a 737 // WebAssembly register class. 738 if (Constraint.size() == 1) { 739 switch (Constraint[0]) { 740 case 'r': 741 assert(VT != MVT::iPTR && "Pointer MVT not expected here"); 742 if (Subtarget->hasSIMD128() && VT.isVector()) { 743 if (VT.getSizeInBits() == 128) 744 return std::make_pair(0U, &WebAssembly::V128RegClass); 745 } 746 if (VT.isInteger() && !VT.isVector()) { 747 if (VT.getSizeInBits() <= 32) 748 return std::make_pair(0U, &WebAssembly::I32RegClass); 749 if (VT.getSizeInBits() <= 64) 750 return std::make_pair(0U, &WebAssembly::I64RegClass); 751 } 752 if (VT.isFloatingPoint() && !VT.isVector()) { 753 switch (VT.getSizeInBits()) { 754 case 32: 755 return std::make_pair(0U, &WebAssembly::F32RegClass); 756 case 64: 757 return std::make_pair(0U, &WebAssembly::F64RegClass); 758 default: 759 break; 760 } 761 } 762 break; 763 default: 764 break; 765 } 766 } 767 768 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 769 } 770 771 bool WebAssemblyTargetLowering::isCheapToSpeculateCttz(Type *Ty) const { 772 // Assume ctz is a relatively cheap operation. 773 return true; 774 } 775 776 bool WebAssemblyTargetLowering::isCheapToSpeculateCtlz(Type *Ty) const { 777 // Assume clz is a relatively cheap operation. 778 return true; 779 } 780 781 bool WebAssemblyTargetLowering::isLegalAddressingMode(const DataLayout &DL, 782 const AddrMode &AM, 783 Type *Ty, unsigned AS, 784 Instruction *I) const { 785 // WebAssembly offsets are added as unsigned without wrapping. The 786 // isLegalAddressingMode gives us no way to determine if wrapping could be 787 // happening, so we approximate this by accepting only non-negative offsets. 788 if (AM.BaseOffs < 0) 789 return false; 790 791 // WebAssembly has no scale register operands. 792 if (AM.Scale != 0) 793 return false; 794 795 // Everything else is legal. 796 return true; 797 } 798 799 bool WebAssemblyTargetLowering::allowsMisalignedMemoryAccesses( 800 EVT /*VT*/, unsigned /*AddrSpace*/, Align /*Align*/, 801 MachineMemOperand::Flags /*Flags*/, unsigned *Fast) const { 802 // WebAssembly supports unaligned accesses, though it should be declared 803 // with the p2align attribute on loads and stores which do so, and there 804 // may be a performance impact. We tell LLVM they're "fast" because 805 // for the kinds of things that LLVM uses this for (merging adjacent stores 806 // of constants, etc.), WebAssembly implementations will either want the 807 // unaligned access or they'll split anyway. 808 if (Fast) 809 *Fast = 1; 810 return true; 811 } 812 813 bool WebAssemblyTargetLowering::isIntDivCheap(EVT VT, 814 AttributeList Attr) const { 815 // The current thinking is that wasm engines will perform this optimization, 816 // so we can save on code size. 817 return true; 818 } 819 820 bool WebAssemblyTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 821 EVT ExtT = ExtVal.getValueType(); 822 EVT MemT = cast<LoadSDNode>(ExtVal->getOperand(0))->getValueType(0); 823 return (ExtT == MVT::v8i16 && MemT == MVT::v8i8) || 824 (ExtT == MVT::v4i32 && MemT == MVT::v4i16) || 825 (ExtT == MVT::v2i64 && MemT == MVT::v2i32); 826 } 827 828 bool WebAssemblyTargetLowering::isOffsetFoldingLegal( 829 const GlobalAddressSDNode *GA) const { 830 // Wasm doesn't support function addresses with offsets 831 const GlobalValue *GV = GA->getGlobal(); 832 return isa<Function>(GV) ? false : TargetLowering::isOffsetFoldingLegal(GA); 833 } 834 835 bool WebAssemblyTargetLowering::shouldSinkOperands( 836 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 837 using namespace llvm::PatternMatch; 838 839 if (!I->getType()->isVectorTy() || !I->isShift()) 840 return false; 841 842 Value *V = I->getOperand(1); 843 // We dont need to sink constant splat. 844 if (dyn_cast<Constant>(V)) 845 return false; 846 847 if (match(V, m_Shuffle(m_InsertElt(m_Value(), m_Value(), m_ZeroInt()), 848 m_Value(), m_ZeroMask()))) { 849 // Sink insert 850 Ops.push_back(&cast<Instruction>(V)->getOperandUse(0)); 851 // Sink shuffle 852 Ops.push_back(&I->getOperandUse(1)); 853 return true; 854 } 855 856 return false; 857 } 858 859 EVT WebAssemblyTargetLowering::getSetCCResultType(const DataLayout &DL, 860 LLVMContext &C, 861 EVT VT) const { 862 if (VT.isVector()) 863 return VT.changeVectorElementTypeToInteger(); 864 865 // So far, all branch instructions in Wasm take an I32 condition. 866 // The default TargetLowering::getSetCCResultType returns the pointer size, 867 // which would be useful to reduce instruction counts when testing 868 // against 64-bit pointers/values if at some point Wasm supports that. 869 return EVT::getIntegerVT(C, 32); 870 } 871 872 bool WebAssemblyTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 873 const CallInst &I, 874 MachineFunction &MF, 875 unsigned Intrinsic) const { 876 switch (Intrinsic) { 877 case Intrinsic::wasm_memory_atomic_notify: 878 Info.opc = ISD::INTRINSIC_W_CHAIN; 879 Info.memVT = MVT::i32; 880 Info.ptrVal = I.getArgOperand(0); 881 Info.offset = 0; 882 Info.align = Align(4); 883 // atomic.notify instruction does not really load the memory specified with 884 // this argument, but MachineMemOperand should either be load or store, so 885 // we set this to a load. 886 // FIXME Volatile isn't really correct, but currently all LLVM atomic 887 // instructions are treated as volatiles in the backend, so we should be 888 // consistent. The same applies for wasm_atomic_wait intrinsics too. 889 Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad; 890 return true; 891 case Intrinsic::wasm_memory_atomic_wait32: 892 Info.opc = ISD::INTRINSIC_W_CHAIN; 893 Info.memVT = MVT::i32; 894 Info.ptrVal = I.getArgOperand(0); 895 Info.offset = 0; 896 Info.align = Align(4); 897 Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad; 898 return true; 899 case Intrinsic::wasm_memory_atomic_wait64: 900 Info.opc = ISD::INTRINSIC_W_CHAIN; 901 Info.memVT = MVT::i64; 902 Info.ptrVal = I.getArgOperand(0); 903 Info.offset = 0; 904 Info.align = Align(8); 905 Info.flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad; 906 return true; 907 case Intrinsic::wasm_loadf16_f32: 908 Info.opc = ISD::INTRINSIC_W_CHAIN; 909 Info.memVT = MVT::f16; 910 Info.ptrVal = I.getArgOperand(0); 911 Info.offset = 0; 912 Info.align = Align(2); 913 Info.flags = MachineMemOperand::MOLoad; 914 return true; 915 case Intrinsic::wasm_storef16_f32: 916 Info.opc = ISD::INTRINSIC_VOID; 917 Info.memVT = MVT::f16; 918 Info.ptrVal = I.getArgOperand(1); 919 Info.offset = 0; 920 Info.align = Align(2); 921 Info.flags = MachineMemOperand::MOStore; 922 return true; 923 default: 924 return false; 925 } 926 } 927 928 void WebAssemblyTargetLowering::computeKnownBitsForTargetNode( 929 const SDValue Op, KnownBits &Known, const APInt &DemandedElts, 930 const SelectionDAG &DAG, unsigned Depth) const { 931 switch (Op.getOpcode()) { 932 default: 933 break; 934 case ISD::INTRINSIC_WO_CHAIN: { 935 unsigned IntNo = Op.getConstantOperandVal(0); 936 switch (IntNo) { 937 default: 938 break; 939 case Intrinsic::wasm_bitmask: { 940 unsigned BitWidth = Known.getBitWidth(); 941 EVT VT = Op.getOperand(1).getSimpleValueType(); 942 unsigned PossibleBits = VT.getVectorNumElements(); 943 APInt ZeroMask = APInt::getHighBitsSet(BitWidth, BitWidth - PossibleBits); 944 Known.Zero |= ZeroMask; 945 break; 946 } 947 } 948 } 949 } 950 } 951 952 TargetLoweringBase::LegalizeTypeAction 953 WebAssemblyTargetLowering::getPreferredVectorAction(MVT VT) const { 954 if (VT.isFixedLengthVector()) { 955 MVT EltVT = VT.getVectorElementType(); 956 // We have legal vector types with these lane types, so widening the 957 // vector would let us use some of the lanes directly without having to 958 // extend or truncate values. 959 if (EltVT == MVT::i8 || EltVT == MVT::i16 || EltVT == MVT::i32 || 960 EltVT == MVT::i64 || EltVT == MVT::f32 || EltVT == MVT::f64) 961 return TypeWidenVector; 962 } 963 964 return TargetLoweringBase::getPreferredVectorAction(VT); 965 } 966 967 bool WebAssemblyTargetLowering::shouldSimplifyDemandedVectorElts( 968 SDValue Op, const TargetLoweringOpt &TLO) const { 969 // ISel process runs DAGCombiner after legalization; this step is called 970 // SelectionDAG optimization phase. This post-legalization combining process 971 // runs DAGCombiner on each node, and if there was a change to be made, 972 // re-runs legalization again on it and its user nodes to make sure 973 // everythiing is in a legalized state. 974 // 975 // The legalization calls lowering routines, and we do our custom lowering for 976 // build_vectors (LowerBUILD_VECTOR), which converts undef vector elements 977 // into zeros. But there is a set of routines in DAGCombiner that turns unused 978 // (= not demanded) nodes into undef, among which SimplifyDemandedVectorElts 979 // turns unused vector elements into undefs. But this routine does not work 980 // with our custom LowerBUILD_VECTOR, which turns undefs into zeros. This 981 // combination can result in a infinite loop, in which undefs are converted to 982 // zeros in legalization and back to undefs in combining. 983 // 984 // So after DAG is legalized, we prevent SimplifyDemandedVectorElts from 985 // running for build_vectors. 986 if (Op.getOpcode() == ISD::BUILD_VECTOR && TLO.LegalOps && TLO.LegalTys) 987 return false; 988 return true; 989 } 990 991 //===----------------------------------------------------------------------===// 992 // WebAssembly Lowering private implementation. 993 //===----------------------------------------------------------------------===// 994 995 //===----------------------------------------------------------------------===// 996 // Lowering Code 997 //===----------------------------------------------------------------------===// 998 999 static void fail(const SDLoc &DL, SelectionDAG &DAG, const char *Msg) { 1000 MachineFunction &MF = DAG.getMachineFunction(); 1001 DAG.getContext()->diagnose( 1002 DiagnosticInfoUnsupported(MF.getFunction(), Msg, DL.getDebugLoc())); 1003 } 1004 1005 // Test whether the given calling convention is supported. 1006 static bool callingConvSupported(CallingConv::ID CallConv) { 1007 // We currently support the language-independent target-independent 1008 // conventions. We don't yet have a way to annotate calls with properties like 1009 // "cold", and we don't have any call-clobbered registers, so these are mostly 1010 // all handled the same. 1011 return CallConv == CallingConv::C || CallConv == CallingConv::Fast || 1012 CallConv == CallingConv::Cold || 1013 CallConv == CallingConv::PreserveMost || 1014 CallConv == CallingConv::PreserveAll || 1015 CallConv == CallingConv::CXX_FAST_TLS || 1016 CallConv == CallingConv::WASM_EmscriptenInvoke || 1017 CallConv == CallingConv::Swift; 1018 } 1019 1020 SDValue 1021 WebAssemblyTargetLowering::LowerCall(CallLoweringInfo &CLI, 1022 SmallVectorImpl<SDValue> &InVals) const { 1023 SelectionDAG &DAG = CLI.DAG; 1024 SDLoc DL = CLI.DL; 1025 SDValue Chain = CLI.Chain; 1026 SDValue Callee = CLI.Callee; 1027 MachineFunction &MF = DAG.getMachineFunction(); 1028 auto Layout = MF.getDataLayout(); 1029 1030 CallingConv::ID CallConv = CLI.CallConv; 1031 if (!callingConvSupported(CallConv)) 1032 fail(DL, DAG, 1033 "WebAssembly doesn't support language-specific or target-specific " 1034 "calling conventions yet"); 1035 if (CLI.IsPatchPoint) 1036 fail(DL, DAG, "WebAssembly doesn't support patch point yet"); 1037 1038 if (CLI.IsTailCall) { 1039 auto NoTail = [&](const char *Msg) { 1040 if (CLI.CB && CLI.CB->isMustTailCall()) 1041 fail(DL, DAG, Msg); 1042 CLI.IsTailCall = false; 1043 }; 1044 1045 if (!Subtarget->hasTailCall()) 1046 NoTail("WebAssembly 'tail-call' feature not enabled"); 1047 1048 // Varargs calls cannot be tail calls because the buffer is on the stack 1049 if (CLI.IsVarArg) 1050 NoTail("WebAssembly does not support varargs tail calls"); 1051 1052 // Do not tail call unless caller and callee return types match 1053 const Function &F = MF.getFunction(); 1054 const TargetMachine &TM = getTargetMachine(); 1055 Type *RetTy = F.getReturnType(); 1056 SmallVector<MVT, 4> CallerRetTys; 1057 SmallVector<MVT, 4> CalleeRetTys; 1058 computeLegalValueVTs(F, TM, RetTy, CallerRetTys); 1059 computeLegalValueVTs(F, TM, CLI.RetTy, CalleeRetTys); 1060 bool TypesMatch = CallerRetTys.size() == CalleeRetTys.size() && 1061 std::equal(CallerRetTys.begin(), CallerRetTys.end(), 1062 CalleeRetTys.begin()); 1063 if (!TypesMatch) 1064 NoTail("WebAssembly tail call requires caller and callee return types to " 1065 "match"); 1066 1067 // If pointers to local stack values are passed, we cannot tail call 1068 if (CLI.CB) { 1069 for (auto &Arg : CLI.CB->args()) { 1070 Value *Val = Arg.get(); 1071 // Trace the value back through pointer operations 1072 while (true) { 1073 Value *Src = Val->stripPointerCastsAndAliases(); 1074 if (auto *GEP = dyn_cast<GetElementPtrInst>(Src)) 1075 Src = GEP->getPointerOperand(); 1076 if (Val == Src) 1077 break; 1078 Val = Src; 1079 } 1080 if (isa<AllocaInst>(Val)) { 1081 NoTail( 1082 "WebAssembly does not support tail calling with stack arguments"); 1083 break; 1084 } 1085 } 1086 } 1087 } 1088 1089 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 1090 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 1091 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 1092 1093 // The generic code may have added an sret argument. If we're lowering an 1094 // invoke function, the ABI requires that the function pointer be the first 1095 // argument, so we may have to swap the arguments. 1096 if (CallConv == CallingConv::WASM_EmscriptenInvoke && Outs.size() >= 2 && 1097 Outs[0].Flags.isSRet()) { 1098 std::swap(Outs[0], Outs[1]); 1099 std::swap(OutVals[0], OutVals[1]); 1100 } 1101 1102 bool HasSwiftSelfArg = false; 1103 bool HasSwiftErrorArg = false; 1104 unsigned NumFixedArgs = 0; 1105 for (unsigned I = 0; I < Outs.size(); ++I) { 1106 const ISD::OutputArg &Out = Outs[I]; 1107 SDValue &OutVal = OutVals[I]; 1108 HasSwiftSelfArg |= Out.Flags.isSwiftSelf(); 1109 HasSwiftErrorArg |= Out.Flags.isSwiftError(); 1110 if (Out.Flags.isNest()) 1111 fail(DL, DAG, "WebAssembly hasn't implemented nest arguments"); 1112 if (Out.Flags.isInAlloca()) 1113 fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments"); 1114 if (Out.Flags.isInConsecutiveRegs()) 1115 fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments"); 1116 if (Out.Flags.isInConsecutiveRegsLast()) 1117 fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments"); 1118 if (Out.Flags.isByVal() && Out.Flags.getByValSize() != 0) { 1119 auto &MFI = MF.getFrameInfo(); 1120 int FI = MFI.CreateStackObject(Out.Flags.getByValSize(), 1121 Out.Flags.getNonZeroByValAlign(), 1122 /*isSS=*/false); 1123 SDValue SizeNode = 1124 DAG.getConstant(Out.Flags.getByValSize(), DL, MVT::i32); 1125 SDValue FINode = DAG.getFrameIndex(FI, getPointerTy(Layout)); 1126 Chain = DAG.getMemcpy(Chain, DL, FINode, OutVal, SizeNode, 1127 Out.Flags.getNonZeroByValAlign(), 1128 /*isVolatile*/ false, /*AlwaysInline=*/false, 1129 /*CI=*/nullptr, std::nullopt, MachinePointerInfo(), 1130 MachinePointerInfo()); 1131 OutVal = FINode; 1132 } 1133 // Count the number of fixed args *after* legalization. 1134 NumFixedArgs += Out.IsFixed; 1135 } 1136 1137 bool IsVarArg = CLI.IsVarArg; 1138 auto PtrVT = getPointerTy(Layout); 1139 1140 // For swiftcc, emit additional swiftself and swifterror arguments 1141 // if there aren't. These additional arguments are also added for callee 1142 // signature They are necessary to match callee and caller signature for 1143 // indirect call. 1144 if (CallConv == CallingConv::Swift) { 1145 if (!HasSwiftSelfArg) { 1146 NumFixedArgs++; 1147 ISD::OutputArg Arg; 1148 Arg.Flags.setSwiftSelf(); 1149 CLI.Outs.push_back(Arg); 1150 SDValue ArgVal = DAG.getUNDEF(PtrVT); 1151 CLI.OutVals.push_back(ArgVal); 1152 } 1153 if (!HasSwiftErrorArg) { 1154 NumFixedArgs++; 1155 ISD::OutputArg Arg; 1156 Arg.Flags.setSwiftError(); 1157 CLI.Outs.push_back(Arg); 1158 SDValue ArgVal = DAG.getUNDEF(PtrVT); 1159 CLI.OutVals.push_back(ArgVal); 1160 } 1161 } 1162 1163 // Analyze operands of the call, assigning locations to each operand. 1164 SmallVector<CCValAssign, 16> ArgLocs; 1165 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 1166 1167 if (IsVarArg) { 1168 // Outgoing non-fixed arguments are placed in a buffer. First 1169 // compute their offsets and the total amount of buffer space needed. 1170 for (unsigned I = NumFixedArgs; I < Outs.size(); ++I) { 1171 const ISD::OutputArg &Out = Outs[I]; 1172 SDValue &Arg = OutVals[I]; 1173 EVT VT = Arg.getValueType(); 1174 assert(VT != MVT::iPTR && "Legalized args should be concrete"); 1175 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 1176 Align Alignment = 1177 std::max(Out.Flags.getNonZeroOrigAlign(), Layout.getABITypeAlign(Ty)); 1178 unsigned Offset = 1179 CCInfo.AllocateStack(Layout.getTypeAllocSize(Ty), Alignment); 1180 CCInfo.addLoc(CCValAssign::getMem(ArgLocs.size(), VT.getSimpleVT(), 1181 Offset, VT.getSimpleVT(), 1182 CCValAssign::Full)); 1183 } 1184 } 1185 1186 unsigned NumBytes = CCInfo.getAlignedCallFrameSize(); 1187 1188 SDValue FINode; 1189 if (IsVarArg && NumBytes) { 1190 // For non-fixed arguments, next emit stores to store the argument values 1191 // to the stack buffer at the offsets computed above. 1192 MaybeAlign StackAlign = Layout.getStackAlignment(); 1193 assert(StackAlign && "data layout string is missing stack alignment"); 1194 int FI = MF.getFrameInfo().CreateStackObject(NumBytes, *StackAlign, 1195 /*isSS=*/false); 1196 unsigned ValNo = 0; 1197 SmallVector<SDValue, 8> Chains; 1198 for (SDValue Arg : drop_begin(OutVals, NumFixedArgs)) { 1199 assert(ArgLocs[ValNo].getValNo() == ValNo && 1200 "ArgLocs should remain in order and only hold varargs args"); 1201 unsigned Offset = ArgLocs[ValNo++].getLocMemOffset(); 1202 FINode = DAG.getFrameIndex(FI, getPointerTy(Layout)); 1203 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, FINode, 1204 DAG.getConstant(Offset, DL, PtrVT)); 1205 Chains.push_back( 1206 DAG.getStore(Chain, DL, Arg, Add, 1207 MachinePointerInfo::getFixedStack(MF, FI, Offset))); 1208 } 1209 if (!Chains.empty()) 1210 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 1211 } else if (IsVarArg) { 1212 FINode = DAG.getIntPtrConstant(0, DL); 1213 } 1214 1215 if (Callee->getOpcode() == ISD::GlobalAddress) { 1216 // If the callee is a GlobalAddress node (quite common, every direct call 1217 // is) turn it into a TargetGlobalAddress node so that LowerGlobalAddress 1218 // doesn't at MO_GOT which is not needed for direct calls. 1219 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Callee); 1220 Callee = DAG.getTargetGlobalAddress(GA->getGlobal(), DL, 1221 getPointerTy(DAG.getDataLayout()), 1222 GA->getOffset()); 1223 Callee = DAG.getNode(WebAssemblyISD::Wrapper, DL, 1224 getPointerTy(DAG.getDataLayout()), Callee); 1225 } 1226 1227 // Compute the operands for the CALLn node. 1228 SmallVector<SDValue, 16> Ops; 1229 Ops.push_back(Chain); 1230 Ops.push_back(Callee); 1231 1232 // Add all fixed arguments. Note that for non-varargs calls, NumFixedArgs 1233 // isn't reliable. 1234 Ops.append(OutVals.begin(), 1235 IsVarArg ? OutVals.begin() + NumFixedArgs : OutVals.end()); 1236 // Add a pointer to the vararg buffer. 1237 if (IsVarArg) 1238 Ops.push_back(FINode); 1239 1240 SmallVector<EVT, 8> InTys; 1241 for (const auto &In : Ins) { 1242 assert(!In.Flags.isByVal() && "byval is not valid for return values"); 1243 assert(!In.Flags.isNest() && "nest is not valid for return values"); 1244 if (In.Flags.isInAlloca()) 1245 fail(DL, DAG, "WebAssembly hasn't implemented inalloca return values"); 1246 if (In.Flags.isInConsecutiveRegs()) 1247 fail(DL, DAG, "WebAssembly hasn't implemented cons regs return values"); 1248 if (In.Flags.isInConsecutiveRegsLast()) 1249 fail(DL, DAG, 1250 "WebAssembly hasn't implemented cons regs last return values"); 1251 // Ignore In.getNonZeroOrigAlign() because all our arguments are passed in 1252 // registers. 1253 InTys.push_back(In.VT); 1254 } 1255 1256 // Lastly, if this is a call to a funcref we need to add an instruction 1257 // table.set to the chain and transform the call. 1258 if (CLI.CB && WebAssembly::isWebAssemblyFuncrefType( 1259 CLI.CB->getCalledOperand()->getType())) { 1260 // In the absence of function references proposal where a funcref call is 1261 // lowered to call_ref, using reference types we generate a table.set to set 1262 // the funcref to a special table used solely for this purpose, followed by 1263 // a call_indirect. Here we just generate the table set, and return the 1264 // SDValue of the table.set so that LowerCall can finalize the lowering by 1265 // generating the call_indirect. 1266 SDValue Chain = Ops[0]; 1267 1268 MCSymbolWasm *Table = WebAssembly::getOrCreateFuncrefCallTableSymbol( 1269 MF.getContext(), Subtarget); 1270 SDValue Sym = DAG.getMCSymbol(Table, PtrVT); 1271 SDValue TableSlot = DAG.getConstant(0, DL, MVT::i32); 1272 SDValue TableSetOps[] = {Chain, Sym, TableSlot, Callee}; 1273 SDValue TableSet = DAG.getMemIntrinsicNode( 1274 WebAssemblyISD::TABLE_SET, DL, DAG.getVTList(MVT::Other), TableSetOps, 1275 MVT::funcref, 1276 // Machine Mem Operand args 1277 MachinePointerInfo( 1278 WebAssembly::WasmAddressSpace::WASM_ADDRESS_SPACE_FUNCREF), 1279 CLI.CB->getCalledOperand()->getPointerAlignment(DAG.getDataLayout()), 1280 MachineMemOperand::MOStore); 1281 1282 Ops[0] = TableSet; // The new chain is the TableSet itself 1283 } 1284 1285 if (CLI.IsTailCall) { 1286 // ret_calls do not return values to the current frame 1287 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 1288 return DAG.getNode(WebAssemblyISD::RET_CALL, DL, NodeTys, Ops); 1289 } 1290 1291 InTys.push_back(MVT::Other); 1292 SDVTList InTyList = DAG.getVTList(InTys); 1293 SDValue Res = DAG.getNode(WebAssemblyISD::CALL, DL, InTyList, Ops); 1294 1295 for (size_t I = 0; I < Ins.size(); ++I) 1296 InVals.push_back(Res.getValue(I)); 1297 1298 // Return the chain 1299 return Res.getValue(Ins.size()); 1300 } 1301 1302 bool WebAssemblyTargetLowering::CanLowerReturn( 1303 CallingConv::ID /*CallConv*/, MachineFunction & /*MF*/, bool /*IsVarArg*/, 1304 const SmallVectorImpl<ISD::OutputArg> &Outs, 1305 LLVMContext & /*Context*/) const { 1306 // WebAssembly can only handle returning tuples with multivalue enabled 1307 return WebAssembly::canLowerReturn(Outs.size(), Subtarget); 1308 } 1309 1310 SDValue WebAssemblyTargetLowering::LowerReturn( 1311 SDValue Chain, CallingConv::ID CallConv, bool /*IsVarArg*/, 1312 const SmallVectorImpl<ISD::OutputArg> &Outs, 1313 const SmallVectorImpl<SDValue> &OutVals, const SDLoc &DL, 1314 SelectionDAG &DAG) const { 1315 assert(WebAssembly::canLowerReturn(Outs.size(), Subtarget) && 1316 "MVP WebAssembly can only return up to one value"); 1317 if (!callingConvSupported(CallConv)) 1318 fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions"); 1319 1320 SmallVector<SDValue, 4> RetOps(1, Chain); 1321 RetOps.append(OutVals.begin(), OutVals.end()); 1322 Chain = DAG.getNode(WebAssemblyISD::RETURN, DL, MVT::Other, RetOps); 1323 1324 // Record the number and types of the return values. 1325 for (const ISD::OutputArg &Out : Outs) { 1326 assert(!Out.Flags.isByVal() && "byval is not valid for return values"); 1327 assert(!Out.Flags.isNest() && "nest is not valid for return values"); 1328 assert(Out.IsFixed && "non-fixed return value is not valid"); 1329 if (Out.Flags.isInAlloca()) 1330 fail(DL, DAG, "WebAssembly hasn't implemented inalloca results"); 1331 if (Out.Flags.isInConsecutiveRegs()) 1332 fail(DL, DAG, "WebAssembly hasn't implemented cons regs results"); 1333 if (Out.Flags.isInConsecutiveRegsLast()) 1334 fail(DL, DAG, "WebAssembly hasn't implemented cons regs last results"); 1335 } 1336 1337 return Chain; 1338 } 1339 1340 SDValue WebAssemblyTargetLowering::LowerFormalArguments( 1341 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 1342 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 1343 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 1344 if (!callingConvSupported(CallConv)) 1345 fail(DL, DAG, "WebAssembly doesn't support non-C calling conventions"); 1346 1347 MachineFunction &MF = DAG.getMachineFunction(); 1348 auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>(); 1349 1350 // Set up the incoming ARGUMENTS value, which serves to represent the liveness 1351 // of the incoming values before they're represented by virtual registers. 1352 MF.getRegInfo().addLiveIn(WebAssembly::ARGUMENTS); 1353 1354 bool HasSwiftErrorArg = false; 1355 bool HasSwiftSelfArg = false; 1356 for (const ISD::InputArg &In : Ins) { 1357 HasSwiftSelfArg |= In.Flags.isSwiftSelf(); 1358 HasSwiftErrorArg |= In.Flags.isSwiftError(); 1359 if (In.Flags.isInAlloca()) 1360 fail(DL, DAG, "WebAssembly hasn't implemented inalloca arguments"); 1361 if (In.Flags.isNest()) 1362 fail(DL, DAG, "WebAssembly hasn't implemented nest arguments"); 1363 if (In.Flags.isInConsecutiveRegs()) 1364 fail(DL, DAG, "WebAssembly hasn't implemented cons regs arguments"); 1365 if (In.Flags.isInConsecutiveRegsLast()) 1366 fail(DL, DAG, "WebAssembly hasn't implemented cons regs last arguments"); 1367 // Ignore In.getNonZeroOrigAlign() because all our arguments are passed in 1368 // registers. 1369 InVals.push_back(In.Used ? DAG.getNode(WebAssemblyISD::ARGUMENT, DL, In.VT, 1370 DAG.getTargetConstant(InVals.size(), 1371 DL, MVT::i32)) 1372 : DAG.getUNDEF(In.VT)); 1373 1374 // Record the number and types of arguments. 1375 MFI->addParam(In.VT); 1376 } 1377 1378 // For swiftcc, emit additional swiftself and swifterror arguments 1379 // if there aren't. These additional arguments are also added for callee 1380 // signature They are necessary to match callee and caller signature for 1381 // indirect call. 1382 auto PtrVT = getPointerTy(MF.getDataLayout()); 1383 if (CallConv == CallingConv::Swift) { 1384 if (!HasSwiftSelfArg) { 1385 MFI->addParam(PtrVT); 1386 } 1387 if (!HasSwiftErrorArg) { 1388 MFI->addParam(PtrVT); 1389 } 1390 } 1391 // Varargs are copied into a buffer allocated by the caller, and a pointer to 1392 // the buffer is passed as an argument. 1393 if (IsVarArg) { 1394 MVT PtrVT = getPointerTy(MF.getDataLayout()); 1395 Register VarargVreg = 1396 MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrVT)); 1397 MFI->setVarargBufferVreg(VarargVreg); 1398 Chain = DAG.getCopyToReg( 1399 Chain, DL, VarargVreg, 1400 DAG.getNode(WebAssemblyISD::ARGUMENT, DL, PtrVT, 1401 DAG.getTargetConstant(Ins.size(), DL, MVT::i32))); 1402 MFI->addParam(PtrVT); 1403 } 1404 1405 // Record the number and types of arguments and results. 1406 SmallVector<MVT, 4> Params; 1407 SmallVector<MVT, 4> Results; 1408 computeSignatureVTs(MF.getFunction().getFunctionType(), &MF.getFunction(), 1409 MF.getFunction(), DAG.getTarget(), Params, Results); 1410 for (MVT VT : Results) 1411 MFI->addResult(VT); 1412 // TODO: Use signatures in WebAssemblyMachineFunctionInfo too and unify 1413 // the param logic here with ComputeSignatureVTs 1414 assert(MFI->getParams().size() == Params.size() && 1415 std::equal(MFI->getParams().begin(), MFI->getParams().end(), 1416 Params.begin())); 1417 1418 return Chain; 1419 } 1420 1421 void WebAssemblyTargetLowering::ReplaceNodeResults( 1422 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const { 1423 switch (N->getOpcode()) { 1424 case ISD::SIGN_EXTEND_INREG: 1425 // Do not add any results, signifying that N should not be custom lowered 1426 // after all. This happens because simd128 turns on custom lowering for 1427 // SIGN_EXTEND_INREG, but for non-vector sign extends the result might be an 1428 // illegal type. 1429 break; 1430 case ISD::SIGN_EXTEND_VECTOR_INREG: 1431 case ISD::ZERO_EXTEND_VECTOR_INREG: 1432 // Do not add any results, signifying that N should not be custom lowered. 1433 // EXTEND_VECTOR_INREG is implemented for some vectors, but not all. 1434 break; 1435 default: 1436 llvm_unreachable( 1437 "ReplaceNodeResults not implemented for this op for WebAssembly!"); 1438 } 1439 } 1440 1441 //===----------------------------------------------------------------------===// 1442 // Custom lowering hooks. 1443 //===----------------------------------------------------------------------===// 1444 1445 SDValue WebAssemblyTargetLowering::LowerOperation(SDValue Op, 1446 SelectionDAG &DAG) const { 1447 SDLoc DL(Op); 1448 switch (Op.getOpcode()) { 1449 default: 1450 llvm_unreachable("unimplemented operation lowering"); 1451 return SDValue(); 1452 case ISD::FrameIndex: 1453 return LowerFrameIndex(Op, DAG); 1454 case ISD::GlobalAddress: 1455 return LowerGlobalAddress(Op, DAG); 1456 case ISD::GlobalTLSAddress: 1457 return LowerGlobalTLSAddress(Op, DAG); 1458 case ISD::ExternalSymbol: 1459 return LowerExternalSymbol(Op, DAG); 1460 case ISD::JumpTable: 1461 return LowerJumpTable(Op, DAG); 1462 case ISD::BR_JT: 1463 return LowerBR_JT(Op, DAG); 1464 case ISD::VASTART: 1465 return LowerVASTART(Op, DAG); 1466 case ISD::BlockAddress: 1467 case ISD::BRIND: 1468 fail(DL, DAG, "WebAssembly hasn't implemented computed gotos"); 1469 return SDValue(); 1470 case ISD::RETURNADDR: 1471 return LowerRETURNADDR(Op, DAG); 1472 case ISD::FRAMEADDR: 1473 return LowerFRAMEADDR(Op, DAG); 1474 case ISD::CopyToReg: 1475 return LowerCopyToReg(Op, DAG); 1476 case ISD::EXTRACT_VECTOR_ELT: 1477 case ISD::INSERT_VECTOR_ELT: 1478 return LowerAccessVectorElement(Op, DAG); 1479 case ISD::INTRINSIC_VOID: 1480 case ISD::INTRINSIC_WO_CHAIN: 1481 case ISD::INTRINSIC_W_CHAIN: 1482 return LowerIntrinsic(Op, DAG); 1483 case ISD::SIGN_EXTEND_INREG: 1484 return LowerSIGN_EXTEND_INREG(Op, DAG); 1485 case ISD::ZERO_EXTEND_VECTOR_INREG: 1486 case ISD::SIGN_EXTEND_VECTOR_INREG: 1487 return LowerEXTEND_VECTOR_INREG(Op, DAG); 1488 case ISD::BUILD_VECTOR: 1489 return LowerBUILD_VECTOR(Op, DAG); 1490 case ISD::VECTOR_SHUFFLE: 1491 return LowerVECTOR_SHUFFLE(Op, DAG); 1492 case ISD::SETCC: 1493 return LowerSETCC(Op, DAG); 1494 case ISD::SHL: 1495 case ISD::SRA: 1496 case ISD::SRL: 1497 return LowerShift(Op, DAG); 1498 case ISD::FP_TO_SINT_SAT: 1499 case ISD::FP_TO_UINT_SAT: 1500 return LowerFP_TO_INT_SAT(Op, DAG); 1501 case ISD::LOAD: 1502 return LowerLoad(Op, DAG); 1503 case ISD::STORE: 1504 return LowerStore(Op, DAG); 1505 case ISD::CTPOP: 1506 case ISD::CTLZ: 1507 case ISD::CTTZ: 1508 return DAG.UnrollVectorOp(Op.getNode()); 1509 case ISD::CLEAR_CACHE: 1510 report_fatal_error("llvm.clear_cache is not supported on wasm"); 1511 } 1512 } 1513 1514 static bool IsWebAssemblyGlobal(SDValue Op) { 1515 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) 1516 return WebAssembly::isWasmVarAddressSpace(GA->getAddressSpace()); 1517 1518 return false; 1519 } 1520 1521 static std::optional<unsigned> IsWebAssemblyLocal(SDValue Op, 1522 SelectionDAG &DAG) { 1523 const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op); 1524 if (!FI) 1525 return std::nullopt; 1526 1527 auto &MF = DAG.getMachineFunction(); 1528 return WebAssemblyFrameLowering::getLocalForStackObject(MF, FI->getIndex()); 1529 } 1530 1531 SDValue WebAssemblyTargetLowering::LowerStore(SDValue Op, 1532 SelectionDAG &DAG) const { 1533 SDLoc DL(Op); 1534 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); 1535 const SDValue &Value = SN->getValue(); 1536 const SDValue &Base = SN->getBasePtr(); 1537 const SDValue &Offset = SN->getOffset(); 1538 1539 if (IsWebAssemblyGlobal(Base)) { 1540 if (!Offset->isUndef()) 1541 report_fatal_error("unexpected offset when storing to webassembly global", 1542 false); 1543 1544 SDVTList Tys = DAG.getVTList(MVT::Other); 1545 SDValue Ops[] = {SN->getChain(), Value, Base}; 1546 return DAG.getMemIntrinsicNode(WebAssemblyISD::GLOBAL_SET, DL, Tys, Ops, 1547 SN->getMemoryVT(), SN->getMemOperand()); 1548 } 1549 1550 if (std::optional<unsigned> Local = IsWebAssemblyLocal(Base, DAG)) { 1551 if (!Offset->isUndef()) 1552 report_fatal_error("unexpected offset when storing to webassembly local", 1553 false); 1554 1555 SDValue Idx = DAG.getTargetConstant(*Local, Base, MVT::i32); 1556 SDVTList Tys = DAG.getVTList(MVT::Other); // The chain. 1557 SDValue Ops[] = {SN->getChain(), Idx, Value}; 1558 return DAG.getNode(WebAssemblyISD::LOCAL_SET, DL, Tys, Ops); 1559 } 1560 1561 if (WebAssembly::isWasmVarAddressSpace(SN->getAddressSpace())) 1562 report_fatal_error( 1563 "Encountered an unlowerable store to the wasm_var address space", 1564 false); 1565 1566 return Op; 1567 } 1568 1569 SDValue WebAssemblyTargetLowering::LowerLoad(SDValue Op, 1570 SelectionDAG &DAG) const { 1571 SDLoc DL(Op); 1572 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); 1573 const SDValue &Base = LN->getBasePtr(); 1574 const SDValue &Offset = LN->getOffset(); 1575 1576 if (IsWebAssemblyGlobal(Base)) { 1577 if (!Offset->isUndef()) 1578 report_fatal_error( 1579 "unexpected offset when loading from webassembly global", false); 1580 1581 SDVTList Tys = DAG.getVTList(LN->getValueType(0), MVT::Other); 1582 SDValue Ops[] = {LN->getChain(), Base}; 1583 return DAG.getMemIntrinsicNode(WebAssemblyISD::GLOBAL_GET, DL, Tys, Ops, 1584 LN->getMemoryVT(), LN->getMemOperand()); 1585 } 1586 1587 if (std::optional<unsigned> Local = IsWebAssemblyLocal(Base, DAG)) { 1588 if (!Offset->isUndef()) 1589 report_fatal_error( 1590 "unexpected offset when loading from webassembly local", false); 1591 1592 SDValue Idx = DAG.getTargetConstant(*Local, Base, MVT::i32); 1593 EVT LocalVT = LN->getValueType(0); 1594 SDValue LocalGet = DAG.getNode(WebAssemblyISD::LOCAL_GET, DL, LocalVT, 1595 {LN->getChain(), Idx}); 1596 SDValue Result = DAG.getMergeValues({LocalGet, LN->getChain()}, DL); 1597 assert(Result->getNumValues() == 2 && "Loads must carry a chain!"); 1598 return Result; 1599 } 1600 1601 if (WebAssembly::isWasmVarAddressSpace(LN->getAddressSpace())) 1602 report_fatal_error( 1603 "Encountered an unlowerable load from the wasm_var address space", 1604 false); 1605 1606 return Op; 1607 } 1608 1609 SDValue WebAssemblyTargetLowering::LowerCopyToReg(SDValue Op, 1610 SelectionDAG &DAG) const { 1611 SDValue Src = Op.getOperand(2); 1612 if (isa<FrameIndexSDNode>(Src.getNode())) { 1613 // CopyToReg nodes don't support FrameIndex operands. Other targets select 1614 // the FI to some LEA-like instruction, but since we don't have that, we 1615 // need to insert some kind of instruction that can take an FI operand and 1616 // produces a value usable by CopyToReg (i.e. in a vreg). So insert a dummy 1617 // local.copy between Op and its FI operand. 1618 SDValue Chain = Op.getOperand(0); 1619 SDLoc DL(Op); 1620 Register Reg = cast<RegisterSDNode>(Op.getOperand(1))->getReg(); 1621 EVT VT = Src.getValueType(); 1622 SDValue Copy(DAG.getMachineNode(VT == MVT::i32 ? WebAssembly::COPY_I32 1623 : WebAssembly::COPY_I64, 1624 DL, VT, Src), 1625 0); 1626 return Op.getNode()->getNumValues() == 1 1627 ? DAG.getCopyToReg(Chain, DL, Reg, Copy) 1628 : DAG.getCopyToReg(Chain, DL, Reg, Copy, 1629 Op.getNumOperands() == 4 ? Op.getOperand(3) 1630 : SDValue()); 1631 } 1632 return SDValue(); 1633 } 1634 1635 SDValue WebAssemblyTargetLowering::LowerFrameIndex(SDValue Op, 1636 SelectionDAG &DAG) const { 1637 int FI = cast<FrameIndexSDNode>(Op)->getIndex(); 1638 return DAG.getTargetFrameIndex(FI, Op.getValueType()); 1639 } 1640 1641 SDValue WebAssemblyTargetLowering::LowerRETURNADDR(SDValue Op, 1642 SelectionDAG &DAG) const { 1643 SDLoc DL(Op); 1644 1645 if (!Subtarget->getTargetTriple().isOSEmscripten()) { 1646 fail(DL, DAG, 1647 "Non-Emscripten WebAssembly hasn't implemented " 1648 "__builtin_return_address"); 1649 return SDValue(); 1650 } 1651 1652 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 1653 return SDValue(); 1654 1655 unsigned Depth = Op.getConstantOperandVal(0); 1656 MakeLibCallOptions CallOptions; 1657 return makeLibCall(DAG, RTLIB::RETURN_ADDRESS, Op.getValueType(), 1658 {DAG.getConstant(Depth, DL, MVT::i32)}, CallOptions, DL) 1659 .first; 1660 } 1661 1662 SDValue WebAssemblyTargetLowering::LowerFRAMEADDR(SDValue Op, 1663 SelectionDAG &DAG) const { 1664 // Non-zero depths are not supported by WebAssembly currently. Use the 1665 // legalizer's default expansion, which is to return 0 (what this function is 1666 // documented to do). 1667 if (Op.getConstantOperandVal(0) > 0) 1668 return SDValue(); 1669 1670 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true); 1671 EVT VT = Op.getValueType(); 1672 Register FP = 1673 Subtarget->getRegisterInfo()->getFrameRegister(DAG.getMachineFunction()); 1674 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), FP, VT); 1675 } 1676 1677 SDValue 1678 WebAssemblyTargetLowering::LowerGlobalTLSAddress(SDValue Op, 1679 SelectionDAG &DAG) const { 1680 SDLoc DL(Op); 1681 const auto *GA = cast<GlobalAddressSDNode>(Op); 1682 1683 MachineFunction &MF = DAG.getMachineFunction(); 1684 if (!MF.getSubtarget<WebAssemblySubtarget>().hasBulkMemory()) 1685 report_fatal_error("cannot use thread-local storage without bulk memory", 1686 false); 1687 1688 const GlobalValue *GV = GA->getGlobal(); 1689 1690 // Currently only Emscripten supports dynamic linking with threads. Therefore, 1691 // on other targets, if we have thread-local storage, only the local-exec 1692 // model is possible. 1693 auto model = Subtarget->getTargetTriple().isOSEmscripten() 1694 ? GV->getThreadLocalMode() 1695 : GlobalValue::LocalExecTLSModel; 1696 1697 // Unsupported TLS modes 1698 assert(model != GlobalValue::NotThreadLocal); 1699 assert(model != GlobalValue::InitialExecTLSModel); 1700 1701 if (model == GlobalValue::LocalExecTLSModel || 1702 model == GlobalValue::LocalDynamicTLSModel || 1703 (model == GlobalValue::GeneralDynamicTLSModel && 1704 getTargetMachine().shouldAssumeDSOLocal(GV))) { 1705 // For DSO-local TLS variables we use offset from __tls_base 1706 1707 MVT PtrVT = getPointerTy(DAG.getDataLayout()); 1708 auto GlobalGet = PtrVT == MVT::i64 ? WebAssembly::GLOBAL_GET_I64 1709 : WebAssembly::GLOBAL_GET_I32; 1710 const char *BaseName = MF.createExternalSymbolName("__tls_base"); 1711 1712 SDValue BaseAddr( 1713 DAG.getMachineNode(GlobalGet, DL, PtrVT, 1714 DAG.getTargetExternalSymbol(BaseName, PtrVT)), 1715 0); 1716 1717 SDValue TLSOffset = DAG.getTargetGlobalAddress( 1718 GV, DL, PtrVT, GA->getOffset(), WebAssemblyII::MO_TLS_BASE_REL); 1719 SDValue SymOffset = 1720 DAG.getNode(WebAssemblyISD::WrapperREL, DL, PtrVT, TLSOffset); 1721 1722 return DAG.getNode(ISD::ADD, DL, PtrVT, BaseAddr, SymOffset); 1723 } 1724 1725 assert(model == GlobalValue::GeneralDynamicTLSModel); 1726 1727 EVT VT = Op.getValueType(); 1728 return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT, 1729 DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT, 1730 GA->getOffset(), 1731 WebAssemblyII::MO_GOT_TLS)); 1732 } 1733 1734 SDValue WebAssemblyTargetLowering::LowerGlobalAddress(SDValue Op, 1735 SelectionDAG &DAG) const { 1736 SDLoc DL(Op); 1737 const auto *GA = cast<GlobalAddressSDNode>(Op); 1738 EVT VT = Op.getValueType(); 1739 assert(GA->getTargetFlags() == 0 && 1740 "Unexpected target flags on generic GlobalAddressSDNode"); 1741 if (!WebAssembly::isValidAddressSpace(GA->getAddressSpace())) 1742 fail(DL, DAG, "Invalid address space for WebAssembly target"); 1743 1744 unsigned OperandFlags = 0; 1745 const GlobalValue *GV = GA->getGlobal(); 1746 // Since WebAssembly tables cannot yet be shared accross modules, we don't 1747 // need special treatment for tables in PIC mode. 1748 if (isPositionIndependent() && 1749 !WebAssembly::isWebAssemblyTableType(GV->getValueType())) { 1750 if (getTargetMachine().shouldAssumeDSOLocal(GV)) { 1751 MachineFunction &MF = DAG.getMachineFunction(); 1752 MVT PtrVT = getPointerTy(MF.getDataLayout()); 1753 const char *BaseName; 1754 if (GV->getValueType()->isFunctionTy()) { 1755 BaseName = MF.createExternalSymbolName("__table_base"); 1756 OperandFlags = WebAssemblyII::MO_TABLE_BASE_REL; 1757 } else { 1758 BaseName = MF.createExternalSymbolName("__memory_base"); 1759 OperandFlags = WebAssemblyII::MO_MEMORY_BASE_REL; 1760 } 1761 SDValue BaseAddr = 1762 DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT, 1763 DAG.getTargetExternalSymbol(BaseName, PtrVT)); 1764 1765 SDValue SymAddr = DAG.getNode( 1766 WebAssemblyISD::WrapperREL, DL, VT, 1767 DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT, GA->getOffset(), 1768 OperandFlags)); 1769 1770 return DAG.getNode(ISD::ADD, DL, VT, BaseAddr, SymAddr); 1771 } 1772 OperandFlags = WebAssemblyII::MO_GOT; 1773 } 1774 1775 return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT, 1776 DAG.getTargetGlobalAddress(GA->getGlobal(), DL, VT, 1777 GA->getOffset(), OperandFlags)); 1778 } 1779 1780 SDValue 1781 WebAssemblyTargetLowering::LowerExternalSymbol(SDValue Op, 1782 SelectionDAG &DAG) const { 1783 SDLoc DL(Op); 1784 const auto *ES = cast<ExternalSymbolSDNode>(Op); 1785 EVT VT = Op.getValueType(); 1786 assert(ES->getTargetFlags() == 0 && 1787 "Unexpected target flags on generic ExternalSymbolSDNode"); 1788 return DAG.getNode(WebAssemblyISD::Wrapper, DL, VT, 1789 DAG.getTargetExternalSymbol(ES->getSymbol(), VT)); 1790 } 1791 1792 SDValue WebAssemblyTargetLowering::LowerJumpTable(SDValue Op, 1793 SelectionDAG &DAG) const { 1794 // There's no need for a Wrapper node because we always incorporate a jump 1795 // table operand into a BR_TABLE instruction, rather than ever 1796 // materializing it in a register. 1797 const JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 1798 return DAG.getTargetJumpTable(JT->getIndex(), Op.getValueType(), 1799 JT->getTargetFlags()); 1800 } 1801 1802 SDValue WebAssemblyTargetLowering::LowerBR_JT(SDValue Op, 1803 SelectionDAG &DAG) const { 1804 SDLoc DL(Op); 1805 SDValue Chain = Op.getOperand(0); 1806 const auto *JT = cast<JumpTableSDNode>(Op.getOperand(1)); 1807 SDValue Index = Op.getOperand(2); 1808 assert(JT->getTargetFlags() == 0 && "WebAssembly doesn't set target flags"); 1809 1810 SmallVector<SDValue, 8> Ops; 1811 Ops.push_back(Chain); 1812 Ops.push_back(Index); 1813 1814 MachineJumpTableInfo *MJTI = DAG.getMachineFunction().getJumpTableInfo(); 1815 const auto &MBBs = MJTI->getJumpTables()[JT->getIndex()].MBBs; 1816 1817 // Add an operand for each case. 1818 for (auto *MBB : MBBs) 1819 Ops.push_back(DAG.getBasicBlock(MBB)); 1820 1821 // Add the first MBB as a dummy default target for now. This will be replaced 1822 // with the proper default target (and the preceding range check eliminated) 1823 // if possible by WebAssemblyFixBrTableDefaults. 1824 Ops.push_back(DAG.getBasicBlock(*MBBs.begin())); 1825 return DAG.getNode(WebAssemblyISD::BR_TABLE, DL, MVT::Other, Ops); 1826 } 1827 1828 SDValue WebAssemblyTargetLowering::LowerVASTART(SDValue Op, 1829 SelectionDAG &DAG) const { 1830 SDLoc DL(Op); 1831 EVT PtrVT = getPointerTy(DAG.getMachineFunction().getDataLayout()); 1832 1833 auto *MFI = DAG.getMachineFunction().getInfo<WebAssemblyFunctionInfo>(); 1834 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 1835 1836 SDValue ArgN = DAG.getCopyFromReg(DAG.getEntryNode(), DL, 1837 MFI->getVarargBufferVreg(), PtrVT); 1838 return DAG.getStore(Op.getOperand(0), DL, ArgN, Op.getOperand(1), 1839 MachinePointerInfo(SV)); 1840 } 1841 1842 SDValue WebAssemblyTargetLowering::LowerIntrinsic(SDValue Op, 1843 SelectionDAG &DAG) const { 1844 MachineFunction &MF = DAG.getMachineFunction(); 1845 unsigned IntNo; 1846 switch (Op.getOpcode()) { 1847 case ISD::INTRINSIC_VOID: 1848 case ISD::INTRINSIC_W_CHAIN: 1849 IntNo = Op.getConstantOperandVal(1); 1850 break; 1851 case ISD::INTRINSIC_WO_CHAIN: 1852 IntNo = Op.getConstantOperandVal(0); 1853 break; 1854 default: 1855 llvm_unreachable("Invalid intrinsic"); 1856 } 1857 SDLoc DL(Op); 1858 1859 switch (IntNo) { 1860 default: 1861 return SDValue(); // Don't custom lower most intrinsics. 1862 1863 case Intrinsic::wasm_lsda: { 1864 auto PtrVT = getPointerTy(MF.getDataLayout()); 1865 const char *SymName = MF.createExternalSymbolName( 1866 "GCC_except_table" + std::to_string(MF.getFunctionNumber())); 1867 if (isPositionIndependent()) { 1868 SDValue Node = DAG.getTargetExternalSymbol( 1869 SymName, PtrVT, WebAssemblyII::MO_MEMORY_BASE_REL); 1870 const char *BaseName = MF.createExternalSymbolName("__memory_base"); 1871 SDValue BaseAddr = 1872 DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT, 1873 DAG.getTargetExternalSymbol(BaseName, PtrVT)); 1874 SDValue SymAddr = 1875 DAG.getNode(WebAssemblyISD::WrapperREL, DL, PtrVT, Node); 1876 return DAG.getNode(ISD::ADD, DL, PtrVT, BaseAddr, SymAddr); 1877 } 1878 SDValue Node = DAG.getTargetExternalSymbol(SymName, PtrVT); 1879 return DAG.getNode(WebAssemblyISD::Wrapper, DL, PtrVT, Node); 1880 } 1881 1882 case Intrinsic::wasm_shuffle: { 1883 // Drop in-chain and replace undefs, but otherwise pass through unchanged 1884 SDValue Ops[18]; 1885 size_t OpIdx = 0; 1886 Ops[OpIdx++] = Op.getOperand(1); 1887 Ops[OpIdx++] = Op.getOperand(2); 1888 while (OpIdx < 18) { 1889 const SDValue &MaskIdx = Op.getOperand(OpIdx + 1); 1890 if (MaskIdx.isUndef() || MaskIdx.getNode()->getAsZExtVal() >= 32) { 1891 bool isTarget = MaskIdx.getNode()->getOpcode() == ISD::TargetConstant; 1892 Ops[OpIdx++] = DAG.getConstant(0, DL, MVT::i32, isTarget); 1893 } else { 1894 Ops[OpIdx++] = MaskIdx; 1895 } 1896 } 1897 return DAG.getNode(WebAssemblyISD::SHUFFLE, DL, Op.getValueType(), Ops); 1898 } 1899 } 1900 } 1901 1902 SDValue 1903 WebAssemblyTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, 1904 SelectionDAG &DAG) const { 1905 SDLoc DL(Op); 1906 // If sign extension operations are disabled, allow sext_inreg only if operand 1907 // is a vector extract of an i8 or i16 lane. SIMD does not depend on sign 1908 // extension operations, but allowing sext_inreg in this context lets us have 1909 // simple patterns to select extract_lane_s instructions. Expanding sext_inreg 1910 // everywhere would be simpler in this file, but would necessitate large and 1911 // brittle patterns to undo the expansion and select extract_lane_s 1912 // instructions. 1913 assert(!Subtarget->hasSignExt() && Subtarget->hasSIMD128()); 1914 if (Op.getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT) 1915 return SDValue(); 1916 1917 const SDValue &Extract = Op.getOperand(0); 1918 MVT VecT = Extract.getOperand(0).getSimpleValueType(); 1919 if (VecT.getVectorElementType().getSizeInBits() > 32) 1920 return SDValue(); 1921 MVT ExtractedLaneT = 1922 cast<VTSDNode>(Op.getOperand(1).getNode())->getVT().getSimpleVT(); 1923 MVT ExtractedVecT = 1924 MVT::getVectorVT(ExtractedLaneT, 128 / ExtractedLaneT.getSizeInBits()); 1925 if (ExtractedVecT == VecT) 1926 return Op; 1927 1928 // Bitcast vector to appropriate type to ensure ISel pattern coverage 1929 const SDNode *Index = Extract.getOperand(1).getNode(); 1930 if (!isa<ConstantSDNode>(Index)) 1931 return SDValue(); 1932 unsigned IndexVal = Index->getAsZExtVal(); 1933 unsigned Scale = 1934 ExtractedVecT.getVectorNumElements() / VecT.getVectorNumElements(); 1935 assert(Scale > 1); 1936 SDValue NewIndex = 1937 DAG.getConstant(IndexVal * Scale, DL, Index->getValueType(0)); 1938 SDValue NewExtract = DAG.getNode( 1939 ISD::EXTRACT_VECTOR_ELT, DL, Extract.getValueType(), 1940 DAG.getBitcast(ExtractedVecT, Extract.getOperand(0)), NewIndex); 1941 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, Op.getValueType(), NewExtract, 1942 Op.getOperand(1)); 1943 } 1944 1945 SDValue 1946 WebAssemblyTargetLowering::LowerEXTEND_VECTOR_INREG(SDValue Op, 1947 SelectionDAG &DAG) const { 1948 SDLoc DL(Op); 1949 EVT VT = Op.getValueType(); 1950 SDValue Src = Op.getOperand(0); 1951 EVT SrcVT = Src.getValueType(); 1952 1953 if (SrcVT.getVectorElementType() == MVT::i1 || 1954 SrcVT.getVectorElementType() == MVT::i64) 1955 return SDValue(); 1956 1957 assert(VT.getScalarSizeInBits() % SrcVT.getScalarSizeInBits() == 0 && 1958 "Unexpected extension factor."); 1959 unsigned Scale = VT.getScalarSizeInBits() / SrcVT.getScalarSizeInBits(); 1960 1961 if (Scale != 2 && Scale != 4 && Scale != 8) 1962 return SDValue(); 1963 1964 unsigned Ext; 1965 switch (Op.getOpcode()) { 1966 case ISD::ZERO_EXTEND_VECTOR_INREG: 1967 Ext = WebAssemblyISD::EXTEND_LOW_U; 1968 break; 1969 case ISD::SIGN_EXTEND_VECTOR_INREG: 1970 Ext = WebAssemblyISD::EXTEND_LOW_S; 1971 break; 1972 } 1973 1974 SDValue Ret = Src; 1975 while (Scale != 1) { 1976 Ret = DAG.getNode(Ext, DL, 1977 Ret.getValueType() 1978 .widenIntegerVectorElementType(*DAG.getContext()) 1979 .getHalfNumVectorElementsVT(*DAG.getContext()), 1980 Ret); 1981 Scale /= 2; 1982 } 1983 assert(Ret.getValueType() == VT); 1984 return Ret; 1985 } 1986 1987 static SDValue LowerConvertLow(SDValue Op, SelectionDAG &DAG) { 1988 SDLoc DL(Op); 1989 if (Op.getValueType() != MVT::v2f64) 1990 return SDValue(); 1991 1992 auto GetConvertedLane = [](SDValue Op, unsigned &Opcode, SDValue &SrcVec, 1993 unsigned &Index) -> bool { 1994 switch (Op.getOpcode()) { 1995 case ISD::SINT_TO_FP: 1996 Opcode = WebAssemblyISD::CONVERT_LOW_S; 1997 break; 1998 case ISD::UINT_TO_FP: 1999 Opcode = WebAssemblyISD::CONVERT_LOW_U; 2000 break; 2001 case ISD::FP_EXTEND: 2002 Opcode = WebAssemblyISD::PROMOTE_LOW; 2003 break; 2004 default: 2005 return false; 2006 } 2007 2008 auto ExtractVector = Op.getOperand(0); 2009 if (ExtractVector.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 2010 return false; 2011 2012 if (!isa<ConstantSDNode>(ExtractVector.getOperand(1).getNode())) 2013 return false; 2014 2015 SrcVec = ExtractVector.getOperand(0); 2016 Index = ExtractVector.getConstantOperandVal(1); 2017 return true; 2018 }; 2019 2020 unsigned LHSOpcode, RHSOpcode, LHSIndex, RHSIndex; 2021 SDValue LHSSrcVec, RHSSrcVec; 2022 if (!GetConvertedLane(Op.getOperand(0), LHSOpcode, LHSSrcVec, LHSIndex) || 2023 !GetConvertedLane(Op.getOperand(1), RHSOpcode, RHSSrcVec, RHSIndex)) 2024 return SDValue(); 2025 2026 if (LHSOpcode != RHSOpcode) 2027 return SDValue(); 2028 2029 MVT ExpectedSrcVT; 2030 switch (LHSOpcode) { 2031 case WebAssemblyISD::CONVERT_LOW_S: 2032 case WebAssemblyISD::CONVERT_LOW_U: 2033 ExpectedSrcVT = MVT::v4i32; 2034 break; 2035 case WebAssemblyISD::PROMOTE_LOW: 2036 ExpectedSrcVT = MVT::v4f32; 2037 break; 2038 } 2039 if (LHSSrcVec.getValueType() != ExpectedSrcVT) 2040 return SDValue(); 2041 2042 auto Src = LHSSrcVec; 2043 if (LHSIndex != 0 || RHSIndex != 1 || LHSSrcVec != RHSSrcVec) { 2044 // Shuffle the source vector so that the converted lanes are the low lanes. 2045 Src = DAG.getVectorShuffle( 2046 ExpectedSrcVT, DL, LHSSrcVec, RHSSrcVec, 2047 {static_cast<int>(LHSIndex), static_cast<int>(RHSIndex) + 4, -1, -1}); 2048 } 2049 return DAG.getNode(LHSOpcode, DL, MVT::v2f64, Src); 2050 } 2051 2052 SDValue WebAssemblyTargetLowering::LowerBUILD_VECTOR(SDValue Op, 2053 SelectionDAG &DAG) const { 2054 if (auto ConvertLow = LowerConvertLow(Op, DAG)) 2055 return ConvertLow; 2056 2057 SDLoc DL(Op); 2058 const EVT VecT = Op.getValueType(); 2059 const EVT LaneT = Op.getOperand(0).getValueType(); 2060 const size_t Lanes = Op.getNumOperands(); 2061 bool CanSwizzle = VecT == MVT::v16i8; 2062 2063 // BUILD_VECTORs are lowered to the instruction that initializes the highest 2064 // possible number of lanes at once followed by a sequence of replace_lane 2065 // instructions to individually initialize any remaining lanes. 2066 2067 // TODO: Tune this. For example, lanewise swizzling is very expensive, so 2068 // swizzled lanes should be given greater weight. 2069 2070 // TODO: Investigate looping rather than always extracting/replacing specific 2071 // lanes to fill gaps. 2072 2073 auto IsConstant = [](const SDValue &V) { 2074 return V.getOpcode() == ISD::Constant || V.getOpcode() == ISD::ConstantFP; 2075 }; 2076 2077 // Returns the source vector and index vector pair if they exist. Checks for: 2078 // (extract_vector_elt 2079 // $src, 2080 // (sign_extend_inreg (extract_vector_elt $indices, $i)) 2081 // ) 2082 auto GetSwizzleSrcs = [](size_t I, const SDValue &Lane) { 2083 auto Bail = std::make_pair(SDValue(), SDValue()); 2084 if (Lane->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 2085 return Bail; 2086 const SDValue &SwizzleSrc = Lane->getOperand(0); 2087 const SDValue &IndexExt = Lane->getOperand(1); 2088 if (IndexExt->getOpcode() != ISD::SIGN_EXTEND_INREG) 2089 return Bail; 2090 const SDValue &Index = IndexExt->getOperand(0); 2091 if (Index->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 2092 return Bail; 2093 const SDValue &SwizzleIndices = Index->getOperand(0); 2094 if (SwizzleSrc.getValueType() != MVT::v16i8 || 2095 SwizzleIndices.getValueType() != MVT::v16i8 || 2096 Index->getOperand(1)->getOpcode() != ISD::Constant || 2097 Index->getConstantOperandVal(1) != I) 2098 return Bail; 2099 return std::make_pair(SwizzleSrc, SwizzleIndices); 2100 }; 2101 2102 // If the lane is extracted from another vector at a constant index, return 2103 // that vector. The source vector must not have more lanes than the dest 2104 // because the shufflevector indices are in terms of the destination lanes and 2105 // would not be able to address the smaller individual source lanes. 2106 auto GetShuffleSrc = [&](const SDValue &Lane) { 2107 if (Lane->getOpcode() != ISD::EXTRACT_VECTOR_ELT) 2108 return SDValue(); 2109 if (!isa<ConstantSDNode>(Lane->getOperand(1).getNode())) 2110 return SDValue(); 2111 if (Lane->getOperand(0).getValueType().getVectorNumElements() > 2112 VecT.getVectorNumElements()) 2113 return SDValue(); 2114 return Lane->getOperand(0); 2115 }; 2116 2117 using ValueEntry = std::pair<SDValue, size_t>; 2118 SmallVector<ValueEntry, 16> SplatValueCounts; 2119 2120 using SwizzleEntry = std::pair<std::pair<SDValue, SDValue>, size_t>; 2121 SmallVector<SwizzleEntry, 16> SwizzleCounts; 2122 2123 using ShuffleEntry = std::pair<SDValue, size_t>; 2124 SmallVector<ShuffleEntry, 16> ShuffleCounts; 2125 2126 auto AddCount = [](auto &Counts, const auto &Val) { 2127 auto CountIt = 2128 llvm::find_if(Counts, [&Val](auto E) { return E.first == Val; }); 2129 if (CountIt == Counts.end()) { 2130 Counts.emplace_back(Val, 1); 2131 } else { 2132 CountIt->second++; 2133 } 2134 }; 2135 2136 auto GetMostCommon = [](auto &Counts) { 2137 auto CommonIt = 2138 std::max_element(Counts.begin(), Counts.end(), llvm::less_second()); 2139 assert(CommonIt != Counts.end() && "Unexpected all-undef build_vector"); 2140 return *CommonIt; 2141 }; 2142 2143 size_t NumConstantLanes = 0; 2144 2145 // Count eligible lanes for each type of vector creation op 2146 for (size_t I = 0; I < Lanes; ++I) { 2147 const SDValue &Lane = Op->getOperand(I); 2148 if (Lane.isUndef()) 2149 continue; 2150 2151 AddCount(SplatValueCounts, Lane); 2152 2153 if (IsConstant(Lane)) 2154 NumConstantLanes++; 2155 if (auto ShuffleSrc = GetShuffleSrc(Lane)) 2156 AddCount(ShuffleCounts, ShuffleSrc); 2157 if (CanSwizzle) { 2158 auto SwizzleSrcs = GetSwizzleSrcs(I, Lane); 2159 if (SwizzleSrcs.first) 2160 AddCount(SwizzleCounts, SwizzleSrcs); 2161 } 2162 } 2163 2164 SDValue SplatValue; 2165 size_t NumSplatLanes; 2166 std::tie(SplatValue, NumSplatLanes) = GetMostCommon(SplatValueCounts); 2167 2168 SDValue SwizzleSrc; 2169 SDValue SwizzleIndices; 2170 size_t NumSwizzleLanes = 0; 2171 if (SwizzleCounts.size()) 2172 std::forward_as_tuple(std::tie(SwizzleSrc, SwizzleIndices), 2173 NumSwizzleLanes) = GetMostCommon(SwizzleCounts); 2174 2175 // Shuffles can draw from up to two vectors, so find the two most common 2176 // sources. 2177 SDValue ShuffleSrc1, ShuffleSrc2; 2178 size_t NumShuffleLanes = 0; 2179 if (ShuffleCounts.size()) { 2180 std::tie(ShuffleSrc1, NumShuffleLanes) = GetMostCommon(ShuffleCounts); 2181 llvm::erase_if(ShuffleCounts, 2182 [&](const auto &Pair) { return Pair.first == ShuffleSrc1; }); 2183 } 2184 if (ShuffleCounts.size()) { 2185 size_t AdditionalShuffleLanes; 2186 std::tie(ShuffleSrc2, AdditionalShuffleLanes) = 2187 GetMostCommon(ShuffleCounts); 2188 NumShuffleLanes += AdditionalShuffleLanes; 2189 } 2190 2191 // Predicate returning true if the lane is properly initialized by the 2192 // original instruction 2193 std::function<bool(size_t, const SDValue &)> IsLaneConstructed; 2194 SDValue Result; 2195 // Prefer swizzles over shuffles over vector consts over splats 2196 if (NumSwizzleLanes >= NumShuffleLanes && 2197 NumSwizzleLanes >= NumConstantLanes && NumSwizzleLanes >= NumSplatLanes) { 2198 Result = DAG.getNode(WebAssemblyISD::SWIZZLE, DL, VecT, SwizzleSrc, 2199 SwizzleIndices); 2200 auto Swizzled = std::make_pair(SwizzleSrc, SwizzleIndices); 2201 IsLaneConstructed = [&, Swizzled](size_t I, const SDValue &Lane) { 2202 return Swizzled == GetSwizzleSrcs(I, Lane); 2203 }; 2204 } else if (NumShuffleLanes >= NumConstantLanes && 2205 NumShuffleLanes >= NumSplatLanes) { 2206 size_t DestLaneSize = VecT.getVectorElementType().getFixedSizeInBits() / 8; 2207 size_t DestLaneCount = VecT.getVectorNumElements(); 2208 size_t Scale1 = 1; 2209 size_t Scale2 = 1; 2210 SDValue Src1 = ShuffleSrc1; 2211 SDValue Src2 = ShuffleSrc2 ? ShuffleSrc2 : DAG.getUNDEF(VecT); 2212 if (Src1.getValueType() != VecT) { 2213 size_t LaneSize = 2214 Src1.getValueType().getVectorElementType().getFixedSizeInBits() / 8; 2215 assert(LaneSize > DestLaneSize); 2216 Scale1 = LaneSize / DestLaneSize; 2217 Src1 = DAG.getBitcast(VecT, Src1); 2218 } 2219 if (Src2.getValueType() != VecT) { 2220 size_t LaneSize = 2221 Src2.getValueType().getVectorElementType().getFixedSizeInBits() / 8; 2222 assert(LaneSize > DestLaneSize); 2223 Scale2 = LaneSize / DestLaneSize; 2224 Src2 = DAG.getBitcast(VecT, Src2); 2225 } 2226 2227 int Mask[16]; 2228 assert(DestLaneCount <= 16); 2229 for (size_t I = 0; I < DestLaneCount; ++I) { 2230 const SDValue &Lane = Op->getOperand(I); 2231 SDValue Src = GetShuffleSrc(Lane); 2232 if (Src == ShuffleSrc1) { 2233 Mask[I] = Lane->getConstantOperandVal(1) * Scale1; 2234 } else if (Src && Src == ShuffleSrc2) { 2235 Mask[I] = DestLaneCount + Lane->getConstantOperandVal(1) * Scale2; 2236 } else { 2237 Mask[I] = -1; 2238 } 2239 } 2240 ArrayRef<int> MaskRef(Mask, DestLaneCount); 2241 Result = DAG.getVectorShuffle(VecT, DL, Src1, Src2, MaskRef); 2242 IsLaneConstructed = [&](size_t, const SDValue &Lane) { 2243 auto Src = GetShuffleSrc(Lane); 2244 return Src == ShuffleSrc1 || (Src && Src == ShuffleSrc2); 2245 }; 2246 } else if (NumConstantLanes >= NumSplatLanes) { 2247 SmallVector<SDValue, 16> ConstLanes; 2248 for (const SDValue &Lane : Op->op_values()) { 2249 if (IsConstant(Lane)) { 2250 // Values may need to be fixed so that they will sign extend to be 2251 // within the expected range during ISel. Check whether the value is in 2252 // bounds based on the lane bit width and if it is out of bounds, lop 2253 // off the extra bits and subtract 2^n to reflect giving the high bit 2254 // value -2^(n-1) rather than +2^(n-1). Skip the i64 case because it 2255 // cannot possibly be out of range. 2256 auto *Const = dyn_cast<ConstantSDNode>(Lane.getNode()); 2257 int64_t Val = Const ? Const->getSExtValue() : 0; 2258 uint64_t LaneBits = 128 / Lanes; 2259 assert((LaneBits == 64 || Val >= -(1ll << (LaneBits - 1))) && 2260 "Unexpected out of bounds negative value"); 2261 if (Const && LaneBits != 64 && Val > (1ll << (LaneBits - 1)) - 1) { 2262 uint64_t Mask = (1ll << LaneBits) - 1; 2263 auto NewVal = (((uint64_t)Val & Mask) - (1ll << LaneBits)) & Mask; 2264 ConstLanes.push_back(DAG.getConstant(NewVal, SDLoc(Lane), LaneT)); 2265 } else { 2266 ConstLanes.push_back(Lane); 2267 } 2268 } else if (LaneT.isFloatingPoint()) { 2269 ConstLanes.push_back(DAG.getConstantFP(0, DL, LaneT)); 2270 } else { 2271 ConstLanes.push_back(DAG.getConstant(0, DL, LaneT)); 2272 } 2273 } 2274 Result = DAG.getBuildVector(VecT, DL, ConstLanes); 2275 IsLaneConstructed = [&IsConstant](size_t _, const SDValue &Lane) { 2276 return IsConstant(Lane); 2277 }; 2278 } else { 2279 size_t DestLaneSize = VecT.getVectorElementType().getFixedSizeInBits(); 2280 if (NumSplatLanes == 1 && Op->getOperand(0) == SplatValue && 2281 (DestLaneSize == 32 || DestLaneSize == 64)) { 2282 // Could be selected to load_zero. 2283 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecT, SplatValue); 2284 } else { 2285 // Use a splat (which might be selected as a load splat) 2286 Result = DAG.getSplatBuildVector(VecT, DL, SplatValue); 2287 } 2288 IsLaneConstructed = [&SplatValue](size_t _, const SDValue &Lane) { 2289 return Lane == SplatValue; 2290 }; 2291 } 2292 2293 assert(Result); 2294 assert(IsLaneConstructed); 2295 2296 // Add replace_lane instructions for any unhandled values 2297 for (size_t I = 0; I < Lanes; ++I) { 2298 const SDValue &Lane = Op->getOperand(I); 2299 if (!Lane.isUndef() && !IsLaneConstructed(I, Lane)) 2300 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VecT, Result, Lane, 2301 DAG.getConstant(I, DL, MVT::i32)); 2302 } 2303 2304 return Result; 2305 } 2306 2307 SDValue 2308 WebAssemblyTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 2309 SelectionDAG &DAG) const { 2310 SDLoc DL(Op); 2311 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op.getNode())->getMask(); 2312 MVT VecType = Op.getOperand(0).getSimpleValueType(); 2313 assert(VecType.is128BitVector() && "Unexpected shuffle vector type"); 2314 size_t LaneBytes = VecType.getVectorElementType().getSizeInBits() / 8; 2315 2316 // Space for two vector args and sixteen mask indices 2317 SDValue Ops[18]; 2318 size_t OpIdx = 0; 2319 Ops[OpIdx++] = Op.getOperand(0); 2320 Ops[OpIdx++] = Op.getOperand(1); 2321 2322 // Expand mask indices to byte indices and materialize them as operands 2323 for (int M : Mask) { 2324 for (size_t J = 0; J < LaneBytes; ++J) { 2325 // Lower undefs (represented by -1 in mask) to {0..J}, which use a 2326 // whole lane of vector input, to allow further reduction at VM. E.g. 2327 // match an 8x16 byte shuffle to an equivalent cheaper 32x4 shuffle. 2328 uint64_t ByteIndex = M == -1 ? J : (uint64_t)M * LaneBytes + J; 2329 Ops[OpIdx++] = DAG.getConstant(ByteIndex, DL, MVT::i32); 2330 } 2331 } 2332 2333 return DAG.getNode(WebAssemblyISD::SHUFFLE, DL, Op.getValueType(), Ops); 2334 } 2335 2336 SDValue WebAssemblyTargetLowering::LowerSETCC(SDValue Op, 2337 SelectionDAG &DAG) const { 2338 SDLoc DL(Op); 2339 // The legalizer does not know how to expand the unsupported comparison modes 2340 // of i64x2 vectors, so we manually unroll them here. 2341 assert(Op->getOperand(0)->getSimpleValueType(0) == MVT::v2i64); 2342 SmallVector<SDValue, 2> LHS, RHS; 2343 DAG.ExtractVectorElements(Op->getOperand(0), LHS); 2344 DAG.ExtractVectorElements(Op->getOperand(1), RHS); 2345 const SDValue &CC = Op->getOperand(2); 2346 auto MakeLane = [&](unsigned I) { 2347 return DAG.getNode(ISD::SELECT_CC, DL, MVT::i64, LHS[I], RHS[I], 2348 DAG.getConstant(uint64_t(-1), DL, MVT::i64), 2349 DAG.getConstant(uint64_t(0), DL, MVT::i64), CC); 2350 }; 2351 return DAG.getBuildVector(Op->getValueType(0), DL, 2352 {MakeLane(0), MakeLane(1)}); 2353 } 2354 2355 SDValue 2356 WebAssemblyTargetLowering::LowerAccessVectorElement(SDValue Op, 2357 SelectionDAG &DAG) const { 2358 // Allow constant lane indices, expand variable lane indices 2359 SDNode *IdxNode = Op.getOperand(Op.getNumOperands() - 1).getNode(); 2360 if (isa<ConstantSDNode>(IdxNode)) { 2361 // Ensure the index type is i32 to match the tablegen patterns 2362 uint64_t Idx = IdxNode->getAsZExtVal(); 2363 SmallVector<SDValue, 3> Ops(Op.getNode()->ops()); 2364 Ops[Op.getNumOperands() - 1] = 2365 DAG.getConstant(Idx, SDLoc(IdxNode), MVT::i32); 2366 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), Ops); 2367 } 2368 // Perform default expansion 2369 return SDValue(); 2370 } 2371 2372 static SDValue unrollVectorShift(SDValue Op, SelectionDAG &DAG) { 2373 EVT LaneT = Op.getSimpleValueType().getVectorElementType(); 2374 // 32-bit and 64-bit unrolled shifts will have proper semantics 2375 if (LaneT.bitsGE(MVT::i32)) 2376 return DAG.UnrollVectorOp(Op.getNode()); 2377 // Otherwise mask the shift value to get proper semantics from 32-bit shift 2378 SDLoc DL(Op); 2379 size_t NumLanes = Op.getSimpleValueType().getVectorNumElements(); 2380 SDValue Mask = DAG.getConstant(LaneT.getSizeInBits() - 1, DL, MVT::i32); 2381 unsigned ShiftOpcode = Op.getOpcode(); 2382 SmallVector<SDValue, 16> ShiftedElements; 2383 DAG.ExtractVectorElements(Op.getOperand(0), ShiftedElements, 0, 0, MVT::i32); 2384 SmallVector<SDValue, 16> ShiftElements; 2385 DAG.ExtractVectorElements(Op.getOperand(1), ShiftElements, 0, 0, MVT::i32); 2386 SmallVector<SDValue, 16> UnrolledOps; 2387 for (size_t i = 0; i < NumLanes; ++i) { 2388 SDValue MaskedShiftValue = 2389 DAG.getNode(ISD::AND, DL, MVT::i32, ShiftElements[i], Mask); 2390 SDValue ShiftedValue = ShiftedElements[i]; 2391 if (ShiftOpcode == ISD::SRA) 2392 ShiftedValue = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i32, 2393 ShiftedValue, DAG.getValueType(LaneT)); 2394 UnrolledOps.push_back( 2395 DAG.getNode(ShiftOpcode, DL, MVT::i32, ShiftedValue, MaskedShiftValue)); 2396 } 2397 return DAG.getBuildVector(Op.getValueType(), DL, UnrolledOps); 2398 } 2399 2400 SDValue WebAssemblyTargetLowering::LowerShift(SDValue Op, 2401 SelectionDAG &DAG) const { 2402 SDLoc DL(Op); 2403 2404 // Only manually lower vector shifts 2405 assert(Op.getSimpleValueType().isVector()); 2406 2407 uint64_t LaneBits = Op.getValueType().getScalarSizeInBits(); 2408 auto ShiftVal = Op.getOperand(1); 2409 2410 // Try to skip bitmask operation since it is implied inside shift instruction 2411 auto SkipImpliedMask = [](SDValue MaskOp, uint64_t MaskBits) { 2412 if (MaskOp.getOpcode() != ISD::AND) 2413 return MaskOp; 2414 SDValue LHS = MaskOp.getOperand(0); 2415 SDValue RHS = MaskOp.getOperand(1); 2416 if (MaskOp.getValueType().isVector()) { 2417 APInt MaskVal; 2418 if (!ISD::isConstantSplatVector(RHS.getNode(), MaskVal)) 2419 std::swap(LHS, RHS); 2420 2421 if (ISD::isConstantSplatVector(RHS.getNode(), MaskVal) && 2422 MaskVal == MaskBits) 2423 MaskOp = LHS; 2424 } else { 2425 if (!isa<ConstantSDNode>(RHS.getNode())) 2426 std::swap(LHS, RHS); 2427 2428 auto ConstantRHS = dyn_cast<ConstantSDNode>(RHS.getNode()); 2429 if (ConstantRHS && ConstantRHS->getAPIntValue() == MaskBits) 2430 MaskOp = LHS; 2431 } 2432 2433 return MaskOp; 2434 }; 2435 2436 // Skip vector and operation 2437 ShiftVal = SkipImpliedMask(ShiftVal, LaneBits - 1); 2438 ShiftVal = DAG.getSplatValue(ShiftVal); 2439 if (!ShiftVal) 2440 return unrollVectorShift(Op, DAG); 2441 2442 // Skip scalar and operation 2443 ShiftVal = SkipImpliedMask(ShiftVal, LaneBits - 1); 2444 // Use anyext because none of the high bits can affect the shift 2445 ShiftVal = DAG.getAnyExtOrTrunc(ShiftVal, DL, MVT::i32); 2446 2447 unsigned Opcode; 2448 switch (Op.getOpcode()) { 2449 case ISD::SHL: 2450 Opcode = WebAssemblyISD::VEC_SHL; 2451 break; 2452 case ISD::SRA: 2453 Opcode = WebAssemblyISD::VEC_SHR_S; 2454 break; 2455 case ISD::SRL: 2456 Opcode = WebAssemblyISD::VEC_SHR_U; 2457 break; 2458 default: 2459 llvm_unreachable("unexpected opcode"); 2460 } 2461 2462 return DAG.getNode(Opcode, DL, Op.getValueType(), Op.getOperand(0), ShiftVal); 2463 } 2464 2465 SDValue WebAssemblyTargetLowering::LowerFP_TO_INT_SAT(SDValue Op, 2466 SelectionDAG &DAG) const { 2467 SDLoc DL(Op); 2468 EVT ResT = Op.getValueType(); 2469 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2470 2471 if ((ResT == MVT::i32 || ResT == MVT::i64) && 2472 (SatVT == MVT::i32 || SatVT == MVT::i64)) 2473 return Op; 2474 2475 if (ResT == MVT::v4i32 && SatVT == MVT::i32) 2476 return Op; 2477 2478 return SDValue(); 2479 } 2480 2481 //===----------------------------------------------------------------------===// 2482 // Custom DAG combine hooks 2483 //===----------------------------------------------------------------------===// 2484 static SDValue 2485 performVECTOR_SHUFFLECombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 2486 auto &DAG = DCI.DAG; 2487 auto Shuffle = cast<ShuffleVectorSDNode>(N); 2488 2489 // Hoist vector bitcasts that don't change the number of lanes out of unary 2490 // shuffles, where they are less likely to get in the way of other combines. 2491 // (shuffle (vNxT1 (bitcast (vNxT0 x))), undef, mask) -> 2492 // (vNxT1 (bitcast (vNxT0 (shuffle x, undef, mask)))) 2493 SDValue Bitcast = N->getOperand(0); 2494 if (Bitcast.getOpcode() != ISD::BITCAST) 2495 return SDValue(); 2496 if (!N->getOperand(1).isUndef()) 2497 return SDValue(); 2498 SDValue CastOp = Bitcast.getOperand(0); 2499 EVT SrcType = CastOp.getValueType(); 2500 EVT DstType = Bitcast.getValueType(); 2501 if (!SrcType.is128BitVector() || 2502 SrcType.getVectorNumElements() != DstType.getVectorNumElements()) 2503 return SDValue(); 2504 SDValue NewShuffle = DAG.getVectorShuffle( 2505 SrcType, SDLoc(N), CastOp, DAG.getUNDEF(SrcType), Shuffle->getMask()); 2506 return DAG.getBitcast(DstType, NewShuffle); 2507 } 2508 2509 /// Convert ({u,s}itofp vec) --> ({u,s}itofp ({s,z}ext vec)) so it doesn't get 2510 /// split up into scalar instructions during legalization, and the vector 2511 /// extending instructions are selected in performVectorExtendCombine below. 2512 static SDValue 2513 performVectorExtendToFPCombine(SDNode *N, 2514 TargetLowering::DAGCombinerInfo &DCI) { 2515 auto &DAG = DCI.DAG; 2516 assert(N->getOpcode() == ISD::UINT_TO_FP || 2517 N->getOpcode() == ISD::SINT_TO_FP); 2518 2519 EVT InVT = N->getOperand(0)->getValueType(0); 2520 EVT ResVT = N->getValueType(0); 2521 MVT ExtVT; 2522 if (ResVT == MVT::v4f32 && (InVT == MVT::v4i16 || InVT == MVT::v4i8)) 2523 ExtVT = MVT::v4i32; 2524 else if (ResVT == MVT::v2f64 && (InVT == MVT::v2i16 || InVT == MVT::v2i8)) 2525 ExtVT = MVT::v2i32; 2526 else 2527 return SDValue(); 2528 2529 unsigned Op = 2530 N->getOpcode() == ISD::UINT_TO_FP ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND; 2531 SDValue Conv = DAG.getNode(Op, SDLoc(N), ExtVT, N->getOperand(0)); 2532 return DAG.getNode(N->getOpcode(), SDLoc(N), ResVT, Conv); 2533 } 2534 2535 static SDValue 2536 performVectorExtendCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 2537 auto &DAG = DCI.DAG; 2538 assert(N->getOpcode() == ISD::SIGN_EXTEND || 2539 N->getOpcode() == ISD::ZERO_EXTEND); 2540 2541 // Combine ({s,z}ext (extract_subvector src, i)) into a widening operation if 2542 // possible before the extract_subvector can be expanded. 2543 auto Extract = N->getOperand(0); 2544 if (Extract.getOpcode() != ISD::EXTRACT_SUBVECTOR) 2545 return SDValue(); 2546 auto Source = Extract.getOperand(0); 2547 auto *IndexNode = dyn_cast<ConstantSDNode>(Extract.getOperand(1)); 2548 if (IndexNode == nullptr) 2549 return SDValue(); 2550 auto Index = IndexNode->getZExtValue(); 2551 2552 // Only v8i8, v4i16, and v2i32 extracts can be widened, and only if the 2553 // extracted subvector is the low or high half of its source. 2554 EVT ResVT = N->getValueType(0); 2555 if (ResVT == MVT::v8i16) { 2556 if (Extract.getValueType() != MVT::v8i8 || 2557 Source.getValueType() != MVT::v16i8 || (Index != 0 && Index != 8)) 2558 return SDValue(); 2559 } else if (ResVT == MVT::v4i32) { 2560 if (Extract.getValueType() != MVT::v4i16 || 2561 Source.getValueType() != MVT::v8i16 || (Index != 0 && Index != 4)) 2562 return SDValue(); 2563 } else if (ResVT == MVT::v2i64) { 2564 if (Extract.getValueType() != MVT::v2i32 || 2565 Source.getValueType() != MVT::v4i32 || (Index != 0 && Index != 2)) 2566 return SDValue(); 2567 } else { 2568 return SDValue(); 2569 } 2570 2571 bool IsSext = N->getOpcode() == ISD::SIGN_EXTEND; 2572 bool IsLow = Index == 0; 2573 2574 unsigned Op = IsSext ? (IsLow ? WebAssemblyISD::EXTEND_LOW_S 2575 : WebAssemblyISD::EXTEND_HIGH_S) 2576 : (IsLow ? WebAssemblyISD::EXTEND_LOW_U 2577 : WebAssemblyISD::EXTEND_HIGH_U); 2578 2579 return DAG.getNode(Op, SDLoc(N), ResVT, Source); 2580 } 2581 2582 static SDValue 2583 performVectorTruncZeroCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { 2584 auto &DAG = DCI.DAG; 2585 2586 auto GetWasmConversionOp = [](unsigned Op) { 2587 switch (Op) { 2588 case ISD::FP_TO_SINT_SAT: 2589 return WebAssemblyISD::TRUNC_SAT_ZERO_S; 2590 case ISD::FP_TO_UINT_SAT: 2591 return WebAssemblyISD::TRUNC_SAT_ZERO_U; 2592 case ISD::FP_ROUND: 2593 return WebAssemblyISD::DEMOTE_ZERO; 2594 } 2595 llvm_unreachable("unexpected op"); 2596 }; 2597 2598 auto IsZeroSplat = [](SDValue SplatVal) { 2599 auto *Splat = dyn_cast<BuildVectorSDNode>(SplatVal.getNode()); 2600 APInt SplatValue, SplatUndef; 2601 unsigned SplatBitSize; 2602 bool HasAnyUndefs; 2603 // Endianness doesn't matter in this context because we are looking for 2604 // an all-zero value. 2605 return Splat && 2606 Splat->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 2607 HasAnyUndefs) && 2608 SplatValue == 0; 2609 }; 2610 2611 if (N->getOpcode() == ISD::CONCAT_VECTORS) { 2612 // Combine this: 2613 // 2614 // (concat_vectors (v2i32 (fp_to_{s,u}int_sat $x, 32)), (v2i32 (splat 0))) 2615 // 2616 // into (i32x4.trunc_sat_f64x2_zero_{s,u} $x). 2617 // 2618 // Or this: 2619 // 2620 // (concat_vectors (v2f32 (fp_round (v2f64 $x))), (v2f32 (splat 0))) 2621 // 2622 // into (f32x4.demote_zero_f64x2 $x). 2623 EVT ResVT; 2624 EVT ExpectedConversionType; 2625 auto Conversion = N->getOperand(0); 2626 auto ConversionOp = Conversion.getOpcode(); 2627 switch (ConversionOp) { 2628 case ISD::FP_TO_SINT_SAT: 2629 case ISD::FP_TO_UINT_SAT: 2630 ResVT = MVT::v4i32; 2631 ExpectedConversionType = MVT::v2i32; 2632 break; 2633 case ISD::FP_ROUND: 2634 ResVT = MVT::v4f32; 2635 ExpectedConversionType = MVT::v2f32; 2636 break; 2637 default: 2638 return SDValue(); 2639 } 2640 2641 if (N->getValueType(0) != ResVT) 2642 return SDValue(); 2643 2644 if (Conversion.getValueType() != ExpectedConversionType) 2645 return SDValue(); 2646 2647 auto Source = Conversion.getOperand(0); 2648 if (Source.getValueType() != MVT::v2f64) 2649 return SDValue(); 2650 2651 if (!IsZeroSplat(N->getOperand(1)) || 2652 N->getOperand(1).getValueType() != ExpectedConversionType) 2653 return SDValue(); 2654 2655 unsigned Op = GetWasmConversionOp(ConversionOp); 2656 return DAG.getNode(Op, SDLoc(N), ResVT, Source); 2657 } 2658 2659 // Combine this: 2660 // 2661 // (fp_to_{s,u}int_sat (concat_vectors $x, (v2f64 (splat 0))), 32) 2662 // 2663 // into (i32x4.trunc_sat_f64x2_zero_{s,u} $x). 2664 // 2665 // Or this: 2666 // 2667 // (v4f32 (fp_round (concat_vectors $x, (v2f64 (splat 0))))) 2668 // 2669 // into (f32x4.demote_zero_f64x2 $x). 2670 EVT ResVT; 2671 auto ConversionOp = N->getOpcode(); 2672 switch (ConversionOp) { 2673 case ISD::FP_TO_SINT_SAT: 2674 case ISD::FP_TO_UINT_SAT: 2675 ResVT = MVT::v4i32; 2676 break; 2677 case ISD::FP_ROUND: 2678 ResVT = MVT::v4f32; 2679 break; 2680 default: 2681 llvm_unreachable("unexpected op"); 2682 } 2683 2684 if (N->getValueType(0) != ResVT) 2685 return SDValue(); 2686 2687 auto Concat = N->getOperand(0); 2688 if (Concat.getValueType() != MVT::v4f64) 2689 return SDValue(); 2690 2691 auto Source = Concat.getOperand(0); 2692 if (Source.getValueType() != MVT::v2f64) 2693 return SDValue(); 2694 2695 if (!IsZeroSplat(Concat.getOperand(1)) || 2696 Concat.getOperand(1).getValueType() != MVT::v2f64) 2697 return SDValue(); 2698 2699 unsigned Op = GetWasmConversionOp(ConversionOp); 2700 return DAG.getNode(Op, SDLoc(N), ResVT, Source); 2701 } 2702 2703 // Helper to extract VectorWidth bits from Vec, starting from IdxVal. 2704 static SDValue extractSubVector(SDValue Vec, unsigned IdxVal, SelectionDAG &DAG, 2705 const SDLoc &DL, unsigned VectorWidth) { 2706 EVT VT = Vec.getValueType(); 2707 EVT ElVT = VT.getVectorElementType(); 2708 unsigned Factor = VT.getSizeInBits() / VectorWidth; 2709 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT, 2710 VT.getVectorNumElements() / Factor); 2711 2712 // Extract the relevant VectorWidth bits. Generate an EXTRACT_SUBVECTOR 2713 unsigned ElemsPerChunk = VectorWidth / ElVT.getSizeInBits(); 2714 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2"); 2715 2716 // This is the index of the first element of the VectorWidth-bit chunk 2717 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits. 2718 IdxVal &= ~(ElemsPerChunk - 1); 2719 2720 // If the input is a buildvector just emit a smaller one. 2721 if (Vec.getOpcode() == ISD::BUILD_VECTOR) 2722 return DAG.getBuildVector(ResultVT, DL, 2723 Vec->ops().slice(IdxVal, ElemsPerChunk)); 2724 2725 SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, DL); 2726 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResultVT, Vec, VecIdx); 2727 } 2728 2729 // Helper to recursively truncate vector elements in half with NARROW_U. DstVT 2730 // is the expected destination value type after recursion. In is the initial 2731 // input. Note that the input should have enough leading zero bits to prevent 2732 // NARROW_U from saturating results. 2733 static SDValue truncateVectorWithNARROW(EVT DstVT, SDValue In, const SDLoc &DL, 2734 SelectionDAG &DAG) { 2735 EVT SrcVT = In.getValueType(); 2736 2737 // No truncation required, we might get here due to recursive calls. 2738 if (SrcVT == DstVT) 2739 return In; 2740 2741 unsigned SrcSizeInBits = SrcVT.getSizeInBits(); 2742 unsigned NumElems = SrcVT.getVectorNumElements(); 2743 if (!isPowerOf2_32(NumElems)) 2744 return SDValue(); 2745 assert(DstVT.getVectorNumElements() == NumElems && "Illegal truncation"); 2746 assert(SrcSizeInBits > DstVT.getSizeInBits() && "Illegal truncation"); 2747 2748 LLVMContext &Ctx = *DAG.getContext(); 2749 EVT PackedSVT = EVT::getIntegerVT(Ctx, SrcVT.getScalarSizeInBits() / 2); 2750 2751 // Narrow to the largest type possible: 2752 // vXi64/vXi32 -> i16x8.narrow_i32x4_u and vXi16 -> i8x16.narrow_i16x8_u. 2753 EVT InVT = MVT::i16, OutVT = MVT::i8; 2754 if (SrcVT.getScalarSizeInBits() > 16) { 2755 InVT = MVT::i32; 2756 OutVT = MVT::i16; 2757 } 2758 unsigned SubSizeInBits = SrcSizeInBits / 2; 2759 InVT = EVT::getVectorVT(Ctx, InVT, SubSizeInBits / InVT.getSizeInBits()); 2760 OutVT = EVT::getVectorVT(Ctx, OutVT, SubSizeInBits / OutVT.getSizeInBits()); 2761 2762 // Split lower/upper subvectors. 2763 SDValue Lo = extractSubVector(In, 0, DAG, DL, SubSizeInBits); 2764 SDValue Hi = extractSubVector(In, NumElems / 2, DAG, DL, SubSizeInBits); 2765 2766 // 256bit -> 128bit truncate - Narrow lower/upper 128-bit subvectors. 2767 if (SrcVT.is256BitVector() && DstVT.is128BitVector()) { 2768 Lo = DAG.getBitcast(InVT, Lo); 2769 Hi = DAG.getBitcast(InVT, Hi); 2770 SDValue Res = DAG.getNode(WebAssemblyISD::NARROW_U, DL, OutVT, Lo, Hi); 2771 return DAG.getBitcast(DstVT, Res); 2772 } 2773 2774 // Recursively narrow lower/upper subvectors, concat result and narrow again. 2775 EVT PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems / 2); 2776 Lo = truncateVectorWithNARROW(PackedVT, Lo, DL, DAG); 2777 Hi = truncateVectorWithNARROW(PackedVT, Hi, DL, DAG); 2778 2779 PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems); 2780 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, PackedVT, Lo, Hi); 2781 return truncateVectorWithNARROW(DstVT, Res, DL, DAG); 2782 } 2783 2784 static SDValue performTruncateCombine(SDNode *N, 2785 TargetLowering::DAGCombinerInfo &DCI) { 2786 auto &DAG = DCI.DAG; 2787 2788 SDValue In = N->getOperand(0); 2789 EVT InVT = In.getValueType(); 2790 if (!InVT.isSimple()) 2791 return SDValue(); 2792 2793 EVT OutVT = N->getValueType(0); 2794 if (!OutVT.isVector()) 2795 return SDValue(); 2796 2797 EVT OutSVT = OutVT.getVectorElementType(); 2798 EVT InSVT = InVT.getVectorElementType(); 2799 // Currently only cover truncate to v16i8 or v8i16. 2800 if (!((InSVT == MVT::i16 || InSVT == MVT::i32 || InSVT == MVT::i64) && 2801 (OutSVT == MVT::i8 || OutSVT == MVT::i16) && OutVT.is128BitVector())) 2802 return SDValue(); 2803 2804 SDLoc DL(N); 2805 APInt Mask = APInt::getLowBitsSet(InVT.getScalarSizeInBits(), 2806 OutVT.getScalarSizeInBits()); 2807 In = DAG.getNode(ISD::AND, DL, InVT, In, DAG.getConstant(Mask, DL, InVT)); 2808 return truncateVectorWithNARROW(OutVT, In, DL, DAG); 2809 } 2810 2811 static SDValue performBitcastCombine(SDNode *N, 2812 TargetLowering::DAGCombinerInfo &DCI) { 2813 auto &DAG = DCI.DAG; 2814 SDLoc DL(N); 2815 SDValue Src = N->getOperand(0); 2816 EVT VT = N->getValueType(0); 2817 EVT SrcVT = Src.getValueType(); 2818 2819 // bitcast <N x i1> to iN 2820 // ==> bitmask 2821 if (DCI.isBeforeLegalize() && VT.isScalarInteger() && 2822 SrcVT.isFixedLengthVector() && SrcVT.getScalarType() == MVT::i1) { 2823 unsigned NumElts = SrcVT.getVectorNumElements(); 2824 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16) 2825 return SDValue(); 2826 EVT Width = MVT::getIntegerVT(128 / NumElts); 2827 return DAG.getZExtOrTrunc( 2828 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32, 2829 {DAG.getConstant(Intrinsic::wasm_bitmask, DL, MVT::i32), 2830 DAG.getSExtOrTrunc(N->getOperand(0), DL, 2831 SrcVT.changeVectorElementType(Width))}), 2832 DL, VT); 2833 } 2834 2835 return SDValue(); 2836 } 2837 2838 static SDValue performSETCCCombine(SDNode *N, 2839 TargetLowering::DAGCombinerInfo &DCI) { 2840 auto &DAG = DCI.DAG; 2841 2842 SDValue LHS = N->getOperand(0); 2843 SDValue RHS = N->getOperand(1); 2844 ISD::CondCode Cond = cast<CondCodeSDNode>(N->getOperand(2))->get(); 2845 SDLoc DL(N); 2846 EVT VT = N->getValueType(0); 2847 2848 // setcc (iN (bitcast (vNi1 X))), 0, ne 2849 // ==> any_true (vNi1 X) 2850 // setcc (iN (bitcast (vNi1 X))), 0, eq 2851 // ==> xor (any_true (vNi1 X)), -1 2852 // setcc (iN (bitcast (vNi1 X))), -1, eq 2853 // ==> all_true (vNi1 X) 2854 // setcc (iN (bitcast (vNi1 X))), -1, ne 2855 // ==> xor (all_true (vNi1 X)), -1 2856 if (DCI.isBeforeLegalize() && VT.isScalarInteger() && 2857 (Cond == ISD::SETEQ || Cond == ISD::SETNE) && 2858 (isNullConstant(RHS) || isAllOnesConstant(RHS)) && 2859 LHS->getOpcode() == ISD::BITCAST) { 2860 EVT FromVT = LHS->getOperand(0).getValueType(); 2861 if (FromVT.isFixedLengthVector() && 2862 FromVT.getVectorElementType() == MVT::i1) { 2863 int Intrin = isNullConstant(RHS) ? Intrinsic::wasm_anytrue 2864 : Intrinsic::wasm_alltrue; 2865 unsigned NumElts = FromVT.getVectorNumElements(); 2866 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16) 2867 return SDValue(); 2868 EVT Width = MVT::getIntegerVT(128 / NumElts); 2869 SDValue Ret = DAG.getZExtOrTrunc( 2870 DAG.getNode( 2871 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32, 2872 {DAG.getConstant(Intrin, DL, MVT::i32), 2873 DAG.getSExtOrTrunc(LHS->getOperand(0), DL, 2874 FromVT.changeVectorElementType(Width))}), 2875 DL, MVT::i1); 2876 if ((isNullConstant(RHS) && (Cond == ISD::SETEQ)) || 2877 (isAllOnesConstant(RHS) && (Cond == ISD::SETNE))) { 2878 Ret = DAG.getNOT(DL, Ret, MVT::i1); 2879 } 2880 return DAG.getZExtOrTrunc(Ret, DL, VT); 2881 } 2882 } 2883 2884 return SDValue(); 2885 } 2886 2887 SDValue 2888 WebAssemblyTargetLowering::PerformDAGCombine(SDNode *N, 2889 DAGCombinerInfo &DCI) const { 2890 switch (N->getOpcode()) { 2891 default: 2892 return SDValue(); 2893 case ISD::BITCAST: 2894 return performBitcastCombine(N, DCI); 2895 case ISD::SETCC: 2896 return performSETCCCombine(N, DCI); 2897 case ISD::VECTOR_SHUFFLE: 2898 return performVECTOR_SHUFFLECombine(N, DCI); 2899 case ISD::SIGN_EXTEND: 2900 case ISD::ZERO_EXTEND: 2901 return performVectorExtendCombine(N, DCI); 2902 case ISD::UINT_TO_FP: 2903 case ISD::SINT_TO_FP: 2904 return performVectorExtendToFPCombine(N, DCI); 2905 case ISD::FP_TO_SINT_SAT: 2906 case ISD::FP_TO_UINT_SAT: 2907 case ISD::FP_ROUND: 2908 case ISD::CONCAT_VECTORS: 2909 return performVectorTruncZeroCombine(N, DCI); 2910 case ISD::TRUNCATE: 2911 return performTruncateCombine(N, DCI); 2912 } 2913 } 2914