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