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