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