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