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