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