xref: /freebsd/contrib/llvm-project/clang/lib/CodeGen/CGBuiltin.cpp (revision 9729f076e4d93c5a37e78d427bfe0f1ab99bbcc6)
1 //===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
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 // This contains code to emit Builtin calls as LLVM code.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CGCUDARuntime.h"
14 #include "CGCXXABI.h"
15 #include "CGObjCRuntime.h"
16 #include "CGOpenCLRuntime.h"
17 #include "CGRecordLayout.h"
18 #include "CodeGenFunction.h"
19 #include "CodeGenModule.h"
20 #include "ConstantEmitter.h"
21 #include "PatternInit.h"
22 #include "TargetInfo.h"
23 #include "clang/AST/ASTContext.h"
24 #include "clang/AST/Attr.h"
25 #include "clang/AST/Decl.h"
26 #include "clang/AST/OSLog.h"
27 #include "clang/Basic/TargetBuiltins.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/CodeGen/CGFunctionInfo.h"
30 #include "llvm/ADT/APFloat.h"
31 #include "llvm/ADT/APInt.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/Analysis/ValueTracking.h"
35 #include "llvm/IR/DataLayout.h"
36 #include "llvm/IR/InlineAsm.h"
37 #include "llvm/IR/Intrinsics.h"
38 #include "llvm/IR/IntrinsicsAArch64.h"
39 #include "llvm/IR/IntrinsicsAMDGPU.h"
40 #include "llvm/IR/IntrinsicsARM.h"
41 #include "llvm/IR/IntrinsicsBPF.h"
42 #include "llvm/IR/IntrinsicsHexagon.h"
43 #include "llvm/IR/IntrinsicsNVPTX.h"
44 #include "llvm/IR/IntrinsicsPowerPC.h"
45 #include "llvm/IR/IntrinsicsR600.h"
46 #include "llvm/IR/IntrinsicsRISCV.h"
47 #include "llvm/IR/IntrinsicsS390.h"
48 #include "llvm/IR/IntrinsicsWebAssembly.h"
49 #include "llvm/IR/IntrinsicsX86.h"
50 #include "llvm/IR/MDBuilder.h"
51 #include "llvm/IR/MatrixBuilder.h"
52 #include "llvm/Support/ConvertUTF.h"
53 #include "llvm/Support/ScopedPrinter.h"
54 #include "llvm/Support/X86TargetParser.h"
55 #include <sstream>
56 
57 using namespace clang;
58 using namespace CodeGen;
59 using namespace llvm;
60 
61 static
62 int64_t clamp(int64_t Value, int64_t Low, int64_t High) {
63   return std::min(High, std::max(Low, Value));
64 }
65 
66 static void initializeAlloca(CodeGenFunction &CGF, AllocaInst *AI, Value *Size,
67                              Align AlignmentInBytes) {
68   ConstantInt *Byte;
69   switch (CGF.getLangOpts().getTrivialAutoVarInit()) {
70   case LangOptions::TrivialAutoVarInitKind::Uninitialized:
71     // Nothing to initialize.
72     return;
73   case LangOptions::TrivialAutoVarInitKind::Zero:
74     Byte = CGF.Builder.getInt8(0x00);
75     break;
76   case LangOptions::TrivialAutoVarInitKind::Pattern: {
77     llvm::Type *Int8 = llvm::IntegerType::getInt8Ty(CGF.CGM.getLLVMContext());
78     Byte = llvm::dyn_cast<llvm::ConstantInt>(
79         initializationPatternFor(CGF.CGM, Int8));
80     break;
81   }
82   }
83   if (CGF.CGM.stopAutoInit())
84     return;
85   auto *I = CGF.Builder.CreateMemSet(AI, Byte, Size, AlignmentInBytes);
86   I->addAnnotationMetadata("auto-init");
87 }
88 
89 /// getBuiltinLibFunction - Given a builtin id for a function like
90 /// "__builtin_fabsf", return a Function* for "fabsf".
91 llvm::Constant *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
92                                                      unsigned BuiltinID) {
93   assert(Context.BuiltinInfo.isLibFunction(BuiltinID));
94 
95   // Get the name, skip over the __builtin_ prefix (if necessary).
96   StringRef Name;
97   GlobalDecl D(FD);
98 
99   // TODO: This list should be expanded or refactored after all GCC-compatible
100   // std libcall builtins are implemented.
101   static SmallDenseMap<unsigned, StringRef, 8> F128Builtins{
102       {Builtin::BI__builtin_printf, "__printfieee128"},
103       {Builtin::BI__builtin_vsnprintf, "__vsnprintfieee128"},
104       {Builtin::BI__builtin_vsprintf, "__vsprintfieee128"},
105       {Builtin::BI__builtin_sprintf, "__sprintfieee128"},
106       {Builtin::BI__builtin_snprintf, "__snprintfieee128"},
107       {Builtin::BI__builtin_fprintf, "__fprintfieee128"},
108       {Builtin::BI__builtin_nexttowardf128, "__nexttowardieee128"},
109   };
110 
111   // If the builtin has been declared explicitly with an assembler label,
112   // use the mangled name. This differs from the plain label on platforms
113   // that prefix labels.
114   if (FD->hasAttr<AsmLabelAttr>())
115     Name = getMangledName(D);
116   else {
117     // TODO: This mutation should also be applied to other targets other than
118     // PPC, after backend supports IEEE 128-bit style libcalls.
119     if (getTriple().isPPC64() &&
120         &getTarget().getLongDoubleFormat() == &llvm::APFloat::IEEEquad() &&
121         F128Builtins.find(BuiltinID) != F128Builtins.end())
122       Name = F128Builtins[BuiltinID];
123     else
124       Name = Context.BuiltinInfo.getName(BuiltinID) + 10;
125   }
126 
127   llvm::FunctionType *Ty =
128     cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
129 
130   return GetOrCreateLLVMFunction(Name, Ty, D, /*ForVTable=*/false);
131 }
132 
133 /// Emit the conversions required to turn the given value into an
134 /// integer of the given size.
135 static Value *EmitToInt(CodeGenFunction &CGF, llvm::Value *V,
136                         QualType T, llvm::IntegerType *IntType) {
137   V = CGF.EmitToMemory(V, T);
138 
139   if (V->getType()->isPointerTy())
140     return CGF.Builder.CreatePtrToInt(V, IntType);
141 
142   assert(V->getType() == IntType);
143   return V;
144 }
145 
146 static Value *EmitFromInt(CodeGenFunction &CGF, llvm::Value *V,
147                           QualType T, llvm::Type *ResultType) {
148   V = CGF.EmitFromMemory(V, T);
149 
150   if (ResultType->isPointerTy())
151     return CGF.Builder.CreateIntToPtr(V, ResultType);
152 
153   assert(V->getType() == ResultType);
154   return V;
155 }
156 
157 /// Utility to insert an atomic instruction based on Intrinsic::ID
158 /// and the expression node.
159 static Value *MakeBinaryAtomicValue(
160     CodeGenFunction &CGF, llvm::AtomicRMWInst::BinOp Kind, const CallExpr *E,
161     AtomicOrdering Ordering = AtomicOrdering::SequentiallyConsistent) {
162 
163   QualType T = E->getType();
164   assert(E->getArg(0)->getType()->isPointerType());
165   assert(CGF.getContext().hasSameUnqualifiedType(T,
166                                   E->getArg(0)->getType()->getPointeeType()));
167   assert(CGF.getContext().hasSameUnqualifiedType(T, E->getArg(1)->getType()));
168 
169   llvm::Value *DestPtr = CGF.EmitScalarExpr(E->getArg(0));
170   unsigned AddrSpace = DestPtr->getType()->getPointerAddressSpace();
171 
172   llvm::IntegerType *IntType =
173     llvm::IntegerType::get(CGF.getLLVMContext(),
174                            CGF.getContext().getTypeSize(T));
175   llvm::Type *IntPtrType = IntType->getPointerTo(AddrSpace);
176 
177   llvm::Value *Args[2];
178   Args[0] = CGF.Builder.CreateBitCast(DestPtr, IntPtrType);
179   Args[1] = CGF.EmitScalarExpr(E->getArg(1));
180   llvm::Type *ValueType = Args[1]->getType();
181   Args[1] = EmitToInt(CGF, Args[1], T, IntType);
182 
183   llvm::Value *Result = CGF.Builder.CreateAtomicRMW(
184       Kind, Args[0], Args[1], Ordering);
185   return EmitFromInt(CGF, Result, T, ValueType);
186 }
187 
188 static Value *EmitNontemporalStore(CodeGenFunction &CGF, const CallExpr *E) {
189   Value *Val = CGF.EmitScalarExpr(E->getArg(0));
190   Value *Address = CGF.EmitScalarExpr(E->getArg(1));
191 
192   // Convert the type of the pointer to a pointer to the stored type.
193   Val = CGF.EmitToMemory(Val, E->getArg(0)->getType());
194   unsigned SrcAddrSpace = Address->getType()->getPointerAddressSpace();
195   Value *BC = CGF.Builder.CreateBitCast(
196       Address, llvm::PointerType::get(Val->getType(), SrcAddrSpace), "cast");
197   LValue LV = CGF.MakeNaturalAlignAddrLValue(BC, E->getArg(0)->getType());
198   LV.setNontemporal(true);
199   CGF.EmitStoreOfScalar(Val, LV, false);
200   return nullptr;
201 }
202 
203 static Value *EmitNontemporalLoad(CodeGenFunction &CGF, const CallExpr *E) {
204   Value *Address = CGF.EmitScalarExpr(E->getArg(0));
205 
206   LValue LV = CGF.MakeNaturalAlignAddrLValue(Address, E->getType());
207   LV.setNontemporal(true);
208   return CGF.EmitLoadOfScalar(LV, E->getExprLoc());
209 }
210 
211 static RValue EmitBinaryAtomic(CodeGenFunction &CGF,
212                                llvm::AtomicRMWInst::BinOp Kind,
213                                const CallExpr *E) {
214   return RValue::get(MakeBinaryAtomicValue(CGF, Kind, E));
215 }
216 
217 /// Utility to insert an atomic instruction based Intrinsic::ID and
218 /// the expression node, where the return value is the result of the
219 /// operation.
220 static RValue EmitBinaryAtomicPost(CodeGenFunction &CGF,
221                                    llvm::AtomicRMWInst::BinOp Kind,
222                                    const CallExpr *E,
223                                    Instruction::BinaryOps Op,
224                                    bool Invert = false) {
225   QualType T = E->getType();
226   assert(E->getArg(0)->getType()->isPointerType());
227   assert(CGF.getContext().hasSameUnqualifiedType(T,
228                                   E->getArg(0)->getType()->getPointeeType()));
229   assert(CGF.getContext().hasSameUnqualifiedType(T, E->getArg(1)->getType()));
230 
231   llvm::Value *DestPtr = CGF.EmitScalarExpr(E->getArg(0));
232   unsigned AddrSpace = DestPtr->getType()->getPointerAddressSpace();
233 
234   llvm::IntegerType *IntType =
235     llvm::IntegerType::get(CGF.getLLVMContext(),
236                            CGF.getContext().getTypeSize(T));
237   llvm::Type *IntPtrType = IntType->getPointerTo(AddrSpace);
238 
239   llvm::Value *Args[2];
240   Args[1] = CGF.EmitScalarExpr(E->getArg(1));
241   llvm::Type *ValueType = Args[1]->getType();
242   Args[1] = EmitToInt(CGF, Args[1], T, IntType);
243   Args[0] = CGF.Builder.CreateBitCast(DestPtr, IntPtrType);
244 
245   llvm::Value *Result = CGF.Builder.CreateAtomicRMW(
246       Kind, Args[0], Args[1], llvm::AtomicOrdering::SequentiallyConsistent);
247   Result = CGF.Builder.CreateBinOp(Op, Result, Args[1]);
248   if (Invert)
249     Result =
250         CGF.Builder.CreateBinOp(llvm::Instruction::Xor, Result,
251                                 llvm::ConstantInt::getAllOnesValue(IntType));
252   Result = EmitFromInt(CGF, Result, T, ValueType);
253   return RValue::get(Result);
254 }
255 
256 /// Utility to insert an atomic cmpxchg instruction.
257 ///
258 /// @param CGF The current codegen function.
259 /// @param E   Builtin call expression to convert to cmpxchg.
260 ///            arg0 - address to operate on
261 ///            arg1 - value to compare with
262 ///            arg2 - new value
263 /// @param ReturnBool Specifies whether to return success flag of
264 ///                   cmpxchg result or the old value.
265 ///
266 /// @returns result of cmpxchg, according to ReturnBool
267 ///
268 /// Note: In order to lower Microsoft's _InterlockedCompareExchange* intrinsics
269 /// invoke the function EmitAtomicCmpXchgForMSIntrin.
270 static Value *MakeAtomicCmpXchgValue(CodeGenFunction &CGF, const CallExpr *E,
271                                      bool ReturnBool) {
272   QualType T = ReturnBool ? E->getArg(1)->getType() : E->getType();
273   llvm::Value *DestPtr = CGF.EmitScalarExpr(E->getArg(0));
274   unsigned AddrSpace = DestPtr->getType()->getPointerAddressSpace();
275 
276   llvm::IntegerType *IntType = llvm::IntegerType::get(
277       CGF.getLLVMContext(), CGF.getContext().getTypeSize(T));
278   llvm::Type *IntPtrType = IntType->getPointerTo(AddrSpace);
279 
280   Value *Args[3];
281   Args[0] = CGF.Builder.CreateBitCast(DestPtr, IntPtrType);
282   Args[1] = CGF.EmitScalarExpr(E->getArg(1));
283   llvm::Type *ValueType = Args[1]->getType();
284   Args[1] = EmitToInt(CGF, Args[1], T, IntType);
285   Args[2] = EmitToInt(CGF, CGF.EmitScalarExpr(E->getArg(2)), T, IntType);
286 
287   Value *Pair = CGF.Builder.CreateAtomicCmpXchg(
288       Args[0], Args[1], Args[2], llvm::AtomicOrdering::SequentiallyConsistent,
289       llvm::AtomicOrdering::SequentiallyConsistent);
290   if (ReturnBool)
291     // Extract boolean success flag and zext it to int.
292     return CGF.Builder.CreateZExt(CGF.Builder.CreateExtractValue(Pair, 1),
293                                   CGF.ConvertType(E->getType()));
294   else
295     // Extract old value and emit it using the same type as compare value.
296     return EmitFromInt(CGF, CGF.Builder.CreateExtractValue(Pair, 0), T,
297                        ValueType);
298 }
299 
300 /// This function should be invoked to emit atomic cmpxchg for Microsoft's
301 /// _InterlockedCompareExchange* intrinsics which have the following signature:
302 /// T _InterlockedCompareExchange(T volatile *Destination,
303 ///                               T Exchange,
304 ///                               T Comparand);
305 ///
306 /// Whereas the llvm 'cmpxchg' instruction has the following syntax:
307 /// cmpxchg *Destination, Comparand, Exchange.
308 /// So we need to swap Comparand and Exchange when invoking
309 /// CreateAtomicCmpXchg. That is the reason we could not use the above utility
310 /// function MakeAtomicCmpXchgValue since it expects the arguments to be
311 /// already swapped.
312 
313 static
314 Value *EmitAtomicCmpXchgForMSIntrin(CodeGenFunction &CGF, const CallExpr *E,
315     AtomicOrdering SuccessOrdering = AtomicOrdering::SequentiallyConsistent) {
316   assert(E->getArg(0)->getType()->isPointerType());
317   assert(CGF.getContext().hasSameUnqualifiedType(
318       E->getType(), E->getArg(0)->getType()->getPointeeType()));
319   assert(CGF.getContext().hasSameUnqualifiedType(E->getType(),
320                                                  E->getArg(1)->getType()));
321   assert(CGF.getContext().hasSameUnqualifiedType(E->getType(),
322                                                  E->getArg(2)->getType()));
323 
324   auto *Destination = CGF.EmitScalarExpr(E->getArg(0));
325   auto *Comparand = CGF.EmitScalarExpr(E->getArg(2));
326   auto *Exchange = CGF.EmitScalarExpr(E->getArg(1));
327 
328   // For Release ordering, the failure ordering should be Monotonic.
329   auto FailureOrdering = SuccessOrdering == AtomicOrdering::Release ?
330                          AtomicOrdering::Monotonic :
331                          SuccessOrdering;
332 
333   // The atomic instruction is marked volatile for consistency with MSVC. This
334   // blocks the few atomics optimizations that LLVM has. If we want to optimize
335   // _Interlocked* operations in the future, we will have to remove the volatile
336   // marker.
337   auto *Result = CGF.Builder.CreateAtomicCmpXchg(
338                    Destination, Comparand, Exchange,
339                    SuccessOrdering, FailureOrdering);
340   Result->setVolatile(true);
341   return CGF.Builder.CreateExtractValue(Result, 0);
342 }
343 
344 // 64-bit Microsoft platforms support 128 bit cmpxchg operations. They are
345 // prototyped like this:
346 //
347 // unsigned char _InterlockedCompareExchange128...(
348 //     __int64 volatile * _Destination,
349 //     __int64 _ExchangeHigh,
350 //     __int64 _ExchangeLow,
351 //     __int64 * _ComparandResult);
352 static Value *EmitAtomicCmpXchg128ForMSIntrin(CodeGenFunction &CGF,
353                                               const CallExpr *E,
354                                               AtomicOrdering SuccessOrdering) {
355   assert(E->getNumArgs() == 4);
356   llvm::Value *Destination = CGF.EmitScalarExpr(E->getArg(0));
357   llvm::Value *ExchangeHigh = CGF.EmitScalarExpr(E->getArg(1));
358   llvm::Value *ExchangeLow = CGF.EmitScalarExpr(E->getArg(2));
359   llvm::Value *ComparandPtr = CGF.EmitScalarExpr(E->getArg(3));
360 
361   assert(Destination->getType()->isPointerTy());
362   assert(!ExchangeHigh->getType()->isPointerTy());
363   assert(!ExchangeLow->getType()->isPointerTy());
364   assert(ComparandPtr->getType()->isPointerTy());
365 
366   // For Release ordering, the failure ordering should be Monotonic.
367   auto FailureOrdering = SuccessOrdering == AtomicOrdering::Release
368                              ? AtomicOrdering::Monotonic
369                              : SuccessOrdering;
370 
371   // Convert to i128 pointers and values.
372   llvm::Type *Int128Ty = llvm::IntegerType::get(CGF.getLLVMContext(), 128);
373   llvm::Type *Int128PtrTy = Int128Ty->getPointerTo();
374   Destination = CGF.Builder.CreateBitCast(Destination, Int128PtrTy);
375   Address ComparandResult(CGF.Builder.CreateBitCast(ComparandPtr, Int128PtrTy),
376                           CGF.getContext().toCharUnitsFromBits(128));
377 
378   // (((i128)hi) << 64) | ((i128)lo)
379   ExchangeHigh = CGF.Builder.CreateZExt(ExchangeHigh, Int128Ty);
380   ExchangeLow = CGF.Builder.CreateZExt(ExchangeLow, Int128Ty);
381   ExchangeHigh =
382       CGF.Builder.CreateShl(ExchangeHigh, llvm::ConstantInt::get(Int128Ty, 64));
383   llvm::Value *Exchange = CGF.Builder.CreateOr(ExchangeHigh, ExchangeLow);
384 
385   // Load the comparand for the instruction.
386   llvm::Value *Comparand = CGF.Builder.CreateLoad(ComparandResult);
387 
388   auto *CXI = CGF.Builder.CreateAtomicCmpXchg(Destination, Comparand, Exchange,
389                                               SuccessOrdering, FailureOrdering);
390 
391   // The atomic instruction is marked volatile for consistency with MSVC. This
392   // blocks the few atomics optimizations that LLVM has. If we want to optimize
393   // _Interlocked* operations in the future, we will have to remove the volatile
394   // marker.
395   CXI->setVolatile(true);
396 
397   // Store the result as an outparameter.
398   CGF.Builder.CreateStore(CGF.Builder.CreateExtractValue(CXI, 0),
399                           ComparandResult);
400 
401   // Get the success boolean and zero extend it to i8.
402   Value *Success = CGF.Builder.CreateExtractValue(CXI, 1);
403   return CGF.Builder.CreateZExt(Success, CGF.Int8Ty);
404 }
405 
406 static Value *EmitAtomicIncrementValue(CodeGenFunction &CGF, const CallExpr *E,
407     AtomicOrdering Ordering = AtomicOrdering::SequentiallyConsistent) {
408   assert(E->getArg(0)->getType()->isPointerType());
409 
410   auto *IntTy = CGF.ConvertType(E->getType());
411   auto *Result = CGF.Builder.CreateAtomicRMW(
412                    AtomicRMWInst::Add,
413                    CGF.EmitScalarExpr(E->getArg(0)),
414                    ConstantInt::get(IntTy, 1),
415                    Ordering);
416   return CGF.Builder.CreateAdd(Result, ConstantInt::get(IntTy, 1));
417 }
418 
419 static Value *EmitAtomicDecrementValue(CodeGenFunction &CGF, const CallExpr *E,
420     AtomicOrdering Ordering = AtomicOrdering::SequentiallyConsistent) {
421   assert(E->getArg(0)->getType()->isPointerType());
422 
423   auto *IntTy = CGF.ConvertType(E->getType());
424   auto *Result = CGF.Builder.CreateAtomicRMW(
425                    AtomicRMWInst::Sub,
426                    CGF.EmitScalarExpr(E->getArg(0)),
427                    ConstantInt::get(IntTy, 1),
428                    Ordering);
429   return CGF.Builder.CreateSub(Result, ConstantInt::get(IntTy, 1));
430 }
431 
432 // Build a plain volatile load.
433 static Value *EmitISOVolatileLoad(CodeGenFunction &CGF, const CallExpr *E) {
434   Value *Ptr = CGF.EmitScalarExpr(E->getArg(0));
435   QualType ElTy = E->getArg(0)->getType()->getPointeeType();
436   CharUnits LoadSize = CGF.getContext().getTypeSizeInChars(ElTy);
437   llvm::Type *ITy =
438       llvm::IntegerType::get(CGF.getLLVMContext(), LoadSize.getQuantity() * 8);
439   Ptr = CGF.Builder.CreateBitCast(Ptr, ITy->getPointerTo());
440   llvm::LoadInst *Load = CGF.Builder.CreateAlignedLoad(ITy, Ptr, LoadSize);
441   Load->setVolatile(true);
442   return Load;
443 }
444 
445 // Build a plain volatile store.
446 static Value *EmitISOVolatileStore(CodeGenFunction &CGF, const CallExpr *E) {
447   Value *Ptr = CGF.EmitScalarExpr(E->getArg(0));
448   Value *Value = CGF.EmitScalarExpr(E->getArg(1));
449   QualType ElTy = E->getArg(0)->getType()->getPointeeType();
450   CharUnits StoreSize = CGF.getContext().getTypeSizeInChars(ElTy);
451   llvm::Type *ITy =
452       llvm::IntegerType::get(CGF.getLLVMContext(), StoreSize.getQuantity() * 8);
453   Ptr = CGF.Builder.CreateBitCast(Ptr, ITy->getPointerTo());
454   llvm::StoreInst *Store =
455       CGF.Builder.CreateAlignedStore(Value, Ptr, StoreSize);
456   Store->setVolatile(true);
457   return Store;
458 }
459 
460 // Emit a simple mangled intrinsic that has 1 argument and a return type
461 // matching the argument type. Depending on mode, this may be a constrained
462 // floating-point intrinsic.
463 static Value *emitUnaryMaybeConstrainedFPBuiltin(CodeGenFunction &CGF,
464                                 const CallExpr *E, unsigned IntrinsicID,
465                                 unsigned ConstrainedIntrinsicID) {
466   llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
467 
468   if (CGF.Builder.getIsFPConstrained()) {
469     CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
470     Function *F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID, Src0->getType());
471     return CGF.Builder.CreateConstrainedFPCall(F, { Src0 });
472   } else {
473     Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
474     return CGF.Builder.CreateCall(F, Src0);
475   }
476 }
477 
478 // Emit an intrinsic that has 2 operands of the same type as its result.
479 // Depending on mode, this may be a constrained floating-point intrinsic.
480 static Value *emitBinaryMaybeConstrainedFPBuiltin(CodeGenFunction &CGF,
481                                 const CallExpr *E, unsigned IntrinsicID,
482                                 unsigned ConstrainedIntrinsicID) {
483   llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
484   llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1));
485 
486   if (CGF.Builder.getIsFPConstrained()) {
487     CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
488     Function *F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID, Src0->getType());
489     return CGF.Builder.CreateConstrainedFPCall(F, { Src0, Src1 });
490   } else {
491     Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
492     return CGF.Builder.CreateCall(F, { Src0, Src1 });
493   }
494 }
495 
496 // Emit an intrinsic that has 3 operands of the same type as its result.
497 // Depending on mode, this may be a constrained floating-point intrinsic.
498 static Value *emitTernaryMaybeConstrainedFPBuiltin(CodeGenFunction &CGF,
499                                  const CallExpr *E, unsigned IntrinsicID,
500                                  unsigned ConstrainedIntrinsicID) {
501   llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
502   llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1));
503   llvm::Value *Src2 = CGF.EmitScalarExpr(E->getArg(2));
504 
505   if (CGF.Builder.getIsFPConstrained()) {
506     CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
507     Function *F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID, Src0->getType());
508     return CGF.Builder.CreateConstrainedFPCall(F, { Src0, Src1, Src2 });
509   } else {
510     Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
511     return CGF.Builder.CreateCall(F, { Src0, Src1, Src2 });
512   }
513 }
514 
515 // Emit an intrinsic where all operands are of the same type as the result.
516 // Depending on mode, this may be a constrained floating-point intrinsic.
517 static Value *emitCallMaybeConstrainedFPBuiltin(CodeGenFunction &CGF,
518                                                 unsigned IntrinsicID,
519                                                 unsigned ConstrainedIntrinsicID,
520                                                 llvm::Type *Ty,
521                                                 ArrayRef<Value *> Args) {
522   Function *F;
523   if (CGF.Builder.getIsFPConstrained())
524     F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID, Ty);
525   else
526     F = CGF.CGM.getIntrinsic(IntrinsicID, Ty);
527 
528   if (CGF.Builder.getIsFPConstrained())
529     return CGF.Builder.CreateConstrainedFPCall(F, Args);
530   else
531     return CGF.Builder.CreateCall(F, Args);
532 }
533 
534 // Emit a simple mangled intrinsic that has 1 argument and a return type
535 // matching the argument type.
536 static Value *emitUnaryBuiltin(CodeGenFunction &CGF, const CallExpr *E,
537                                unsigned IntrinsicID,
538                                llvm::StringRef Name = "") {
539   llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
540 
541   Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
542   return CGF.Builder.CreateCall(F, Src0, Name);
543 }
544 
545 // Emit an intrinsic that has 2 operands of the same type as its result.
546 static Value *emitBinaryBuiltin(CodeGenFunction &CGF,
547                                 const CallExpr *E,
548                                 unsigned IntrinsicID) {
549   llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
550   llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1));
551 
552   Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
553   return CGF.Builder.CreateCall(F, { Src0, Src1 });
554 }
555 
556 // Emit an intrinsic that has 3 operands of the same type as its result.
557 static Value *emitTernaryBuiltin(CodeGenFunction &CGF,
558                                  const CallExpr *E,
559                                  unsigned IntrinsicID) {
560   llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
561   llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1));
562   llvm::Value *Src2 = CGF.EmitScalarExpr(E->getArg(2));
563 
564   Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
565   return CGF.Builder.CreateCall(F, { Src0, Src1, Src2 });
566 }
567 
568 // Emit an intrinsic that has 1 float or double operand, and 1 integer.
569 static Value *emitFPIntBuiltin(CodeGenFunction &CGF,
570                                const CallExpr *E,
571                                unsigned IntrinsicID) {
572   llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
573   llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1));
574 
575   Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
576   return CGF.Builder.CreateCall(F, {Src0, Src1});
577 }
578 
579 // Emit an intrinsic that has overloaded integer result and fp operand.
580 static Value *
581 emitMaybeConstrainedFPToIntRoundBuiltin(CodeGenFunction &CGF, const CallExpr *E,
582                                         unsigned IntrinsicID,
583                                         unsigned ConstrainedIntrinsicID) {
584   llvm::Type *ResultType = CGF.ConvertType(E->getType());
585   llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
586 
587   if (CGF.Builder.getIsFPConstrained()) {
588     CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
589     Function *F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID,
590                                        {ResultType, Src0->getType()});
591     return CGF.Builder.CreateConstrainedFPCall(F, {Src0});
592   } else {
593     Function *F =
594         CGF.CGM.getIntrinsic(IntrinsicID, {ResultType, Src0->getType()});
595     return CGF.Builder.CreateCall(F, Src0);
596   }
597 }
598 
599 /// EmitFAbs - Emit a call to @llvm.fabs().
600 static Value *EmitFAbs(CodeGenFunction &CGF, Value *V) {
601   Function *F = CGF.CGM.getIntrinsic(Intrinsic::fabs, V->getType());
602   llvm::CallInst *Call = CGF.Builder.CreateCall(F, V);
603   Call->setDoesNotAccessMemory();
604   return Call;
605 }
606 
607 /// Emit the computation of the sign bit for a floating point value. Returns
608 /// the i1 sign bit value.
609 static Value *EmitSignBit(CodeGenFunction &CGF, Value *V) {
610   LLVMContext &C = CGF.CGM.getLLVMContext();
611 
612   llvm::Type *Ty = V->getType();
613   int Width = Ty->getPrimitiveSizeInBits();
614   llvm::Type *IntTy = llvm::IntegerType::get(C, Width);
615   V = CGF.Builder.CreateBitCast(V, IntTy);
616   if (Ty->isPPC_FP128Ty()) {
617     // We want the sign bit of the higher-order double. The bitcast we just
618     // did works as if the double-double was stored to memory and then
619     // read as an i128. The "store" will put the higher-order double in the
620     // lower address in both little- and big-Endian modes, but the "load"
621     // will treat those bits as a different part of the i128: the low bits in
622     // little-Endian, the high bits in big-Endian. Therefore, on big-Endian
623     // we need to shift the high bits down to the low before truncating.
624     Width >>= 1;
625     if (CGF.getTarget().isBigEndian()) {
626       Value *ShiftCst = llvm::ConstantInt::get(IntTy, Width);
627       V = CGF.Builder.CreateLShr(V, ShiftCst);
628     }
629     // We are truncating value in order to extract the higher-order
630     // double, which we will be using to extract the sign from.
631     IntTy = llvm::IntegerType::get(C, Width);
632     V = CGF.Builder.CreateTrunc(V, IntTy);
633   }
634   Value *Zero = llvm::Constant::getNullValue(IntTy);
635   return CGF.Builder.CreateICmpSLT(V, Zero);
636 }
637 
638 static RValue emitLibraryCall(CodeGenFunction &CGF, const FunctionDecl *FD,
639                               const CallExpr *E, llvm::Constant *calleeValue) {
640   CGCallee callee = CGCallee::forDirect(calleeValue, GlobalDecl(FD));
641   return CGF.EmitCall(E->getCallee()->getType(), callee, E, ReturnValueSlot());
642 }
643 
644 /// Emit a call to llvm.{sadd,uadd,ssub,usub,smul,umul}.with.overflow.*
645 /// depending on IntrinsicID.
646 ///
647 /// \arg CGF The current codegen function.
648 /// \arg IntrinsicID The ID for the Intrinsic we wish to generate.
649 /// \arg X The first argument to the llvm.*.with.overflow.*.
650 /// \arg Y The second argument to the llvm.*.with.overflow.*.
651 /// \arg Carry The carry returned by the llvm.*.with.overflow.*.
652 /// \returns The result (i.e. sum/product) returned by the intrinsic.
653 static llvm::Value *EmitOverflowIntrinsic(CodeGenFunction &CGF,
654                                           const llvm::Intrinsic::ID IntrinsicID,
655                                           llvm::Value *X, llvm::Value *Y,
656                                           llvm::Value *&Carry) {
657   // Make sure we have integers of the same width.
658   assert(X->getType() == Y->getType() &&
659          "Arguments must be the same type. (Did you forget to make sure both "
660          "arguments have the same integer width?)");
661 
662   Function *Callee = CGF.CGM.getIntrinsic(IntrinsicID, X->getType());
663   llvm::Value *Tmp = CGF.Builder.CreateCall(Callee, {X, Y});
664   Carry = CGF.Builder.CreateExtractValue(Tmp, 1);
665   return CGF.Builder.CreateExtractValue(Tmp, 0);
666 }
667 
668 static Value *emitRangedBuiltin(CodeGenFunction &CGF,
669                                 unsigned IntrinsicID,
670                                 int low, int high) {
671     llvm::MDBuilder MDHelper(CGF.getLLVMContext());
672     llvm::MDNode *RNode = MDHelper.createRange(APInt(32, low), APInt(32, high));
673     Function *F = CGF.CGM.getIntrinsic(IntrinsicID, {});
674     llvm::Instruction *Call = CGF.Builder.CreateCall(F);
675     Call->setMetadata(llvm::LLVMContext::MD_range, RNode);
676     return Call;
677 }
678 
679 namespace {
680   struct WidthAndSignedness {
681     unsigned Width;
682     bool Signed;
683   };
684 }
685 
686 static WidthAndSignedness
687 getIntegerWidthAndSignedness(const clang::ASTContext &context,
688                              const clang::QualType Type) {
689   assert(Type->isIntegerType() && "Given type is not an integer.");
690   unsigned Width = Type->isBooleanType()  ? 1
691                    : Type->isBitIntType() ? context.getIntWidth(Type)
692                                           : context.getTypeInfo(Type).Width;
693   bool Signed = Type->isSignedIntegerType();
694   return {Width, Signed};
695 }
696 
697 // Given one or more integer types, this function produces an integer type that
698 // encompasses them: any value in one of the given types could be expressed in
699 // the encompassing type.
700 static struct WidthAndSignedness
701 EncompassingIntegerType(ArrayRef<struct WidthAndSignedness> Types) {
702   assert(Types.size() > 0 && "Empty list of types.");
703 
704   // If any of the given types is signed, we must return a signed type.
705   bool Signed = false;
706   for (const auto &Type : Types) {
707     Signed |= Type.Signed;
708   }
709 
710   // The encompassing type must have a width greater than or equal to the width
711   // of the specified types.  Additionally, if the encompassing type is signed,
712   // its width must be strictly greater than the width of any unsigned types
713   // given.
714   unsigned Width = 0;
715   for (const auto &Type : Types) {
716     unsigned MinWidth = Type.Width + (Signed && !Type.Signed);
717     if (Width < MinWidth) {
718       Width = MinWidth;
719     }
720   }
721 
722   return {Width, Signed};
723 }
724 
725 Value *CodeGenFunction::EmitVAStartEnd(Value *ArgValue, bool IsStart) {
726   llvm::Type *DestType = Int8PtrTy;
727   if (ArgValue->getType() != DestType)
728     ArgValue =
729         Builder.CreateBitCast(ArgValue, DestType, ArgValue->getName().data());
730 
731   Intrinsic::ID inst = IsStart ? Intrinsic::vastart : Intrinsic::vaend;
732   return Builder.CreateCall(CGM.getIntrinsic(inst), ArgValue);
733 }
734 
735 /// Checks if using the result of __builtin_object_size(p, @p From) in place of
736 /// __builtin_object_size(p, @p To) is correct
737 static bool areBOSTypesCompatible(int From, int To) {
738   // Note: Our __builtin_object_size implementation currently treats Type=0 and
739   // Type=2 identically. Encoding this implementation detail here may make
740   // improving __builtin_object_size difficult in the future, so it's omitted.
741   return From == To || (From == 0 && To == 1) || (From == 3 && To == 2);
742 }
743 
744 static llvm::Value *
745 getDefaultBuiltinObjectSizeResult(unsigned Type, llvm::IntegerType *ResType) {
746   return ConstantInt::get(ResType, (Type & 2) ? 0 : -1, /*isSigned=*/true);
747 }
748 
749 llvm::Value *
750 CodeGenFunction::evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type,
751                                                  llvm::IntegerType *ResType,
752                                                  llvm::Value *EmittedE,
753                                                  bool IsDynamic) {
754   uint64_t ObjectSize;
755   if (!E->tryEvaluateObjectSize(ObjectSize, getContext(), Type))
756     return emitBuiltinObjectSize(E, Type, ResType, EmittedE, IsDynamic);
757   return ConstantInt::get(ResType, ObjectSize, /*isSigned=*/true);
758 }
759 
760 /// Returns a Value corresponding to the size of the given expression.
761 /// This Value may be either of the following:
762 ///   - A llvm::Argument (if E is a param with the pass_object_size attribute on
763 ///     it)
764 ///   - A call to the @llvm.objectsize intrinsic
765 ///
766 /// EmittedE is the result of emitting `E` as a scalar expr. If it's non-null
767 /// and we wouldn't otherwise try to reference a pass_object_size parameter,
768 /// we'll call @llvm.objectsize on EmittedE, rather than emitting E.
769 llvm::Value *
770 CodeGenFunction::emitBuiltinObjectSize(const Expr *E, unsigned Type,
771                                        llvm::IntegerType *ResType,
772                                        llvm::Value *EmittedE, bool IsDynamic) {
773   // We need to reference an argument if the pointer is a parameter with the
774   // pass_object_size attribute.
775   if (auto *D = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) {
776     auto *Param = dyn_cast<ParmVarDecl>(D->getDecl());
777     auto *PS = D->getDecl()->getAttr<PassObjectSizeAttr>();
778     if (Param != nullptr && PS != nullptr &&
779         areBOSTypesCompatible(PS->getType(), Type)) {
780       auto Iter = SizeArguments.find(Param);
781       assert(Iter != SizeArguments.end());
782 
783       const ImplicitParamDecl *D = Iter->second;
784       auto DIter = LocalDeclMap.find(D);
785       assert(DIter != LocalDeclMap.end());
786 
787       return EmitLoadOfScalar(DIter->second, /*Volatile=*/false,
788                               getContext().getSizeType(), E->getBeginLoc());
789     }
790   }
791 
792   // LLVM can't handle Type=3 appropriately, and __builtin_object_size shouldn't
793   // evaluate E for side-effects. In either case, we shouldn't lower to
794   // @llvm.objectsize.
795   if (Type == 3 || (!EmittedE && E->HasSideEffects(getContext())))
796     return getDefaultBuiltinObjectSizeResult(Type, ResType);
797 
798   Value *Ptr = EmittedE ? EmittedE : EmitScalarExpr(E);
799   assert(Ptr->getType()->isPointerTy() &&
800          "Non-pointer passed to __builtin_object_size?");
801 
802   Function *F =
803       CGM.getIntrinsic(Intrinsic::objectsize, {ResType, Ptr->getType()});
804 
805   // LLVM only supports 0 and 2, make sure that we pass along that as a boolean.
806   Value *Min = Builder.getInt1((Type & 2) != 0);
807   // For GCC compatibility, __builtin_object_size treat NULL as unknown size.
808   Value *NullIsUnknown = Builder.getTrue();
809   Value *Dynamic = Builder.getInt1(IsDynamic);
810   return Builder.CreateCall(F, {Ptr, Min, NullIsUnknown, Dynamic});
811 }
812 
813 namespace {
814 /// A struct to generically describe a bit test intrinsic.
815 struct BitTest {
816   enum ActionKind : uint8_t { TestOnly, Complement, Reset, Set };
817   enum InterlockingKind : uint8_t {
818     Unlocked,
819     Sequential,
820     Acquire,
821     Release,
822     NoFence
823   };
824 
825   ActionKind Action;
826   InterlockingKind Interlocking;
827   bool Is64Bit;
828 
829   static BitTest decodeBitTestBuiltin(unsigned BuiltinID);
830 };
831 } // namespace
832 
833 BitTest BitTest::decodeBitTestBuiltin(unsigned BuiltinID) {
834   switch (BuiltinID) {
835     // Main portable variants.
836   case Builtin::BI_bittest:
837     return {TestOnly, Unlocked, false};
838   case Builtin::BI_bittestandcomplement:
839     return {Complement, Unlocked, false};
840   case Builtin::BI_bittestandreset:
841     return {Reset, Unlocked, false};
842   case Builtin::BI_bittestandset:
843     return {Set, Unlocked, false};
844   case Builtin::BI_interlockedbittestandreset:
845     return {Reset, Sequential, false};
846   case Builtin::BI_interlockedbittestandset:
847     return {Set, Sequential, false};
848 
849     // X86-specific 64-bit variants.
850   case Builtin::BI_bittest64:
851     return {TestOnly, Unlocked, true};
852   case Builtin::BI_bittestandcomplement64:
853     return {Complement, Unlocked, true};
854   case Builtin::BI_bittestandreset64:
855     return {Reset, Unlocked, true};
856   case Builtin::BI_bittestandset64:
857     return {Set, Unlocked, true};
858   case Builtin::BI_interlockedbittestandreset64:
859     return {Reset, Sequential, true};
860   case Builtin::BI_interlockedbittestandset64:
861     return {Set, Sequential, true};
862 
863     // ARM/AArch64-specific ordering variants.
864   case Builtin::BI_interlockedbittestandset_acq:
865     return {Set, Acquire, false};
866   case Builtin::BI_interlockedbittestandset_rel:
867     return {Set, Release, false};
868   case Builtin::BI_interlockedbittestandset_nf:
869     return {Set, NoFence, false};
870   case Builtin::BI_interlockedbittestandreset_acq:
871     return {Reset, Acquire, false};
872   case Builtin::BI_interlockedbittestandreset_rel:
873     return {Reset, Release, false};
874   case Builtin::BI_interlockedbittestandreset_nf:
875     return {Reset, NoFence, false};
876   }
877   llvm_unreachable("expected only bittest intrinsics");
878 }
879 
880 static char bitActionToX86BTCode(BitTest::ActionKind A) {
881   switch (A) {
882   case BitTest::TestOnly:   return '\0';
883   case BitTest::Complement: return 'c';
884   case BitTest::Reset:      return 'r';
885   case BitTest::Set:        return 's';
886   }
887   llvm_unreachable("invalid action");
888 }
889 
890 static llvm::Value *EmitX86BitTestIntrinsic(CodeGenFunction &CGF,
891                                             BitTest BT,
892                                             const CallExpr *E, Value *BitBase,
893                                             Value *BitPos) {
894   char Action = bitActionToX86BTCode(BT.Action);
895   char SizeSuffix = BT.Is64Bit ? 'q' : 'l';
896 
897   // Build the assembly.
898   SmallString<64> Asm;
899   raw_svector_ostream AsmOS(Asm);
900   if (BT.Interlocking != BitTest::Unlocked)
901     AsmOS << "lock ";
902   AsmOS << "bt";
903   if (Action)
904     AsmOS << Action;
905   AsmOS << SizeSuffix << " $2, ($1)";
906 
907   // Build the constraints. FIXME: We should support immediates when possible.
908   std::string Constraints = "={@ccc},r,r,~{cc},~{memory}";
909   std::string MachineClobbers = CGF.getTarget().getClobbers();
910   if (!MachineClobbers.empty()) {
911     Constraints += ',';
912     Constraints += MachineClobbers;
913   }
914   llvm::IntegerType *IntType = llvm::IntegerType::get(
915       CGF.getLLVMContext(),
916       CGF.getContext().getTypeSize(E->getArg(1)->getType()));
917   llvm::Type *IntPtrType = IntType->getPointerTo();
918   llvm::FunctionType *FTy =
919       llvm::FunctionType::get(CGF.Int8Ty, {IntPtrType, IntType}, false);
920 
921   llvm::InlineAsm *IA =
922       llvm::InlineAsm::get(FTy, Asm, Constraints, /*hasSideEffects=*/true);
923   return CGF.Builder.CreateCall(IA, {BitBase, BitPos});
924 }
925 
926 static llvm::AtomicOrdering
927 getBitTestAtomicOrdering(BitTest::InterlockingKind I) {
928   switch (I) {
929   case BitTest::Unlocked:   return llvm::AtomicOrdering::NotAtomic;
930   case BitTest::Sequential: return llvm::AtomicOrdering::SequentiallyConsistent;
931   case BitTest::Acquire:    return llvm::AtomicOrdering::Acquire;
932   case BitTest::Release:    return llvm::AtomicOrdering::Release;
933   case BitTest::NoFence:    return llvm::AtomicOrdering::Monotonic;
934   }
935   llvm_unreachable("invalid interlocking");
936 }
937 
938 /// Emit a _bittest* intrinsic. These intrinsics take a pointer to an array of
939 /// bits and a bit position and read and optionally modify the bit at that
940 /// position. The position index can be arbitrarily large, i.e. it can be larger
941 /// than 31 or 63, so we need an indexed load in the general case.
942 static llvm::Value *EmitBitTestIntrinsic(CodeGenFunction &CGF,
943                                          unsigned BuiltinID,
944                                          const CallExpr *E) {
945   Value *BitBase = CGF.EmitScalarExpr(E->getArg(0));
946   Value *BitPos = CGF.EmitScalarExpr(E->getArg(1));
947 
948   BitTest BT = BitTest::decodeBitTestBuiltin(BuiltinID);
949 
950   // X86 has special BT, BTC, BTR, and BTS instructions that handle the array
951   // indexing operation internally. Use them if possible.
952   if (CGF.getTarget().getTriple().isX86())
953     return EmitX86BitTestIntrinsic(CGF, BT, E, BitBase, BitPos);
954 
955   // Otherwise, use generic code to load one byte and test the bit. Use all but
956   // the bottom three bits as the array index, and the bottom three bits to form
957   // a mask.
958   // Bit = BitBaseI8[BitPos >> 3] & (1 << (BitPos & 0x7)) != 0;
959   Value *ByteIndex = CGF.Builder.CreateAShr(
960       BitPos, llvm::ConstantInt::get(BitPos->getType(), 3), "bittest.byteidx");
961   Value *BitBaseI8 = CGF.Builder.CreatePointerCast(BitBase, CGF.Int8PtrTy);
962   Address ByteAddr(CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, BitBaseI8,
963                                                  ByteIndex, "bittest.byteaddr"),
964                    CharUnits::One());
965   Value *PosLow =
966       CGF.Builder.CreateAnd(CGF.Builder.CreateTrunc(BitPos, CGF.Int8Ty),
967                             llvm::ConstantInt::get(CGF.Int8Ty, 0x7));
968 
969   // The updating instructions will need a mask.
970   Value *Mask = nullptr;
971   if (BT.Action != BitTest::TestOnly) {
972     Mask = CGF.Builder.CreateShl(llvm::ConstantInt::get(CGF.Int8Ty, 1), PosLow,
973                                  "bittest.mask");
974   }
975 
976   // Check the action and ordering of the interlocked intrinsics.
977   llvm::AtomicOrdering Ordering = getBitTestAtomicOrdering(BT.Interlocking);
978 
979   Value *OldByte = nullptr;
980   if (Ordering != llvm::AtomicOrdering::NotAtomic) {
981     // Emit a combined atomicrmw load/store operation for the interlocked
982     // intrinsics.
983     llvm::AtomicRMWInst::BinOp RMWOp = llvm::AtomicRMWInst::Or;
984     if (BT.Action == BitTest::Reset) {
985       Mask = CGF.Builder.CreateNot(Mask);
986       RMWOp = llvm::AtomicRMWInst::And;
987     }
988     OldByte = CGF.Builder.CreateAtomicRMW(RMWOp, ByteAddr.getPointer(), Mask,
989                                           Ordering);
990   } else {
991     // Emit a plain load for the non-interlocked intrinsics.
992     OldByte = CGF.Builder.CreateLoad(ByteAddr, "bittest.byte");
993     Value *NewByte = nullptr;
994     switch (BT.Action) {
995     case BitTest::TestOnly:
996       // Don't store anything.
997       break;
998     case BitTest::Complement:
999       NewByte = CGF.Builder.CreateXor(OldByte, Mask);
1000       break;
1001     case BitTest::Reset:
1002       NewByte = CGF.Builder.CreateAnd(OldByte, CGF.Builder.CreateNot(Mask));
1003       break;
1004     case BitTest::Set:
1005       NewByte = CGF.Builder.CreateOr(OldByte, Mask);
1006       break;
1007     }
1008     if (NewByte)
1009       CGF.Builder.CreateStore(NewByte, ByteAddr);
1010   }
1011 
1012   // However we loaded the old byte, either by plain load or atomicrmw, shift
1013   // the bit into the low position and mask it to 0 or 1.
1014   Value *ShiftedByte = CGF.Builder.CreateLShr(OldByte, PosLow, "bittest.shr");
1015   return CGF.Builder.CreateAnd(
1016       ShiftedByte, llvm::ConstantInt::get(CGF.Int8Ty, 1), "bittest.res");
1017 }
1018 
1019 static llvm::Value *emitPPCLoadReserveIntrinsic(CodeGenFunction &CGF,
1020                                                 unsigned BuiltinID,
1021                                                 const CallExpr *E) {
1022   Value *Addr = CGF.EmitScalarExpr(E->getArg(0));
1023 
1024   SmallString<64> Asm;
1025   raw_svector_ostream AsmOS(Asm);
1026   llvm::IntegerType *RetType = CGF.Int32Ty;
1027 
1028   switch (BuiltinID) {
1029   case clang::PPC::BI__builtin_ppc_ldarx:
1030     AsmOS << "ldarx ";
1031     RetType = CGF.Int64Ty;
1032     break;
1033   case clang::PPC::BI__builtin_ppc_lwarx:
1034     AsmOS << "lwarx ";
1035     RetType = CGF.Int32Ty;
1036     break;
1037   case clang::PPC::BI__builtin_ppc_lharx:
1038     AsmOS << "lharx ";
1039     RetType = CGF.Int16Ty;
1040     break;
1041   case clang::PPC::BI__builtin_ppc_lbarx:
1042     AsmOS << "lbarx ";
1043     RetType = CGF.Int8Ty;
1044     break;
1045   default:
1046     llvm_unreachable("Expected only PowerPC load reserve intrinsics");
1047   }
1048 
1049   AsmOS << "$0, ${1:y}";
1050 
1051   std::string Constraints = "=r,*Z,~{memory}";
1052   std::string MachineClobbers = CGF.getTarget().getClobbers();
1053   if (!MachineClobbers.empty()) {
1054     Constraints += ',';
1055     Constraints += MachineClobbers;
1056   }
1057 
1058   llvm::Type *IntPtrType = RetType->getPointerTo();
1059   llvm::FunctionType *FTy =
1060       llvm::FunctionType::get(RetType, {IntPtrType}, false);
1061 
1062   llvm::InlineAsm *IA =
1063       llvm::InlineAsm::get(FTy, Asm, Constraints, /*hasSideEffects=*/true);
1064   llvm::CallInst *CI = CGF.Builder.CreateCall(IA, {Addr});
1065   CI->addParamAttr(
1066       0, Attribute::get(CGF.getLLVMContext(), Attribute::ElementType, RetType));
1067   return CI;
1068 }
1069 
1070 namespace {
1071 enum class MSVCSetJmpKind {
1072   _setjmpex,
1073   _setjmp3,
1074   _setjmp
1075 };
1076 }
1077 
1078 /// MSVC handles setjmp a bit differently on different platforms. On every
1079 /// architecture except 32-bit x86, the frame address is passed. On x86, extra
1080 /// parameters can be passed as variadic arguments, but we always pass none.
1081 static RValue EmitMSVCRTSetJmp(CodeGenFunction &CGF, MSVCSetJmpKind SJKind,
1082                                const CallExpr *E) {
1083   llvm::Value *Arg1 = nullptr;
1084   llvm::Type *Arg1Ty = nullptr;
1085   StringRef Name;
1086   bool IsVarArg = false;
1087   if (SJKind == MSVCSetJmpKind::_setjmp3) {
1088     Name = "_setjmp3";
1089     Arg1Ty = CGF.Int32Ty;
1090     Arg1 = llvm::ConstantInt::get(CGF.IntTy, 0);
1091     IsVarArg = true;
1092   } else {
1093     Name = SJKind == MSVCSetJmpKind::_setjmp ? "_setjmp" : "_setjmpex";
1094     Arg1Ty = CGF.Int8PtrTy;
1095     if (CGF.getTarget().getTriple().getArch() == llvm::Triple::aarch64) {
1096       Arg1 = CGF.Builder.CreateCall(
1097           CGF.CGM.getIntrinsic(Intrinsic::sponentry, CGF.AllocaInt8PtrTy));
1098     } else
1099       Arg1 = CGF.Builder.CreateCall(
1100           CGF.CGM.getIntrinsic(Intrinsic::frameaddress, CGF.AllocaInt8PtrTy),
1101           llvm::ConstantInt::get(CGF.Int32Ty, 0));
1102   }
1103 
1104   // Mark the call site and declaration with ReturnsTwice.
1105   llvm::Type *ArgTypes[2] = {CGF.Int8PtrTy, Arg1Ty};
1106   llvm::AttributeList ReturnsTwiceAttr = llvm::AttributeList::get(
1107       CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex,
1108       llvm::Attribute::ReturnsTwice);
1109   llvm::FunctionCallee SetJmpFn = CGF.CGM.CreateRuntimeFunction(
1110       llvm::FunctionType::get(CGF.IntTy, ArgTypes, IsVarArg), Name,
1111       ReturnsTwiceAttr, /*Local=*/true);
1112 
1113   llvm::Value *Buf = CGF.Builder.CreateBitOrPointerCast(
1114       CGF.EmitScalarExpr(E->getArg(0)), CGF.Int8PtrTy);
1115   llvm::Value *Args[] = {Buf, Arg1};
1116   llvm::CallBase *CB = CGF.EmitRuntimeCallOrInvoke(SetJmpFn, Args);
1117   CB->setAttributes(ReturnsTwiceAttr);
1118   return RValue::get(CB);
1119 }
1120 
1121 // Many of MSVC builtins are on x64, ARM and AArch64; to avoid repeating code,
1122 // we handle them here.
1123 enum class CodeGenFunction::MSVCIntrin {
1124   _BitScanForward,
1125   _BitScanReverse,
1126   _InterlockedAnd,
1127   _InterlockedDecrement,
1128   _InterlockedExchange,
1129   _InterlockedExchangeAdd,
1130   _InterlockedExchangeSub,
1131   _InterlockedIncrement,
1132   _InterlockedOr,
1133   _InterlockedXor,
1134   _InterlockedExchangeAdd_acq,
1135   _InterlockedExchangeAdd_rel,
1136   _InterlockedExchangeAdd_nf,
1137   _InterlockedExchange_acq,
1138   _InterlockedExchange_rel,
1139   _InterlockedExchange_nf,
1140   _InterlockedCompareExchange_acq,
1141   _InterlockedCompareExchange_rel,
1142   _InterlockedCompareExchange_nf,
1143   _InterlockedCompareExchange128,
1144   _InterlockedCompareExchange128_acq,
1145   _InterlockedCompareExchange128_rel,
1146   _InterlockedCompareExchange128_nf,
1147   _InterlockedOr_acq,
1148   _InterlockedOr_rel,
1149   _InterlockedOr_nf,
1150   _InterlockedXor_acq,
1151   _InterlockedXor_rel,
1152   _InterlockedXor_nf,
1153   _InterlockedAnd_acq,
1154   _InterlockedAnd_rel,
1155   _InterlockedAnd_nf,
1156   _InterlockedIncrement_acq,
1157   _InterlockedIncrement_rel,
1158   _InterlockedIncrement_nf,
1159   _InterlockedDecrement_acq,
1160   _InterlockedDecrement_rel,
1161   _InterlockedDecrement_nf,
1162   __fastfail,
1163 };
1164 
1165 static Optional<CodeGenFunction::MSVCIntrin>
1166 translateArmToMsvcIntrin(unsigned BuiltinID) {
1167   using MSVCIntrin = CodeGenFunction::MSVCIntrin;
1168   switch (BuiltinID) {
1169   default:
1170     return None;
1171   case ARM::BI_BitScanForward:
1172   case ARM::BI_BitScanForward64:
1173     return MSVCIntrin::_BitScanForward;
1174   case ARM::BI_BitScanReverse:
1175   case ARM::BI_BitScanReverse64:
1176     return MSVCIntrin::_BitScanReverse;
1177   case ARM::BI_InterlockedAnd64:
1178     return MSVCIntrin::_InterlockedAnd;
1179   case ARM::BI_InterlockedExchange64:
1180     return MSVCIntrin::_InterlockedExchange;
1181   case ARM::BI_InterlockedExchangeAdd64:
1182     return MSVCIntrin::_InterlockedExchangeAdd;
1183   case ARM::BI_InterlockedExchangeSub64:
1184     return MSVCIntrin::_InterlockedExchangeSub;
1185   case ARM::BI_InterlockedOr64:
1186     return MSVCIntrin::_InterlockedOr;
1187   case ARM::BI_InterlockedXor64:
1188     return MSVCIntrin::_InterlockedXor;
1189   case ARM::BI_InterlockedDecrement64:
1190     return MSVCIntrin::_InterlockedDecrement;
1191   case ARM::BI_InterlockedIncrement64:
1192     return MSVCIntrin::_InterlockedIncrement;
1193   case ARM::BI_InterlockedExchangeAdd8_acq:
1194   case ARM::BI_InterlockedExchangeAdd16_acq:
1195   case ARM::BI_InterlockedExchangeAdd_acq:
1196   case ARM::BI_InterlockedExchangeAdd64_acq:
1197     return MSVCIntrin::_InterlockedExchangeAdd_acq;
1198   case ARM::BI_InterlockedExchangeAdd8_rel:
1199   case ARM::BI_InterlockedExchangeAdd16_rel:
1200   case ARM::BI_InterlockedExchangeAdd_rel:
1201   case ARM::BI_InterlockedExchangeAdd64_rel:
1202     return MSVCIntrin::_InterlockedExchangeAdd_rel;
1203   case ARM::BI_InterlockedExchangeAdd8_nf:
1204   case ARM::BI_InterlockedExchangeAdd16_nf:
1205   case ARM::BI_InterlockedExchangeAdd_nf:
1206   case ARM::BI_InterlockedExchangeAdd64_nf:
1207     return MSVCIntrin::_InterlockedExchangeAdd_nf;
1208   case ARM::BI_InterlockedExchange8_acq:
1209   case ARM::BI_InterlockedExchange16_acq:
1210   case ARM::BI_InterlockedExchange_acq:
1211   case ARM::BI_InterlockedExchange64_acq:
1212     return MSVCIntrin::_InterlockedExchange_acq;
1213   case ARM::BI_InterlockedExchange8_rel:
1214   case ARM::BI_InterlockedExchange16_rel:
1215   case ARM::BI_InterlockedExchange_rel:
1216   case ARM::BI_InterlockedExchange64_rel:
1217     return MSVCIntrin::_InterlockedExchange_rel;
1218   case ARM::BI_InterlockedExchange8_nf:
1219   case ARM::BI_InterlockedExchange16_nf:
1220   case ARM::BI_InterlockedExchange_nf:
1221   case ARM::BI_InterlockedExchange64_nf:
1222     return MSVCIntrin::_InterlockedExchange_nf;
1223   case ARM::BI_InterlockedCompareExchange8_acq:
1224   case ARM::BI_InterlockedCompareExchange16_acq:
1225   case ARM::BI_InterlockedCompareExchange_acq:
1226   case ARM::BI_InterlockedCompareExchange64_acq:
1227     return MSVCIntrin::_InterlockedCompareExchange_acq;
1228   case ARM::BI_InterlockedCompareExchange8_rel:
1229   case ARM::BI_InterlockedCompareExchange16_rel:
1230   case ARM::BI_InterlockedCompareExchange_rel:
1231   case ARM::BI_InterlockedCompareExchange64_rel:
1232     return MSVCIntrin::_InterlockedCompareExchange_rel;
1233   case ARM::BI_InterlockedCompareExchange8_nf:
1234   case ARM::BI_InterlockedCompareExchange16_nf:
1235   case ARM::BI_InterlockedCompareExchange_nf:
1236   case ARM::BI_InterlockedCompareExchange64_nf:
1237     return MSVCIntrin::_InterlockedCompareExchange_nf;
1238   case ARM::BI_InterlockedOr8_acq:
1239   case ARM::BI_InterlockedOr16_acq:
1240   case ARM::BI_InterlockedOr_acq:
1241   case ARM::BI_InterlockedOr64_acq:
1242     return MSVCIntrin::_InterlockedOr_acq;
1243   case ARM::BI_InterlockedOr8_rel:
1244   case ARM::BI_InterlockedOr16_rel:
1245   case ARM::BI_InterlockedOr_rel:
1246   case ARM::BI_InterlockedOr64_rel:
1247     return MSVCIntrin::_InterlockedOr_rel;
1248   case ARM::BI_InterlockedOr8_nf:
1249   case ARM::BI_InterlockedOr16_nf:
1250   case ARM::BI_InterlockedOr_nf:
1251   case ARM::BI_InterlockedOr64_nf:
1252     return MSVCIntrin::_InterlockedOr_nf;
1253   case ARM::BI_InterlockedXor8_acq:
1254   case ARM::BI_InterlockedXor16_acq:
1255   case ARM::BI_InterlockedXor_acq:
1256   case ARM::BI_InterlockedXor64_acq:
1257     return MSVCIntrin::_InterlockedXor_acq;
1258   case ARM::BI_InterlockedXor8_rel:
1259   case ARM::BI_InterlockedXor16_rel:
1260   case ARM::BI_InterlockedXor_rel:
1261   case ARM::BI_InterlockedXor64_rel:
1262     return MSVCIntrin::_InterlockedXor_rel;
1263   case ARM::BI_InterlockedXor8_nf:
1264   case ARM::BI_InterlockedXor16_nf:
1265   case ARM::BI_InterlockedXor_nf:
1266   case ARM::BI_InterlockedXor64_nf:
1267     return MSVCIntrin::_InterlockedXor_nf;
1268   case ARM::BI_InterlockedAnd8_acq:
1269   case ARM::BI_InterlockedAnd16_acq:
1270   case ARM::BI_InterlockedAnd_acq:
1271   case ARM::BI_InterlockedAnd64_acq:
1272     return MSVCIntrin::_InterlockedAnd_acq;
1273   case ARM::BI_InterlockedAnd8_rel:
1274   case ARM::BI_InterlockedAnd16_rel:
1275   case ARM::BI_InterlockedAnd_rel:
1276   case ARM::BI_InterlockedAnd64_rel:
1277     return MSVCIntrin::_InterlockedAnd_rel;
1278   case ARM::BI_InterlockedAnd8_nf:
1279   case ARM::BI_InterlockedAnd16_nf:
1280   case ARM::BI_InterlockedAnd_nf:
1281   case ARM::BI_InterlockedAnd64_nf:
1282     return MSVCIntrin::_InterlockedAnd_nf;
1283   case ARM::BI_InterlockedIncrement16_acq:
1284   case ARM::BI_InterlockedIncrement_acq:
1285   case ARM::BI_InterlockedIncrement64_acq:
1286     return MSVCIntrin::_InterlockedIncrement_acq;
1287   case ARM::BI_InterlockedIncrement16_rel:
1288   case ARM::BI_InterlockedIncrement_rel:
1289   case ARM::BI_InterlockedIncrement64_rel:
1290     return MSVCIntrin::_InterlockedIncrement_rel;
1291   case ARM::BI_InterlockedIncrement16_nf:
1292   case ARM::BI_InterlockedIncrement_nf:
1293   case ARM::BI_InterlockedIncrement64_nf:
1294     return MSVCIntrin::_InterlockedIncrement_nf;
1295   case ARM::BI_InterlockedDecrement16_acq:
1296   case ARM::BI_InterlockedDecrement_acq:
1297   case ARM::BI_InterlockedDecrement64_acq:
1298     return MSVCIntrin::_InterlockedDecrement_acq;
1299   case ARM::BI_InterlockedDecrement16_rel:
1300   case ARM::BI_InterlockedDecrement_rel:
1301   case ARM::BI_InterlockedDecrement64_rel:
1302     return MSVCIntrin::_InterlockedDecrement_rel;
1303   case ARM::BI_InterlockedDecrement16_nf:
1304   case ARM::BI_InterlockedDecrement_nf:
1305   case ARM::BI_InterlockedDecrement64_nf:
1306     return MSVCIntrin::_InterlockedDecrement_nf;
1307   }
1308   llvm_unreachable("must return from switch");
1309 }
1310 
1311 static Optional<CodeGenFunction::MSVCIntrin>
1312 translateAarch64ToMsvcIntrin(unsigned BuiltinID) {
1313   using MSVCIntrin = CodeGenFunction::MSVCIntrin;
1314   switch (BuiltinID) {
1315   default:
1316     return None;
1317   case AArch64::BI_BitScanForward:
1318   case AArch64::BI_BitScanForward64:
1319     return MSVCIntrin::_BitScanForward;
1320   case AArch64::BI_BitScanReverse:
1321   case AArch64::BI_BitScanReverse64:
1322     return MSVCIntrin::_BitScanReverse;
1323   case AArch64::BI_InterlockedAnd64:
1324     return MSVCIntrin::_InterlockedAnd;
1325   case AArch64::BI_InterlockedExchange64:
1326     return MSVCIntrin::_InterlockedExchange;
1327   case AArch64::BI_InterlockedExchangeAdd64:
1328     return MSVCIntrin::_InterlockedExchangeAdd;
1329   case AArch64::BI_InterlockedExchangeSub64:
1330     return MSVCIntrin::_InterlockedExchangeSub;
1331   case AArch64::BI_InterlockedOr64:
1332     return MSVCIntrin::_InterlockedOr;
1333   case AArch64::BI_InterlockedXor64:
1334     return MSVCIntrin::_InterlockedXor;
1335   case AArch64::BI_InterlockedDecrement64:
1336     return MSVCIntrin::_InterlockedDecrement;
1337   case AArch64::BI_InterlockedIncrement64:
1338     return MSVCIntrin::_InterlockedIncrement;
1339   case AArch64::BI_InterlockedExchangeAdd8_acq:
1340   case AArch64::BI_InterlockedExchangeAdd16_acq:
1341   case AArch64::BI_InterlockedExchangeAdd_acq:
1342   case AArch64::BI_InterlockedExchangeAdd64_acq:
1343     return MSVCIntrin::_InterlockedExchangeAdd_acq;
1344   case AArch64::BI_InterlockedExchangeAdd8_rel:
1345   case AArch64::BI_InterlockedExchangeAdd16_rel:
1346   case AArch64::BI_InterlockedExchangeAdd_rel:
1347   case AArch64::BI_InterlockedExchangeAdd64_rel:
1348     return MSVCIntrin::_InterlockedExchangeAdd_rel;
1349   case AArch64::BI_InterlockedExchangeAdd8_nf:
1350   case AArch64::BI_InterlockedExchangeAdd16_nf:
1351   case AArch64::BI_InterlockedExchangeAdd_nf:
1352   case AArch64::BI_InterlockedExchangeAdd64_nf:
1353     return MSVCIntrin::_InterlockedExchangeAdd_nf;
1354   case AArch64::BI_InterlockedExchange8_acq:
1355   case AArch64::BI_InterlockedExchange16_acq:
1356   case AArch64::BI_InterlockedExchange_acq:
1357   case AArch64::BI_InterlockedExchange64_acq:
1358     return MSVCIntrin::_InterlockedExchange_acq;
1359   case AArch64::BI_InterlockedExchange8_rel:
1360   case AArch64::BI_InterlockedExchange16_rel:
1361   case AArch64::BI_InterlockedExchange_rel:
1362   case AArch64::BI_InterlockedExchange64_rel:
1363     return MSVCIntrin::_InterlockedExchange_rel;
1364   case AArch64::BI_InterlockedExchange8_nf:
1365   case AArch64::BI_InterlockedExchange16_nf:
1366   case AArch64::BI_InterlockedExchange_nf:
1367   case AArch64::BI_InterlockedExchange64_nf:
1368     return MSVCIntrin::_InterlockedExchange_nf;
1369   case AArch64::BI_InterlockedCompareExchange8_acq:
1370   case AArch64::BI_InterlockedCompareExchange16_acq:
1371   case AArch64::BI_InterlockedCompareExchange_acq:
1372   case AArch64::BI_InterlockedCompareExchange64_acq:
1373     return MSVCIntrin::_InterlockedCompareExchange_acq;
1374   case AArch64::BI_InterlockedCompareExchange8_rel:
1375   case AArch64::BI_InterlockedCompareExchange16_rel:
1376   case AArch64::BI_InterlockedCompareExchange_rel:
1377   case AArch64::BI_InterlockedCompareExchange64_rel:
1378     return MSVCIntrin::_InterlockedCompareExchange_rel;
1379   case AArch64::BI_InterlockedCompareExchange8_nf:
1380   case AArch64::BI_InterlockedCompareExchange16_nf:
1381   case AArch64::BI_InterlockedCompareExchange_nf:
1382   case AArch64::BI_InterlockedCompareExchange64_nf:
1383     return MSVCIntrin::_InterlockedCompareExchange_nf;
1384   case AArch64::BI_InterlockedCompareExchange128:
1385     return MSVCIntrin::_InterlockedCompareExchange128;
1386   case AArch64::BI_InterlockedCompareExchange128_acq:
1387     return MSVCIntrin::_InterlockedCompareExchange128_acq;
1388   case AArch64::BI_InterlockedCompareExchange128_nf:
1389     return MSVCIntrin::_InterlockedCompareExchange128_nf;
1390   case AArch64::BI_InterlockedCompareExchange128_rel:
1391     return MSVCIntrin::_InterlockedCompareExchange128_rel;
1392   case AArch64::BI_InterlockedOr8_acq:
1393   case AArch64::BI_InterlockedOr16_acq:
1394   case AArch64::BI_InterlockedOr_acq:
1395   case AArch64::BI_InterlockedOr64_acq:
1396     return MSVCIntrin::_InterlockedOr_acq;
1397   case AArch64::BI_InterlockedOr8_rel:
1398   case AArch64::BI_InterlockedOr16_rel:
1399   case AArch64::BI_InterlockedOr_rel:
1400   case AArch64::BI_InterlockedOr64_rel:
1401     return MSVCIntrin::_InterlockedOr_rel;
1402   case AArch64::BI_InterlockedOr8_nf:
1403   case AArch64::BI_InterlockedOr16_nf:
1404   case AArch64::BI_InterlockedOr_nf:
1405   case AArch64::BI_InterlockedOr64_nf:
1406     return MSVCIntrin::_InterlockedOr_nf;
1407   case AArch64::BI_InterlockedXor8_acq:
1408   case AArch64::BI_InterlockedXor16_acq:
1409   case AArch64::BI_InterlockedXor_acq:
1410   case AArch64::BI_InterlockedXor64_acq:
1411     return MSVCIntrin::_InterlockedXor_acq;
1412   case AArch64::BI_InterlockedXor8_rel:
1413   case AArch64::BI_InterlockedXor16_rel:
1414   case AArch64::BI_InterlockedXor_rel:
1415   case AArch64::BI_InterlockedXor64_rel:
1416     return MSVCIntrin::_InterlockedXor_rel;
1417   case AArch64::BI_InterlockedXor8_nf:
1418   case AArch64::BI_InterlockedXor16_nf:
1419   case AArch64::BI_InterlockedXor_nf:
1420   case AArch64::BI_InterlockedXor64_nf:
1421     return MSVCIntrin::_InterlockedXor_nf;
1422   case AArch64::BI_InterlockedAnd8_acq:
1423   case AArch64::BI_InterlockedAnd16_acq:
1424   case AArch64::BI_InterlockedAnd_acq:
1425   case AArch64::BI_InterlockedAnd64_acq:
1426     return MSVCIntrin::_InterlockedAnd_acq;
1427   case AArch64::BI_InterlockedAnd8_rel:
1428   case AArch64::BI_InterlockedAnd16_rel:
1429   case AArch64::BI_InterlockedAnd_rel:
1430   case AArch64::BI_InterlockedAnd64_rel:
1431     return MSVCIntrin::_InterlockedAnd_rel;
1432   case AArch64::BI_InterlockedAnd8_nf:
1433   case AArch64::BI_InterlockedAnd16_nf:
1434   case AArch64::BI_InterlockedAnd_nf:
1435   case AArch64::BI_InterlockedAnd64_nf:
1436     return MSVCIntrin::_InterlockedAnd_nf;
1437   case AArch64::BI_InterlockedIncrement16_acq:
1438   case AArch64::BI_InterlockedIncrement_acq:
1439   case AArch64::BI_InterlockedIncrement64_acq:
1440     return MSVCIntrin::_InterlockedIncrement_acq;
1441   case AArch64::BI_InterlockedIncrement16_rel:
1442   case AArch64::BI_InterlockedIncrement_rel:
1443   case AArch64::BI_InterlockedIncrement64_rel:
1444     return MSVCIntrin::_InterlockedIncrement_rel;
1445   case AArch64::BI_InterlockedIncrement16_nf:
1446   case AArch64::BI_InterlockedIncrement_nf:
1447   case AArch64::BI_InterlockedIncrement64_nf:
1448     return MSVCIntrin::_InterlockedIncrement_nf;
1449   case AArch64::BI_InterlockedDecrement16_acq:
1450   case AArch64::BI_InterlockedDecrement_acq:
1451   case AArch64::BI_InterlockedDecrement64_acq:
1452     return MSVCIntrin::_InterlockedDecrement_acq;
1453   case AArch64::BI_InterlockedDecrement16_rel:
1454   case AArch64::BI_InterlockedDecrement_rel:
1455   case AArch64::BI_InterlockedDecrement64_rel:
1456     return MSVCIntrin::_InterlockedDecrement_rel;
1457   case AArch64::BI_InterlockedDecrement16_nf:
1458   case AArch64::BI_InterlockedDecrement_nf:
1459   case AArch64::BI_InterlockedDecrement64_nf:
1460     return MSVCIntrin::_InterlockedDecrement_nf;
1461   }
1462   llvm_unreachable("must return from switch");
1463 }
1464 
1465 static Optional<CodeGenFunction::MSVCIntrin>
1466 translateX86ToMsvcIntrin(unsigned BuiltinID) {
1467   using MSVCIntrin = CodeGenFunction::MSVCIntrin;
1468   switch (BuiltinID) {
1469   default:
1470     return None;
1471   case clang::X86::BI_BitScanForward:
1472   case clang::X86::BI_BitScanForward64:
1473     return MSVCIntrin::_BitScanForward;
1474   case clang::X86::BI_BitScanReverse:
1475   case clang::X86::BI_BitScanReverse64:
1476     return MSVCIntrin::_BitScanReverse;
1477   case clang::X86::BI_InterlockedAnd64:
1478     return MSVCIntrin::_InterlockedAnd;
1479   case clang::X86::BI_InterlockedCompareExchange128:
1480     return MSVCIntrin::_InterlockedCompareExchange128;
1481   case clang::X86::BI_InterlockedExchange64:
1482     return MSVCIntrin::_InterlockedExchange;
1483   case clang::X86::BI_InterlockedExchangeAdd64:
1484     return MSVCIntrin::_InterlockedExchangeAdd;
1485   case clang::X86::BI_InterlockedExchangeSub64:
1486     return MSVCIntrin::_InterlockedExchangeSub;
1487   case clang::X86::BI_InterlockedOr64:
1488     return MSVCIntrin::_InterlockedOr;
1489   case clang::X86::BI_InterlockedXor64:
1490     return MSVCIntrin::_InterlockedXor;
1491   case clang::X86::BI_InterlockedDecrement64:
1492     return MSVCIntrin::_InterlockedDecrement;
1493   case clang::X86::BI_InterlockedIncrement64:
1494     return MSVCIntrin::_InterlockedIncrement;
1495   }
1496   llvm_unreachable("must return from switch");
1497 }
1498 
1499 // Emit an MSVC intrinsic. Assumes that arguments have *not* been evaluated.
1500 Value *CodeGenFunction::EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID,
1501                                             const CallExpr *E) {
1502   switch (BuiltinID) {
1503   case MSVCIntrin::_BitScanForward:
1504   case MSVCIntrin::_BitScanReverse: {
1505     Address IndexAddress(EmitPointerWithAlignment(E->getArg(0)));
1506     Value *ArgValue = EmitScalarExpr(E->getArg(1));
1507 
1508     llvm::Type *ArgType = ArgValue->getType();
1509     llvm::Type *IndexType = IndexAddress.getElementType();
1510     llvm::Type *ResultType = ConvertType(E->getType());
1511 
1512     Value *ArgZero = llvm::Constant::getNullValue(ArgType);
1513     Value *ResZero = llvm::Constant::getNullValue(ResultType);
1514     Value *ResOne = llvm::ConstantInt::get(ResultType, 1);
1515 
1516     BasicBlock *Begin = Builder.GetInsertBlock();
1517     BasicBlock *End = createBasicBlock("bitscan_end", this->CurFn);
1518     Builder.SetInsertPoint(End);
1519     PHINode *Result = Builder.CreatePHI(ResultType, 2, "bitscan_result");
1520 
1521     Builder.SetInsertPoint(Begin);
1522     Value *IsZero = Builder.CreateICmpEQ(ArgValue, ArgZero);
1523     BasicBlock *NotZero = createBasicBlock("bitscan_not_zero", this->CurFn);
1524     Builder.CreateCondBr(IsZero, End, NotZero);
1525     Result->addIncoming(ResZero, Begin);
1526 
1527     Builder.SetInsertPoint(NotZero);
1528 
1529     if (BuiltinID == MSVCIntrin::_BitScanForward) {
1530       Function *F = CGM.getIntrinsic(Intrinsic::cttz, ArgType);
1531       Value *ZeroCount = Builder.CreateCall(F, {ArgValue, Builder.getTrue()});
1532       ZeroCount = Builder.CreateIntCast(ZeroCount, IndexType, false);
1533       Builder.CreateStore(ZeroCount, IndexAddress, false);
1534     } else {
1535       unsigned ArgWidth = cast<llvm::IntegerType>(ArgType)->getBitWidth();
1536       Value *ArgTypeLastIndex = llvm::ConstantInt::get(IndexType, ArgWidth - 1);
1537 
1538       Function *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
1539       Value *ZeroCount = Builder.CreateCall(F, {ArgValue, Builder.getTrue()});
1540       ZeroCount = Builder.CreateIntCast(ZeroCount, IndexType, false);
1541       Value *Index = Builder.CreateNSWSub(ArgTypeLastIndex, ZeroCount);
1542       Builder.CreateStore(Index, IndexAddress, false);
1543     }
1544     Builder.CreateBr(End);
1545     Result->addIncoming(ResOne, NotZero);
1546 
1547     Builder.SetInsertPoint(End);
1548     return Result;
1549   }
1550   case MSVCIntrin::_InterlockedAnd:
1551     return MakeBinaryAtomicValue(*this, AtomicRMWInst::And, E);
1552   case MSVCIntrin::_InterlockedExchange:
1553     return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xchg, E);
1554   case MSVCIntrin::_InterlockedExchangeAdd:
1555     return MakeBinaryAtomicValue(*this, AtomicRMWInst::Add, E);
1556   case MSVCIntrin::_InterlockedExchangeSub:
1557     return MakeBinaryAtomicValue(*this, AtomicRMWInst::Sub, E);
1558   case MSVCIntrin::_InterlockedOr:
1559     return MakeBinaryAtomicValue(*this, AtomicRMWInst::Or, E);
1560   case MSVCIntrin::_InterlockedXor:
1561     return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xor, E);
1562   case MSVCIntrin::_InterlockedExchangeAdd_acq:
1563     return MakeBinaryAtomicValue(*this, AtomicRMWInst::Add, E,
1564                                  AtomicOrdering::Acquire);
1565   case MSVCIntrin::_InterlockedExchangeAdd_rel:
1566     return MakeBinaryAtomicValue(*this, AtomicRMWInst::Add, E,
1567                                  AtomicOrdering::Release);
1568   case MSVCIntrin::_InterlockedExchangeAdd_nf:
1569     return MakeBinaryAtomicValue(*this, AtomicRMWInst::Add, E,
1570                                  AtomicOrdering::Monotonic);
1571   case MSVCIntrin::_InterlockedExchange_acq:
1572     return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xchg, E,
1573                                  AtomicOrdering::Acquire);
1574   case MSVCIntrin::_InterlockedExchange_rel:
1575     return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xchg, E,
1576                                  AtomicOrdering::Release);
1577   case MSVCIntrin::_InterlockedExchange_nf:
1578     return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xchg, E,
1579                                  AtomicOrdering::Monotonic);
1580   case MSVCIntrin::_InterlockedCompareExchange_acq:
1581     return EmitAtomicCmpXchgForMSIntrin(*this, E, AtomicOrdering::Acquire);
1582   case MSVCIntrin::_InterlockedCompareExchange_rel:
1583     return EmitAtomicCmpXchgForMSIntrin(*this, E, AtomicOrdering::Release);
1584   case MSVCIntrin::_InterlockedCompareExchange_nf:
1585     return EmitAtomicCmpXchgForMSIntrin(*this, E, AtomicOrdering::Monotonic);
1586   case MSVCIntrin::_InterlockedCompareExchange128:
1587     return EmitAtomicCmpXchg128ForMSIntrin(
1588         *this, E, AtomicOrdering::SequentiallyConsistent);
1589   case MSVCIntrin::_InterlockedCompareExchange128_acq:
1590     return EmitAtomicCmpXchg128ForMSIntrin(*this, E, AtomicOrdering::Acquire);
1591   case MSVCIntrin::_InterlockedCompareExchange128_rel:
1592     return EmitAtomicCmpXchg128ForMSIntrin(*this, E, AtomicOrdering::Release);
1593   case MSVCIntrin::_InterlockedCompareExchange128_nf:
1594     return EmitAtomicCmpXchg128ForMSIntrin(*this, E, AtomicOrdering::Monotonic);
1595   case MSVCIntrin::_InterlockedOr_acq:
1596     return MakeBinaryAtomicValue(*this, AtomicRMWInst::Or, E,
1597                                  AtomicOrdering::Acquire);
1598   case MSVCIntrin::_InterlockedOr_rel:
1599     return MakeBinaryAtomicValue(*this, AtomicRMWInst::Or, E,
1600                                  AtomicOrdering::Release);
1601   case MSVCIntrin::_InterlockedOr_nf:
1602     return MakeBinaryAtomicValue(*this, AtomicRMWInst::Or, E,
1603                                  AtomicOrdering::Monotonic);
1604   case MSVCIntrin::_InterlockedXor_acq:
1605     return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xor, E,
1606                                  AtomicOrdering::Acquire);
1607   case MSVCIntrin::_InterlockedXor_rel:
1608     return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xor, E,
1609                                  AtomicOrdering::Release);
1610   case MSVCIntrin::_InterlockedXor_nf:
1611     return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xor, E,
1612                                  AtomicOrdering::Monotonic);
1613   case MSVCIntrin::_InterlockedAnd_acq:
1614     return MakeBinaryAtomicValue(*this, AtomicRMWInst::And, E,
1615                                  AtomicOrdering::Acquire);
1616   case MSVCIntrin::_InterlockedAnd_rel:
1617     return MakeBinaryAtomicValue(*this, AtomicRMWInst::And, E,
1618                                  AtomicOrdering::Release);
1619   case MSVCIntrin::_InterlockedAnd_nf:
1620     return MakeBinaryAtomicValue(*this, AtomicRMWInst::And, E,
1621                                  AtomicOrdering::Monotonic);
1622   case MSVCIntrin::_InterlockedIncrement_acq:
1623     return EmitAtomicIncrementValue(*this, E, AtomicOrdering::Acquire);
1624   case MSVCIntrin::_InterlockedIncrement_rel:
1625     return EmitAtomicIncrementValue(*this, E, AtomicOrdering::Release);
1626   case MSVCIntrin::_InterlockedIncrement_nf:
1627     return EmitAtomicIncrementValue(*this, E, AtomicOrdering::Monotonic);
1628   case MSVCIntrin::_InterlockedDecrement_acq:
1629     return EmitAtomicDecrementValue(*this, E, AtomicOrdering::Acquire);
1630   case MSVCIntrin::_InterlockedDecrement_rel:
1631     return EmitAtomicDecrementValue(*this, E, AtomicOrdering::Release);
1632   case MSVCIntrin::_InterlockedDecrement_nf:
1633     return EmitAtomicDecrementValue(*this, E, AtomicOrdering::Monotonic);
1634 
1635   case MSVCIntrin::_InterlockedDecrement:
1636     return EmitAtomicDecrementValue(*this, E);
1637   case MSVCIntrin::_InterlockedIncrement:
1638     return EmitAtomicIncrementValue(*this, E);
1639 
1640   case MSVCIntrin::__fastfail: {
1641     // Request immediate process termination from the kernel. The instruction
1642     // sequences to do this are documented on MSDN:
1643     // https://msdn.microsoft.com/en-us/library/dn774154.aspx
1644     llvm::Triple::ArchType ISA = getTarget().getTriple().getArch();
1645     StringRef Asm, Constraints;
1646     switch (ISA) {
1647     default:
1648       ErrorUnsupported(E, "__fastfail call for this architecture");
1649       break;
1650     case llvm::Triple::x86:
1651     case llvm::Triple::x86_64:
1652       Asm = "int $$0x29";
1653       Constraints = "{cx}";
1654       break;
1655     case llvm::Triple::thumb:
1656       Asm = "udf #251";
1657       Constraints = "{r0}";
1658       break;
1659     case llvm::Triple::aarch64:
1660       Asm = "brk #0xF003";
1661       Constraints = "{w0}";
1662     }
1663     llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, {Int32Ty}, false);
1664     llvm::InlineAsm *IA =
1665         llvm::InlineAsm::get(FTy, Asm, Constraints, /*hasSideEffects=*/true);
1666     llvm::AttributeList NoReturnAttr = llvm::AttributeList::get(
1667         getLLVMContext(), llvm::AttributeList::FunctionIndex,
1668         llvm::Attribute::NoReturn);
1669     llvm::CallInst *CI = Builder.CreateCall(IA, EmitScalarExpr(E->getArg(0)));
1670     CI->setAttributes(NoReturnAttr);
1671     return CI;
1672   }
1673   }
1674   llvm_unreachable("Incorrect MSVC intrinsic!");
1675 }
1676 
1677 namespace {
1678 // ARC cleanup for __builtin_os_log_format
1679 struct CallObjCArcUse final : EHScopeStack::Cleanup {
1680   CallObjCArcUse(llvm::Value *object) : object(object) {}
1681   llvm::Value *object;
1682 
1683   void Emit(CodeGenFunction &CGF, Flags flags) override {
1684     CGF.EmitARCIntrinsicUse(object);
1685   }
1686 };
1687 }
1688 
1689 Value *CodeGenFunction::EmitCheckedArgForBuiltin(const Expr *E,
1690                                                  BuiltinCheckKind Kind) {
1691   assert((Kind == BCK_CLZPassedZero || Kind == BCK_CTZPassedZero)
1692           && "Unsupported builtin check kind");
1693 
1694   Value *ArgValue = EmitScalarExpr(E);
1695   if (!SanOpts.has(SanitizerKind::Builtin) || !getTarget().isCLZForZeroUndef())
1696     return ArgValue;
1697 
1698   SanitizerScope SanScope(this);
1699   Value *Cond = Builder.CreateICmpNE(
1700       ArgValue, llvm::Constant::getNullValue(ArgValue->getType()));
1701   EmitCheck(std::make_pair(Cond, SanitizerKind::Builtin),
1702             SanitizerHandler::InvalidBuiltin,
1703             {EmitCheckSourceLocation(E->getExprLoc()),
1704              llvm::ConstantInt::get(Builder.getInt8Ty(), Kind)},
1705             None);
1706   return ArgValue;
1707 }
1708 
1709 /// Get the argument type for arguments to os_log_helper.
1710 static CanQualType getOSLogArgType(ASTContext &C, int Size) {
1711   QualType UnsignedTy = C.getIntTypeForBitwidth(Size * 8, /*Signed=*/false);
1712   return C.getCanonicalType(UnsignedTy);
1713 }
1714 
1715 llvm::Function *CodeGenFunction::generateBuiltinOSLogHelperFunction(
1716     const analyze_os_log::OSLogBufferLayout &Layout,
1717     CharUnits BufferAlignment) {
1718   ASTContext &Ctx = getContext();
1719 
1720   llvm::SmallString<64> Name;
1721   {
1722     raw_svector_ostream OS(Name);
1723     OS << "__os_log_helper";
1724     OS << "_" << BufferAlignment.getQuantity();
1725     OS << "_" << int(Layout.getSummaryByte());
1726     OS << "_" << int(Layout.getNumArgsByte());
1727     for (const auto &Item : Layout.Items)
1728       OS << "_" << int(Item.getSizeByte()) << "_"
1729          << int(Item.getDescriptorByte());
1730   }
1731 
1732   if (llvm::Function *F = CGM.getModule().getFunction(Name))
1733     return F;
1734 
1735   llvm::SmallVector<QualType, 4> ArgTys;
1736   FunctionArgList Args;
1737   Args.push_back(ImplicitParamDecl::Create(
1738       Ctx, nullptr, SourceLocation(), &Ctx.Idents.get("buffer"), Ctx.VoidPtrTy,
1739       ImplicitParamDecl::Other));
1740   ArgTys.emplace_back(Ctx.VoidPtrTy);
1741 
1742   for (unsigned int I = 0, E = Layout.Items.size(); I < E; ++I) {
1743     char Size = Layout.Items[I].getSizeByte();
1744     if (!Size)
1745       continue;
1746 
1747     QualType ArgTy = getOSLogArgType(Ctx, Size);
1748     Args.push_back(ImplicitParamDecl::Create(
1749         Ctx, nullptr, SourceLocation(),
1750         &Ctx.Idents.get(std::string("arg") + llvm::to_string(I)), ArgTy,
1751         ImplicitParamDecl::Other));
1752     ArgTys.emplace_back(ArgTy);
1753   }
1754 
1755   QualType ReturnTy = Ctx.VoidTy;
1756 
1757   // The helper function has linkonce_odr linkage to enable the linker to merge
1758   // identical functions. To ensure the merging always happens, 'noinline' is
1759   // attached to the function when compiling with -Oz.
1760   const CGFunctionInfo &FI =
1761       CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, Args);
1762   llvm::FunctionType *FuncTy = CGM.getTypes().GetFunctionType(FI);
1763   llvm::Function *Fn = llvm::Function::Create(
1764       FuncTy, llvm::GlobalValue::LinkOnceODRLinkage, Name, &CGM.getModule());
1765   Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
1766   CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Fn, /*IsThunk=*/false);
1767   CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Fn);
1768   Fn->setDoesNotThrow();
1769 
1770   // Attach 'noinline' at -Oz.
1771   if (CGM.getCodeGenOpts().OptimizeSize == 2)
1772     Fn->addFnAttr(llvm::Attribute::NoInline);
1773 
1774   auto NL = ApplyDebugLocation::CreateEmpty(*this);
1775   StartFunction(GlobalDecl(), ReturnTy, Fn, FI, Args);
1776 
1777   // Create a scope with an artificial location for the body of this function.
1778   auto AL = ApplyDebugLocation::CreateArtificial(*this);
1779 
1780   CharUnits Offset;
1781   Address BufAddr(Builder.CreateLoad(GetAddrOfLocalVar(Args[0]), "buf"),
1782                   BufferAlignment);
1783   Builder.CreateStore(Builder.getInt8(Layout.getSummaryByte()),
1784                       Builder.CreateConstByteGEP(BufAddr, Offset++, "summary"));
1785   Builder.CreateStore(Builder.getInt8(Layout.getNumArgsByte()),
1786                       Builder.CreateConstByteGEP(BufAddr, Offset++, "numArgs"));
1787 
1788   unsigned I = 1;
1789   for (const auto &Item : Layout.Items) {
1790     Builder.CreateStore(
1791         Builder.getInt8(Item.getDescriptorByte()),
1792         Builder.CreateConstByteGEP(BufAddr, Offset++, "argDescriptor"));
1793     Builder.CreateStore(
1794         Builder.getInt8(Item.getSizeByte()),
1795         Builder.CreateConstByteGEP(BufAddr, Offset++, "argSize"));
1796 
1797     CharUnits Size = Item.size();
1798     if (!Size.getQuantity())
1799       continue;
1800 
1801     Address Arg = GetAddrOfLocalVar(Args[I]);
1802     Address Addr = Builder.CreateConstByteGEP(BufAddr, Offset, "argData");
1803     Addr = Builder.CreateBitCast(Addr, Arg.getPointer()->getType(),
1804                                  "argDataCast");
1805     Builder.CreateStore(Builder.CreateLoad(Arg), Addr);
1806     Offset += Size;
1807     ++I;
1808   }
1809 
1810   FinishFunction();
1811 
1812   return Fn;
1813 }
1814 
1815 RValue CodeGenFunction::emitBuiltinOSLogFormat(const CallExpr &E) {
1816   assert(E.getNumArgs() >= 2 &&
1817          "__builtin_os_log_format takes at least 2 arguments");
1818   ASTContext &Ctx = getContext();
1819   analyze_os_log::OSLogBufferLayout Layout;
1820   analyze_os_log::computeOSLogBufferLayout(Ctx, &E, Layout);
1821   Address BufAddr = EmitPointerWithAlignment(E.getArg(0));
1822   llvm::SmallVector<llvm::Value *, 4> RetainableOperands;
1823 
1824   // Ignore argument 1, the format string. It is not currently used.
1825   CallArgList Args;
1826   Args.add(RValue::get(BufAddr.getPointer()), Ctx.VoidPtrTy);
1827 
1828   for (const auto &Item : Layout.Items) {
1829     int Size = Item.getSizeByte();
1830     if (!Size)
1831       continue;
1832 
1833     llvm::Value *ArgVal;
1834 
1835     if (Item.getKind() == analyze_os_log::OSLogBufferItem::MaskKind) {
1836       uint64_t Val = 0;
1837       for (unsigned I = 0, E = Item.getMaskType().size(); I < E; ++I)
1838         Val |= ((uint64_t)Item.getMaskType()[I]) << I * 8;
1839       ArgVal = llvm::Constant::getIntegerValue(Int64Ty, llvm::APInt(64, Val));
1840     } else if (const Expr *TheExpr = Item.getExpr()) {
1841       ArgVal = EmitScalarExpr(TheExpr, /*Ignore*/ false);
1842 
1843       // If a temporary object that requires destruction after the full
1844       // expression is passed, push a lifetime-extended cleanup to extend its
1845       // lifetime to the end of the enclosing block scope.
1846       auto LifetimeExtendObject = [&](const Expr *E) {
1847         E = E->IgnoreParenCasts();
1848         // Extend lifetimes of objects returned by function calls and message
1849         // sends.
1850 
1851         // FIXME: We should do this in other cases in which temporaries are
1852         //        created including arguments of non-ARC types (e.g., C++
1853         //        temporaries).
1854         if (isa<CallExpr>(E) || isa<ObjCMessageExpr>(E))
1855           return true;
1856         return false;
1857       };
1858 
1859       if (TheExpr->getType()->isObjCRetainableType() &&
1860           getLangOpts().ObjCAutoRefCount && LifetimeExtendObject(TheExpr)) {
1861         assert(getEvaluationKind(TheExpr->getType()) == TEK_Scalar &&
1862                "Only scalar can be a ObjC retainable type");
1863         if (!isa<Constant>(ArgVal)) {
1864           CleanupKind Cleanup = getARCCleanupKind();
1865           QualType Ty = TheExpr->getType();
1866           Address Alloca = Address::invalid();
1867           Address Addr = CreateMemTemp(Ty, "os.log.arg", &Alloca);
1868           ArgVal = EmitARCRetain(Ty, ArgVal);
1869           Builder.CreateStore(ArgVal, Addr);
1870           pushLifetimeExtendedDestroy(Cleanup, Alloca, Ty,
1871                                       CodeGenFunction::destroyARCStrongPrecise,
1872                                       Cleanup & EHCleanup);
1873 
1874           // Push a clang.arc.use call to ensure ARC optimizer knows that the
1875           // argument has to be alive.
1876           if (CGM.getCodeGenOpts().OptimizationLevel != 0)
1877             pushCleanupAfterFullExpr<CallObjCArcUse>(Cleanup, ArgVal);
1878         }
1879       }
1880     } else {
1881       ArgVal = Builder.getInt32(Item.getConstValue().getQuantity());
1882     }
1883 
1884     unsigned ArgValSize =
1885         CGM.getDataLayout().getTypeSizeInBits(ArgVal->getType());
1886     llvm::IntegerType *IntTy = llvm::Type::getIntNTy(getLLVMContext(),
1887                                                      ArgValSize);
1888     ArgVal = Builder.CreateBitOrPointerCast(ArgVal, IntTy);
1889     CanQualType ArgTy = getOSLogArgType(Ctx, Size);
1890     // If ArgVal has type x86_fp80, zero-extend ArgVal.
1891     ArgVal = Builder.CreateZExtOrBitCast(ArgVal, ConvertType(ArgTy));
1892     Args.add(RValue::get(ArgVal), ArgTy);
1893   }
1894 
1895   const CGFunctionInfo &FI =
1896       CGM.getTypes().arrangeBuiltinFunctionCall(Ctx.VoidTy, Args);
1897   llvm::Function *F = CodeGenFunction(CGM).generateBuiltinOSLogHelperFunction(
1898       Layout, BufAddr.getAlignment());
1899   EmitCall(FI, CGCallee::forDirect(F), ReturnValueSlot(), Args);
1900   return RValue::get(BufAddr.getPointer());
1901 }
1902 
1903 static bool isSpecialUnsignedMultiplySignedResult(
1904     unsigned BuiltinID, WidthAndSignedness Op1Info, WidthAndSignedness Op2Info,
1905     WidthAndSignedness ResultInfo) {
1906   return BuiltinID == Builtin::BI__builtin_mul_overflow &&
1907          Op1Info.Width == Op2Info.Width && Op2Info.Width == ResultInfo.Width &&
1908          !Op1Info.Signed && !Op2Info.Signed && ResultInfo.Signed;
1909 }
1910 
1911 static RValue EmitCheckedUnsignedMultiplySignedResult(
1912     CodeGenFunction &CGF, const clang::Expr *Op1, WidthAndSignedness Op1Info,
1913     const clang::Expr *Op2, WidthAndSignedness Op2Info,
1914     const clang::Expr *ResultArg, QualType ResultQTy,
1915     WidthAndSignedness ResultInfo) {
1916   assert(isSpecialUnsignedMultiplySignedResult(
1917              Builtin::BI__builtin_mul_overflow, Op1Info, Op2Info, ResultInfo) &&
1918          "Cannot specialize this multiply");
1919 
1920   llvm::Value *V1 = CGF.EmitScalarExpr(Op1);
1921   llvm::Value *V2 = CGF.EmitScalarExpr(Op2);
1922 
1923   llvm::Value *HasOverflow;
1924   llvm::Value *Result = EmitOverflowIntrinsic(
1925       CGF, llvm::Intrinsic::umul_with_overflow, V1, V2, HasOverflow);
1926 
1927   // The intrinsic call will detect overflow when the value is > UINT_MAX,
1928   // however, since the original builtin had a signed result, we need to report
1929   // an overflow when the result is greater than INT_MAX.
1930   auto IntMax = llvm::APInt::getSignedMaxValue(ResultInfo.Width);
1931   llvm::Value *IntMaxValue = llvm::ConstantInt::get(Result->getType(), IntMax);
1932 
1933   llvm::Value *IntMaxOverflow = CGF.Builder.CreateICmpUGT(Result, IntMaxValue);
1934   HasOverflow = CGF.Builder.CreateOr(HasOverflow, IntMaxOverflow);
1935 
1936   bool isVolatile =
1937       ResultArg->getType()->getPointeeType().isVolatileQualified();
1938   Address ResultPtr = CGF.EmitPointerWithAlignment(ResultArg);
1939   CGF.Builder.CreateStore(CGF.EmitToMemory(Result, ResultQTy), ResultPtr,
1940                           isVolatile);
1941   return RValue::get(HasOverflow);
1942 }
1943 
1944 /// Determine if a binop is a checked mixed-sign multiply we can specialize.
1945 static bool isSpecialMixedSignMultiply(unsigned BuiltinID,
1946                                        WidthAndSignedness Op1Info,
1947                                        WidthAndSignedness Op2Info,
1948                                        WidthAndSignedness ResultInfo) {
1949   return BuiltinID == Builtin::BI__builtin_mul_overflow &&
1950          std::max(Op1Info.Width, Op2Info.Width) >= ResultInfo.Width &&
1951          Op1Info.Signed != Op2Info.Signed;
1952 }
1953 
1954 /// Emit a checked mixed-sign multiply. This is a cheaper specialization of
1955 /// the generic checked-binop irgen.
1956 static RValue
1957 EmitCheckedMixedSignMultiply(CodeGenFunction &CGF, const clang::Expr *Op1,
1958                              WidthAndSignedness Op1Info, const clang::Expr *Op2,
1959                              WidthAndSignedness Op2Info,
1960                              const clang::Expr *ResultArg, QualType ResultQTy,
1961                              WidthAndSignedness ResultInfo) {
1962   assert(isSpecialMixedSignMultiply(Builtin::BI__builtin_mul_overflow, Op1Info,
1963                                     Op2Info, ResultInfo) &&
1964          "Not a mixed-sign multipliction we can specialize");
1965 
1966   // Emit the signed and unsigned operands.
1967   const clang::Expr *SignedOp = Op1Info.Signed ? Op1 : Op2;
1968   const clang::Expr *UnsignedOp = Op1Info.Signed ? Op2 : Op1;
1969   llvm::Value *Signed = CGF.EmitScalarExpr(SignedOp);
1970   llvm::Value *Unsigned = CGF.EmitScalarExpr(UnsignedOp);
1971   unsigned SignedOpWidth = Op1Info.Signed ? Op1Info.Width : Op2Info.Width;
1972   unsigned UnsignedOpWidth = Op1Info.Signed ? Op2Info.Width : Op1Info.Width;
1973 
1974   // One of the operands may be smaller than the other. If so, [s|z]ext it.
1975   if (SignedOpWidth < UnsignedOpWidth)
1976     Signed = CGF.Builder.CreateSExt(Signed, Unsigned->getType(), "op.sext");
1977   if (UnsignedOpWidth < SignedOpWidth)
1978     Unsigned = CGF.Builder.CreateZExt(Unsigned, Signed->getType(), "op.zext");
1979 
1980   llvm::Type *OpTy = Signed->getType();
1981   llvm::Value *Zero = llvm::Constant::getNullValue(OpTy);
1982   Address ResultPtr = CGF.EmitPointerWithAlignment(ResultArg);
1983   llvm::Type *ResTy = ResultPtr.getElementType();
1984   unsigned OpWidth = std::max(Op1Info.Width, Op2Info.Width);
1985 
1986   // Take the absolute value of the signed operand.
1987   llvm::Value *IsNegative = CGF.Builder.CreateICmpSLT(Signed, Zero);
1988   llvm::Value *AbsOfNegative = CGF.Builder.CreateSub(Zero, Signed);
1989   llvm::Value *AbsSigned =
1990       CGF.Builder.CreateSelect(IsNegative, AbsOfNegative, Signed);
1991 
1992   // Perform a checked unsigned multiplication.
1993   llvm::Value *UnsignedOverflow;
1994   llvm::Value *UnsignedResult =
1995       EmitOverflowIntrinsic(CGF, llvm::Intrinsic::umul_with_overflow, AbsSigned,
1996                             Unsigned, UnsignedOverflow);
1997 
1998   llvm::Value *Overflow, *Result;
1999   if (ResultInfo.Signed) {
2000     // Signed overflow occurs if the result is greater than INT_MAX or lesser
2001     // than INT_MIN, i.e when |Result| > (INT_MAX + IsNegative).
2002     auto IntMax =
2003         llvm::APInt::getSignedMaxValue(ResultInfo.Width).zextOrSelf(OpWidth);
2004     llvm::Value *MaxResult =
2005         CGF.Builder.CreateAdd(llvm::ConstantInt::get(OpTy, IntMax),
2006                               CGF.Builder.CreateZExt(IsNegative, OpTy));
2007     llvm::Value *SignedOverflow =
2008         CGF.Builder.CreateICmpUGT(UnsignedResult, MaxResult);
2009     Overflow = CGF.Builder.CreateOr(UnsignedOverflow, SignedOverflow);
2010 
2011     // Prepare the signed result (possibly by negating it).
2012     llvm::Value *NegativeResult = CGF.Builder.CreateNeg(UnsignedResult);
2013     llvm::Value *SignedResult =
2014         CGF.Builder.CreateSelect(IsNegative, NegativeResult, UnsignedResult);
2015     Result = CGF.Builder.CreateTrunc(SignedResult, ResTy);
2016   } else {
2017     // Unsigned overflow occurs if the result is < 0 or greater than UINT_MAX.
2018     llvm::Value *Underflow = CGF.Builder.CreateAnd(
2019         IsNegative, CGF.Builder.CreateIsNotNull(UnsignedResult));
2020     Overflow = CGF.Builder.CreateOr(UnsignedOverflow, Underflow);
2021     if (ResultInfo.Width < OpWidth) {
2022       auto IntMax =
2023           llvm::APInt::getMaxValue(ResultInfo.Width).zext(OpWidth);
2024       llvm::Value *TruncOverflow = CGF.Builder.CreateICmpUGT(
2025           UnsignedResult, llvm::ConstantInt::get(OpTy, IntMax));
2026       Overflow = CGF.Builder.CreateOr(Overflow, TruncOverflow);
2027     }
2028 
2029     // Negate the product if it would be negative in infinite precision.
2030     Result = CGF.Builder.CreateSelect(
2031         IsNegative, CGF.Builder.CreateNeg(UnsignedResult), UnsignedResult);
2032 
2033     Result = CGF.Builder.CreateTrunc(Result, ResTy);
2034   }
2035   assert(Overflow && Result && "Missing overflow or result");
2036 
2037   bool isVolatile =
2038       ResultArg->getType()->getPointeeType().isVolatileQualified();
2039   CGF.Builder.CreateStore(CGF.EmitToMemory(Result, ResultQTy), ResultPtr,
2040                           isVolatile);
2041   return RValue::get(Overflow);
2042 }
2043 
2044 static llvm::Value *dumpRecord(CodeGenFunction &CGF, QualType RType,
2045                                Value *&RecordPtr, CharUnits Align,
2046                                llvm::FunctionCallee Func, int Lvl) {
2047   ASTContext &Context = CGF.getContext();
2048   RecordDecl *RD = RType->castAs<RecordType>()->getDecl()->getDefinition();
2049   std::string Pad = std::string(Lvl * 4, ' ');
2050 
2051   Value *GString =
2052       CGF.Builder.CreateGlobalStringPtr(RType.getAsString() + " {\n");
2053   Value *Res = CGF.Builder.CreateCall(Func, {GString});
2054 
2055   static llvm::DenseMap<QualType, const char *> Types;
2056   if (Types.empty()) {
2057     Types[Context.CharTy] = "%c";
2058     Types[Context.BoolTy] = "%d";
2059     Types[Context.SignedCharTy] = "%hhd";
2060     Types[Context.UnsignedCharTy] = "%hhu";
2061     Types[Context.IntTy] = "%d";
2062     Types[Context.UnsignedIntTy] = "%u";
2063     Types[Context.LongTy] = "%ld";
2064     Types[Context.UnsignedLongTy] = "%lu";
2065     Types[Context.LongLongTy] = "%lld";
2066     Types[Context.UnsignedLongLongTy] = "%llu";
2067     Types[Context.ShortTy] = "%hd";
2068     Types[Context.UnsignedShortTy] = "%hu";
2069     Types[Context.VoidPtrTy] = "%p";
2070     Types[Context.FloatTy] = "%f";
2071     Types[Context.DoubleTy] = "%f";
2072     Types[Context.LongDoubleTy] = "%Lf";
2073     Types[Context.getPointerType(Context.CharTy)] = "%s";
2074     Types[Context.getPointerType(Context.getConstType(Context.CharTy))] = "%s";
2075   }
2076 
2077   for (const auto *FD : RD->fields()) {
2078     Value *FieldPtr = RecordPtr;
2079     if (RD->isUnion())
2080       FieldPtr = CGF.Builder.CreatePointerCast(
2081           FieldPtr, CGF.ConvertType(Context.getPointerType(FD->getType())));
2082     else
2083       FieldPtr = CGF.Builder.CreateStructGEP(CGF.ConvertType(RType), FieldPtr,
2084                                              FD->getFieldIndex());
2085 
2086     GString = CGF.Builder.CreateGlobalStringPtr(
2087         llvm::Twine(Pad)
2088             .concat(FD->getType().getAsString())
2089             .concat(llvm::Twine(' '))
2090             .concat(FD->getNameAsString())
2091             .concat(" : ")
2092             .str());
2093     Value *TmpRes = CGF.Builder.CreateCall(Func, {GString});
2094     Res = CGF.Builder.CreateAdd(Res, TmpRes);
2095 
2096     QualType CanonicalType =
2097         FD->getType().getUnqualifiedType().getCanonicalType();
2098 
2099     // We check whether we are in a recursive type
2100     if (CanonicalType->isRecordType()) {
2101       TmpRes = dumpRecord(CGF, CanonicalType, FieldPtr, Align, Func, Lvl + 1);
2102       Res = CGF.Builder.CreateAdd(TmpRes, Res);
2103       continue;
2104     }
2105 
2106     // We try to determine the best format to print the current field
2107     llvm::Twine Format = Types.find(CanonicalType) == Types.end()
2108                              ? Types[Context.VoidPtrTy]
2109                              : Types[CanonicalType];
2110 
2111     Address FieldAddress = Address(FieldPtr, Align);
2112     FieldPtr = CGF.Builder.CreateLoad(FieldAddress);
2113 
2114     // FIXME Need to handle bitfield here
2115     GString = CGF.Builder.CreateGlobalStringPtr(
2116         Format.concat(llvm::Twine('\n')).str());
2117     TmpRes = CGF.Builder.CreateCall(Func, {GString, FieldPtr});
2118     Res = CGF.Builder.CreateAdd(Res, TmpRes);
2119   }
2120 
2121   GString = CGF.Builder.CreateGlobalStringPtr(Pad + "}\n");
2122   Value *TmpRes = CGF.Builder.CreateCall(Func, {GString});
2123   Res = CGF.Builder.CreateAdd(Res, TmpRes);
2124   return Res;
2125 }
2126 
2127 static bool
2128 TypeRequiresBuiltinLaunderImp(const ASTContext &Ctx, QualType Ty,
2129                               llvm::SmallPtrSetImpl<const Decl *> &Seen) {
2130   if (const auto *Arr = Ctx.getAsArrayType(Ty))
2131     Ty = Ctx.getBaseElementType(Arr);
2132 
2133   const auto *Record = Ty->getAsCXXRecordDecl();
2134   if (!Record)
2135     return false;
2136 
2137   // We've already checked this type, or are in the process of checking it.
2138   if (!Seen.insert(Record).second)
2139     return false;
2140 
2141   assert(Record->hasDefinition() &&
2142          "Incomplete types should already be diagnosed");
2143 
2144   if (Record->isDynamicClass())
2145     return true;
2146 
2147   for (FieldDecl *F : Record->fields()) {
2148     if (TypeRequiresBuiltinLaunderImp(Ctx, F->getType(), Seen))
2149       return true;
2150   }
2151   return false;
2152 }
2153 
2154 /// Determine if the specified type requires laundering by checking if it is a
2155 /// dynamic class type or contains a subobject which is a dynamic class type.
2156 static bool TypeRequiresBuiltinLaunder(CodeGenModule &CGM, QualType Ty) {
2157   if (!CGM.getCodeGenOpts().StrictVTablePointers)
2158     return false;
2159   llvm::SmallPtrSet<const Decl *, 16> Seen;
2160   return TypeRequiresBuiltinLaunderImp(CGM.getContext(), Ty, Seen);
2161 }
2162 
2163 RValue CodeGenFunction::emitRotate(const CallExpr *E, bool IsRotateRight) {
2164   llvm::Value *Src = EmitScalarExpr(E->getArg(0));
2165   llvm::Value *ShiftAmt = EmitScalarExpr(E->getArg(1));
2166 
2167   // The builtin's shift arg may have a different type than the source arg and
2168   // result, but the LLVM intrinsic uses the same type for all values.
2169   llvm::Type *Ty = Src->getType();
2170   ShiftAmt = Builder.CreateIntCast(ShiftAmt, Ty, false);
2171 
2172   // Rotate is a special case of LLVM funnel shift - 1st 2 args are the same.
2173   unsigned IID = IsRotateRight ? Intrinsic::fshr : Intrinsic::fshl;
2174   Function *F = CGM.getIntrinsic(IID, Ty);
2175   return RValue::get(Builder.CreateCall(F, { Src, Src, ShiftAmt }));
2176 }
2177 
2178 // Map math builtins for long-double to f128 version.
2179 static unsigned mutateLongDoubleBuiltin(unsigned BuiltinID) {
2180   switch (BuiltinID) {
2181 #define MUTATE_LDBL(func) \
2182   case Builtin::BI__builtin_##func##l: \
2183     return Builtin::BI__builtin_##func##f128;
2184   MUTATE_LDBL(sqrt)
2185   MUTATE_LDBL(cbrt)
2186   MUTATE_LDBL(fabs)
2187   MUTATE_LDBL(log)
2188   MUTATE_LDBL(log2)
2189   MUTATE_LDBL(log10)
2190   MUTATE_LDBL(log1p)
2191   MUTATE_LDBL(logb)
2192   MUTATE_LDBL(exp)
2193   MUTATE_LDBL(exp2)
2194   MUTATE_LDBL(expm1)
2195   MUTATE_LDBL(fdim)
2196   MUTATE_LDBL(hypot)
2197   MUTATE_LDBL(ilogb)
2198   MUTATE_LDBL(pow)
2199   MUTATE_LDBL(fmin)
2200   MUTATE_LDBL(fmax)
2201   MUTATE_LDBL(ceil)
2202   MUTATE_LDBL(trunc)
2203   MUTATE_LDBL(rint)
2204   MUTATE_LDBL(nearbyint)
2205   MUTATE_LDBL(round)
2206   MUTATE_LDBL(floor)
2207   MUTATE_LDBL(lround)
2208   MUTATE_LDBL(llround)
2209   MUTATE_LDBL(lrint)
2210   MUTATE_LDBL(llrint)
2211   MUTATE_LDBL(fmod)
2212   MUTATE_LDBL(modf)
2213   MUTATE_LDBL(nan)
2214   MUTATE_LDBL(nans)
2215   MUTATE_LDBL(inf)
2216   MUTATE_LDBL(fma)
2217   MUTATE_LDBL(sin)
2218   MUTATE_LDBL(cos)
2219   MUTATE_LDBL(tan)
2220   MUTATE_LDBL(sinh)
2221   MUTATE_LDBL(cosh)
2222   MUTATE_LDBL(tanh)
2223   MUTATE_LDBL(asin)
2224   MUTATE_LDBL(acos)
2225   MUTATE_LDBL(atan)
2226   MUTATE_LDBL(asinh)
2227   MUTATE_LDBL(acosh)
2228   MUTATE_LDBL(atanh)
2229   MUTATE_LDBL(atan2)
2230   MUTATE_LDBL(erf)
2231   MUTATE_LDBL(erfc)
2232   MUTATE_LDBL(ldexp)
2233   MUTATE_LDBL(frexp)
2234   MUTATE_LDBL(huge_val)
2235   MUTATE_LDBL(copysign)
2236   MUTATE_LDBL(nextafter)
2237   MUTATE_LDBL(nexttoward)
2238   MUTATE_LDBL(remainder)
2239   MUTATE_LDBL(remquo)
2240   MUTATE_LDBL(scalbln)
2241   MUTATE_LDBL(scalbn)
2242   MUTATE_LDBL(tgamma)
2243   MUTATE_LDBL(lgamma)
2244 #undef MUTATE_LDBL
2245   default:
2246     return BuiltinID;
2247   }
2248 }
2249 
2250 RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID,
2251                                         const CallExpr *E,
2252                                         ReturnValueSlot ReturnValue) {
2253   const FunctionDecl *FD = GD.getDecl()->getAsFunction();
2254   // See if we can constant fold this builtin.  If so, don't emit it at all.
2255   Expr::EvalResult Result;
2256   if (E->EvaluateAsRValue(Result, CGM.getContext()) &&
2257       !Result.hasSideEffects()) {
2258     if (Result.Val.isInt())
2259       return RValue::get(llvm::ConstantInt::get(getLLVMContext(),
2260                                                 Result.Val.getInt()));
2261     if (Result.Val.isFloat())
2262       return RValue::get(llvm::ConstantFP::get(getLLVMContext(),
2263                                                Result.Val.getFloat()));
2264   }
2265 
2266   // If current long-double semantics is IEEE 128-bit, replace math builtins
2267   // of long-double with f128 equivalent.
2268   // TODO: This mutation should also be applied to other targets other than PPC,
2269   // after backend supports IEEE 128-bit style libcalls.
2270   if (getTarget().getTriple().isPPC64() &&
2271       &getTarget().getLongDoubleFormat() == &llvm::APFloat::IEEEquad())
2272     BuiltinID = mutateLongDoubleBuiltin(BuiltinID);
2273 
2274   // If the builtin has been declared explicitly with an assembler label,
2275   // disable the specialized emitting below. Ideally we should communicate the
2276   // rename in IR, or at least avoid generating the intrinsic calls that are
2277   // likely to get lowered to the renamed library functions.
2278   const unsigned BuiltinIDIfNoAsmLabel =
2279       FD->hasAttr<AsmLabelAttr>() ? 0 : BuiltinID;
2280 
2281   // There are LLVM math intrinsics/instructions corresponding to math library
2282   // functions except the LLVM op will never set errno while the math library
2283   // might. Also, math builtins have the same semantics as their math library
2284   // twins. Thus, we can transform math library and builtin calls to their
2285   // LLVM counterparts if the call is marked 'const' (known to never set errno).
2286   if (FD->hasAttr<ConstAttr>()) {
2287     switch (BuiltinIDIfNoAsmLabel) {
2288     case Builtin::BIceil:
2289     case Builtin::BIceilf:
2290     case Builtin::BIceill:
2291     case Builtin::BI__builtin_ceil:
2292     case Builtin::BI__builtin_ceilf:
2293     case Builtin::BI__builtin_ceilf16:
2294     case Builtin::BI__builtin_ceill:
2295     case Builtin::BI__builtin_ceilf128:
2296       return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E,
2297                                    Intrinsic::ceil,
2298                                    Intrinsic::experimental_constrained_ceil));
2299 
2300     case Builtin::BIcopysign:
2301     case Builtin::BIcopysignf:
2302     case Builtin::BIcopysignl:
2303     case Builtin::BI__builtin_copysign:
2304     case Builtin::BI__builtin_copysignf:
2305     case Builtin::BI__builtin_copysignf16:
2306     case Builtin::BI__builtin_copysignl:
2307     case Builtin::BI__builtin_copysignf128:
2308       return RValue::get(emitBinaryBuiltin(*this, E, Intrinsic::copysign));
2309 
2310     case Builtin::BIcos:
2311     case Builtin::BIcosf:
2312     case Builtin::BIcosl:
2313     case Builtin::BI__builtin_cos:
2314     case Builtin::BI__builtin_cosf:
2315     case Builtin::BI__builtin_cosf16:
2316     case Builtin::BI__builtin_cosl:
2317     case Builtin::BI__builtin_cosf128:
2318       return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E,
2319                                    Intrinsic::cos,
2320                                    Intrinsic::experimental_constrained_cos));
2321 
2322     case Builtin::BIexp:
2323     case Builtin::BIexpf:
2324     case Builtin::BIexpl:
2325     case Builtin::BI__builtin_exp:
2326     case Builtin::BI__builtin_expf:
2327     case Builtin::BI__builtin_expf16:
2328     case Builtin::BI__builtin_expl:
2329     case Builtin::BI__builtin_expf128:
2330       return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E,
2331                                    Intrinsic::exp,
2332                                    Intrinsic::experimental_constrained_exp));
2333 
2334     case Builtin::BIexp2:
2335     case Builtin::BIexp2f:
2336     case Builtin::BIexp2l:
2337     case Builtin::BI__builtin_exp2:
2338     case Builtin::BI__builtin_exp2f:
2339     case Builtin::BI__builtin_exp2f16:
2340     case Builtin::BI__builtin_exp2l:
2341     case Builtin::BI__builtin_exp2f128:
2342       return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E,
2343                                    Intrinsic::exp2,
2344                                    Intrinsic::experimental_constrained_exp2));
2345 
2346     case Builtin::BIfabs:
2347     case Builtin::BIfabsf:
2348     case Builtin::BIfabsl:
2349     case Builtin::BI__builtin_fabs:
2350     case Builtin::BI__builtin_fabsf:
2351     case Builtin::BI__builtin_fabsf16:
2352     case Builtin::BI__builtin_fabsl:
2353     case Builtin::BI__builtin_fabsf128:
2354       return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::fabs));
2355 
2356     case Builtin::BIfloor:
2357     case Builtin::BIfloorf:
2358     case Builtin::BIfloorl:
2359     case Builtin::BI__builtin_floor:
2360     case Builtin::BI__builtin_floorf:
2361     case Builtin::BI__builtin_floorf16:
2362     case Builtin::BI__builtin_floorl:
2363     case Builtin::BI__builtin_floorf128:
2364       return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E,
2365                                    Intrinsic::floor,
2366                                    Intrinsic::experimental_constrained_floor));
2367 
2368     case Builtin::BIfma:
2369     case Builtin::BIfmaf:
2370     case Builtin::BIfmal:
2371     case Builtin::BI__builtin_fma:
2372     case Builtin::BI__builtin_fmaf:
2373     case Builtin::BI__builtin_fmaf16:
2374     case Builtin::BI__builtin_fmal:
2375     case Builtin::BI__builtin_fmaf128:
2376       return RValue::get(emitTernaryMaybeConstrainedFPBuiltin(*this, E,
2377                                    Intrinsic::fma,
2378                                    Intrinsic::experimental_constrained_fma));
2379 
2380     case Builtin::BIfmax:
2381     case Builtin::BIfmaxf:
2382     case Builtin::BIfmaxl:
2383     case Builtin::BI__builtin_fmax:
2384     case Builtin::BI__builtin_fmaxf:
2385     case Builtin::BI__builtin_fmaxf16:
2386     case Builtin::BI__builtin_fmaxl:
2387     case Builtin::BI__builtin_fmaxf128:
2388       return RValue::get(emitBinaryMaybeConstrainedFPBuiltin(*this, E,
2389                                    Intrinsic::maxnum,
2390                                    Intrinsic::experimental_constrained_maxnum));
2391 
2392     case Builtin::BIfmin:
2393     case Builtin::BIfminf:
2394     case Builtin::BIfminl:
2395     case Builtin::BI__builtin_fmin:
2396     case Builtin::BI__builtin_fminf:
2397     case Builtin::BI__builtin_fminf16:
2398     case Builtin::BI__builtin_fminl:
2399     case Builtin::BI__builtin_fminf128:
2400       return RValue::get(emitBinaryMaybeConstrainedFPBuiltin(*this, E,
2401                                    Intrinsic::minnum,
2402                                    Intrinsic::experimental_constrained_minnum));
2403 
2404     // fmod() is a special-case. It maps to the frem instruction rather than an
2405     // LLVM intrinsic.
2406     case Builtin::BIfmod:
2407     case Builtin::BIfmodf:
2408     case Builtin::BIfmodl:
2409     case Builtin::BI__builtin_fmod:
2410     case Builtin::BI__builtin_fmodf:
2411     case Builtin::BI__builtin_fmodf16:
2412     case Builtin::BI__builtin_fmodl:
2413     case Builtin::BI__builtin_fmodf128: {
2414       CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
2415       Value *Arg1 = EmitScalarExpr(E->getArg(0));
2416       Value *Arg2 = EmitScalarExpr(E->getArg(1));
2417       return RValue::get(Builder.CreateFRem(Arg1, Arg2, "fmod"));
2418     }
2419 
2420     case Builtin::BIlog:
2421     case Builtin::BIlogf:
2422     case Builtin::BIlogl:
2423     case Builtin::BI__builtin_log:
2424     case Builtin::BI__builtin_logf:
2425     case Builtin::BI__builtin_logf16:
2426     case Builtin::BI__builtin_logl:
2427     case Builtin::BI__builtin_logf128:
2428       return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E,
2429                                    Intrinsic::log,
2430                                    Intrinsic::experimental_constrained_log));
2431 
2432     case Builtin::BIlog10:
2433     case Builtin::BIlog10f:
2434     case Builtin::BIlog10l:
2435     case Builtin::BI__builtin_log10:
2436     case Builtin::BI__builtin_log10f:
2437     case Builtin::BI__builtin_log10f16:
2438     case Builtin::BI__builtin_log10l:
2439     case Builtin::BI__builtin_log10f128:
2440       return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E,
2441                                    Intrinsic::log10,
2442                                    Intrinsic::experimental_constrained_log10));
2443 
2444     case Builtin::BIlog2:
2445     case Builtin::BIlog2f:
2446     case Builtin::BIlog2l:
2447     case Builtin::BI__builtin_log2:
2448     case Builtin::BI__builtin_log2f:
2449     case Builtin::BI__builtin_log2f16:
2450     case Builtin::BI__builtin_log2l:
2451     case Builtin::BI__builtin_log2f128:
2452       return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E,
2453                                    Intrinsic::log2,
2454                                    Intrinsic::experimental_constrained_log2));
2455 
2456     case Builtin::BInearbyint:
2457     case Builtin::BInearbyintf:
2458     case Builtin::BInearbyintl:
2459     case Builtin::BI__builtin_nearbyint:
2460     case Builtin::BI__builtin_nearbyintf:
2461     case Builtin::BI__builtin_nearbyintl:
2462     case Builtin::BI__builtin_nearbyintf128:
2463       return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E,
2464                                 Intrinsic::nearbyint,
2465                                 Intrinsic::experimental_constrained_nearbyint));
2466 
2467     case Builtin::BIpow:
2468     case Builtin::BIpowf:
2469     case Builtin::BIpowl:
2470     case Builtin::BI__builtin_pow:
2471     case Builtin::BI__builtin_powf:
2472     case Builtin::BI__builtin_powf16:
2473     case Builtin::BI__builtin_powl:
2474     case Builtin::BI__builtin_powf128:
2475       return RValue::get(emitBinaryMaybeConstrainedFPBuiltin(*this, E,
2476                                    Intrinsic::pow,
2477                                    Intrinsic::experimental_constrained_pow));
2478 
2479     case Builtin::BIrint:
2480     case Builtin::BIrintf:
2481     case Builtin::BIrintl:
2482     case Builtin::BI__builtin_rint:
2483     case Builtin::BI__builtin_rintf:
2484     case Builtin::BI__builtin_rintf16:
2485     case Builtin::BI__builtin_rintl:
2486     case Builtin::BI__builtin_rintf128:
2487       return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E,
2488                                    Intrinsic::rint,
2489                                    Intrinsic::experimental_constrained_rint));
2490 
2491     case Builtin::BIround:
2492     case Builtin::BIroundf:
2493     case Builtin::BIroundl:
2494     case Builtin::BI__builtin_round:
2495     case Builtin::BI__builtin_roundf:
2496     case Builtin::BI__builtin_roundf16:
2497     case Builtin::BI__builtin_roundl:
2498     case Builtin::BI__builtin_roundf128:
2499       return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E,
2500                                    Intrinsic::round,
2501                                    Intrinsic::experimental_constrained_round));
2502 
2503     case Builtin::BIsin:
2504     case Builtin::BIsinf:
2505     case Builtin::BIsinl:
2506     case Builtin::BI__builtin_sin:
2507     case Builtin::BI__builtin_sinf:
2508     case Builtin::BI__builtin_sinf16:
2509     case Builtin::BI__builtin_sinl:
2510     case Builtin::BI__builtin_sinf128:
2511       return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E,
2512                                    Intrinsic::sin,
2513                                    Intrinsic::experimental_constrained_sin));
2514 
2515     case Builtin::BIsqrt:
2516     case Builtin::BIsqrtf:
2517     case Builtin::BIsqrtl:
2518     case Builtin::BI__builtin_sqrt:
2519     case Builtin::BI__builtin_sqrtf:
2520     case Builtin::BI__builtin_sqrtf16:
2521     case Builtin::BI__builtin_sqrtl:
2522     case Builtin::BI__builtin_sqrtf128:
2523       return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E,
2524                                    Intrinsic::sqrt,
2525                                    Intrinsic::experimental_constrained_sqrt));
2526 
2527     case Builtin::BItrunc:
2528     case Builtin::BItruncf:
2529     case Builtin::BItruncl:
2530     case Builtin::BI__builtin_trunc:
2531     case Builtin::BI__builtin_truncf:
2532     case Builtin::BI__builtin_truncf16:
2533     case Builtin::BI__builtin_truncl:
2534     case Builtin::BI__builtin_truncf128:
2535       return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E,
2536                                    Intrinsic::trunc,
2537                                    Intrinsic::experimental_constrained_trunc));
2538 
2539     case Builtin::BIlround:
2540     case Builtin::BIlroundf:
2541     case Builtin::BIlroundl:
2542     case Builtin::BI__builtin_lround:
2543     case Builtin::BI__builtin_lroundf:
2544     case Builtin::BI__builtin_lroundl:
2545     case Builtin::BI__builtin_lroundf128:
2546       return RValue::get(emitMaybeConstrainedFPToIntRoundBuiltin(
2547           *this, E, Intrinsic::lround,
2548           Intrinsic::experimental_constrained_lround));
2549 
2550     case Builtin::BIllround:
2551     case Builtin::BIllroundf:
2552     case Builtin::BIllroundl:
2553     case Builtin::BI__builtin_llround:
2554     case Builtin::BI__builtin_llroundf:
2555     case Builtin::BI__builtin_llroundl:
2556     case Builtin::BI__builtin_llroundf128:
2557       return RValue::get(emitMaybeConstrainedFPToIntRoundBuiltin(
2558           *this, E, Intrinsic::llround,
2559           Intrinsic::experimental_constrained_llround));
2560 
2561     case Builtin::BIlrint:
2562     case Builtin::BIlrintf:
2563     case Builtin::BIlrintl:
2564     case Builtin::BI__builtin_lrint:
2565     case Builtin::BI__builtin_lrintf:
2566     case Builtin::BI__builtin_lrintl:
2567     case Builtin::BI__builtin_lrintf128:
2568       return RValue::get(emitMaybeConstrainedFPToIntRoundBuiltin(
2569           *this, E, Intrinsic::lrint,
2570           Intrinsic::experimental_constrained_lrint));
2571 
2572     case Builtin::BIllrint:
2573     case Builtin::BIllrintf:
2574     case Builtin::BIllrintl:
2575     case Builtin::BI__builtin_llrint:
2576     case Builtin::BI__builtin_llrintf:
2577     case Builtin::BI__builtin_llrintl:
2578     case Builtin::BI__builtin_llrintf128:
2579       return RValue::get(emitMaybeConstrainedFPToIntRoundBuiltin(
2580           *this, E, Intrinsic::llrint,
2581           Intrinsic::experimental_constrained_llrint));
2582 
2583     default:
2584       break;
2585     }
2586   }
2587 
2588   switch (BuiltinIDIfNoAsmLabel) {
2589   default: break;
2590   case Builtin::BI__builtin___CFStringMakeConstantString:
2591   case Builtin::BI__builtin___NSStringMakeConstantString:
2592     return RValue::get(ConstantEmitter(*this).emitAbstract(E, E->getType()));
2593   case Builtin::BI__builtin_stdarg_start:
2594   case Builtin::BI__builtin_va_start:
2595   case Builtin::BI__va_start:
2596   case Builtin::BI__builtin_va_end:
2597     return RValue::get(
2598         EmitVAStartEnd(BuiltinID == Builtin::BI__va_start
2599                            ? EmitScalarExpr(E->getArg(0))
2600                            : EmitVAListRef(E->getArg(0)).getPointer(),
2601                        BuiltinID != Builtin::BI__builtin_va_end));
2602   case Builtin::BI__builtin_va_copy: {
2603     Value *DstPtr = EmitVAListRef(E->getArg(0)).getPointer();
2604     Value *SrcPtr = EmitVAListRef(E->getArg(1)).getPointer();
2605 
2606     llvm::Type *Type = Int8PtrTy;
2607 
2608     DstPtr = Builder.CreateBitCast(DstPtr, Type);
2609     SrcPtr = Builder.CreateBitCast(SrcPtr, Type);
2610     return RValue::get(Builder.CreateCall(CGM.getIntrinsic(Intrinsic::vacopy),
2611                                           {DstPtr, SrcPtr}));
2612   }
2613   case Builtin::BI__builtin_abs:
2614   case Builtin::BI__builtin_labs:
2615   case Builtin::BI__builtin_llabs: {
2616     // X < 0 ? -X : X
2617     // The negation has 'nsw' because abs of INT_MIN is undefined.
2618     Value *ArgValue = EmitScalarExpr(E->getArg(0));
2619     Value *NegOp = Builder.CreateNSWNeg(ArgValue, "neg");
2620     Constant *Zero = llvm::Constant::getNullValue(ArgValue->getType());
2621     Value *CmpResult = Builder.CreateICmpSLT(ArgValue, Zero, "abscond");
2622     Value *Result = Builder.CreateSelect(CmpResult, NegOp, ArgValue, "abs");
2623     return RValue::get(Result);
2624   }
2625   case Builtin::BI__builtin_complex: {
2626     Value *Real = EmitScalarExpr(E->getArg(0));
2627     Value *Imag = EmitScalarExpr(E->getArg(1));
2628     return RValue::getComplex({Real, Imag});
2629   }
2630   case Builtin::BI__builtin_conj:
2631   case Builtin::BI__builtin_conjf:
2632   case Builtin::BI__builtin_conjl:
2633   case Builtin::BIconj:
2634   case Builtin::BIconjf:
2635   case Builtin::BIconjl: {
2636     ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0));
2637     Value *Real = ComplexVal.first;
2638     Value *Imag = ComplexVal.second;
2639     Imag = Builder.CreateFNeg(Imag, "neg");
2640     return RValue::getComplex(std::make_pair(Real, Imag));
2641   }
2642   case Builtin::BI__builtin_creal:
2643   case Builtin::BI__builtin_crealf:
2644   case Builtin::BI__builtin_creall:
2645   case Builtin::BIcreal:
2646   case Builtin::BIcrealf:
2647   case Builtin::BIcreall: {
2648     ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0));
2649     return RValue::get(ComplexVal.first);
2650   }
2651 
2652   case Builtin::BI__builtin_dump_struct: {
2653     llvm::Type *LLVMIntTy = getTypes().ConvertType(getContext().IntTy);
2654     llvm::FunctionType *LLVMFuncType = llvm::FunctionType::get(
2655         LLVMIntTy, {llvm::Type::getInt8PtrTy(getLLVMContext())}, true);
2656 
2657     Value *Func = EmitScalarExpr(E->getArg(1)->IgnoreImpCasts());
2658     CharUnits Arg0Align = EmitPointerWithAlignment(E->getArg(0)).getAlignment();
2659 
2660     const Expr *Arg0 = E->getArg(0)->IgnoreImpCasts();
2661     QualType Arg0Type = Arg0->getType()->getPointeeType();
2662 
2663     Value *RecordPtr = EmitScalarExpr(Arg0);
2664     Value *Res = dumpRecord(*this, Arg0Type, RecordPtr, Arg0Align,
2665                             {LLVMFuncType, Func}, 0);
2666     return RValue::get(Res);
2667   }
2668 
2669   case Builtin::BI__builtin_preserve_access_index: {
2670     // Only enabled preserved access index region when debuginfo
2671     // is available as debuginfo is needed to preserve user-level
2672     // access pattern.
2673     if (!getDebugInfo()) {
2674       CGM.Error(E->getExprLoc(), "using builtin_preserve_access_index() without -g");
2675       return RValue::get(EmitScalarExpr(E->getArg(0)));
2676     }
2677 
2678     // Nested builtin_preserve_access_index() not supported
2679     if (IsInPreservedAIRegion) {
2680       CGM.Error(E->getExprLoc(), "nested builtin_preserve_access_index() not supported");
2681       return RValue::get(EmitScalarExpr(E->getArg(0)));
2682     }
2683 
2684     IsInPreservedAIRegion = true;
2685     Value *Res = EmitScalarExpr(E->getArg(0));
2686     IsInPreservedAIRegion = false;
2687     return RValue::get(Res);
2688   }
2689 
2690   case Builtin::BI__builtin_cimag:
2691   case Builtin::BI__builtin_cimagf:
2692   case Builtin::BI__builtin_cimagl:
2693   case Builtin::BIcimag:
2694   case Builtin::BIcimagf:
2695   case Builtin::BIcimagl: {
2696     ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0));
2697     return RValue::get(ComplexVal.second);
2698   }
2699 
2700   case Builtin::BI__builtin_clrsb:
2701   case Builtin::BI__builtin_clrsbl:
2702   case Builtin::BI__builtin_clrsbll: {
2703     // clrsb(x) -> clz(x < 0 ? ~x : x) - 1 or
2704     Value *ArgValue = EmitScalarExpr(E->getArg(0));
2705 
2706     llvm::Type *ArgType = ArgValue->getType();
2707     Function *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
2708 
2709     llvm::Type *ResultType = ConvertType(E->getType());
2710     Value *Zero = llvm::Constant::getNullValue(ArgType);
2711     Value *IsNeg = Builder.CreateICmpSLT(ArgValue, Zero, "isneg");
2712     Value *Inverse = Builder.CreateNot(ArgValue, "not");
2713     Value *Tmp = Builder.CreateSelect(IsNeg, Inverse, ArgValue);
2714     Value *Ctlz = Builder.CreateCall(F, {Tmp, Builder.getFalse()});
2715     Value *Result = Builder.CreateSub(Ctlz, llvm::ConstantInt::get(ArgType, 1));
2716     Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
2717                                    "cast");
2718     return RValue::get(Result);
2719   }
2720   case Builtin::BI__builtin_ctzs:
2721   case Builtin::BI__builtin_ctz:
2722   case Builtin::BI__builtin_ctzl:
2723   case Builtin::BI__builtin_ctzll: {
2724     Value *ArgValue = EmitCheckedArgForBuiltin(E->getArg(0), BCK_CTZPassedZero);
2725 
2726     llvm::Type *ArgType = ArgValue->getType();
2727     Function *F = CGM.getIntrinsic(Intrinsic::cttz, ArgType);
2728 
2729     llvm::Type *ResultType = ConvertType(E->getType());
2730     Value *ZeroUndef = Builder.getInt1(getTarget().isCLZForZeroUndef());
2731     Value *Result = Builder.CreateCall(F, {ArgValue, ZeroUndef});
2732     if (Result->getType() != ResultType)
2733       Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
2734                                      "cast");
2735     return RValue::get(Result);
2736   }
2737   case Builtin::BI__builtin_clzs:
2738   case Builtin::BI__builtin_clz:
2739   case Builtin::BI__builtin_clzl:
2740   case Builtin::BI__builtin_clzll: {
2741     Value *ArgValue = EmitCheckedArgForBuiltin(E->getArg(0), BCK_CLZPassedZero);
2742 
2743     llvm::Type *ArgType = ArgValue->getType();
2744     Function *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
2745 
2746     llvm::Type *ResultType = ConvertType(E->getType());
2747     Value *ZeroUndef = Builder.getInt1(getTarget().isCLZForZeroUndef());
2748     Value *Result = Builder.CreateCall(F, {ArgValue, ZeroUndef});
2749     if (Result->getType() != ResultType)
2750       Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
2751                                      "cast");
2752     return RValue::get(Result);
2753   }
2754   case Builtin::BI__builtin_ffs:
2755   case Builtin::BI__builtin_ffsl:
2756   case Builtin::BI__builtin_ffsll: {
2757     // ffs(x) -> x ? cttz(x) + 1 : 0
2758     Value *ArgValue = EmitScalarExpr(E->getArg(0));
2759 
2760     llvm::Type *ArgType = ArgValue->getType();
2761     Function *F = CGM.getIntrinsic(Intrinsic::cttz, ArgType);
2762 
2763     llvm::Type *ResultType = ConvertType(E->getType());
2764     Value *Tmp =
2765         Builder.CreateAdd(Builder.CreateCall(F, {ArgValue, Builder.getTrue()}),
2766                           llvm::ConstantInt::get(ArgType, 1));
2767     Value *Zero = llvm::Constant::getNullValue(ArgType);
2768     Value *IsZero = Builder.CreateICmpEQ(ArgValue, Zero, "iszero");
2769     Value *Result = Builder.CreateSelect(IsZero, Zero, Tmp, "ffs");
2770     if (Result->getType() != ResultType)
2771       Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
2772                                      "cast");
2773     return RValue::get(Result);
2774   }
2775   case Builtin::BI__builtin_parity:
2776   case Builtin::BI__builtin_parityl:
2777   case Builtin::BI__builtin_parityll: {
2778     // parity(x) -> ctpop(x) & 1
2779     Value *ArgValue = EmitScalarExpr(E->getArg(0));
2780 
2781     llvm::Type *ArgType = ArgValue->getType();
2782     Function *F = CGM.getIntrinsic(Intrinsic::ctpop, ArgType);
2783 
2784     llvm::Type *ResultType = ConvertType(E->getType());
2785     Value *Tmp = Builder.CreateCall(F, ArgValue);
2786     Value *Result = Builder.CreateAnd(Tmp, llvm::ConstantInt::get(ArgType, 1));
2787     if (Result->getType() != ResultType)
2788       Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
2789                                      "cast");
2790     return RValue::get(Result);
2791   }
2792   case Builtin::BI__lzcnt16:
2793   case Builtin::BI__lzcnt:
2794   case Builtin::BI__lzcnt64: {
2795     Value *ArgValue = EmitScalarExpr(E->getArg(0));
2796 
2797     llvm::Type *ArgType = ArgValue->getType();
2798     Function *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
2799 
2800     llvm::Type *ResultType = ConvertType(E->getType());
2801     Value *Result = Builder.CreateCall(F, {ArgValue, Builder.getFalse()});
2802     if (Result->getType() != ResultType)
2803       Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
2804                                      "cast");
2805     return RValue::get(Result);
2806   }
2807   case Builtin::BI__popcnt16:
2808   case Builtin::BI__popcnt:
2809   case Builtin::BI__popcnt64:
2810   case Builtin::BI__builtin_popcount:
2811   case Builtin::BI__builtin_popcountl:
2812   case Builtin::BI__builtin_popcountll: {
2813     Value *ArgValue = EmitScalarExpr(E->getArg(0));
2814 
2815     llvm::Type *ArgType = ArgValue->getType();
2816     Function *F = CGM.getIntrinsic(Intrinsic::ctpop, ArgType);
2817 
2818     llvm::Type *ResultType = ConvertType(E->getType());
2819     Value *Result = Builder.CreateCall(F, ArgValue);
2820     if (Result->getType() != ResultType)
2821       Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
2822                                      "cast");
2823     return RValue::get(Result);
2824   }
2825   case Builtin::BI__builtin_unpredictable: {
2826     // Always return the argument of __builtin_unpredictable. LLVM does not
2827     // handle this builtin. Metadata for this builtin should be added directly
2828     // to instructions such as branches or switches that use it.
2829     return RValue::get(EmitScalarExpr(E->getArg(0)));
2830   }
2831   case Builtin::BI__builtin_expect: {
2832     Value *ArgValue = EmitScalarExpr(E->getArg(0));
2833     llvm::Type *ArgType = ArgValue->getType();
2834 
2835     Value *ExpectedValue = EmitScalarExpr(E->getArg(1));
2836     // Don't generate llvm.expect on -O0 as the backend won't use it for
2837     // anything.
2838     // Note, we still IRGen ExpectedValue because it could have side-effects.
2839     if (CGM.getCodeGenOpts().OptimizationLevel == 0)
2840       return RValue::get(ArgValue);
2841 
2842     Function *FnExpect = CGM.getIntrinsic(Intrinsic::expect, ArgType);
2843     Value *Result =
2844         Builder.CreateCall(FnExpect, {ArgValue, ExpectedValue}, "expval");
2845     return RValue::get(Result);
2846   }
2847   case Builtin::BI__builtin_expect_with_probability: {
2848     Value *ArgValue = EmitScalarExpr(E->getArg(0));
2849     llvm::Type *ArgType = ArgValue->getType();
2850 
2851     Value *ExpectedValue = EmitScalarExpr(E->getArg(1));
2852     llvm::APFloat Probability(0.0);
2853     const Expr *ProbArg = E->getArg(2);
2854     bool EvalSucceed = ProbArg->EvaluateAsFloat(Probability, CGM.getContext());
2855     assert(EvalSucceed && "probability should be able to evaluate as float");
2856     (void)EvalSucceed;
2857     bool LoseInfo = false;
2858     Probability.convert(llvm::APFloat::IEEEdouble(),
2859                         llvm::RoundingMode::Dynamic, &LoseInfo);
2860     llvm::Type *Ty = ConvertType(ProbArg->getType());
2861     Constant *Confidence = ConstantFP::get(Ty, Probability);
2862     // Don't generate llvm.expect.with.probability on -O0 as the backend
2863     // won't use it for anything.
2864     // Note, we still IRGen ExpectedValue because it could have side-effects.
2865     if (CGM.getCodeGenOpts().OptimizationLevel == 0)
2866       return RValue::get(ArgValue);
2867 
2868     Function *FnExpect =
2869         CGM.getIntrinsic(Intrinsic::expect_with_probability, ArgType);
2870     Value *Result = Builder.CreateCall(
2871         FnExpect, {ArgValue, ExpectedValue, Confidence}, "expval");
2872     return RValue::get(Result);
2873   }
2874   case Builtin::BI__builtin_assume_aligned: {
2875     const Expr *Ptr = E->getArg(0);
2876     Value *PtrValue = EmitScalarExpr(Ptr);
2877     Value *OffsetValue =
2878       (E->getNumArgs() > 2) ? EmitScalarExpr(E->getArg(2)) : nullptr;
2879 
2880     Value *AlignmentValue = EmitScalarExpr(E->getArg(1));
2881     ConstantInt *AlignmentCI = cast<ConstantInt>(AlignmentValue);
2882     if (AlignmentCI->getValue().ugt(llvm::Value::MaximumAlignment))
2883       AlignmentCI = ConstantInt::get(AlignmentCI->getType(),
2884                                      llvm::Value::MaximumAlignment);
2885 
2886     emitAlignmentAssumption(PtrValue, Ptr,
2887                             /*The expr loc is sufficient.*/ SourceLocation(),
2888                             AlignmentCI, OffsetValue);
2889     return RValue::get(PtrValue);
2890   }
2891   case Builtin::BI__assume:
2892   case Builtin::BI__builtin_assume: {
2893     if (E->getArg(0)->HasSideEffects(getContext()))
2894       return RValue::get(nullptr);
2895 
2896     Value *ArgValue = EmitScalarExpr(E->getArg(0));
2897     Function *FnAssume = CGM.getIntrinsic(Intrinsic::assume);
2898     return RValue::get(Builder.CreateCall(FnAssume, ArgValue));
2899   }
2900   case Builtin::BI__arithmetic_fence: {
2901     // Create the builtin call if FastMath is selected, and the target
2902     // supports the builtin, otherwise just return the argument.
2903     CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
2904     llvm::FastMathFlags FMF = Builder.getFastMathFlags();
2905     bool isArithmeticFenceEnabled =
2906         FMF.allowReassoc() &&
2907         getContext().getTargetInfo().checkArithmeticFenceSupported();
2908     QualType ArgType = E->getArg(0)->getType();
2909     if (ArgType->isComplexType()) {
2910       if (isArithmeticFenceEnabled) {
2911         QualType ElementType = ArgType->castAs<ComplexType>()->getElementType();
2912         ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0));
2913         Value *Real = Builder.CreateArithmeticFence(ComplexVal.first,
2914                                                     ConvertType(ElementType));
2915         Value *Imag = Builder.CreateArithmeticFence(ComplexVal.second,
2916                                                     ConvertType(ElementType));
2917         return RValue::getComplex(std::make_pair(Real, Imag));
2918       }
2919       ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0));
2920       Value *Real = ComplexVal.first;
2921       Value *Imag = ComplexVal.second;
2922       return RValue::getComplex(std::make_pair(Real, Imag));
2923     }
2924     Value *ArgValue = EmitScalarExpr(E->getArg(0));
2925     if (isArithmeticFenceEnabled)
2926       return RValue::get(
2927           Builder.CreateArithmeticFence(ArgValue, ConvertType(ArgType)));
2928     return RValue::get(ArgValue);
2929   }
2930   case Builtin::BI__builtin_bswap16:
2931   case Builtin::BI__builtin_bswap32:
2932   case Builtin::BI__builtin_bswap64: {
2933     return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::bswap));
2934   }
2935   case Builtin::BI__builtin_bitreverse8:
2936   case Builtin::BI__builtin_bitreverse16:
2937   case Builtin::BI__builtin_bitreverse32:
2938   case Builtin::BI__builtin_bitreverse64: {
2939     return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::bitreverse));
2940   }
2941   case Builtin::BI__builtin_rotateleft8:
2942   case Builtin::BI__builtin_rotateleft16:
2943   case Builtin::BI__builtin_rotateleft32:
2944   case Builtin::BI__builtin_rotateleft64:
2945   case Builtin::BI_rotl8: // Microsoft variants of rotate left
2946   case Builtin::BI_rotl16:
2947   case Builtin::BI_rotl:
2948   case Builtin::BI_lrotl:
2949   case Builtin::BI_rotl64:
2950     return emitRotate(E, false);
2951 
2952   case Builtin::BI__builtin_rotateright8:
2953   case Builtin::BI__builtin_rotateright16:
2954   case Builtin::BI__builtin_rotateright32:
2955   case Builtin::BI__builtin_rotateright64:
2956   case Builtin::BI_rotr8: // Microsoft variants of rotate right
2957   case Builtin::BI_rotr16:
2958   case Builtin::BI_rotr:
2959   case Builtin::BI_lrotr:
2960   case Builtin::BI_rotr64:
2961     return emitRotate(E, true);
2962 
2963   case Builtin::BI__builtin_constant_p: {
2964     llvm::Type *ResultType = ConvertType(E->getType());
2965 
2966     const Expr *Arg = E->getArg(0);
2967     QualType ArgType = Arg->getType();
2968     // FIXME: The allowance for Obj-C pointers and block pointers is historical
2969     // and likely a mistake.
2970     if (!ArgType->isIntegralOrEnumerationType() && !ArgType->isFloatingType() &&
2971         !ArgType->isObjCObjectPointerType() && !ArgType->isBlockPointerType())
2972       // Per the GCC documentation, only numeric constants are recognized after
2973       // inlining.
2974       return RValue::get(ConstantInt::get(ResultType, 0));
2975 
2976     if (Arg->HasSideEffects(getContext()))
2977       // The argument is unevaluated, so be conservative if it might have
2978       // side-effects.
2979       return RValue::get(ConstantInt::get(ResultType, 0));
2980 
2981     Value *ArgValue = EmitScalarExpr(Arg);
2982     if (ArgType->isObjCObjectPointerType()) {
2983       // Convert Objective-C objects to id because we cannot distinguish between
2984       // LLVM types for Obj-C classes as they are opaque.
2985       ArgType = CGM.getContext().getObjCIdType();
2986       ArgValue = Builder.CreateBitCast(ArgValue, ConvertType(ArgType));
2987     }
2988     Function *F =
2989         CGM.getIntrinsic(Intrinsic::is_constant, ConvertType(ArgType));
2990     Value *Result = Builder.CreateCall(F, ArgValue);
2991     if (Result->getType() != ResultType)
2992       Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/false);
2993     return RValue::get(Result);
2994   }
2995   case Builtin::BI__builtin_dynamic_object_size:
2996   case Builtin::BI__builtin_object_size: {
2997     unsigned Type =
2998         E->getArg(1)->EvaluateKnownConstInt(getContext()).getZExtValue();
2999     auto *ResType = cast<llvm::IntegerType>(ConvertType(E->getType()));
3000 
3001     // We pass this builtin onto the optimizer so that it can figure out the
3002     // object size in more complex cases.
3003     bool IsDynamic = BuiltinID == Builtin::BI__builtin_dynamic_object_size;
3004     return RValue::get(emitBuiltinObjectSize(E->getArg(0), Type, ResType,
3005                                              /*EmittedE=*/nullptr, IsDynamic));
3006   }
3007   case Builtin::BI__builtin_prefetch: {
3008     Value *Locality, *RW, *Address = EmitScalarExpr(E->getArg(0));
3009     // FIXME: Technically these constants should of type 'int', yes?
3010     RW = (E->getNumArgs() > 1) ? EmitScalarExpr(E->getArg(1)) :
3011       llvm::ConstantInt::get(Int32Ty, 0);
3012     Locality = (E->getNumArgs() > 2) ? EmitScalarExpr(E->getArg(2)) :
3013       llvm::ConstantInt::get(Int32Ty, 3);
3014     Value *Data = llvm::ConstantInt::get(Int32Ty, 1);
3015     Function *F = CGM.getIntrinsic(Intrinsic::prefetch, Address->getType());
3016     return RValue::get(Builder.CreateCall(F, {Address, RW, Locality, Data}));
3017   }
3018   case Builtin::BI__builtin_readcyclecounter: {
3019     Function *F = CGM.getIntrinsic(Intrinsic::readcyclecounter);
3020     return RValue::get(Builder.CreateCall(F));
3021   }
3022   case Builtin::BI__builtin___clear_cache: {
3023     Value *Begin = EmitScalarExpr(E->getArg(0));
3024     Value *End = EmitScalarExpr(E->getArg(1));
3025     Function *F = CGM.getIntrinsic(Intrinsic::clear_cache);
3026     return RValue::get(Builder.CreateCall(F, {Begin, End}));
3027   }
3028   case Builtin::BI__builtin_trap:
3029     return RValue::get(EmitTrapCall(Intrinsic::trap));
3030   case Builtin::BI__debugbreak:
3031     return RValue::get(EmitTrapCall(Intrinsic::debugtrap));
3032   case Builtin::BI__builtin_unreachable: {
3033     EmitUnreachable(E->getExprLoc());
3034 
3035     // We do need to preserve an insertion point.
3036     EmitBlock(createBasicBlock("unreachable.cont"));
3037 
3038     return RValue::get(nullptr);
3039   }
3040 
3041   case Builtin::BI__builtin_powi:
3042   case Builtin::BI__builtin_powif:
3043   case Builtin::BI__builtin_powil: {
3044     llvm::Value *Src0 = EmitScalarExpr(E->getArg(0));
3045     llvm::Value *Src1 = EmitScalarExpr(E->getArg(1));
3046 
3047     if (Builder.getIsFPConstrained()) {
3048       CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
3049       Function *F = CGM.getIntrinsic(Intrinsic::experimental_constrained_powi,
3050                                      Src0->getType());
3051       return RValue::get(Builder.CreateConstrainedFPCall(F, { Src0, Src1 }));
3052     }
3053 
3054     Function *F = CGM.getIntrinsic(Intrinsic::powi,
3055                                    { Src0->getType(), Src1->getType() });
3056     return RValue::get(Builder.CreateCall(F, { Src0, Src1 }));
3057   }
3058   case Builtin::BI__builtin_isgreater:
3059   case Builtin::BI__builtin_isgreaterequal:
3060   case Builtin::BI__builtin_isless:
3061   case Builtin::BI__builtin_islessequal:
3062   case Builtin::BI__builtin_islessgreater:
3063   case Builtin::BI__builtin_isunordered: {
3064     // Ordered comparisons: we know the arguments to these are matching scalar
3065     // floating point values.
3066     CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
3067     // FIXME: for strictfp/IEEE-754 we need to not trap on SNaN here.
3068     Value *LHS = EmitScalarExpr(E->getArg(0));
3069     Value *RHS = EmitScalarExpr(E->getArg(1));
3070 
3071     switch (BuiltinID) {
3072     default: llvm_unreachable("Unknown ordered comparison");
3073     case Builtin::BI__builtin_isgreater:
3074       LHS = Builder.CreateFCmpOGT(LHS, RHS, "cmp");
3075       break;
3076     case Builtin::BI__builtin_isgreaterequal:
3077       LHS = Builder.CreateFCmpOGE(LHS, RHS, "cmp");
3078       break;
3079     case Builtin::BI__builtin_isless:
3080       LHS = Builder.CreateFCmpOLT(LHS, RHS, "cmp");
3081       break;
3082     case Builtin::BI__builtin_islessequal:
3083       LHS = Builder.CreateFCmpOLE(LHS, RHS, "cmp");
3084       break;
3085     case Builtin::BI__builtin_islessgreater:
3086       LHS = Builder.CreateFCmpONE(LHS, RHS, "cmp");
3087       break;
3088     case Builtin::BI__builtin_isunordered:
3089       LHS = Builder.CreateFCmpUNO(LHS, RHS, "cmp");
3090       break;
3091     }
3092     // ZExt bool to int type.
3093     return RValue::get(Builder.CreateZExt(LHS, ConvertType(E->getType())));
3094   }
3095   case Builtin::BI__builtin_isnan: {
3096     CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
3097     Value *V = EmitScalarExpr(E->getArg(0));
3098     llvm::Type *Ty = V->getType();
3099     const llvm::fltSemantics &Semantics = Ty->getFltSemantics();
3100     if (!Builder.getIsFPConstrained() ||
3101         Builder.getDefaultConstrainedExcept() == fp::ebIgnore ||
3102         !Ty->isIEEE()) {
3103       V = Builder.CreateFCmpUNO(V, V, "cmp");
3104       return RValue::get(Builder.CreateZExt(V, ConvertType(E->getType())));
3105     }
3106 
3107     if (Value *Result = getTargetHooks().testFPKind(V, BuiltinID, Builder, CGM))
3108       return RValue::get(Result);
3109 
3110     // NaN has all exp bits set and a non zero significand. Therefore:
3111     // isnan(V) == ((exp mask - (abs(V) & exp mask)) < 0)
3112     unsigned bitsize = Ty->getScalarSizeInBits();
3113     llvm::IntegerType *IntTy = Builder.getIntNTy(bitsize);
3114     Value *IntV = Builder.CreateBitCast(V, IntTy);
3115     APInt AndMask = APInt::getSignedMaxValue(bitsize);
3116     Value *AbsV =
3117         Builder.CreateAnd(IntV, llvm::ConstantInt::get(IntTy, AndMask));
3118     APInt ExpMask = APFloat::getInf(Semantics).bitcastToAPInt();
3119     Value *Sub =
3120         Builder.CreateSub(llvm::ConstantInt::get(IntTy, ExpMask), AbsV);
3121     // V = sign bit (Sub) <=> V = (Sub < 0)
3122     V = Builder.CreateLShr(Sub, llvm::ConstantInt::get(IntTy, bitsize - 1));
3123     if (bitsize > 32)
3124       V = Builder.CreateTrunc(V, ConvertType(E->getType()));
3125     return RValue::get(V);
3126   }
3127 
3128   case Builtin::BI__builtin_elementwise_abs: {
3129     Value *Result;
3130     QualType QT = E->getArg(0)->getType();
3131 
3132     if (auto *VecTy = QT->getAs<VectorType>())
3133       QT = VecTy->getElementType();
3134     if (QT->isIntegerType())
3135       Result = Builder.CreateBinaryIntrinsic(
3136           llvm::Intrinsic::abs, EmitScalarExpr(E->getArg(0)),
3137           Builder.getFalse(), nullptr, "elt.abs");
3138     else
3139       Result = emitUnaryBuiltin(*this, E, llvm::Intrinsic::fabs, "elt.abs");
3140 
3141     return RValue::get(Result);
3142   }
3143 
3144   case Builtin::BI__builtin_elementwise_ceil:
3145     return RValue::get(
3146         emitUnaryBuiltin(*this, E, llvm::Intrinsic::ceil, "elt.ceil"));
3147   case Builtin::BI__builtin_elementwise_floor:
3148     return RValue::get(
3149         emitUnaryBuiltin(*this, E, llvm::Intrinsic::floor, "elt.floor"));
3150   case Builtin::BI__builtin_elementwise_roundeven:
3151     return RValue::get(emitUnaryBuiltin(*this, E, llvm::Intrinsic::roundeven,
3152                                         "elt.roundeven"));
3153   case Builtin::BI__builtin_elementwise_trunc:
3154     return RValue::get(
3155         emitUnaryBuiltin(*this, E, llvm::Intrinsic::trunc, "elt.trunc"));
3156 
3157   case Builtin::BI__builtin_elementwise_max: {
3158     Value *Op0 = EmitScalarExpr(E->getArg(0));
3159     Value *Op1 = EmitScalarExpr(E->getArg(1));
3160     Value *Result;
3161     if (Op0->getType()->isIntOrIntVectorTy()) {
3162       QualType Ty = E->getArg(0)->getType();
3163       if (auto *VecTy = Ty->getAs<VectorType>())
3164         Ty = VecTy->getElementType();
3165       Result = Builder.CreateBinaryIntrinsic(Ty->isSignedIntegerType()
3166                                                  ? llvm::Intrinsic::smax
3167                                                  : llvm::Intrinsic::umax,
3168                                              Op0, Op1, nullptr, "elt.max");
3169     } else
3170       Result = Builder.CreateMaxNum(Op0, Op1, "elt.max");
3171     return RValue::get(Result);
3172   }
3173   case Builtin::BI__builtin_elementwise_min: {
3174     Value *Op0 = EmitScalarExpr(E->getArg(0));
3175     Value *Op1 = EmitScalarExpr(E->getArg(1));
3176     Value *Result;
3177     if (Op0->getType()->isIntOrIntVectorTy()) {
3178       QualType Ty = E->getArg(0)->getType();
3179       if (auto *VecTy = Ty->getAs<VectorType>())
3180         Ty = VecTy->getElementType();
3181       Result = Builder.CreateBinaryIntrinsic(Ty->isSignedIntegerType()
3182                                                  ? llvm::Intrinsic::smin
3183                                                  : llvm::Intrinsic::umin,
3184                                              Op0, Op1, nullptr, "elt.min");
3185     } else
3186       Result = Builder.CreateMinNum(Op0, Op1, "elt.min");
3187     return RValue::get(Result);
3188   }
3189 
3190   case Builtin::BI__builtin_reduce_max: {
3191     auto GetIntrinsicID = [](QualType QT) {
3192       if (auto *VecTy = QT->getAs<VectorType>())
3193         QT = VecTy->getElementType();
3194       if (QT->isSignedIntegerType())
3195         return llvm::Intrinsic::vector_reduce_smax;
3196       if (QT->isUnsignedIntegerType())
3197         return llvm::Intrinsic::vector_reduce_umax;
3198       assert(QT->isFloatingType() && "must have a float here");
3199       return llvm::Intrinsic::vector_reduce_fmax;
3200     };
3201     return RValue::get(emitUnaryBuiltin(
3202         *this, E, GetIntrinsicID(E->getArg(0)->getType()), "rdx.min"));
3203   }
3204 
3205   case Builtin::BI__builtin_reduce_min: {
3206     auto GetIntrinsicID = [](QualType QT) {
3207       if (auto *VecTy = QT->getAs<VectorType>())
3208         QT = VecTy->getElementType();
3209       if (QT->isSignedIntegerType())
3210         return llvm::Intrinsic::vector_reduce_smin;
3211       if (QT->isUnsignedIntegerType())
3212         return llvm::Intrinsic::vector_reduce_umin;
3213       assert(QT->isFloatingType() && "must have a float here");
3214       return llvm::Intrinsic::vector_reduce_fmin;
3215     };
3216 
3217     return RValue::get(emitUnaryBuiltin(
3218         *this, E, GetIntrinsicID(E->getArg(0)->getType()), "rdx.min"));
3219   }
3220 
3221   case Builtin::BI__builtin_reduce_xor:
3222     return RValue::get(emitUnaryBuiltin(
3223         *this, E, llvm::Intrinsic::vector_reduce_xor, "rdx.xor"));
3224   case Builtin::BI__builtin_reduce_or:
3225     return RValue::get(emitUnaryBuiltin(
3226         *this, E, llvm::Intrinsic::vector_reduce_or, "rdx.or"));
3227   case Builtin::BI__builtin_reduce_and:
3228     return RValue::get(emitUnaryBuiltin(
3229         *this, E, llvm::Intrinsic::vector_reduce_and, "rdx.and"));
3230 
3231   case Builtin::BI__builtin_matrix_transpose: {
3232     auto *MatrixTy = E->getArg(0)->getType()->castAs<ConstantMatrixType>();
3233     Value *MatValue = EmitScalarExpr(E->getArg(0));
3234     MatrixBuilder<CGBuilderTy> MB(Builder);
3235     Value *Result = MB.CreateMatrixTranspose(MatValue, MatrixTy->getNumRows(),
3236                                              MatrixTy->getNumColumns());
3237     return RValue::get(Result);
3238   }
3239 
3240   case Builtin::BI__builtin_matrix_column_major_load: {
3241     MatrixBuilder<CGBuilderTy> MB(Builder);
3242     // Emit everything that isn't dependent on the first parameter type
3243     Value *Stride = EmitScalarExpr(E->getArg(3));
3244     const auto *ResultTy = E->getType()->getAs<ConstantMatrixType>();
3245     auto *PtrTy = E->getArg(0)->getType()->getAs<PointerType>();
3246     assert(PtrTy && "arg0 must be of pointer type");
3247     bool IsVolatile = PtrTy->getPointeeType().isVolatileQualified();
3248 
3249     Address Src = EmitPointerWithAlignment(E->getArg(0));
3250     EmitNonNullArgCheck(RValue::get(Src.getPointer()), E->getArg(0)->getType(),
3251                         E->getArg(0)->getExprLoc(), FD, 0);
3252     Value *Result = MB.CreateColumnMajorLoad(
3253         Src.getPointer(), Align(Src.getAlignment().getQuantity()), Stride,
3254         IsVolatile, ResultTy->getNumRows(), ResultTy->getNumColumns(),
3255         "matrix");
3256     return RValue::get(Result);
3257   }
3258 
3259   case Builtin::BI__builtin_matrix_column_major_store: {
3260     MatrixBuilder<CGBuilderTy> MB(Builder);
3261     Value *Matrix = EmitScalarExpr(E->getArg(0));
3262     Address Dst = EmitPointerWithAlignment(E->getArg(1));
3263     Value *Stride = EmitScalarExpr(E->getArg(2));
3264 
3265     const auto *MatrixTy = E->getArg(0)->getType()->getAs<ConstantMatrixType>();
3266     auto *PtrTy = E->getArg(1)->getType()->getAs<PointerType>();
3267     assert(PtrTy && "arg1 must be of pointer type");
3268     bool IsVolatile = PtrTy->getPointeeType().isVolatileQualified();
3269 
3270     EmitNonNullArgCheck(RValue::get(Dst.getPointer()), E->getArg(1)->getType(),
3271                         E->getArg(1)->getExprLoc(), FD, 0);
3272     Value *Result = MB.CreateColumnMajorStore(
3273         Matrix, Dst.getPointer(), Align(Dst.getAlignment().getQuantity()),
3274         Stride, IsVolatile, MatrixTy->getNumRows(), MatrixTy->getNumColumns());
3275     return RValue::get(Result);
3276   }
3277 
3278   case Builtin::BIfinite:
3279   case Builtin::BI__finite:
3280   case Builtin::BIfinitef:
3281   case Builtin::BI__finitef:
3282   case Builtin::BIfinitel:
3283   case Builtin::BI__finitel:
3284   case Builtin::BI__builtin_isinf:
3285   case Builtin::BI__builtin_isfinite: {
3286     // isinf(x)    --> fabs(x) == infinity
3287     // isfinite(x) --> fabs(x) != infinity
3288     // x != NaN via the ordered compare in either case.
3289     CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
3290     Value *V = EmitScalarExpr(E->getArg(0));
3291     llvm::Type *Ty = V->getType();
3292     if (!Builder.getIsFPConstrained() ||
3293         Builder.getDefaultConstrainedExcept() == fp::ebIgnore ||
3294         !Ty->isIEEE()) {
3295       Value *Fabs = EmitFAbs(*this, V);
3296       Constant *Infinity = ConstantFP::getInfinity(V->getType());
3297       CmpInst::Predicate Pred = (BuiltinID == Builtin::BI__builtin_isinf)
3298                                     ? CmpInst::FCMP_OEQ
3299                                     : CmpInst::FCMP_ONE;
3300       Value *FCmp = Builder.CreateFCmp(Pred, Fabs, Infinity, "cmpinf");
3301       return RValue::get(Builder.CreateZExt(FCmp, ConvertType(E->getType())));
3302     }
3303 
3304     if (Value *Result = getTargetHooks().testFPKind(V, BuiltinID, Builder, CGM))
3305       return RValue::get(Result);
3306 
3307     // Inf values have all exp bits set and a zero significand. Therefore:
3308     // isinf(V) == ((V << 1) == ((exp mask) << 1))
3309     // isfinite(V) == ((V << 1) < ((exp mask) << 1)) using unsigned comparison
3310     unsigned bitsize = Ty->getScalarSizeInBits();
3311     llvm::IntegerType *IntTy = Builder.getIntNTy(bitsize);
3312     Value *IntV = Builder.CreateBitCast(V, IntTy);
3313     Value *Shl1 = Builder.CreateShl(IntV, 1);
3314     const llvm::fltSemantics &Semantics = Ty->getFltSemantics();
3315     APInt ExpMask = APFloat::getInf(Semantics).bitcastToAPInt();
3316     Value *ExpMaskShl1 = llvm::ConstantInt::get(IntTy, ExpMask.shl(1));
3317     if (BuiltinID == Builtin::BI__builtin_isinf)
3318       V = Builder.CreateICmpEQ(Shl1, ExpMaskShl1);
3319     else
3320       V = Builder.CreateICmpULT(Shl1, ExpMaskShl1);
3321     return RValue::get(Builder.CreateZExt(V, ConvertType(E->getType())));
3322   }
3323 
3324   case Builtin::BI__builtin_isinf_sign: {
3325     // isinf_sign(x) -> fabs(x) == infinity ? (signbit(x) ? -1 : 1) : 0
3326     CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
3327     // FIXME: for strictfp/IEEE-754 we need to not trap on SNaN here.
3328     Value *Arg = EmitScalarExpr(E->getArg(0));
3329     Value *AbsArg = EmitFAbs(*this, Arg);
3330     Value *IsInf = Builder.CreateFCmpOEQ(
3331         AbsArg, ConstantFP::getInfinity(Arg->getType()), "isinf");
3332     Value *IsNeg = EmitSignBit(*this, Arg);
3333 
3334     llvm::Type *IntTy = ConvertType(E->getType());
3335     Value *Zero = Constant::getNullValue(IntTy);
3336     Value *One = ConstantInt::get(IntTy, 1);
3337     Value *NegativeOne = ConstantInt::get(IntTy, -1);
3338     Value *SignResult = Builder.CreateSelect(IsNeg, NegativeOne, One);
3339     Value *Result = Builder.CreateSelect(IsInf, SignResult, Zero);
3340     return RValue::get(Result);
3341   }
3342 
3343   case Builtin::BI__builtin_isnormal: {
3344     // isnormal(x) --> x == x && fabsf(x) < infinity && fabsf(x) >= float_min
3345     CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
3346     // FIXME: for strictfp/IEEE-754 we need to not trap on SNaN here.
3347     Value *V = EmitScalarExpr(E->getArg(0));
3348     Value *Eq = Builder.CreateFCmpOEQ(V, V, "iseq");
3349 
3350     Value *Abs = EmitFAbs(*this, V);
3351     Value *IsLessThanInf =
3352       Builder.CreateFCmpULT(Abs, ConstantFP::getInfinity(V->getType()),"isinf");
3353     APFloat Smallest = APFloat::getSmallestNormalized(
3354                    getContext().getFloatTypeSemantics(E->getArg(0)->getType()));
3355     Value *IsNormal =
3356       Builder.CreateFCmpUGE(Abs, ConstantFP::get(V->getContext(), Smallest),
3357                             "isnormal");
3358     V = Builder.CreateAnd(Eq, IsLessThanInf, "and");
3359     V = Builder.CreateAnd(V, IsNormal, "and");
3360     return RValue::get(Builder.CreateZExt(V, ConvertType(E->getType())));
3361   }
3362 
3363   case Builtin::BI__builtin_flt_rounds: {
3364     Function *F = CGM.getIntrinsic(Intrinsic::flt_rounds);
3365 
3366     llvm::Type *ResultType = ConvertType(E->getType());
3367     Value *Result = Builder.CreateCall(F);
3368     if (Result->getType() != ResultType)
3369       Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
3370                                      "cast");
3371     return RValue::get(Result);
3372   }
3373 
3374   case Builtin::BI__builtin_fpclassify: {
3375     CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
3376     // FIXME: for strictfp/IEEE-754 we need to not trap on SNaN here.
3377     Value *V = EmitScalarExpr(E->getArg(5));
3378     llvm::Type *Ty = ConvertType(E->getArg(5)->getType());
3379 
3380     // Create Result
3381     BasicBlock *Begin = Builder.GetInsertBlock();
3382     BasicBlock *End = createBasicBlock("fpclassify_end", this->CurFn);
3383     Builder.SetInsertPoint(End);
3384     PHINode *Result =
3385       Builder.CreatePHI(ConvertType(E->getArg(0)->getType()), 4,
3386                         "fpclassify_result");
3387 
3388     // if (V==0) return FP_ZERO
3389     Builder.SetInsertPoint(Begin);
3390     Value *IsZero = Builder.CreateFCmpOEQ(V, Constant::getNullValue(Ty),
3391                                           "iszero");
3392     Value *ZeroLiteral = EmitScalarExpr(E->getArg(4));
3393     BasicBlock *NotZero = createBasicBlock("fpclassify_not_zero", this->CurFn);
3394     Builder.CreateCondBr(IsZero, End, NotZero);
3395     Result->addIncoming(ZeroLiteral, Begin);
3396 
3397     // if (V != V) return FP_NAN
3398     Builder.SetInsertPoint(NotZero);
3399     Value *IsNan = Builder.CreateFCmpUNO(V, V, "cmp");
3400     Value *NanLiteral = EmitScalarExpr(E->getArg(0));
3401     BasicBlock *NotNan = createBasicBlock("fpclassify_not_nan", this->CurFn);
3402     Builder.CreateCondBr(IsNan, End, NotNan);
3403     Result->addIncoming(NanLiteral, NotZero);
3404 
3405     // if (fabs(V) == infinity) return FP_INFINITY
3406     Builder.SetInsertPoint(NotNan);
3407     Value *VAbs = EmitFAbs(*this, V);
3408     Value *IsInf =
3409       Builder.CreateFCmpOEQ(VAbs, ConstantFP::getInfinity(V->getType()),
3410                             "isinf");
3411     Value *InfLiteral = EmitScalarExpr(E->getArg(1));
3412     BasicBlock *NotInf = createBasicBlock("fpclassify_not_inf", this->CurFn);
3413     Builder.CreateCondBr(IsInf, End, NotInf);
3414     Result->addIncoming(InfLiteral, NotNan);
3415 
3416     // if (fabs(V) >= MIN_NORMAL) return FP_NORMAL else FP_SUBNORMAL
3417     Builder.SetInsertPoint(NotInf);
3418     APFloat Smallest = APFloat::getSmallestNormalized(
3419         getContext().getFloatTypeSemantics(E->getArg(5)->getType()));
3420     Value *IsNormal =
3421       Builder.CreateFCmpUGE(VAbs, ConstantFP::get(V->getContext(), Smallest),
3422                             "isnormal");
3423     Value *NormalResult =
3424       Builder.CreateSelect(IsNormal, EmitScalarExpr(E->getArg(2)),
3425                            EmitScalarExpr(E->getArg(3)));
3426     Builder.CreateBr(End);
3427     Result->addIncoming(NormalResult, NotInf);
3428 
3429     // return Result
3430     Builder.SetInsertPoint(End);
3431     return RValue::get(Result);
3432   }
3433 
3434   case Builtin::BIalloca:
3435   case Builtin::BI_alloca:
3436   case Builtin::BI__builtin_alloca_uninitialized:
3437   case Builtin::BI__builtin_alloca: {
3438     Value *Size = EmitScalarExpr(E->getArg(0));
3439     const TargetInfo &TI = getContext().getTargetInfo();
3440     // The alignment of the alloca should correspond to __BIGGEST_ALIGNMENT__.
3441     const Align SuitableAlignmentInBytes =
3442         CGM.getContext()
3443             .toCharUnitsFromBits(TI.getSuitableAlign())
3444             .getAsAlign();
3445     AllocaInst *AI = Builder.CreateAlloca(Builder.getInt8Ty(), Size);
3446     AI->setAlignment(SuitableAlignmentInBytes);
3447     if (BuiltinID != Builtin::BI__builtin_alloca_uninitialized)
3448       initializeAlloca(*this, AI, Size, SuitableAlignmentInBytes);
3449     return RValue::get(AI);
3450   }
3451 
3452   case Builtin::BI__builtin_alloca_with_align_uninitialized:
3453   case Builtin::BI__builtin_alloca_with_align: {
3454     Value *Size = EmitScalarExpr(E->getArg(0));
3455     Value *AlignmentInBitsValue = EmitScalarExpr(E->getArg(1));
3456     auto *AlignmentInBitsCI = cast<ConstantInt>(AlignmentInBitsValue);
3457     unsigned AlignmentInBits = AlignmentInBitsCI->getZExtValue();
3458     const Align AlignmentInBytes =
3459         CGM.getContext().toCharUnitsFromBits(AlignmentInBits).getAsAlign();
3460     AllocaInst *AI = Builder.CreateAlloca(Builder.getInt8Ty(), Size);
3461     AI->setAlignment(AlignmentInBytes);
3462     if (BuiltinID != Builtin::BI__builtin_alloca_with_align_uninitialized)
3463       initializeAlloca(*this, AI, Size, AlignmentInBytes);
3464     return RValue::get(AI);
3465   }
3466 
3467   case Builtin::BIbzero:
3468   case Builtin::BI__builtin_bzero: {
3469     Address Dest = EmitPointerWithAlignment(E->getArg(0));
3470     Value *SizeVal = EmitScalarExpr(E->getArg(1));
3471     EmitNonNullArgCheck(RValue::get(Dest.getPointer()), E->getArg(0)->getType(),
3472                         E->getArg(0)->getExprLoc(), FD, 0);
3473     Builder.CreateMemSet(Dest, Builder.getInt8(0), SizeVal, false);
3474     return RValue::get(nullptr);
3475   }
3476   case Builtin::BImemcpy:
3477   case Builtin::BI__builtin_memcpy:
3478   case Builtin::BImempcpy:
3479   case Builtin::BI__builtin_mempcpy: {
3480     Address Dest = EmitPointerWithAlignment(E->getArg(0));
3481     Address Src = EmitPointerWithAlignment(E->getArg(1));
3482     Value *SizeVal = EmitScalarExpr(E->getArg(2));
3483     EmitNonNullArgCheck(RValue::get(Dest.getPointer()), E->getArg(0)->getType(),
3484                         E->getArg(0)->getExprLoc(), FD, 0);
3485     EmitNonNullArgCheck(RValue::get(Src.getPointer()), E->getArg(1)->getType(),
3486                         E->getArg(1)->getExprLoc(), FD, 1);
3487     Builder.CreateMemCpy(Dest, Src, SizeVal, false);
3488     if (BuiltinID == Builtin::BImempcpy ||
3489         BuiltinID == Builtin::BI__builtin_mempcpy)
3490       return RValue::get(Builder.CreateInBoundsGEP(Dest.getElementType(),
3491                                                    Dest.getPointer(), SizeVal));
3492     else
3493       return RValue::get(Dest.getPointer());
3494   }
3495 
3496   case Builtin::BI__builtin_memcpy_inline: {
3497     Address Dest = EmitPointerWithAlignment(E->getArg(0));
3498     Address Src = EmitPointerWithAlignment(E->getArg(1));
3499     uint64_t Size =
3500         E->getArg(2)->EvaluateKnownConstInt(getContext()).getZExtValue();
3501     EmitNonNullArgCheck(RValue::get(Dest.getPointer()), E->getArg(0)->getType(),
3502                         E->getArg(0)->getExprLoc(), FD, 0);
3503     EmitNonNullArgCheck(RValue::get(Src.getPointer()), E->getArg(1)->getType(),
3504                         E->getArg(1)->getExprLoc(), FD, 1);
3505     Builder.CreateMemCpyInline(Dest, Src, Size);
3506     return RValue::get(nullptr);
3507   }
3508 
3509   case Builtin::BI__builtin_char_memchr:
3510     BuiltinID = Builtin::BI__builtin_memchr;
3511     break;
3512 
3513   case Builtin::BI__builtin___memcpy_chk: {
3514     // fold __builtin_memcpy_chk(x, y, cst1, cst2) to memcpy iff cst1<=cst2.
3515     Expr::EvalResult SizeResult, DstSizeResult;
3516     if (!E->getArg(2)->EvaluateAsInt(SizeResult, CGM.getContext()) ||
3517         !E->getArg(3)->EvaluateAsInt(DstSizeResult, CGM.getContext()))
3518       break;
3519     llvm::APSInt Size = SizeResult.Val.getInt();
3520     llvm::APSInt DstSize = DstSizeResult.Val.getInt();
3521     if (Size.ugt(DstSize))
3522       break;
3523     Address Dest = EmitPointerWithAlignment(E->getArg(0));
3524     Address Src = EmitPointerWithAlignment(E->getArg(1));
3525     Value *SizeVal = llvm::ConstantInt::get(Builder.getContext(), Size);
3526     Builder.CreateMemCpy(Dest, Src, SizeVal, false);
3527     return RValue::get(Dest.getPointer());
3528   }
3529 
3530   case Builtin::BI__builtin_objc_memmove_collectable: {
3531     Address DestAddr = EmitPointerWithAlignment(E->getArg(0));
3532     Address SrcAddr = EmitPointerWithAlignment(E->getArg(1));
3533     Value *SizeVal = EmitScalarExpr(E->getArg(2));
3534     CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this,
3535                                                   DestAddr, SrcAddr, SizeVal);
3536     return RValue::get(DestAddr.getPointer());
3537   }
3538 
3539   case Builtin::BI__builtin___memmove_chk: {
3540     // fold __builtin_memmove_chk(x, y, cst1, cst2) to memmove iff cst1<=cst2.
3541     Expr::EvalResult SizeResult, DstSizeResult;
3542     if (!E->getArg(2)->EvaluateAsInt(SizeResult, CGM.getContext()) ||
3543         !E->getArg(3)->EvaluateAsInt(DstSizeResult, CGM.getContext()))
3544       break;
3545     llvm::APSInt Size = SizeResult.Val.getInt();
3546     llvm::APSInt DstSize = DstSizeResult.Val.getInt();
3547     if (Size.ugt(DstSize))
3548       break;
3549     Address Dest = EmitPointerWithAlignment(E->getArg(0));
3550     Address Src = EmitPointerWithAlignment(E->getArg(1));
3551     Value *SizeVal = llvm::ConstantInt::get(Builder.getContext(), Size);
3552     Builder.CreateMemMove(Dest, Src, SizeVal, false);
3553     return RValue::get(Dest.getPointer());
3554   }
3555 
3556   case Builtin::BImemmove:
3557   case Builtin::BI__builtin_memmove: {
3558     Address Dest = EmitPointerWithAlignment(E->getArg(0));
3559     Address Src = EmitPointerWithAlignment(E->getArg(1));
3560     Value *SizeVal = EmitScalarExpr(E->getArg(2));
3561     EmitNonNullArgCheck(RValue::get(Dest.getPointer()), E->getArg(0)->getType(),
3562                         E->getArg(0)->getExprLoc(), FD, 0);
3563     EmitNonNullArgCheck(RValue::get(Src.getPointer()), E->getArg(1)->getType(),
3564                         E->getArg(1)->getExprLoc(), FD, 1);
3565     Builder.CreateMemMove(Dest, Src, SizeVal, false);
3566     return RValue::get(Dest.getPointer());
3567   }
3568   case Builtin::BImemset:
3569   case Builtin::BI__builtin_memset: {
3570     Address Dest = EmitPointerWithAlignment(E->getArg(0));
3571     Value *ByteVal = Builder.CreateTrunc(EmitScalarExpr(E->getArg(1)),
3572                                          Builder.getInt8Ty());
3573     Value *SizeVal = EmitScalarExpr(E->getArg(2));
3574     EmitNonNullArgCheck(RValue::get(Dest.getPointer()), E->getArg(0)->getType(),
3575                         E->getArg(0)->getExprLoc(), FD, 0);
3576     Builder.CreateMemSet(Dest, ByteVal, SizeVal, false);
3577     return RValue::get(Dest.getPointer());
3578   }
3579   case Builtin::BI__builtin___memset_chk: {
3580     // fold __builtin_memset_chk(x, y, cst1, cst2) to memset iff cst1<=cst2.
3581     Expr::EvalResult SizeResult, DstSizeResult;
3582     if (!E->getArg(2)->EvaluateAsInt(SizeResult, CGM.getContext()) ||
3583         !E->getArg(3)->EvaluateAsInt(DstSizeResult, CGM.getContext()))
3584       break;
3585     llvm::APSInt Size = SizeResult.Val.getInt();
3586     llvm::APSInt DstSize = DstSizeResult.Val.getInt();
3587     if (Size.ugt(DstSize))
3588       break;
3589     Address Dest = EmitPointerWithAlignment(E->getArg(0));
3590     Value *ByteVal = Builder.CreateTrunc(EmitScalarExpr(E->getArg(1)),
3591                                          Builder.getInt8Ty());
3592     Value *SizeVal = llvm::ConstantInt::get(Builder.getContext(), Size);
3593     Builder.CreateMemSet(Dest, ByteVal, SizeVal, false);
3594     return RValue::get(Dest.getPointer());
3595   }
3596   case Builtin::BI__builtin_wmemchr: {
3597     // The MSVC runtime library does not provide a definition of wmemchr, so we
3598     // need an inline implementation.
3599     if (!getTarget().getTriple().isOSMSVCRT())
3600       break;
3601 
3602     llvm::Type *WCharTy = ConvertType(getContext().WCharTy);
3603     Value *Str = EmitScalarExpr(E->getArg(0));
3604     Value *Chr = EmitScalarExpr(E->getArg(1));
3605     Value *Size = EmitScalarExpr(E->getArg(2));
3606 
3607     BasicBlock *Entry = Builder.GetInsertBlock();
3608     BasicBlock *CmpEq = createBasicBlock("wmemchr.eq");
3609     BasicBlock *Next = createBasicBlock("wmemchr.next");
3610     BasicBlock *Exit = createBasicBlock("wmemchr.exit");
3611     Value *SizeEq0 = Builder.CreateICmpEQ(Size, ConstantInt::get(SizeTy, 0));
3612     Builder.CreateCondBr(SizeEq0, Exit, CmpEq);
3613 
3614     EmitBlock(CmpEq);
3615     PHINode *StrPhi = Builder.CreatePHI(Str->getType(), 2);
3616     StrPhi->addIncoming(Str, Entry);
3617     PHINode *SizePhi = Builder.CreatePHI(SizeTy, 2);
3618     SizePhi->addIncoming(Size, Entry);
3619     CharUnits WCharAlign =
3620         getContext().getTypeAlignInChars(getContext().WCharTy);
3621     Value *StrCh = Builder.CreateAlignedLoad(WCharTy, StrPhi, WCharAlign);
3622     Value *FoundChr = Builder.CreateConstInBoundsGEP1_32(WCharTy, StrPhi, 0);
3623     Value *StrEqChr = Builder.CreateICmpEQ(StrCh, Chr);
3624     Builder.CreateCondBr(StrEqChr, Exit, Next);
3625 
3626     EmitBlock(Next);
3627     Value *NextStr = Builder.CreateConstInBoundsGEP1_32(WCharTy, StrPhi, 1);
3628     Value *NextSize = Builder.CreateSub(SizePhi, ConstantInt::get(SizeTy, 1));
3629     Value *NextSizeEq0 =
3630         Builder.CreateICmpEQ(NextSize, ConstantInt::get(SizeTy, 0));
3631     Builder.CreateCondBr(NextSizeEq0, Exit, CmpEq);
3632     StrPhi->addIncoming(NextStr, Next);
3633     SizePhi->addIncoming(NextSize, Next);
3634 
3635     EmitBlock(Exit);
3636     PHINode *Ret = Builder.CreatePHI(Str->getType(), 3);
3637     Ret->addIncoming(llvm::Constant::getNullValue(Str->getType()), Entry);
3638     Ret->addIncoming(llvm::Constant::getNullValue(Str->getType()), Next);
3639     Ret->addIncoming(FoundChr, CmpEq);
3640     return RValue::get(Ret);
3641   }
3642   case Builtin::BI__builtin_wmemcmp: {
3643     // The MSVC runtime library does not provide a definition of wmemcmp, so we
3644     // need an inline implementation.
3645     if (!getTarget().getTriple().isOSMSVCRT())
3646       break;
3647 
3648     llvm::Type *WCharTy = ConvertType(getContext().WCharTy);
3649 
3650     Value *Dst = EmitScalarExpr(E->getArg(0));
3651     Value *Src = EmitScalarExpr(E->getArg(1));
3652     Value *Size = EmitScalarExpr(E->getArg(2));
3653 
3654     BasicBlock *Entry = Builder.GetInsertBlock();
3655     BasicBlock *CmpGT = createBasicBlock("wmemcmp.gt");
3656     BasicBlock *CmpLT = createBasicBlock("wmemcmp.lt");
3657     BasicBlock *Next = createBasicBlock("wmemcmp.next");
3658     BasicBlock *Exit = createBasicBlock("wmemcmp.exit");
3659     Value *SizeEq0 = Builder.CreateICmpEQ(Size, ConstantInt::get(SizeTy, 0));
3660     Builder.CreateCondBr(SizeEq0, Exit, CmpGT);
3661 
3662     EmitBlock(CmpGT);
3663     PHINode *DstPhi = Builder.CreatePHI(Dst->getType(), 2);
3664     DstPhi->addIncoming(Dst, Entry);
3665     PHINode *SrcPhi = Builder.CreatePHI(Src->getType(), 2);
3666     SrcPhi->addIncoming(Src, Entry);
3667     PHINode *SizePhi = Builder.CreatePHI(SizeTy, 2);
3668     SizePhi->addIncoming(Size, Entry);
3669     CharUnits WCharAlign =
3670         getContext().getTypeAlignInChars(getContext().WCharTy);
3671     Value *DstCh = Builder.CreateAlignedLoad(WCharTy, DstPhi, WCharAlign);
3672     Value *SrcCh = Builder.CreateAlignedLoad(WCharTy, SrcPhi, WCharAlign);
3673     Value *DstGtSrc = Builder.CreateICmpUGT(DstCh, SrcCh);
3674     Builder.CreateCondBr(DstGtSrc, Exit, CmpLT);
3675 
3676     EmitBlock(CmpLT);
3677     Value *DstLtSrc = Builder.CreateICmpULT(DstCh, SrcCh);
3678     Builder.CreateCondBr(DstLtSrc, Exit, Next);
3679 
3680     EmitBlock(Next);
3681     Value *NextDst = Builder.CreateConstInBoundsGEP1_32(WCharTy, DstPhi, 1);
3682     Value *NextSrc = Builder.CreateConstInBoundsGEP1_32(WCharTy, SrcPhi, 1);
3683     Value *NextSize = Builder.CreateSub(SizePhi, ConstantInt::get(SizeTy, 1));
3684     Value *NextSizeEq0 =
3685         Builder.CreateICmpEQ(NextSize, ConstantInt::get(SizeTy, 0));
3686     Builder.CreateCondBr(NextSizeEq0, Exit, CmpGT);
3687     DstPhi->addIncoming(NextDst, Next);
3688     SrcPhi->addIncoming(NextSrc, Next);
3689     SizePhi->addIncoming(NextSize, Next);
3690 
3691     EmitBlock(Exit);
3692     PHINode *Ret = Builder.CreatePHI(IntTy, 4);
3693     Ret->addIncoming(ConstantInt::get(IntTy, 0), Entry);
3694     Ret->addIncoming(ConstantInt::get(IntTy, 1), CmpGT);
3695     Ret->addIncoming(ConstantInt::get(IntTy, -1), CmpLT);
3696     Ret->addIncoming(ConstantInt::get(IntTy, 0), Next);
3697     return RValue::get(Ret);
3698   }
3699   case Builtin::BI__builtin_dwarf_cfa: {
3700     // The offset in bytes from the first argument to the CFA.
3701     //
3702     // Why on earth is this in the frontend?  Is there any reason at
3703     // all that the backend can't reasonably determine this while
3704     // lowering llvm.eh.dwarf.cfa()?
3705     //
3706     // TODO: If there's a satisfactory reason, add a target hook for
3707     // this instead of hard-coding 0, which is correct for most targets.
3708     int32_t Offset = 0;
3709 
3710     Function *F = CGM.getIntrinsic(Intrinsic::eh_dwarf_cfa);
3711     return RValue::get(Builder.CreateCall(F,
3712                                       llvm::ConstantInt::get(Int32Ty, Offset)));
3713   }
3714   case Builtin::BI__builtin_return_address: {
3715     Value *Depth = ConstantEmitter(*this).emitAbstract(E->getArg(0),
3716                                                    getContext().UnsignedIntTy);
3717     Function *F = CGM.getIntrinsic(Intrinsic::returnaddress);
3718     return RValue::get(Builder.CreateCall(F, Depth));
3719   }
3720   case Builtin::BI_ReturnAddress: {
3721     Function *F = CGM.getIntrinsic(Intrinsic::returnaddress);
3722     return RValue::get(Builder.CreateCall(F, Builder.getInt32(0)));
3723   }
3724   case Builtin::BI__builtin_frame_address: {
3725     Value *Depth = ConstantEmitter(*this).emitAbstract(E->getArg(0),
3726                                                    getContext().UnsignedIntTy);
3727     Function *F = CGM.getIntrinsic(Intrinsic::frameaddress, AllocaInt8PtrTy);
3728     return RValue::get(Builder.CreateCall(F, Depth));
3729   }
3730   case Builtin::BI__builtin_extract_return_addr: {
3731     Value *Address = EmitScalarExpr(E->getArg(0));
3732     Value *Result = getTargetHooks().decodeReturnAddress(*this, Address);
3733     return RValue::get(Result);
3734   }
3735   case Builtin::BI__builtin_frob_return_addr: {
3736     Value *Address = EmitScalarExpr(E->getArg(0));
3737     Value *Result = getTargetHooks().encodeReturnAddress(*this, Address);
3738     return RValue::get(Result);
3739   }
3740   case Builtin::BI__builtin_dwarf_sp_column: {
3741     llvm::IntegerType *Ty
3742       = cast<llvm::IntegerType>(ConvertType(E->getType()));
3743     int Column = getTargetHooks().getDwarfEHStackPointer(CGM);
3744     if (Column == -1) {
3745       CGM.ErrorUnsupported(E, "__builtin_dwarf_sp_column");
3746       return RValue::get(llvm::UndefValue::get(Ty));
3747     }
3748     return RValue::get(llvm::ConstantInt::get(Ty, Column, true));
3749   }
3750   case Builtin::BI__builtin_init_dwarf_reg_size_table: {
3751     Value *Address = EmitScalarExpr(E->getArg(0));
3752     if (getTargetHooks().initDwarfEHRegSizeTable(*this, Address))
3753       CGM.ErrorUnsupported(E, "__builtin_init_dwarf_reg_size_table");
3754     return RValue::get(llvm::UndefValue::get(ConvertType(E->getType())));
3755   }
3756   case Builtin::BI__builtin_eh_return: {
3757     Value *Int = EmitScalarExpr(E->getArg(0));
3758     Value *Ptr = EmitScalarExpr(E->getArg(1));
3759 
3760     llvm::IntegerType *IntTy = cast<llvm::IntegerType>(Int->getType());
3761     assert((IntTy->getBitWidth() == 32 || IntTy->getBitWidth() == 64) &&
3762            "LLVM's __builtin_eh_return only supports 32- and 64-bit variants");
3763     Function *F =
3764         CGM.getIntrinsic(IntTy->getBitWidth() == 32 ? Intrinsic::eh_return_i32
3765                                                     : Intrinsic::eh_return_i64);
3766     Builder.CreateCall(F, {Int, Ptr});
3767     Builder.CreateUnreachable();
3768 
3769     // We do need to preserve an insertion point.
3770     EmitBlock(createBasicBlock("builtin_eh_return.cont"));
3771 
3772     return RValue::get(nullptr);
3773   }
3774   case Builtin::BI__builtin_unwind_init: {
3775     Function *F = CGM.getIntrinsic(Intrinsic::eh_unwind_init);
3776     return RValue::get(Builder.CreateCall(F));
3777   }
3778   case Builtin::BI__builtin_extend_pointer: {
3779     // Extends a pointer to the size of an _Unwind_Word, which is
3780     // uint64_t on all platforms.  Generally this gets poked into a
3781     // register and eventually used as an address, so if the
3782     // addressing registers are wider than pointers and the platform
3783     // doesn't implicitly ignore high-order bits when doing
3784     // addressing, we need to make sure we zext / sext based on
3785     // the platform's expectations.
3786     //
3787     // See: http://gcc.gnu.org/ml/gcc-bugs/2002-02/msg00237.html
3788 
3789     // Cast the pointer to intptr_t.
3790     Value *Ptr = EmitScalarExpr(E->getArg(0));
3791     Value *Result = Builder.CreatePtrToInt(Ptr, IntPtrTy, "extend.cast");
3792 
3793     // If that's 64 bits, we're done.
3794     if (IntPtrTy->getBitWidth() == 64)
3795       return RValue::get(Result);
3796 
3797     // Otherwise, ask the codegen data what to do.
3798     if (getTargetHooks().extendPointerWithSExt())
3799       return RValue::get(Builder.CreateSExt(Result, Int64Ty, "extend.sext"));
3800     else
3801       return RValue::get(Builder.CreateZExt(Result, Int64Ty, "extend.zext"));
3802   }
3803   case Builtin::BI__builtin_setjmp: {
3804     // Buffer is a void**.
3805     Address Buf = EmitPointerWithAlignment(E->getArg(0));
3806 
3807     // Store the frame pointer to the setjmp buffer.
3808     Value *FrameAddr = Builder.CreateCall(
3809         CGM.getIntrinsic(Intrinsic::frameaddress, AllocaInt8PtrTy),
3810         ConstantInt::get(Int32Ty, 0));
3811     Builder.CreateStore(FrameAddr, Buf);
3812 
3813     // Store the stack pointer to the setjmp buffer.
3814     Value *StackAddr =
3815         Builder.CreateCall(CGM.getIntrinsic(Intrinsic::stacksave));
3816     Address StackSaveSlot = Builder.CreateConstInBoundsGEP(Buf, 2);
3817     Builder.CreateStore(StackAddr, StackSaveSlot);
3818 
3819     // Call LLVM's EH setjmp, which is lightweight.
3820     Function *F = CGM.getIntrinsic(Intrinsic::eh_sjlj_setjmp);
3821     Buf = Builder.CreateBitCast(Buf, Int8PtrTy);
3822     return RValue::get(Builder.CreateCall(F, Buf.getPointer()));
3823   }
3824   case Builtin::BI__builtin_longjmp: {
3825     Value *Buf = EmitScalarExpr(E->getArg(0));
3826     Buf = Builder.CreateBitCast(Buf, Int8PtrTy);
3827 
3828     // Call LLVM's EH longjmp, which is lightweight.
3829     Builder.CreateCall(CGM.getIntrinsic(Intrinsic::eh_sjlj_longjmp), Buf);
3830 
3831     // longjmp doesn't return; mark this as unreachable.
3832     Builder.CreateUnreachable();
3833 
3834     // We do need to preserve an insertion point.
3835     EmitBlock(createBasicBlock("longjmp.cont"));
3836 
3837     return RValue::get(nullptr);
3838   }
3839   case Builtin::BI__builtin_launder: {
3840     const Expr *Arg = E->getArg(0);
3841     QualType ArgTy = Arg->getType()->getPointeeType();
3842     Value *Ptr = EmitScalarExpr(Arg);
3843     if (TypeRequiresBuiltinLaunder(CGM, ArgTy))
3844       Ptr = Builder.CreateLaunderInvariantGroup(Ptr);
3845 
3846     return RValue::get(Ptr);
3847   }
3848   case Builtin::BI__sync_fetch_and_add:
3849   case Builtin::BI__sync_fetch_and_sub:
3850   case Builtin::BI__sync_fetch_and_or:
3851   case Builtin::BI__sync_fetch_and_and:
3852   case Builtin::BI__sync_fetch_and_xor:
3853   case Builtin::BI__sync_fetch_and_nand:
3854   case Builtin::BI__sync_add_and_fetch:
3855   case Builtin::BI__sync_sub_and_fetch:
3856   case Builtin::BI__sync_and_and_fetch:
3857   case Builtin::BI__sync_or_and_fetch:
3858   case Builtin::BI__sync_xor_and_fetch:
3859   case Builtin::BI__sync_nand_and_fetch:
3860   case Builtin::BI__sync_val_compare_and_swap:
3861   case Builtin::BI__sync_bool_compare_and_swap:
3862   case Builtin::BI__sync_lock_test_and_set:
3863   case Builtin::BI__sync_lock_release:
3864   case Builtin::BI__sync_swap:
3865     llvm_unreachable("Shouldn't make it through sema");
3866   case Builtin::BI__sync_fetch_and_add_1:
3867   case Builtin::BI__sync_fetch_and_add_2:
3868   case Builtin::BI__sync_fetch_and_add_4:
3869   case Builtin::BI__sync_fetch_and_add_8:
3870   case Builtin::BI__sync_fetch_and_add_16:
3871     return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Add, E);
3872   case Builtin::BI__sync_fetch_and_sub_1:
3873   case Builtin::BI__sync_fetch_and_sub_2:
3874   case Builtin::BI__sync_fetch_and_sub_4:
3875   case Builtin::BI__sync_fetch_and_sub_8:
3876   case Builtin::BI__sync_fetch_and_sub_16:
3877     return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Sub, E);
3878   case Builtin::BI__sync_fetch_and_or_1:
3879   case Builtin::BI__sync_fetch_and_or_2:
3880   case Builtin::BI__sync_fetch_and_or_4:
3881   case Builtin::BI__sync_fetch_and_or_8:
3882   case Builtin::BI__sync_fetch_and_or_16:
3883     return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Or, E);
3884   case Builtin::BI__sync_fetch_and_and_1:
3885   case Builtin::BI__sync_fetch_and_and_2:
3886   case Builtin::BI__sync_fetch_and_and_4:
3887   case Builtin::BI__sync_fetch_and_and_8:
3888   case Builtin::BI__sync_fetch_and_and_16:
3889     return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::And, E);
3890   case Builtin::BI__sync_fetch_and_xor_1:
3891   case Builtin::BI__sync_fetch_and_xor_2:
3892   case Builtin::BI__sync_fetch_and_xor_4:
3893   case Builtin::BI__sync_fetch_and_xor_8:
3894   case Builtin::BI__sync_fetch_and_xor_16:
3895     return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Xor, E);
3896   case Builtin::BI__sync_fetch_and_nand_1:
3897   case Builtin::BI__sync_fetch_and_nand_2:
3898   case Builtin::BI__sync_fetch_and_nand_4:
3899   case Builtin::BI__sync_fetch_and_nand_8:
3900   case Builtin::BI__sync_fetch_and_nand_16:
3901     return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Nand, E);
3902 
3903   // Clang extensions: not overloaded yet.
3904   case Builtin::BI__sync_fetch_and_min:
3905     return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Min, E);
3906   case Builtin::BI__sync_fetch_and_max:
3907     return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Max, E);
3908   case Builtin::BI__sync_fetch_and_umin:
3909     return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::UMin, E);
3910   case Builtin::BI__sync_fetch_and_umax:
3911     return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::UMax, E);
3912 
3913   case Builtin::BI__sync_add_and_fetch_1:
3914   case Builtin::BI__sync_add_and_fetch_2:
3915   case Builtin::BI__sync_add_and_fetch_4:
3916   case Builtin::BI__sync_add_and_fetch_8:
3917   case Builtin::BI__sync_add_and_fetch_16:
3918     return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Add, E,
3919                                 llvm::Instruction::Add);
3920   case Builtin::BI__sync_sub_and_fetch_1:
3921   case Builtin::BI__sync_sub_and_fetch_2:
3922   case Builtin::BI__sync_sub_and_fetch_4:
3923   case Builtin::BI__sync_sub_and_fetch_8:
3924   case Builtin::BI__sync_sub_and_fetch_16:
3925     return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Sub, E,
3926                                 llvm::Instruction::Sub);
3927   case Builtin::BI__sync_and_and_fetch_1:
3928   case Builtin::BI__sync_and_and_fetch_2:
3929   case Builtin::BI__sync_and_and_fetch_4:
3930   case Builtin::BI__sync_and_and_fetch_8:
3931   case Builtin::BI__sync_and_and_fetch_16:
3932     return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::And, E,
3933                                 llvm::Instruction::And);
3934   case Builtin::BI__sync_or_and_fetch_1:
3935   case Builtin::BI__sync_or_and_fetch_2:
3936   case Builtin::BI__sync_or_and_fetch_4:
3937   case Builtin::BI__sync_or_and_fetch_8:
3938   case Builtin::BI__sync_or_and_fetch_16:
3939     return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Or, E,
3940                                 llvm::Instruction::Or);
3941   case Builtin::BI__sync_xor_and_fetch_1:
3942   case Builtin::BI__sync_xor_and_fetch_2:
3943   case Builtin::BI__sync_xor_and_fetch_4:
3944   case Builtin::BI__sync_xor_and_fetch_8:
3945   case Builtin::BI__sync_xor_and_fetch_16:
3946     return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Xor, E,
3947                                 llvm::Instruction::Xor);
3948   case Builtin::BI__sync_nand_and_fetch_1:
3949   case Builtin::BI__sync_nand_and_fetch_2:
3950   case Builtin::BI__sync_nand_and_fetch_4:
3951   case Builtin::BI__sync_nand_and_fetch_8:
3952   case Builtin::BI__sync_nand_and_fetch_16:
3953     return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Nand, E,
3954                                 llvm::Instruction::And, true);
3955 
3956   case Builtin::BI__sync_val_compare_and_swap_1:
3957   case Builtin::BI__sync_val_compare_and_swap_2:
3958   case Builtin::BI__sync_val_compare_and_swap_4:
3959   case Builtin::BI__sync_val_compare_and_swap_8:
3960   case Builtin::BI__sync_val_compare_and_swap_16:
3961     return RValue::get(MakeAtomicCmpXchgValue(*this, E, false));
3962 
3963   case Builtin::BI__sync_bool_compare_and_swap_1:
3964   case Builtin::BI__sync_bool_compare_and_swap_2:
3965   case Builtin::BI__sync_bool_compare_and_swap_4:
3966   case Builtin::BI__sync_bool_compare_and_swap_8:
3967   case Builtin::BI__sync_bool_compare_and_swap_16:
3968     return RValue::get(MakeAtomicCmpXchgValue(*this, E, true));
3969 
3970   case Builtin::BI__sync_swap_1:
3971   case Builtin::BI__sync_swap_2:
3972   case Builtin::BI__sync_swap_4:
3973   case Builtin::BI__sync_swap_8:
3974   case Builtin::BI__sync_swap_16:
3975     return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Xchg, E);
3976 
3977   case Builtin::BI__sync_lock_test_and_set_1:
3978   case Builtin::BI__sync_lock_test_and_set_2:
3979   case Builtin::BI__sync_lock_test_and_set_4:
3980   case Builtin::BI__sync_lock_test_and_set_8:
3981   case Builtin::BI__sync_lock_test_and_set_16:
3982     return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Xchg, E);
3983 
3984   case Builtin::BI__sync_lock_release_1:
3985   case Builtin::BI__sync_lock_release_2:
3986   case Builtin::BI__sync_lock_release_4:
3987   case Builtin::BI__sync_lock_release_8:
3988   case Builtin::BI__sync_lock_release_16: {
3989     Value *Ptr = EmitScalarExpr(E->getArg(0));
3990     QualType ElTy = E->getArg(0)->getType()->getPointeeType();
3991     CharUnits StoreSize = getContext().getTypeSizeInChars(ElTy);
3992     llvm::Type *ITy = llvm::IntegerType::get(getLLVMContext(),
3993                                              StoreSize.getQuantity() * 8);
3994     Ptr = Builder.CreateBitCast(Ptr, ITy->getPointerTo());
3995     llvm::StoreInst *Store =
3996       Builder.CreateAlignedStore(llvm::Constant::getNullValue(ITy), Ptr,
3997                                  StoreSize);
3998     Store->setAtomic(llvm::AtomicOrdering::Release);
3999     return RValue::get(nullptr);
4000   }
4001 
4002   case Builtin::BI__sync_synchronize: {
4003     // We assume this is supposed to correspond to a C++0x-style
4004     // sequentially-consistent fence (i.e. this is only usable for
4005     // synchronization, not device I/O or anything like that). This intrinsic
4006     // is really badly designed in the sense that in theory, there isn't
4007     // any way to safely use it... but in practice, it mostly works
4008     // to use it with non-atomic loads and stores to get acquire/release
4009     // semantics.
4010     Builder.CreateFence(llvm::AtomicOrdering::SequentiallyConsistent);
4011     return RValue::get(nullptr);
4012   }
4013 
4014   case Builtin::BI__builtin_nontemporal_load:
4015     return RValue::get(EmitNontemporalLoad(*this, E));
4016   case Builtin::BI__builtin_nontemporal_store:
4017     return RValue::get(EmitNontemporalStore(*this, E));
4018   case Builtin::BI__c11_atomic_is_lock_free:
4019   case Builtin::BI__atomic_is_lock_free: {
4020     // Call "bool __atomic_is_lock_free(size_t size, void *ptr)". For the
4021     // __c11 builtin, ptr is 0 (indicating a properly-aligned object), since
4022     // _Atomic(T) is always properly-aligned.
4023     const char *LibCallName = "__atomic_is_lock_free";
4024     CallArgList Args;
4025     Args.add(RValue::get(EmitScalarExpr(E->getArg(0))),
4026              getContext().getSizeType());
4027     if (BuiltinID == Builtin::BI__atomic_is_lock_free)
4028       Args.add(RValue::get(EmitScalarExpr(E->getArg(1))),
4029                getContext().VoidPtrTy);
4030     else
4031       Args.add(RValue::get(llvm::Constant::getNullValue(VoidPtrTy)),
4032                getContext().VoidPtrTy);
4033     const CGFunctionInfo &FuncInfo =
4034         CGM.getTypes().arrangeBuiltinFunctionCall(E->getType(), Args);
4035     llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FuncInfo);
4036     llvm::FunctionCallee Func = CGM.CreateRuntimeFunction(FTy, LibCallName);
4037     return EmitCall(FuncInfo, CGCallee::forDirect(Func),
4038                     ReturnValueSlot(), Args);
4039   }
4040 
4041   case Builtin::BI__atomic_test_and_set: {
4042     // Look at the argument type to determine whether this is a volatile
4043     // operation. The parameter type is always volatile.
4044     QualType PtrTy = E->getArg(0)->IgnoreImpCasts()->getType();
4045     bool Volatile =
4046         PtrTy->castAs<PointerType>()->getPointeeType().isVolatileQualified();
4047 
4048     Value *Ptr = EmitScalarExpr(E->getArg(0));
4049     unsigned AddrSpace = Ptr->getType()->getPointerAddressSpace();
4050     Ptr = Builder.CreateBitCast(Ptr, Int8Ty->getPointerTo(AddrSpace));
4051     Value *NewVal = Builder.getInt8(1);
4052     Value *Order = EmitScalarExpr(E->getArg(1));
4053     if (isa<llvm::ConstantInt>(Order)) {
4054       int ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
4055       AtomicRMWInst *Result = nullptr;
4056       switch (ord) {
4057       case 0:  // memory_order_relaxed
4058       default: // invalid order
4059         Result = Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg, Ptr, NewVal,
4060                                          llvm::AtomicOrdering::Monotonic);
4061         break;
4062       case 1: // memory_order_consume
4063       case 2: // memory_order_acquire
4064         Result = Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg, Ptr, NewVal,
4065                                          llvm::AtomicOrdering::Acquire);
4066         break;
4067       case 3: // memory_order_release
4068         Result = Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg, Ptr, NewVal,
4069                                          llvm::AtomicOrdering::Release);
4070         break;
4071       case 4: // memory_order_acq_rel
4072 
4073         Result = Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg, Ptr, NewVal,
4074                                          llvm::AtomicOrdering::AcquireRelease);
4075         break;
4076       case 5: // memory_order_seq_cst
4077         Result = Builder.CreateAtomicRMW(
4078             llvm::AtomicRMWInst::Xchg, Ptr, NewVal,
4079             llvm::AtomicOrdering::SequentiallyConsistent);
4080         break;
4081       }
4082       Result->setVolatile(Volatile);
4083       return RValue::get(Builder.CreateIsNotNull(Result, "tobool"));
4084     }
4085 
4086     llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
4087 
4088     llvm::BasicBlock *BBs[5] = {
4089       createBasicBlock("monotonic", CurFn),
4090       createBasicBlock("acquire", CurFn),
4091       createBasicBlock("release", CurFn),
4092       createBasicBlock("acqrel", CurFn),
4093       createBasicBlock("seqcst", CurFn)
4094     };
4095     llvm::AtomicOrdering Orders[5] = {
4096         llvm::AtomicOrdering::Monotonic, llvm::AtomicOrdering::Acquire,
4097         llvm::AtomicOrdering::Release, llvm::AtomicOrdering::AcquireRelease,
4098         llvm::AtomicOrdering::SequentiallyConsistent};
4099 
4100     Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
4101     llvm::SwitchInst *SI = Builder.CreateSwitch(Order, BBs[0]);
4102 
4103     Builder.SetInsertPoint(ContBB);
4104     PHINode *Result = Builder.CreatePHI(Int8Ty, 5, "was_set");
4105 
4106     for (unsigned i = 0; i < 5; ++i) {
4107       Builder.SetInsertPoint(BBs[i]);
4108       AtomicRMWInst *RMW = Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg,
4109                                                    Ptr, NewVal, Orders[i]);
4110       RMW->setVolatile(Volatile);
4111       Result->addIncoming(RMW, BBs[i]);
4112       Builder.CreateBr(ContBB);
4113     }
4114 
4115     SI->addCase(Builder.getInt32(0), BBs[0]);
4116     SI->addCase(Builder.getInt32(1), BBs[1]);
4117     SI->addCase(Builder.getInt32(2), BBs[1]);
4118     SI->addCase(Builder.getInt32(3), BBs[2]);
4119     SI->addCase(Builder.getInt32(4), BBs[3]);
4120     SI->addCase(Builder.getInt32(5), BBs[4]);
4121 
4122     Builder.SetInsertPoint(ContBB);
4123     return RValue::get(Builder.CreateIsNotNull(Result, "tobool"));
4124   }
4125 
4126   case Builtin::BI__atomic_clear: {
4127     QualType PtrTy = E->getArg(0)->IgnoreImpCasts()->getType();
4128     bool Volatile =
4129         PtrTy->castAs<PointerType>()->getPointeeType().isVolatileQualified();
4130 
4131     Address Ptr = EmitPointerWithAlignment(E->getArg(0));
4132     unsigned AddrSpace = Ptr.getPointer()->getType()->getPointerAddressSpace();
4133     Ptr = Builder.CreateBitCast(Ptr, Int8Ty->getPointerTo(AddrSpace));
4134     Value *NewVal = Builder.getInt8(0);
4135     Value *Order = EmitScalarExpr(E->getArg(1));
4136     if (isa<llvm::ConstantInt>(Order)) {
4137       int ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
4138       StoreInst *Store = Builder.CreateStore(NewVal, Ptr, Volatile);
4139       switch (ord) {
4140       case 0:  // memory_order_relaxed
4141       default: // invalid order
4142         Store->setOrdering(llvm::AtomicOrdering::Monotonic);
4143         break;
4144       case 3:  // memory_order_release
4145         Store->setOrdering(llvm::AtomicOrdering::Release);
4146         break;
4147       case 5:  // memory_order_seq_cst
4148         Store->setOrdering(llvm::AtomicOrdering::SequentiallyConsistent);
4149         break;
4150       }
4151       return RValue::get(nullptr);
4152     }
4153 
4154     llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
4155 
4156     llvm::BasicBlock *BBs[3] = {
4157       createBasicBlock("monotonic", CurFn),
4158       createBasicBlock("release", CurFn),
4159       createBasicBlock("seqcst", CurFn)
4160     };
4161     llvm::AtomicOrdering Orders[3] = {
4162         llvm::AtomicOrdering::Monotonic, llvm::AtomicOrdering::Release,
4163         llvm::AtomicOrdering::SequentiallyConsistent};
4164 
4165     Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
4166     llvm::SwitchInst *SI = Builder.CreateSwitch(Order, BBs[0]);
4167 
4168     for (unsigned i = 0; i < 3; ++i) {
4169       Builder.SetInsertPoint(BBs[i]);
4170       StoreInst *Store = Builder.CreateStore(NewVal, Ptr, Volatile);
4171       Store->setOrdering(Orders[i]);
4172       Builder.CreateBr(ContBB);
4173     }
4174 
4175     SI->addCase(Builder.getInt32(0), BBs[0]);
4176     SI->addCase(Builder.getInt32(3), BBs[1]);
4177     SI->addCase(Builder.getInt32(5), BBs[2]);
4178 
4179     Builder.SetInsertPoint(ContBB);
4180     return RValue::get(nullptr);
4181   }
4182 
4183   case Builtin::BI__atomic_thread_fence:
4184   case Builtin::BI__atomic_signal_fence:
4185   case Builtin::BI__c11_atomic_thread_fence:
4186   case Builtin::BI__c11_atomic_signal_fence: {
4187     llvm::SyncScope::ID SSID;
4188     if (BuiltinID == Builtin::BI__atomic_signal_fence ||
4189         BuiltinID == Builtin::BI__c11_atomic_signal_fence)
4190       SSID = llvm::SyncScope::SingleThread;
4191     else
4192       SSID = llvm::SyncScope::System;
4193     Value *Order = EmitScalarExpr(E->getArg(0));
4194     if (isa<llvm::ConstantInt>(Order)) {
4195       int ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
4196       switch (ord) {
4197       case 0:  // memory_order_relaxed
4198       default: // invalid order
4199         break;
4200       case 1:  // memory_order_consume
4201       case 2:  // memory_order_acquire
4202         Builder.CreateFence(llvm::AtomicOrdering::Acquire, SSID);
4203         break;
4204       case 3:  // memory_order_release
4205         Builder.CreateFence(llvm::AtomicOrdering::Release, SSID);
4206         break;
4207       case 4:  // memory_order_acq_rel
4208         Builder.CreateFence(llvm::AtomicOrdering::AcquireRelease, SSID);
4209         break;
4210       case 5:  // memory_order_seq_cst
4211         Builder.CreateFence(llvm::AtomicOrdering::SequentiallyConsistent, SSID);
4212         break;
4213       }
4214       return RValue::get(nullptr);
4215     }
4216 
4217     llvm::BasicBlock *AcquireBB, *ReleaseBB, *AcqRelBB, *SeqCstBB;
4218     AcquireBB = createBasicBlock("acquire", CurFn);
4219     ReleaseBB = createBasicBlock("release", CurFn);
4220     AcqRelBB = createBasicBlock("acqrel", CurFn);
4221     SeqCstBB = createBasicBlock("seqcst", CurFn);
4222     llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
4223 
4224     Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
4225     llvm::SwitchInst *SI = Builder.CreateSwitch(Order, ContBB);
4226 
4227     Builder.SetInsertPoint(AcquireBB);
4228     Builder.CreateFence(llvm::AtomicOrdering::Acquire, SSID);
4229     Builder.CreateBr(ContBB);
4230     SI->addCase(Builder.getInt32(1), AcquireBB);
4231     SI->addCase(Builder.getInt32(2), AcquireBB);
4232 
4233     Builder.SetInsertPoint(ReleaseBB);
4234     Builder.CreateFence(llvm::AtomicOrdering::Release, SSID);
4235     Builder.CreateBr(ContBB);
4236     SI->addCase(Builder.getInt32(3), ReleaseBB);
4237 
4238     Builder.SetInsertPoint(AcqRelBB);
4239     Builder.CreateFence(llvm::AtomicOrdering::AcquireRelease, SSID);
4240     Builder.CreateBr(ContBB);
4241     SI->addCase(Builder.getInt32(4), AcqRelBB);
4242 
4243     Builder.SetInsertPoint(SeqCstBB);
4244     Builder.CreateFence(llvm::AtomicOrdering::SequentiallyConsistent, SSID);
4245     Builder.CreateBr(ContBB);
4246     SI->addCase(Builder.getInt32(5), SeqCstBB);
4247 
4248     Builder.SetInsertPoint(ContBB);
4249     return RValue::get(nullptr);
4250   }
4251 
4252   case Builtin::BI__builtin_signbit:
4253   case Builtin::BI__builtin_signbitf:
4254   case Builtin::BI__builtin_signbitl: {
4255     return RValue::get(
4256         Builder.CreateZExt(EmitSignBit(*this, EmitScalarExpr(E->getArg(0))),
4257                            ConvertType(E->getType())));
4258   }
4259   case Builtin::BI__warn_memset_zero_len:
4260     return RValue::getIgnored();
4261   case Builtin::BI__annotation: {
4262     // Re-encode each wide string to UTF8 and make an MDString.
4263     SmallVector<Metadata *, 1> Strings;
4264     for (const Expr *Arg : E->arguments()) {
4265       const auto *Str = cast<StringLiteral>(Arg->IgnoreParenCasts());
4266       assert(Str->getCharByteWidth() == 2);
4267       StringRef WideBytes = Str->getBytes();
4268       std::string StrUtf8;
4269       if (!convertUTF16ToUTF8String(
4270               makeArrayRef(WideBytes.data(), WideBytes.size()), StrUtf8)) {
4271         CGM.ErrorUnsupported(E, "non-UTF16 __annotation argument");
4272         continue;
4273       }
4274       Strings.push_back(llvm::MDString::get(getLLVMContext(), StrUtf8));
4275     }
4276 
4277     // Build and MDTuple of MDStrings and emit the intrinsic call.
4278     llvm::Function *F =
4279         CGM.getIntrinsic(llvm::Intrinsic::codeview_annotation, {});
4280     MDTuple *StrTuple = MDTuple::get(getLLVMContext(), Strings);
4281     Builder.CreateCall(F, MetadataAsValue::get(getLLVMContext(), StrTuple));
4282     return RValue::getIgnored();
4283   }
4284   case Builtin::BI__builtin_annotation: {
4285     llvm::Value *AnnVal = EmitScalarExpr(E->getArg(0));
4286     llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::annotation,
4287                                       AnnVal->getType());
4288 
4289     // Get the annotation string, go through casts. Sema requires this to be a
4290     // non-wide string literal, potentially casted, so the cast<> is safe.
4291     const Expr *AnnotationStrExpr = E->getArg(1)->IgnoreParenCasts();
4292     StringRef Str = cast<StringLiteral>(AnnotationStrExpr)->getString();
4293     return RValue::get(
4294         EmitAnnotationCall(F, AnnVal, Str, E->getExprLoc(), nullptr));
4295   }
4296   case Builtin::BI__builtin_addcb:
4297   case Builtin::BI__builtin_addcs:
4298   case Builtin::BI__builtin_addc:
4299   case Builtin::BI__builtin_addcl:
4300   case Builtin::BI__builtin_addcll:
4301   case Builtin::BI__builtin_subcb:
4302   case Builtin::BI__builtin_subcs:
4303   case Builtin::BI__builtin_subc:
4304   case Builtin::BI__builtin_subcl:
4305   case Builtin::BI__builtin_subcll: {
4306 
4307     // We translate all of these builtins from expressions of the form:
4308     //   int x = ..., y = ..., carryin = ..., carryout, result;
4309     //   result = __builtin_addc(x, y, carryin, &carryout);
4310     //
4311     // to LLVM IR of the form:
4312     //
4313     //   %tmp1 = call {i32, i1} @llvm.uadd.with.overflow.i32(i32 %x, i32 %y)
4314     //   %tmpsum1 = extractvalue {i32, i1} %tmp1, 0
4315     //   %carry1 = extractvalue {i32, i1} %tmp1, 1
4316     //   %tmp2 = call {i32, i1} @llvm.uadd.with.overflow.i32(i32 %tmpsum1,
4317     //                                                       i32 %carryin)
4318     //   %result = extractvalue {i32, i1} %tmp2, 0
4319     //   %carry2 = extractvalue {i32, i1} %tmp2, 1
4320     //   %tmp3 = or i1 %carry1, %carry2
4321     //   %tmp4 = zext i1 %tmp3 to i32
4322     //   store i32 %tmp4, i32* %carryout
4323 
4324     // Scalarize our inputs.
4325     llvm::Value *X = EmitScalarExpr(E->getArg(0));
4326     llvm::Value *Y = EmitScalarExpr(E->getArg(1));
4327     llvm::Value *Carryin = EmitScalarExpr(E->getArg(2));
4328     Address CarryOutPtr = EmitPointerWithAlignment(E->getArg(3));
4329 
4330     // Decide if we are lowering to a uadd.with.overflow or usub.with.overflow.
4331     llvm::Intrinsic::ID IntrinsicId;
4332     switch (BuiltinID) {
4333     default: llvm_unreachable("Unknown multiprecision builtin id.");
4334     case Builtin::BI__builtin_addcb:
4335     case Builtin::BI__builtin_addcs:
4336     case Builtin::BI__builtin_addc:
4337     case Builtin::BI__builtin_addcl:
4338     case Builtin::BI__builtin_addcll:
4339       IntrinsicId = llvm::Intrinsic::uadd_with_overflow;
4340       break;
4341     case Builtin::BI__builtin_subcb:
4342     case Builtin::BI__builtin_subcs:
4343     case Builtin::BI__builtin_subc:
4344     case Builtin::BI__builtin_subcl:
4345     case Builtin::BI__builtin_subcll:
4346       IntrinsicId = llvm::Intrinsic::usub_with_overflow;
4347       break;
4348     }
4349 
4350     // Construct our resulting LLVM IR expression.
4351     llvm::Value *Carry1;
4352     llvm::Value *Sum1 = EmitOverflowIntrinsic(*this, IntrinsicId,
4353                                               X, Y, Carry1);
4354     llvm::Value *Carry2;
4355     llvm::Value *Sum2 = EmitOverflowIntrinsic(*this, IntrinsicId,
4356                                               Sum1, Carryin, Carry2);
4357     llvm::Value *CarryOut = Builder.CreateZExt(Builder.CreateOr(Carry1, Carry2),
4358                                                X->getType());
4359     Builder.CreateStore(CarryOut, CarryOutPtr);
4360     return RValue::get(Sum2);
4361   }
4362 
4363   case Builtin::BI__builtin_add_overflow:
4364   case Builtin::BI__builtin_sub_overflow:
4365   case Builtin::BI__builtin_mul_overflow: {
4366     const clang::Expr *LeftArg = E->getArg(0);
4367     const clang::Expr *RightArg = E->getArg(1);
4368     const clang::Expr *ResultArg = E->getArg(2);
4369 
4370     clang::QualType ResultQTy =
4371         ResultArg->getType()->castAs<PointerType>()->getPointeeType();
4372 
4373     WidthAndSignedness LeftInfo =
4374         getIntegerWidthAndSignedness(CGM.getContext(), LeftArg->getType());
4375     WidthAndSignedness RightInfo =
4376         getIntegerWidthAndSignedness(CGM.getContext(), RightArg->getType());
4377     WidthAndSignedness ResultInfo =
4378         getIntegerWidthAndSignedness(CGM.getContext(), ResultQTy);
4379 
4380     // Handle mixed-sign multiplication as a special case, because adding
4381     // runtime or backend support for our generic irgen would be too expensive.
4382     if (isSpecialMixedSignMultiply(BuiltinID, LeftInfo, RightInfo, ResultInfo))
4383       return EmitCheckedMixedSignMultiply(*this, LeftArg, LeftInfo, RightArg,
4384                                           RightInfo, ResultArg, ResultQTy,
4385                                           ResultInfo);
4386 
4387     if (isSpecialUnsignedMultiplySignedResult(BuiltinID, LeftInfo, RightInfo,
4388                                               ResultInfo))
4389       return EmitCheckedUnsignedMultiplySignedResult(
4390           *this, LeftArg, LeftInfo, RightArg, RightInfo, ResultArg, ResultQTy,
4391           ResultInfo);
4392 
4393     WidthAndSignedness EncompassingInfo =
4394         EncompassingIntegerType({LeftInfo, RightInfo, ResultInfo});
4395 
4396     llvm::Type *EncompassingLLVMTy =
4397         llvm::IntegerType::get(CGM.getLLVMContext(), EncompassingInfo.Width);
4398 
4399     llvm::Type *ResultLLVMTy = CGM.getTypes().ConvertType(ResultQTy);
4400 
4401     llvm::Intrinsic::ID IntrinsicId;
4402     switch (BuiltinID) {
4403     default:
4404       llvm_unreachable("Unknown overflow builtin id.");
4405     case Builtin::BI__builtin_add_overflow:
4406       IntrinsicId = EncompassingInfo.Signed
4407                         ? llvm::Intrinsic::sadd_with_overflow
4408                         : llvm::Intrinsic::uadd_with_overflow;
4409       break;
4410     case Builtin::BI__builtin_sub_overflow:
4411       IntrinsicId = EncompassingInfo.Signed
4412                         ? llvm::Intrinsic::ssub_with_overflow
4413                         : llvm::Intrinsic::usub_with_overflow;
4414       break;
4415     case Builtin::BI__builtin_mul_overflow:
4416       IntrinsicId = EncompassingInfo.Signed
4417                         ? llvm::Intrinsic::smul_with_overflow
4418                         : llvm::Intrinsic::umul_with_overflow;
4419       break;
4420     }
4421 
4422     llvm::Value *Left = EmitScalarExpr(LeftArg);
4423     llvm::Value *Right = EmitScalarExpr(RightArg);
4424     Address ResultPtr = EmitPointerWithAlignment(ResultArg);
4425 
4426     // Extend each operand to the encompassing type.
4427     Left = Builder.CreateIntCast(Left, EncompassingLLVMTy, LeftInfo.Signed);
4428     Right = Builder.CreateIntCast(Right, EncompassingLLVMTy, RightInfo.Signed);
4429 
4430     // Perform the operation on the extended values.
4431     llvm::Value *Overflow, *Result;
4432     Result = EmitOverflowIntrinsic(*this, IntrinsicId, Left, Right, Overflow);
4433 
4434     if (EncompassingInfo.Width > ResultInfo.Width) {
4435       // The encompassing type is wider than the result type, so we need to
4436       // truncate it.
4437       llvm::Value *ResultTrunc = Builder.CreateTrunc(Result, ResultLLVMTy);
4438 
4439       // To see if the truncation caused an overflow, we will extend
4440       // the result and then compare it to the original result.
4441       llvm::Value *ResultTruncExt = Builder.CreateIntCast(
4442           ResultTrunc, EncompassingLLVMTy, ResultInfo.Signed);
4443       llvm::Value *TruncationOverflow =
4444           Builder.CreateICmpNE(Result, ResultTruncExt);
4445 
4446       Overflow = Builder.CreateOr(Overflow, TruncationOverflow);
4447       Result = ResultTrunc;
4448     }
4449 
4450     // Finally, store the result using the pointer.
4451     bool isVolatile =
4452       ResultArg->getType()->getPointeeType().isVolatileQualified();
4453     Builder.CreateStore(EmitToMemory(Result, ResultQTy), ResultPtr, isVolatile);
4454 
4455     return RValue::get(Overflow);
4456   }
4457 
4458   case Builtin::BI__builtin_uadd_overflow:
4459   case Builtin::BI__builtin_uaddl_overflow:
4460   case Builtin::BI__builtin_uaddll_overflow:
4461   case Builtin::BI__builtin_usub_overflow:
4462   case Builtin::BI__builtin_usubl_overflow:
4463   case Builtin::BI__builtin_usubll_overflow:
4464   case Builtin::BI__builtin_umul_overflow:
4465   case Builtin::BI__builtin_umull_overflow:
4466   case Builtin::BI__builtin_umulll_overflow:
4467   case Builtin::BI__builtin_sadd_overflow:
4468   case Builtin::BI__builtin_saddl_overflow:
4469   case Builtin::BI__builtin_saddll_overflow:
4470   case Builtin::BI__builtin_ssub_overflow:
4471   case Builtin::BI__builtin_ssubl_overflow:
4472   case Builtin::BI__builtin_ssubll_overflow:
4473   case Builtin::BI__builtin_smul_overflow:
4474   case Builtin::BI__builtin_smull_overflow:
4475   case Builtin::BI__builtin_smulll_overflow: {
4476 
4477     // We translate all of these builtins directly to the relevant llvm IR node.
4478 
4479     // Scalarize our inputs.
4480     llvm::Value *X = EmitScalarExpr(E->getArg(0));
4481     llvm::Value *Y = EmitScalarExpr(E->getArg(1));
4482     Address SumOutPtr = EmitPointerWithAlignment(E->getArg(2));
4483 
4484     // Decide which of the overflow intrinsics we are lowering to:
4485     llvm::Intrinsic::ID IntrinsicId;
4486     switch (BuiltinID) {
4487     default: llvm_unreachable("Unknown overflow builtin id.");
4488     case Builtin::BI__builtin_uadd_overflow:
4489     case Builtin::BI__builtin_uaddl_overflow:
4490     case Builtin::BI__builtin_uaddll_overflow:
4491       IntrinsicId = llvm::Intrinsic::uadd_with_overflow;
4492       break;
4493     case Builtin::BI__builtin_usub_overflow:
4494     case Builtin::BI__builtin_usubl_overflow:
4495     case Builtin::BI__builtin_usubll_overflow:
4496       IntrinsicId = llvm::Intrinsic::usub_with_overflow;
4497       break;
4498     case Builtin::BI__builtin_umul_overflow:
4499     case Builtin::BI__builtin_umull_overflow:
4500     case Builtin::BI__builtin_umulll_overflow:
4501       IntrinsicId = llvm::Intrinsic::umul_with_overflow;
4502       break;
4503     case Builtin::BI__builtin_sadd_overflow:
4504     case Builtin::BI__builtin_saddl_overflow:
4505     case Builtin::BI__builtin_saddll_overflow:
4506       IntrinsicId = llvm::Intrinsic::sadd_with_overflow;
4507       break;
4508     case Builtin::BI__builtin_ssub_overflow:
4509     case Builtin::BI__builtin_ssubl_overflow:
4510     case Builtin::BI__builtin_ssubll_overflow:
4511       IntrinsicId = llvm::Intrinsic::ssub_with_overflow;
4512       break;
4513     case Builtin::BI__builtin_smul_overflow:
4514     case Builtin::BI__builtin_smull_overflow:
4515     case Builtin::BI__builtin_smulll_overflow:
4516       IntrinsicId = llvm::Intrinsic::smul_with_overflow;
4517       break;
4518     }
4519 
4520 
4521     llvm::Value *Carry;
4522     llvm::Value *Sum = EmitOverflowIntrinsic(*this, IntrinsicId, X, Y, Carry);
4523     Builder.CreateStore(Sum, SumOutPtr);
4524 
4525     return RValue::get(Carry);
4526   }
4527   case Builtin::BI__builtin_addressof:
4528     return RValue::get(EmitLValue(E->getArg(0)).getPointer(*this));
4529   case Builtin::BI__builtin_function_start:
4530     return RValue::get(CGM.GetFunctionStart(
4531         E->getArg(0)->getAsBuiltinConstantDeclRef(CGM.getContext())));
4532   case Builtin::BI__builtin_operator_new:
4533     return EmitBuiltinNewDeleteCall(
4534         E->getCallee()->getType()->castAs<FunctionProtoType>(), E, false);
4535   case Builtin::BI__builtin_operator_delete:
4536     return EmitBuiltinNewDeleteCall(
4537         E->getCallee()->getType()->castAs<FunctionProtoType>(), E, true);
4538 
4539   case Builtin::BI__builtin_is_aligned:
4540     return EmitBuiltinIsAligned(E);
4541   case Builtin::BI__builtin_align_up:
4542     return EmitBuiltinAlignTo(E, true);
4543   case Builtin::BI__builtin_align_down:
4544     return EmitBuiltinAlignTo(E, false);
4545 
4546   case Builtin::BI__noop:
4547     // __noop always evaluates to an integer literal zero.
4548     return RValue::get(ConstantInt::get(IntTy, 0));
4549   case Builtin::BI__builtin_call_with_static_chain: {
4550     const CallExpr *Call = cast<CallExpr>(E->getArg(0));
4551     const Expr *Chain = E->getArg(1);
4552     return EmitCall(Call->getCallee()->getType(),
4553                     EmitCallee(Call->getCallee()), Call, ReturnValue,
4554                     EmitScalarExpr(Chain));
4555   }
4556   case Builtin::BI_InterlockedExchange8:
4557   case Builtin::BI_InterlockedExchange16:
4558   case Builtin::BI_InterlockedExchange:
4559   case Builtin::BI_InterlockedExchangePointer:
4560     return RValue::get(
4561         EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedExchange, E));
4562   case Builtin::BI_InterlockedCompareExchangePointer:
4563   case Builtin::BI_InterlockedCompareExchangePointer_nf: {
4564     llvm::Type *RTy;
4565     llvm::IntegerType *IntType =
4566       IntegerType::get(getLLVMContext(),
4567                        getContext().getTypeSize(E->getType()));
4568     llvm::Type *IntPtrType = IntType->getPointerTo();
4569 
4570     llvm::Value *Destination =
4571       Builder.CreateBitCast(EmitScalarExpr(E->getArg(0)), IntPtrType);
4572 
4573     llvm::Value *Exchange = EmitScalarExpr(E->getArg(1));
4574     RTy = Exchange->getType();
4575     Exchange = Builder.CreatePtrToInt(Exchange, IntType);
4576 
4577     llvm::Value *Comparand =
4578       Builder.CreatePtrToInt(EmitScalarExpr(E->getArg(2)), IntType);
4579 
4580     auto Ordering =
4581       BuiltinID == Builtin::BI_InterlockedCompareExchangePointer_nf ?
4582       AtomicOrdering::Monotonic : AtomicOrdering::SequentiallyConsistent;
4583 
4584     auto Result = Builder.CreateAtomicCmpXchg(Destination, Comparand, Exchange,
4585                                               Ordering, Ordering);
4586     Result->setVolatile(true);
4587 
4588     return RValue::get(Builder.CreateIntToPtr(Builder.CreateExtractValue(Result,
4589                                                                          0),
4590                                               RTy));
4591   }
4592   case Builtin::BI_InterlockedCompareExchange8:
4593   case Builtin::BI_InterlockedCompareExchange16:
4594   case Builtin::BI_InterlockedCompareExchange:
4595   case Builtin::BI_InterlockedCompareExchange64:
4596     return RValue::get(EmitAtomicCmpXchgForMSIntrin(*this, E));
4597   case Builtin::BI_InterlockedIncrement16:
4598   case Builtin::BI_InterlockedIncrement:
4599     return RValue::get(
4600         EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedIncrement, E));
4601   case Builtin::BI_InterlockedDecrement16:
4602   case Builtin::BI_InterlockedDecrement:
4603     return RValue::get(
4604         EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedDecrement, E));
4605   case Builtin::BI_InterlockedAnd8:
4606   case Builtin::BI_InterlockedAnd16:
4607   case Builtin::BI_InterlockedAnd:
4608     return RValue::get(EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedAnd, E));
4609   case Builtin::BI_InterlockedExchangeAdd8:
4610   case Builtin::BI_InterlockedExchangeAdd16:
4611   case Builtin::BI_InterlockedExchangeAdd:
4612     return RValue::get(
4613         EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedExchangeAdd, E));
4614   case Builtin::BI_InterlockedExchangeSub8:
4615   case Builtin::BI_InterlockedExchangeSub16:
4616   case Builtin::BI_InterlockedExchangeSub:
4617     return RValue::get(
4618         EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedExchangeSub, E));
4619   case Builtin::BI_InterlockedOr8:
4620   case Builtin::BI_InterlockedOr16:
4621   case Builtin::BI_InterlockedOr:
4622     return RValue::get(EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedOr, E));
4623   case Builtin::BI_InterlockedXor8:
4624   case Builtin::BI_InterlockedXor16:
4625   case Builtin::BI_InterlockedXor:
4626     return RValue::get(EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedXor, E));
4627 
4628   case Builtin::BI_bittest64:
4629   case Builtin::BI_bittest:
4630   case Builtin::BI_bittestandcomplement64:
4631   case Builtin::BI_bittestandcomplement:
4632   case Builtin::BI_bittestandreset64:
4633   case Builtin::BI_bittestandreset:
4634   case Builtin::BI_bittestandset64:
4635   case Builtin::BI_bittestandset:
4636   case Builtin::BI_interlockedbittestandreset:
4637   case Builtin::BI_interlockedbittestandreset64:
4638   case Builtin::BI_interlockedbittestandset64:
4639   case Builtin::BI_interlockedbittestandset:
4640   case Builtin::BI_interlockedbittestandset_acq:
4641   case Builtin::BI_interlockedbittestandset_rel:
4642   case Builtin::BI_interlockedbittestandset_nf:
4643   case Builtin::BI_interlockedbittestandreset_acq:
4644   case Builtin::BI_interlockedbittestandreset_rel:
4645   case Builtin::BI_interlockedbittestandreset_nf:
4646     return RValue::get(EmitBitTestIntrinsic(*this, BuiltinID, E));
4647 
4648     // These builtins exist to emit regular volatile loads and stores not
4649     // affected by the -fms-volatile setting.
4650   case Builtin::BI__iso_volatile_load8:
4651   case Builtin::BI__iso_volatile_load16:
4652   case Builtin::BI__iso_volatile_load32:
4653   case Builtin::BI__iso_volatile_load64:
4654     return RValue::get(EmitISOVolatileLoad(*this, E));
4655   case Builtin::BI__iso_volatile_store8:
4656   case Builtin::BI__iso_volatile_store16:
4657   case Builtin::BI__iso_volatile_store32:
4658   case Builtin::BI__iso_volatile_store64:
4659     return RValue::get(EmitISOVolatileStore(*this, E));
4660 
4661   case Builtin::BI__exception_code:
4662   case Builtin::BI_exception_code:
4663     return RValue::get(EmitSEHExceptionCode());
4664   case Builtin::BI__exception_info:
4665   case Builtin::BI_exception_info:
4666     return RValue::get(EmitSEHExceptionInfo());
4667   case Builtin::BI__abnormal_termination:
4668   case Builtin::BI_abnormal_termination:
4669     return RValue::get(EmitSEHAbnormalTermination());
4670   case Builtin::BI_setjmpex:
4671     if (getTarget().getTriple().isOSMSVCRT() && E->getNumArgs() == 1 &&
4672         E->getArg(0)->getType()->isPointerType())
4673       return EmitMSVCRTSetJmp(*this, MSVCSetJmpKind::_setjmpex, E);
4674     break;
4675   case Builtin::BI_setjmp:
4676     if (getTarget().getTriple().isOSMSVCRT() && E->getNumArgs() == 1 &&
4677         E->getArg(0)->getType()->isPointerType()) {
4678       if (getTarget().getTriple().getArch() == llvm::Triple::x86)
4679         return EmitMSVCRTSetJmp(*this, MSVCSetJmpKind::_setjmp3, E);
4680       else if (getTarget().getTriple().getArch() == llvm::Triple::aarch64)
4681         return EmitMSVCRTSetJmp(*this, MSVCSetJmpKind::_setjmpex, E);
4682       return EmitMSVCRTSetJmp(*this, MSVCSetJmpKind::_setjmp, E);
4683     }
4684     break;
4685 
4686   case Builtin::BI__GetExceptionInfo: {
4687     if (llvm::GlobalVariable *GV =
4688             CGM.getCXXABI().getThrowInfo(FD->getParamDecl(0)->getType()))
4689       return RValue::get(llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy));
4690     break;
4691   }
4692 
4693   case Builtin::BI__fastfail:
4694     return RValue::get(EmitMSVCBuiltinExpr(MSVCIntrin::__fastfail, E));
4695 
4696   case Builtin::BI__builtin_coro_size: {
4697     auto & Context = getContext();
4698     auto SizeTy = Context.getSizeType();
4699     auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
4700     Function *F = CGM.getIntrinsic(Intrinsic::coro_size, T);
4701     return RValue::get(Builder.CreateCall(F));
4702   }
4703 
4704   case Builtin::BI__builtin_coro_id:
4705     return EmitCoroutineIntrinsic(E, Intrinsic::coro_id);
4706   case Builtin::BI__builtin_coro_promise:
4707     return EmitCoroutineIntrinsic(E, Intrinsic::coro_promise);
4708   case Builtin::BI__builtin_coro_resume:
4709     return EmitCoroutineIntrinsic(E, Intrinsic::coro_resume);
4710   case Builtin::BI__builtin_coro_frame:
4711     return EmitCoroutineIntrinsic(E, Intrinsic::coro_frame);
4712   case Builtin::BI__builtin_coro_noop:
4713     return EmitCoroutineIntrinsic(E, Intrinsic::coro_noop);
4714   case Builtin::BI__builtin_coro_free:
4715     return EmitCoroutineIntrinsic(E, Intrinsic::coro_free);
4716   case Builtin::BI__builtin_coro_destroy:
4717     return EmitCoroutineIntrinsic(E, Intrinsic::coro_destroy);
4718   case Builtin::BI__builtin_coro_done:
4719     return EmitCoroutineIntrinsic(E, Intrinsic::coro_done);
4720   case Builtin::BI__builtin_coro_alloc:
4721     return EmitCoroutineIntrinsic(E, Intrinsic::coro_alloc);
4722   case Builtin::BI__builtin_coro_begin:
4723     return EmitCoroutineIntrinsic(E, Intrinsic::coro_begin);
4724   case Builtin::BI__builtin_coro_end:
4725     return EmitCoroutineIntrinsic(E, Intrinsic::coro_end);
4726   case Builtin::BI__builtin_coro_suspend:
4727     return EmitCoroutineIntrinsic(E, Intrinsic::coro_suspend);
4728 
4729   // OpenCL v2.0 s6.13.16.2, Built-in pipe read and write functions
4730   case Builtin::BIread_pipe:
4731   case Builtin::BIwrite_pipe: {
4732     Value *Arg0 = EmitScalarExpr(E->getArg(0)),
4733           *Arg1 = EmitScalarExpr(E->getArg(1));
4734     CGOpenCLRuntime OpenCLRT(CGM);
4735     Value *PacketSize = OpenCLRT.getPipeElemSize(E->getArg(0));
4736     Value *PacketAlign = OpenCLRT.getPipeElemAlign(E->getArg(0));
4737 
4738     // Type of the generic packet parameter.
4739     unsigned GenericAS =
4740         getContext().getTargetAddressSpace(LangAS::opencl_generic);
4741     llvm::Type *I8PTy = llvm::PointerType::get(
4742         llvm::Type::getInt8Ty(getLLVMContext()), GenericAS);
4743 
4744     // Testing which overloaded version we should generate the call for.
4745     if (2U == E->getNumArgs()) {
4746       const char *Name = (BuiltinID == Builtin::BIread_pipe) ? "__read_pipe_2"
4747                                                              : "__write_pipe_2";
4748       // Creating a generic function type to be able to call with any builtin or
4749       // user defined type.
4750       llvm::Type *ArgTys[] = {Arg0->getType(), I8PTy, Int32Ty, Int32Ty};
4751       llvm::FunctionType *FTy = llvm::FunctionType::get(
4752           Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
4753       Value *BCast = Builder.CreatePointerCast(Arg1, I8PTy);
4754       return RValue::get(
4755           EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
4756                           {Arg0, BCast, PacketSize, PacketAlign}));
4757     } else {
4758       assert(4 == E->getNumArgs() &&
4759              "Illegal number of parameters to pipe function");
4760       const char *Name = (BuiltinID == Builtin::BIread_pipe) ? "__read_pipe_4"
4761                                                              : "__write_pipe_4";
4762 
4763       llvm::Type *ArgTys[] = {Arg0->getType(), Arg1->getType(), Int32Ty, I8PTy,
4764                               Int32Ty, Int32Ty};
4765       Value *Arg2 = EmitScalarExpr(E->getArg(2)),
4766             *Arg3 = EmitScalarExpr(E->getArg(3));
4767       llvm::FunctionType *FTy = llvm::FunctionType::get(
4768           Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
4769       Value *BCast = Builder.CreatePointerCast(Arg3, I8PTy);
4770       // We know the third argument is an integer type, but we may need to cast
4771       // it to i32.
4772       if (Arg2->getType() != Int32Ty)
4773         Arg2 = Builder.CreateZExtOrTrunc(Arg2, Int32Ty);
4774       return RValue::get(
4775           EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
4776                           {Arg0, Arg1, Arg2, BCast, PacketSize, PacketAlign}));
4777     }
4778   }
4779   // OpenCL v2.0 s6.13.16 ,s9.17.3.5 - Built-in pipe reserve read and write
4780   // functions
4781   case Builtin::BIreserve_read_pipe:
4782   case Builtin::BIreserve_write_pipe:
4783   case Builtin::BIwork_group_reserve_read_pipe:
4784   case Builtin::BIwork_group_reserve_write_pipe:
4785   case Builtin::BIsub_group_reserve_read_pipe:
4786   case Builtin::BIsub_group_reserve_write_pipe: {
4787     // Composing the mangled name for the function.
4788     const char *Name;
4789     if (BuiltinID == Builtin::BIreserve_read_pipe)
4790       Name = "__reserve_read_pipe";
4791     else if (BuiltinID == Builtin::BIreserve_write_pipe)
4792       Name = "__reserve_write_pipe";
4793     else if (BuiltinID == Builtin::BIwork_group_reserve_read_pipe)
4794       Name = "__work_group_reserve_read_pipe";
4795     else if (BuiltinID == Builtin::BIwork_group_reserve_write_pipe)
4796       Name = "__work_group_reserve_write_pipe";
4797     else if (BuiltinID == Builtin::BIsub_group_reserve_read_pipe)
4798       Name = "__sub_group_reserve_read_pipe";
4799     else
4800       Name = "__sub_group_reserve_write_pipe";
4801 
4802     Value *Arg0 = EmitScalarExpr(E->getArg(0)),
4803           *Arg1 = EmitScalarExpr(E->getArg(1));
4804     llvm::Type *ReservedIDTy = ConvertType(getContext().OCLReserveIDTy);
4805     CGOpenCLRuntime OpenCLRT(CGM);
4806     Value *PacketSize = OpenCLRT.getPipeElemSize(E->getArg(0));
4807     Value *PacketAlign = OpenCLRT.getPipeElemAlign(E->getArg(0));
4808 
4809     // Building the generic function prototype.
4810     llvm::Type *ArgTys[] = {Arg0->getType(), Int32Ty, Int32Ty, Int32Ty};
4811     llvm::FunctionType *FTy = llvm::FunctionType::get(
4812         ReservedIDTy, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
4813     // We know the second argument is an integer type, but we may need to cast
4814     // it to i32.
4815     if (Arg1->getType() != Int32Ty)
4816       Arg1 = Builder.CreateZExtOrTrunc(Arg1, Int32Ty);
4817     return RValue::get(EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
4818                                        {Arg0, Arg1, PacketSize, PacketAlign}));
4819   }
4820   // OpenCL v2.0 s6.13.16, s9.17.3.5 - Built-in pipe commit read and write
4821   // functions
4822   case Builtin::BIcommit_read_pipe:
4823   case Builtin::BIcommit_write_pipe:
4824   case Builtin::BIwork_group_commit_read_pipe:
4825   case Builtin::BIwork_group_commit_write_pipe:
4826   case Builtin::BIsub_group_commit_read_pipe:
4827   case Builtin::BIsub_group_commit_write_pipe: {
4828     const char *Name;
4829     if (BuiltinID == Builtin::BIcommit_read_pipe)
4830       Name = "__commit_read_pipe";
4831     else if (BuiltinID == Builtin::BIcommit_write_pipe)
4832       Name = "__commit_write_pipe";
4833     else if (BuiltinID == Builtin::BIwork_group_commit_read_pipe)
4834       Name = "__work_group_commit_read_pipe";
4835     else if (BuiltinID == Builtin::BIwork_group_commit_write_pipe)
4836       Name = "__work_group_commit_write_pipe";
4837     else if (BuiltinID == Builtin::BIsub_group_commit_read_pipe)
4838       Name = "__sub_group_commit_read_pipe";
4839     else
4840       Name = "__sub_group_commit_write_pipe";
4841 
4842     Value *Arg0 = EmitScalarExpr(E->getArg(0)),
4843           *Arg1 = EmitScalarExpr(E->getArg(1));
4844     CGOpenCLRuntime OpenCLRT(CGM);
4845     Value *PacketSize = OpenCLRT.getPipeElemSize(E->getArg(0));
4846     Value *PacketAlign = OpenCLRT.getPipeElemAlign(E->getArg(0));
4847 
4848     // Building the generic function prototype.
4849     llvm::Type *ArgTys[] = {Arg0->getType(), Arg1->getType(), Int32Ty, Int32Ty};
4850     llvm::FunctionType *FTy =
4851         llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
4852                                 llvm::ArrayRef<llvm::Type *>(ArgTys), false);
4853 
4854     return RValue::get(EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
4855                                        {Arg0, Arg1, PacketSize, PacketAlign}));
4856   }
4857   // OpenCL v2.0 s6.13.16.4 Built-in pipe query functions
4858   case Builtin::BIget_pipe_num_packets:
4859   case Builtin::BIget_pipe_max_packets: {
4860     const char *BaseName;
4861     const auto *PipeTy = E->getArg(0)->getType()->castAs<PipeType>();
4862     if (BuiltinID == Builtin::BIget_pipe_num_packets)
4863       BaseName = "__get_pipe_num_packets";
4864     else
4865       BaseName = "__get_pipe_max_packets";
4866     std::string Name = std::string(BaseName) +
4867                        std::string(PipeTy->isReadOnly() ? "_ro" : "_wo");
4868 
4869     // Building the generic function prototype.
4870     Value *Arg0 = EmitScalarExpr(E->getArg(0));
4871     CGOpenCLRuntime OpenCLRT(CGM);
4872     Value *PacketSize = OpenCLRT.getPipeElemSize(E->getArg(0));
4873     Value *PacketAlign = OpenCLRT.getPipeElemAlign(E->getArg(0));
4874     llvm::Type *ArgTys[] = {Arg0->getType(), Int32Ty, Int32Ty};
4875     llvm::FunctionType *FTy = llvm::FunctionType::get(
4876         Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
4877 
4878     return RValue::get(EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
4879                                        {Arg0, PacketSize, PacketAlign}));
4880   }
4881 
4882   // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
4883   case Builtin::BIto_global:
4884   case Builtin::BIto_local:
4885   case Builtin::BIto_private: {
4886     auto Arg0 = EmitScalarExpr(E->getArg(0));
4887     auto NewArgT = llvm::PointerType::get(Int8Ty,
4888       CGM.getContext().getTargetAddressSpace(LangAS::opencl_generic));
4889     auto NewRetT = llvm::PointerType::get(Int8Ty,
4890       CGM.getContext().getTargetAddressSpace(
4891         E->getType()->getPointeeType().getAddressSpace()));
4892     auto FTy = llvm::FunctionType::get(NewRetT, {NewArgT}, false);
4893     llvm::Value *NewArg;
4894     if (Arg0->getType()->getPointerAddressSpace() !=
4895         NewArgT->getPointerAddressSpace())
4896       NewArg = Builder.CreateAddrSpaceCast(Arg0, NewArgT);
4897     else
4898       NewArg = Builder.CreateBitOrPointerCast(Arg0, NewArgT);
4899     auto NewName = std::string("__") + E->getDirectCallee()->getName().str();
4900     auto NewCall =
4901         EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, NewName), {NewArg});
4902     return RValue::get(Builder.CreateBitOrPointerCast(NewCall,
4903       ConvertType(E->getType())));
4904   }
4905 
4906   // OpenCL v2.0, s6.13.17 - Enqueue kernel function.
4907   // It contains four different overload formats specified in Table 6.13.17.1.
4908   case Builtin::BIenqueue_kernel: {
4909     StringRef Name; // Generated function call name
4910     unsigned NumArgs = E->getNumArgs();
4911 
4912     llvm::Type *QueueTy = ConvertType(getContext().OCLQueueTy);
4913     llvm::Type *GenericVoidPtrTy = Builder.getInt8PtrTy(
4914         getContext().getTargetAddressSpace(LangAS::opencl_generic));
4915 
4916     llvm::Value *Queue = EmitScalarExpr(E->getArg(0));
4917     llvm::Value *Flags = EmitScalarExpr(E->getArg(1));
4918     LValue NDRangeL = EmitAggExprToLValue(E->getArg(2));
4919     llvm::Value *Range = NDRangeL.getAddress(*this).getPointer();
4920     llvm::Type *RangeTy = NDRangeL.getAddress(*this).getType();
4921 
4922     if (NumArgs == 4) {
4923       // The most basic form of the call with parameters:
4924       // queue_t, kernel_enqueue_flags_t, ndrange_t, block(void)
4925       Name = "__enqueue_kernel_basic";
4926       llvm::Type *ArgTys[] = {QueueTy, Int32Ty, RangeTy, GenericVoidPtrTy,
4927                               GenericVoidPtrTy};
4928       llvm::FunctionType *FTy = llvm::FunctionType::get(
4929           Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
4930 
4931       auto Info =
4932           CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(3));
4933       llvm::Value *Kernel =
4934           Builder.CreatePointerCast(Info.Kernel, GenericVoidPtrTy);
4935       llvm::Value *Block =
4936           Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
4937 
4938       AttrBuilder B(Builder.getContext());
4939       B.addByValAttr(NDRangeL.getAddress(*this).getElementType());
4940       llvm::AttributeList ByValAttrSet =
4941           llvm::AttributeList::get(CGM.getModule().getContext(), 3U, B);
4942 
4943       auto RTCall =
4944           EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name, ByValAttrSet),
4945                           {Queue, Flags, Range, Kernel, Block});
4946       RTCall->setAttributes(ByValAttrSet);
4947       return RValue::get(RTCall);
4948     }
4949     assert(NumArgs >= 5 && "Invalid enqueue_kernel signature");
4950 
4951     // Create a temporary array to hold the sizes of local pointer arguments
4952     // for the block. \p First is the position of the first size argument.
4953     auto CreateArrayForSizeVar = [=](unsigned First)
4954         -> std::tuple<llvm::Value *, llvm::Value *, llvm::Value *> {
4955       llvm::APInt ArraySize(32, NumArgs - First);
4956       QualType SizeArrayTy = getContext().getConstantArrayType(
4957           getContext().getSizeType(), ArraySize, nullptr, ArrayType::Normal,
4958           /*IndexTypeQuals=*/0);
4959       auto Tmp = CreateMemTemp(SizeArrayTy, "block_sizes");
4960       llvm::Value *TmpPtr = Tmp.getPointer();
4961       llvm::Value *TmpSize = EmitLifetimeStart(
4962           CGM.getDataLayout().getTypeAllocSize(Tmp.getElementType()), TmpPtr);
4963       llvm::Value *ElemPtr;
4964       // Each of the following arguments specifies the size of the corresponding
4965       // argument passed to the enqueued block.
4966       auto *Zero = llvm::ConstantInt::get(IntTy, 0);
4967       for (unsigned I = First; I < NumArgs; ++I) {
4968         auto *Index = llvm::ConstantInt::get(IntTy, I - First);
4969         auto *GEP = Builder.CreateGEP(Tmp.getElementType(), TmpPtr,
4970                                       {Zero, Index});
4971         if (I == First)
4972           ElemPtr = GEP;
4973         auto *V =
4974             Builder.CreateZExtOrTrunc(EmitScalarExpr(E->getArg(I)), SizeTy);
4975         Builder.CreateAlignedStore(
4976             V, GEP, CGM.getDataLayout().getPrefTypeAlign(SizeTy));
4977       }
4978       return std::tie(ElemPtr, TmpSize, TmpPtr);
4979     };
4980 
4981     // Could have events and/or varargs.
4982     if (E->getArg(3)->getType()->isBlockPointerType()) {
4983       // No events passed, but has variadic arguments.
4984       Name = "__enqueue_kernel_varargs";
4985       auto Info =
4986           CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(3));
4987       llvm::Value *Kernel =
4988           Builder.CreatePointerCast(Info.Kernel, GenericVoidPtrTy);
4989       auto *Block = Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
4990       llvm::Value *ElemPtr, *TmpSize, *TmpPtr;
4991       std::tie(ElemPtr, TmpSize, TmpPtr) = CreateArrayForSizeVar(4);
4992 
4993       // Create a vector of the arguments, as well as a constant value to
4994       // express to the runtime the number of variadic arguments.
4995       llvm::Value *const Args[] = {Queue,  Flags,
4996                                    Range,  Kernel,
4997                                    Block,  ConstantInt::get(IntTy, NumArgs - 4),
4998                                    ElemPtr};
4999       llvm::Type *const ArgTys[] = {
5000           QueueTy,          IntTy, RangeTy,           GenericVoidPtrTy,
5001           GenericVoidPtrTy, IntTy, ElemPtr->getType()};
5002 
5003       llvm::FunctionType *FTy = llvm::FunctionType::get(Int32Ty, ArgTys, false);
5004       auto Call = RValue::get(
5005           EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name), Args));
5006       if (TmpSize)
5007         EmitLifetimeEnd(TmpSize, TmpPtr);
5008       return Call;
5009     }
5010     // Any calls now have event arguments passed.
5011     if (NumArgs >= 7) {
5012       llvm::Type *EventTy = ConvertType(getContext().OCLClkEventTy);
5013       llvm::PointerType *EventPtrTy = EventTy->getPointerTo(
5014           CGM.getContext().getTargetAddressSpace(LangAS::opencl_generic));
5015 
5016       llvm::Value *NumEvents =
5017           Builder.CreateZExtOrTrunc(EmitScalarExpr(E->getArg(3)), Int32Ty);
5018 
5019       // Since SemaOpenCLBuiltinEnqueueKernel allows fifth and sixth arguments
5020       // to be a null pointer constant (including `0` literal), we can take it
5021       // into account and emit null pointer directly.
5022       llvm::Value *EventWaitList = nullptr;
5023       if (E->getArg(4)->isNullPointerConstant(
5024               getContext(), Expr::NPC_ValueDependentIsNotNull)) {
5025         EventWaitList = llvm::ConstantPointerNull::get(EventPtrTy);
5026       } else {
5027         EventWaitList = E->getArg(4)->getType()->isArrayType()
5028                         ? EmitArrayToPointerDecay(E->getArg(4)).getPointer()
5029                         : EmitScalarExpr(E->getArg(4));
5030         // Convert to generic address space.
5031         EventWaitList = Builder.CreatePointerCast(EventWaitList, EventPtrTy);
5032       }
5033       llvm::Value *EventRet = nullptr;
5034       if (E->getArg(5)->isNullPointerConstant(
5035               getContext(), Expr::NPC_ValueDependentIsNotNull)) {
5036         EventRet = llvm::ConstantPointerNull::get(EventPtrTy);
5037       } else {
5038         EventRet =
5039             Builder.CreatePointerCast(EmitScalarExpr(E->getArg(5)), EventPtrTy);
5040       }
5041 
5042       auto Info =
5043           CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(6));
5044       llvm::Value *Kernel =
5045           Builder.CreatePointerCast(Info.Kernel, GenericVoidPtrTy);
5046       llvm::Value *Block =
5047           Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
5048 
5049       std::vector<llvm::Type *> ArgTys = {
5050           QueueTy,    Int32Ty,    RangeTy,          Int32Ty,
5051           EventPtrTy, EventPtrTy, GenericVoidPtrTy, GenericVoidPtrTy};
5052 
5053       std::vector<llvm::Value *> Args = {Queue,     Flags,         Range,
5054                                          NumEvents, EventWaitList, EventRet,
5055                                          Kernel,    Block};
5056 
5057       if (NumArgs == 7) {
5058         // Has events but no variadics.
5059         Name = "__enqueue_kernel_basic_events";
5060         llvm::FunctionType *FTy = llvm::FunctionType::get(
5061             Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
5062         return RValue::get(
5063             EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
5064                             llvm::ArrayRef<llvm::Value *>(Args)));
5065       }
5066       // Has event info and variadics
5067       // Pass the number of variadics to the runtime function too.
5068       Args.push_back(ConstantInt::get(Int32Ty, NumArgs - 7));
5069       ArgTys.push_back(Int32Ty);
5070       Name = "__enqueue_kernel_events_varargs";
5071 
5072       llvm::Value *ElemPtr, *TmpSize, *TmpPtr;
5073       std::tie(ElemPtr, TmpSize, TmpPtr) = CreateArrayForSizeVar(7);
5074       Args.push_back(ElemPtr);
5075       ArgTys.push_back(ElemPtr->getType());
5076 
5077       llvm::FunctionType *FTy = llvm::FunctionType::get(
5078           Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
5079       auto Call =
5080           RValue::get(EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
5081                                       llvm::ArrayRef<llvm::Value *>(Args)));
5082       if (TmpSize)
5083         EmitLifetimeEnd(TmpSize, TmpPtr);
5084       return Call;
5085     }
5086     LLVM_FALLTHROUGH;
5087   }
5088   // OpenCL v2.0 s6.13.17.6 - Kernel query functions need bitcast of block
5089   // parameter.
5090   case Builtin::BIget_kernel_work_group_size: {
5091     llvm::Type *GenericVoidPtrTy = Builder.getInt8PtrTy(
5092         getContext().getTargetAddressSpace(LangAS::opencl_generic));
5093     auto Info =
5094         CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(0));
5095     Value *Kernel = Builder.CreatePointerCast(Info.Kernel, GenericVoidPtrTy);
5096     Value *Arg = Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
5097     return RValue::get(EmitRuntimeCall(
5098         CGM.CreateRuntimeFunction(
5099             llvm::FunctionType::get(IntTy, {GenericVoidPtrTy, GenericVoidPtrTy},
5100                                     false),
5101             "__get_kernel_work_group_size_impl"),
5102         {Kernel, Arg}));
5103   }
5104   case Builtin::BIget_kernel_preferred_work_group_size_multiple: {
5105     llvm::Type *GenericVoidPtrTy = Builder.getInt8PtrTy(
5106         getContext().getTargetAddressSpace(LangAS::opencl_generic));
5107     auto Info =
5108         CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(0));
5109     Value *Kernel = Builder.CreatePointerCast(Info.Kernel, GenericVoidPtrTy);
5110     Value *Arg = Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
5111     return RValue::get(EmitRuntimeCall(
5112         CGM.CreateRuntimeFunction(
5113             llvm::FunctionType::get(IntTy, {GenericVoidPtrTy, GenericVoidPtrTy},
5114                                     false),
5115             "__get_kernel_preferred_work_group_size_multiple_impl"),
5116         {Kernel, Arg}));
5117   }
5118   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
5119   case Builtin::BIget_kernel_sub_group_count_for_ndrange: {
5120     llvm::Type *GenericVoidPtrTy = Builder.getInt8PtrTy(
5121         getContext().getTargetAddressSpace(LangAS::opencl_generic));
5122     LValue NDRangeL = EmitAggExprToLValue(E->getArg(0));
5123     llvm::Value *NDRange = NDRangeL.getAddress(*this).getPointer();
5124     auto Info =
5125         CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(1));
5126     Value *Kernel = Builder.CreatePointerCast(Info.Kernel, GenericVoidPtrTy);
5127     Value *Block = Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
5128     const char *Name =
5129         BuiltinID == Builtin::BIget_kernel_max_sub_group_size_for_ndrange
5130             ? "__get_kernel_max_sub_group_size_for_ndrange_impl"
5131             : "__get_kernel_sub_group_count_for_ndrange_impl";
5132     return RValue::get(EmitRuntimeCall(
5133         CGM.CreateRuntimeFunction(
5134             llvm::FunctionType::get(
5135                 IntTy, {NDRange->getType(), GenericVoidPtrTy, GenericVoidPtrTy},
5136                 false),
5137             Name),
5138         {NDRange, Kernel, Block}));
5139   }
5140 
5141   case Builtin::BI__builtin_store_half:
5142   case Builtin::BI__builtin_store_halff: {
5143     Value *Val = EmitScalarExpr(E->getArg(0));
5144     Address Address = EmitPointerWithAlignment(E->getArg(1));
5145     Value *HalfVal = Builder.CreateFPTrunc(Val, Builder.getHalfTy());
5146     return RValue::get(Builder.CreateStore(HalfVal, Address));
5147   }
5148   case Builtin::BI__builtin_load_half: {
5149     Address Address = EmitPointerWithAlignment(E->getArg(0));
5150     Value *HalfVal = Builder.CreateLoad(Address);
5151     return RValue::get(Builder.CreateFPExt(HalfVal, Builder.getDoubleTy()));
5152   }
5153   case Builtin::BI__builtin_load_halff: {
5154     Address Address = EmitPointerWithAlignment(E->getArg(0));
5155     Value *HalfVal = Builder.CreateLoad(Address);
5156     return RValue::get(Builder.CreateFPExt(HalfVal, Builder.getFloatTy()));
5157   }
5158   case Builtin::BIprintf:
5159     if (getTarget().getTriple().isNVPTX() ||
5160         getTarget().getTriple().isAMDGCN()) {
5161       if (getLangOpts().OpenMPIsDevice)
5162         return EmitOpenMPDevicePrintfCallExpr(E);
5163       if (getTarget().getTriple().isNVPTX())
5164         return EmitNVPTXDevicePrintfCallExpr(E);
5165       if (getTarget().getTriple().isAMDGCN() && getLangOpts().HIP)
5166         return EmitAMDGPUDevicePrintfCallExpr(E);
5167     }
5168 
5169     break;
5170   case Builtin::BI__builtin_canonicalize:
5171   case Builtin::BI__builtin_canonicalizef:
5172   case Builtin::BI__builtin_canonicalizef16:
5173   case Builtin::BI__builtin_canonicalizel:
5174     return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::canonicalize));
5175 
5176   case Builtin::BI__builtin_thread_pointer: {
5177     if (!getContext().getTargetInfo().isTLSSupported())
5178       CGM.ErrorUnsupported(E, "__builtin_thread_pointer");
5179     // Fall through - it's already mapped to the intrinsic by GCCBuiltin.
5180     break;
5181   }
5182   case Builtin::BI__builtin_os_log_format:
5183     return emitBuiltinOSLogFormat(*E);
5184 
5185   case Builtin::BI__xray_customevent: {
5186     if (!ShouldXRayInstrumentFunction())
5187       return RValue::getIgnored();
5188 
5189     if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
5190             XRayInstrKind::Custom))
5191       return RValue::getIgnored();
5192 
5193     if (const auto *XRayAttr = CurFuncDecl->getAttr<XRayInstrumentAttr>())
5194       if (XRayAttr->neverXRayInstrument() && !AlwaysEmitXRayCustomEvents())
5195         return RValue::getIgnored();
5196 
5197     Function *F = CGM.getIntrinsic(Intrinsic::xray_customevent);
5198     auto FTy = F->getFunctionType();
5199     auto Arg0 = E->getArg(0);
5200     auto Arg0Val = EmitScalarExpr(Arg0);
5201     auto Arg0Ty = Arg0->getType();
5202     auto PTy0 = FTy->getParamType(0);
5203     if (PTy0 != Arg0Val->getType()) {
5204       if (Arg0Ty->isArrayType())
5205         Arg0Val = EmitArrayToPointerDecay(Arg0).getPointer();
5206       else
5207         Arg0Val = Builder.CreatePointerCast(Arg0Val, PTy0);
5208     }
5209     auto Arg1 = EmitScalarExpr(E->getArg(1));
5210     auto PTy1 = FTy->getParamType(1);
5211     if (PTy1 != Arg1->getType())
5212       Arg1 = Builder.CreateTruncOrBitCast(Arg1, PTy1);
5213     return RValue::get(Builder.CreateCall(F, {Arg0Val, Arg1}));
5214   }
5215 
5216   case Builtin::BI__xray_typedevent: {
5217     // TODO: There should be a way to always emit events even if the current
5218     // function is not instrumented. Losing events in a stream can cripple
5219     // a trace.
5220     if (!ShouldXRayInstrumentFunction())
5221       return RValue::getIgnored();
5222 
5223     if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
5224             XRayInstrKind::Typed))
5225       return RValue::getIgnored();
5226 
5227     if (const auto *XRayAttr = CurFuncDecl->getAttr<XRayInstrumentAttr>())
5228       if (XRayAttr->neverXRayInstrument() && !AlwaysEmitXRayTypedEvents())
5229         return RValue::getIgnored();
5230 
5231     Function *F = CGM.getIntrinsic(Intrinsic::xray_typedevent);
5232     auto FTy = F->getFunctionType();
5233     auto Arg0 = EmitScalarExpr(E->getArg(0));
5234     auto PTy0 = FTy->getParamType(0);
5235     if (PTy0 != Arg0->getType())
5236       Arg0 = Builder.CreateTruncOrBitCast(Arg0, PTy0);
5237     auto Arg1 = E->getArg(1);
5238     auto Arg1Val = EmitScalarExpr(Arg1);
5239     auto Arg1Ty = Arg1->getType();
5240     auto PTy1 = FTy->getParamType(1);
5241     if (PTy1 != Arg1Val->getType()) {
5242       if (Arg1Ty->isArrayType())
5243         Arg1Val = EmitArrayToPointerDecay(Arg1).getPointer();
5244       else
5245         Arg1Val = Builder.CreatePointerCast(Arg1Val, PTy1);
5246     }
5247     auto Arg2 = EmitScalarExpr(E->getArg(2));
5248     auto PTy2 = FTy->getParamType(2);
5249     if (PTy2 != Arg2->getType())
5250       Arg2 = Builder.CreateTruncOrBitCast(Arg2, PTy2);
5251     return RValue::get(Builder.CreateCall(F, {Arg0, Arg1Val, Arg2}));
5252   }
5253 
5254   case Builtin::BI__builtin_ms_va_start:
5255   case Builtin::BI__builtin_ms_va_end:
5256     return RValue::get(
5257         EmitVAStartEnd(EmitMSVAListRef(E->getArg(0)).getPointer(),
5258                        BuiltinID == Builtin::BI__builtin_ms_va_start));
5259 
5260   case Builtin::BI__builtin_ms_va_copy: {
5261     // Lower this manually. We can't reliably determine whether or not any
5262     // given va_copy() is for a Win64 va_list from the calling convention
5263     // alone, because it's legal to do this from a System V ABI function.
5264     // With opaque pointer types, we won't have enough information in LLVM
5265     // IR to determine this from the argument types, either. Best to do it
5266     // now, while we have enough information.
5267     Address DestAddr = EmitMSVAListRef(E->getArg(0));
5268     Address SrcAddr = EmitMSVAListRef(E->getArg(1));
5269 
5270     llvm::Type *BPP = Int8PtrPtrTy;
5271 
5272     DestAddr = Address(Builder.CreateBitCast(DestAddr.getPointer(), BPP, "cp"),
5273                        Int8PtrTy, DestAddr.getAlignment());
5274     SrcAddr = Address(Builder.CreateBitCast(SrcAddr.getPointer(), BPP, "ap"),
5275                       Int8PtrTy, SrcAddr.getAlignment());
5276 
5277     Value *ArgPtr = Builder.CreateLoad(SrcAddr, "ap.val");
5278     return RValue::get(Builder.CreateStore(ArgPtr, DestAddr));
5279   }
5280 
5281   case Builtin::BI__builtin_get_device_side_mangled_name: {
5282     auto Name = CGM.getCUDARuntime().getDeviceSideName(
5283         cast<DeclRefExpr>(E->getArg(0)->IgnoreImpCasts())->getDecl());
5284     auto Str = CGM.GetAddrOfConstantCString(Name, "");
5285     llvm::Constant *Zeros[] = {llvm::ConstantInt::get(SizeTy, 0),
5286                                llvm::ConstantInt::get(SizeTy, 0)};
5287     auto *Ptr = llvm::ConstantExpr::getGetElementPtr(Str.getElementType(),
5288                                                      Str.getPointer(), Zeros);
5289     return RValue::get(Ptr);
5290   }
5291   }
5292 
5293   // If this is an alias for a lib function (e.g. __builtin_sin), emit
5294   // the call using the normal call path, but using the unmangled
5295   // version of the function name.
5296   if (getContext().BuiltinInfo.isLibFunction(BuiltinID))
5297     return emitLibraryCall(*this, FD, E,
5298                            CGM.getBuiltinLibFunction(FD, BuiltinID));
5299 
5300   // If this is a predefined lib function (e.g. malloc), emit the call
5301   // using exactly the normal call path.
5302   if (getContext().BuiltinInfo.isPredefinedLibFunction(BuiltinID))
5303     return emitLibraryCall(*this, FD, E,
5304                       cast<llvm::Constant>(EmitScalarExpr(E->getCallee())));
5305 
5306   // Check that a call to a target specific builtin has the correct target
5307   // features.
5308   // This is down here to avoid non-target specific builtins, however, if
5309   // generic builtins start to require generic target features then we
5310   // can move this up to the beginning of the function.
5311   checkTargetFeatures(E, FD);
5312 
5313   if (unsigned VectorWidth = getContext().BuiltinInfo.getRequiredVectorWidth(BuiltinID))
5314     LargestVectorWidth = std::max(LargestVectorWidth, VectorWidth);
5315 
5316   // See if we have a target specific intrinsic.
5317   const char *Name = getContext().BuiltinInfo.getName(BuiltinID);
5318   Intrinsic::ID IntrinsicID = Intrinsic::not_intrinsic;
5319   StringRef Prefix =
5320       llvm::Triple::getArchTypePrefix(getTarget().getTriple().getArch());
5321   if (!Prefix.empty()) {
5322     IntrinsicID = Intrinsic::getIntrinsicForGCCBuiltin(Prefix.data(), Name);
5323     // NOTE we don't need to perform a compatibility flag check here since the
5324     // intrinsics are declared in Builtins*.def via LANGBUILTIN which filter the
5325     // MS builtins via ALL_MS_LANGUAGES and are filtered earlier.
5326     if (IntrinsicID == Intrinsic::not_intrinsic)
5327       IntrinsicID = Intrinsic::getIntrinsicForMSBuiltin(Prefix.data(), Name);
5328   }
5329 
5330   if (IntrinsicID != Intrinsic::not_intrinsic) {
5331     SmallVector<Value*, 16> Args;
5332 
5333     // Find out if any arguments are required to be integer constant
5334     // expressions.
5335     unsigned ICEArguments = 0;
5336     ASTContext::GetBuiltinTypeError Error;
5337     getContext().GetBuiltinType(BuiltinID, Error, &ICEArguments);
5338     assert(Error == ASTContext::GE_None && "Should not codegen an error");
5339 
5340     Function *F = CGM.getIntrinsic(IntrinsicID);
5341     llvm::FunctionType *FTy = F->getFunctionType();
5342 
5343     for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
5344       Value *ArgValue;
5345       // If this is a normal argument, just emit it as a scalar.
5346       if ((ICEArguments & (1 << i)) == 0) {
5347         ArgValue = EmitScalarExpr(E->getArg(i));
5348       } else {
5349         // If this is required to be a constant, constant fold it so that we
5350         // know that the generated intrinsic gets a ConstantInt.
5351         ArgValue = llvm::ConstantInt::get(
5352             getLLVMContext(),
5353             *E->getArg(i)->getIntegerConstantExpr(getContext()));
5354       }
5355 
5356       // If the intrinsic arg type is different from the builtin arg type
5357       // we need to do a bit cast.
5358       llvm::Type *PTy = FTy->getParamType(i);
5359       if (PTy != ArgValue->getType()) {
5360         // XXX - vector of pointers?
5361         if (auto *PtrTy = dyn_cast<llvm::PointerType>(PTy)) {
5362           if (PtrTy->getAddressSpace() !=
5363               ArgValue->getType()->getPointerAddressSpace()) {
5364             ArgValue = Builder.CreateAddrSpaceCast(
5365               ArgValue,
5366               ArgValue->getType()->getPointerTo(PtrTy->getAddressSpace()));
5367           }
5368         }
5369 
5370         assert(PTy->canLosslesslyBitCastTo(FTy->getParamType(i)) &&
5371                "Must be able to losslessly bit cast to param");
5372         ArgValue = Builder.CreateBitCast(ArgValue, PTy);
5373       }
5374 
5375       Args.push_back(ArgValue);
5376     }
5377 
5378     Value *V = Builder.CreateCall(F, Args);
5379     QualType BuiltinRetType = E->getType();
5380 
5381     llvm::Type *RetTy = VoidTy;
5382     if (!BuiltinRetType->isVoidType())
5383       RetTy = ConvertType(BuiltinRetType);
5384 
5385     if (RetTy != V->getType()) {
5386       // XXX - vector of pointers?
5387       if (auto *PtrTy = dyn_cast<llvm::PointerType>(RetTy)) {
5388         if (PtrTy->getAddressSpace() != V->getType()->getPointerAddressSpace()) {
5389           V = Builder.CreateAddrSpaceCast(
5390             V, V->getType()->getPointerTo(PtrTy->getAddressSpace()));
5391         }
5392       }
5393 
5394       assert(V->getType()->canLosslesslyBitCastTo(RetTy) &&
5395              "Must be able to losslessly bit cast result type");
5396       V = Builder.CreateBitCast(V, RetTy);
5397     }
5398 
5399     return RValue::get(V);
5400   }
5401 
5402   // Some target-specific builtins can have aggregate return values, e.g.
5403   // __builtin_arm_mve_vld2q_u32. So if the result is an aggregate, force
5404   // ReturnValue to be non-null, so that the target-specific emission code can
5405   // always just emit into it.
5406   TypeEvaluationKind EvalKind = getEvaluationKind(E->getType());
5407   if (EvalKind == TEK_Aggregate && ReturnValue.isNull()) {
5408     Address DestPtr = CreateMemTemp(E->getType(), "agg.tmp");
5409     ReturnValue = ReturnValueSlot(DestPtr, false);
5410   }
5411 
5412   // Now see if we can emit a target-specific builtin.
5413   if (Value *V = EmitTargetBuiltinExpr(BuiltinID, E, ReturnValue)) {
5414     switch (EvalKind) {
5415     case TEK_Scalar:
5416       return RValue::get(V);
5417     case TEK_Aggregate:
5418       return RValue::getAggregate(ReturnValue.getValue(),
5419                                   ReturnValue.isVolatile());
5420     case TEK_Complex:
5421       llvm_unreachable("No current target builtin returns complex");
5422     }
5423     llvm_unreachable("Bad evaluation kind in EmitBuiltinExpr");
5424   }
5425 
5426   ErrorUnsupported(E, "builtin function");
5427 
5428   // Unknown builtin, for now just dump it out and return undef.
5429   return GetUndefRValue(E->getType());
5430 }
5431 
5432 static Value *EmitTargetArchBuiltinExpr(CodeGenFunction *CGF,
5433                                         unsigned BuiltinID, const CallExpr *E,
5434                                         ReturnValueSlot ReturnValue,
5435                                         llvm::Triple::ArchType Arch) {
5436   switch (Arch) {
5437   case llvm::Triple::arm:
5438   case llvm::Triple::armeb:
5439   case llvm::Triple::thumb:
5440   case llvm::Triple::thumbeb:
5441     return CGF->EmitARMBuiltinExpr(BuiltinID, E, ReturnValue, Arch);
5442   case llvm::Triple::aarch64:
5443   case llvm::Triple::aarch64_32:
5444   case llvm::Triple::aarch64_be:
5445     return CGF->EmitAArch64BuiltinExpr(BuiltinID, E, Arch);
5446   case llvm::Triple::bpfeb:
5447   case llvm::Triple::bpfel:
5448     return CGF->EmitBPFBuiltinExpr(BuiltinID, E);
5449   case llvm::Triple::x86:
5450   case llvm::Triple::x86_64:
5451     return CGF->EmitX86BuiltinExpr(BuiltinID, E);
5452   case llvm::Triple::ppc:
5453   case llvm::Triple::ppcle:
5454   case llvm::Triple::ppc64:
5455   case llvm::Triple::ppc64le:
5456     return CGF->EmitPPCBuiltinExpr(BuiltinID, E);
5457   case llvm::Triple::r600:
5458   case llvm::Triple::amdgcn:
5459     return CGF->EmitAMDGPUBuiltinExpr(BuiltinID, E);
5460   case llvm::Triple::systemz:
5461     return CGF->EmitSystemZBuiltinExpr(BuiltinID, E);
5462   case llvm::Triple::nvptx:
5463   case llvm::Triple::nvptx64:
5464     return CGF->EmitNVPTXBuiltinExpr(BuiltinID, E);
5465   case llvm::Triple::wasm32:
5466   case llvm::Triple::wasm64:
5467     return CGF->EmitWebAssemblyBuiltinExpr(BuiltinID, E);
5468   case llvm::Triple::hexagon:
5469     return CGF->EmitHexagonBuiltinExpr(BuiltinID, E);
5470   case llvm::Triple::riscv32:
5471   case llvm::Triple::riscv64:
5472     return CGF->EmitRISCVBuiltinExpr(BuiltinID, E, ReturnValue);
5473   default:
5474     return nullptr;
5475   }
5476 }
5477 
5478 Value *CodeGenFunction::EmitTargetBuiltinExpr(unsigned BuiltinID,
5479                                               const CallExpr *E,
5480                                               ReturnValueSlot ReturnValue) {
5481   if (getContext().BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
5482     assert(getContext().getAuxTargetInfo() && "Missing aux target info");
5483     return EmitTargetArchBuiltinExpr(
5484         this, getContext().BuiltinInfo.getAuxBuiltinID(BuiltinID), E,
5485         ReturnValue, getContext().getAuxTargetInfo()->getTriple().getArch());
5486   }
5487 
5488   return EmitTargetArchBuiltinExpr(this, BuiltinID, E, ReturnValue,
5489                                    getTarget().getTriple().getArch());
5490 }
5491 
5492 static llvm::FixedVectorType *GetNeonType(CodeGenFunction *CGF,
5493                                           NeonTypeFlags TypeFlags,
5494                                           bool HasLegalHalfType = true,
5495                                           bool V1Ty = false,
5496                                           bool AllowBFloatArgsAndRet = true) {
5497   int IsQuad = TypeFlags.isQuad();
5498   switch (TypeFlags.getEltType()) {
5499   case NeonTypeFlags::Int8:
5500   case NeonTypeFlags::Poly8:
5501     return llvm::FixedVectorType::get(CGF->Int8Ty, V1Ty ? 1 : (8 << IsQuad));
5502   case NeonTypeFlags::Int16:
5503   case NeonTypeFlags::Poly16:
5504     return llvm::FixedVectorType::get(CGF->Int16Ty, V1Ty ? 1 : (4 << IsQuad));
5505   case NeonTypeFlags::BFloat16:
5506     if (AllowBFloatArgsAndRet)
5507       return llvm::FixedVectorType::get(CGF->BFloatTy, V1Ty ? 1 : (4 << IsQuad));
5508     else
5509       return llvm::FixedVectorType::get(CGF->Int16Ty, V1Ty ? 1 : (4 << IsQuad));
5510   case NeonTypeFlags::Float16:
5511     if (HasLegalHalfType)
5512       return llvm::FixedVectorType::get(CGF->HalfTy, V1Ty ? 1 : (4 << IsQuad));
5513     else
5514       return llvm::FixedVectorType::get(CGF->Int16Ty, V1Ty ? 1 : (4 << IsQuad));
5515   case NeonTypeFlags::Int32:
5516     return llvm::FixedVectorType::get(CGF->Int32Ty, V1Ty ? 1 : (2 << IsQuad));
5517   case NeonTypeFlags::Int64:
5518   case NeonTypeFlags::Poly64:
5519     return llvm::FixedVectorType::get(CGF->Int64Ty, V1Ty ? 1 : (1 << IsQuad));
5520   case NeonTypeFlags::Poly128:
5521     // FIXME: i128 and f128 doesn't get fully support in Clang and llvm.
5522     // There is a lot of i128 and f128 API missing.
5523     // so we use v16i8 to represent poly128 and get pattern matched.
5524     return llvm::FixedVectorType::get(CGF->Int8Ty, 16);
5525   case NeonTypeFlags::Float32:
5526     return llvm::FixedVectorType::get(CGF->FloatTy, V1Ty ? 1 : (2 << IsQuad));
5527   case NeonTypeFlags::Float64:
5528     return llvm::FixedVectorType::get(CGF->DoubleTy, V1Ty ? 1 : (1 << IsQuad));
5529   }
5530   llvm_unreachable("Unknown vector element type!");
5531 }
5532 
5533 static llvm::VectorType *GetFloatNeonType(CodeGenFunction *CGF,
5534                                           NeonTypeFlags IntTypeFlags) {
5535   int IsQuad = IntTypeFlags.isQuad();
5536   switch (IntTypeFlags.getEltType()) {
5537   case NeonTypeFlags::Int16:
5538     return llvm::FixedVectorType::get(CGF->HalfTy, (4 << IsQuad));
5539   case NeonTypeFlags::Int32:
5540     return llvm::FixedVectorType::get(CGF->FloatTy, (2 << IsQuad));
5541   case NeonTypeFlags::Int64:
5542     return llvm::FixedVectorType::get(CGF->DoubleTy, (1 << IsQuad));
5543   default:
5544     llvm_unreachable("Type can't be converted to floating-point!");
5545   }
5546 }
5547 
5548 Value *CodeGenFunction::EmitNeonSplat(Value *V, Constant *C,
5549                                       const ElementCount &Count) {
5550   Value *SV = llvm::ConstantVector::getSplat(Count, C);
5551   return Builder.CreateShuffleVector(V, V, SV, "lane");
5552 }
5553 
5554 Value *CodeGenFunction::EmitNeonSplat(Value *V, Constant *C) {
5555   ElementCount EC = cast<llvm::VectorType>(V->getType())->getElementCount();
5556   return EmitNeonSplat(V, C, EC);
5557 }
5558 
5559 Value *CodeGenFunction::EmitNeonCall(Function *F, SmallVectorImpl<Value*> &Ops,
5560                                      const char *name,
5561                                      unsigned shift, bool rightshift) {
5562   unsigned j = 0;
5563   for (Function::const_arg_iterator ai = F->arg_begin(), ae = F->arg_end();
5564        ai != ae; ++ai, ++j) {
5565     if (F->isConstrainedFPIntrinsic())
5566       if (ai->getType()->isMetadataTy())
5567         continue;
5568     if (shift > 0 && shift == j)
5569       Ops[j] = EmitNeonShiftVector(Ops[j], ai->getType(), rightshift);
5570     else
5571       Ops[j] = Builder.CreateBitCast(Ops[j], ai->getType(), name);
5572   }
5573 
5574   if (F->isConstrainedFPIntrinsic())
5575     return Builder.CreateConstrainedFPCall(F, Ops, name);
5576   else
5577     return Builder.CreateCall(F, Ops, name);
5578 }
5579 
5580 Value *CodeGenFunction::EmitNeonShiftVector(Value *V, llvm::Type *Ty,
5581                                             bool neg) {
5582   int SV = cast<ConstantInt>(V)->getSExtValue();
5583   return ConstantInt::get(Ty, neg ? -SV : SV);
5584 }
5585 
5586 // Right-shift a vector by a constant.
5587 Value *CodeGenFunction::EmitNeonRShiftImm(Value *Vec, Value *Shift,
5588                                           llvm::Type *Ty, bool usgn,
5589                                           const char *name) {
5590   llvm::VectorType *VTy = cast<llvm::VectorType>(Ty);
5591 
5592   int ShiftAmt = cast<ConstantInt>(Shift)->getSExtValue();
5593   int EltSize = VTy->getScalarSizeInBits();
5594 
5595   Vec = Builder.CreateBitCast(Vec, Ty);
5596 
5597   // lshr/ashr are undefined when the shift amount is equal to the vector
5598   // element size.
5599   if (ShiftAmt == EltSize) {
5600     if (usgn) {
5601       // Right-shifting an unsigned value by its size yields 0.
5602       return llvm::ConstantAggregateZero::get(VTy);
5603     } else {
5604       // Right-shifting a signed value by its size is equivalent
5605       // to a shift of size-1.
5606       --ShiftAmt;
5607       Shift = ConstantInt::get(VTy->getElementType(), ShiftAmt);
5608     }
5609   }
5610 
5611   Shift = EmitNeonShiftVector(Shift, Ty, false);
5612   if (usgn)
5613     return Builder.CreateLShr(Vec, Shift, name);
5614   else
5615     return Builder.CreateAShr(Vec, Shift, name);
5616 }
5617 
5618 enum {
5619   AddRetType = (1 << 0),
5620   Add1ArgType = (1 << 1),
5621   Add2ArgTypes = (1 << 2),
5622 
5623   VectorizeRetType = (1 << 3),
5624   VectorizeArgTypes = (1 << 4),
5625 
5626   InventFloatType = (1 << 5),
5627   UnsignedAlts = (1 << 6),
5628 
5629   Use64BitVectors = (1 << 7),
5630   Use128BitVectors = (1 << 8),
5631 
5632   Vectorize1ArgType = Add1ArgType | VectorizeArgTypes,
5633   VectorRet = AddRetType | VectorizeRetType,
5634   VectorRetGetArgs01 =
5635       AddRetType | Add2ArgTypes | VectorizeRetType | VectorizeArgTypes,
5636   FpCmpzModifiers =
5637       AddRetType | VectorizeRetType | Add1ArgType | InventFloatType
5638 };
5639 
5640 namespace {
5641 struct ARMVectorIntrinsicInfo {
5642   const char *NameHint;
5643   unsigned BuiltinID;
5644   unsigned LLVMIntrinsic;
5645   unsigned AltLLVMIntrinsic;
5646   uint64_t TypeModifier;
5647 
5648   bool operator<(unsigned RHSBuiltinID) const {
5649     return BuiltinID < RHSBuiltinID;
5650   }
5651   bool operator<(const ARMVectorIntrinsicInfo &TE) const {
5652     return BuiltinID < TE.BuiltinID;
5653   }
5654 };
5655 } // end anonymous namespace
5656 
5657 #define NEONMAP0(NameBase) \
5658   { #NameBase, NEON::BI__builtin_neon_ ## NameBase, 0, 0, 0 }
5659 
5660 #define NEONMAP1(NameBase, LLVMIntrinsic, TypeModifier) \
5661   { #NameBase, NEON:: BI__builtin_neon_ ## NameBase, \
5662       Intrinsic::LLVMIntrinsic, 0, TypeModifier }
5663 
5664 #define NEONMAP2(NameBase, LLVMIntrinsic, AltLLVMIntrinsic, TypeModifier) \
5665   { #NameBase, NEON:: BI__builtin_neon_ ## NameBase, \
5666       Intrinsic::LLVMIntrinsic, Intrinsic::AltLLVMIntrinsic, \
5667       TypeModifier }
5668 
5669 static const ARMVectorIntrinsicInfo ARMSIMDIntrinsicMap [] = {
5670   NEONMAP1(__a32_vcvt_bf16_v, arm_neon_vcvtfp2bf, 0),
5671   NEONMAP0(splat_lane_v),
5672   NEONMAP0(splat_laneq_v),
5673   NEONMAP0(splatq_lane_v),
5674   NEONMAP0(splatq_laneq_v),
5675   NEONMAP2(vabd_v, arm_neon_vabdu, arm_neon_vabds, Add1ArgType | UnsignedAlts),
5676   NEONMAP2(vabdq_v, arm_neon_vabdu, arm_neon_vabds, Add1ArgType | UnsignedAlts),
5677   NEONMAP1(vabs_v, arm_neon_vabs, 0),
5678   NEONMAP1(vabsq_v, arm_neon_vabs, 0),
5679   NEONMAP0(vadd_v),
5680   NEONMAP0(vaddhn_v),
5681   NEONMAP0(vaddq_v),
5682   NEONMAP1(vaesdq_v, arm_neon_aesd, 0),
5683   NEONMAP1(vaeseq_v, arm_neon_aese, 0),
5684   NEONMAP1(vaesimcq_v, arm_neon_aesimc, 0),
5685   NEONMAP1(vaesmcq_v, arm_neon_aesmc, 0),
5686   NEONMAP1(vbfdot_v, arm_neon_bfdot, 0),
5687   NEONMAP1(vbfdotq_v, arm_neon_bfdot, 0),
5688   NEONMAP1(vbfmlalbq_v, arm_neon_bfmlalb, 0),
5689   NEONMAP1(vbfmlaltq_v, arm_neon_bfmlalt, 0),
5690   NEONMAP1(vbfmmlaq_v, arm_neon_bfmmla, 0),
5691   NEONMAP1(vbsl_v, arm_neon_vbsl, AddRetType),
5692   NEONMAP1(vbslq_v, arm_neon_vbsl, AddRetType),
5693   NEONMAP1(vcadd_rot270_v, arm_neon_vcadd_rot270, Add1ArgType),
5694   NEONMAP1(vcadd_rot90_v, arm_neon_vcadd_rot90, Add1ArgType),
5695   NEONMAP1(vcaddq_rot270_v, arm_neon_vcadd_rot270, Add1ArgType),
5696   NEONMAP1(vcaddq_rot90_v, arm_neon_vcadd_rot90, Add1ArgType),
5697   NEONMAP1(vcage_v, arm_neon_vacge, 0),
5698   NEONMAP1(vcageq_v, arm_neon_vacge, 0),
5699   NEONMAP1(vcagt_v, arm_neon_vacgt, 0),
5700   NEONMAP1(vcagtq_v, arm_neon_vacgt, 0),
5701   NEONMAP1(vcale_v, arm_neon_vacge, 0),
5702   NEONMAP1(vcaleq_v, arm_neon_vacge, 0),
5703   NEONMAP1(vcalt_v, arm_neon_vacgt, 0),
5704   NEONMAP1(vcaltq_v, arm_neon_vacgt, 0),
5705   NEONMAP0(vceqz_v),
5706   NEONMAP0(vceqzq_v),
5707   NEONMAP0(vcgez_v),
5708   NEONMAP0(vcgezq_v),
5709   NEONMAP0(vcgtz_v),
5710   NEONMAP0(vcgtzq_v),
5711   NEONMAP0(vclez_v),
5712   NEONMAP0(vclezq_v),
5713   NEONMAP1(vcls_v, arm_neon_vcls, Add1ArgType),
5714   NEONMAP1(vclsq_v, arm_neon_vcls, Add1ArgType),
5715   NEONMAP0(vcltz_v),
5716   NEONMAP0(vcltzq_v),
5717   NEONMAP1(vclz_v, ctlz, Add1ArgType),
5718   NEONMAP1(vclzq_v, ctlz, Add1ArgType),
5719   NEONMAP1(vcnt_v, ctpop, Add1ArgType),
5720   NEONMAP1(vcntq_v, ctpop, Add1ArgType),
5721   NEONMAP1(vcvt_f16_f32, arm_neon_vcvtfp2hf, 0),
5722   NEONMAP0(vcvt_f16_v),
5723   NEONMAP1(vcvt_f32_f16, arm_neon_vcvthf2fp, 0),
5724   NEONMAP0(vcvt_f32_v),
5725   NEONMAP2(vcvt_n_f16_v, arm_neon_vcvtfxu2fp, arm_neon_vcvtfxs2fp, 0),
5726   NEONMAP2(vcvt_n_f32_v, arm_neon_vcvtfxu2fp, arm_neon_vcvtfxs2fp, 0),
5727   NEONMAP1(vcvt_n_s16_v, arm_neon_vcvtfp2fxs, 0),
5728   NEONMAP1(vcvt_n_s32_v, arm_neon_vcvtfp2fxs, 0),
5729   NEONMAP1(vcvt_n_s64_v, arm_neon_vcvtfp2fxs, 0),
5730   NEONMAP1(vcvt_n_u16_v, arm_neon_vcvtfp2fxu, 0),
5731   NEONMAP1(vcvt_n_u32_v, arm_neon_vcvtfp2fxu, 0),
5732   NEONMAP1(vcvt_n_u64_v, arm_neon_vcvtfp2fxu, 0),
5733   NEONMAP0(vcvt_s16_v),
5734   NEONMAP0(vcvt_s32_v),
5735   NEONMAP0(vcvt_s64_v),
5736   NEONMAP0(vcvt_u16_v),
5737   NEONMAP0(vcvt_u32_v),
5738   NEONMAP0(vcvt_u64_v),
5739   NEONMAP1(vcvta_s16_v, arm_neon_vcvtas, 0),
5740   NEONMAP1(vcvta_s32_v, arm_neon_vcvtas, 0),
5741   NEONMAP1(vcvta_s64_v, arm_neon_vcvtas, 0),
5742   NEONMAP1(vcvta_u16_v, arm_neon_vcvtau, 0),
5743   NEONMAP1(vcvta_u32_v, arm_neon_vcvtau, 0),
5744   NEONMAP1(vcvta_u64_v, arm_neon_vcvtau, 0),
5745   NEONMAP1(vcvtaq_s16_v, arm_neon_vcvtas, 0),
5746   NEONMAP1(vcvtaq_s32_v, arm_neon_vcvtas, 0),
5747   NEONMAP1(vcvtaq_s64_v, arm_neon_vcvtas, 0),
5748   NEONMAP1(vcvtaq_u16_v, arm_neon_vcvtau, 0),
5749   NEONMAP1(vcvtaq_u32_v, arm_neon_vcvtau, 0),
5750   NEONMAP1(vcvtaq_u64_v, arm_neon_vcvtau, 0),
5751   NEONMAP1(vcvth_bf16_f32, arm_neon_vcvtbfp2bf, 0),
5752   NEONMAP1(vcvtm_s16_v, arm_neon_vcvtms, 0),
5753   NEONMAP1(vcvtm_s32_v, arm_neon_vcvtms, 0),
5754   NEONMAP1(vcvtm_s64_v, arm_neon_vcvtms, 0),
5755   NEONMAP1(vcvtm_u16_v, arm_neon_vcvtmu, 0),
5756   NEONMAP1(vcvtm_u32_v, arm_neon_vcvtmu, 0),
5757   NEONMAP1(vcvtm_u64_v, arm_neon_vcvtmu, 0),
5758   NEONMAP1(vcvtmq_s16_v, arm_neon_vcvtms, 0),
5759   NEONMAP1(vcvtmq_s32_v, arm_neon_vcvtms, 0),
5760   NEONMAP1(vcvtmq_s64_v, arm_neon_vcvtms, 0),
5761   NEONMAP1(vcvtmq_u16_v, arm_neon_vcvtmu, 0),
5762   NEONMAP1(vcvtmq_u32_v, arm_neon_vcvtmu, 0),
5763   NEONMAP1(vcvtmq_u64_v, arm_neon_vcvtmu, 0),
5764   NEONMAP1(vcvtn_s16_v, arm_neon_vcvtns, 0),
5765   NEONMAP1(vcvtn_s32_v, arm_neon_vcvtns, 0),
5766   NEONMAP1(vcvtn_s64_v, arm_neon_vcvtns, 0),
5767   NEONMAP1(vcvtn_u16_v, arm_neon_vcvtnu, 0),
5768   NEONMAP1(vcvtn_u32_v, arm_neon_vcvtnu, 0),
5769   NEONMAP1(vcvtn_u64_v, arm_neon_vcvtnu, 0),
5770   NEONMAP1(vcvtnq_s16_v, arm_neon_vcvtns, 0),
5771   NEONMAP1(vcvtnq_s32_v, arm_neon_vcvtns, 0),
5772   NEONMAP1(vcvtnq_s64_v, arm_neon_vcvtns, 0),
5773   NEONMAP1(vcvtnq_u16_v, arm_neon_vcvtnu, 0),
5774   NEONMAP1(vcvtnq_u32_v, arm_neon_vcvtnu, 0),
5775   NEONMAP1(vcvtnq_u64_v, arm_neon_vcvtnu, 0),
5776   NEONMAP1(vcvtp_s16_v, arm_neon_vcvtps, 0),
5777   NEONMAP1(vcvtp_s32_v, arm_neon_vcvtps, 0),
5778   NEONMAP1(vcvtp_s64_v, arm_neon_vcvtps, 0),
5779   NEONMAP1(vcvtp_u16_v, arm_neon_vcvtpu, 0),
5780   NEONMAP1(vcvtp_u32_v, arm_neon_vcvtpu, 0),
5781   NEONMAP1(vcvtp_u64_v, arm_neon_vcvtpu, 0),
5782   NEONMAP1(vcvtpq_s16_v, arm_neon_vcvtps, 0),
5783   NEONMAP1(vcvtpq_s32_v, arm_neon_vcvtps, 0),
5784   NEONMAP1(vcvtpq_s64_v, arm_neon_vcvtps, 0),
5785   NEONMAP1(vcvtpq_u16_v, arm_neon_vcvtpu, 0),
5786   NEONMAP1(vcvtpq_u32_v, arm_neon_vcvtpu, 0),
5787   NEONMAP1(vcvtpq_u64_v, arm_neon_vcvtpu, 0),
5788   NEONMAP0(vcvtq_f16_v),
5789   NEONMAP0(vcvtq_f32_v),
5790   NEONMAP2(vcvtq_n_f16_v, arm_neon_vcvtfxu2fp, arm_neon_vcvtfxs2fp, 0),
5791   NEONMAP2(vcvtq_n_f32_v, arm_neon_vcvtfxu2fp, arm_neon_vcvtfxs2fp, 0),
5792   NEONMAP1(vcvtq_n_s16_v, arm_neon_vcvtfp2fxs, 0),
5793   NEONMAP1(vcvtq_n_s32_v, arm_neon_vcvtfp2fxs, 0),
5794   NEONMAP1(vcvtq_n_s64_v, arm_neon_vcvtfp2fxs, 0),
5795   NEONMAP1(vcvtq_n_u16_v, arm_neon_vcvtfp2fxu, 0),
5796   NEONMAP1(vcvtq_n_u32_v, arm_neon_vcvtfp2fxu, 0),
5797   NEONMAP1(vcvtq_n_u64_v, arm_neon_vcvtfp2fxu, 0),
5798   NEONMAP0(vcvtq_s16_v),
5799   NEONMAP0(vcvtq_s32_v),
5800   NEONMAP0(vcvtq_s64_v),
5801   NEONMAP0(vcvtq_u16_v),
5802   NEONMAP0(vcvtq_u32_v),
5803   NEONMAP0(vcvtq_u64_v),
5804   NEONMAP2(vdot_v, arm_neon_udot, arm_neon_sdot, 0),
5805   NEONMAP2(vdotq_v, arm_neon_udot, arm_neon_sdot, 0),
5806   NEONMAP0(vext_v),
5807   NEONMAP0(vextq_v),
5808   NEONMAP0(vfma_v),
5809   NEONMAP0(vfmaq_v),
5810   NEONMAP2(vhadd_v, arm_neon_vhaddu, arm_neon_vhadds, Add1ArgType | UnsignedAlts),
5811   NEONMAP2(vhaddq_v, arm_neon_vhaddu, arm_neon_vhadds, Add1ArgType | UnsignedAlts),
5812   NEONMAP2(vhsub_v, arm_neon_vhsubu, arm_neon_vhsubs, Add1ArgType | UnsignedAlts),
5813   NEONMAP2(vhsubq_v, arm_neon_vhsubu, arm_neon_vhsubs, Add1ArgType | UnsignedAlts),
5814   NEONMAP0(vld1_dup_v),
5815   NEONMAP1(vld1_v, arm_neon_vld1, 0),
5816   NEONMAP1(vld1_x2_v, arm_neon_vld1x2, 0),
5817   NEONMAP1(vld1_x3_v, arm_neon_vld1x3, 0),
5818   NEONMAP1(vld1_x4_v, arm_neon_vld1x4, 0),
5819   NEONMAP0(vld1q_dup_v),
5820   NEONMAP1(vld1q_v, arm_neon_vld1, 0),
5821   NEONMAP1(vld1q_x2_v, arm_neon_vld1x2, 0),
5822   NEONMAP1(vld1q_x3_v, arm_neon_vld1x3, 0),
5823   NEONMAP1(vld1q_x4_v, arm_neon_vld1x4, 0),
5824   NEONMAP1(vld2_dup_v, arm_neon_vld2dup, 0),
5825   NEONMAP1(vld2_lane_v, arm_neon_vld2lane, 0),
5826   NEONMAP1(vld2_v, arm_neon_vld2, 0),
5827   NEONMAP1(vld2q_dup_v, arm_neon_vld2dup, 0),
5828   NEONMAP1(vld2q_lane_v, arm_neon_vld2lane, 0),
5829   NEONMAP1(vld2q_v, arm_neon_vld2, 0),
5830   NEONMAP1(vld3_dup_v, arm_neon_vld3dup, 0),
5831   NEONMAP1(vld3_lane_v, arm_neon_vld3lane, 0),
5832   NEONMAP1(vld3_v, arm_neon_vld3, 0),
5833   NEONMAP1(vld3q_dup_v, arm_neon_vld3dup, 0),
5834   NEONMAP1(vld3q_lane_v, arm_neon_vld3lane, 0),
5835   NEONMAP1(vld3q_v, arm_neon_vld3, 0),
5836   NEONMAP1(vld4_dup_v, arm_neon_vld4dup, 0),
5837   NEONMAP1(vld4_lane_v, arm_neon_vld4lane, 0),
5838   NEONMAP1(vld4_v, arm_neon_vld4, 0),
5839   NEONMAP1(vld4q_dup_v, arm_neon_vld4dup, 0),
5840   NEONMAP1(vld4q_lane_v, arm_neon_vld4lane, 0),
5841   NEONMAP1(vld4q_v, arm_neon_vld4, 0),
5842   NEONMAP2(vmax_v, arm_neon_vmaxu, arm_neon_vmaxs, Add1ArgType | UnsignedAlts),
5843   NEONMAP1(vmaxnm_v, arm_neon_vmaxnm, Add1ArgType),
5844   NEONMAP1(vmaxnmq_v, arm_neon_vmaxnm, Add1ArgType),
5845   NEONMAP2(vmaxq_v, arm_neon_vmaxu, arm_neon_vmaxs, Add1ArgType | UnsignedAlts),
5846   NEONMAP2(vmin_v, arm_neon_vminu, arm_neon_vmins, Add1ArgType | UnsignedAlts),
5847   NEONMAP1(vminnm_v, arm_neon_vminnm, Add1ArgType),
5848   NEONMAP1(vminnmq_v, arm_neon_vminnm, Add1ArgType),
5849   NEONMAP2(vminq_v, arm_neon_vminu, arm_neon_vmins, Add1ArgType | UnsignedAlts),
5850   NEONMAP2(vmmlaq_v, arm_neon_ummla, arm_neon_smmla, 0),
5851   NEONMAP0(vmovl_v),
5852   NEONMAP0(vmovn_v),
5853   NEONMAP1(vmul_v, arm_neon_vmulp, Add1ArgType),
5854   NEONMAP0(vmull_v),
5855   NEONMAP1(vmulq_v, arm_neon_vmulp, Add1ArgType),
5856   NEONMAP2(vpadal_v, arm_neon_vpadalu, arm_neon_vpadals, UnsignedAlts),
5857   NEONMAP2(vpadalq_v, arm_neon_vpadalu, arm_neon_vpadals, UnsignedAlts),
5858   NEONMAP1(vpadd_v, arm_neon_vpadd, Add1ArgType),
5859   NEONMAP2(vpaddl_v, arm_neon_vpaddlu, arm_neon_vpaddls, UnsignedAlts),
5860   NEONMAP2(vpaddlq_v, arm_neon_vpaddlu, arm_neon_vpaddls, UnsignedAlts),
5861   NEONMAP1(vpaddq_v, arm_neon_vpadd, Add1ArgType),
5862   NEONMAP2(vpmax_v, arm_neon_vpmaxu, arm_neon_vpmaxs, Add1ArgType | UnsignedAlts),
5863   NEONMAP2(vpmin_v, arm_neon_vpminu, arm_neon_vpmins, Add1ArgType | UnsignedAlts),
5864   NEONMAP1(vqabs_v, arm_neon_vqabs, Add1ArgType),
5865   NEONMAP1(vqabsq_v, arm_neon_vqabs, Add1ArgType),
5866   NEONMAP2(vqadd_v, uadd_sat, sadd_sat, Add1ArgType | UnsignedAlts),
5867   NEONMAP2(vqaddq_v, uadd_sat, sadd_sat, Add1ArgType | UnsignedAlts),
5868   NEONMAP2(vqdmlal_v, arm_neon_vqdmull, sadd_sat, 0),
5869   NEONMAP2(vqdmlsl_v, arm_neon_vqdmull, ssub_sat, 0),
5870   NEONMAP1(vqdmulh_v, arm_neon_vqdmulh, Add1ArgType),
5871   NEONMAP1(vqdmulhq_v, arm_neon_vqdmulh, Add1ArgType),
5872   NEONMAP1(vqdmull_v, arm_neon_vqdmull, Add1ArgType),
5873   NEONMAP2(vqmovn_v, arm_neon_vqmovnu, arm_neon_vqmovns, Add1ArgType | UnsignedAlts),
5874   NEONMAP1(vqmovun_v, arm_neon_vqmovnsu, Add1ArgType),
5875   NEONMAP1(vqneg_v, arm_neon_vqneg, Add1ArgType),
5876   NEONMAP1(vqnegq_v, arm_neon_vqneg, Add1ArgType),
5877   NEONMAP1(vqrdmlah_v, arm_neon_vqrdmlah, Add1ArgType),
5878   NEONMAP1(vqrdmlahq_v, arm_neon_vqrdmlah, Add1ArgType),
5879   NEONMAP1(vqrdmlsh_v, arm_neon_vqrdmlsh, Add1ArgType),
5880   NEONMAP1(vqrdmlshq_v, arm_neon_vqrdmlsh, Add1ArgType),
5881   NEONMAP1(vqrdmulh_v, arm_neon_vqrdmulh, Add1ArgType),
5882   NEONMAP1(vqrdmulhq_v, arm_neon_vqrdmulh, Add1ArgType),
5883   NEONMAP2(vqrshl_v, arm_neon_vqrshiftu, arm_neon_vqrshifts, Add1ArgType | UnsignedAlts),
5884   NEONMAP2(vqrshlq_v, arm_neon_vqrshiftu, arm_neon_vqrshifts, Add1ArgType | UnsignedAlts),
5885   NEONMAP2(vqshl_n_v, arm_neon_vqshiftu, arm_neon_vqshifts, UnsignedAlts),
5886   NEONMAP2(vqshl_v, arm_neon_vqshiftu, arm_neon_vqshifts, Add1ArgType | UnsignedAlts),
5887   NEONMAP2(vqshlq_n_v, arm_neon_vqshiftu, arm_neon_vqshifts, UnsignedAlts),
5888   NEONMAP2(vqshlq_v, arm_neon_vqshiftu, arm_neon_vqshifts, Add1ArgType | UnsignedAlts),
5889   NEONMAP1(vqshlu_n_v, arm_neon_vqshiftsu, 0),
5890   NEONMAP1(vqshluq_n_v, arm_neon_vqshiftsu, 0),
5891   NEONMAP2(vqsub_v, usub_sat, ssub_sat, Add1ArgType | UnsignedAlts),
5892   NEONMAP2(vqsubq_v, usub_sat, ssub_sat, Add1ArgType | UnsignedAlts),
5893   NEONMAP1(vraddhn_v, arm_neon_vraddhn, Add1ArgType),
5894   NEONMAP2(vrecpe_v, arm_neon_vrecpe, arm_neon_vrecpe, 0),
5895   NEONMAP2(vrecpeq_v, arm_neon_vrecpe, arm_neon_vrecpe, 0),
5896   NEONMAP1(vrecps_v, arm_neon_vrecps, Add1ArgType),
5897   NEONMAP1(vrecpsq_v, arm_neon_vrecps, Add1ArgType),
5898   NEONMAP2(vrhadd_v, arm_neon_vrhaddu, arm_neon_vrhadds, Add1ArgType | UnsignedAlts),
5899   NEONMAP2(vrhaddq_v, arm_neon_vrhaddu, arm_neon_vrhadds, Add1ArgType | UnsignedAlts),
5900   NEONMAP1(vrnd_v, arm_neon_vrintz, Add1ArgType),
5901   NEONMAP1(vrnda_v, arm_neon_vrinta, Add1ArgType),
5902   NEONMAP1(vrndaq_v, arm_neon_vrinta, Add1ArgType),
5903   NEONMAP0(vrndi_v),
5904   NEONMAP0(vrndiq_v),
5905   NEONMAP1(vrndm_v, arm_neon_vrintm, Add1ArgType),
5906   NEONMAP1(vrndmq_v, arm_neon_vrintm, Add1ArgType),
5907   NEONMAP1(vrndn_v, arm_neon_vrintn, Add1ArgType),
5908   NEONMAP1(vrndnq_v, arm_neon_vrintn, Add1ArgType),
5909   NEONMAP1(vrndp_v, arm_neon_vrintp, Add1ArgType),
5910   NEONMAP1(vrndpq_v, arm_neon_vrintp, Add1ArgType),
5911   NEONMAP1(vrndq_v, arm_neon_vrintz, Add1ArgType),
5912   NEONMAP1(vrndx_v, arm_neon_vrintx, Add1ArgType),
5913   NEONMAP1(vrndxq_v, arm_neon_vrintx, Add1ArgType),
5914   NEONMAP2(vrshl_v, arm_neon_vrshiftu, arm_neon_vrshifts, Add1ArgType | UnsignedAlts),
5915   NEONMAP2(vrshlq_v, arm_neon_vrshiftu, arm_neon_vrshifts, Add1ArgType | UnsignedAlts),
5916   NEONMAP2(vrshr_n_v, arm_neon_vrshiftu, arm_neon_vrshifts, UnsignedAlts),
5917   NEONMAP2(vrshrq_n_v, arm_neon_vrshiftu, arm_neon_vrshifts, UnsignedAlts),
5918   NEONMAP2(vrsqrte_v, arm_neon_vrsqrte, arm_neon_vrsqrte, 0),
5919   NEONMAP2(vrsqrteq_v, arm_neon_vrsqrte, arm_neon_vrsqrte, 0),
5920   NEONMAP1(vrsqrts_v, arm_neon_vrsqrts, Add1ArgType),
5921   NEONMAP1(vrsqrtsq_v, arm_neon_vrsqrts, Add1ArgType),
5922   NEONMAP1(vrsubhn_v, arm_neon_vrsubhn, Add1ArgType),
5923   NEONMAP1(vsha1su0q_v, arm_neon_sha1su0, 0),
5924   NEONMAP1(vsha1su1q_v, arm_neon_sha1su1, 0),
5925   NEONMAP1(vsha256h2q_v, arm_neon_sha256h2, 0),
5926   NEONMAP1(vsha256hq_v, arm_neon_sha256h, 0),
5927   NEONMAP1(vsha256su0q_v, arm_neon_sha256su0, 0),
5928   NEONMAP1(vsha256su1q_v, arm_neon_sha256su1, 0),
5929   NEONMAP0(vshl_n_v),
5930   NEONMAP2(vshl_v, arm_neon_vshiftu, arm_neon_vshifts, Add1ArgType | UnsignedAlts),
5931   NEONMAP0(vshll_n_v),
5932   NEONMAP0(vshlq_n_v),
5933   NEONMAP2(vshlq_v, arm_neon_vshiftu, arm_neon_vshifts, Add1ArgType | UnsignedAlts),
5934   NEONMAP0(vshr_n_v),
5935   NEONMAP0(vshrn_n_v),
5936   NEONMAP0(vshrq_n_v),
5937   NEONMAP1(vst1_v, arm_neon_vst1, 0),
5938   NEONMAP1(vst1_x2_v, arm_neon_vst1x2, 0),
5939   NEONMAP1(vst1_x3_v, arm_neon_vst1x3, 0),
5940   NEONMAP1(vst1_x4_v, arm_neon_vst1x4, 0),
5941   NEONMAP1(vst1q_v, arm_neon_vst1, 0),
5942   NEONMAP1(vst1q_x2_v, arm_neon_vst1x2, 0),
5943   NEONMAP1(vst1q_x3_v, arm_neon_vst1x3, 0),
5944   NEONMAP1(vst1q_x4_v, arm_neon_vst1x4, 0),
5945   NEONMAP1(vst2_lane_v, arm_neon_vst2lane, 0),
5946   NEONMAP1(vst2_v, arm_neon_vst2, 0),
5947   NEONMAP1(vst2q_lane_v, arm_neon_vst2lane, 0),
5948   NEONMAP1(vst2q_v, arm_neon_vst2, 0),
5949   NEONMAP1(vst3_lane_v, arm_neon_vst3lane, 0),
5950   NEONMAP1(vst3_v, arm_neon_vst3, 0),
5951   NEONMAP1(vst3q_lane_v, arm_neon_vst3lane, 0),
5952   NEONMAP1(vst3q_v, arm_neon_vst3, 0),
5953   NEONMAP1(vst4_lane_v, arm_neon_vst4lane, 0),
5954   NEONMAP1(vst4_v, arm_neon_vst4, 0),
5955   NEONMAP1(vst4q_lane_v, arm_neon_vst4lane, 0),
5956   NEONMAP1(vst4q_v, arm_neon_vst4, 0),
5957   NEONMAP0(vsubhn_v),
5958   NEONMAP0(vtrn_v),
5959   NEONMAP0(vtrnq_v),
5960   NEONMAP0(vtst_v),
5961   NEONMAP0(vtstq_v),
5962   NEONMAP1(vusdot_v, arm_neon_usdot, 0),
5963   NEONMAP1(vusdotq_v, arm_neon_usdot, 0),
5964   NEONMAP1(vusmmlaq_v, arm_neon_usmmla, 0),
5965   NEONMAP0(vuzp_v),
5966   NEONMAP0(vuzpq_v),
5967   NEONMAP0(vzip_v),
5968   NEONMAP0(vzipq_v)
5969 };
5970 
5971 static const ARMVectorIntrinsicInfo AArch64SIMDIntrinsicMap[] = {
5972   NEONMAP1(__a64_vcvtq_low_bf16_v, aarch64_neon_bfcvtn, 0),
5973   NEONMAP0(splat_lane_v),
5974   NEONMAP0(splat_laneq_v),
5975   NEONMAP0(splatq_lane_v),
5976   NEONMAP0(splatq_laneq_v),
5977   NEONMAP1(vabs_v, aarch64_neon_abs, 0),
5978   NEONMAP1(vabsq_v, aarch64_neon_abs, 0),
5979   NEONMAP0(vadd_v),
5980   NEONMAP0(vaddhn_v),
5981   NEONMAP0(vaddq_p128),
5982   NEONMAP0(vaddq_v),
5983   NEONMAP1(vaesdq_v, aarch64_crypto_aesd, 0),
5984   NEONMAP1(vaeseq_v, aarch64_crypto_aese, 0),
5985   NEONMAP1(vaesimcq_v, aarch64_crypto_aesimc, 0),
5986   NEONMAP1(vaesmcq_v, aarch64_crypto_aesmc, 0),
5987   NEONMAP2(vbcaxq_v, aarch64_crypto_bcaxu, aarch64_crypto_bcaxs, Add1ArgType | UnsignedAlts),
5988   NEONMAP1(vbfdot_v, aarch64_neon_bfdot, 0),
5989   NEONMAP1(vbfdotq_v, aarch64_neon_bfdot, 0),
5990   NEONMAP1(vbfmlalbq_v, aarch64_neon_bfmlalb, 0),
5991   NEONMAP1(vbfmlaltq_v, aarch64_neon_bfmlalt, 0),
5992   NEONMAP1(vbfmmlaq_v, aarch64_neon_bfmmla, 0),
5993   NEONMAP1(vcadd_rot270_v, aarch64_neon_vcadd_rot270, Add1ArgType),
5994   NEONMAP1(vcadd_rot90_v, aarch64_neon_vcadd_rot90, Add1ArgType),
5995   NEONMAP1(vcaddq_rot270_v, aarch64_neon_vcadd_rot270, Add1ArgType),
5996   NEONMAP1(vcaddq_rot90_v, aarch64_neon_vcadd_rot90, Add1ArgType),
5997   NEONMAP1(vcage_v, aarch64_neon_facge, 0),
5998   NEONMAP1(vcageq_v, aarch64_neon_facge, 0),
5999   NEONMAP1(vcagt_v, aarch64_neon_facgt, 0),
6000   NEONMAP1(vcagtq_v, aarch64_neon_facgt, 0),
6001   NEONMAP1(vcale_v, aarch64_neon_facge, 0),
6002   NEONMAP1(vcaleq_v, aarch64_neon_facge, 0),
6003   NEONMAP1(vcalt_v, aarch64_neon_facgt, 0),
6004   NEONMAP1(vcaltq_v, aarch64_neon_facgt, 0),
6005   NEONMAP0(vceqz_v),
6006   NEONMAP0(vceqzq_v),
6007   NEONMAP0(vcgez_v),
6008   NEONMAP0(vcgezq_v),
6009   NEONMAP0(vcgtz_v),
6010   NEONMAP0(vcgtzq_v),
6011   NEONMAP0(vclez_v),
6012   NEONMAP0(vclezq_v),
6013   NEONMAP1(vcls_v, aarch64_neon_cls, Add1ArgType),
6014   NEONMAP1(vclsq_v, aarch64_neon_cls, Add1ArgType),
6015   NEONMAP0(vcltz_v),
6016   NEONMAP0(vcltzq_v),
6017   NEONMAP1(vclz_v, ctlz, Add1ArgType),
6018   NEONMAP1(vclzq_v, ctlz, Add1ArgType),
6019   NEONMAP1(vcmla_rot180_v, aarch64_neon_vcmla_rot180, Add1ArgType),
6020   NEONMAP1(vcmla_rot270_v, aarch64_neon_vcmla_rot270, Add1ArgType),
6021   NEONMAP1(vcmla_rot90_v, aarch64_neon_vcmla_rot90, Add1ArgType),
6022   NEONMAP1(vcmla_v, aarch64_neon_vcmla_rot0, Add1ArgType),
6023   NEONMAP1(vcmlaq_rot180_v, aarch64_neon_vcmla_rot180, Add1ArgType),
6024   NEONMAP1(vcmlaq_rot270_v, aarch64_neon_vcmla_rot270, Add1ArgType),
6025   NEONMAP1(vcmlaq_rot90_v, aarch64_neon_vcmla_rot90, Add1ArgType),
6026   NEONMAP1(vcmlaq_v, aarch64_neon_vcmla_rot0, Add1ArgType),
6027   NEONMAP1(vcnt_v, ctpop, Add1ArgType),
6028   NEONMAP1(vcntq_v, ctpop, Add1ArgType),
6029   NEONMAP1(vcvt_f16_f32, aarch64_neon_vcvtfp2hf, 0),
6030   NEONMAP0(vcvt_f16_v),
6031   NEONMAP1(vcvt_f32_f16, aarch64_neon_vcvthf2fp, 0),
6032   NEONMAP0(vcvt_f32_v),
6033   NEONMAP2(vcvt_n_f16_v, aarch64_neon_vcvtfxu2fp, aarch64_neon_vcvtfxs2fp, 0),
6034   NEONMAP2(vcvt_n_f32_v, aarch64_neon_vcvtfxu2fp, aarch64_neon_vcvtfxs2fp, 0),
6035   NEONMAP2(vcvt_n_f64_v, aarch64_neon_vcvtfxu2fp, aarch64_neon_vcvtfxs2fp, 0),
6036   NEONMAP1(vcvt_n_s16_v, aarch64_neon_vcvtfp2fxs, 0),
6037   NEONMAP1(vcvt_n_s32_v, aarch64_neon_vcvtfp2fxs, 0),
6038   NEONMAP1(vcvt_n_s64_v, aarch64_neon_vcvtfp2fxs, 0),
6039   NEONMAP1(vcvt_n_u16_v, aarch64_neon_vcvtfp2fxu, 0),
6040   NEONMAP1(vcvt_n_u32_v, aarch64_neon_vcvtfp2fxu, 0),
6041   NEONMAP1(vcvt_n_u64_v, aarch64_neon_vcvtfp2fxu, 0),
6042   NEONMAP0(vcvtq_f16_v),
6043   NEONMAP0(vcvtq_f32_v),
6044   NEONMAP1(vcvtq_high_bf16_v, aarch64_neon_bfcvtn2, 0),
6045   NEONMAP2(vcvtq_n_f16_v, aarch64_neon_vcvtfxu2fp, aarch64_neon_vcvtfxs2fp, 0),
6046   NEONMAP2(vcvtq_n_f32_v, aarch64_neon_vcvtfxu2fp, aarch64_neon_vcvtfxs2fp, 0),
6047   NEONMAP2(vcvtq_n_f64_v, aarch64_neon_vcvtfxu2fp, aarch64_neon_vcvtfxs2fp, 0),
6048   NEONMAP1(vcvtq_n_s16_v, aarch64_neon_vcvtfp2fxs, 0),
6049   NEONMAP1(vcvtq_n_s32_v, aarch64_neon_vcvtfp2fxs, 0),
6050   NEONMAP1(vcvtq_n_s64_v, aarch64_neon_vcvtfp2fxs, 0),
6051   NEONMAP1(vcvtq_n_u16_v, aarch64_neon_vcvtfp2fxu, 0),
6052   NEONMAP1(vcvtq_n_u32_v, aarch64_neon_vcvtfp2fxu, 0),
6053   NEONMAP1(vcvtq_n_u64_v, aarch64_neon_vcvtfp2fxu, 0),
6054   NEONMAP1(vcvtx_f32_v, aarch64_neon_fcvtxn, AddRetType | Add1ArgType),
6055   NEONMAP2(vdot_v, aarch64_neon_udot, aarch64_neon_sdot, 0),
6056   NEONMAP2(vdotq_v, aarch64_neon_udot, aarch64_neon_sdot, 0),
6057   NEONMAP2(veor3q_v, aarch64_crypto_eor3u, aarch64_crypto_eor3s, Add1ArgType | UnsignedAlts),
6058   NEONMAP0(vext_v),
6059   NEONMAP0(vextq_v),
6060   NEONMAP0(vfma_v),
6061   NEONMAP0(vfmaq_v),
6062   NEONMAP1(vfmlal_high_v, aarch64_neon_fmlal2, 0),
6063   NEONMAP1(vfmlal_low_v, aarch64_neon_fmlal, 0),
6064   NEONMAP1(vfmlalq_high_v, aarch64_neon_fmlal2, 0),
6065   NEONMAP1(vfmlalq_low_v, aarch64_neon_fmlal, 0),
6066   NEONMAP1(vfmlsl_high_v, aarch64_neon_fmlsl2, 0),
6067   NEONMAP1(vfmlsl_low_v, aarch64_neon_fmlsl, 0),
6068   NEONMAP1(vfmlslq_high_v, aarch64_neon_fmlsl2, 0),
6069   NEONMAP1(vfmlslq_low_v, aarch64_neon_fmlsl, 0),
6070   NEONMAP2(vhadd_v, aarch64_neon_uhadd, aarch64_neon_shadd, Add1ArgType | UnsignedAlts),
6071   NEONMAP2(vhaddq_v, aarch64_neon_uhadd, aarch64_neon_shadd, Add1ArgType | UnsignedAlts),
6072   NEONMAP2(vhsub_v, aarch64_neon_uhsub, aarch64_neon_shsub, Add1ArgType | UnsignedAlts),
6073   NEONMAP2(vhsubq_v, aarch64_neon_uhsub, aarch64_neon_shsub, Add1ArgType | UnsignedAlts),
6074   NEONMAP1(vld1_x2_v, aarch64_neon_ld1x2, 0),
6075   NEONMAP1(vld1_x3_v, aarch64_neon_ld1x3, 0),
6076   NEONMAP1(vld1_x4_v, aarch64_neon_ld1x4, 0),
6077   NEONMAP1(vld1q_x2_v, aarch64_neon_ld1x2, 0),
6078   NEONMAP1(vld1q_x3_v, aarch64_neon_ld1x3, 0),
6079   NEONMAP1(vld1q_x4_v, aarch64_neon_ld1x4, 0),
6080   NEONMAP2(vmmlaq_v, aarch64_neon_ummla, aarch64_neon_smmla, 0),
6081   NEONMAP0(vmovl_v),
6082   NEONMAP0(vmovn_v),
6083   NEONMAP1(vmul_v, aarch64_neon_pmul, Add1ArgType),
6084   NEONMAP1(vmulq_v, aarch64_neon_pmul, Add1ArgType),
6085   NEONMAP1(vpadd_v, aarch64_neon_addp, Add1ArgType),
6086   NEONMAP2(vpaddl_v, aarch64_neon_uaddlp, aarch64_neon_saddlp, UnsignedAlts),
6087   NEONMAP2(vpaddlq_v, aarch64_neon_uaddlp, aarch64_neon_saddlp, UnsignedAlts),
6088   NEONMAP1(vpaddq_v, aarch64_neon_addp, Add1ArgType),
6089   NEONMAP1(vqabs_v, aarch64_neon_sqabs, Add1ArgType),
6090   NEONMAP1(vqabsq_v, aarch64_neon_sqabs, Add1ArgType),
6091   NEONMAP2(vqadd_v, aarch64_neon_uqadd, aarch64_neon_sqadd, Add1ArgType | UnsignedAlts),
6092   NEONMAP2(vqaddq_v, aarch64_neon_uqadd, aarch64_neon_sqadd, Add1ArgType | UnsignedAlts),
6093   NEONMAP2(vqdmlal_v, aarch64_neon_sqdmull, aarch64_neon_sqadd, 0),
6094   NEONMAP2(vqdmlsl_v, aarch64_neon_sqdmull, aarch64_neon_sqsub, 0),
6095   NEONMAP1(vqdmulh_lane_v, aarch64_neon_sqdmulh_lane, 0),
6096   NEONMAP1(vqdmulh_laneq_v, aarch64_neon_sqdmulh_laneq, 0),
6097   NEONMAP1(vqdmulh_v, aarch64_neon_sqdmulh, Add1ArgType),
6098   NEONMAP1(vqdmulhq_lane_v, aarch64_neon_sqdmulh_lane, 0),
6099   NEONMAP1(vqdmulhq_laneq_v, aarch64_neon_sqdmulh_laneq, 0),
6100   NEONMAP1(vqdmulhq_v, aarch64_neon_sqdmulh, Add1ArgType),
6101   NEONMAP1(vqdmull_v, aarch64_neon_sqdmull, Add1ArgType),
6102   NEONMAP2(vqmovn_v, aarch64_neon_uqxtn, aarch64_neon_sqxtn, Add1ArgType | UnsignedAlts),
6103   NEONMAP1(vqmovun_v, aarch64_neon_sqxtun, Add1ArgType),
6104   NEONMAP1(vqneg_v, aarch64_neon_sqneg, Add1ArgType),
6105   NEONMAP1(vqnegq_v, aarch64_neon_sqneg, Add1ArgType),
6106   NEONMAP1(vqrdmlah_v, aarch64_neon_sqrdmlah, Add1ArgType),
6107   NEONMAP1(vqrdmlahq_v, aarch64_neon_sqrdmlah, Add1ArgType),
6108   NEONMAP1(vqrdmlsh_v, aarch64_neon_sqrdmlsh, Add1ArgType),
6109   NEONMAP1(vqrdmlshq_v, aarch64_neon_sqrdmlsh, Add1ArgType),
6110   NEONMAP1(vqrdmulh_lane_v, aarch64_neon_sqrdmulh_lane, 0),
6111   NEONMAP1(vqrdmulh_laneq_v, aarch64_neon_sqrdmulh_laneq, 0),
6112   NEONMAP1(vqrdmulh_v, aarch64_neon_sqrdmulh, Add1ArgType),
6113   NEONMAP1(vqrdmulhq_lane_v, aarch64_neon_sqrdmulh_lane, 0),
6114   NEONMAP1(vqrdmulhq_laneq_v, aarch64_neon_sqrdmulh_laneq, 0),
6115   NEONMAP1(vqrdmulhq_v, aarch64_neon_sqrdmulh, Add1ArgType),
6116   NEONMAP2(vqrshl_v, aarch64_neon_uqrshl, aarch64_neon_sqrshl, Add1ArgType | UnsignedAlts),
6117   NEONMAP2(vqrshlq_v, aarch64_neon_uqrshl, aarch64_neon_sqrshl, Add1ArgType | UnsignedAlts),
6118   NEONMAP2(vqshl_n_v, aarch64_neon_uqshl, aarch64_neon_sqshl, UnsignedAlts),
6119   NEONMAP2(vqshl_v, aarch64_neon_uqshl, aarch64_neon_sqshl, Add1ArgType | UnsignedAlts),
6120   NEONMAP2(vqshlq_n_v, aarch64_neon_uqshl, aarch64_neon_sqshl,UnsignedAlts),
6121   NEONMAP2(vqshlq_v, aarch64_neon_uqshl, aarch64_neon_sqshl, Add1ArgType | UnsignedAlts),
6122   NEONMAP1(vqshlu_n_v, aarch64_neon_sqshlu, 0),
6123   NEONMAP1(vqshluq_n_v, aarch64_neon_sqshlu, 0),
6124   NEONMAP2(vqsub_v, aarch64_neon_uqsub, aarch64_neon_sqsub, Add1ArgType | UnsignedAlts),
6125   NEONMAP2(vqsubq_v, aarch64_neon_uqsub, aarch64_neon_sqsub, Add1ArgType | UnsignedAlts),
6126   NEONMAP1(vraddhn_v, aarch64_neon_raddhn, Add1ArgType),
6127   NEONMAP1(vrax1q_v, aarch64_crypto_rax1, 0),
6128   NEONMAP2(vrecpe_v, aarch64_neon_frecpe, aarch64_neon_urecpe, 0),
6129   NEONMAP2(vrecpeq_v, aarch64_neon_frecpe, aarch64_neon_urecpe, 0),
6130   NEONMAP1(vrecps_v, aarch64_neon_frecps, Add1ArgType),
6131   NEONMAP1(vrecpsq_v, aarch64_neon_frecps, Add1ArgType),
6132   NEONMAP2(vrhadd_v, aarch64_neon_urhadd, aarch64_neon_srhadd, Add1ArgType | UnsignedAlts),
6133   NEONMAP2(vrhaddq_v, aarch64_neon_urhadd, aarch64_neon_srhadd, Add1ArgType | UnsignedAlts),
6134   NEONMAP1(vrnd32x_v, aarch64_neon_frint32x, Add1ArgType),
6135   NEONMAP1(vrnd32xq_v, aarch64_neon_frint32x, Add1ArgType),
6136   NEONMAP1(vrnd32z_v, aarch64_neon_frint32z, Add1ArgType),
6137   NEONMAP1(vrnd32zq_v, aarch64_neon_frint32z, Add1ArgType),
6138   NEONMAP1(vrnd64x_v, aarch64_neon_frint64x, Add1ArgType),
6139   NEONMAP1(vrnd64xq_v, aarch64_neon_frint64x, Add1ArgType),
6140   NEONMAP1(vrnd64z_v, aarch64_neon_frint64z, Add1ArgType),
6141   NEONMAP1(vrnd64zq_v, aarch64_neon_frint64z, Add1ArgType),
6142   NEONMAP0(vrndi_v),
6143   NEONMAP0(vrndiq_v),
6144   NEONMAP2(vrshl_v, aarch64_neon_urshl, aarch64_neon_srshl, Add1ArgType | UnsignedAlts),
6145   NEONMAP2(vrshlq_v, aarch64_neon_urshl, aarch64_neon_srshl, Add1ArgType | UnsignedAlts),
6146   NEONMAP2(vrshr_n_v, aarch64_neon_urshl, aarch64_neon_srshl, UnsignedAlts),
6147   NEONMAP2(vrshrq_n_v, aarch64_neon_urshl, aarch64_neon_srshl, UnsignedAlts),
6148   NEONMAP2(vrsqrte_v, aarch64_neon_frsqrte, aarch64_neon_ursqrte, 0),
6149   NEONMAP2(vrsqrteq_v, aarch64_neon_frsqrte, aarch64_neon_ursqrte, 0),
6150   NEONMAP1(vrsqrts_v, aarch64_neon_frsqrts, Add1ArgType),
6151   NEONMAP1(vrsqrtsq_v, aarch64_neon_frsqrts, Add1ArgType),
6152   NEONMAP1(vrsubhn_v, aarch64_neon_rsubhn, Add1ArgType),
6153   NEONMAP1(vsha1su0q_v, aarch64_crypto_sha1su0, 0),
6154   NEONMAP1(vsha1su1q_v, aarch64_crypto_sha1su1, 0),
6155   NEONMAP1(vsha256h2q_v, aarch64_crypto_sha256h2, 0),
6156   NEONMAP1(vsha256hq_v, aarch64_crypto_sha256h, 0),
6157   NEONMAP1(vsha256su0q_v, aarch64_crypto_sha256su0, 0),
6158   NEONMAP1(vsha256su1q_v, aarch64_crypto_sha256su1, 0),
6159   NEONMAP1(vsha512h2q_v, aarch64_crypto_sha512h2, 0),
6160   NEONMAP1(vsha512hq_v, aarch64_crypto_sha512h, 0),
6161   NEONMAP1(vsha512su0q_v, aarch64_crypto_sha512su0, 0),
6162   NEONMAP1(vsha512su1q_v, aarch64_crypto_sha512su1, 0),
6163   NEONMAP0(vshl_n_v),
6164   NEONMAP2(vshl_v, aarch64_neon_ushl, aarch64_neon_sshl, Add1ArgType | UnsignedAlts),
6165   NEONMAP0(vshll_n_v),
6166   NEONMAP0(vshlq_n_v),
6167   NEONMAP2(vshlq_v, aarch64_neon_ushl, aarch64_neon_sshl, Add1ArgType | UnsignedAlts),
6168   NEONMAP0(vshr_n_v),
6169   NEONMAP0(vshrn_n_v),
6170   NEONMAP0(vshrq_n_v),
6171   NEONMAP1(vsm3partw1q_v, aarch64_crypto_sm3partw1, 0),
6172   NEONMAP1(vsm3partw2q_v, aarch64_crypto_sm3partw2, 0),
6173   NEONMAP1(vsm3ss1q_v, aarch64_crypto_sm3ss1, 0),
6174   NEONMAP1(vsm3tt1aq_v, aarch64_crypto_sm3tt1a, 0),
6175   NEONMAP1(vsm3tt1bq_v, aarch64_crypto_sm3tt1b, 0),
6176   NEONMAP1(vsm3tt2aq_v, aarch64_crypto_sm3tt2a, 0),
6177   NEONMAP1(vsm3tt2bq_v, aarch64_crypto_sm3tt2b, 0),
6178   NEONMAP1(vsm4ekeyq_v, aarch64_crypto_sm4ekey, 0),
6179   NEONMAP1(vsm4eq_v, aarch64_crypto_sm4e, 0),
6180   NEONMAP1(vst1_x2_v, aarch64_neon_st1x2, 0),
6181   NEONMAP1(vst1_x3_v, aarch64_neon_st1x3, 0),
6182   NEONMAP1(vst1_x4_v, aarch64_neon_st1x4, 0),
6183   NEONMAP1(vst1q_x2_v, aarch64_neon_st1x2, 0),
6184   NEONMAP1(vst1q_x3_v, aarch64_neon_st1x3, 0),
6185   NEONMAP1(vst1q_x4_v, aarch64_neon_st1x4, 0),
6186   NEONMAP0(vsubhn_v),
6187   NEONMAP0(vtst_v),
6188   NEONMAP0(vtstq_v),
6189   NEONMAP1(vusdot_v, aarch64_neon_usdot, 0),
6190   NEONMAP1(vusdotq_v, aarch64_neon_usdot, 0),
6191   NEONMAP1(vusmmlaq_v, aarch64_neon_usmmla, 0),
6192   NEONMAP1(vxarq_v, aarch64_crypto_xar, 0),
6193 };
6194 
6195 static const ARMVectorIntrinsicInfo AArch64SISDIntrinsicMap[] = {
6196   NEONMAP1(vabdd_f64, aarch64_sisd_fabd, Add1ArgType),
6197   NEONMAP1(vabds_f32, aarch64_sisd_fabd, Add1ArgType),
6198   NEONMAP1(vabsd_s64, aarch64_neon_abs, Add1ArgType),
6199   NEONMAP1(vaddlv_s32, aarch64_neon_saddlv, AddRetType | Add1ArgType),
6200   NEONMAP1(vaddlv_u32, aarch64_neon_uaddlv, AddRetType | Add1ArgType),
6201   NEONMAP1(vaddlvq_s32, aarch64_neon_saddlv, AddRetType | Add1ArgType),
6202   NEONMAP1(vaddlvq_u32, aarch64_neon_uaddlv, AddRetType | Add1ArgType),
6203   NEONMAP1(vaddv_f32, aarch64_neon_faddv, AddRetType | Add1ArgType),
6204   NEONMAP1(vaddv_s32, aarch64_neon_saddv, AddRetType | Add1ArgType),
6205   NEONMAP1(vaddv_u32, aarch64_neon_uaddv, AddRetType | Add1ArgType),
6206   NEONMAP1(vaddvq_f32, aarch64_neon_faddv, AddRetType | Add1ArgType),
6207   NEONMAP1(vaddvq_f64, aarch64_neon_faddv, AddRetType | Add1ArgType),
6208   NEONMAP1(vaddvq_s32, aarch64_neon_saddv, AddRetType | Add1ArgType),
6209   NEONMAP1(vaddvq_s64, aarch64_neon_saddv, AddRetType | Add1ArgType),
6210   NEONMAP1(vaddvq_u32, aarch64_neon_uaddv, AddRetType | Add1ArgType),
6211   NEONMAP1(vaddvq_u64, aarch64_neon_uaddv, AddRetType | Add1ArgType),
6212   NEONMAP1(vcaged_f64, aarch64_neon_facge, AddRetType | Add1ArgType),
6213   NEONMAP1(vcages_f32, aarch64_neon_facge, AddRetType | Add1ArgType),
6214   NEONMAP1(vcagtd_f64, aarch64_neon_facgt, AddRetType | Add1ArgType),
6215   NEONMAP1(vcagts_f32, aarch64_neon_facgt, AddRetType | Add1ArgType),
6216   NEONMAP1(vcaled_f64, aarch64_neon_facge, AddRetType | Add1ArgType),
6217   NEONMAP1(vcales_f32, aarch64_neon_facge, AddRetType | Add1ArgType),
6218   NEONMAP1(vcaltd_f64, aarch64_neon_facgt, AddRetType | Add1ArgType),
6219   NEONMAP1(vcalts_f32, aarch64_neon_facgt, AddRetType | Add1ArgType),
6220   NEONMAP1(vcvtad_s64_f64, aarch64_neon_fcvtas, AddRetType | Add1ArgType),
6221   NEONMAP1(vcvtad_u64_f64, aarch64_neon_fcvtau, AddRetType | Add1ArgType),
6222   NEONMAP1(vcvtas_s32_f32, aarch64_neon_fcvtas, AddRetType | Add1ArgType),
6223   NEONMAP1(vcvtas_u32_f32, aarch64_neon_fcvtau, AddRetType | Add1ArgType),
6224   NEONMAP1(vcvtd_n_f64_s64, aarch64_neon_vcvtfxs2fp, AddRetType | Add1ArgType),
6225   NEONMAP1(vcvtd_n_f64_u64, aarch64_neon_vcvtfxu2fp, AddRetType | Add1ArgType),
6226   NEONMAP1(vcvtd_n_s64_f64, aarch64_neon_vcvtfp2fxs, AddRetType | Add1ArgType),
6227   NEONMAP1(vcvtd_n_u64_f64, aarch64_neon_vcvtfp2fxu, AddRetType | Add1ArgType),
6228   NEONMAP1(vcvtd_s64_f64, aarch64_neon_fcvtzs, AddRetType | Add1ArgType),
6229   NEONMAP1(vcvtd_u64_f64, aarch64_neon_fcvtzu, AddRetType | Add1ArgType),
6230   NEONMAP1(vcvth_bf16_f32, aarch64_neon_bfcvt, 0),
6231   NEONMAP1(vcvtmd_s64_f64, aarch64_neon_fcvtms, AddRetType | Add1ArgType),
6232   NEONMAP1(vcvtmd_u64_f64, aarch64_neon_fcvtmu, AddRetType | Add1ArgType),
6233   NEONMAP1(vcvtms_s32_f32, aarch64_neon_fcvtms, AddRetType | Add1ArgType),
6234   NEONMAP1(vcvtms_u32_f32, aarch64_neon_fcvtmu, AddRetType | Add1ArgType),
6235   NEONMAP1(vcvtnd_s64_f64, aarch64_neon_fcvtns, AddRetType | Add1ArgType),
6236   NEONMAP1(vcvtnd_u64_f64, aarch64_neon_fcvtnu, AddRetType | Add1ArgType),
6237   NEONMAP1(vcvtns_s32_f32, aarch64_neon_fcvtns, AddRetType | Add1ArgType),
6238   NEONMAP1(vcvtns_u32_f32, aarch64_neon_fcvtnu, AddRetType | Add1ArgType),
6239   NEONMAP1(vcvtpd_s64_f64, aarch64_neon_fcvtps, AddRetType | Add1ArgType),
6240   NEONMAP1(vcvtpd_u64_f64, aarch64_neon_fcvtpu, AddRetType | Add1ArgType),
6241   NEONMAP1(vcvtps_s32_f32, aarch64_neon_fcvtps, AddRetType | Add1ArgType),
6242   NEONMAP1(vcvtps_u32_f32, aarch64_neon_fcvtpu, AddRetType | Add1ArgType),
6243   NEONMAP1(vcvts_n_f32_s32, aarch64_neon_vcvtfxs2fp, AddRetType | Add1ArgType),
6244   NEONMAP1(vcvts_n_f32_u32, aarch64_neon_vcvtfxu2fp, AddRetType | Add1ArgType),
6245   NEONMAP1(vcvts_n_s32_f32, aarch64_neon_vcvtfp2fxs, AddRetType | Add1ArgType),
6246   NEONMAP1(vcvts_n_u32_f32, aarch64_neon_vcvtfp2fxu, AddRetType | Add1ArgType),
6247   NEONMAP1(vcvts_s32_f32, aarch64_neon_fcvtzs, AddRetType | Add1ArgType),
6248   NEONMAP1(vcvts_u32_f32, aarch64_neon_fcvtzu, AddRetType | Add1ArgType),
6249   NEONMAP1(vcvtxd_f32_f64, aarch64_sisd_fcvtxn, 0),
6250   NEONMAP1(vmaxnmv_f32, aarch64_neon_fmaxnmv, AddRetType | Add1ArgType),
6251   NEONMAP1(vmaxnmvq_f32, aarch64_neon_fmaxnmv, AddRetType | Add1ArgType),
6252   NEONMAP1(vmaxnmvq_f64, aarch64_neon_fmaxnmv, AddRetType | Add1ArgType),
6253   NEONMAP1(vmaxv_f32, aarch64_neon_fmaxv, AddRetType | Add1ArgType),
6254   NEONMAP1(vmaxv_s32, aarch64_neon_smaxv, AddRetType | Add1ArgType),
6255   NEONMAP1(vmaxv_u32, aarch64_neon_umaxv, AddRetType | Add1ArgType),
6256   NEONMAP1(vmaxvq_f32, aarch64_neon_fmaxv, AddRetType | Add1ArgType),
6257   NEONMAP1(vmaxvq_f64, aarch64_neon_fmaxv, AddRetType | Add1ArgType),
6258   NEONMAP1(vmaxvq_s32, aarch64_neon_smaxv, AddRetType | Add1ArgType),
6259   NEONMAP1(vmaxvq_u32, aarch64_neon_umaxv, AddRetType | Add1ArgType),
6260   NEONMAP1(vminnmv_f32, aarch64_neon_fminnmv, AddRetType | Add1ArgType),
6261   NEONMAP1(vminnmvq_f32, aarch64_neon_fminnmv, AddRetType | Add1ArgType),
6262   NEONMAP1(vminnmvq_f64, aarch64_neon_fminnmv, AddRetType | Add1ArgType),
6263   NEONMAP1(vminv_f32, aarch64_neon_fminv, AddRetType | Add1ArgType),
6264   NEONMAP1(vminv_s32, aarch64_neon_sminv, AddRetType | Add1ArgType),
6265   NEONMAP1(vminv_u32, aarch64_neon_uminv, AddRetType | Add1ArgType),
6266   NEONMAP1(vminvq_f32, aarch64_neon_fminv, AddRetType | Add1ArgType),
6267   NEONMAP1(vminvq_f64, aarch64_neon_fminv, AddRetType | Add1ArgType),
6268   NEONMAP1(vminvq_s32, aarch64_neon_sminv, AddRetType | Add1ArgType),
6269   NEONMAP1(vminvq_u32, aarch64_neon_uminv, AddRetType | Add1ArgType),
6270   NEONMAP1(vmull_p64, aarch64_neon_pmull64, 0),
6271   NEONMAP1(vmulxd_f64, aarch64_neon_fmulx, Add1ArgType),
6272   NEONMAP1(vmulxs_f32, aarch64_neon_fmulx, Add1ArgType),
6273   NEONMAP1(vpaddd_s64, aarch64_neon_uaddv, AddRetType | Add1ArgType),
6274   NEONMAP1(vpaddd_u64, aarch64_neon_uaddv, AddRetType | Add1ArgType),
6275   NEONMAP1(vpmaxnmqd_f64, aarch64_neon_fmaxnmv, AddRetType | Add1ArgType),
6276   NEONMAP1(vpmaxnms_f32, aarch64_neon_fmaxnmv, AddRetType | Add1ArgType),
6277   NEONMAP1(vpmaxqd_f64, aarch64_neon_fmaxv, AddRetType | Add1ArgType),
6278   NEONMAP1(vpmaxs_f32, aarch64_neon_fmaxv, AddRetType | Add1ArgType),
6279   NEONMAP1(vpminnmqd_f64, aarch64_neon_fminnmv, AddRetType | Add1ArgType),
6280   NEONMAP1(vpminnms_f32, aarch64_neon_fminnmv, AddRetType | Add1ArgType),
6281   NEONMAP1(vpminqd_f64, aarch64_neon_fminv, AddRetType | Add1ArgType),
6282   NEONMAP1(vpmins_f32, aarch64_neon_fminv, AddRetType | Add1ArgType),
6283   NEONMAP1(vqabsb_s8, aarch64_neon_sqabs, Vectorize1ArgType | Use64BitVectors),
6284   NEONMAP1(vqabsd_s64, aarch64_neon_sqabs, Add1ArgType),
6285   NEONMAP1(vqabsh_s16, aarch64_neon_sqabs, Vectorize1ArgType | Use64BitVectors),
6286   NEONMAP1(vqabss_s32, aarch64_neon_sqabs, Add1ArgType),
6287   NEONMAP1(vqaddb_s8, aarch64_neon_sqadd, Vectorize1ArgType | Use64BitVectors),
6288   NEONMAP1(vqaddb_u8, aarch64_neon_uqadd, Vectorize1ArgType | Use64BitVectors),
6289   NEONMAP1(vqaddd_s64, aarch64_neon_sqadd, Add1ArgType),
6290   NEONMAP1(vqaddd_u64, aarch64_neon_uqadd, Add1ArgType),
6291   NEONMAP1(vqaddh_s16, aarch64_neon_sqadd, Vectorize1ArgType | Use64BitVectors),
6292   NEONMAP1(vqaddh_u16, aarch64_neon_uqadd, Vectorize1ArgType | Use64BitVectors),
6293   NEONMAP1(vqadds_s32, aarch64_neon_sqadd, Add1ArgType),
6294   NEONMAP1(vqadds_u32, aarch64_neon_uqadd, Add1ArgType),
6295   NEONMAP1(vqdmulhh_s16, aarch64_neon_sqdmulh, Vectorize1ArgType | Use64BitVectors),
6296   NEONMAP1(vqdmulhs_s32, aarch64_neon_sqdmulh, Add1ArgType),
6297   NEONMAP1(vqdmullh_s16, aarch64_neon_sqdmull, VectorRet | Use128BitVectors),
6298   NEONMAP1(vqdmulls_s32, aarch64_neon_sqdmulls_scalar, 0),
6299   NEONMAP1(vqmovnd_s64, aarch64_neon_scalar_sqxtn, AddRetType | Add1ArgType),
6300   NEONMAP1(vqmovnd_u64, aarch64_neon_scalar_uqxtn, AddRetType | Add1ArgType),
6301   NEONMAP1(vqmovnh_s16, aarch64_neon_sqxtn, VectorRet | Use64BitVectors),
6302   NEONMAP1(vqmovnh_u16, aarch64_neon_uqxtn, VectorRet | Use64BitVectors),
6303   NEONMAP1(vqmovns_s32, aarch64_neon_sqxtn, VectorRet | Use64BitVectors),
6304   NEONMAP1(vqmovns_u32, aarch64_neon_uqxtn, VectorRet | Use64BitVectors),
6305   NEONMAP1(vqmovund_s64, aarch64_neon_scalar_sqxtun, AddRetType | Add1ArgType),
6306   NEONMAP1(vqmovunh_s16, aarch64_neon_sqxtun, VectorRet | Use64BitVectors),
6307   NEONMAP1(vqmovuns_s32, aarch64_neon_sqxtun, VectorRet | Use64BitVectors),
6308   NEONMAP1(vqnegb_s8, aarch64_neon_sqneg, Vectorize1ArgType | Use64BitVectors),
6309   NEONMAP1(vqnegd_s64, aarch64_neon_sqneg, Add1ArgType),
6310   NEONMAP1(vqnegh_s16, aarch64_neon_sqneg, Vectorize1ArgType | Use64BitVectors),
6311   NEONMAP1(vqnegs_s32, aarch64_neon_sqneg, Add1ArgType),
6312   NEONMAP1(vqrdmlahh_s16, aarch64_neon_sqrdmlah, Vectorize1ArgType | Use64BitVectors),
6313   NEONMAP1(vqrdmlahs_s32, aarch64_neon_sqrdmlah, Add1ArgType),
6314   NEONMAP1(vqrdmlshh_s16, aarch64_neon_sqrdmlsh, Vectorize1ArgType | Use64BitVectors),
6315   NEONMAP1(vqrdmlshs_s32, aarch64_neon_sqrdmlsh, Add1ArgType),
6316   NEONMAP1(vqrdmulhh_s16, aarch64_neon_sqrdmulh, Vectorize1ArgType | Use64BitVectors),
6317   NEONMAP1(vqrdmulhs_s32, aarch64_neon_sqrdmulh, Add1ArgType),
6318   NEONMAP1(vqrshlb_s8, aarch64_neon_sqrshl, Vectorize1ArgType | Use64BitVectors),
6319   NEONMAP1(vqrshlb_u8, aarch64_neon_uqrshl, Vectorize1ArgType | Use64BitVectors),
6320   NEONMAP1(vqrshld_s64, aarch64_neon_sqrshl, Add1ArgType),
6321   NEONMAP1(vqrshld_u64, aarch64_neon_uqrshl, Add1ArgType),
6322   NEONMAP1(vqrshlh_s16, aarch64_neon_sqrshl, Vectorize1ArgType | Use64BitVectors),
6323   NEONMAP1(vqrshlh_u16, aarch64_neon_uqrshl, Vectorize1ArgType | Use64BitVectors),
6324   NEONMAP1(vqrshls_s32, aarch64_neon_sqrshl, Add1ArgType),
6325   NEONMAP1(vqrshls_u32, aarch64_neon_uqrshl, Add1ArgType),
6326   NEONMAP1(vqrshrnd_n_s64, aarch64_neon_sqrshrn, AddRetType),
6327   NEONMAP1(vqrshrnd_n_u64, aarch64_neon_uqrshrn, AddRetType),
6328   NEONMAP1(vqrshrnh_n_s16, aarch64_neon_sqrshrn, VectorRet | Use64BitVectors),
6329   NEONMAP1(vqrshrnh_n_u16, aarch64_neon_uqrshrn, VectorRet | Use64BitVectors),
6330   NEONMAP1(vqrshrns_n_s32, aarch64_neon_sqrshrn, VectorRet | Use64BitVectors),
6331   NEONMAP1(vqrshrns_n_u32, aarch64_neon_uqrshrn, VectorRet | Use64BitVectors),
6332   NEONMAP1(vqrshrund_n_s64, aarch64_neon_sqrshrun, AddRetType),
6333   NEONMAP1(vqrshrunh_n_s16, aarch64_neon_sqrshrun, VectorRet | Use64BitVectors),
6334   NEONMAP1(vqrshruns_n_s32, aarch64_neon_sqrshrun, VectorRet | Use64BitVectors),
6335   NEONMAP1(vqshlb_n_s8, aarch64_neon_sqshl, Vectorize1ArgType | Use64BitVectors),
6336   NEONMAP1(vqshlb_n_u8, aarch64_neon_uqshl, Vectorize1ArgType | Use64BitVectors),
6337   NEONMAP1(vqshlb_s8, aarch64_neon_sqshl, Vectorize1ArgType | Use64BitVectors),
6338   NEONMAP1(vqshlb_u8, aarch64_neon_uqshl, Vectorize1ArgType | Use64BitVectors),
6339   NEONMAP1(vqshld_s64, aarch64_neon_sqshl, Add1ArgType),
6340   NEONMAP1(vqshld_u64, aarch64_neon_uqshl, Add1ArgType),
6341   NEONMAP1(vqshlh_n_s16, aarch64_neon_sqshl, Vectorize1ArgType | Use64BitVectors),
6342   NEONMAP1(vqshlh_n_u16, aarch64_neon_uqshl, Vectorize1ArgType | Use64BitVectors),
6343   NEONMAP1(vqshlh_s16, aarch64_neon_sqshl, Vectorize1ArgType | Use64BitVectors),
6344   NEONMAP1(vqshlh_u16, aarch64_neon_uqshl, Vectorize1ArgType | Use64BitVectors),
6345   NEONMAP1(vqshls_n_s32, aarch64_neon_sqshl, Add1ArgType),
6346   NEONMAP1(vqshls_n_u32, aarch64_neon_uqshl, Add1ArgType),
6347   NEONMAP1(vqshls_s32, aarch64_neon_sqshl, Add1ArgType),
6348   NEONMAP1(vqshls_u32, aarch64_neon_uqshl, Add1ArgType),
6349   NEONMAP1(vqshlub_n_s8, aarch64_neon_sqshlu, Vectorize1ArgType | Use64BitVectors),
6350   NEONMAP1(vqshluh_n_s16, aarch64_neon_sqshlu, Vectorize1ArgType | Use64BitVectors),
6351   NEONMAP1(vqshlus_n_s32, aarch64_neon_sqshlu, Add1ArgType),
6352   NEONMAP1(vqshrnd_n_s64, aarch64_neon_sqshrn, AddRetType),
6353   NEONMAP1(vqshrnd_n_u64, aarch64_neon_uqshrn, AddRetType),
6354   NEONMAP1(vqshrnh_n_s16, aarch64_neon_sqshrn, VectorRet | Use64BitVectors),
6355   NEONMAP1(vqshrnh_n_u16, aarch64_neon_uqshrn, VectorRet | Use64BitVectors),
6356   NEONMAP1(vqshrns_n_s32, aarch64_neon_sqshrn, VectorRet | Use64BitVectors),
6357   NEONMAP1(vqshrns_n_u32, aarch64_neon_uqshrn, VectorRet | Use64BitVectors),
6358   NEONMAP1(vqshrund_n_s64, aarch64_neon_sqshrun, AddRetType),
6359   NEONMAP1(vqshrunh_n_s16, aarch64_neon_sqshrun, VectorRet | Use64BitVectors),
6360   NEONMAP1(vqshruns_n_s32, aarch64_neon_sqshrun, VectorRet | Use64BitVectors),
6361   NEONMAP1(vqsubb_s8, aarch64_neon_sqsub, Vectorize1ArgType | Use64BitVectors),
6362   NEONMAP1(vqsubb_u8, aarch64_neon_uqsub, Vectorize1ArgType | Use64BitVectors),
6363   NEONMAP1(vqsubd_s64, aarch64_neon_sqsub, Add1ArgType),
6364   NEONMAP1(vqsubd_u64, aarch64_neon_uqsub, Add1ArgType),
6365   NEONMAP1(vqsubh_s16, aarch64_neon_sqsub, Vectorize1ArgType | Use64BitVectors),
6366   NEONMAP1(vqsubh_u16, aarch64_neon_uqsub, Vectorize1ArgType | Use64BitVectors),
6367   NEONMAP1(vqsubs_s32, aarch64_neon_sqsub, Add1ArgType),
6368   NEONMAP1(vqsubs_u32, aarch64_neon_uqsub, Add1ArgType),
6369   NEONMAP1(vrecped_f64, aarch64_neon_frecpe, Add1ArgType),
6370   NEONMAP1(vrecpes_f32, aarch64_neon_frecpe, Add1ArgType),
6371   NEONMAP1(vrecpxd_f64, aarch64_neon_frecpx, Add1ArgType),
6372   NEONMAP1(vrecpxs_f32, aarch64_neon_frecpx, Add1ArgType),
6373   NEONMAP1(vrshld_s64, aarch64_neon_srshl, Add1ArgType),
6374   NEONMAP1(vrshld_u64, aarch64_neon_urshl, Add1ArgType),
6375   NEONMAP1(vrsqrted_f64, aarch64_neon_frsqrte, Add1ArgType),
6376   NEONMAP1(vrsqrtes_f32, aarch64_neon_frsqrte, Add1ArgType),
6377   NEONMAP1(vrsqrtsd_f64, aarch64_neon_frsqrts, Add1ArgType),
6378   NEONMAP1(vrsqrtss_f32, aarch64_neon_frsqrts, Add1ArgType),
6379   NEONMAP1(vsha1cq_u32, aarch64_crypto_sha1c, 0),
6380   NEONMAP1(vsha1h_u32, aarch64_crypto_sha1h, 0),
6381   NEONMAP1(vsha1mq_u32, aarch64_crypto_sha1m, 0),
6382   NEONMAP1(vsha1pq_u32, aarch64_crypto_sha1p, 0),
6383   NEONMAP1(vshld_s64, aarch64_neon_sshl, Add1ArgType),
6384   NEONMAP1(vshld_u64, aarch64_neon_ushl, Add1ArgType),
6385   NEONMAP1(vslid_n_s64, aarch64_neon_vsli, Vectorize1ArgType),
6386   NEONMAP1(vslid_n_u64, aarch64_neon_vsli, Vectorize1ArgType),
6387   NEONMAP1(vsqaddb_u8, aarch64_neon_usqadd, Vectorize1ArgType | Use64BitVectors),
6388   NEONMAP1(vsqaddd_u64, aarch64_neon_usqadd, Add1ArgType),
6389   NEONMAP1(vsqaddh_u16, aarch64_neon_usqadd, Vectorize1ArgType | Use64BitVectors),
6390   NEONMAP1(vsqadds_u32, aarch64_neon_usqadd, Add1ArgType),
6391   NEONMAP1(vsrid_n_s64, aarch64_neon_vsri, Vectorize1ArgType),
6392   NEONMAP1(vsrid_n_u64, aarch64_neon_vsri, Vectorize1ArgType),
6393   NEONMAP1(vuqaddb_s8, aarch64_neon_suqadd, Vectorize1ArgType | Use64BitVectors),
6394   NEONMAP1(vuqaddd_s64, aarch64_neon_suqadd, Add1ArgType),
6395   NEONMAP1(vuqaddh_s16, aarch64_neon_suqadd, Vectorize1ArgType | Use64BitVectors),
6396   NEONMAP1(vuqadds_s32, aarch64_neon_suqadd, Add1ArgType),
6397   // FP16 scalar intrinisics go here.
6398   NEONMAP1(vabdh_f16, aarch64_sisd_fabd, Add1ArgType),
6399   NEONMAP1(vcvtah_s32_f16, aarch64_neon_fcvtas, AddRetType | Add1ArgType),
6400   NEONMAP1(vcvtah_s64_f16, aarch64_neon_fcvtas, AddRetType | Add1ArgType),
6401   NEONMAP1(vcvtah_u32_f16, aarch64_neon_fcvtau, AddRetType | Add1ArgType),
6402   NEONMAP1(vcvtah_u64_f16, aarch64_neon_fcvtau, AddRetType | Add1ArgType),
6403   NEONMAP1(vcvth_n_f16_s32, aarch64_neon_vcvtfxs2fp, AddRetType | Add1ArgType),
6404   NEONMAP1(vcvth_n_f16_s64, aarch64_neon_vcvtfxs2fp, AddRetType | Add1ArgType),
6405   NEONMAP1(vcvth_n_f16_u32, aarch64_neon_vcvtfxu2fp, AddRetType | Add1ArgType),
6406   NEONMAP1(vcvth_n_f16_u64, aarch64_neon_vcvtfxu2fp, AddRetType | Add1ArgType),
6407   NEONMAP1(vcvth_n_s32_f16, aarch64_neon_vcvtfp2fxs, AddRetType | Add1ArgType),
6408   NEONMAP1(vcvth_n_s64_f16, aarch64_neon_vcvtfp2fxs, AddRetType | Add1ArgType),
6409   NEONMAP1(vcvth_n_u32_f16, aarch64_neon_vcvtfp2fxu, AddRetType | Add1ArgType),
6410   NEONMAP1(vcvth_n_u64_f16, aarch64_neon_vcvtfp2fxu, AddRetType | Add1ArgType),
6411   NEONMAP1(vcvth_s32_f16, aarch64_neon_fcvtzs, AddRetType | Add1ArgType),
6412   NEONMAP1(vcvth_s64_f16, aarch64_neon_fcvtzs, AddRetType | Add1ArgType),
6413   NEONMAP1(vcvth_u32_f16, aarch64_neon_fcvtzu, AddRetType | Add1ArgType),
6414   NEONMAP1(vcvth_u64_f16, aarch64_neon_fcvtzu, AddRetType | Add1ArgType),
6415   NEONMAP1(vcvtmh_s32_f16, aarch64_neon_fcvtms, AddRetType | Add1ArgType),
6416   NEONMAP1(vcvtmh_s64_f16, aarch64_neon_fcvtms, AddRetType | Add1ArgType),
6417   NEONMAP1(vcvtmh_u32_f16, aarch64_neon_fcvtmu, AddRetType | Add1ArgType),
6418   NEONMAP1(vcvtmh_u64_f16, aarch64_neon_fcvtmu, AddRetType | Add1ArgType),
6419   NEONMAP1(vcvtnh_s32_f16, aarch64_neon_fcvtns, AddRetType | Add1ArgType),
6420   NEONMAP1(vcvtnh_s64_f16, aarch64_neon_fcvtns, AddRetType | Add1ArgType),
6421   NEONMAP1(vcvtnh_u32_f16, aarch64_neon_fcvtnu, AddRetType | Add1ArgType),
6422   NEONMAP1(vcvtnh_u64_f16, aarch64_neon_fcvtnu, AddRetType | Add1ArgType),
6423   NEONMAP1(vcvtph_s32_f16, aarch64_neon_fcvtps, AddRetType | Add1ArgType),
6424   NEONMAP1(vcvtph_s64_f16, aarch64_neon_fcvtps, AddRetType | Add1ArgType),
6425   NEONMAP1(vcvtph_u32_f16, aarch64_neon_fcvtpu, AddRetType | Add1ArgType),
6426   NEONMAP1(vcvtph_u64_f16, aarch64_neon_fcvtpu, AddRetType | Add1ArgType),
6427   NEONMAP1(vmulxh_f16, aarch64_neon_fmulx, Add1ArgType),
6428   NEONMAP1(vrecpeh_f16, aarch64_neon_frecpe, Add1ArgType),
6429   NEONMAP1(vrecpxh_f16, aarch64_neon_frecpx, Add1ArgType),
6430   NEONMAP1(vrsqrteh_f16, aarch64_neon_frsqrte, Add1ArgType),
6431   NEONMAP1(vrsqrtsh_f16, aarch64_neon_frsqrts, Add1ArgType),
6432 };
6433 
6434 #undef NEONMAP0
6435 #undef NEONMAP1
6436 #undef NEONMAP2
6437 
6438 #define SVEMAP1(NameBase, LLVMIntrinsic, TypeModifier)                         \
6439   {                                                                            \
6440     #NameBase, SVE::BI__builtin_sve_##NameBase, Intrinsic::LLVMIntrinsic, 0,   \
6441         TypeModifier                                                           \
6442   }
6443 
6444 #define SVEMAP2(NameBase, TypeModifier)                                        \
6445   { #NameBase, SVE::BI__builtin_sve_##NameBase, 0, 0, TypeModifier }
6446 static const ARMVectorIntrinsicInfo AArch64SVEIntrinsicMap[] = {
6447 #define GET_SVE_LLVM_INTRINSIC_MAP
6448 #include "clang/Basic/arm_sve_builtin_cg.inc"
6449 #include "clang/Basic/BuiltinsAArch64NeonSVEBridge_cg.def"
6450 #undef GET_SVE_LLVM_INTRINSIC_MAP
6451 };
6452 
6453 #undef SVEMAP1
6454 #undef SVEMAP2
6455 
6456 static bool NEONSIMDIntrinsicsProvenSorted = false;
6457 
6458 static bool AArch64SIMDIntrinsicsProvenSorted = false;
6459 static bool AArch64SISDIntrinsicsProvenSorted = false;
6460 static bool AArch64SVEIntrinsicsProvenSorted = false;
6461 
6462 static const ARMVectorIntrinsicInfo *
6463 findARMVectorIntrinsicInMap(ArrayRef<ARMVectorIntrinsicInfo> IntrinsicMap,
6464                             unsigned BuiltinID, bool &MapProvenSorted) {
6465 
6466 #ifndef NDEBUG
6467   if (!MapProvenSorted) {
6468     assert(llvm::is_sorted(IntrinsicMap));
6469     MapProvenSorted = true;
6470   }
6471 #endif
6472 
6473   const ARMVectorIntrinsicInfo *Builtin =
6474       llvm::lower_bound(IntrinsicMap, BuiltinID);
6475 
6476   if (Builtin != IntrinsicMap.end() && Builtin->BuiltinID == BuiltinID)
6477     return Builtin;
6478 
6479   return nullptr;
6480 }
6481 
6482 Function *CodeGenFunction::LookupNeonLLVMIntrinsic(unsigned IntrinsicID,
6483                                                    unsigned Modifier,
6484                                                    llvm::Type *ArgType,
6485                                                    const CallExpr *E) {
6486   int VectorSize = 0;
6487   if (Modifier & Use64BitVectors)
6488     VectorSize = 64;
6489   else if (Modifier & Use128BitVectors)
6490     VectorSize = 128;
6491 
6492   // Return type.
6493   SmallVector<llvm::Type *, 3> Tys;
6494   if (Modifier & AddRetType) {
6495     llvm::Type *Ty = ConvertType(E->getCallReturnType(getContext()));
6496     if (Modifier & VectorizeRetType)
6497       Ty = llvm::FixedVectorType::get(
6498           Ty, VectorSize ? VectorSize / Ty->getPrimitiveSizeInBits() : 1);
6499 
6500     Tys.push_back(Ty);
6501   }
6502 
6503   // Arguments.
6504   if (Modifier & VectorizeArgTypes) {
6505     int Elts = VectorSize ? VectorSize / ArgType->getPrimitiveSizeInBits() : 1;
6506     ArgType = llvm::FixedVectorType::get(ArgType, Elts);
6507   }
6508 
6509   if (Modifier & (Add1ArgType | Add2ArgTypes))
6510     Tys.push_back(ArgType);
6511 
6512   if (Modifier & Add2ArgTypes)
6513     Tys.push_back(ArgType);
6514 
6515   if (Modifier & InventFloatType)
6516     Tys.push_back(FloatTy);
6517 
6518   return CGM.getIntrinsic(IntrinsicID, Tys);
6519 }
6520 
6521 static Value *EmitCommonNeonSISDBuiltinExpr(
6522     CodeGenFunction &CGF, const ARMVectorIntrinsicInfo &SISDInfo,
6523     SmallVectorImpl<Value *> &Ops, const CallExpr *E) {
6524   unsigned BuiltinID = SISDInfo.BuiltinID;
6525   unsigned int Int = SISDInfo.LLVMIntrinsic;
6526   unsigned Modifier = SISDInfo.TypeModifier;
6527   const char *s = SISDInfo.NameHint;
6528 
6529   switch (BuiltinID) {
6530   case NEON::BI__builtin_neon_vcled_s64:
6531   case NEON::BI__builtin_neon_vcled_u64:
6532   case NEON::BI__builtin_neon_vcles_f32:
6533   case NEON::BI__builtin_neon_vcled_f64:
6534   case NEON::BI__builtin_neon_vcltd_s64:
6535   case NEON::BI__builtin_neon_vcltd_u64:
6536   case NEON::BI__builtin_neon_vclts_f32:
6537   case NEON::BI__builtin_neon_vcltd_f64:
6538   case NEON::BI__builtin_neon_vcales_f32:
6539   case NEON::BI__builtin_neon_vcaled_f64:
6540   case NEON::BI__builtin_neon_vcalts_f32:
6541   case NEON::BI__builtin_neon_vcaltd_f64:
6542     // Only one direction of comparisons actually exist, cmle is actually a cmge
6543     // with swapped operands. The table gives us the right intrinsic but we
6544     // still need to do the swap.
6545     std::swap(Ops[0], Ops[1]);
6546     break;
6547   }
6548 
6549   assert(Int && "Generic code assumes a valid intrinsic");
6550 
6551   // Determine the type(s) of this overloaded AArch64 intrinsic.
6552   const Expr *Arg = E->getArg(0);
6553   llvm::Type *ArgTy = CGF.ConvertType(Arg->getType());
6554   Function *F = CGF.LookupNeonLLVMIntrinsic(Int, Modifier, ArgTy, E);
6555 
6556   int j = 0;
6557   ConstantInt *C0 = ConstantInt::get(CGF.SizeTy, 0);
6558   for (Function::const_arg_iterator ai = F->arg_begin(), ae = F->arg_end();
6559        ai != ae; ++ai, ++j) {
6560     llvm::Type *ArgTy = ai->getType();
6561     if (Ops[j]->getType()->getPrimitiveSizeInBits() ==
6562              ArgTy->getPrimitiveSizeInBits())
6563       continue;
6564 
6565     assert(ArgTy->isVectorTy() && !Ops[j]->getType()->isVectorTy());
6566     // The constant argument to an _n_ intrinsic always has Int32Ty, so truncate
6567     // it before inserting.
6568     Ops[j] = CGF.Builder.CreateTruncOrBitCast(
6569         Ops[j], cast<llvm::VectorType>(ArgTy)->getElementType());
6570     Ops[j] =
6571         CGF.Builder.CreateInsertElement(UndefValue::get(ArgTy), Ops[j], C0);
6572   }
6573 
6574   Value *Result = CGF.EmitNeonCall(F, Ops, s);
6575   llvm::Type *ResultType = CGF.ConvertType(E->getType());
6576   if (ResultType->getPrimitiveSizeInBits().getFixedSize() <
6577       Result->getType()->getPrimitiveSizeInBits().getFixedSize())
6578     return CGF.Builder.CreateExtractElement(Result, C0);
6579 
6580   return CGF.Builder.CreateBitCast(Result, ResultType, s);
6581 }
6582 
6583 Value *CodeGenFunction::EmitCommonNeonBuiltinExpr(
6584     unsigned BuiltinID, unsigned LLVMIntrinsic, unsigned AltLLVMIntrinsic,
6585     const char *NameHint, unsigned Modifier, const CallExpr *E,
6586     SmallVectorImpl<llvm::Value *> &Ops, Address PtrOp0, Address PtrOp1,
6587     llvm::Triple::ArchType Arch) {
6588   // Get the last argument, which specifies the vector type.
6589   const Expr *Arg = E->getArg(E->getNumArgs() - 1);
6590   Optional<llvm::APSInt> NeonTypeConst =
6591       Arg->getIntegerConstantExpr(getContext());
6592   if (!NeonTypeConst)
6593     return nullptr;
6594 
6595   // Determine the type of this overloaded NEON intrinsic.
6596   NeonTypeFlags Type(NeonTypeConst->getZExtValue());
6597   bool Usgn = Type.isUnsigned();
6598   bool Quad = Type.isQuad();
6599   const bool HasLegalHalfType = getTarget().hasLegalHalfType();
6600   const bool AllowBFloatArgsAndRet =
6601       getTargetHooks().getABIInfo().allowBFloatArgsAndRet();
6602 
6603   llvm::FixedVectorType *VTy =
6604       GetNeonType(this, Type, HasLegalHalfType, false, AllowBFloatArgsAndRet);
6605   llvm::Type *Ty = VTy;
6606   if (!Ty)
6607     return nullptr;
6608 
6609   auto getAlignmentValue32 = [&](Address addr) -> Value* {
6610     return Builder.getInt32(addr.getAlignment().getQuantity());
6611   };
6612 
6613   unsigned Int = LLVMIntrinsic;
6614   if ((Modifier & UnsignedAlts) && !Usgn)
6615     Int = AltLLVMIntrinsic;
6616 
6617   switch (BuiltinID) {
6618   default: break;
6619   case NEON::BI__builtin_neon_splat_lane_v:
6620   case NEON::BI__builtin_neon_splat_laneq_v:
6621   case NEON::BI__builtin_neon_splatq_lane_v:
6622   case NEON::BI__builtin_neon_splatq_laneq_v: {
6623     auto NumElements = VTy->getElementCount();
6624     if (BuiltinID == NEON::BI__builtin_neon_splatq_lane_v)
6625       NumElements = NumElements * 2;
6626     if (BuiltinID == NEON::BI__builtin_neon_splat_laneq_v)
6627       NumElements = NumElements.divideCoefficientBy(2);
6628 
6629     Ops[0] = Builder.CreateBitCast(Ops[0], VTy);
6630     return EmitNeonSplat(Ops[0], cast<ConstantInt>(Ops[1]), NumElements);
6631   }
6632   case NEON::BI__builtin_neon_vpadd_v:
6633   case NEON::BI__builtin_neon_vpaddq_v:
6634     // We don't allow fp/int overloading of intrinsics.
6635     if (VTy->getElementType()->isFloatingPointTy() &&
6636         Int == Intrinsic::aarch64_neon_addp)
6637       Int = Intrinsic::aarch64_neon_faddp;
6638     break;
6639   case NEON::BI__builtin_neon_vabs_v:
6640   case NEON::BI__builtin_neon_vabsq_v:
6641     if (VTy->getElementType()->isFloatingPointTy())
6642       return EmitNeonCall(CGM.getIntrinsic(Intrinsic::fabs, Ty), Ops, "vabs");
6643     return EmitNeonCall(CGM.getIntrinsic(LLVMIntrinsic, Ty), Ops, "vabs");
6644   case NEON::BI__builtin_neon_vadd_v:
6645   case NEON::BI__builtin_neon_vaddq_v: {
6646     llvm::Type *VTy = llvm::FixedVectorType::get(Int8Ty, Quad ? 16 : 8);
6647     Ops[0] = Builder.CreateBitCast(Ops[0], VTy);
6648     Ops[1] = Builder.CreateBitCast(Ops[1], VTy);
6649     Ops[0] =  Builder.CreateXor(Ops[0], Ops[1]);
6650     return Builder.CreateBitCast(Ops[0], Ty);
6651   }
6652   case NEON::BI__builtin_neon_vaddhn_v: {
6653     llvm::FixedVectorType *SrcTy =
6654         llvm::FixedVectorType::getExtendedElementVectorType(VTy);
6655 
6656     // %sum = add <4 x i32> %lhs, %rhs
6657     Ops[0] = Builder.CreateBitCast(Ops[0], SrcTy);
6658     Ops[1] = Builder.CreateBitCast(Ops[1], SrcTy);
6659     Ops[0] = Builder.CreateAdd(Ops[0], Ops[1], "vaddhn");
6660 
6661     // %high = lshr <4 x i32> %sum, <i32 16, i32 16, i32 16, i32 16>
6662     Constant *ShiftAmt =
6663         ConstantInt::get(SrcTy, SrcTy->getScalarSizeInBits() / 2);
6664     Ops[0] = Builder.CreateLShr(Ops[0], ShiftAmt, "vaddhn");
6665 
6666     // %res = trunc <4 x i32> %high to <4 x i16>
6667     return Builder.CreateTrunc(Ops[0], VTy, "vaddhn");
6668   }
6669   case NEON::BI__builtin_neon_vcale_v:
6670   case NEON::BI__builtin_neon_vcaleq_v:
6671   case NEON::BI__builtin_neon_vcalt_v:
6672   case NEON::BI__builtin_neon_vcaltq_v:
6673     std::swap(Ops[0], Ops[1]);
6674     LLVM_FALLTHROUGH;
6675   case NEON::BI__builtin_neon_vcage_v:
6676   case NEON::BI__builtin_neon_vcageq_v:
6677   case NEON::BI__builtin_neon_vcagt_v:
6678   case NEON::BI__builtin_neon_vcagtq_v: {
6679     llvm::Type *Ty;
6680     switch (VTy->getScalarSizeInBits()) {
6681     default: llvm_unreachable("unexpected type");
6682     case 32:
6683       Ty = FloatTy;
6684       break;
6685     case 64:
6686       Ty = DoubleTy;
6687       break;
6688     case 16:
6689       Ty = HalfTy;
6690       break;
6691     }
6692     auto *VecFlt = llvm::FixedVectorType::get(Ty, VTy->getNumElements());
6693     llvm::Type *Tys[] = { VTy, VecFlt };
6694     Function *F = CGM.getIntrinsic(LLVMIntrinsic, Tys);
6695     return EmitNeonCall(F, Ops, NameHint);
6696   }
6697   case NEON::BI__builtin_neon_vceqz_v:
6698   case NEON::BI__builtin_neon_vceqzq_v:
6699     return EmitAArch64CompareBuiltinExpr(Ops[0], Ty, ICmpInst::FCMP_OEQ,
6700                                          ICmpInst::ICMP_EQ, "vceqz");
6701   case NEON::BI__builtin_neon_vcgez_v:
6702   case NEON::BI__builtin_neon_vcgezq_v:
6703     return EmitAArch64CompareBuiltinExpr(Ops[0], Ty, ICmpInst::FCMP_OGE,
6704                                          ICmpInst::ICMP_SGE, "vcgez");
6705   case NEON::BI__builtin_neon_vclez_v:
6706   case NEON::BI__builtin_neon_vclezq_v:
6707     return EmitAArch64CompareBuiltinExpr(Ops[0], Ty, ICmpInst::FCMP_OLE,
6708                                          ICmpInst::ICMP_SLE, "vclez");
6709   case NEON::BI__builtin_neon_vcgtz_v:
6710   case NEON::BI__builtin_neon_vcgtzq_v:
6711     return EmitAArch64CompareBuiltinExpr(Ops[0], Ty, ICmpInst::FCMP_OGT,
6712                                          ICmpInst::ICMP_SGT, "vcgtz");
6713   case NEON::BI__builtin_neon_vcltz_v:
6714   case NEON::BI__builtin_neon_vcltzq_v:
6715     return EmitAArch64CompareBuiltinExpr(Ops[0], Ty, ICmpInst::FCMP_OLT,
6716                                          ICmpInst::ICMP_SLT, "vcltz");
6717   case NEON::BI__builtin_neon_vclz_v:
6718   case NEON::BI__builtin_neon_vclzq_v:
6719     // We generate target-independent intrinsic, which needs a second argument
6720     // for whether or not clz of zero is undefined; on ARM it isn't.
6721     Ops.push_back(Builder.getInt1(getTarget().isCLZForZeroUndef()));
6722     break;
6723   case NEON::BI__builtin_neon_vcvt_f32_v:
6724   case NEON::BI__builtin_neon_vcvtq_f32_v:
6725     Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
6726     Ty = GetNeonType(this, NeonTypeFlags(NeonTypeFlags::Float32, false, Quad),
6727                      HasLegalHalfType);
6728     return Usgn ? Builder.CreateUIToFP(Ops[0], Ty, "vcvt")
6729                 : Builder.CreateSIToFP(Ops[0], Ty, "vcvt");
6730   case NEON::BI__builtin_neon_vcvt_f16_v:
6731   case NEON::BI__builtin_neon_vcvtq_f16_v:
6732     Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
6733     Ty = GetNeonType(this, NeonTypeFlags(NeonTypeFlags::Float16, false, Quad),
6734                      HasLegalHalfType);
6735     return Usgn ? Builder.CreateUIToFP(Ops[0], Ty, "vcvt")
6736                 : Builder.CreateSIToFP(Ops[0], Ty, "vcvt");
6737   case NEON::BI__builtin_neon_vcvt_n_f16_v:
6738   case NEON::BI__builtin_neon_vcvt_n_f32_v:
6739   case NEON::BI__builtin_neon_vcvt_n_f64_v:
6740   case NEON::BI__builtin_neon_vcvtq_n_f16_v:
6741   case NEON::BI__builtin_neon_vcvtq_n_f32_v:
6742   case NEON::BI__builtin_neon_vcvtq_n_f64_v: {
6743     llvm::Type *Tys[2] = { GetFloatNeonType(this, Type), Ty };
6744     Int = Usgn ? LLVMIntrinsic : AltLLVMIntrinsic;
6745     Function *F = CGM.getIntrinsic(Int, Tys);
6746     return EmitNeonCall(F, Ops, "vcvt_n");
6747   }
6748   case NEON::BI__builtin_neon_vcvt_n_s16_v:
6749   case NEON::BI__builtin_neon_vcvt_n_s32_v:
6750   case NEON::BI__builtin_neon_vcvt_n_u16_v:
6751   case NEON::BI__builtin_neon_vcvt_n_u32_v:
6752   case NEON::BI__builtin_neon_vcvt_n_s64_v:
6753   case NEON::BI__builtin_neon_vcvt_n_u64_v:
6754   case NEON::BI__builtin_neon_vcvtq_n_s16_v:
6755   case NEON::BI__builtin_neon_vcvtq_n_s32_v:
6756   case NEON::BI__builtin_neon_vcvtq_n_u16_v:
6757   case NEON::BI__builtin_neon_vcvtq_n_u32_v:
6758   case NEON::BI__builtin_neon_vcvtq_n_s64_v:
6759   case NEON::BI__builtin_neon_vcvtq_n_u64_v: {
6760     llvm::Type *Tys[2] = { Ty, GetFloatNeonType(this, Type) };
6761     Function *F = CGM.getIntrinsic(LLVMIntrinsic, Tys);
6762     return EmitNeonCall(F, Ops, "vcvt_n");
6763   }
6764   case NEON::BI__builtin_neon_vcvt_s32_v:
6765   case NEON::BI__builtin_neon_vcvt_u32_v:
6766   case NEON::BI__builtin_neon_vcvt_s64_v:
6767   case NEON::BI__builtin_neon_vcvt_u64_v:
6768   case NEON::BI__builtin_neon_vcvt_s16_v:
6769   case NEON::BI__builtin_neon_vcvt_u16_v:
6770   case NEON::BI__builtin_neon_vcvtq_s32_v:
6771   case NEON::BI__builtin_neon_vcvtq_u32_v:
6772   case NEON::BI__builtin_neon_vcvtq_s64_v:
6773   case NEON::BI__builtin_neon_vcvtq_u64_v:
6774   case NEON::BI__builtin_neon_vcvtq_s16_v:
6775   case NEON::BI__builtin_neon_vcvtq_u16_v: {
6776     Ops[0] = Builder.CreateBitCast(Ops[0], GetFloatNeonType(this, Type));
6777     return Usgn ? Builder.CreateFPToUI(Ops[0], Ty, "vcvt")
6778                 : Builder.CreateFPToSI(Ops[0], Ty, "vcvt");
6779   }
6780   case NEON::BI__builtin_neon_vcvta_s16_v:
6781   case NEON::BI__builtin_neon_vcvta_s32_v:
6782   case NEON::BI__builtin_neon_vcvta_s64_v:
6783   case NEON::BI__builtin_neon_vcvta_u16_v:
6784   case NEON::BI__builtin_neon_vcvta_u32_v:
6785   case NEON::BI__builtin_neon_vcvta_u64_v:
6786   case NEON::BI__builtin_neon_vcvtaq_s16_v:
6787   case NEON::BI__builtin_neon_vcvtaq_s32_v:
6788   case NEON::BI__builtin_neon_vcvtaq_s64_v:
6789   case NEON::BI__builtin_neon_vcvtaq_u16_v:
6790   case NEON::BI__builtin_neon_vcvtaq_u32_v:
6791   case NEON::BI__builtin_neon_vcvtaq_u64_v:
6792   case NEON::BI__builtin_neon_vcvtn_s16_v:
6793   case NEON::BI__builtin_neon_vcvtn_s32_v:
6794   case NEON::BI__builtin_neon_vcvtn_s64_v:
6795   case NEON::BI__builtin_neon_vcvtn_u16_v:
6796   case NEON::BI__builtin_neon_vcvtn_u32_v:
6797   case NEON::BI__builtin_neon_vcvtn_u64_v:
6798   case NEON::BI__builtin_neon_vcvtnq_s16_v:
6799   case NEON::BI__builtin_neon_vcvtnq_s32_v:
6800   case NEON::BI__builtin_neon_vcvtnq_s64_v:
6801   case NEON::BI__builtin_neon_vcvtnq_u16_v:
6802   case NEON::BI__builtin_neon_vcvtnq_u32_v:
6803   case NEON::BI__builtin_neon_vcvtnq_u64_v:
6804   case NEON::BI__builtin_neon_vcvtp_s16_v:
6805   case NEON::BI__builtin_neon_vcvtp_s32_v:
6806   case NEON::BI__builtin_neon_vcvtp_s64_v:
6807   case NEON::BI__builtin_neon_vcvtp_u16_v:
6808   case NEON::BI__builtin_neon_vcvtp_u32_v:
6809   case NEON::BI__builtin_neon_vcvtp_u64_v:
6810   case NEON::BI__builtin_neon_vcvtpq_s16_v:
6811   case NEON::BI__builtin_neon_vcvtpq_s32_v:
6812   case NEON::BI__builtin_neon_vcvtpq_s64_v:
6813   case NEON::BI__builtin_neon_vcvtpq_u16_v:
6814   case NEON::BI__builtin_neon_vcvtpq_u32_v:
6815   case NEON::BI__builtin_neon_vcvtpq_u64_v:
6816   case NEON::BI__builtin_neon_vcvtm_s16_v:
6817   case NEON::BI__builtin_neon_vcvtm_s32_v:
6818   case NEON::BI__builtin_neon_vcvtm_s64_v:
6819   case NEON::BI__builtin_neon_vcvtm_u16_v:
6820   case NEON::BI__builtin_neon_vcvtm_u32_v:
6821   case NEON::BI__builtin_neon_vcvtm_u64_v:
6822   case NEON::BI__builtin_neon_vcvtmq_s16_v:
6823   case NEON::BI__builtin_neon_vcvtmq_s32_v:
6824   case NEON::BI__builtin_neon_vcvtmq_s64_v:
6825   case NEON::BI__builtin_neon_vcvtmq_u16_v:
6826   case NEON::BI__builtin_neon_vcvtmq_u32_v:
6827   case NEON::BI__builtin_neon_vcvtmq_u64_v: {
6828     llvm::Type *Tys[2] = { Ty, GetFloatNeonType(this, Type) };
6829     return EmitNeonCall(CGM.getIntrinsic(LLVMIntrinsic, Tys), Ops, NameHint);
6830   }
6831   case NEON::BI__builtin_neon_vcvtx_f32_v: {
6832     llvm::Type *Tys[2] = { VTy->getTruncatedElementVectorType(VTy), Ty};
6833     return EmitNeonCall(CGM.getIntrinsic(LLVMIntrinsic, Tys), Ops, NameHint);
6834 
6835   }
6836   case NEON::BI__builtin_neon_vext_v:
6837   case NEON::BI__builtin_neon_vextq_v: {
6838     int CV = cast<ConstantInt>(Ops[2])->getSExtValue();
6839     SmallVector<int, 16> Indices;
6840     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i)
6841       Indices.push_back(i+CV);
6842 
6843     Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
6844     Ops[1] = Builder.CreateBitCast(Ops[1], Ty);
6845     return Builder.CreateShuffleVector(Ops[0], Ops[1], Indices, "vext");
6846   }
6847   case NEON::BI__builtin_neon_vfma_v:
6848   case NEON::BI__builtin_neon_vfmaq_v: {
6849     Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
6850     Ops[1] = Builder.CreateBitCast(Ops[1], Ty);
6851     Ops[2] = Builder.CreateBitCast(Ops[2], Ty);
6852 
6853     // NEON intrinsic puts accumulator first, unlike the LLVM fma.
6854     return emitCallMaybeConstrainedFPBuiltin(
6855         *this, Intrinsic::fma, Intrinsic::experimental_constrained_fma, Ty,
6856         {Ops[1], Ops[2], Ops[0]});
6857   }
6858   case NEON::BI__builtin_neon_vld1_v:
6859   case NEON::BI__builtin_neon_vld1q_v: {
6860     llvm::Type *Tys[] = {Ty, Int8PtrTy};
6861     Ops.push_back(getAlignmentValue32(PtrOp0));
6862     return EmitNeonCall(CGM.getIntrinsic(LLVMIntrinsic, Tys), Ops, "vld1");
6863   }
6864   case NEON::BI__builtin_neon_vld1_x2_v:
6865   case NEON::BI__builtin_neon_vld1q_x2_v:
6866   case NEON::BI__builtin_neon_vld1_x3_v:
6867   case NEON::BI__builtin_neon_vld1q_x3_v:
6868   case NEON::BI__builtin_neon_vld1_x4_v:
6869   case NEON::BI__builtin_neon_vld1q_x4_v: {
6870     llvm::Type *PTy = llvm::PointerType::getUnqual(VTy->getElementType());
6871     Ops[1] = Builder.CreateBitCast(Ops[1], PTy);
6872     llvm::Type *Tys[2] = { VTy, PTy };
6873     Function *F = CGM.getIntrinsic(LLVMIntrinsic, Tys);
6874     Ops[1] = Builder.CreateCall(F, Ops[1], "vld1xN");
6875     Ty = llvm::PointerType::getUnqual(Ops[1]->getType());
6876     Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
6877     return Builder.CreateDefaultAlignedStore(Ops[1], Ops[0]);
6878   }
6879   case NEON::BI__builtin_neon_vld2_v:
6880   case NEON::BI__builtin_neon_vld2q_v:
6881   case NEON::BI__builtin_neon_vld3_v:
6882   case NEON::BI__builtin_neon_vld3q_v:
6883   case NEON::BI__builtin_neon_vld4_v:
6884   case NEON::BI__builtin_neon_vld4q_v:
6885   case NEON::BI__builtin_neon_vld2_dup_v:
6886   case NEON::BI__builtin_neon_vld2q_dup_v:
6887   case NEON::BI__builtin_neon_vld3_dup_v:
6888   case NEON::BI__builtin_neon_vld3q_dup_v:
6889   case NEON::BI__builtin_neon_vld4_dup_v:
6890   case NEON::BI__builtin_neon_vld4q_dup_v: {
6891     llvm::Type *Tys[] = {Ty, Int8PtrTy};
6892     Function *F = CGM.getIntrinsic(LLVMIntrinsic, Tys);
6893     Value *Align = getAlignmentValue32(PtrOp1);
6894     Ops[1] = Builder.CreateCall(F, {Ops[1], Align}, NameHint);
6895     Ty = llvm::PointerType::getUnqual(Ops[1]->getType());
6896     Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
6897     return Builder.CreateDefaultAlignedStore(Ops[1], Ops[0]);
6898   }
6899   case NEON::BI__builtin_neon_vld1_dup_v:
6900   case NEON::BI__builtin_neon_vld1q_dup_v: {
6901     Value *V = UndefValue::get(Ty);
6902     Ty = llvm::PointerType::getUnqual(VTy->getElementType());
6903     PtrOp0 = Builder.CreateBitCast(PtrOp0, Ty);
6904     LoadInst *Ld = Builder.CreateLoad(PtrOp0);
6905     llvm::Constant *CI = ConstantInt::get(SizeTy, 0);
6906     Ops[0] = Builder.CreateInsertElement(V, Ld, CI);
6907     return EmitNeonSplat(Ops[0], CI);
6908   }
6909   case NEON::BI__builtin_neon_vld2_lane_v:
6910   case NEON::BI__builtin_neon_vld2q_lane_v:
6911   case NEON::BI__builtin_neon_vld3_lane_v:
6912   case NEON::BI__builtin_neon_vld3q_lane_v:
6913   case NEON::BI__builtin_neon_vld4_lane_v:
6914   case NEON::BI__builtin_neon_vld4q_lane_v: {
6915     llvm::Type *Tys[] = {Ty, Int8PtrTy};
6916     Function *F = CGM.getIntrinsic(LLVMIntrinsic, Tys);
6917     for (unsigned I = 2; I < Ops.size() - 1; ++I)
6918       Ops[I] = Builder.CreateBitCast(Ops[I], Ty);
6919     Ops.push_back(getAlignmentValue32(PtrOp1));
6920     Ops[1] = Builder.CreateCall(F, makeArrayRef(Ops).slice(1), NameHint);
6921     Ty = llvm::PointerType::getUnqual(Ops[1]->getType());
6922     Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
6923     return Builder.CreateDefaultAlignedStore(Ops[1], Ops[0]);
6924   }
6925   case NEON::BI__builtin_neon_vmovl_v: {
6926     llvm::FixedVectorType *DTy =
6927         llvm::FixedVectorType::getTruncatedElementVectorType(VTy);
6928     Ops[0] = Builder.CreateBitCast(Ops[0], DTy);
6929     if (Usgn)
6930       return Builder.CreateZExt(Ops[0], Ty, "vmovl");
6931     return Builder.CreateSExt(Ops[0], Ty, "vmovl");
6932   }
6933   case NEON::BI__builtin_neon_vmovn_v: {
6934     llvm::FixedVectorType *QTy =
6935         llvm::FixedVectorType::getExtendedElementVectorType(VTy);
6936     Ops[0] = Builder.CreateBitCast(Ops[0], QTy);
6937     return Builder.CreateTrunc(Ops[0], Ty, "vmovn");
6938   }
6939   case NEON::BI__builtin_neon_vmull_v:
6940     // FIXME: the integer vmull operations could be emitted in terms of pure
6941     // LLVM IR (2 exts followed by a mul). Unfortunately LLVM has a habit of
6942     // hoisting the exts outside loops. Until global ISel comes along that can
6943     // see through such movement this leads to bad CodeGen. So we need an
6944     // intrinsic for now.
6945     Int = Usgn ? Intrinsic::arm_neon_vmullu : Intrinsic::arm_neon_vmulls;
6946     Int = Type.isPoly() ? (unsigned)Intrinsic::arm_neon_vmullp : Int;
6947     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vmull");
6948   case NEON::BI__builtin_neon_vpadal_v:
6949   case NEON::BI__builtin_neon_vpadalq_v: {
6950     // The source operand type has twice as many elements of half the size.
6951     unsigned EltBits = VTy->getElementType()->getPrimitiveSizeInBits();
6952     llvm::Type *EltTy =
6953       llvm::IntegerType::get(getLLVMContext(), EltBits / 2);
6954     auto *NarrowTy =
6955         llvm::FixedVectorType::get(EltTy, VTy->getNumElements() * 2);
6956     llvm::Type *Tys[2] = { Ty, NarrowTy };
6957     return EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, NameHint);
6958   }
6959   case NEON::BI__builtin_neon_vpaddl_v:
6960   case NEON::BI__builtin_neon_vpaddlq_v: {
6961     // The source operand type has twice as many elements of half the size.
6962     unsigned EltBits = VTy->getElementType()->getPrimitiveSizeInBits();
6963     llvm::Type *EltTy = llvm::IntegerType::get(getLLVMContext(), EltBits / 2);
6964     auto *NarrowTy =
6965         llvm::FixedVectorType::get(EltTy, VTy->getNumElements() * 2);
6966     llvm::Type *Tys[2] = { Ty, NarrowTy };
6967     return EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vpaddl");
6968   }
6969   case NEON::BI__builtin_neon_vqdmlal_v:
6970   case NEON::BI__builtin_neon_vqdmlsl_v: {
6971     SmallVector<Value *, 2> MulOps(Ops.begin() + 1, Ops.end());
6972     Ops[1] =
6973         EmitNeonCall(CGM.getIntrinsic(LLVMIntrinsic, Ty), MulOps, "vqdmlal");
6974     Ops.resize(2);
6975     return EmitNeonCall(CGM.getIntrinsic(AltLLVMIntrinsic, Ty), Ops, NameHint);
6976   }
6977   case NEON::BI__builtin_neon_vqdmulhq_lane_v:
6978   case NEON::BI__builtin_neon_vqdmulh_lane_v:
6979   case NEON::BI__builtin_neon_vqrdmulhq_lane_v:
6980   case NEON::BI__builtin_neon_vqrdmulh_lane_v: {
6981     auto *RTy = cast<llvm::FixedVectorType>(Ty);
6982     if (BuiltinID == NEON::BI__builtin_neon_vqdmulhq_lane_v ||
6983         BuiltinID == NEON::BI__builtin_neon_vqrdmulhq_lane_v)
6984       RTy = llvm::FixedVectorType::get(RTy->getElementType(),
6985                                        RTy->getNumElements() * 2);
6986     llvm::Type *Tys[2] = {
6987         RTy, GetNeonType(this, NeonTypeFlags(Type.getEltType(), false,
6988                                              /*isQuad*/ false))};
6989     return EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, NameHint);
6990   }
6991   case NEON::BI__builtin_neon_vqdmulhq_laneq_v:
6992   case NEON::BI__builtin_neon_vqdmulh_laneq_v:
6993   case NEON::BI__builtin_neon_vqrdmulhq_laneq_v:
6994   case NEON::BI__builtin_neon_vqrdmulh_laneq_v: {
6995     llvm::Type *Tys[2] = {
6996         Ty, GetNeonType(this, NeonTypeFlags(Type.getEltType(), false,
6997                                             /*isQuad*/ true))};
6998     return EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, NameHint);
6999   }
7000   case NEON::BI__builtin_neon_vqshl_n_v:
7001   case NEON::BI__builtin_neon_vqshlq_n_v:
7002     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vqshl_n",
7003                         1, false);
7004   case NEON::BI__builtin_neon_vqshlu_n_v:
7005   case NEON::BI__builtin_neon_vqshluq_n_v:
7006     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vqshlu_n",
7007                         1, false);
7008   case NEON::BI__builtin_neon_vrecpe_v:
7009   case NEON::BI__builtin_neon_vrecpeq_v:
7010   case NEON::BI__builtin_neon_vrsqrte_v:
7011   case NEON::BI__builtin_neon_vrsqrteq_v:
7012     Int = Ty->isFPOrFPVectorTy() ? LLVMIntrinsic : AltLLVMIntrinsic;
7013     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, NameHint);
7014   case NEON::BI__builtin_neon_vrndi_v:
7015   case NEON::BI__builtin_neon_vrndiq_v:
7016     Int = Builder.getIsFPConstrained()
7017               ? Intrinsic::experimental_constrained_nearbyint
7018               : Intrinsic::nearbyint;
7019     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, NameHint);
7020   case NEON::BI__builtin_neon_vrshr_n_v:
7021   case NEON::BI__builtin_neon_vrshrq_n_v:
7022     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vrshr_n",
7023                         1, true);
7024   case NEON::BI__builtin_neon_vsha512hq_v:
7025   case NEON::BI__builtin_neon_vsha512h2q_v:
7026   case NEON::BI__builtin_neon_vsha512su0q_v:
7027   case NEON::BI__builtin_neon_vsha512su1q_v: {
7028     Function *F = CGM.getIntrinsic(Int);
7029     return EmitNeonCall(F, Ops, "");
7030   }
7031   case NEON::BI__builtin_neon_vshl_n_v:
7032   case NEON::BI__builtin_neon_vshlq_n_v:
7033     Ops[1] = EmitNeonShiftVector(Ops[1], Ty, false);
7034     return Builder.CreateShl(Builder.CreateBitCast(Ops[0],Ty), Ops[1],
7035                              "vshl_n");
7036   case NEON::BI__builtin_neon_vshll_n_v: {
7037     llvm::FixedVectorType *SrcTy =
7038         llvm::FixedVectorType::getTruncatedElementVectorType(VTy);
7039     Ops[0] = Builder.CreateBitCast(Ops[0], SrcTy);
7040     if (Usgn)
7041       Ops[0] = Builder.CreateZExt(Ops[0], VTy);
7042     else
7043       Ops[0] = Builder.CreateSExt(Ops[0], VTy);
7044     Ops[1] = EmitNeonShiftVector(Ops[1], VTy, false);
7045     return Builder.CreateShl(Ops[0], Ops[1], "vshll_n");
7046   }
7047   case NEON::BI__builtin_neon_vshrn_n_v: {
7048     llvm::FixedVectorType *SrcTy =
7049         llvm::FixedVectorType::getExtendedElementVectorType(VTy);
7050     Ops[0] = Builder.CreateBitCast(Ops[0], SrcTy);
7051     Ops[1] = EmitNeonShiftVector(Ops[1], SrcTy, false);
7052     if (Usgn)
7053       Ops[0] = Builder.CreateLShr(Ops[0], Ops[1]);
7054     else
7055       Ops[0] = Builder.CreateAShr(Ops[0], Ops[1]);
7056     return Builder.CreateTrunc(Ops[0], Ty, "vshrn_n");
7057   }
7058   case NEON::BI__builtin_neon_vshr_n_v:
7059   case NEON::BI__builtin_neon_vshrq_n_v:
7060     return EmitNeonRShiftImm(Ops[0], Ops[1], Ty, Usgn, "vshr_n");
7061   case NEON::BI__builtin_neon_vst1_v:
7062   case NEON::BI__builtin_neon_vst1q_v:
7063   case NEON::BI__builtin_neon_vst2_v:
7064   case NEON::BI__builtin_neon_vst2q_v:
7065   case NEON::BI__builtin_neon_vst3_v:
7066   case NEON::BI__builtin_neon_vst3q_v:
7067   case NEON::BI__builtin_neon_vst4_v:
7068   case NEON::BI__builtin_neon_vst4q_v:
7069   case NEON::BI__builtin_neon_vst2_lane_v:
7070   case NEON::BI__builtin_neon_vst2q_lane_v:
7071   case NEON::BI__builtin_neon_vst3_lane_v:
7072   case NEON::BI__builtin_neon_vst3q_lane_v:
7073   case NEON::BI__builtin_neon_vst4_lane_v:
7074   case NEON::BI__builtin_neon_vst4q_lane_v: {
7075     llvm::Type *Tys[] = {Int8PtrTy, Ty};
7076     Ops.push_back(getAlignmentValue32(PtrOp0));
7077     return EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "");
7078   }
7079   case NEON::BI__builtin_neon_vsm3partw1q_v:
7080   case NEON::BI__builtin_neon_vsm3partw2q_v:
7081   case NEON::BI__builtin_neon_vsm3ss1q_v:
7082   case NEON::BI__builtin_neon_vsm4ekeyq_v:
7083   case NEON::BI__builtin_neon_vsm4eq_v: {
7084     Function *F = CGM.getIntrinsic(Int);
7085     return EmitNeonCall(F, Ops, "");
7086   }
7087   case NEON::BI__builtin_neon_vsm3tt1aq_v:
7088   case NEON::BI__builtin_neon_vsm3tt1bq_v:
7089   case NEON::BI__builtin_neon_vsm3tt2aq_v:
7090   case NEON::BI__builtin_neon_vsm3tt2bq_v: {
7091     Function *F = CGM.getIntrinsic(Int);
7092     Ops[3] = Builder.CreateZExt(Ops[3], Int64Ty);
7093     return EmitNeonCall(F, Ops, "");
7094   }
7095   case NEON::BI__builtin_neon_vst1_x2_v:
7096   case NEON::BI__builtin_neon_vst1q_x2_v:
7097   case NEON::BI__builtin_neon_vst1_x3_v:
7098   case NEON::BI__builtin_neon_vst1q_x3_v:
7099   case NEON::BI__builtin_neon_vst1_x4_v:
7100   case NEON::BI__builtin_neon_vst1q_x4_v: {
7101     llvm::Type *PTy = llvm::PointerType::getUnqual(VTy->getElementType());
7102     // TODO: Currently in AArch32 mode the pointer operand comes first, whereas
7103     // in AArch64 it comes last. We may want to stick to one or another.
7104     if (Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be ||
7105         Arch == llvm::Triple::aarch64_32) {
7106       llvm::Type *Tys[2] = { VTy, PTy };
7107       std::rotate(Ops.begin(), Ops.begin() + 1, Ops.end());
7108       return EmitNeonCall(CGM.getIntrinsic(LLVMIntrinsic, Tys), Ops, "");
7109     }
7110     llvm::Type *Tys[2] = { PTy, VTy };
7111     return EmitNeonCall(CGM.getIntrinsic(LLVMIntrinsic, Tys), Ops, "");
7112   }
7113   case NEON::BI__builtin_neon_vsubhn_v: {
7114     llvm::FixedVectorType *SrcTy =
7115         llvm::FixedVectorType::getExtendedElementVectorType(VTy);
7116 
7117     // %sum = add <4 x i32> %lhs, %rhs
7118     Ops[0] = Builder.CreateBitCast(Ops[0], SrcTy);
7119     Ops[1] = Builder.CreateBitCast(Ops[1], SrcTy);
7120     Ops[0] = Builder.CreateSub(Ops[0], Ops[1], "vsubhn");
7121 
7122     // %high = lshr <4 x i32> %sum, <i32 16, i32 16, i32 16, i32 16>
7123     Constant *ShiftAmt =
7124         ConstantInt::get(SrcTy, SrcTy->getScalarSizeInBits() / 2);
7125     Ops[0] = Builder.CreateLShr(Ops[0], ShiftAmt, "vsubhn");
7126 
7127     // %res = trunc <4 x i32> %high to <4 x i16>
7128     return Builder.CreateTrunc(Ops[0], VTy, "vsubhn");
7129   }
7130   case NEON::BI__builtin_neon_vtrn_v:
7131   case NEON::BI__builtin_neon_vtrnq_v: {
7132     Ops[0] = Builder.CreateBitCast(Ops[0], llvm::PointerType::getUnqual(Ty));
7133     Ops[1] = Builder.CreateBitCast(Ops[1], Ty);
7134     Ops[2] = Builder.CreateBitCast(Ops[2], Ty);
7135     Value *SV = nullptr;
7136 
7137     for (unsigned vi = 0; vi != 2; ++vi) {
7138       SmallVector<int, 16> Indices;
7139       for (unsigned i = 0, e = VTy->getNumElements(); i != e; i += 2) {
7140         Indices.push_back(i+vi);
7141         Indices.push_back(i+e+vi);
7142       }
7143       Value *Addr = Builder.CreateConstInBoundsGEP1_32(Ty, Ops[0], vi);
7144       SV = Builder.CreateShuffleVector(Ops[1], Ops[2], Indices, "vtrn");
7145       SV = Builder.CreateDefaultAlignedStore(SV, Addr);
7146     }
7147     return SV;
7148   }
7149   case NEON::BI__builtin_neon_vtst_v:
7150   case NEON::BI__builtin_neon_vtstq_v: {
7151     Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
7152     Ops[1] = Builder.CreateBitCast(Ops[1], Ty);
7153     Ops[0] = Builder.CreateAnd(Ops[0], Ops[1]);
7154     Ops[0] = Builder.CreateICmp(ICmpInst::ICMP_NE, Ops[0],
7155                                 ConstantAggregateZero::get(Ty));
7156     return Builder.CreateSExt(Ops[0], Ty, "vtst");
7157   }
7158   case NEON::BI__builtin_neon_vuzp_v:
7159   case NEON::BI__builtin_neon_vuzpq_v: {
7160     Ops[0] = Builder.CreateBitCast(Ops[0], llvm::PointerType::getUnqual(Ty));
7161     Ops[1] = Builder.CreateBitCast(Ops[1], Ty);
7162     Ops[2] = Builder.CreateBitCast(Ops[2], Ty);
7163     Value *SV = nullptr;
7164 
7165     for (unsigned vi = 0; vi != 2; ++vi) {
7166       SmallVector<int, 16> Indices;
7167       for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i)
7168         Indices.push_back(2*i+vi);
7169 
7170       Value *Addr = Builder.CreateConstInBoundsGEP1_32(Ty, Ops[0], vi);
7171       SV = Builder.CreateShuffleVector(Ops[1], Ops[2], Indices, "vuzp");
7172       SV = Builder.CreateDefaultAlignedStore(SV, Addr);
7173     }
7174     return SV;
7175   }
7176   case NEON::BI__builtin_neon_vxarq_v: {
7177     Function *F = CGM.getIntrinsic(Int);
7178     Ops[2] = Builder.CreateZExt(Ops[2], Int64Ty);
7179     return EmitNeonCall(F, Ops, "");
7180   }
7181   case NEON::BI__builtin_neon_vzip_v:
7182   case NEON::BI__builtin_neon_vzipq_v: {
7183     Ops[0] = Builder.CreateBitCast(Ops[0], llvm::PointerType::getUnqual(Ty));
7184     Ops[1] = Builder.CreateBitCast(Ops[1], Ty);
7185     Ops[2] = Builder.CreateBitCast(Ops[2], Ty);
7186     Value *SV = nullptr;
7187 
7188     for (unsigned vi = 0; vi != 2; ++vi) {
7189       SmallVector<int, 16> Indices;
7190       for (unsigned i = 0, e = VTy->getNumElements(); i != e; i += 2) {
7191         Indices.push_back((i + vi*e) >> 1);
7192         Indices.push_back(((i + vi*e) >> 1)+e);
7193       }
7194       Value *Addr = Builder.CreateConstInBoundsGEP1_32(Ty, Ops[0], vi);
7195       SV = Builder.CreateShuffleVector(Ops[1], Ops[2], Indices, "vzip");
7196       SV = Builder.CreateDefaultAlignedStore(SV, Addr);
7197     }
7198     return SV;
7199   }
7200   case NEON::BI__builtin_neon_vdot_v:
7201   case NEON::BI__builtin_neon_vdotq_v: {
7202     auto *InputTy =
7203         llvm::FixedVectorType::get(Int8Ty, Ty->getPrimitiveSizeInBits() / 8);
7204     llvm::Type *Tys[2] = { Ty, InputTy };
7205     Int = Usgn ? LLVMIntrinsic : AltLLVMIntrinsic;
7206     return EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vdot");
7207   }
7208   case NEON::BI__builtin_neon_vfmlal_low_v:
7209   case NEON::BI__builtin_neon_vfmlalq_low_v: {
7210     auto *InputTy =
7211         llvm::FixedVectorType::get(HalfTy, Ty->getPrimitiveSizeInBits() / 16);
7212     llvm::Type *Tys[2] = { Ty, InputTy };
7213     return EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vfmlal_low");
7214   }
7215   case NEON::BI__builtin_neon_vfmlsl_low_v:
7216   case NEON::BI__builtin_neon_vfmlslq_low_v: {
7217     auto *InputTy =
7218         llvm::FixedVectorType::get(HalfTy, Ty->getPrimitiveSizeInBits() / 16);
7219     llvm::Type *Tys[2] = { Ty, InputTy };
7220     return EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vfmlsl_low");
7221   }
7222   case NEON::BI__builtin_neon_vfmlal_high_v:
7223   case NEON::BI__builtin_neon_vfmlalq_high_v: {
7224     auto *InputTy =
7225         llvm::FixedVectorType::get(HalfTy, Ty->getPrimitiveSizeInBits() / 16);
7226     llvm::Type *Tys[2] = { Ty, InputTy };
7227     return EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vfmlal_high");
7228   }
7229   case NEON::BI__builtin_neon_vfmlsl_high_v:
7230   case NEON::BI__builtin_neon_vfmlslq_high_v: {
7231     auto *InputTy =
7232         llvm::FixedVectorType::get(HalfTy, Ty->getPrimitiveSizeInBits() / 16);
7233     llvm::Type *Tys[2] = { Ty, InputTy };
7234     return EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vfmlsl_high");
7235   }
7236   case NEON::BI__builtin_neon_vmmlaq_v: {
7237     auto *InputTy =
7238         llvm::FixedVectorType::get(Int8Ty, Ty->getPrimitiveSizeInBits() / 8);
7239     llvm::Type *Tys[2] = { Ty, InputTy };
7240     Int = Usgn ? LLVMIntrinsic : AltLLVMIntrinsic;
7241     return EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vmmla");
7242   }
7243   case NEON::BI__builtin_neon_vusmmlaq_v: {
7244     auto *InputTy =
7245         llvm::FixedVectorType::get(Int8Ty, Ty->getPrimitiveSizeInBits() / 8);
7246     llvm::Type *Tys[2] = { Ty, InputTy };
7247     return EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vusmmla");
7248   }
7249   case NEON::BI__builtin_neon_vusdot_v:
7250   case NEON::BI__builtin_neon_vusdotq_v: {
7251     auto *InputTy =
7252         llvm::FixedVectorType::get(Int8Ty, Ty->getPrimitiveSizeInBits() / 8);
7253     llvm::Type *Tys[2] = { Ty, InputTy };
7254     return EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vusdot");
7255   }
7256   case NEON::BI__builtin_neon_vbfdot_v:
7257   case NEON::BI__builtin_neon_vbfdotq_v: {
7258     llvm::Type *InputTy =
7259         llvm::FixedVectorType::get(BFloatTy, Ty->getPrimitiveSizeInBits() / 16);
7260     llvm::Type *Tys[2] = { Ty, InputTy };
7261     return EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vbfdot");
7262   }
7263   case NEON::BI__builtin_neon___a32_vcvt_bf16_v: {
7264     llvm::Type *Tys[1] = { Ty };
7265     Function *F = CGM.getIntrinsic(Int, Tys);
7266     return EmitNeonCall(F, Ops, "vcvtfp2bf");
7267   }
7268 
7269   }
7270 
7271   assert(Int && "Expected valid intrinsic number");
7272 
7273   // Determine the type(s) of this overloaded AArch64 intrinsic.
7274   Function *F = LookupNeonLLVMIntrinsic(Int, Modifier, Ty, E);
7275 
7276   Value *Result = EmitNeonCall(F, Ops, NameHint);
7277   llvm::Type *ResultType = ConvertType(E->getType());
7278   // AArch64 intrinsic one-element vector type cast to
7279   // scalar type expected by the builtin
7280   return Builder.CreateBitCast(Result, ResultType, NameHint);
7281 }
7282 
7283 Value *CodeGenFunction::EmitAArch64CompareBuiltinExpr(
7284     Value *Op, llvm::Type *Ty, const CmpInst::Predicate Fp,
7285     const CmpInst::Predicate Ip, const Twine &Name) {
7286   llvm::Type *OTy = Op->getType();
7287 
7288   // FIXME: this is utterly horrific. We should not be looking at previous
7289   // codegen context to find out what needs doing. Unfortunately TableGen
7290   // currently gives us exactly the same calls for vceqz_f32 and vceqz_s32
7291   // (etc).
7292   if (BitCastInst *BI = dyn_cast<BitCastInst>(Op))
7293     OTy = BI->getOperand(0)->getType();
7294 
7295   Op = Builder.CreateBitCast(Op, OTy);
7296   if (OTy->getScalarType()->isFloatingPointTy()) {
7297     Op = Builder.CreateFCmp(Fp, Op, Constant::getNullValue(OTy));
7298   } else {
7299     Op = Builder.CreateICmp(Ip, Op, Constant::getNullValue(OTy));
7300   }
7301   return Builder.CreateSExt(Op, Ty, Name);
7302 }
7303 
7304 static Value *packTBLDVectorList(CodeGenFunction &CGF, ArrayRef<Value *> Ops,
7305                                  Value *ExtOp, Value *IndexOp,
7306                                  llvm::Type *ResTy, unsigned IntID,
7307                                  const char *Name) {
7308   SmallVector<Value *, 2> TblOps;
7309   if (ExtOp)
7310     TblOps.push_back(ExtOp);
7311 
7312   // Build a vector containing sequential number like (0, 1, 2, ..., 15)
7313   SmallVector<int, 16> Indices;
7314   auto *TblTy = cast<llvm::FixedVectorType>(Ops[0]->getType());
7315   for (unsigned i = 0, e = TblTy->getNumElements(); i != e; ++i) {
7316     Indices.push_back(2*i);
7317     Indices.push_back(2*i+1);
7318   }
7319 
7320   int PairPos = 0, End = Ops.size() - 1;
7321   while (PairPos < End) {
7322     TblOps.push_back(CGF.Builder.CreateShuffleVector(Ops[PairPos],
7323                                                      Ops[PairPos+1], Indices,
7324                                                      Name));
7325     PairPos += 2;
7326   }
7327 
7328   // If there's an odd number of 64-bit lookup table, fill the high 64-bit
7329   // of the 128-bit lookup table with zero.
7330   if (PairPos == End) {
7331     Value *ZeroTbl = ConstantAggregateZero::get(TblTy);
7332     TblOps.push_back(CGF.Builder.CreateShuffleVector(Ops[PairPos],
7333                                                      ZeroTbl, Indices, Name));
7334   }
7335 
7336   Function *TblF;
7337   TblOps.push_back(IndexOp);
7338   TblF = CGF.CGM.getIntrinsic(IntID, ResTy);
7339 
7340   return CGF.EmitNeonCall(TblF, TblOps, Name);
7341 }
7342 
7343 Value *CodeGenFunction::GetValueForARMHint(unsigned BuiltinID) {
7344   unsigned Value;
7345   switch (BuiltinID) {
7346   default:
7347     return nullptr;
7348   case ARM::BI__builtin_arm_nop:
7349     Value = 0;
7350     break;
7351   case ARM::BI__builtin_arm_yield:
7352   case ARM::BI__yield:
7353     Value = 1;
7354     break;
7355   case ARM::BI__builtin_arm_wfe:
7356   case ARM::BI__wfe:
7357     Value = 2;
7358     break;
7359   case ARM::BI__builtin_arm_wfi:
7360   case ARM::BI__wfi:
7361     Value = 3;
7362     break;
7363   case ARM::BI__builtin_arm_sev:
7364   case ARM::BI__sev:
7365     Value = 4;
7366     break;
7367   case ARM::BI__builtin_arm_sevl:
7368   case ARM::BI__sevl:
7369     Value = 5;
7370     break;
7371   }
7372 
7373   return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::arm_hint),
7374                             llvm::ConstantInt::get(Int32Ty, Value));
7375 }
7376 
7377 enum SpecialRegisterAccessKind {
7378   NormalRead,
7379   VolatileRead,
7380   Write,
7381 };
7382 
7383 // Generates the IR for the read/write special register builtin,
7384 // ValueType is the type of the value that is to be written or read,
7385 // RegisterType is the type of the register being written to or read from.
7386 static Value *EmitSpecialRegisterBuiltin(CodeGenFunction &CGF,
7387                                          const CallExpr *E,
7388                                          llvm::Type *RegisterType,
7389                                          llvm::Type *ValueType,
7390                                          SpecialRegisterAccessKind AccessKind,
7391                                          StringRef SysReg = "") {
7392   // write and register intrinsics only support 32 and 64 bit operations.
7393   assert((RegisterType->isIntegerTy(32) || RegisterType->isIntegerTy(64))
7394           && "Unsupported size for register.");
7395 
7396   CodeGen::CGBuilderTy &Builder = CGF.Builder;
7397   CodeGen::CodeGenModule &CGM = CGF.CGM;
7398   LLVMContext &Context = CGM.getLLVMContext();
7399 
7400   if (SysReg.empty()) {
7401     const Expr *SysRegStrExpr = E->getArg(0)->IgnoreParenCasts();
7402     SysReg = cast<clang::StringLiteral>(SysRegStrExpr)->getString();
7403   }
7404 
7405   llvm::Metadata *Ops[] = { llvm::MDString::get(Context, SysReg) };
7406   llvm::MDNode *RegName = llvm::MDNode::get(Context, Ops);
7407   llvm::Value *Metadata = llvm::MetadataAsValue::get(Context, RegName);
7408 
7409   llvm::Type *Types[] = { RegisterType };
7410 
7411   bool MixedTypes = RegisterType->isIntegerTy(64) && ValueType->isIntegerTy(32);
7412   assert(!(RegisterType->isIntegerTy(32) && ValueType->isIntegerTy(64))
7413             && "Can't fit 64-bit value in 32-bit register");
7414 
7415   if (AccessKind != Write) {
7416     assert(AccessKind == NormalRead || AccessKind == VolatileRead);
7417     llvm::Function *F = CGM.getIntrinsic(
7418         AccessKind == VolatileRead ? llvm::Intrinsic::read_volatile_register
7419                                    : llvm::Intrinsic::read_register,
7420         Types);
7421     llvm::Value *Call = Builder.CreateCall(F, Metadata);
7422 
7423     if (MixedTypes)
7424       // Read into 64 bit register and then truncate result to 32 bit.
7425       return Builder.CreateTrunc(Call, ValueType);
7426 
7427     if (ValueType->isPointerTy())
7428       // Have i32/i64 result (Call) but want to return a VoidPtrTy (i8*).
7429       return Builder.CreateIntToPtr(Call, ValueType);
7430 
7431     return Call;
7432   }
7433 
7434   llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
7435   llvm::Value *ArgValue = CGF.EmitScalarExpr(E->getArg(1));
7436   if (MixedTypes) {
7437     // Extend 32 bit write value to 64 bit to pass to write.
7438     ArgValue = Builder.CreateZExt(ArgValue, RegisterType);
7439     return Builder.CreateCall(F, { Metadata, ArgValue });
7440   }
7441 
7442   if (ValueType->isPointerTy()) {
7443     // Have VoidPtrTy ArgValue but want to return an i32/i64.
7444     ArgValue = Builder.CreatePtrToInt(ArgValue, RegisterType);
7445     return Builder.CreateCall(F, { Metadata, ArgValue });
7446   }
7447 
7448   return Builder.CreateCall(F, { Metadata, ArgValue });
7449 }
7450 
7451 /// Return true if BuiltinID is an overloaded Neon intrinsic with an extra
7452 /// argument that specifies the vector type.
7453 static bool HasExtraNeonArgument(unsigned BuiltinID) {
7454   switch (BuiltinID) {
7455   default: break;
7456   case NEON::BI__builtin_neon_vget_lane_i8:
7457   case NEON::BI__builtin_neon_vget_lane_i16:
7458   case NEON::BI__builtin_neon_vget_lane_bf16:
7459   case NEON::BI__builtin_neon_vget_lane_i32:
7460   case NEON::BI__builtin_neon_vget_lane_i64:
7461   case NEON::BI__builtin_neon_vget_lane_f32:
7462   case NEON::BI__builtin_neon_vgetq_lane_i8:
7463   case NEON::BI__builtin_neon_vgetq_lane_i16:
7464   case NEON::BI__builtin_neon_vgetq_lane_bf16:
7465   case NEON::BI__builtin_neon_vgetq_lane_i32:
7466   case NEON::BI__builtin_neon_vgetq_lane_i64:
7467   case NEON::BI__builtin_neon_vgetq_lane_f32:
7468   case NEON::BI__builtin_neon_vduph_lane_bf16:
7469   case NEON::BI__builtin_neon_vduph_laneq_bf16:
7470   case NEON::BI__builtin_neon_vset_lane_i8:
7471   case NEON::BI__builtin_neon_vset_lane_i16:
7472   case NEON::BI__builtin_neon_vset_lane_bf16:
7473   case NEON::BI__builtin_neon_vset_lane_i32:
7474   case NEON::BI__builtin_neon_vset_lane_i64:
7475   case NEON::BI__builtin_neon_vset_lane_f32:
7476   case NEON::BI__builtin_neon_vsetq_lane_i8:
7477   case NEON::BI__builtin_neon_vsetq_lane_i16:
7478   case NEON::BI__builtin_neon_vsetq_lane_bf16:
7479   case NEON::BI__builtin_neon_vsetq_lane_i32:
7480   case NEON::BI__builtin_neon_vsetq_lane_i64:
7481   case NEON::BI__builtin_neon_vsetq_lane_f32:
7482   case NEON::BI__builtin_neon_vsha1h_u32:
7483   case NEON::BI__builtin_neon_vsha1cq_u32:
7484   case NEON::BI__builtin_neon_vsha1pq_u32:
7485   case NEON::BI__builtin_neon_vsha1mq_u32:
7486   case NEON::BI__builtin_neon_vcvth_bf16_f32:
7487   case clang::ARM::BI_MoveToCoprocessor:
7488   case clang::ARM::BI_MoveToCoprocessor2:
7489     return false;
7490   }
7491   return true;
7492 }
7493 
7494 Value *CodeGenFunction::EmitARMBuiltinExpr(unsigned BuiltinID,
7495                                            const CallExpr *E,
7496                                            ReturnValueSlot ReturnValue,
7497                                            llvm::Triple::ArchType Arch) {
7498   if (auto Hint = GetValueForARMHint(BuiltinID))
7499     return Hint;
7500 
7501   if (BuiltinID == ARM::BI__emit) {
7502     bool IsThumb = getTarget().getTriple().getArch() == llvm::Triple::thumb;
7503     llvm::FunctionType *FTy =
7504         llvm::FunctionType::get(VoidTy, /*Variadic=*/false);
7505 
7506     Expr::EvalResult Result;
7507     if (!E->getArg(0)->EvaluateAsInt(Result, CGM.getContext()))
7508       llvm_unreachable("Sema will ensure that the parameter is constant");
7509 
7510     llvm::APSInt Value = Result.Val.getInt();
7511     uint64_t ZExtValue = Value.zextOrTrunc(IsThumb ? 16 : 32).getZExtValue();
7512 
7513     llvm::InlineAsm *Emit =
7514         IsThumb ? InlineAsm::get(FTy, ".inst.n 0x" + utohexstr(ZExtValue), "",
7515                                  /*hasSideEffects=*/true)
7516                 : InlineAsm::get(FTy, ".inst 0x" + utohexstr(ZExtValue), "",
7517                                  /*hasSideEffects=*/true);
7518 
7519     return Builder.CreateCall(Emit);
7520   }
7521 
7522   if (BuiltinID == ARM::BI__builtin_arm_dbg) {
7523     Value *Option = EmitScalarExpr(E->getArg(0));
7524     return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::arm_dbg), Option);
7525   }
7526 
7527   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
7528     Value *Address = EmitScalarExpr(E->getArg(0));
7529     Value *RW      = EmitScalarExpr(E->getArg(1));
7530     Value *IsData  = EmitScalarExpr(E->getArg(2));
7531 
7532     // Locality is not supported on ARM target
7533     Value *Locality = llvm::ConstantInt::get(Int32Ty, 3);
7534 
7535     Function *F = CGM.getIntrinsic(Intrinsic::prefetch, Address->getType());
7536     return Builder.CreateCall(F, {Address, RW, Locality, IsData});
7537   }
7538 
7539   if (BuiltinID == ARM::BI__builtin_arm_rbit) {
7540     llvm::Value *Arg = EmitScalarExpr(E->getArg(0));
7541     return Builder.CreateCall(
7542         CGM.getIntrinsic(Intrinsic::bitreverse, Arg->getType()), Arg, "rbit");
7543   }
7544 
7545   if (BuiltinID == ARM::BI__builtin_arm_cls) {
7546     llvm::Value *Arg = EmitScalarExpr(E->getArg(0));
7547     return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::arm_cls), Arg, "cls");
7548   }
7549   if (BuiltinID == ARM::BI__builtin_arm_cls64) {
7550     llvm::Value *Arg = EmitScalarExpr(E->getArg(0));
7551     return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::arm_cls64), Arg,
7552                               "cls");
7553   }
7554 
7555   if (BuiltinID == ARM::BI__clear_cache) {
7556     assert(E->getNumArgs() == 2 && "__clear_cache takes 2 arguments");
7557     const FunctionDecl *FD = E->getDirectCallee();
7558     Value *Ops[2];
7559     for (unsigned i = 0; i < 2; i++)
7560       Ops[i] = EmitScalarExpr(E->getArg(i));
7561     llvm::Type *Ty = CGM.getTypes().ConvertType(FD->getType());
7562     llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
7563     StringRef Name = FD->getName();
7564     return EmitNounwindRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name), Ops);
7565   }
7566 
7567   if (BuiltinID == ARM::BI__builtin_arm_mcrr ||
7568       BuiltinID == ARM::BI__builtin_arm_mcrr2) {
7569     Function *F;
7570 
7571     switch (BuiltinID) {
7572     default: llvm_unreachable("unexpected builtin");
7573     case ARM::BI__builtin_arm_mcrr:
7574       F = CGM.getIntrinsic(Intrinsic::arm_mcrr);
7575       break;
7576     case ARM::BI__builtin_arm_mcrr2:
7577       F = CGM.getIntrinsic(Intrinsic::arm_mcrr2);
7578       break;
7579     }
7580 
7581     // MCRR{2} instruction has 5 operands but
7582     // the intrinsic has 4 because Rt and Rt2
7583     // are represented as a single unsigned 64
7584     // bit integer in the intrinsic definition
7585     // but internally it's represented as 2 32
7586     // bit integers.
7587 
7588     Value *Coproc = EmitScalarExpr(E->getArg(0));
7589     Value *Opc1 = EmitScalarExpr(E->getArg(1));
7590     Value *RtAndRt2 = EmitScalarExpr(E->getArg(2));
7591     Value *CRm = EmitScalarExpr(E->getArg(3));
7592 
7593     Value *C1 = llvm::ConstantInt::get(Int64Ty, 32);
7594     Value *Rt = Builder.CreateTruncOrBitCast(RtAndRt2, Int32Ty);
7595     Value *Rt2 = Builder.CreateLShr(RtAndRt2, C1);
7596     Rt2 = Builder.CreateTruncOrBitCast(Rt2, Int32Ty);
7597 
7598     return Builder.CreateCall(F, {Coproc, Opc1, Rt, Rt2, CRm});
7599   }
7600 
7601   if (BuiltinID == ARM::BI__builtin_arm_mrrc ||
7602       BuiltinID == ARM::BI__builtin_arm_mrrc2) {
7603     Function *F;
7604 
7605     switch (BuiltinID) {
7606     default: llvm_unreachable("unexpected builtin");
7607     case ARM::BI__builtin_arm_mrrc:
7608       F = CGM.getIntrinsic(Intrinsic::arm_mrrc);
7609       break;
7610     case ARM::BI__builtin_arm_mrrc2:
7611       F = CGM.getIntrinsic(Intrinsic::arm_mrrc2);
7612       break;
7613     }
7614 
7615     Value *Coproc = EmitScalarExpr(E->getArg(0));
7616     Value *Opc1 = EmitScalarExpr(E->getArg(1));
7617     Value *CRm  = EmitScalarExpr(E->getArg(2));
7618     Value *RtAndRt2 = Builder.CreateCall(F, {Coproc, Opc1, CRm});
7619 
7620     // Returns an unsigned 64 bit integer, represented
7621     // as two 32 bit integers.
7622 
7623     Value *Rt = Builder.CreateExtractValue(RtAndRt2, 1);
7624     Value *Rt1 = Builder.CreateExtractValue(RtAndRt2, 0);
7625     Rt = Builder.CreateZExt(Rt, Int64Ty);
7626     Rt1 = Builder.CreateZExt(Rt1, Int64Ty);
7627 
7628     Value *ShiftCast = llvm::ConstantInt::get(Int64Ty, 32);
7629     RtAndRt2 = Builder.CreateShl(Rt, ShiftCast, "shl", true);
7630     RtAndRt2 = Builder.CreateOr(RtAndRt2, Rt1);
7631 
7632     return Builder.CreateBitCast(RtAndRt2, ConvertType(E->getType()));
7633   }
7634 
7635   if (BuiltinID == ARM::BI__builtin_arm_ldrexd ||
7636       ((BuiltinID == ARM::BI__builtin_arm_ldrex ||
7637         BuiltinID == ARM::BI__builtin_arm_ldaex) &&
7638        getContext().getTypeSize(E->getType()) == 64) ||
7639       BuiltinID == ARM::BI__ldrexd) {
7640     Function *F;
7641 
7642     switch (BuiltinID) {
7643     default: llvm_unreachable("unexpected builtin");
7644     case ARM::BI__builtin_arm_ldaex:
7645       F = CGM.getIntrinsic(Intrinsic::arm_ldaexd);
7646       break;
7647     case ARM::BI__builtin_arm_ldrexd:
7648     case ARM::BI__builtin_arm_ldrex:
7649     case ARM::BI__ldrexd:
7650       F = CGM.getIntrinsic(Intrinsic::arm_ldrexd);
7651       break;
7652     }
7653 
7654     Value *LdPtr = EmitScalarExpr(E->getArg(0));
7655     Value *Val = Builder.CreateCall(F, Builder.CreateBitCast(LdPtr, Int8PtrTy),
7656                                     "ldrexd");
7657 
7658     Value *Val0 = Builder.CreateExtractValue(Val, 1);
7659     Value *Val1 = Builder.CreateExtractValue(Val, 0);
7660     Val0 = Builder.CreateZExt(Val0, Int64Ty);
7661     Val1 = Builder.CreateZExt(Val1, Int64Ty);
7662 
7663     Value *ShiftCst = llvm::ConstantInt::get(Int64Ty, 32);
7664     Val = Builder.CreateShl(Val0, ShiftCst, "shl", true /* nuw */);
7665     Val = Builder.CreateOr(Val, Val1);
7666     return Builder.CreateBitCast(Val, ConvertType(E->getType()));
7667   }
7668 
7669   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
7670       BuiltinID == ARM::BI__builtin_arm_ldaex) {
7671     Value *LoadAddr = EmitScalarExpr(E->getArg(0));
7672 
7673     QualType Ty = E->getType();
7674     llvm::Type *RealResTy = ConvertType(Ty);
7675     llvm::Type *PtrTy = llvm::IntegerType::get(
7676         getLLVMContext(), getContext().getTypeSize(Ty))->getPointerTo();
7677     LoadAddr = Builder.CreateBitCast(LoadAddr, PtrTy);
7678 
7679     Function *F = CGM.getIntrinsic(BuiltinID == ARM::BI__builtin_arm_ldaex
7680                                        ? Intrinsic::arm_ldaex
7681                                        : Intrinsic::arm_ldrex,
7682                                    PtrTy);
7683     Value *Val = Builder.CreateCall(F, LoadAddr, "ldrex");
7684 
7685     if (RealResTy->isPointerTy())
7686       return Builder.CreateIntToPtr(Val, RealResTy);
7687     else {
7688       llvm::Type *IntResTy = llvm::IntegerType::get(
7689           getLLVMContext(), CGM.getDataLayout().getTypeSizeInBits(RealResTy));
7690       Val = Builder.CreateTruncOrBitCast(Val, IntResTy);
7691       return Builder.CreateBitCast(Val, RealResTy);
7692     }
7693   }
7694 
7695   if (BuiltinID == ARM::BI__builtin_arm_strexd ||
7696       ((BuiltinID == ARM::BI__builtin_arm_stlex ||
7697         BuiltinID == ARM::BI__builtin_arm_strex) &&
7698        getContext().getTypeSize(E->getArg(0)->getType()) == 64)) {
7699     Function *F = CGM.getIntrinsic(BuiltinID == ARM::BI__builtin_arm_stlex
7700                                        ? Intrinsic::arm_stlexd
7701                                        : Intrinsic::arm_strexd);
7702     llvm::Type *STy = llvm::StructType::get(Int32Ty, Int32Ty);
7703 
7704     Address Tmp = CreateMemTemp(E->getArg(0)->getType());
7705     Value *Val = EmitScalarExpr(E->getArg(0));
7706     Builder.CreateStore(Val, Tmp);
7707 
7708     Address LdPtr = Builder.CreateBitCast(Tmp,llvm::PointerType::getUnqual(STy));
7709     Val = Builder.CreateLoad(LdPtr);
7710 
7711     Value *Arg0 = Builder.CreateExtractValue(Val, 0);
7712     Value *Arg1 = Builder.CreateExtractValue(Val, 1);
7713     Value *StPtr = Builder.CreateBitCast(EmitScalarExpr(E->getArg(1)), Int8PtrTy);
7714     return Builder.CreateCall(F, {Arg0, Arg1, StPtr}, "strexd");
7715   }
7716 
7717   if (BuiltinID == ARM::BI__builtin_arm_strex ||
7718       BuiltinID == ARM::BI__builtin_arm_stlex) {
7719     Value *StoreVal = EmitScalarExpr(E->getArg(0));
7720     Value *StoreAddr = EmitScalarExpr(E->getArg(1));
7721 
7722     QualType Ty = E->getArg(0)->getType();
7723     llvm::Type *StoreTy = llvm::IntegerType::get(getLLVMContext(),
7724                                                  getContext().getTypeSize(Ty));
7725     StoreAddr = Builder.CreateBitCast(StoreAddr, StoreTy->getPointerTo());
7726 
7727     if (StoreVal->getType()->isPointerTy())
7728       StoreVal = Builder.CreatePtrToInt(StoreVal, Int32Ty);
7729     else {
7730       llvm::Type *IntTy = llvm::IntegerType::get(
7731           getLLVMContext(),
7732           CGM.getDataLayout().getTypeSizeInBits(StoreVal->getType()));
7733       StoreVal = Builder.CreateBitCast(StoreVal, IntTy);
7734       StoreVal = Builder.CreateZExtOrBitCast(StoreVal, Int32Ty);
7735     }
7736 
7737     Function *F = CGM.getIntrinsic(BuiltinID == ARM::BI__builtin_arm_stlex
7738                                        ? Intrinsic::arm_stlex
7739                                        : Intrinsic::arm_strex,
7740                                    StoreAddr->getType());
7741     return Builder.CreateCall(F, {StoreVal, StoreAddr}, "strex");
7742   }
7743 
7744   if (BuiltinID == ARM::BI__builtin_arm_clrex) {
7745     Function *F = CGM.getIntrinsic(Intrinsic::arm_clrex);
7746     return Builder.CreateCall(F);
7747   }
7748 
7749   // CRC32
7750   Intrinsic::ID CRCIntrinsicID = Intrinsic::not_intrinsic;
7751   switch (BuiltinID) {
7752   case ARM::BI__builtin_arm_crc32b:
7753     CRCIntrinsicID = Intrinsic::arm_crc32b; break;
7754   case ARM::BI__builtin_arm_crc32cb:
7755     CRCIntrinsicID = Intrinsic::arm_crc32cb; break;
7756   case ARM::BI__builtin_arm_crc32h:
7757     CRCIntrinsicID = Intrinsic::arm_crc32h; break;
7758   case ARM::BI__builtin_arm_crc32ch:
7759     CRCIntrinsicID = Intrinsic::arm_crc32ch; break;
7760   case ARM::BI__builtin_arm_crc32w:
7761   case ARM::BI__builtin_arm_crc32d:
7762     CRCIntrinsicID = Intrinsic::arm_crc32w; break;
7763   case ARM::BI__builtin_arm_crc32cw:
7764   case ARM::BI__builtin_arm_crc32cd:
7765     CRCIntrinsicID = Intrinsic::arm_crc32cw; break;
7766   }
7767 
7768   if (CRCIntrinsicID != Intrinsic::not_intrinsic) {
7769     Value *Arg0 = EmitScalarExpr(E->getArg(0));
7770     Value *Arg1 = EmitScalarExpr(E->getArg(1));
7771 
7772     // crc32{c,}d intrinsics are implemnted as two calls to crc32{c,}w
7773     // intrinsics, hence we need different codegen for these cases.
7774     if (BuiltinID == ARM::BI__builtin_arm_crc32d ||
7775         BuiltinID == ARM::BI__builtin_arm_crc32cd) {
7776       Value *C1 = llvm::ConstantInt::get(Int64Ty, 32);
7777       Value *Arg1a = Builder.CreateTruncOrBitCast(Arg1, Int32Ty);
7778       Value *Arg1b = Builder.CreateLShr(Arg1, C1);
7779       Arg1b = Builder.CreateTruncOrBitCast(Arg1b, Int32Ty);
7780 
7781       Function *F = CGM.getIntrinsic(CRCIntrinsicID);
7782       Value *Res = Builder.CreateCall(F, {Arg0, Arg1a});
7783       return Builder.CreateCall(F, {Res, Arg1b});
7784     } else {
7785       Arg1 = Builder.CreateZExtOrBitCast(Arg1, Int32Ty);
7786 
7787       Function *F = CGM.getIntrinsic(CRCIntrinsicID);
7788       return Builder.CreateCall(F, {Arg0, Arg1});
7789     }
7790   }
7791 
7792   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
7793       BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7794       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7795       BuiltinID == ARM::BI__builtin_arm_wsr ||
7796       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7797       BuiltinID == ARM::BI__builtin_arm_wsrp) {
7798 
7799     SpecialRegisterAccessKind AccessKind = Write;
7800     if (BuiltinID == ARM::BI__builtin_arm_rsr ||
7801         BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7802         BuiltinID == ARM::BI__builtin_arm_rsrp)
7803       AccessKind = VolatileRead;
7804 
7805     bool IsPointerBuiltin = BuiltinID == ARM::BI__builtin_arm_rsrp ||
7806                             BuiltinID == ARM::BI__builtin_arm_wsrp;
7807 
7808     bool Is64Bit = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7809                    BuiltinID == ARM::BI__builtin_arm_wsr64;
7810 
7811     llvm::Type *ValueType;
7812     llvm::Type *RegisterType;
7813     if (IsPointerBuiltin) {
7814       ValueType = VoidPtrTy;
7815       RegisterType = Int32Ty;
7816     } else if (Is64Bit) {
7817       ValueType = RegisterType = Int64Ty;
7818     } else {
7819       ValueType = RegisterType = Int32Ty;
7820     }
7821 
7822     return EmitSpecialRegisterBuiltin(*this, E, RegisterType, ValueType,
7823                                       AccessKind);
7824   }
7825 
7826   // Handle MSVC intrinsics before argument evaluation to prevent double
7827   // evaluation.
7828   if (Optional<MSVCIntrin> MsvcIntId = translateArmToMsvcIntrin(BuiltinID))
7829     return EmitMSVCBuiltinExpr(*MsvcIntId, E);
7830 
7831   // Deal with MVE builtins
7832   if (Value *Result = EmitARMMVEBuiltinExpr(BuiltinID, E, ReturnValue, Arch))
7833     return Result;
7834   // Handle CDE builtins
7835   if (Value *Result = EmitARMCDEBuiltinExpr(BuiltinID, E, ReturnValue, Arch))
7836     return Result;
7837 
7838   // Find out if any arguments are required to be integer constant
7839   // expressions.
7840   unsigned ICEArguments = 0;
7841   ASTContext::GetBuiltinTypeError Error;
7842   getContext().GetBuiltinType(BuiltinID, Error, &ICEArguments);
7843   assert(Error == ASTContext::GE_None && "Should not codegen an error");
7844 
7845   auto getAlignmentValue32 = [&](Address addr) -> Value* {
7846     return Builder.getInt32(addr.getAlignment().getQuantity());
7847   };
7848 
7849   Address PtrOp0 = Address::invalid();
7850   Address PtrOp1 = Address::invalid();
7851   SmallVector<Value*, 4> Ops;
7852   bool HasExtraArg = HasExtraNeonArgument(BuiltinID);
7853   unsigned NumArgs = E->getNumArgs() - (HasExtraArg ? 1 : 0);
7854   for (unsigned i = 0, e = NumArgs; i != e; i++) {
7855     if (i == 0) {
7856       switch (BuiltinID) {
7857       case NEON::BI__builtin_neon_vld1_v:
7858       case NEON::BI__builtin_neon_vld1q_v:
7859       case NEON::BI__builtin_neon_vld1q_lane_v:
7860       case NEON::BI__builtin_neon_vld1_lane_v:
7861       case NEON::BI__builtin_neon_vld1_dup_v:
7862       case NEON::BI__builtin_neon_vld1q_dup_v:
7863       case NEON::BI__builtin_neon_vst1_v:
7864       case NEON::BI__builtin_neon_vst1q_v:
7865       case NEON::BI__builtin_neon_vst1q_lane_v:
7866       case NEON::BI__builtin_neon_vst1_lane_v:
7867       case NEON::BI__builtin_neon_vst2_v:
7868       case NEON::BI__builtin_neon_vst2q_v:
7869       case NEON::BI__builtin_neon_vst2_lane_v:
7870       case NEON::BI__builtin_neon_vst2q_lane_v:
7871       case NEON::BI__builtin_neon_vst3_v:
7872       case NEON::BI__builtin_neon_vst3q_v:
7873       case NEON::BI__builtin_neon_vst3_lane_v:
7874       case NEON::BI__builtin_neon_vst3q_lane_v:
7875       case NEON::BI__builtin_neon_vst4_v:
7876       case NEON::BI__builtin_neon_vst4q_v:
7877       case NEON::BI__builtin_neon_vst4_lane_v:
7878       case NEON::BI__builtin_neon_vst4q_lane_v:
7879         // Get the alignment for the argument in addition to the value;
7880         // we'll use it later.
7881         PtrOp0 = EmitPointerWithAlignment(E->getArg(0));
7882         Ops.push_back(PtrOp0.getPointer());
7883         continue;
7884       }
7885     }
7886     if (i == 1) {
7887       switch (BuiltinID) {
7888       case NEON::BI__builtin_neon_vld2_v:
7889       case NEON::BI__builtin_neon_vld2q_v:
7890       case NEON::BI__builtin_neon_vld3_v:
7891       case NEON::BI__builtin_neon_vld3q_v:
7892       case NEON::BI__builtin_neon_vld4_v:
7893       case NEON::BI__builtin_neon_vld4q_v:
7894       case NEON::BI__builtin_neon_vld2_lane_v:
7895       case NEON::BI__builtin_neon_vld2q_lane_v:
7896       case NEON::BI__builtin_neon_vld3_lane_v:
7897       case NEON::BI__builtin_neon_vld3q_lane_v:
7898       case NEON::BI__builtin_neon_vld4_lane_v:
7899       case NEON::BI__builtin_neon_vld4q_lane_v:
7900       case NEON::BI__builtin_neon_vld2_dup_v:
7901       case NEON::BI__builtin_neon_vld2q_dup_v:
7902       case NEON::BI__builtin_neon_vld3_dup_v:
7903       case NEON::BI__builtin_neon_vld3q_dup_v:
7904       case NEON::BI__builtin_neon_vld4_dup_v:
7905       case NEON::BI__builtin_neon_vld4q_dup_v:
7906         // Get the alignment for the argument in addition to the value;
7907         // we'll use it later.
7908         PtrOp1 = EmitPointerWithAlignment(E->getArg(1));
7909         Ops.push_back(PtrOp1.getPointer());
7910         continue;
7911       }
7912     }
7913 
7914     if ((ICEArguments & (1 << i)) == 0) {
7915       Ops.push_back(EmitScalarExpr(E->getArg(i)));
7916     } else {
7917       // If this is required to be a constant, constant fold it so that we know
7918       // that the generated intrinsic gets a ConstantInt.
7919       Ops.push_back(llvm::ConstantInt::get(
7920           getLLVMContext(),
7921           *E->getArg(i)->getIntegerConstantExpr(getContext())));
7922     }
7923   }
7924 
7925   switch (BuiltinID) {
7926   default: break;
7927 
7928   case NEON::BI__builtin_neon_vget_lane_i8:
7929   case NEON::BI__builtin_neon_vget_lane_i16:
7930   case NEON::BI__builtin_neon_vget_lane_i32:
7931   case NEON::BI__builtin_neon_vget_lane_i64:
7932   case NEON::BI__builtin_neon_vget_lane_bf16:
7933   case NEON::BI__builtin_neon_vget_lane_f32:
7934   case NEON::BI__builtin_neon_vgetq_lane_i8:
7935   case NEON::BI__builtin_neon_vgetq_lane_i16:
7936   case NEON::BI__builtin_neon_vgetq_lane_i32:
7937   case NEON::BI__builtin_neon_vgetq_lane_i64:
7938   case NEON::BI__builtin_neon_vgetq_lane_bf16:
7939   case NEON::BI__builtin_neon_vgetq_lane_f32:
7940   case NEON::BI__builtin_neon_vduph_lane_bf16:
7941   case NEON::BI__builtin_neon_vduph_laneq_bf16:
7942     return Builder.CreateExtractElement(Ops[0], Ops[1], "vget_lane");
7943 
7944   case NEON::BI__builtin_neon_vrndns_f32: {
7945     Value *Arg = EmitScalarExpr(E->getArg(0));
7946     llvm::Type *Tys[] = {Arg->getType()};
7947     Function *F = CGM.getIntrinsic(Intrinsic::arm_neon_vrintn, Tys);
7948     return Builder.CreateCall(F, {Arg}, "vrndn"); }
7949 
7950   case NEON::BI__builtin_neon_vset_lane_i8:
7951   case NEON::BI__builtin_neon_vset_lane_i16:
7952   case NEON::BI__builtin_neon_vset_lane_i32:
7953   case NEON::BI__builtin_neon_vset_lane_i64:
7954   case NEON::BI__builtin_neon_vset_lane_bf16:
7955   case NEON::BI__builtin_neon_vset_lane_f32:
7956   case NEON::BI__builtin_neon_vsetq_lane_i8:
7957   case NEON::BI__builtin_neon_vsetq_lane_i16:
7958   case NEON::BI__builtin_neon_vsetq_lane_i32:
7959   case NEON::BI__builtin_neon_vsetq_lane_i64:
7960   case NEON::BI__builtin_neon_vsetq_lane_bf16:
7961   case NEON::BI__builtin_neon_vsetq_lane_f32:
7962     return Builder.CreateInsertElement(Ops[1], Ops[0], Ops[2], "vset_lane");
7963 
7964   case NEON::BI__builtin_neon_vsha1h_u32:
7965     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::arm_neon_sha1h), Ops,
7966                         "vsha1h");
7967   case NEON::BI__builtin_neon_vsha1cq_u32:
7968     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::arm_neon_sha1c), Ops,
7969                         "vsha1h");
7970   case NEON::BI__builtin_neon_vsha1pq_u32:
7971     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::arm_neon_sha1p), Ops,
7972                         "vsha1h");
7973   case NEON::BI__builtin_neon_vsha1mq_u32:
7974     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::arm_neon_sha1m), Ops,
7975                         "vsha1h");
7976 
7977   case NEON::BI__builtin_neon_vcvth_bf16_f32: {
7978     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::arm_neon_vcvtbfp2bf), Ops,
7979                         "vcvtbfp2bf");
7980   }
7981 
7982   // The ARM _MoveToCoprocessor builtins put the input register value as
7983   // the first argument, but the LLVM intrinsic expects it as the third one.
7984   case ARM::BI_MoveToCoprocessor:
7985   case ARM::BI_MoveToCoprocessor2: {
7986     Function *F = CGM.getIntrinsic(BuiltinID == ARM::BI_MoveToCoprocessor ?
7987                                    Intrinsic::arm_mcr : Intrinsic::arm_mcr2);
7988     return Builder.CreateCall(F, {Ops[1], Ops[2], Ops[0],
7989                                   Ops[3], Ops[4], Ops[5]});
7990   }
7991   }
7992 
7993   // Get the last argument, which specifies the vector type.
7994   assert(HasExtraArg);
7995   const Expr *Arg = E->getArg(E->getNumArgs()-1);
7996   Optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(getContext());
7997   if (!Result)
7998     return nullptr;
7999 
8000   if (BuiltinID == ARM::BI__builtin_arm_vcvtr_f ||
8001       BuiltinID == ARM::BI__builtin_arm_vcvtr_d) {
8002     // Determine the overloaded type of this builtin.
8003     llvm::Type *Ty;
8004     if (BuiltinID == ARM::BI__builtin_arm_vcvtr_f)
8005       Ty = FloatTy;
8006     else
8007       Ty = DoubleTy;
8008 
8009     // Determine whether this is an unsigned conversion or not.
8010     bool usgn = Result->getZExtValue() == 1;
8011     unsigned Int = usgn ? Intrinsic::arm_vcvtru : Intrinsic::arm_vcvtr;
8012 
8013     // Call the appropriate intrinsic.
8014     Function *F = CGM.getIntrinsic(Int, Ty);
8015     return Builder.CreateCall(F, Ops, "vcvtr");
8016   }
8017 
8018   // Determine the type of this overloaded NEON intrinsic.
8019   NeonTypeFlags Type = Result->getZExtValue();
8020   bool usgn = Type.isUnsigned();
8021   bool rightShift = false;
8022 
8023   llvm::FixedVectorType *VTy =
8024       GetNeonType(this, Type, getTarget().hasLegalHalfType(), false,
8025                   getTarget().hasBFloat16Type());
8026   llvm::Type *Ty = VTy;
8027   if (!Ty)
8028     return nullptr;
8029 
8030   // Many NEON builtins have identical semantics and uses in ARM and
8031   // AArch64. Emit these in a single function.
8032   auto IntrinsicMap = makeArrayRef(ARMSIMDIntrinsicMap);
8033   const ARMVectorIntrinsicInfo *Builtin = findARMVectorIntrinsicInMap(
8034       IntrinsicMap, BuiltinID, NEONSIMDIntrinsicsProvenSorted);
8035   if (Builtin)
8036     return EmitCommonNeonBuiltinExpr(
8037         Builtin->BuiltinID, Builtin->LLVMIntrinsic, Builtin->AltLLVMIntrinsic,
8038         Builtin->NameHint, Builtin->TypeModifier, E, Ops, PtrOp0, PtrOp1, Arch);
8039 
8040   unsigned Int;
8041   switch (BuiltinID) {
8042   default: return nullptr;
8043   case NEON::BI__builtin_neon_vld1q_lane_v:
8044     // Handle 64-bit integer elements as a special case.  Use shuffles of
8045     // one-element vectors to avoid poor code for i64 in the backend.
8046     if (VTy->getElementType()->isIntegerTy(64)) {
8047       // Extract the other lane.
8048       Ops[1] = Builder.CreateBitCast(Ops[1], Ty);
8049       int Lane = cast<ConstantInt>(Ops[2])->getZExtValue();
8050       Value *SV = llvm::ConstantVector::get(ConstantInt::get(Int32Ty, 1-Lane));
8051       Ops[1] = Builder.CreateShuffleVector(Ops[1], Ops[1], SV);
8052       // Load the value as a one-element vector.
8053       Ty = llvm::FixedVectorType::get(VTy->getElementType(), 1);
8054       llvm::Type *Tys[] = {Ty, Int8PtrTy};
8055       Function *F = CGM.getIntrinsic(Intrinsic::arm_neon_vld1, Tys);
8056       Value *Align = getAlignmentValue32(PtrOp0);
8057       Value *Ld = Builder.CreateCall(F, {Ops[0], Align});
8058       // Combine them.
8059       int Indices[] = {1 - Lane, Lane};
8060       return Builder.CreateShuffleVector(Ops[1], Ld, Indices, "vld1q_lane");
8061     }
8062     LLVM_FALLTHROUGH;
8063   case NEON::BI__builtin_neon_vld1_lane_v: {
8064     Ops[1] = Builder.CreateBitCast(Ops[1], Ty);
8065     PtrOp0 = Builder.CreateElementBitCast(PtrOp0, VTy->getElementType());
8066     Value *Ld = Builder.CreateLoad(PtrOp0);
8067     return Builder.CreateInsertElement(Ops[1], Ld, Ops[2], "vld1_lane");
8068   }
8069   case NEON::BI__builtin_neon_vqrshrn_n_v:
8070     Int =
8071       usgn ? Intrinsic::arm_neon_vqrshiftnu : Intrinsic::arm_neon_vqrshiftns;
8072     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vqrshrn_n",
8073                         1, true);
8074   case NEON::BI__builtin_neon_vqrshrun_n_v:
8075     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::arm_neon_vqrshiftnsu, Ty),
8076                         Ops, "vqrshrun_n", 1, true);
8077   case NEON::BI__builtin_neon_vqshrn_n_v:
8078     Int = usgn ? Intrinsic::arm_neon_vqshiftnu : Intrinsic::arm_neon_vqshiftns;
8079     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vqshrn_n",
8080                         1, true);
8081   case NEON::BI__builtin_neon_vqshrun_n_v:
8082     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::arm_neon_vqshiftnsu, Ty),
8083                         Ops, "vqshrun_n", 1, true);
8084   case NEON::BI__builtin_neon_vrecpe_v:
8085   case NEON::BI__builtin_neon_vrecpeq_v:
8086     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::arm_neon_vrecpe, Ty),
8087                         Ops, "vrecpe");
8088   case NEON::BI__builtin_neon_vrshrn_n_v:
8089     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::arm_neon_vrshiftn, Ty),
8090                         Ops, "vrshrn_n", 1, true);
8091   case NEON::BI__builtin_neon_vrsra_n_v:
8092   case NEON::BI__builtin_neon_vrsraq_n_v:
8093     Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
8094     Ops[1] = Builder.CreateBitCast(Ops[1], Ty);
8095     Ops[2] = EmitNeonShiftVector(Ops[2], Ty, true);
8096     Int = usgn ? Intrinsic::arm_neon_vrshiftu : Intrinsic::arm_neon_vrshifts;
8097     Ops[1] = Builder.CreateCall(CGM.getIntrinsic(Int, Ty), {Ops[1], Ops[2]});
8098     return Builder.CreateAdd(Ops[0], Ops[1], "vrsra_n");
8099   case NEON::BI__builtin_neon_vsri_n_v:
8100   case NEON::BI__builtin_neon_vsriq_n_v:
8101     rightShift = true;
8102     LLVM_FALLTHROUGH;
8103   case NEON::BI__builtin_neon_vsli_n_v:
8104   case NEON::BI__builtin_neon_vsliq_n_v:
8105     Ops[2] = EmitNeonShiftVector(Ops[2], Ty, rightShift);
8106     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::arm_neon_vshiftins, Ty),
8107                         Ops, "vsli_n");
8108   case NEON::BI__builtin_neon_vsra_n_v:
8109   case NEON::BI__builtin_neon_vsraq_n_v:
8110     Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
8111     Ops[1] = EmitNeonRShiftImm(Ops[1], Ops[2], Ty, usgn, "vsra_n");
8112     return Builder.CreateAdd(Ops[0], Ops[1]);
8113   case NEON::BI__builtin_neon_vst1q_lane_v:
8114     // Handle 64-bit integer elements as a special case.  Use a shuffle to get
8115     // a one-element vector and avoid poor code for i64 in the backend.
8116     if (VTy->getElementType()->isIntegerTy(64)) {
8117       Ops[1] = Builder.CreateBitCast(Ops[1], Ty);
8118       Value *SV = llvm::ConstantVector::get(cast<llvm::Constant>(Ops[2]));
8119       Ops[1] = Builder.CreateShuffleVector(Ops[1], Ops[1], SV);
8120       Ops[2] = getAlignmentValue32(PtrOp0);
8121       llvm::Type *Tys[] = {Int8PtrTy, Ops[1]->getType()};
8122       return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::arm_neon_vst1,
8123                                                  Tys), Ops);
8124     }
8125     LLVM_FALLTHROUGH;
8126   case NEON::BI__builtin_neon_vst1_lane_v: {
8127     Ops[1] = Builder.CreateBitCast(Ops[1], Ty);
8128     Ops[1] = Builder.CreateExtractElement(Ops[1], Ops[2]);
8129     Ty = llvm::PointerType::getUnqual(Ops[1]->getType());
8130     auto St = Builder.CreateStore(Ops[1], Builder.CreateBitCast(PtrOp0, Ty));
8131     return St;
8132   }
8133   case NEON::BI__builtin_neon_vtbl1_v:
8134     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::arm_neon_vtbl1),
8135                         Ops, "vtbl1");
8136   case NEON::BI__builtin_neon_vtbl2_v:
8137     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::arm_neon_vtbl2),
8138                         Ops, "vtbl2");
8139   case NEON::BI__builtin_neon_vtbl3_v:
8140     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::arm_neon_vtbl3),
8141                         Ops, "vtbl3");
8142   case NEON::BI__builtin_neon_vtbl4_v:
8143     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::arm_neon_vtbl4),
8144                         Ops, "vtbl4");
8145   case NEON::BI__builtin_neon_vtbx1_v:
8146     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::arm_neon_vtbx1),
8147                         Ops, "vtbx1");
8148   case NEON::BI__builtin_neon_vtbx2_v:
8149     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::arm_neon_vtbx2),
8150                         Ops, "vtbx2");
8151   case NEON::BI__builtin_neon_vtbx3_v:
8152     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::arm_neon_vtbx3),
8153                         Ops, "vtbx3");
8154   case NEON::BI__builtin_neon_vtbx4_v:
8155     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::arm_neon_vtbx4),
8156                         Ops, "vtbx4");
8157   }
8158 }
8159 
8160 template<typename Integer>
8161 static Integer GetIntegerConstantValue(const Expr *E, ASTContext &Context) {
8162   return E->getIntegerConstantExpr(Context)->getExtValue();
8163 }
8164 
8165 static llvm::Value *SignOrZeroExtend(CGBuilderTy &Builder, llvm::Value *V,
8166                                      llvm::Type *T, bool Unsigned) {
8167   // Helper function called by Tablegen-constructed ARM MVE builtin codegen,
8168   // which finds it convenient to specify signed/unsigned as a boolean flag.
8169   return Unsigned ? Builder.CreateZExt(V, T) : Builder.CreateSExt(V, T);
8170 }
8171 
8172 static llvm::Value *MVEImmediateShr(CGBuilderTy &Builder, llvm::Value *V,
8173                                     uint32_t Shift, bool Unsigned) {
8174   // MVE helper function for integer shift right. This must handle signed vs
8175   // unsigned, and also deal specially with the case where the shift count is
8176   // equal to the lane size. In LLVM IR, an LShr with that parameter would be
8177   // undefined behavior, but in MVE it's legal, so we must convert it to code
8178   // that is not undefined in IR.
8179   unsigned LaneBits = cast<llvm::VectorType>(V->getType())
8180                           ->getElementType()
8181                           ->getPrimitiveSizeInBits();
8182   if (Shift == LaneBits) {
8183     // An unsigned shift of the full lane size always generates zero, so we can
8184     // simply emit a zero vector. A signed shift of the full lane size does the
8185     // same thing as shifting by one bit fewer.
8186     if (Unsigned)
8187       return llvm::Constant::getNullValue(V->getType());
8188     else
8189       --Shift;
8190   }
8191   return Unsigned ? Builder.CreateLShr(V, Shift) : Builder.CreateAShr(V, Shift);
8192 }
8193 
8194 static llvm::Value *ARMMVEVectorSplat(CGBuilderTy &Builder, llvm::Value *V) {
8195   // MVE-specific helper function for a vector splat, which infers the element
8196   // count of the output vector by knowing that MVE vectors are all 128 bits
8197   // wide.
8198   unsigned Elements = 128 / V->getType()->getPrimitiveSizeInBits();
8199   return Builder.CreateVectorSplat(Elements, V);
8200 }
8201 
8202 static llvm::Value *ARMMVEVectorReinterpret(CGBuilderTy &Builder,
8203                                             CodeGenFunction *CGF,
8204                                             llvm::Value *V,
8205                                             llvm::Type *DestType) {
8206   // Convert one MVE vector type into another by reinterpreting its in-register
8207   // format.
8208   //
8209   // Little-endian, this is identical to a bitcast (which reinterprets the
8210   // memory format). But big-endian, they're not necessarily the same, because
8211   // the register and memory formats map to each other differently depending on
8212   // the lane size.
8213   //
8214   // We generate a bitcast whenever we can (if we're little-endian, or if the
8215   // lane sizes are the same anyway). Otherwise we fall back to an IR intrinsic
8216   // that performs the different kind of reinterpretation.
8217   if (CGF->getTarget().isBigEndian() &&
8218       V->getType()->getScalarSizeInBits() != DestType->getScalarSizeInBits()) {
8219     return Builder.CreateCall(
8220         CGF->CGM.getIntrinsic(Intrinsic::arm_mve_vreinterpretq,
8221                               {DestType, V->getType()}),
8222         V);
8223   } else {
8224     return Builder.CreateBitCast(V, DestType);
8225   }
8226 }
8227 
8228 static llvm::Value *VectorUnzip(CGBuilderTy &Builder, llvm::Value *V, bool Odd) {
8229   // Make a shufflevector that extracts every other element of a vector (evens
8230   // or odds, as desired).
8231   SmallVector<int, 16> Indices;
8232   unsigned InputElements =
8233       cast<llvm::FixedVectorType>(V->getType())->getNumElements();
8234   for (unsigned i = 0; i < InputElements; i += 2)
8235     Indices.push_back(i + Odd);
8236   return Builder.CreateShuffleVector(V, Indices);
8237 }
8238 
8239 static llvm::Value *VectorZip(CGBuilderTy &Builder, llvm::Value *V0,
8240                               llvm::Value *V1) {
8241   // Make a shufflevector that interleaves two vectors element by element.
8242   assert(V0->getType() == V1->getType() && "Can't zip different vector types");
8243   SmallVector<int, 16> Indices;
8244   unsigned InputElements =
8245       cast<llvm::FixedVectorType>(V0->getType())->getNumElements();
8246   for (unsigned i = 0; i < InputElements; i++) {
8247     Indices.push_back(i);
8248     Indices.push_back(i + InputElements);
8249   }
8250   return Builder.CreateShuffleVector(V0, V1, Indices);
8251 }
8252 
8253 template<unsigned HighBit, unsigned OtherBits>
8254 static llvm::Value *ARMMVEConstantSplat(CGBuilderTy &Builder, llvm::Type *VT) {
8255   // MVE-specific helper function to make a vector splat of a constant such as
8256   // UINT_MAX or INT_MIN, in which all bits below the highest one are equal.
8257   llvm::Type *T = cast<llvm::VectorType>(VT)->getElementType();
8258   unsigned LaneBits = T->getPrimitiveSizeInBits();
8259   uint32_t Value = HighBit << (LaneBits - 1);
8260   if (OtherBits)
8261     Value |= (1UL << (LaneBits - 1)) - 1;
8262   llvm::Value *Lane = llvm::ConstantInt::get(T, Value);
8263   return ARMMVEVectorSplat(Builder, Lane);
8264 }
8265 
8266 static llvm::Value *ARMMVEVectorElementReverse(CGBuilderTy &Builder,
8267                                                llvm::Value *V,
8268                                                unsigned ReverseWidth) {
8269   // MVE-specific helper function which reverses the elements of a
8270   // vector within every (ReverseWidth)-bit collection of lanes.
8271   SmallVector<int, 16> Indices;
8272   unsigned LaneSize = V->getType()->getScalarSizeInBits();
8273   unsigned Elements = 128 / LaneSize;
8274   unsigned Mask = ReverseWidth / LaneSize - 1;
8275   for (unsigned i = 0; i < Elements; i++)
8276     Indices.push_back(i ^ Mask);
8277   return Builder.CreateShuffleVector(V, Indices);
8278 }
8279 
8280 Value *CodeGenFunction::EmitARMMVEBuiltinExpr(unsigned BuiltinID,
8281                                               const CallExpr *E,
8282                                               ReturnValueSlot ReturnValue,
8283                                               llvm::Triple::ArchType Arch) {
8284   enum class CustomCodeGen { VLD24, VST24 } CustomCodeGenType;
8285   Intrinsic::ID IRIntr;
8286   unsigned NumVectors;
8287 
8288   // Code autogenerated by Tablegen will handle all the simple builtins.
8289   switch (BuiltinID) {
8290     #include "clang/Basic/arm_mve_builtin_cg.inc"
8291 
8292     // If we didn't match an MVE builtin id at all, go back to the
8293     // main EmitARMBuiltinExpr.
8294   default:
8295     return nullptr;
8296   }
8297 
8298   // Anything that breaks from that switch is an MVE builtin that
8299   // needs handwritten code to generate.
8300 
8301   switch (CustomCodeGenType) {
8302 
8303   case CustomCodeGen::VLD24: {
8304     llvm::SmallVector<Value *, 4> Ops;
8305     llvm::SmallVector<llvm::Type *, 4> Tys;
8306 
8307     auto MvecCType = E->getType();
8308     auto MvecLType = ConvertType(MvecCType);
8309     assert(MvecLType->isStructTy() &&
8310            "Return type for vld[24]q should be a struct");
8311     assert(MvecLType->getStructNumElements() == 1 &&
8312            "Return-type struct for vld[24]q should have one element");
8313     auto MvecLTypeInner = MvecLType->getStructElementType(0);
8314     assert(MvecLTypeInner->isArrayTy() &&
8315            "Return-type struct for vld[24]q should contain an array");
8316     assert(MvecLTypeInner->getArrayNumElements() == NumVectors &&
8317            "Array member of return-type struct vld[24]q has wrong length");
8318     auto VecLType = MvecLTypeInner->getArrayElementType();
8319 
8320     Tys.push_back(VecLType);
8321 
8322     auto Addr = E->getArg(0);
8323     Ops.push_back(EmitScalarExpr(Addr));
8324     Tys.push_back(ConvertType(Addr->getType()));
8325 
8326     Function *F = CGM.getIntrinsic(IRIntr, makeArrayRef(Tys));
8327     Value *LoadResult = Builder.CreateCall(F, Ops);
8328     Value *MvecOut = UndefValue::get(MvecLType);
8329     for (unsigned i = 0; i < NumVectors; ++i) {
8330       Value *Vec = Builder.CreateExtractValue(LoadResult, i);
8331       MvecOut = Builder.CreateInsertValue(MvecOut, Vec, {0, i});
8332     }
8333 
8334     if (ReturnValue.isNull())
8335       return MvecOut;
8336     else
8337       return Builder.CreateStore(MvecOut, ReturnValue.getValue());
8338   }
8339 
8340   case CustomCodeGen::VST24: {
8341     llvm::SmallVector<Value *, 4> Ops;
8342     llvm::SmallVector<llvm::Type *, 4> Tys;
8343 
8344     auto Addr = E->getArg(0);
8345     Ops.push_back(EmitScalarExpr(Addr));
8346     Tys.push_back(ConvertType(Addr->getType()));
8347 
8348     auto MvecCType = E->getArg(1)->getType();
8349     auto MvecLType = ConvertType(MvecCType);
8350     assert(MvecLType->isStructTy() && "Data type for vst2q should be a struct");
8351     assert(MvecLType->getStructNumElements() == 1 &&
8352            "Data-type struct for vst2q should have one element");
8353     auto MvecLTypeInner = MvecLType->getStructElementType(0);
8354     assert(MvecLTypeInner->isArrayTy() &&
8355            "Data-type struct for vst2q should contain an array");
8356     assert(MvecLTypeInner->getArrayNumElements() == NumVectors &&
8357            "Array member of return-type struct vld[24]q has wrong length");
8358     auto VecLType = MvecLTypeInner->getArrayElementType();
8359 
8360     Tys.push_back(VecLType);
8361 
8362     AggValueSlot MvecSlot = CreateAggTemp(MvecCType);
8363     EmitAggExpr(E->getArg(1), MvecSlot);
8364     auto Mvec = Builder.CreateLoad(MvecSlot.getAddress());
8365     for (unsigned i = 0; i < NumVectors; i++)
8366       Ops.push_back(Builder.CreateExtractValue(Mvec, {0, i}));
8367 
8368     Function *F = CGM.getIntrinsic(IRIntr, makeArrayRef(Tys));
8369     Value *ToReturn = nullptr;
8370     for (unsigned i = 0; i < NumVectors; i++) {
8371       Ops.push_back(llvm::ConstantInt::get(Int32Ty, i));
8372       ToReturn = Builder.CreateCall(F, Ops);
8373       Ops.pop_back();
8374     }
8375     return ToReturn;
8376   }
8377   }
8378   llvm_unreachable("unknown custom codegen type.");
8379 }
8380 
8381 Value *CodeGenFunction::EmitARMCDEBuiltinExpr(unsigned BuiltinID,
8382                                               const CallExpr *E,
8383                                               ReturnValueSlot ReturnValue,
8384                                               llvm::Triple::ArchType Arch) {
8385   switch (BuiltinID) {
8386   default:
8387     return nullptr;
8388 #include "clang/Basic/arm_cde_builtin_cg.inc"
8389   }
8390 }
8391 
8392 static Value *EmitAArch64TblBuiltinExpr(CodeGenFunction &CGF, unsigned BuiltinID,
8393                                       const CallExpr *E,
8394                                       SmallVectorImpl<Value *> &Ops,
8395                                       llvm::Triple::ArchType Arch) {
8396   unsigned int Int = 0;
8397   const char *s = nullptr;
8398 
8399   switch (BuiltinID) {
8400   default:
8401     return nullptr;
8402   case NEON::BI__builtin_neon_vtbl1_v:
8403   case NEON::BI__builtin_neon_vqtbl1_v:
8404   case NEON::BI__builtin_neon_vqtbl1q_v:
8405   case NEON::BI__builtin_neon_vtbl2_v:
8406   case NEON::BI__builtin_neon_vqtbl2_v:
8407   case NEON::BI__builtin_neon_vqtbl2q_v:
8408   case NEON::BI__builtin_neon_vtbl3_v:
8409   case NEON::BI__builtin_neon_vqtbl3_v:
8410   case NEON::BI__builtin_neon_vqtbl3q_v:
8411   case NEON::BI__builtin_neon_vtbl4_v:
8412   case NEON::BI__builtin_neon_vqtbl4_v:
8413   case NEON::BI__builtin_neon_vqtbl4q_v:
8414     break;
8415   case NEON::BI__builtin_neon_vtbx1_v:
8416   case NEON::BI__builtin_neon_vqtbx1_v:
8417   case NEON::BI__builtin_neon_vqtbx1q_v:
8418   case NEON::BI__builtin_neon_vtbx2_v:
8419   case NEON::BI__builtin_neon_vqtbx2_v:
8420   case NEON::BI__builtin_neon_vqtbx2q_v:
8421   case NEON::BI__builtin_neon_vtbx3_v:
8422   case NEON::BI__builtin_neon_vqtbx3_v:
8423   case NEON::BI__builtin_neon_vqtbx3q_v:
8424   case NEON::BI__builtin_neon_vtbx4_v:
8425   case NEON::BI__builtin_neon_vqtbx4_v:
8426   case NEON::BI__builtin_neon_vqtbx4q_v:
8427     break;
8428   }
8429 
8430   assert(E->getNumArgs() >= 3);
8431 
8432   // Get the last argument, which specifies the vector type.
8433   const Expr *Arg = E->getArg(E->getNumArgs() - 1);
8434   Optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(CGF.getContext());
8435   if (!Result)
8436     return nullptr;
8437 
8438   // Determine the type of this overloaded NEON intrinsic.
8439   NeonTypeFlags Type = Result->getZExtValue();
8440   llvm::FixedVectorType *Ty = GetNeonType(&CGF, Type);
8441   if (!Ty)
8442     return nullptr;
8443 
8444   CodeGen::CGBuilderTy &Builder = CGF.Builder;
8445 
8446   // AArch64 scalar builtins are not overloaded, they do not have an extra
8447   // argument that specifies the vector type, need to handle each case.
8448   switch (BuiltinID) {
8449   case NEON::BI__builtin_neon_vtbl1_v: {
8450     return packTBLDVectorList(CGF, makeArrayRef(Ops).slice(0, 1), nullptr,
8451                               Ops[1], Ty, Intrinsic::aarch64_neon_tbl1,
8452                               "vtbl1");
8453   }
8454   case NEON::BI__builtin_neon_vtbl2_v: {
8455     return packTBLDVectorList(CGF, makeArrayRef(Ops).slice(0, 2), nullptr,
8456                               Ops[2], Ty, Intrinsic::aarch64_neon_tbl1,
8457                               "vtbl1");
8458   }
8459   case NEON::BI__builtin_neon_vtbl3_v: {
8460     return packTBLDVectorList(CGF, makeArrayRef(Ops).slice(0, 3), nullptr,
8461                               Ops[3], Ty, Intrinsic::aarch64_neon_tbl2,
8462                               "vtbl2");
8463   }
8464   case NEON::BI__builtin_neon_vtbl4_v: {
8465     return packTBLDVectorList(CGF, makeArrayRef(Ops).slice(0, 4), nullptr,
8466                               Ops[4], Ty, Intrinsic::aarch64_neon_tbl2,
8467                               "vtbl2");
8468   }
8469   case NEON::BI__builtin_neon_vtbx1_v: {
8470     Value *TblRes =
8471         packTBLDVectorList(CGF, makeArrayRef(Ops).slice(1, 1), nullptr, Ops[2],
8472                            Ty, Intrinsic::aarch64_neon_tbl1, "vtbl1");
8473 
8474     llvm::Constant *EightV = ConstantInt::get(Ty, 8);
8475     Value *CmpRes = Builder.CreateICmp(ICmpInst::ICMP_UGE, Ops[2], EightV);
8476     CmpRes = Builder.CreateSExt(CmpRes, Ty);
8477 
8478     Value *EltsFromInput = Builder.CreateAnd(CmpRes, Ops[0]);
8479     Value *EltsFromTbl = Builder.CreateAnd(Builder.CreateNot(CmpRes), TblRes);
8480     return Builder.CreateOr(EltsFromInput, EltsFromTbl, "vtbx");
8481   }
8482   case NEON::BI__builtin_neon_vtbx2_v: {
8483     return packTBLDVectorList(CGF, makeArrayRef(Ops).slice(1, 2), Ops[0],
8484                               Ops[3], Ty, Intrinsic::aarch64_neon_tbx1,
8485                               "vtbx1");
8486   }
8487   case NEON::BI__builtin_neon_vtbx3_v: {
8488     Value *TblRes =
8489         packTBLDVectorList(CGF, makeArrayRef(Ops).slice(1, 3), nullptr, Ops[4],
8490                            Ty, Intrinsic::aarch64_neon_tbl2, "vtbl2");
8491 
8492     llvm::Constant *TwentyFourV = ConstantInt::get(Ty, 24);
8493     Value *CmpRes = Builder.CreateICmp(ICmpInst::ICMP_UGE, Ops[4],
8494                                            TwentyFourV);
8495     CmpRes = Builder.CreateSExt(CmpRes, Ty);
8496 
8497     Value *EltsFromInput = Builder.CreateAnd(CmpRes, Ops[0]);
8498     Value *EltsFromTbl = Builder.CreateAnd(Builder.CreateNot(CmpRes), TblRes);
8499     return Builder.CreateOr(EltsFromInput, EltsFromTbl, "vtbx");
8500   }
8501   case NEON::BI__builtin_neon_vtbx4_v: {
8502     return packTBLDVectorList(CGF, makeArrayRef(Ops).slice(1, 4), Ops[0],
8503                               Ops[5], Ty, Intrinsic::aarch64_neon_tbx2,
8504                               "vtbx2");
8505   }
8506   case NEON::BI__builtin_neon_vqtbl1_v:
8507   case NEON::BI__builtin_neon_vqtbl1q_v:
8508     Int = Intrinsic::aarch64_neon_tbl1; s = "vtbl1"; break;
8509   case NEON::BI__builtin_neon_vqtbl2_v:
8510   case NEON::BI__builtin_neon_vqtbl2q_v: {
8511     Int = Intrinsic::aarch64_neon_tbl2; s = "vtbl2"; break;
8512   case NEON::BI__builtin_neon_vqtbl3_v:
8513   case NEON::BI__builtin_neon_vqtbl3q_v:
8514     Int = Intrinsic::aarch64_neon_tbl3; s = "vtbl3"; break;
8515   case NEON::BI__builtin_neon_vqtbl4_v:
8516   case NEON::BI__builtin_neon_vqtbl4q_v:
8517     Int = Intrinsic::aarch64_neon_tbl4; s = "vtbl4"; break;
8518   case NEON::BI__builtin_neon_vqtbx1_v:
8519   case NEON::BI__builtin_neon_vqtbx1q_v:
8520     Int = Intrinsic::aarch64_neon_tbx1; s = "vtbx1"; break;
8521   case NEON::BI__builtin_neon_vqtbx2_v:
8522   case NEON::BI__builtin_neon_vqtbx2q_v:
8523     Int = Intrinsic::aarch64_neon_tbx2; s = "vtbx2"; break;
8524   case NEON::BI__builtin_neon_vqtbx3_v:
8525   case NEON::BI__builtin_neon_vqtbx3q_v:
8526     Int = Intrinsic::aarch64_neon_tbx3; s = "vtbx3"; break;
8527   case NEON::BI__builtin_neon_vqtbx4_v:
8528   case NEON::BI__builtin_neon_vqtbx4q_v:
8529     Int = Intrinsic::aarch64_neon_tbx4; s = "vtbx4"; break;
8530   }
8531   }
8532 
8533   if (!Int)
8534     return nullptr;
8535 
8536   Function *F = CGF.CGM.getIntrinsic(Int, Ty);
8537   return CGF.EmitNeonCall(F, Ops, s);
8538 }
8539 
8540 Value *CodeGenFunction::vectorWrapScalar16(Value *Op) {
8541   auto *VTy = llvm::FixedVectorType::get(Int16Ty, 4);
8542   Op = Builder.CreateBitCast(Op, Int16Ty);
8543   Value *V = UndefValue::get(VTy);
8544   llvm::Constant *CI = ConstantInt::get(SizeTy, 0);
8545   Op = Builder.CreateInsertElement(V, Op, CI);
8546   return Op;
8547 }
8548 
8549 /// SVEBuiltinMemEltTy - Returns the memory element type for this memory
8550 /// access builtin.  Only required if it can't be inferred from the base pointer
8551 /// operand.
8552 llvm::Type *CodeGenFunction::SVEBuiltinMemEltTy(const SVETypeFlags &TypeFlags) {
8553   switch (TypeFlags.getMemEltType()) {
8554   case SVETypeFlags::MemEltTyDefault:
8555     return getEltType(TypeFlags);
8556   case SVETypeFlags::MemEltTyInt8:
8557     return Builder.getInt8Ty();
8558   case SVETypeFlags::MemEltTyInt16:
8559     return Builder.getInt16Ty();
8560   case SVETypeFlags::MemEltTyInt32:
8561     return Builder.getInt32Ty();
8562   case SVETypeFlags::MemEltTyInt64:
8563     return Builder.getInt64Ty();
8564   }
8565   llvm_unreachable("Unknown MemEltType");
8566 }
8567 
8568 llvm::Type *CodeGenFunction::getEltType(const SVETypeFlags &TypeFlags) {
8569   switch (TypeFlags.getEltType()) {
8570   default:
8571     llvm_unreachable("Invalid SVETypeFlag!");
8572 
8573   case SVETypeFlags::EltTyInt8:
8574     return Builder.getInt8Ty();
8575   case SVETypeFlags::EltTyInt16:
8576     return Builder.getInt16Ty();
8577   case SVETypeFlags::EltTyInt32:
8578     return Builder.getInt32Ty();
8579   case SVETypeFlags::EltTyInt64:
8580     return Builder.getInt64Ty();
8581 
8582   case SVETypeFlags::EltTyFloat16:
8583     return Builder.getHalfTy();
8584   case SVETypeFlags::EltTyFloat32:
8585     return Builder.getFloatTy();
8586   case SVETypeFlags::EltTyFloat64:
8587     return Builder.getDoubleTy();
8588 
8589   case SVETypeFlags::EltTyBFloat16:
8590     return Builder.getBFloatTy();
8591 
8592   case SVETypeFlags::EltTyBool8:
8593   case SVETypeFlags::EltTyBool16:
8594   case SVETypeFlags::EltTyBool32:
8595   case SVETypeFlags::EltTyBool64:
8596     return Builder.getInt1Ty();
8597   }
8598 }
8599 
8600 // Return the llvm predicate vector type corresponding to the specified element
8601 // TypeFlags.
8602 llvm::ScalableVectorType *
8603 CodeGenFunction::getSVEPredType(const SVETypeFlags &TypeFlags) {
8604   switch (TypeFlags.getEltType()) {
8605   default: llvm_unreachable("Unhandled SVETypeFlag!");
8606 
8607   case SVETypeFlags::EltTyInt8:
8608     return llvm::ScalableVectorType::get(Builder.getInt1Ty(), 16);
8609   case SVETypeFlags::EltTyInt16:
8610     return llvm::ScalableVectorType::get(Builder.getInt1Ty(), 8);
8611   case SVETypeFlags::EltTyInt32:
8612     return llvm::ScalableVectorType::get(Builder.getInt1Ty(), 4);
8613   case SVETypeFlags::EltTyInt64:
8614     return llvm::ScalableVectorType::get(Builder.getInt1Ty(), 2);
8615 
8616   case SVETypeFlags::EltTyBFloat16:
8617     return llvm::ScalableVectorType::get(Builder.getInt1Ty(), 8);
8618   case SVETypeFlags::EltTyFloat16:
8619     return llvm::ScalableVectorType::get(Builder.getInt1Ty(), 8);
8620   case SVETypeFlags::EltTyFloat32:
8621     return llvm::ScalableVectorType::get(Builder.getInt1Ty(), 4);
8622   case SVETypeFlags::EltTyFloat64:
8623     return llvm::ScalableVectorType::get(Builder.getInt1Ty(), 2);
8624 
8625   case SVETypeFlags::EltTyBool8:
8626     return llvm::ScalableVectorType::get(Builder.getInt1Ty(), 16);
8627   case SVETypeFlags::EltTyBool16:
8628     return llvm::ScalableVectorType::get(Builder.getInt1Ty(), 8);
8629   case SVETypeFlags::EltTyBool32:
8630     return llvm::ScalableVectorType::get(Builder.getInt1Ty(), 4);
8631   case SVETypeFlags::EltTyBool64:
8632     return llvm::ScalableVectorType::get(Builder.getInt1Ty(), 2);
8633   }
8634 }
8635 
8636 // Return the llvm vector type corresponding to the specified element TypeFlags.
8637 llvm::ScalableVectorType *
8638 CodeGenFunction::getSVEType(const SVETypeFlags &TypeFlags) {
8639   switch (TypeFlags.getEltType()) {
8640   default:
8641     llvm_unreachable("Invalid SVETypeFlag!");
8642 
8643   case SVETypeFlags::EltTyInt8:
8644     return llvm::ScalableVectorType::get(Builder.getInt8Ty(), 16);
8645   case SVETypeFlags::EltTyInt16:
8646     return llvm::ScalableVectorType::get(Builder.getInt16Ty(), 8);
8647   case SVETypeFlags::EltTyInt32:
8648     return llvm::ScalableVectorType::get(Builder.getInt32Ty(), 4);
8649   case SVETypeFlags::EltTyInt64:
8650     return llvm::ScalableVectorType::get(Builder.getInt64Ty(), 2);
8651 
8652   case SVETypeFlags::EltTyFloat16:
8653     return llvm::ScalableVectorType::get(Builder.getHalfTy(), 8);
8654   case SVETypeFlags::EltTyBFloat16:
8655     return llvm::ScalableVectorType::get(Builder.getBFloatTy(), 8);
8656   case SVETypeFlags::EltTyFloat32:
8657     return llvm::ScalableVectorType::get(Builder.getFloatTy(), 4);
8658   case SVETypeFlags::EltTyFloat64:
8659     return llvm::ScalableVectorType::get(Builder.getDoubleTy(), 2);
8660 
8661   case SVETypeFlags::EltTyBool8:
8662     return llvm::ScalableVectorType::get(Builder.getInt1Ty(), 16);
8663   case SVETypeFlags::EltTyBool16:
8664     return llvm::ScalableVectorType::get(Builder.getInt1Ty(), 8);
8665   case SVETypeFlags::EltTyBool32:
8666     return llvm::ScalableVectorType::get(Builder.getInt1Ty(), 4);
8667   case SVETypeFlags::EltTyBool64:
8668     return llvm::ScalableVectorType::get(Builder.getInt1Ty(), 2);
8669   }
8670 }
8671 
8672 llvm::Value *
8673 CodeGenFunction::EmitSVEAllTruePred(const SVETypeFlags &TypeFlags) {
8674   Function *Ptrue =
8675       CGM.getIntrinsic(Intrinsic::aarch64_sve_ptrue, getSVEPredType(TypeFlags));
8676   return Builder.CreateCall(Ptrue, {Builder.getInt32(/*SV_ALL*/ 31)});
8677 }
8678 
8679 constexpr unsigned SVEBitsPerBlock = 128;
8680 
8681 static llvm::ScalableVectorType *getSVEVectorForElementType(llvm::Type *EltTy) {
8682   unsigned NumElts = SVEBitsPerBlock / EltTy->getScalarSizeInBits();
8683   return llvm::ScalableVectorType::get(EltTy, NumElts);
8684 }
8685 
8686 // Reinterpret the input predicate so that it can be used to correctly isolate
8687 // the elements of the specified datatype.
8688 Value *CodeGenFunction::EmitSVEPredicateCast(Value *Pred,
8689                                              llvm::ScalableVectorType *VTy) {
8690   auto *RTy = llvm::VectorType::get(IntegerType::get(getLLVMContext(), 1), VTy);
8691   if (Pred->getType() == RTy)
8692     return Pred;
8693 
8694   unsigned IntID;
8695   llvm::Type *IntrinsicTy;
8696   switch (VTy->getMinNumElements()) {
8697   default:
8698     llvm_unreachable("unsupported element count!");
8699   case 2:
8700   case 4:
8701   case 8:
8702     IntID = Intrinsic::aarch64_sve_convert_from_svbool;
8703     IntrinsicTy = RTy;
8704     break;
8705   case 16:
8706     IntID = Intrinsic::aarch64_sve_convert_to_svbool;
8707     IntrinsicTy = Pred->getType();
8708     break;
8709   }
8710 
8711   Function *F = CGM.getIntrinsic(IntID, IntrinsicTy);
8712   Value *C = Builder.CreateCall(F, Pred);
8713   assert(C->getType() == RTy && "Unexpected return type!");
8714   return C;
8715 }
8716 
8717 Value *CodeGenFunction::EmitSVEGatherLoad(const SVETypeFlags &TypeFlags,
8718                                           SmallVectorImpl<Value *> &Ops,
8719                                           unsigned IntID) {
8720   auto *ResultTy = getSVEType(TypeFlags);
8721   auto *OverloadedTy =
8722       llvm::ScalableVectorType::get(SVEBuiltinMemEltTy(TypeFlags), ResultTy);
8723 
8724   // At the ACLE level there's only one predicate type, svbool_t, which is
8725   // mapped to <n x 16 x i1>. However, this might be incompatible with the
8726   // actual type being loaded. For example, when loading doubles (i64) the
8727   // predicated should be <n x 2 x i1> instead. At the IR level the type of
8728   // the predicate and the data being loaded must match. Cast accordingly.
8729   Ops[0] = EmitSVEPredicateCast(Ops[0], OverloadedTy);
8730 
8731   Function *F = nullptr;
8732   if (Ops[1]->getType()->isVectorTy())
8733     // This is the "vector base, scalar offset" case. In order to uniquely
8734     // map this built-in to an LLVM IR intrinsic, we need both the return type
8735     // and the type of the vector base.
8736     F = CGM.getIntrinsic(IntID, {OverloadedTy, Ops[1]->getType()});
8737   else
8738     // This is the "scalar base, vector offset case". The type of the offset
8739     // is encoded in the name of the intrinsic. We only need to specify the
8740     // return type in order to uniquely map this built-in to an LLVM IR
8741     // intrinsic.
8742     F = CGM.getIntrinsic(IntID, OverloadedTy);
8743 
8744   // Pass 0 when the offset is missing. This can only be applied when using
8745   // the "vector base" addressing mode for which ACLE allows no offset. The
8746   // corresponding LLVM IR always requires an offset.
8747   if (Ops.size() == 2) {
8748     assert(Ops[1]->getType()->isVectorTy() && "Scalar base requires an offset");
8749     Ops.push_back(ConstantInt::get(Int64Ty, 0));
8750   }
8751 
8752   // For "vector base, scalar index" scale the index so that it becomes a
8753   // scalar offset.
8754   if (!TypeFlags.isByteIndexed() && Ops[1]->getType()->isVectorTy()) {
8755     unsigned BytesPerElt =
8756         OverloadedTy->getElementType()->getScalarSizeInBits() / 8;
8757     Value *Scale = ConstantInt::get(Int64Ty, BytesPerElt);
8758     Ops[2] = Builder.CreateMul(Ops[2], Scale);
8759   }
8760 
8761   Value *Call = Builder.CreateCall(F, Ops);
8762 
8763   // The following sext/zext is only needed when ResultTy != OverloadedTy. In
8764   // other cases it's folded into a nop.
8765   return TypeFlags.isZExtReturn() ? Builder.CreateZExt(Call, ResultTy)
8766                                   : Builder.CreateSExt(Call, ResultTy);
8767 }
8768 
8769 Value *CodeGenFunction::EmitSVEScatterStore(const SVETypeFlags &TypeFlags,
8770                                             SmallVectorImpl<Value *> &Ops,
8771                                             unsigned IntID) {
8772   auto *SrcDataTy = getSVEType(TypeFlags);
8773   auto *OverloadedTy =
8774       llvm::ScalableVectorType::get(SVEBuiltinMemEltTy(TypeFlags), SrcDataTy);
8775 
8776   // In ACLE the source data is passed in the last argument, whereas in LLVM IR
8777   // it's the first argument. Move it accordingly.
8778   Ops.insert(Ops.begin(), Ops.pop_back_val());
8779 
8780   Function *F = nullptr;
8781   if (Ops[2]->getType()->isVectorTy())
8782     // This is the "vector base, scalar offset" case. In order to uniquely
8783     // map this built-in to an LLVM IR intrinsic, we need both the return type
8784     // and the type of the vector base.
8785     F = CGM.getIntrinsic(IntID, {OverloadedTy, Ops[2]->getType()});
8786   else
8787     // This is the "scalar base, vector offset case". The type of the offset
8788     // is encoded in the name of the intrinsic. We only need to specify the
8789     // return type in order to uniquely map this built-in to an LLVM IR
8790     // intrinsic.
8791     F = CGM.getIntrinsic(IntID, OverloadedTy);
8792 
8793   // Pass 0 when the offset is missing. This can only be applied when using
8794   // the "vector base" addressing mode for which ACLE allows no offset. The
8795   // corresponding LLVM IR always requires an offset.
8796   if (Ops.size() == 3) {
8797     assert(Ops[1]->getType()->isVectorTy() && "Scalar base requires an offset");
8798     Ops.push_back(ConstantInt::get(Int64Ty, 0));
8799   }
8800 
8801   // Truncation is needed when SrcDataTy != OverloadedTy. In other cases it's
8802   // folded into a nop.
8803   Ops[0] = Builder.CreateTrunc(Ops[0], OverloadedTy);
8804 
8805   // At the ACLE level there's only one predicate type, svbool_t, which is
8806   // mapped to <n x 16 x i1>. However, this might be incompatible with the
8807   // actual type being stored. For example, when storing doubles (i64) the
8808   // predicated should be <n x 2 x i1> instead. At the IR level the type of
8809   // the predicate and the data being stored must match. Cast accordingly.
8810   Ops[1] = EmitSVEPredicateCast(Ops[1], OverloadedTy);
8811 
8812   // For "vector base, scalar index" scale the index so that it becomes a
8813   // scalar offset.
8814   if (!TypeFlags.isByteIndexed() && Ops[2]->getType()->isVectorTy()) {
8815     unsigned BytesPerElt =
8816         OverloadedTy->getElementType()->getScalarSizeInBits() / 8;
8817     Value *Scale = ConstantInt::get(Int64Ty, BytesPerElt);
8818     Ops[3] = Builder.CreateMul(Ops[3], Scale);
8819   }
8820 
8821   return Builder.CreateCall(F, Ops);
8822 }
8823 
8824 Value *CodeGenFunction::EmitSVEGatherPrefetch(const SVETypeFlags &TypeFlags,
8825                                               SmallVectorImpl<Value *> &Ops,
8826                                               unsigned IntID) {
8827   // The gather prefetches are overloaded on the vector input - this can either
8828   // be the vector of base addresses or vector of offsets.
8829   auto *OverloadedTy = dyn_cast<llvm::ScalableVectorType>(Ops[1]->getType());
8830   if (!OverloadedTy)
8831     OverloadedTy = cast<llvm::ScalableVectorType>(Ops[2]->getType());
8832 
8833   // Cast the predicate from svbool_t to the right number of elements.
8834   Ops[0] = EmitSVEPredicateCast(Ops[0], OverloadedTy);
8835 
8836   // vector + imm addressing modes
8837   if (Ops[1]->getType()->isVectorTy()) {
8838     if (Ops.size() == 3) {
8839       // Pass 0 for 'vector+imm' when the index is omitted.
8840       Ops.push_back(ConstantInt::get(Int64Ty, 0));
8841 
8842       // The sv_prfop is the last operand in the builtin and IR intrinsic.
8843       std::swap(Ops[2], Ops[3]);
8844     } else {
8845       // Index needs to be passed as scaled offset.
8846       llvm::Type *MemEltTy = SVEBuiltinMemEltTy(TypeFlags);
8847       unsigned BytesPerElt = MemEltTy->getPrimitiveSizeInBits() / 8;
8848       Value *Scale = ConstantInt::get(Int64Ty, BytesPerElt);
8849       Ops[2] = Builder.CreateMul(Ops[2], Scale);
8850     }
8851   }
8852 
8853   Function *F = CGM.getIntrinsic(IntID, OverloadedTy);
8854   return Builder.CreateCall(F, Ops);
8855 }
8856 
8857 Value *CodeGenFunction::EmitSVEStructLoad(const SVETypeFlags &TypeFlags,
8858                                           SmallVectorImpl<Value*> &Ops,
8859                                           unsigned IntID) {
8860   llvm::ScalableVectorType *VTy = getSVEType(TypeFlags);
8861   auto VecPtrTy = llvm::PointerType::getUnqual(VTy);
8862   auto EltPtrTy = llvm::PointerType::getUnqual(VTy->getElementType());
8863 
8864   unsigned N;
8865   switch (IntID) {
8866   case Intrinsic::aarch64_sve_ld2:
8867     N = 2;
8868     break;
8869   case Intrinsic::aarch64_sve_ld3:
8870     N = 3;
8871     break;
8872   case Intrinsic::aarch64_sve_ld4:
8873     N = 4;
8874     break;
8875   default:
8876     llvm_unreachable("unknown intrinsic!");
8877   }
8878   auto RetTy = llvm::VectorType::get(VTy->getElementType(),
8879                                      VTy->getElementCount() * N);
8880 
8881 	Value *Predicate = EmitSVEPredicateCast(Ops[0], VTy);
8882   Value *BasePtr= Builder.CreateBitCast(Ops[1], VecPtrTy);
8883   Value *Offset = Ops.size() > 2 ? Ops[2] : Builder.getInt32(0);
8884   BasePtr = Builder.CreateGEP(VTy, BasePtr, Offset);
8885   BasePtr = Builder.CreateBitCast(BasePtr, EltPtrTy);
8886 
8887   Function *F = CGM.getIntrinsic(IntID, {RetTy, Predicate->getType()});
8888   return Builder.CreateCall(F, { Predicate, BasePtr });
8889 }
8890 
8891 Value *CodeGenFunction::EmitSVEStructStore(const SVETypeFlags &TypeFlags,
8892                                            SmallVectorImpl<Value*> &Ops,
8893                                            unsigned IntID) {
8894   llvm::ScalableVectorType *VTy = getSVEType(TypeFlags);
8895   auto VecPtrTy = llvm::PointerType::getUnqual(VTy);
8896   auto EltPtrTy = llvm::PointerType::getUnqual(VTy->getElementType());
8897 
8898   unsigned N;
8899   switch (IntID) {
8900   case Intrinsic::aarch64_sve_st2:
8901     N = 2;
8902     break;
8903   case Intrinsic::aarch64_sve_st3:
8904     N = 3;
8905     break;
8906   case Intrinsic::aarch64_sve_st4:
8907     N = 4;
8908     break;
8909   default:
8910     llvm_unreachable("unknown intrinsic!");
8911   }
8912   auto TupleTy =
8913       llvm::VectorType::get(VTy->getElementType(), VTy->getElementCount() * N);
8914 
8915   Value *Predicate = EmitSVEPredicateCast(Ops[0], VTy);
8916   Value *BasePtr = Builder.CreateBitCast(Ops[1], VecPtrTy);
8917   Value *Offset = Ops.size() > 3 ? Ops[2] : Builder.getInt32(0);
8918   Value *Val = Ops.back();
8919   BasePtr = Builder.CreateGEP(VTy, BasePtr, Offset);
8920   BasePtr = Builder.CreateBitCast(BasePtr, EltPtrTy);
8921 
8922   // The llvm.aarch64.sve.st2/3/4 intrinsics take legal part vectors, so we
8923   // need to break up the tuple vector.
8924   SmallVector<llvm::Value*, 5> Operands;
8925   Function *FExtr =
8926       CGM.getIntrinsic(Intrinsic::aarch64_sve_tuple_get, {VTy, TupleTy});
8927   for (unsigned I = 0; I < N; ++I)
8928     Operands.push_back(Builder.CreateCall(FExtr, {Val, Builder.getInt32(I)}));
8929   Operands.append({Predicate, BasePtr});
8930 
8931   Function *F = CGM.getIntrinsic(IntID, { VTy });
8932   return Builder.CreateCall(F, Operands);
8933 }
8934 
8935 // SVE2's svpmullb and svpmullt builtins are similar to the svpmullb_pair and
8936 // svpmullt_pair intrinsics, with the exception that their results are bitcast
8937 // to a wider type.
8938 Value *CodeGenFunction::EmitSVEPMull(const SVETypeFlags &TypeFlags,
8939                                      SmallVectorImpl<Value *> &Ops,
8940                                      unsigned BuiltinID) {
8941   // Splat scalar operand to vector (intrinsics with _n infix)
8942   if (TypeFlags.hasSplatOperand()) {
8943     unsigned OpNo = TypeFlags.getSplatOperand();
8944     Ops[OpNo] = EmitSVEDupX(Ops[OpNo]);
8945   }
8946 
8947   // The pair-wise function has a narrower overloaded type.
8948   Function *F = CGM.getIntrinsic(BuiltinID, Ops[0]->getType());
8949   Value *Call = Builder.CreateCall(F, {Ops[0], Ops[1]});
8950 
8951   // Now bitcast to the wider result type.
8952   llvm::ScalableVectorType *Ty = getSVEType(TypeFlags);
8953   return EmitSVEReinterpret(Call, Ty);
8954 }
8955 
8956 Value *CodeGenFunction::EmitSVEMovl(const SVETypeFlags &TypeFlags,
8957                                     ArrayRef<Value *> Ops, unsigned BuiltinID) {
8958   llvm::Type *OverloadedTy = getSVEType(TypeFlags);
8959   Function *F = CGM.getIntrinsic(BuiltinID, OverloadedTy);
8960   return Builder.CreateCall(F, {Ops[0], Builder.getInt32(0)});
8961 }
8962 
8963 Value *CodeGenFunction::EmitSVEPrefetchLoad(const SVETypeFlags &TypeFlags,
8964                                             SmallVectorImpl<Value *> &Ops,
8965                                             unsigned BuiltinID) {
8966   auto *MemEltTy = SVEBuiltinMemEltTy(TypeFlags);
8967   auto *VectorTy = getSVEVectorForElementType(MemEltTy);
8968   auto *MemoryTy = llvm::ScalableVectorType::get(MemEltTy, VectorTy);
8969 
8970   Value *Predicate = EmitSVEPredicateCast(Ops[0], MemoryTy);
8971   Value *BasePtr = Ops[1];
8972 
8973   // Implement the index operand if not omitted.
8974   if (Ops.size() > 3) {
8975     BasePtr = Builder.CreateBitCast(BasePtr, MemoryTy->getPointerTo());
8976     BasePtr = Builder.CreateGEP(MemoryTy, BasePtr, Ops[2]);
8977   }
8978 
8979   // Prefetch intriniscs always expect an i8*
8980   BasePtr = Builder.CreateBitCast(BasePtr, llvm::PointerType::getUnqual(Int8Ty));
8981   Value *PrfOp = Ops.back();
8982 
8983   Function *F = CGM.getIntrinsic(BuiltinID, Predicate->getType());
8984   return Builder.CreateCall(F, {Predicate, BasePtr, PrfOp});
8985 }
8986 
8987 Value *CodeGenFunction::EmitSVEMaskedLoad(const CallExpr *E,
8988                                           llvm::Type *ReturnTy,
8989                                           SmallVectorImpl<Value *> &Ops,
8990                                           unsigned BuiltinID,
8991                                           bool IsZExtReturn) {
8992   QualType LangPTy = E->getArg(1)->getType();
8993   llvm::Type *MemEltTy = CGM.getTypes().ConvertType(
8994       LangPTy->castAs<PointerType>()->getPointeeType());
8995 
8996   // The vector type that is returned may be different from the
8997   // eventual type loaded from memory.
8998   auto VectorTy = cast<llvm::ScalableVectorType>(ReturnTy);
8999   auto MemoryTy = llvm::ScalableVectorType::get(MemEltTy, VectorTy);
9000 
9001   Value *Predicate = EmitSVEPredicateCast(Ops[0], MemoryTy);
9002   Value *BasePtr = Builder.CreateBitCast(Ops[1], MemoryTy->getPointerTo());
9003   Value *Offset = Ops.size() > 2 ? Ops[2] : Builder.getInt32(0);
9004   BasePtr = Builder.CreateGEP(MemoryTy, BasePtr, Offset);
9005 
9006   BasePtr = Builder.CreateBitCast(BasePtr, MemEltTy->getPointerTo());
9007   Function *F = CGM.getIntrinsic(BuiltinID, MemoryTy);
9008   Value *Load = Builder.CreateCall(F, {Predicate, BasePtr});
9009 
9010   return IsZExtReturn ? Builder.CreateZExt(Load, VectorTy)
9011                      : Builder.CreateSExt(Load, VectorTy);
9012 }
9013 
9014 Value *CodeGenFunction::EmitSVEMaskedStore(const CallExpr *E,
9015                                            SmallVectorImpl<Value *> &Ops,
9016                                            unsigned BuiltinID) {
9017   QualType LangPTy = E->getArg(1)->getType();
9018   llvm::Type *MemEltTy = CGM.getTypes().ConvertType(
9019       LangPTy->castAs<PointerType>()->getPointeeType());
9020 
9021   // The vector type that is stored may be different from the
9022   // eventual type stored to memory.
9023   auto VectorTy = cast<llvm::ScalableVectorType>(Ops.back()->getType());
9024   auto MemoryTy = llvm::ScalableVectorType::get(MemEltTy, VectorTy);
9025 
9026   Value *Predicate = EmitSVEPredicateCast(Ops[0], MemoryTy);
9027   Value *BasePtr = Builder.CreateBitCast(Ops[1], MemoryTy->getPointerTo());
9028   Value *Offset = Ops.size() == 4 ? Ops[2] : Builder.getInt32(0);
9029   BasePtr = Builder.CreateGEP(MemoryTy, BasePtr, Offset);
9030 
9031   // Last value is always the data
9032   llvm::Value *Val = Builder.CreateTrunc(Ops.back(), MemoryTy);
9033 
9034   BasePtr = Builder.CreateBitCast(BasePtr, MemEltTy->getPointerTo());
9035   Function *F = CGM.getIntrinsic(BuiltinID, MemoryTy);
9036   return Builder.CreateCall(F, {Val, Predicate, BasePtr});
9037 }
9038 
9039 // Limit the usage of scalable llvm IR generated by the ACLE by using the
9040 // sve dup.x intrinsic instead of IRBuilder::CreateVectorSplat.
9041 Value *CodeGenFunction::EmitSVEDupX(Value *Scalar, llvm::Type *Ty) {
9042   auto F = CGM.getIntrinsic(Intrinsic::aarch64_sve_dup_x, Ty);
9043   return Builder.CreateCall(F, Scalar);
9044 }
9045 
9046 Value *CodeGenFunction::EmitSVEDupX(Value* Scalar) {
9047   return EmitSVEDupX(Scalar, getSVEVectorForElementType(Scalar->getType()));
9048 }
9049 
9050 Value *CodeGenFunction::EmitSVEReinterpret(Value *Val, llvm::Type *Ty) {
9051   // FIXME: For big endian this needs an additional REV, or needs a separate
9052   // intrinsic that is code-generated as a no-op, because the LLVM bitcast
9053   // instruction is defined as 'bitwise' equivalent from memory point of
9054   // view (when storing/reloading), whereas the svreinterpret builtin
9055   // implements bitwise equivalent cast from register point of view.
9056   // LLVM CodeGen for a bitcast must add an explicit REV for big-endian.
9057   return Builder.CreateBitCast(Val, Ty);
9058 }
9059 
9060 static void InsertExplicitZeroOperand(CGBuilderTy &Builder, llvm::Type *Ty,
9061                                       SmallVectorImpl<Value *> &Ops) {
9062   auto *SplatZero = Constant::getNullValue(Ty);
9063   Ops.insert(Ops.begin(), SplatZero);
9064 }
9065 
9066 static void InsertExplicitUndefOperand(CGBuilderTy &Builder, llvm::Type *Ty,
9067                                        SmallVectorImpl<Value *> &Ops) {
9068   auto *SplatUndef = UndefValue::get(Ty);
9069   Ops.insert(Ops.begin(), SplatUndef);
9070 }
9071 
9072 SmallVector<llvm::Type *, 2>
9073 CodeGenFunction::getSVEOverloadTypes(const SVETypeFlags &TypeFlags,
9074                                      llvm::Type *ResultType,
9075                                      ArrayRef<Value *> Ops) {
9076   if (TypeFlags.isOverloadNone())
9077     return {};
9078 
9079   llvm::Type *DefaultType = getSVEType(TypeFlags);
9080 
9081   if (TypeFlags.isOverloadWhile())
9082     return {DefaultType, Ops[1]->getType()};
9083 
9084   if (TypeFlags.isOverloadWhileRW())
9085     return {getSVEPredType(TypeFlags), Ops[0]->getType()};
9086 
9087   if (TypeFlags.isOverloadCvt() || TypeFlags.isTupleSet())
9088     return {Ops[0]->getType(), Ops.back()->getType()};
9089 
9090   if (TypeFlags.isTupleCreate() || TypeFlags.isTupleGet())
9091     return {ResultType, Ops[0]->getType()};
9092 
9093   assert(TypeFlags.isOverloadDefault() && "Unexpected value for overloads");
9094   return {DefaultType};
9095 }
9096 
9097 Value *CodeGenFunction::EmitAArch64SVEBuiltinExpr(unsigned BuiltinID,
9098                                                   const CallExpr *E) {
9099   // Find out if any arguments are required to be integer constant expressions.
9100   unsigned ICEArguments = 0;
9101   ASTContext::GetBuiltinTypeError Error;
9102   getContext().GetBuiltinType(BuiltinID, Error, &ICEArguments);
9103   assert(Error == ASTContext::GE_None && "Should not codegen an error");
9104 
9105   llvm::Type *Ty = ConvertType(E->getType());
9106   if (BuiltinID >= SVE::BI__builtin_sve_reinterpret_s8_s8 &&
9107       BuiltinID <= SVE::BI__builtin_sve_reinterpret_f64_f64) {
9108     Value *Val = EmitScalarExpr(E->getArg(0));
9109     return EmitSVEReinterpret(Val, Ty);
9110   }
9111 
9112   llvm::SmallVector<Value *, 4> Ops;
9113   for (unsigned i = 0, e = E->getNumArgs(); i != e; i++) {
9114     if ((ICEArguments & (1 << i)) == 0)
9115       Ops.push_back(EmitScalarExpr(E->getArg(i)));
9116     else {
9117       // If this is required to be a constant, constant fold it so that we know
9118       // that the generated intrinsic gets a ConstantInt.
9119       Optional<llvm::APSInt> Result =
9120           E->getArg(i)->getIntegerConstantExpr(getContext());
9121       assert(Result && "Expected argument to be a constant");
9122 
9123       // Immediates for SVE llvm intrinsics are always 32bit.  We can safely
9124       // truncate because the immediate has been range checked and no valid
9125       // immediate requires more than a handful of bits.
9126       *Result = Result->extOrTrunc(32);
9127       Ops.push_back(llvm::ConstantInt::get(getLLVMContext(), *Result));
9128     }
9129   }
9130 
9131   auto *Builtin = findARMVectorIntrinsicInMap(AArch64SVEIntrinsicMap, BuiltinID,
9132                                               AArch64SVEIntrinsicsProvenSorted);
9133   SVETypeFlags TypeFlags(Builtin->TypeModifier);
9134   if (TypeFlags.isLoad())
9135     return EmitSVEMaskedLoad(E, Ty, Ops, Builtin->LLVMIntrinsic,
9136                              TypeFlags.isZExtReturn());
9137   else if (TypeFlags.isStore())
9138     return EmitSVEMaskedStore(E, Ops, Builtin->LLVMIntrinsic);
9139   else if (TypeFlags.isGatherLoad())
9140     return EmitSVEGatherLoad(TypeFlags, Ops, Builtin->LLVMIntrinsic);
9141   else if (TypeFlags.isScatterStore())
9142     return EmitSVEScatterStore(TypeFlags, Ops, Builtin->LLVMIntrinsic);
9143   else if (TypeFlags.isPrefetch())
9144     return EmitSVEPrefetchLoad(TypeFlags, Ops, Builtin->LLVMIntrinsic);
9145   else if (TypeFlags.isGatherPrefetch())
9146     return EmitSVEGatherPrefetch(TypeFlags, Ops, Builtin->LLVMIntrinsic);
9147 	else if (TypeFlags.isStructLoad())
9148 		return EmitSVEStructLoad(TypeFlags, Ops, Builtin->LLVMIntrinsic);
9149 	else if (TypeFlags.isStructStore())
9150 		return EmitSVEStructStore(TypeFlags, Ops, Builtin->LLVMIntrinsic);
9151   else if (TypeFlags.isUndef())
9152     return UndefValue::get(Ty);
9153   else if (Builtin->LLVMIntrinsic != 0) {
9154     if (TypeFlags.getMergeType() == SVETypeFlags::MergeZeroExp)
9155       InsertExplicitZeroOperand(Builder, Ty, Ops);
9156 
9157     if (TypeFlags.getMergeType() == SVETypeFlags::MergeAnyExp)
9158       InsertExplicitUndefOperand(Builder, Ty, Ops);
9159 
9160     // Some ACLE builtins leave out the argument to specify the predicate
9161     // pattern, which is expected to be expanded to an SV_ALL pattern.
9162     if (TypeFlags.isAppendSVALL())
9163       Ops.push_back(Builder.getInt32(/*SV_ALL*/ 31));
9164     if (TypeFlags.isInsertOp1SVALL())
9165       Ops.insert(&Ops[1], Builder.getInt32(/*SV_ALL*/ 31));
9166 
9167     // Predicates must match the main datatype.
9168     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
9169       if (auto PredTy = dyn_cast<llvm::VectorType>(Ops[i]->getType()))
9170         if (PredTy->getElementType()->isIntegerTy(1))
9171           Ops[i] = EmitSVEPredicateCast(Ops[i], getSVEType(TypeFlags));
9172 
9173     // Splat scalar operand to vector (intrinsics with _n infix)
9174     if (TypeFlags.hasSplatOperand()) {
9175       unsigned OpNo = TypeFlags.getSplatOperand();
9176       Ops[OpNo] = EmitSVEDupX(Ops[OpNo]);
9177     }
9178 
9179     if (TypeFlags.isReverseCompare())
9180       std::swap(Ops[1], Ops[2]);
9181 
9182     if (TypeFlags.isReverseUSDOT())
9183       std::swap(Ops[1], Ops[2]);
9184 
9185     // Predicated intrinsics with _z suffix need a select w/ zeroinitializer.
9186     if (TypeFlags.getMergeType() == SVETypeFlags::MergeZero) {
9187       llvm::Type *OpndTy = Ops[1]->getType();
9188       auto *SplatZero = Constant::getNullValue(OpndTy);
9189       Function *Sel = CGM.getIntrinsic(Intrinsic::aarch64_sve_sel, OpndTy);
9190       Ops[1] = Builder.CreateCall(Sel, {Ops[0], Ops[1], SplatZero});
9191     }
9192 
9193     Function *F = CGM.getIntrinsic(Builtin->LLVMIntrinsic,
9194                                    getSVEOverloadTypes(TypeFlags, Ty, Ops));
9195     Value *Call = Builder.CreateCall(F, Ops);
9196 
9197     // Predicate results must be converted to svbool_t.
9198     if (auto PredTy = dyn_cast<llvm::VectorType>(Call->getType()))
9199       if (PredTy->getScalarType()->isIntegerTy(1))
9200         Call = EmitSVEPredicateCast(Call, cast<llvm::ScalableVectorType>(Ty));
9201 
9202     return Call;
9203   }
9204 
9205   switch (BuiltinID) {
9206   default:
9207     return nullptr;
9208 
9209   case SVE::BI__builtin_sve_svmov_b_z: {
9210     // svmov_b_z(pg, op) <=> svand_b_z(pg, op, op)
9211     SVETypeFlags TypeFlags(Builtin->TypeModifier);
9212     llvm::Type* OverloadedTy = getSVEType(TypeFlags);
9213     Function *F = CGM.getIntrinsic(Intrinsic::aarch64_sve_and_z, OverloadedTy);
9214     return Builder.CreateCall(F, {Ops[0], Ops[1], Ops[1]});
9215   }
9216 
9217   case SVE::BI__builtin_sve_svnot_b_z: {
9218     // svnot_b_z(pg, op) <=> sveor_b_z(pg, op, pg)
9219     SVETypeFlags TypeFlags(Builtin->TypeModifier);
9220     llvm::Type* OverloadedTy = getSVEType(TypeFlags);
9221     Function *F = CGM.getIntrinsic(Intrinsic::aarch64_sve_eor_z, OverloadedTy);
9222     return Builder.CreateCall(F, {Ops[0], Ops[1], Ops[0]});
9223   }
9224 
9225   case SVE::BI__builtin_sve_svmovlb_u16:
9226   case SVE::BI__builtin_sve_svmovlb_u32:
9227   case SVE::BI__builtin_sve_svmovlb_u64:
9228     return EmitSVEMovl(TypeFlags, Ops, Intrinsic::aarch64_sve_ushllb);
9229 
9230   case SVE::BI__builtin_sve_svmovlb_s16:
9231   case SVE::BI__builtin_sve_svmovlb_s32:
9232   case SVE::BI__builtin_sve_svmovlb_s64:
9233     return EmitSVEMovl(TypeFlags, Ops, Intrinsic::aarch64_sve_sshllb);
9234 
9235   case SVE::BI__builtin_sve_svmovlt_u16:
9236   case SVE::BI__builtin_sve_svmovlt_u32:
9237   case SVE::BI__builtin_sve_svmovlt_u64:
9238     return EmitSVEMovl(TypeFlags, Ops, Intrinsic::aarch64_sve_ushllt);
9239 
9240   case SVE::BI__builtin_sve_svmovlt_s16:
9241   case SVE::BI__builtin_sve_svmovlt_s32:
9242   case SVE::BI__builtin_sve_svmovlt_s64:
9243     return EmitSVEMovl(TypeFlags, Ops, Intrinsic::aarch64_sve_sshllt);
9244 
9245   case SVE::BI__builtin_sve_svpmullt_u16:
9246   case SVE::BI__builtin_sve_svpmullt_u64:
9247   case SVE::BI__builtin_sve_svpmullt_n_u16:
9248   case SVE::BI__builtin_sve_svpmullt_n_u64:
9249     return EmitSVEPMull(TypeFlags, Ops, Intrinsic::aarch64_sve_pmullt_pair);
9250 
9251   case SVE::BI__builtin_sve_svpmullb_u16:
9252   case SVE::BI__builtin_sve_svpmullb_u64:
9253   case SVE::BI__builtin_sve_svpmullb_n_u16:
9254   case SVE::BI__builtin_sve_svpmullb_n_u64:
9255     return EmitSVEPMull(TypeFlags, Ops, Intrinsic::aarch64_sve_pmullb_pair);
9256 
9257   case SVE::BI__builtin_sve_svdup_n_b8:
9258   case SVE::BI__builtin_sve_svdup_n_b16:
9259   case SVE::BI__builtin_sve_svdup_n_b32:
9260   case SVE::BI__builtin_sve_svdup_n_b64: {
9261     Value *CmpNE =
9262         Builder.CreateICmpNE(Ops[0], Constant::getNullValue(Ops[0]->getType()));
9263     llvm::ScalableVectorType *OverloadedTy = getSVEType(TypeFlags);
9264     Value *Dup = EmitSVEDupX(CmpNE, OverloadedTy);
9265     return EmitSVEPredicateCast(Dup, cast<llvm::ScalableVectorType>(Ty));
9266   }
9267 
9268   case SVE::BI__builtin_sve_svdupq_n_b8:
9269   case SVE::BI__builtin_sve_svdupq_n_b16:
9270   case SVE::BI__builtin_sve_svdupq_n_b32:
9271   case SVE::BI__builtin_sve_svdupq_n_b64:
9272   case SVE::BI__builtin_sve_svdupq_n_u8:
9273   case SVE::BI__builtin_sve_svdupq_n_s8:
9274   case SVE::BI__builtin_sve_svdupq_n_u64:
9275   case SVE::BI__builtin_sve_svdupq_n_f64:
9276   case SVE::BI__builtin_sve_svdupq_n_s64:
9277   case SVE::BI__builtin_sve_svdupq_n_u16:
9278   case SVE::BI__builtin_sve_svdupq_n_f16:
9279   case SVE::BI__builtin_sve_svdupq_n_bf16:
9280   case SVE::BI__builtin_sve_svdupq_n_s16:
9281   case SVE::BI__builtin_sve_svdupq_n_u32:
9282   case SVE::BI__builtin_sve_svdupq_n_f32:
9283   case SVE::BI__builtin_sve_svdupq_n_s32: {
9284     // These builtins are implemented by storing each element to an array and using
9285     // ld1rq to materialize a vector.
9286     unsigned NumOpnds = Ops.size();
9287 
9288     bool IsBoolTy =
9289         cast<llvm::VectorType>(Ty)->getElementType()->isIntegerTy(1);
9290 
9291     // For svdupq_n_b* the element type of is an integer of type 128/numelts,
9292     // so that the compare can use the width that is natural for the expected
9293     // number of predicate lanes.
9294     llvm::Type *EltTy = Ops[0]->getType();
9295     if (IsBoolTy)
9296       EltTy = IntegerType::get(getLLVMContext(), SVEBitsPerBlock / NumOpnds);
9297 
9298     SmallVector<llvm::Value *, 16> VecOps;
9299     for (unsigned I = 0; I < NumOpnds; ++I)
9300         VecOps.push_back(Builder.CreateZExt(Ops[I], EltTy));
9301     Value *Vec = BuildVector(VecOps);
9302 
9303     SVETypeFlags TypeFlags(Builtin->TypeModifier);
9304     Value *Pred = EmitSVEAllTruePred(TypeFlags);
9305 
9306     llvm::Type *OverloadedTy = getSVEVectorForElementType(EltTy);
9307     Value *InsertSubVec = Builder.CreateInsertVector(
9308         OverloadedTy, UndefValue::get(OverloadedTy), Vec, Builder.getInt64(0));
9309 
9310     Function *F =
9311         CGM.getIntrinsic(Intrinsic::aarch64_sve_dupq_lane, OverloadedTy);
9312     Value *DupQLane =
9313         Builder.CreateCall(F, {InsertSubVec, Builder.getInt64(0)});
9314 
9315     if (!IsBoolTy)
9316       return DupQLane;
9317 
9318     // For svdupq_n_b* we need to add an additional 'cmpne' with '0'.
9319     F = CGM.getIntrinsic(NumOpnds == 2 ? Intrinsic::aarch64_sve_cmpne
9320                                        : Intrinsic::aarch64_sve_cmpne_wide,
9321                          OverloadedTy);
9322     Value *Call = Builder.CreateCall(
9323         F, {Pred, DupQLane, EmitSVEDupX(Builder.getInt64(0))});
9324     return EmitSVEPredicateCast(Call, cast<llvm::ScalableVectorType>(Ty));
9325   }
9326 
9327   case SVE::BI__builtin_sve_svpfalse_b:
9328     return ConstantInt::getFalse(Ty);
9329 
9330   case SVE::BI__builtin_sve_svlen_bf16:
9331   case SVE::BI__builtin_sve_svlen_f16:
9332   case SVE::BI__builtin_sve_svlen_f32:
9333   case SVE::BI__builtin_sve_svlen_f64:
9334   case SVE::BI__builtin_sve_svlen_s8:
9335   case SVE::BI__builtin_sve_svlen_s16:
9336   case SVE::BI__builtin_sve_svlen_s32:
9337   case SVE::BI__builtin_sve_svlen_s64:
9338   case SVE::BI__builtin_sve_svlen_u8:
9339   case SVE::BI__builtin_sve_svlen_u16:
9340   case SVE::BI__builtin_sve_svlen_u32:
9341   case SVE::BI__builtin_sve_svlen_u64: {
9342     SVETypeFlags TF(Builtin->TypeModifier);
9343     auto VTy = cast<llvm::VectorType>(getSVEType(TF));
9344     auto *NumEls =
9345         llvm::ConstantInt::get(Ty, VTy->getElementCount().getKnownMinValue());
9346 
9347     Function *F = CGM.getIntrinsic(Intrinsic::vscale, Ty);
9348     return Builder.CreateMul(NumEls, Builder.CreateCall(F));
9349   }
9350 
9351   case SVE::BI__builtin_sve_svtbl2_u8:
9352   case SVE::BI__builtin_sve_svtbl2_s8:
9353   case SVE::BI__builtin_sve_svtbl2_u16:
9354   case SVE::BI__builtin_sve_svtbl2_s16:
9355   case SVE::BI__builtin_sve_svtbl2_u32:
9356   case SVE::BI__builtin_sve_svtbl2_s32:
9357   case SVE::BI__builtin_sve_svtbl2_u64:
9358   case SVE::BI__builtin_sve_svtbl2_s64:
9359   case SVE::BI__builtin_sve_svtbl2_f16:
9360   case SVE::BI__builtin_sve_svtbl2_bf16:
9361   case SVE::BI__builtin_sve_svtbl2_f32:
9362   case SVE::BI__builtin_sve_svtbl2_f64: {
9363     SVETypeFlags TF(Builtin->TypeModifier);
9364     auto VTy = cast<llvm::VectorType>(getSVEType(TF));
9365     auto TupleTy = llvm::VectorType::getDoubleElementsVectorType(VTy);
9366     Function *FExtr =
9367         CGM.getIntrinsic(Intrinsic::aarch64_sve_tuple_get, {VTy, TupleTy});
9368     Value *V0 = Builder.CreateCall(FExtr, {Ops[0], Builder.getInt32(0)});
9369     Value *V1 = Builder.CreateCall(FExtr, {Ops[0], Builder.getInt32(1)});
9370     Function *F = CGM.getIntrinsic(Intrinsic::aarch64_sve_tbl2, VTy);
9371     return Builder.CreateCall(F, {V0, V1, Ops[1]});
9372   }
9373 
9374   case SVE::BI__builtin_sve_svset_neonq_s8:
9375   case SVE::BI__builtin_sve_svset_neonq_s16:
9376   case SVE::BI__builtin_sve_svset_neonq_s32:
9377   case SVE::BI__builtin_sve_svset_neonq_s64:
9378   case SVE::BI__builtin_sve_svset_neonq_u8:
9379   case SVE::BI__builtin_sve_svset_neonq_u16:
9380   case SVE::BI__builtin_sve_svset_neonq_u32:
9381   case SVE::BI__builtin_sve_svset_neonq_u64:
9382   case SVE::BI__builtin_sve_svset_neonq_f16:
9383   case SVE::BI__builtin_sve_svset_neonq_f32:
9384   case SVE::BI__builtin_sve_svset_neonq_f64:
9385   case SVE::BI__builtin_sve_svset_neonq_bf16: {
9386     return Builder.CreateInsertVector(Ty, Ops[0], Ops[1], Builder.getInt64(0));
9387   }
9388 
9389   case SVE::BI__builtin_sve_svget_neonq_s8:
9390   case SVE::BI__builtin_sve_svget_neonq_s16:
9391   case SVE::BI__builtin_sve_svget_neonq_s32:
9392   case SVE::BI__builtin_sve_svget_neonq_s64:
9393   case SVE::BI__builtin_sve_svget_neonq_u8:
9394   case SVE::BI__builtin_sve_svget_neonq_u16:
9395   case SVE::BI__builtin_sve_svget_neonq_u32:
9396   case SVE::BI__builtin_sve_svget_neonq_u64:
9397   case SVE::BI__builtin_sve_svget_neonq_f16:
9398   case SVE::BI__builtin_sve_svget_neonq_f32:
9399   case SVE::BI__builtin_sve_svget_neonq_f64:
9400   case SVE::BI__builtin_sve_svget_neonq_bf16: {
9401     return Builder.CreateExtractVector(Ty, Ops[0], Builder.getInt64(0));
9402   }
9403 
9404   case SVE::BI__builtin_sve_svdup_neonq_s8:
9405   case SVE::BI__builtin_sve_svdup_neonq_s16:
9406   case SVE::BI__builtin_sve_svdup_neonq_s32:
9407   case SVE::BI__builtin_sve_svdup_neonq_s64:
9408   case SVE::BI__builtin_sve_svdup_neonq_u8:
9409   case SVE::BI__builtin_sve_svdup_neonq_u16:
9410   case SVE::BI__builtin_sve_svdup_neonq_u32:
9411   case SVE::BI__builtin_sve_svdup_neonq_u64:
9412   case SVE::BI__builtin_sve_svdup_neonq_f16:
9413   case SVE::BI__builtin_sve_svdup_neonq_f32:
9414   case SVE::BI__builtin_sve_svdup_neonq_f64:
9415   case SVE::BI__builtin_sve_svdup_neonq_bf16: {
9416     Value *Insert = Builder.CreateInsertVector(Ty, UndefValue::get(Ty), Ops[0],
9417                                                Builder.getInt64(0));
9418     return Builder.CreateIntrinsic(Intrinsic::aarch64_sve_dupq_lane, {Ty},
9419                                    {Insert, Builder.getInt64(0)});
9420   }
9421   }
9422 
9423   /// Should not happen
9424   return nullptr;
9425 }
9426 
9427 Value *CodeGenFunction::EmitAArch64BuiltinExpr(unsigned BuiltinID,
9428                                                const CallExpr *E,
9429                                                llvm::Triple::ArchType Arch) {
9430   if (BuiltinID >= AArch64::FirstSVEBuiltin &&
9431       BuiltinID <= AArch64::LastSVEBuiltin)
9432     return EmitAArch64SVEBuiltinExpr(BuiltinID, E);
9433 
9434   unsigned HintID = static_cast<unsigned>(-1);
9435   switch (BuiltinID) {
9436   default: break;
9437   case AArch64::BI__builtin_arm_nop:
9438     HintID = 0;
9439     break;
9440   case AArch64::BI__builtin_arm_yield:
9441   case AArch64::BI__yield:
9442     HintID = 1;
9443     break;
9444   case AArch64::BI__builtin_arm_wfe:
9445   case AArch64::BI__wfe:
9446     HintID = 2;
9447     break;
9448   case AArch64::BI__builtin_arm_wfi:
9449   case AArch64::BI__wfi:
9450     HintID = 3;
9451     break;
9452   case AArch64::BI__builtin_arm_sev:
9453   case AArch64::BI__sev:
9454     HintID = 4;
9455     break;
9456   case AArch64::BI__builtin_arm_sevl:
9457   case AArch64::BI__sevl:
9458     HintID = 5;
9459     break;
9460   }
9461 
9462   if (HintID != static_cast<unsigned>(-1)) {
9463     Function *F = CGM.getIntrinsic(Intrinsic::aarch64_hint);
9464     return Builder.CreateCall(F, llvm::ConstantInt::get(Int32Ty, HintID));
9465   }
9466 
9467   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
9468     Value *Address         = EmitScalarExpr(E->getArg(0));
9469     Value *RW              = EmitScalarExpr(E->getArg(1));
9470     Value *CacheLevel      = EmitScalarExpr(E->getArg(2));
9471     Value *RetentionPolicy = EmitScalarExpr(E->getArg(3));
9472     Value *IsData          = EmitScalarExpr(E->getArg(4));
9473 
9474     Value *Locality = nullptr;
9475     if (cast<llvm::ConstantInt>(RetentionPolicy)->isZero()) {
9476       // Temporal fetch, needs to convert cache level to locality.
9477       Locality = llvm::ConstantInt::get(Int32Ty,
9478         -cast<llvm::ConstantInt>(CacheLevel)->getValue() + 3);
9479     } else {
9480       // Streaming fetch.
9481       Locality = llvm::ConstantInt::get(Int32Ty, 0);
9482     }
9483 
9484     // FIXME: We need AArch64 specific LLVM intrinsic if we want to specify
9485     // PLDL3STRM or PLDL2STRM.
9486     Function *F = CGM.getIntrinsic(Intrinsic::prefetch, Address->getType());
9487     return Builder.CreateCall(F, {Address, RW, Locality, IsData});
9488   }
9489 
9490   if (BuiltinID == AArch64::BI__builtin_arm_rbit) {
9491     assert((getContext().getTypeSize(E->getType()) == 32) &&
9492            "rbit of unusual size!");
9493     llvm::Value *Arg = EmitScalarExpr(E->getArg(0));
9494     return Builder.CreateCall(
9495         CGM.getIntrinsic(Intrinsic::bitreverse, Arg->getType()), Arg, "rbit");
9496   }
9497   if (BuiltinID == AArch64::BI__builtin_arm_rbit64) {
9498     assert((getContext().getTypeSize(E->getType()) == 64) &&
9499            "rbit of unusual size!");
9500     llvm::Value *Arg = EmitScalarExpr(E->getArg(0));
9501     return Builder.CreateCall(
9502         CGM.getIntrinsic(Intrinsic::bitreverse, Arg->getType()), Arg, "rbit");
9503   }
9504 
9505   if (BuiltinID == AArch64::BI__builtin_arm_cls) {
9506     llvm::Value *Arg = EmitScalarExpr(E->getArg(0));
9507     return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::aarch64_cls), Arg,
9508                               "cls");
9509   }
9510   if (BuiltinID == AArch64::BI__builtin_arm_cls64) {
9511     llvm::Value *Arg = EmitScalarExpr(E->getArg(0));
9512     return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::aarch64_cls64), Arg,
9513                               "cls");
9514   }
9515 
9516   if (BuiltinID == AArch64::BI__builtin_arm_frint32zf ||
9517       BuiltinID == AArch64::BI__builtin_arm_frint32z) {
9518     llvm::Value *Arg = EmitScalarExpr(E->getArg(0));
9519     llvm::Type *Ty = Arg->getType();
9520     return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::aarch64_frint32z, Ty),
9521                               Arg, "frint32z");
9522   }
9523 
9524   if (BuiltinID == AArch64::BI__builtin_arm_frint64zf ||
9525       BuiltinID == AArch64::BI__builtin_arm_frint64z) {
9526     llvm::Value *Arg = EmitScalarExpr(E->getArg(0));
9527     llvm::Type *Ty = Arg->getType();
9528     return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::aarch64_frint64z, Ty),
9529                               Arg, "frint64z");
9530   }
9531 
9532   if (BuiltinID == AArch64::BI__builtin_arm_frint32xf ||
9533       BuiltinID == AArch64::BI__builtin_arm_frint32x) {
9534     llvm::Value *Arg = EmitScalarExpr(E->getArg(0));
9535     llvm::Type *Ty = Arg->getType();
9536     return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::aarch64_frint32x, Ty),
9537                               Arg, "frint32x");
9538   }
9539 
9540   if (BuiltinID == AArch64::BI__builtin_arm_frint64xf ||
9541       BuiltinID == AArch64::BI__builtin_arm_frint64x) {
9542     llvm::Value *Arg = EmitScalarExpr(E->getArg(0));
9543     llvm::Type *Ty = Arg->getType();
9544     return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::aarch64_frint64x, Ty),
9545                               Arg, "frint64x");
9546   }
9547 
9548   if (BuiltinID == AArch64::BI__builtin_arm_jcvt) {
9549     assert((getContext().getTypeSize(E->getType()) == 32) &&
9550            "__jcvt of unusual size!");
9551     llvm::Value *Arg = EmitScalarExpr(E->getArg(0));
9552     return Builder.CreateCall(
9553         CGM.getIntrinsic(Intrinsic::aarch64_fjcvtzs), Arg);
9554   }
9555 
9556   if (BuiltinID == AArch64::BI__builtin_arm_ld64b ||
9557       BuiltinID == AArch64::BI__builtin_arm_st64b ||
9558       BuiltinID == AArch64::BI__builtin_arm_st64bv ||
9559       BuiltinID == AArch64::BI__builtin_arm_st64bv0) {
9560     llvm::Value *MemAddr = EmitScalarExpr(E->getArg(0));
9561     llvm::Value *ValPtr = EmitScalarExpr(E->getArg(1));
9562 
9563     if (BuiltinID == AArch64::BI__builtin_arm_ld64b) {
9564       // Load from the address via an LLVM intrinsic, receiving a
9565       // tuple of 8 i64 words, and store each one to ValPtr.
9566       Function *F = CGM.getIntrinsic(Intrinsic::aarch64_ld64b);
9567       llvm::Value *Val = Builder.CreateCall(F, MemAddr);
9568       llvm::Value *ToRet;
9569       for (size_t i = 0; i < 8; i++) {
9570         llvm::Value *ValOffsetPtr =
9571             Builder.CreateGEP(Int64Ty, ValPtr, Builder.getInt32(i));
9572         Address Addr(ValOffsetPtr, CharUnits::fromQuantity(8));
9573         ToRet = Builder.CreateStore(Builder.CreateExtractValue(Val, i), Addr);
9574       }
9575       return ToRet;
9576     } else {
9577       // Load 8 i64 words from ValPtr, and store them to the address
9578       // via an LLVM intrinsic.
9579       SmallVector<llvm::Value *, 9> Args;
9580       Args.push_back(MemAddr);
9581       for (size_t i = 0; i < 8; i++) {
9582         llvm::Value *ValOffsetPtr =
9583             Builder.CreateGEP(Int64Ty, ValPtr, Builder.getInt32(i));
9584         Address Addr(ValOffsetPtr, CharUnits::fromQuantity(8));
9585         Args.push_back(Builder.CreateLoad(Addr));
9586       }
9587 
9588       auto Intr = (BuiltinID == AArch64::BI__builtin_arm_st64b
9589                        ? Intrinsic::aarch64_st64b
9590                        : BuiltinID == AArch64::BI__builtin_arm_st64bv
9591                              ? Intrinsic::aarch64_st64bv
9592                              : Intrinsic::aarch64_st64bv0);
9593       Function *F = CGM.getIntrinsic(Intr);
9594       return Builder.CreateCall(F, Args);
9595     }
9596   }
9597 
9598   if (BuiltinID == AArch64::BI__builtin_arm_rndr ||
9599       BuiltinID == AArch64::BI__builtin_arm_rndrrs) {
9600 
9601     auto Intr = (BuiltinID == AArch64::BI__builtin_arm_rndr
9602                      ? Intrinsic::aarch64_rndr
9603                      : Intrinsic::aarch64_rndrrs);
9604     Function *F = CGM.getIntrinsic(Intr);
9605     llvm::Value *Val = Builder.CreateCall(F);
9606     Value *RandomValue = Builder.CreateExtractValue(Val, 0);
9607     Value *Status = Builder.CreateExtractValue(Val, 1);
9608 
9609     Address MemAddress = EmitPointerWithAlignment(E->getArg(0));
9610     Builder.CreateStore(RandomValue, MemAddress);
9611     Status = Builder.CreateZExt(Status, Int32Ty);
9612     return Status;
9613   }
9614 
9615   if (BuiltinID == AArch64::BI__clear_cache) {
9616     assert(E->getNumArgs() == 2 && "__clear_cache takes 2 arguments");
9617     const FunctionDecl *FD = E->getDirectCallee();
9618     Value *Ops[2];
9619     for (unsigned i = 0; i < 2; i++)
9620       Ops[i] = EmitScalarExpr(E->getArg(i));
9621     llvm::Type *Ty = CGM.getTypes().ConvertType(FD->getType());
9622     llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
9623     StringRef Name = FD->getName();
9624     return EmitNounwindRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name), Ops);
9625   }
9626 
9627   if ((BuiltinID == AArch64::BI__builtin_arm_ldrex ||
9628       BuiltinID == AArch64::BI__builtin_arm_ldaex) &&
9629       getContext().getTypeSize(E->getType()) == 128) {
9630     Function *F = CGM.getIntrinsic(BuiltinID == AArch64::BI__builtin_arm_ldaex
9631                                        ? Intrinsic::aarch64_ldaxp
9632                                        : Intrinsic::aarch64_ldxp);
9633 
9634     Value *LdPtr = EmitScalarExpr(E->getArg(0));
9635     Value *Val = Builder.CreateCall(F, Builder.CreateBitCast(LdPtr, Int8PtrTy),
9636                                     "ldxp");
9637 
9638     Value *Val0 = Builder.CreateExtractValue(Val, 1);
9639     Value *Val1 = Builder.CreateExtractValue(Val, 0);
9640     llvm::Type *Int128Ty = llvm::IntegerType::get(getLLVMContext(), 128);
9641     Val0 = Builder.CreateZExt(Val0, Int128Ty);
9642     Val1 = Builder.CreateZExt(Val1, Int128Ty);
9643 
9644     Value *ShiftCst = llvm::ConstantInt::get(Int128Ty, 64);
9645     Val = Builder.CreateShl(Val0, ShiftCst, "shl", true /* nuw */);
9646     Val = Builder.CreateOr(Val, Val1);
9647     return Builder.CreateBitCast(Val, ConvertType(E->getType()));
9648   } else if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
9649              BuiltinID == AArch64::BI__builtin_arm_ldaex) {
9650     Value *LoadAddr = EmitScalarExpr(E->getArg(0));
9651 
9652     QualType Ty = E->getType();
9653     llvm::Type *RealResTy = ConvertType(Ty);
9654     llvm::Type *PtrTy = llvm::IntegerType::get(
9655         getLLVMContext(), getContext().getTypeSize(Ty))->getPointerTo();
9656     LoadAddr = Builder.CreateBitCast(LoadAddr, PtrTy);
9657 
9658     Function *F = CGM.getIntrinsic(BuiltinID == AArch64::BI__builtin_arm_ldaex
9659                                        ? Intrinsic::aarch64_ldaxr
9660                                        : Intrinsic::aarch64_ldxr,
9661                                    PtrTy);
9662     Value *Val = Builder.CreateCall(F, LoadAddr, "ldxr");
9663 
9664     if (RealResTy->isPointerTy())
9665       return Builder.CreateIntToPtr(Val, RealResTy);
9666 
9667     llvm::Type *IntResTy = llvm::IntegerType::get(
9668         getLLVMContext(), CGM.getDataLayout().getTypeSizeInBits(RealResTy));
9669     Val = Builder.CreateTruncOrBitCast(Val, IntResTy);
9670     return Builder.CreateBitCast(Val, RealResTy);
9671   }
9672 
9673   if ((BuiltinID == AArch64::BI__builtin_arm_strex ||
9674        BuiltinID == AArch64::BI__builtin_arm_stlex) &&
9675       getContext().getTypeSize(E->getArg(0)->getType()) == 128) {
9676     Function *F = CGM.getIntrinsic(BuiltinID == AArch64::BI__builtin_arm_stlex
9677                                        ? Intrinsic::aarch64_stlxp
9678                                        : Intrinsic::aarch64_stxp);
9679     llvm::Type *STy = llvm::StructType::get(Int64Ty, Int64Ty);
9680 
9681     Address Tmp = CreateMemTemp(E->getArg(0)->getType());
9682     EmitAnyExprToMem(E->getArg(0), Tmp, Qualifiers(), /*init*/ true);
9683 
9684     Tmp = Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(STy));
9685     llvm::Value *Val = Builder.CreateLoad(Tmp);
9686 
9687     Value *Arg0 = Builder.CreateExtractValue(Val, 0);
9688     Value *Arg1 = Builder.CreateExtractValue(Val, 1);
9689     Value *StPtr = Builder.CreateBitCast(EmitScalarExpr(E->getArg(1)),
9690                                          Int8PtrTy);
9691     return Builder.CreateCall(F, {Arg0, Arg1, StPtr}, "stxp");
9692   }
9693 
9694   if (BuiltinID == AArch64::BI__builtin_arm_strex ||
9695       BuiltinID == AArch64::BI__builtin_arm_stlex) {
9696     Value *StoreVal = EmitScalarExpr(E->getArg(0));
9697     Value *StoreAddr = EmitScalarExpr(E->getArg(1));
9698 
9699     QualType Ty = E->getArg(0)->getType();
9700     llvm::Type *StoreTy = llvm::IntegerType::get(getLLVMContext(),
9701                                                  getContext().getTypeSize(Ty));
9702     StoreAddr = Builder.CreateBitCast(StoreAddr, StoreTy->getPointerTo());
9703 
9704     if (StoreVal->getType()->isPointerTy())
9705       StoreVal = Builder.CreatePtrToInt(StoreVal, Int64Ty);
9706     else {
9707       llvm::Type *IntTy = llvm::IntegerType::get(
9708           getLLVMContext(),
9709           CGM.getDataLayout().getTypeSizeInBits(StoreVal->getType()));
9710       StoreVal = Builder.CreateBitCast(StoreVal, IntTy);
9711       StoreVal = Builder.CreateZExtOrBitCast(StoreVal, Int64Ty);
9712     }
9713 
9714     Function *F = CGM.getIntrinsic(BuiltinID == AArch64::BI__builtin_arm_stlex
9715                                        ? Intrinsic::aarch64_stlxr
9716                                        : Intrinsic::aarch64_stxr,
9717                                    StoreAddr->getType());
9718     return Builder.CreateCall(F, {StoreVal, StoreAddr}, "stxr");
9719   }
9720 
9721   if (BuiltinID == AArch64::BI__getReg) {
9722     Expr::EvalResult Result;
9723     if (!E->getArg(0)->EvaluateAsInt(Result, CGM.getContext()))
9724       llvm_unreachable("Sema will ensure that the parameter is constant");
9725 
9726     llvm::APSInt Value = Result.Val.getInt();
9727     LLVMContext &Context = CGM.getLLVMContext();
9728     std::string Reg = Value == 31 ? "sp" : "x" + toString(Value, 10);
9729 
9730     llvm::Metadata *Ops[] = {llvm::MDString::get(Context, Reg)};
9731     llvm::MDNode *RegName = llvm::MDNode::get(Context, Ops);
9732     llvm::Value *Metadata = llvm::MetadataAsValue::get(Context, RegName);
9733 
9734     llvm::Function *F =
9735         CGM.getIntrinsic(llvm::Intrinsic::read_register, {Int64Ty});
9736     return Builder.CreateCall(F, Metadata);
9737   }
9738 
9739   if (BuiltinID == AArch64::BI__builtin_arm_clrex) {
9740     Function *F = CGM.getIntrinsic(Intrinsic::aarch64_clrex);
9741     return Builder.CreateCall(F);
9742   }
9743 
9744   if (BuiltinID == AArch64::BI_ReadWriteBarrier)
9745     return Builder.CreateFence(llvm::AtomicOrdering::SequentiallyConsistent,
9746                                llvm::SyncScope::SingleThread);
9747 
9748   // CRC32
9749   Intrinsic::ID CRCIntrinsicID = Intrinsic::not_intrinsic;
9750   switch (BuiltinID) {
9751   case AArch64::BI__builtin_arm_crc32b:
9752     CRCIntrinsicID = Intrinsic::aarch64_crc32b; break;
9753   case AArch64::BI__builtin_arm_crc32cb:
9754     CRCIntrinsicID = Intrinsic::aarch64_crc32cb; break;
9755   case AArch64::BI__builtin_arm_crc32h:
9756     CRCIntrinsicID = Intrinsic::aarch64_crc32h; break;
9757   case AArch64::BI__builtin_arm_crc32ch:
9758     CRCIntrinsicID = Intrinsic::aarch64_crc32ch; break;
9759   case AArch64::BI__builtin_arm_crc32w:
9760     CRCIntrinsicID = Intrinsic::aarch64_crc32w; break;
9761   case AArch64::BI__builtin_arm_crc32cw:
9762     CRCIntrinsicID = Intrinsic::aarch64_crc32cw; break;
9763   case AArch64::BI__builtin_arm_crc32d:
9764     CRCIntrinsicID = Intrinsic::aarch64_crc32x; break;
9765   case AArch64::BI__builtin_arm_crc32cd:
9766     CRCIntrinsicID = Intrinsic::aarch64_crc32cx; break;
9767   }
9768 
9769   if (CRCIntrinsicID != Intrinsic::not_intrinsic) {
9770     Value *Arg0 = EmitScalarExpr(E->getArg(0));
9771     Value *Arg1 = EmitScalarExpr(E->getArg(1));
9772     Function *F = CGM.getIntrinsic(CRCIntrinsicID);
9773 
9774     llvm::Type *DataTy = F->getFunctionType()->getParamType(1);
9775     Arg1 = Builder.CreateZExtOrBitCast(Arg1, DataTy);
9776 
9777     return Builder.CreateCall(F, {Arg0, Arg1});
9778   }
9779 
9780   // Memory Operations (MOPS)
9781   if (BuiltinID == AArch64::BI__builtin_arm_mops_memset_tag) {
9782     Value *Dst = EmitScalarExpr(E->getArg(0));
9783     Value *Val = EmitScalarExpr(E->getArg(1));
9784     Value *Size = EmitScalarExpr(E->getArg(2));
9785     Dst = Builder.CreatePointerCast(Dst, Int8PtrTy);
9786     Val = Builder.CreateTrunc(Val, Int8Ty);
9787     Size = Builder.CreateIntCast(Size, Int64Ty, false);
9788     return Builder.CreateCall(
9789         CGM.getIntrinsic(Intrinsic::aarch64_mops_memset_tag), {Dst, Val, Size});
9790   }
9791 
9792   // Memory Tagging Extensions (MTE) Intrinsics
9793   Intrinsic::ID MTEIntrinsicID = Intrinsic::not_intrinsic;
9794   switch (BuiltinID) {
9795   case AArch64::BI__builtin_arm_irg:
9796     MTEIntrinsicID = Intrinsic::aarch64_irg; break;
9797   case  AArch64::BI__builtin_arm_addg:
9798     MTEIntrinsicID = Intrinsic::aarch64_addg; break;
9799   case  AArch64::BI__builtin_arm_gmi:
9800     MTEIntrinsicID = Intrinsic::aarch64_gmi; break;
9801   case  AArch64::BI__builtin_arm_ldg:
9802     MTEIntrinsicID = Intrinsic::aarch64_ldg; break;
9803   case AArch64::BI__builtin_arm_stg:
9804     MTEIntrinsicID = Intrinsic::aarch64_stg; break;
9805   case AArch64::BI__builtin_arm_subp:
9806     MTEIntrinsicID = Intrinsic::aarch64_subp; break;
9807   }
9808 
9809   if (MTEIntrinsicID != Intrinsic::not_intrinsic) {
9810     llvm::Type *T = ConvertType(E->getType());
9811 
9812     if (MTEIntrinsicID == Intrinsic::aarch64_irg) {
9813       Value *Pointer = EmitScalarExpr(E->getArg(0));
9814       Value *Mask = EmitScalarExpr(E->getArg(1));
9815 
9816       Pointer = Builder.CreatePointerCast(Pointer, Int8PtrTy);
9817       Mask = Builder.CreateZExt(Mask, Int64Ty);
9818       Value *RV = Builder.CreateCall(
9819                        CGM.getIntrinsic(MTEIntrinsicID), {Pointer, Mask});
9820        return Builder.CreatePointerCast(RV, T);
9821     }
9822     if (MTEIntrinsicID == Intrinsic::aarch64_addg) {
9823       Value *Pointer = EmitScalarExpr(E->getArg(0));
9824       Value *TagOffset = EmitScalarExpr(E->getArg(1));
9825 
9826       Pointer = Builder.CreatePointerCast(Pointer, Int8PtrTy);
9827       TagOffset = Builder.CreateZExt(TagOffset, Int64Ty);
9828       Value *RV = Builder.CreateCall(
9829                        CGM.getIntrinsic(MTEIntrinsicID), {Pointer, TagOffset});
9830       return Builder.CreatePointerCast(RV, T);
9831     }
9832     if (MTEIntrinsicID == Intrinsic::aarch64_gmi) {
9833       Value *Pointer = EmitScalarExpr(E->getArg(0));
9834       Value *ExcludedMask = EmitScalarExpr(E->getArg(1));
9835 
9836       ExcludedMask = Builder.CreateZExt(ExcludedMask, Int64Ty);
9837       Pointer = Builder.CreatePointerCast(Pointer, Int8PtrTy);
9838       return Builder.CreateCall(
9839                        CGM.getIntrinsic(MTEIntrinsicID), {Pointer, ExcludedMask});
9840     }
9841     // Although it is possible to supply a different return
9842     // address (first arg) to this intrinsic, for now we set
9843     // return address same as input address.
9844     if (MTEIntrinsicID == Intrinsic::aarch64_ldg) {
9845       Value *TagAddress = EmitScalarExpr(E->getArg(0));
9846       TagAddress = Builder.CreatePointerCast(TagAddress, Int8PtrTy);
9847       Value *RV = Builder.CreateCall(
9848                     CGM.getIntrinsic(MTEIntrinsicID), {TagAddress, TagAddress});
9849       return Builder.CreatePointerCast(RV, T);
9850     }
9851     // Although it is possible to supply a different tag (to set)
9852     // to this intrinsic (as first arg), for now we supply
9853     // the tag that is in input address arg (common use case).
9854     if (MTEIntrinsicID == Intrinsic::aarch64_stg) {
9855         Value *TagAddress = EmitScalarExpr(E->getArg(0));
9856         TagAddress = Builder.CreatePointerCast(TagAddress, Int8PtrTy);
9857         return Builder.CreateCall(
9858                  CGM.getIntrinsic(MTEIntrinsicID), {TagAddress, TagAddress});
9859     }
9860     if (MTEIntrinsicID == Intrinsic::aarch64_subp) {
9861       Value *PointerA = EmitScalarExpr(E->getArg(0));
9862       Value *PointerB = EmitScalarExpr(E->getArg(1));
9863       PointerA = Builder.CreatePointerCast(PointerA, Int8PtrTy);
9864       PointerB = Builder.CreatePointerCast(PointerB, Int8PtrTy);
9865       return Builder.CreateCall(
9866                        CGM.getIntrinsic(MTEIntrinsicID), {PointerA, PointerB});
9867     }
9868   }
9869 
9870   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
9871       BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
9872       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
9873       BuiltinID == AArch64::BI__builtin_arm_wsr ||
9874       BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
9875       BuiltinID == AArch64::BI__builtin_arm_wsrp) {
9876 
9877     SpecialRegisterAccessKind AccessKind = Write;
9878     if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
9879         BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
9880         BuiltinID == AArch64::BI__builtin_arm_rsrp)
9881       AccessKind = VolatileRead;
9882 
9883     bool IsPointerBuiltin = BuiltinID == AArch64::BI__builtin_arm_rsrp ||
9884                             BuiltinID == AArch64::BI__builtin_arm_wsrp;
9885 
9886     bool Is64Bit = BuiltinID != AArch64::BI__builtin_arm_rsr &&
9887                    BuiltinID != AArch64::BI__builtin_arm_wsr;
9888 
9889     llvm::Type *ValueType;
9890     llvm::Type *RegisterType = Int64Ty;
9891     if (IsPointerBuiltin) {
9892       ValueType = VoidPtrTy;
9893     } else if (Is64Bit) {
9894       ValueType = Int64Ty;
9895     } else {
9896       ValueType = Int32Ty;
9897     }
9898 
9899     return EmitSpecialRegisterBuiltin(*this, E, RegisterType, ValueType,
9900                                       AccessKind);
9901   }
9902 
9903   if (BuiltinID == AArch64::BI_ReadStatusReg ||
9904       BuiltinID == AArch64::BI_WriteStatusReg) {
9905     LLVMContext &Context = CGM.getLLVMContext();
9906 
9907     unsigned SysReg =
9908       E->getArg(0)->EvaluateKnownConstInt(getContext()).getZExtValue();
9909 
9910     std::string SysRegStr;
9911     llvm::raw_string_ostream(SysRegStr) <<
9912                        ((1 << 1) | ((SysReg >> 14) & 1))  << ":" <<
9913                        ((SysReg >> 11) & 7)               << ":" <<
9914                        ((SysReg >> 7)  & 15)              << ":" <<
9915                        ((SysReg >> 3)  & 15)              << ":" <<
9916                        ( SysReg        & 7);
9917 
9918     llvm::Metadata *Ops[] = { llvm::MDString::get(Context, SysRegStr) };
9919     llvm::MDNode *RegName = llvm::MDNode::get(Context, Ops);
9920     llvm::Value *Metadata = llvm::MetadataAsValue::get(Context, RegName);
9921 
9922     llvm::Type *RegisterType = Int64Ty;
9923     llvm::Type *Types[] = { RegisterType };
9924 
9925     if (BuiltinID == AArch64::BI_ReadStatusReg) {
9926       llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
9927 
9928       return Builder.CreateCall(F, Metadata);
9929     }
9930 
9931     llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
9932     llvm::Value *ArgValue = EmitScalarExpr(E->getArg(1));
9933 
9934     return Builder.CreateCall(F, { Metadata, ArgValue });
9935   }
9936 
9937   if (BuiltinID == AArch64::BI_AddressOfReturnAddress) {
9938     llvm::Function *F =
9939         CGM.getIntrinsic(Intrinsic::addressofreturnaddress, AllocaInt8PtrTy);
9940     return Builder.CreateCall(F);
9941   }
9942 
9943   if (BuiltinID == AArch64::BI__builtin_sponentry) {
9944     llvm::Function *F = CGM.getIntrinsic(Intrinsic::sponentry, AllocaInt8PtrTy);
9945     return Builder.CreateCall(F);
9946   }
9947 
9948   if (BuiltinID == AArch64::BI__mulh || BuiltinID == AArch64::BI__umulh) {
9949     llvm::Type *ResType = ConvertType(E->getType());
9950     llvm::Type *Int128Ty = llvm::IntegerType::get(getLLVMContext(), 128);
9951 
9952     bool IsSigned = BuiltinID == AArch64::BI__mulh;
9953     Value *LHS =
9954         Builder.CreateIntCast(EmitScalarExpr(E->getArg(0)), Int128Ty, IsSigned);
9955     Value *RHS =
9956         Builder.CreateIntCast(EmitScalarExpr(E->getArg(1)), Int128Ty, IsSigned);
9957 
9958     Value *MulResult, *HigherBits;
9959     if (IsSigned) {
9960       MulResult = Builder.CreateNSWMul(LHS, RHS);
9961       HigherBits = Builder.CreateAShr(MulResult, 64);
9962     } else {
9963       MulResult = Builder.CreateNUWMul(LHS, RHS);
9964       HigherBits = Builder.CreateLShr(MulResult, 64);
9965     }
9966     HigherBits = Builder.CreateIntCast(HigherBits, ResType, IsSigned);
9967 
9968     return HigherBits;
9969   }
9970 
9971   // Handle MSVC intrinsics before argument evaluation to prevent double
9972   // evaluation.
9973   if (Optional<MSVCIntrin> MsvcIntId = translateAarch64ToMsvcIntrin(BuiltinID))
9974     return EmitMSVCBuiltinExpr(*MsvcIntId, E);
9975 
9976   // Find out if any arguments are required to be integer constant
9977   // expressions.
9978   unsigned ICEArguments = 0;
9979   ASTContext::GetBuiltinTypeError Error;
9980   getContext().GetBuiltinType(BuiltinID, Error, &ICEArguments);
9981   assert(Error == ASTContext::GE_None && "Should not codegen an error");
9982 
9983   llvm::SmallVector<Value*, 4> Ops;
9984   Address PtrOp0 = Address::invalid();
9985   for (unsigned i = 0, e = E->getNumArgs() - 1; i != e; i++) {
9986     if (i == 0) {
9987       switch (BuiltinID) {
9988       case NEON::BI__builtin_neon_vld1_v:
9989       case NEON::BI__builtin_neon_vld1q_v:
9990       case NEON::BI__builtin_neon_vld1_dup_v:
9991       case NEON::BI__builtin_neon_vld1q_dup_v:
9992       case NEON::BI__builtin_neon_vld1_lane_v:
9993       case NEON::BI__builtin_neon_vld1q_lane_v:
9994       case NEON::BI__builtin_neon_vst1_v:
9995       case NEON::BI__builtin_neon_vst1q_v:
9996       case NEON::BI__builtin_neon_vst1_lane_v:
9997       case NEON::BI__builtin_neon_vst1q_lane_v:
9998         // Get the alignment for the argument in addition to the value;
9999         // we'll use it later.
10000         PtrOp0 = EmitPointerWithAlignment(E->getArg(0));
10001         Ops.push_back(PtrOp0.getPointer());
10002         continue;
10003       }
10004     }
10005     if ((ICEArguments & (1 << i)) == 0) {
10006       Ops.push_back(EmitScalarExpr(E->getArg(i)));
10007     } else {
10008       // If this is required to be a constant, constant fold it so that we know
10009       // that the generated intrinsic gets a ConstantInt.
10010       Ops.push_back(llvm::ConstantInt::get(
10011           getLLVMContext(),
10012           *E->getArg(i)->getIntegerConstantExpr(getContext())));
10013     }
10014   }
10015 
10016   auto SISDMap = makeArrayRef(AArch64SISDIntrinsicMap);
10017   const ARMVectorIntrinsicInfo *Builtin = findARMVectorIntrinsicInMap(
10018       SISDMap, BuiltinID, AArch64SISDIntrinsicsProvenSorted);
10019 
10020   if (Builtin) {
10021     Ops.push_back(EmitScalarExpr(E->getArg(E->getNumArgs() - 1)));
10022     Value *Result = EmitCommonNeonSISDBuiltinExpr(*this, *Builtin, Ops, E);
10023     assert(Result && "SISD intrinsic should have been handled");
10024     return Result;
10025   }
10026 
10027   const Expr *Arg = E->getArg(E->getNumArgs()-1);
10028   NeonTypeFlags Type(0);
10029   if (Optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(getContext()))
10030     // Determine the type of this overloaded NEON intrinsic.
10031     Type = NeonTypeFlags(Result->getZExtValue());
10032 
10033   bool usgn = Type.isUnsigned();
10034   bool quad = Type.isQuad();
10035 
10036   // Handle non-overloaded intrinsics first.
10037   switch (BuiltinID) {
10038   default: break;
10039   case NEON::BI__builtin_neon_vabsh_f16:
10040     Ops.push_back(EmitScalarExpr(E->getArg(0)));
10041     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::fabs, HalfTy), Ops, "vabs");
10042   case NEON::BI__builtin_neon_vaddq_p128: {
10043     llvm::Type *Ty = GetNeonType(this, NeonTypeFlags::Poly128);
10044     Ops.push_back(EmitScalarExpr(E->getArg(1)));
10045     Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
10046     Ops[1] = Builder.CreateBitCast(Ops[1], Ty);
10047     Ops[0] =  Builder.CreateXor(Ops[0], Ops[1]);
10048     llvm::Type *Int128Ty = llvm::Type::getIntNTy(getLLVMContext(), 128);
10049     return Builder.CreateBitCast(Ops[0], Int128Ty);
10050   }
10051   case NEON::BI__builtin_neon_vldrq_p128: {
10052     llvm::Type *Int128Ty = llvm::Type::getIntNTy(getLLVMContext(), 128);
10053     llvm::Type *Int128PTy = llvm::PointerType::get(Int128Ty, 0);
10054     Value *Ptr = Builder.CreateBitCast(EmitScalarExpr(E->getArg(0)), Int128PTy);
10055     return Builder.CreateAlignedLoad(Int128Ty, Ptr,
10056                                      CharUnits::fromQuantity(16));
10057   }
10058   case NEON::BI__builtin_neon_vstrq_p128: {
10059     llvm::Type *Int128PTy = llvm::Type::getIntNPtrTy(getLLVMContext(), 128);
10060     Value *Ptr = Builder.CreateBitCast(Ops[0], Int128PTy);
10061     return Builder.CreateDefaultAlignedStore(EmitScalarExpr(E->getArg(1)), Ptr);
10062   }
10063   case NEON::BI__builtin_neon_vcvts_f32_u32:
10064   case NEON::BI__builtin_neon_vcvtd_f64_u64:
10065     usgn = true;
10066     LLVM_FALLTHROUGH;
10067   case NEON::BI__builtin_neon_vcvts_f32_s32:
10068   case NEON::BI__builtin_neon_vcvtd_f64_s64: {
10069     Ops.push_back(EmitScalarExpr(E->getArg(0)));
10070     bool Is64 = Ops[0]->getType()->getPrimitiveSizeInBits() == 64;
10071     llvm::Type *InTy = Is64 ? Int64Ty : Int32Ty;
10072     llvm::Type *FTy = Is64 ? DoubleTy : FloatTy;
10073     Ops[0] = Builder.CreateBitCast(Ops[0], InTy);
10074     if (usgn)
10075       return Builder.CreateUIToFP(Ops[0], FTy);
10076     return Builder.CreateSIToFP(Ops[0], FTy);
10077   }
10078   case NEON::BI__builtin_neon_vcvth_f16_u16:
10079   case NEON::BI__builtin_neon_vcvth_f16_u32:
10080   case NEON::BI__builtin_neon_vcvth_f16_u64:
10081     usgn = true;
10082     LLVM_FALLTHROUGH;
10083   case NEON::BI__builtin_neon_vcvth_f16_s16:
10084   case NEON::BI__builtin_neon_vcvth_f16_s32:
10085   case NEON::BI__builtin_neon_vcvth_f16_s64: {
10086     Ops.push_back(EmitScalarExpr(E->getArg(0)));
10087     llvm::Type *FTy = HalfTy;
10088     llvm::Type *InTy;
10089     if (Ops[0]->getType()->getPrimitiveSizeInBits() == 64)
10090       InTy = Int64Ty;
10091     else if (Ops[0]->getType()->getPrimitiveSizeInBits() == 32)
10092       InTy = Int32Ty;
10093     else
10094       InTy = Int16Ty;
10095     Ops[0] = Builder.CreateBitCast(Ops[0], InTy);
10096     if (usgn)
10097       return Builder.CreateUIToFP(Ops[0], FTy);
10098     return Builder.CreateSIToFP(Ops[0], FTy);
10099   }
10100   case NEON::BI__builtin_neon_vcvtah_u16_f16:
10101   case NEON::BI__builtin_neon_vcvtmh_u16_f16:
10102   case NEON::BI__builtin_neon_vcvtnh_u16_f16:
10103   case NEON::BI__builtin_neon_vcvtph_u16_f16:
10104   case NEON::BI__builtin_neon_vcvth_u16_f16:
10105   case NEON::BI__builtin_neon_vcvtah_s16_f16:
10106   case NEON::BI__builtin_neon_vcvtmh_s16_f16:
10107   case NEON::BI__builtin_neon_vcvtnh_s16_f16:
10108   case NEON::BI__builtin_neon_vcvtph_s16_f16:
10109   case NEON::BI__builtin_neon_vcvth_s16_f16: {
10110     unsigned Int;
10111     llvm::Type* InTy = Int32Ty;
10112     llvm::Type* FTy  = HalfTy;
10113     llvm::Type *Tys[2] = {InTy, FTy};
10114     Ops.push_back(EmitScalarExpr(E->getArg(0)));
10115     switch (BuiltinID) {
10116     default: llvm_unreachable("missing builtin ID in switch!");
10117     case NEON::BI__builtin_neon_vcvtah_u16_f16:
10118       Int = Intrinsic::aarch64_neon_fcvtau; break;
10119     case NEON::BI__builtin_neon_vcvtmh_u16_f16:
10120       Int = Intrinsic::aarch64_neon_fcvtmu; break;
10121     case NEON::BI__builtin_neon_vcvtnh_u16_f16:
10122       Int = Intrinsic::aarch64_neon_fcvtnu; break;
10123     case NEON::BI__builtin_neon_vcvtph_u16_f16:
10124       Int = Intrinsic::aarch64_neon_fcvtpu; break;
10125     case NEON::BI__builtin_neon_vcvth_u16_f16:
10126       Int = Intrinsic::aarch64_neon_fcvtzu; break;
10127     case NEON::BI__builtin_neon_vcvtah_s16_f16:
10128       Int = Intrinsic::aarch64_neon_fcvtas; break;
10129     case NEON::BI__builtin_neon_vcvtmh_s16_f16:
10130       Int = Intrinsic::aarch64_neon_fcvtms; break;
10131     case NEON::BI__builtin_neon_vcvtnh_s16_f16:
10132       Int = Intrinsic::aarch64_neon_fcvtns; break;
10133     case NEON::BI__builtin_neon_vcvtph_s16_f16:
10134       Int = Intrinsic::aarch64_neon_fcvtps; break;
10135     case NEON::BI__builtin_neon_vcvth_s16_f16:
10136       Int = Intrinsic::aarch64_neon_fcvtzs; break;
10137     }
10138     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "fcvt");
10139     return Builder.CreateTrunc(Ops[0], Int16Ty);
10140   }
10141   case NEON::BI__builtin_neon_vcaleh_f16:
10142   case NEON::BI__builtin_neon_vcalth_f16:
10143   case NEON::BI__builtin_neon_vcageh_f16:
10144   case NEON::BI__builtin_neon_vcagth_f16: {
10145     unsigned Int;
10146     llvm::Type* InTy = Int32Ty;
10147     llvm::Type* FTy  = HalfTy;
10148     llvm::Type *Tys[2] = {InTy, FTy};
10149     Ops.push_back(EmitScalarExpr(E->getArg(1)));
10150     switch (BuiltinID) {
10151     default: llvm_unreachable("missing builtin ID in switch!");
10152     case NEON::BI__builtin_neon_vcageh_f16:
10153       Int = Intrinsic::aarch64_neon_facge; break;
10154     case NEON::BI__builtin_neon_vcagth_f16:
10155       Int = Intrinsic::aarch64_neon_facgt; break;
10156     case NEON::BI__builtin_neon_vcaleh_f16:
10157       Int = Intrinsic::aarch64_neon_facge; std::swap(Ops[0], Ops[1]); break;
10158     case NEON::BI__builtin_neon_vcalth_f16:
10159       Int = Intrinsic::aarch64_neon_facgt; std::swap(Ops[0], Ops[1]); break;
10160     }
10161     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "facg");
10162     return Builder.CreateTrunc(Ops[0], Int16Ty);
10163   }
10164   case NEON::BI__builtin_neon_vcvth_n_s16_f16:
10165   case NEON::BI__builtin_neon_vcvth_n_u16_f16: {
10166     unsigned Int;
10167     llvm::Type* InTy = Int32Ty;
10168     llvm::Type* FTy  = HalfTy;
10169     llvm::Type *Tys[2] = {InTy, FTy};
10170     Ops.push_back(EmitScalarExpr(E->getArg(1)));
10171     switch (BuiltinID) {
10172     default: llvm_unreachable("missing builtin ID in switch!");
10173     case NEON::BI__builtin_neon_vcvth_n_s16_f16:
10174       Int = Intrinsic::aarch64_neon_vcvtfp2fxs; break;
10175     case NEON::BI__builtin_neon_vcvth_n_u16_f16:
10176       Int = Intrinsic::aarch64_neon_vcvtfp2fxu; break;
10177     }
10178     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "fcvth_n");
10179     return Builder.CreateTrunc(Ops[0], Int16Ty);
10180   }
10181   case NEON::BI__builtin_neon_vcvth_n_f16_s16:
10182   case NEON::BI__builtin_neon_vcvth_n_f16_u16: {
10183     unsigned Int;
10184     llvm::Type* FTy  = HalfTy;
10185     llvm::Type* InTy = Int32Ty;
10186     llvm::Type *Tys[2] = {FTy, InTy};
10187     Ops.push_back(EmitScalarExpr(E->getArg(1)));
10188     switch (BuiltinID) {
10189     default: llvm_unreachable("missing builtin ID in switch!");
10190     case NEON::BI__builtin_neon_vcvth_n_f16_s16:
10191       Int = Intrinsic::aarch64_neon_vcvtfxs2fp;
10192       Ops[0] = Builder.CreateSExt(Ops[0], InTy, "sext");
10193       break;
10194     case NEON::BI__builtin_neon_vcvth_n_f16_u16:
10195       Int = Intrinsic::aarch64_neon_vcvtfxu2fp;
10196       Ops[0] = Builder.CreateZExt(Ops[0], InTy);
10197       break;
10198     }
10199     return EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "fcvth_n");
10200   }
10201   case NEON::BI__builtin_neon_vpaddd_s64: {
10202     auto *Ty = llvm::FixedVectorType::get(Int64Ty, 2);
10203     Value *Vec = EmitScalarExpr(E->getArg(0));
10204     // The vector is v2f64, so make sure it's bitcast to that.
10205     Vec = Builder.CreateBitCast(Vec, Ty, "v2i64");
10206     llvm::Value *Idx0 = llvm::ConstantInt::get(SizeTy, 0);
10207     llvm::Value *Idx1 = llvm::ConstantInt::get(SizeTy, 1);
10208     Value *Op0 = Builder.CreateExtractElement(Vec, Idx0, "lane0");
10209     Value *Op1 = Builder.CreateExtractElement(Vec, Idx1, "lane1");
10210     // Pairwise addition of a v2f64 into a scalar f64.
10211     return Builder.CreateAdd(Op0, Op1, "vpaddd");
10212   }
10213   case NEON::BI__builtin_neon_vpaddd_f64: {
10214     auto *Ty = llvm::FixedVectorType::get(DoubleTy, 2);
10215     Value *Vec = EmitScalarExpr(E->getArg(0));
10216     // The vector is v2f64, so make sure it's bitcast to that.
10217     Vec = Builder.CreateBitCast(Vec, Ty, "v2f64");
10218     llvm::Value *Idx0 = llvm::ConstantInt::get(SizeTy, 0);
10219     llvm::Value *Idx1 = llvm::ConstantInt::get(SizeTy, 1);
10220     Value *Op0 = Builder.CreateExtractElement(Vec, Idx0, "lane0");
10221     Value *Op1 = Builder.CreateExtractElement(Vec, Idx1, "lane1");
10222     // Pairwise addition of a v2f64 into a scalar f64.
10223     return Builder.CreateFAdd(Op0, Op1, "vpaddd");
10224   }
10225   case NEON::BI__builtin_neon_vpadds_f32: {
10226     auto *Ty = llvm::FixedVectorType::get(FloatTy, 2);
10227     Value *Vec = EmitScalarExpr(E->getArg(0));
10228     // The vector is v2f32, so make sure it's bitcast to that.
10229     Vec = Builder.CreateBitCast(Vec, Ty, "v2f32");
10230     llvm::Value *Idx0 = llvm::ConstantInt::get(SizeTy, 0);
10231     llvm::Value *Idx1 = llvm::ConstantInt::get(SizeTy, 1);
10232     Value *Op0 = Builder.CreateExtractElement(Vec, Idx0, "lane0");
10233     Value *Op1 = Builder.CreateExtractElement(Vec, Idx1, "lane1");
10234     // Pairwise addition of a v2f32 into a scalar f32.
10235     return Builder.CreateFAdd(Op0, Op1, "vpaddd");
10236   }
10237   case NEON::BI__builtin_neon_vceqzd_s64:
10238   case NEON::BI__builtin_neon_vceqzd_f64:
10239   case NEON::BI__builtin_neon_vceqzs_f32:
10240   case NEON::BI__builtin_neon_vceqzh_f16:
10241     Ops.push_back(EmitScalarExpr(E->getArg(0)));
10242     return EmitAArch64CompareBuiltinExpr(
10243         Ops[0], ConvertType(E->getCallReturnType(getContext())),
10244         ICmpInst::FCMP_OEQ, ICmpInst::ICMP_EQ, "vceqz");
10245   case NEON::BI__builtin_neon_vcgezd_s64:
10246   case NEON::BI__builtin_neon_vcgezd_f64:
10247   case NEON::BI__builtin_neon_vcgezs_f32:
10248   case NEON::BI__builtin_neon_vcgezh_f16:
10249     Ops.push_back(EmitScalarExpr(E->getArg(0)));
10250     return EmitAArch64CompareBuiltinExpr(
10251         Ops[0], ConvertType(E->getCallReturnType(getContext())),
10252         ICmpInst::FCMP_OGE, ICmpInst::ICMP_SGE, "vcgez");
10253   case NEON::BI__builtin_neon_vclezd_s64:
10254   case NEON::BI__builtin_neon_vclezd_f64:
10255   case NEON::BI__builtin_neon_vclezs_f32:
10256   case NEON::BI__builtin_neon_vclezh_f16:
10257     Ops.push_back(EmitScalarExpr(E->getArg(0)));
10258     return EmitAArch64CompareBuiltinExpr(
10259         Ops[0], ConvertType(E->getCallReturnType(getContext())),
10260         ICmpInst::FCMP_OLE, ICmpInst::ICMP_SLE, "vclez");
10261   case NEON::BI__builtin_neon_vcgtzd_s64:
10262   case NEON::BI__builtin_neon_vcgtzd_f64:
10263   case NEON::BI__builtin_neon_vcgtzs_f32:
10264   case NEON::BI__builtin_neon_vcgtzh_f16:
10265     Ops.push_back(EmitScalarExpr(E->getArg(0)));
10266     return EmitAArch64CompareBuiltinExpr(
10267         Ops[0], ConvertType(E->getCallReturnType(getContext())),
10268         ICmpInst::FCMP_OGT, ICmpInst::ICMP_SGT, "vcgtz");
10269   case NEON::BI__builtin_neon_vcltzd_s64:
10270   case NEON::BI__builtin_neon_vcltzd_f64:
10271   case NEON::BI__builtin_neon_vcltzs_f32:
10272   case NEON::BI__builtin_neon_vcltzh_f16:
10273     Ops.push_back(EmitScalarExpr(E->getArg(0)));
10274     return EmitAArch64CompareBuiltinExpr(
10275         Ops[0], ConvertType(E->getCallReturnType(getContext())),
10276         ICmpInst::FCMP_OLT, ICmpInst::ICMP_SLT, "vcltz");
10277 
10278   case NEON::BI__builtin_neon_vceqzd_u64: {
10279     Ops.push_back(EmitScalarExpr(E->getArg(0)));
10280     Ops[0] = Builder.CreateBitCast(Ops[0], Int64Ty);
10281     Ops[0] =
10282         Builder.CreateICmpEQ(Ops[0], llvm::Constant::getNullValue(Int64Ty));
10283     return Builder.CreateSExt(Ops[0], Int64Ty, "vceqzd");
10284   }
10285   case NEON::BI__builtin_neon_vceqd_f64:
10286   case NEON::BI__builtin_neon_vcled_f64:
10287   case NEON::BI__builtin_neon_vcltd_f64:
10288   case NEON::BI__builtin_neon_vcged_f64:
10289   case NEON::BI__builtin_neon_vcgtd_f64: {
10290     llvm::CmpInst::Predicate P;
10291     switch (BuiltinID) {
10292     default: llvm_unreachable("missing builtin ID in switch!");
10293     case NEON::BI__builtin_neon_vceqd_f64: P = llvm::FCmpInst::FCMP_OEQ; break;
10294     case NEON::BI__builtin_neon_vcled_f64: P = llvm::FCmpInst::FCMP_OLE; break;
10295     case NEON::BI__builtin_neon_vcltd_f64: P = llvm::FCmpInst::FCMP_OLT; break;
10296     case NEON::BI__builtin_neon_vcged_f64: P = llvm::FCmpInst::FCMP_OGE; break;
10297     case NEON::BI__builtin_neon_vcgtd_f64: P = llvm::FCmpInst::FCMP_OGT; break;
10298     }
10299     Ops.push_back(EmitScalarExpr(E->getArg(1)));
10300     Ops[0] = Builder.CreateBitCast(Ops[0], DoubleTy);
10301     Ops[1] = Builder.CreateBitCast(Ops[1], DoubleTy);
10302     Ops[0] = Builder.CreateFCmp(P, Ops[0], Ops[1]);
10303     return Builder.CreateSExt(Ops[0], Int64Ty, "vcmpd");
10304   }
10305   case NEON::BI__builtin_neon_vceqs_f32:
10306   case NEON::BI__builtin_neon_vcles_f32:
10307   case NEON::BI__builtin_neon_vclts_f32:
10308   case NEON::BI__builtin_neon_vcges_f32:
10309   case NEON::BI__builtin_neon_vcgts_f32: {
10310     llvm::CmpInst::Predicate P;
10311     switch (BuiltinID) {
10312     default: llvm_unreachable("missing builtin ID in switch!");
10313     case NEON::BI__builtin_neon_vceqs_f32: P = llvm::FCmpInst::FCMP_OEQ; break;
10314     case NEON::BI__builtin_neon_vcles_f32: P = llvm::FCmpInst::FCMP_OLE; break;
10315     case NEON::BI__builtin_neon_vclts_f32: P = llvm::FCmpInst::FCMP_OLT; break;
10316     case NEON::BI__builtin_neon_vcges_f32: P = llvm::FCmpInst::FCMP_OGE; break;
10317     case NEON::BI__builtin_neon_vcgts_f32: P = llvm::FCmpInst::FCMP_OGT; break;
10318     }
10319     Ops.push_back(EmitScalarExpr(E->getArg(1)));
10320     Ops[0] = Builder.CreateBitCast(Ops[0], FloatTy);
10321     Ops[1] = Builder.CreateBitCast(Ops[1], FloatTy);
10322     Ops[0] = Builder.CreateFCmp(P, Ops[0], Ops[1]);
10323     return Builder.CreateSExt(Ops[0], Int32Ty, "vcmpd");
10324   }
10325   case NEON::BI__builtin_neon_vceqh_f16:
10326   case NEON::BI__builtin_neon_vcleh_f16:
10327   case NEON::BI__builtin_neon_vclth_f16:
10328   case NEON::BI__builtin_neon_vcgeh_f16:
10329   case NEON::BI__builtin_neon_vcgth_f16: {
10330     llvm::CmpInst::Predicate P;
10331     switch (BuiltinID) {
10332     default: llvm_unreachable("missing builtin ID in switch!");
10333     case NEON::BI__builtin_neon_vceqh_f16: P = llvm::FCmpInst::FCMP_OEQ; break;
10334     case NEON::BI__builtin_neon_vcleh_f16: P = llvm::FCmpInst::FCMP_OLE; break;
10335     case NEON::BI__builtin_neon_vclth_f16: P = llvm::FCmpInst::FCMP_OLT; break;
10336     case NEON::BI__builtin_neon_vcgeh_f16: P = llvm::FCmpInst::FCMP_OGE; break;
10337     case NEON::BI__builtin_neon_vcgth_f16: P = llvm::FCmpInst::FCMP_OGT; break;
10338     }
10339     Ops.push_back(EmitScalarExpr(E->getArg(1)));
10340     Ops[0] = Builder.CreateBitCast(Ops[0], HalfTy);
10341     Ops[1] = Builder.CreateBitCast(Ops[1], HalfTy);
10342     Ops[0] = Builder.CreateFCmp(P, Ops[0], Ops[1]);
10343     return Builder.CreateSExt(Ops[0], Int16Ty, "vcmpd");
10344   }
10345   case NEON::BI__builtin_neon_vceqd_s64:
10346   case NEON::BI__builtin_neon_vceqd_u64:
10347   case NEON::BI__builtin_neon_vcgtd_s64:
10348   case NEON::BI__builtin_neon_vcgtd_u64:
10349   case NEON::BI__builtin_neon_vcltd_s64:
10350   case NEON::BI__builtin_neon_vcltd_u64:
10351   case NEON::BI__builtin_neon_vcged_u64:
10352   case NEON::BI__builtin_neon_vcged_s64:
10353   case NEON::BI__builtin_neon_vcled_u64:
10354   case NEON::BI__builtin_neon_vcled_s64: {
10355     llvm::CmpInst::Predicate P;
10356     switch (BuiltinID) {
10357     default: llvm_unreachable("missing builtin ID in switch!");
10358     case NEON::BI__builtin_neon_vceqd_s64:
10359     case NEON::BI__builtin_neon_vceqd_u64:P = llvm::ICmpInst::ICMP_EQ;break;
10360     case NEON::BI__builtin_neon_vcgtd_s64:P = llvm::ICmpInst::ICMP_SGT;break;
10361     case NEON::BI__builtin_neon_vcgtd_u64:P = llvm::ICmpInst::ICMP_UGT;break;
10362     case NEON::BI__builtin_neon_vcltd_s64:P = llvm::ICmpInst::ICMP_SLT;break;
10363     case NEON::BI__builtin_neon_vcltd_u64:P = llvm::ICmpInst::ICMP_ULT;break;
10364     case NEON::BI__builtin_neon_vcged_u64:P = llvm::ICmpInst::ICMP_UGE;break;
10365     case NEON::BI__builtin_neon_vcged_s64:P = llvm::ICmpInst::ICMP_SGE;break;
10366     case NEON::BI__builtin_neon_vcled_u64:P = llvm::ICmpInst::ICMP_ULE;break;
10367     case NEON::BI__builtin_neon_vcled_s64:P = llvm::ICmpInst::ICMP_SLE;break;
10368     }
10369     Ops.push_back(EmitScalarExpr(E->getArg(1)));
10370     Ops[0] = Builder.CreateBitCast(Ops[0], Int64Ty);
10371     Ops[1] = Builder.CreateBitCast(Ops[1], Int64Ty);
10372     Ops[0] = Builder.CreateICmp(P, Ops[0], Ops[1]);
10373     return Builder.CreateSExt(Ops[0], Int64Ty, "vceqd");
10374   }
10375   case NEON::BI__builtin_neon_vtstd_s64:
10376   case NEON::BI__builtin_neon_vtstd_u64: {
10377     Ops.push_back(EmitScalarExpr(E->getArg(1)));
10378     Ops[0] = Builder.CreateBitCast(Ops[0], Int64Ty);
10379     Ops[1] = Builder.CreateBitCast(Ops[1], Int64Ty);
10380     Ops[0] = Builder.CreateAnd(Ops[0], Ops[1]);
10381     Ops[0] = Builder.CreateICmp(ICmpInst::ICMP_NE, Ops[0],
10382                                 llvm::Constant::getNullValue(Int64Ty));
10383     return Builder.CreateSExt(Ops[0], Int64Ty, "vtstd");
10384   }
10385   case NEON::BI__builtin_neon_vset_lane_i8:
10386   case NEON::BI__builtin_neon_vset_lane_i16:
10387   case NEON::BI__builtin_neon_vset_lane_i32:
10388   case NEON::BI__builtin_neon_vset_lane_i64:
10389   case NEON::BI__builtin_neon_vset_lane_bf16:
10390   case NEON::BI__builtin_neon_vset_lane_f32:
10391   case NEON::BI__builtin_neon_vsetq_lane_i8:
10392   case NEON::BI__builtin_neon_vsetq_lane_i16:
10393   case NEON::BI__builtin_neon_vsetq_lane_i32:
10394   case NEON::BI__builtin_neon_vsetq_lane_i64:
10395   case NEON::BI__builtin_neon_vsetq_lane_bf16:
10396   case NEON::BI__builtin_neon_vsetq_lane_f32:
10397     Ops.push_back(EmitScalarExpr(E->getArg(2)));
10398     return Builder.CreateInsertElement(Ops[1], Ops[0], Ops[2], "vset_lane");
10399   case NEON::BI__builtin_neon_vset_lane_f64:
10400     // The vector type needs a cast for the v1f64 variant.
10401     Ops[1] =
10402         Builder.CreateBitCast(Ops[1], llvm::FixedVectorType::get(DoubleTy, 1));
10403     Ops.push_back(EmitScalarExpr(E->getArg(2)));
10404     return Builder.CreateInsertElement(Ops[1], Ops[0], Ops[2], "vset_lane");
10405   case NEON::BI__builtin_neon_vsetq_lane_f64:
10406     // The vector type needs a cast for the v2f64 variant.
10407     Ops[1] =
10408         Builder.CreateBitCast(Ops[1], llvm::FixedVectorType::get(DoubleTy, 2));
10409     Ops.push_back(EmitScalarExpr(E->getArg(2)));
10410     return Builder.CreateInsertElement(Ops[1], Ops[0], Ops[2], "vset_lane");
10411 
10412   case NEON::BI__builtin_neon_vget_lane_i8:
10413   case NEON::BI__builtin_neon_vdupb_lane_i8:
10414     Ops[0] =
10415         Builder.CreateBitCast(Ops[0], llvm::FixedVectorType::get(Int8Ty, 8));
10416     return Builder.CreateExtractElement(Ops[0], EmitScalarExpr(E->getArg(1)),
10417                                         "vget_lane");
10418   case NEON::BI__builtin_neon_vgetq_lane_i8:
10419   case NEON::BI__builtin_neon_vdupb_laneq_i8:
10420     Ops[0] =
10421         Builder.CreateBitCast(Ops[0], llvm::FixedVectorType::get(Int8Ty, 16));
10422     return Builder.CreateExtractElement(Ops[0], EmitScalarExpr(E->getArg(1)),
10423                                         "vgetq_lane");
10424   case NEON::BI__builtin_neon_vget_lane_i16:
10425   case NEON::BI__builtin_neon_vduph_lane_i16:
10426     Ops[0] =
10427         Builder.CreateBitCast(Ops[0], llvm::FixedVectorType::get(Int16Ty, 4));
10428     return Builder.CreateExtractElement(Ops[0], EmitScalarExpr(E->getArg(1)),
10429                                         "vget_lane");
10430   case NEON::BI__builtin_neon_vgetq_lane_i16:
10431   case NEON::BI__builtin_neon_vduph_laneq_i16:
10432     Ops[0] =
10433         Builder.CreateBitCast(Ops[0], llvm::FixedVectorType::get(Int16Ty, 8));
10434     return Builder.CreateExtractElement(Ops[0], EmitScalarExpr(E->getArg(1)),
10435                                         "vgetq_lane");
10436   case NEON::BI__builtin_neon_vget_lane_i32:
10437   case NEON::BI__builtin_neon_vdups_lane_i32:
10438     Ops[0] =
10439         Builder.CreateBitCast(Ops[0], llvm::FixedVectorType::get(Int32Ty, 2));
10440     return Builder.CreateExtractElement(Ops[0], EmitScalarExpr(E->getArg(1)),
10441                                         "vget_lane");
10442   case NEON::BI__builtin_neon_vdups_lane_f32:
10443     Ops[0] =
10444         Builder.CreateBitCast(Ops[0], llvm::FixedVectorType::get(FloatTy, 2));
10445     return Builder.CreateExtractElement(Ops[0], EmitScalarExpr(E->getArg(1)),
10446                                         "vdups_lane");
10447   case NEON::BI__builtin_neon_vgetq_lane_i32:
10448   case NEON::BI__builtin_neon_vdups_laneq_i32:
10449     Ops[0] =
10450         Builder.CreateBitCast(Ops[0], llvm::FixedVectorType::get(Int32Ty, 4));
10451     return Builder.CreateExtractElement(Ops[0], EmitScalarExpr(E->getArg(1)),
10452                                         "vgetq_lane");
10453   case NEON::BI__builtin_neon_vget_lane_i64:
10454   case NEON::BI__builtin_neon_vdupd_lane_i64:
10455     Ops[0] =
10456         Builder.CreateBitCast(Ops[0], llvm::FixedVectorType::get(Int64Ty, 1));
10457     return Builder.CreateExtractElement(Ops[0], EmitScalarExpr(E->getArg(1)),
10458                                         "vget_lane");
10459   case NEON::BI__builtin_neon_vdupd_lane_f64:
10460     Ops[0] =
10461         Builder.CreateBitCast(Ops[0], llvm::FixedVectorType::get(DoubleTy, 1));
10462     return Builder.CreateExtractElement(Ops[0], EmitScalarExpr(E->getArg(1)),
10463                                         "vdupd_lane");
10464   case NEON::BI__builtin_neon_vgetq_lane_i64:
10465   case NEON::BI__builtin_neon_vdupd_laneq_i64:
10466     Ops[0] =
10467         Builder.CreateBitCast(Ops[0], llvm::FixedVectorType::get(Int64Ty, 2));
10468     return Builder.CreateExtractElement(Ops[0], EmitScalarExpr(E->getArg(1)),
10469                                         "vgetq_lane");
10470   case NEON::BI__builtin_neon_vget_lane_f32:
10471     Ops[0] =
10472         Builder.CreateBitCast(Ops[0], llvm::FixedVectorType::get(FloatTy, 2));
10473     return Builder.CreateExtractElement(Ops[0], EmitScalarExpr(E->getArg(1)),
10474                                         "vget_lane");
10475   case NEON::BI__builtin_neon_vget_lane_f64:
10476     Ops[0] =
10477         Builder.CreateBitCast(Ops[0], llvm::FixedVectorType::get(DoubleTy, 1));
10478     return Builder.CreateExtractElement(Ops[0], EmitScalarExpr(E->getArg(1)),
10479                                         "vget_lane");
10480   case NEON::BI__builtin_neon_vgetq_lane_f32:
10481   case NEON::BI__builtin_neon_vdups_laneq_f32:
10482     Ops[0] =
10483         Builder.CreateBitCast(Ops[0], llvm::FixedVectorType::get(FloatTy, 4));
10484     return Builder.CreateExtractElement(Ops[0], EmitScalarExpr(E->getArg(1)),
10485                                         "vgetq_lane");
10486   case NEON::BI__builtin_neon_vgetq_lane_f64:
10487   case NEON::BI__builtin_neon_vdupd_laneq_f64:
10488     Ops[0] =
10489         Builder.CreateBitCast(Ops[0], llvm::FixedVectorType::get(DoubleTy, 2));
10490     return Builder.CreateExtractElement(Ops[0], EmitScalarExpr(E->getArg(1)),
10491                                         "vgetq_lane");
10492   case NEON::BI__builtin_neon_vaddh_f16:
10493     Ops.push_back(EmitScalarExpr(E->getArg(1)));
10494     return Builder.CreateFAdd(Ops[0], Ops[1], "vaddh");
10495   case NEON::BI__builtin_neon_vsubh_f16:
10496     Ops.push_back(EmitScalarExpr(E->getArg(1)));
10497     return Builder.CreateFSub(Ops[0], Ops[1], "vsubh");
10498   case NEON::BI__builtin_neon_vmulh_f16:
10499     Ops.push_back(EmitScalarExpr(E->getArg(1)));
10500     return Builder.CreateFMul(Ops[0], Ops[1], "vmulh");
10501   case NEON::BI__builtin_neon_vdivh_f16:
10502     Ops.push_back(EmitScalarExpr(E->getArg(1)));
10503     return Builder.CreateFDiv(Ops[0], Ops[1], "vdivh");
10504   case NEON::BI__builtin_neon_vfmah_f16:
10505     // NEON intrinsic puts accumulator first, unlike the LLVM fma.
10506     return emitCallMaybeConstrainedFPBuiltin(
10507         *this, Intrinsic::fma, Intrinsic::experimental_constrained_fma, HalfTy,
10508         {EmitScalarExpr(E->getArg(1)), EmitScalarExpr(E->getArg(2)), Ops[0]});
10509   case NEON::BI__builtin_neon_vfmsh_f16: {
10510     // FIXME: This should be an fneg instruction:
10511     Value *Zero = llvm::ConstantFP::getZeroValueForNegation(HalfTy);
10512     Value* Sub = Builder.CreateFSub(Zero, EmitScalarExpr(E->getArg(1)), "vsubh");
10513 
10514     // NEON intrinsic puts accumulator first, unlike the LLVM fma.
10515     return emitCallMaybeConstrainedFPBuiltin(
10516         *this, Intrinsic::fma, Intrinsic::experimental_constrained_fma, HalfTy,
10517         {Sub, EmitScalarExpr(E->getArg(2)), Ops[0]});
10518   }
10519   case NEON::BI__builtin_neon_vaddd_s64:
10520   case NEON::BI__builtin_neon_vaddd_u64:
10521     return Builder.CreateAdd(Ops[0], EmitScalarExpr(E->getArg(1)), "vaddd");
10522   case NEON::BI__builtin_neon_vsubd_s64:
10523   case NEON::BI__builtin_neon_vsubd_u64:
10524     return Builder.CreateSub(Ops[0], EmitScalarExpr(E->getArg(1)), "vsubd");
10525   case NEON::BI__builtin_neon_vqdmlalh_s16:
10526   case NEON::BI__builtin_neon_vqdmlslh_s16: {
10527     SmallVector<Value *, 2> ProductOps;
10528     ProductOps.push_back(vectorWrapScalar16(Ops[1]));
10529     ProductOps.push_back(vectorWrapScalar16(EmitScalarExpr(E->getArg(2))));
10530     auto *VTy = llvm::FixedVectorType::get(Int32Ty, 4);
10531     Ops[1] = EmitNeonCall(CGM.getIntrinsic(Intrinsic::aarch64_neon_sqdmull, VTy),
10532                           ProductOps, "vqdmlXl");
10533     Constant *CI = ConstantInt::get(SizeTy, 0);
10534     Ops[1] = Builder.CreateExtractElement(Ops[1], CI, "lane0");
10535 
10536     unsigned AccumInt = BuiltinID == NEON::BI__builtin_neon_vqdmlalh_s16
10537                                         ? Intrinsic::aarch64_neon_sqadd
10538                                         : Intrinsic::aarch64_neon_sqsub;
10539     return EmitNeonCall(CGM.getIntrinsic(AccumInt, Int32Ty), Ops, "vqdmlXl");
10540   }
10541   case NEON::BI__builtin_neon_vqshlud_n_s64: {
10542     Ops.push_back(EmitScalarExpr(E->getArg(1)));
10543     Ops[1] = Builder.CreateZExt(Ops[1], Int64Ty);
10544     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::aarch64_neon_sqshlu, Int64Ty),
10545                         Ops, "vqshlu_n");
10546   }
10547   case NEON::BI__builtin_neon_vqshld_n_u64:
10548   case NEON::BI__builtin_neon_vqshld_n_s64: {
10549     unsigned Int = BuiltinID == NEON::BI__builtin_neon_vqshld_n_u64
10550                                    ? Intrinsic::aarch64_neon_uqshl
10551                                    : Intrinsic::aarch64_neon_sqshl;
10552     Ops.push_back(EmitScalarExpr(E->getArg(1)));
10553     Ops[1] = Builder.CreateZExt(Ops[1], Int64Ty);
10554     return EmitNeonCall(CGM.getIntrinsic(Int, Int64Ty), Ops, "vqshl_n");
10555   }
10556   case NEON::BI__builtin_neon_vrshrd_n_u64:
10557   case NEON::BI__builtin_neon_vrshrd_n_s64: {
10558     unsigned Int = BuiltinID == NEON::BI__builtin_neon_vrshrd_n_u64
10559                                    ? Intrinsic::aarch64_neon_urshl
10560                                    : Intrinsic::aarch64_neon_srshl;
10561     Ops.push_back(EmitScalarExpr(E->getArg(1)));
10562     int SV = cast<ConstantInt>(Ops[1])->getSExtValue();
10563     Ops[1] = ConstantInt::get(Int64Ty, -SV);
10564     return EmitNeonCall(CGM.getIntrinsic(Int, Int64Ty), Ops, "vrshr_n");
10565   }
10566   case NEON::BI__builtin_neon_vrsrad_n_u64:
10567   case NEON::BI__builtin_neon_vrsrad_n_s64: {
10568     unsigned Int = BuiltinID == NEON::BI__builtin_neon_vrsrad_n_u64
10569                                    ? Intrinsic::aarch64_neon_urshl
10570                                    : Intrinsic::aarch64_neon_srshl;
10571     Ops[1] = Builder.CreateBitCast(Ops[1], Int64Ty);
10572     Ops.push_back(Builder.CreateNeg(EmitScalarExpr(E->getArg(2))));
10573     Ops[1] = Builder.CreateCall(CGM.getIntrinsic(Int, Int64Ty),
10574                                 {Ops[1], Builder.CreateSExt(Ops[2], Int64Ty)});
10575     return Builder.CreateAdd(Ops[0], Builder.CreateBitCast(Ops[1], Int64Ty));
10576   }
10577   case NEON::BI__builtin_neon_vshld_n_s64:
10578   case NEON::BI__builtin_neon_vshld_n_u64: {
10579     llvm::ConstantInt *Amt = cast<ConstantInt>(EmitScalarExpr(E->getArg(1)));
10580     return Builder.CreateShl(
10581         Ops[0], ConstantInt::get(Int64Ty, Amt->getZExtValue()), "shld_n");
10582   }
10583   case NEON::BI__builtin_neon_vshrd_n_s64: {
10584     llvm::ConstantInt *Amt = cast<ConstantInt>(EmitScalarExpr(E->getArg(1)));
10585     return Builder.CreateAShr(
10586         Ops[0], ConstantInt::get(Int64Ty, std::min(static_cast<uint64_t>(63),
10587                                                    Amt->getZExtValue())),
10588         "shrd_n");
10589   }
10590   case NEON::BI__builtin_neon_vshrd_n_u64: {
10591     llvm::ConstantInt *Amt = cast<ConstantInt>(EmitScalarExpr(E->getArg(1)));
10592     uint64_t ShiftAmt = Amt->getZExtValue();
10593     // Right-shifting an unsigned value by its size yields 0.
10594     if (ShiftAmt == 64)
10595       return ConstantInt::get(Int64Ty, 0);
10596     return Builder.CreateLShr(Ops[0], ConstantInt::get(Int64Ty, ShiftAmt),
10597                               "shrd_n");
10598   }
10599   case NEON::BI__builtin_neon_vsrad_n_s64: {
10600     llvm::ConstantInt *Amt = cast<ConstantInt>(EmitScalarExpr(E->getArg(2)));
10601     Ops[1] = Builder.CreateAShr(
10602         Ops[1], ConstantInt::get(Int64Ty, std::min(static_cast<uint64_t>(63),
10603                                                    Amt->getZExtValue())),
10604         "shrd_n");
10605     return Builder.CreateAdd(Ops[0], Ops[1]);
10606   }
10607   case NEON::BI__builtin_neon_vsrad_n_u64: {
10608     llvm::ConstantInt *Amt = cast<ConstantInt>(EmitScalarExpr(E->getArg(2)));
10609     uint64_t ShiftAmt = Amt->getZExtValue();
10610     // Right-shifting an unsigned value by its size yields 0.
10611     // As Op + 0 = Op, return Ops[0] directly.
10612     if (ShiftAmt == 64)
10613       return Ops[0];
10614     Ops[1] = Builder.CreateLShr(Ops[1], ConstantInt::get(Int64Ty, ShiftAmt),
10615                                 "shrd_n");
10616     return Builder.CreateAdd(Ops[0], Ops[1]);
10617   }
10618   case NEON::BI__builtin_neon_vqdmlalh_lane_s16:
10619   case NEON::BI__builtin_neon_vqdmlalh_laneq_s16:
10620   case NEON::BI__builtin_neon_vqdmlslh_lane_s16:
10621   case NEON::BI__builtin_neon_vqdmlslh_laneq_s16: {
10622     Ops[2] = Builder.CreateExtractElement(Ops[2], EmitScalarExpr(E->getArg(3)),
10623                                           "lane");
10624     SmallVector<Value *, 2> ProductOps;
10625     ProductOps.push_back(vectorWrapScalar16(Ops[1]));
10626     ProductOps.push_back(vectorWrapScalar16(Ops[2]));
10627     auto *VTy = llvm::FixedVectorType::get(Int32Ty, 4);
10628     Ops[1] = EmitNeonCall(CGM.getIntrinsic(Intrinsic::aarch64_neon_sqdmull, VTy),
10629                           ProductOps, "vqdmlXl");
10630     Constant *CI = ConstantInt::get(SizeTy, 0);
10631     Ops[1] = Builder.CreateExtractElement(Ops[1], CI, "lane0");
10632     Ops.pop_back();
10633 
10634     unsigned AccInt = (BuiltinID == NEON::BI__builtin_neon_vqdmlalh_lane_s16 ||
10635                        BuiltinID == NEON::BI__builtin_neon_vqdmlalh_laneq_s16)
10636                           ? Intrinsic::aarch64_neon_sqadd
10637                           : Intrinsic::aarch64_neon_sqsub;
10638     return EmitNeonCall(CGM.getIntrinsic(AccInt, Int32Ty), Ops, "vqdmlXl");
10639   }
10640   case NEON::BI__builtin_neon_vqdmlals_s32:
10641   case NEON::BI__builtin_neon_vqdmlsls_s32: {
10642     SmallVector<Value *, 2> ProductOps;
10643     ProductOps.push_back(Ops[1]);
10644     ProductOps.push_back(EmitScalarExpr(E->getArg(2)));
10645     Ops[1] =
10646         EmitNeonCall(CGM.getIntrinsic(Intrinsic::aarch64_neon_sqdmulls_scalar),
10647                      ProductOps, "vqdmlXl");
10648 
10649     unsigned AccumInt = BuiltinID == NEON::BI__builtin_neon_vqdmlals_s32
10650                                         ? Intrinsic::aarch64_neon_sqadd
10651                                         : Intrinsic::aarch64_neon_sqsub;
10652     return EmitNeonCall(CGM.getIntrinsic(AccumInt, Int64Ty), Ops, "vqdmlXl");
10653   }
10654   case NEON::BI__builtin_neon_vqdmlals_lane_s32:
10655   case NEON::BI__builtin_neon_vqdmlals_laneq_s32:
10656   case NEON::BI__builtin_neon_vqdmlsls_lane_s32:
10657   case NEON::BI__builtin_neon_vqdmlsls_laneq_s32: {
10658     Ops[2] = Builder.CreateExtractElement(Ops[2], EmitScalarExpr(E->getArg(3)),
10659                                           "lane");
10660     SmallVector<Value *, 2> ProductOps;
10661     ProductOps.push_back(Ops[1]);
10662     ProductOps.push_back(Ops[2]);
10663     Ops[1] =
10664         EmitNeonCall(CGM.getIntrinsic(Intrinsic::aarch64_neon_sqdmulls_scalar),
10665                      ProductOps, "vqdmlXl");
10666     Ops.pop_back();
10667 
10668     unsigned AccInt = (BuiltinID == NEON::BI__builtin_neon_vqdmlals_lane_s32 ||
10669                        BuiltinID == NEON::BI__builtin_neon_vqdmlals_laneq_s32)
10670                           ? Intrinsic::aarch64_neon_sqadd
10671                           : Intrinsic::aarch64_neon_sqsub;
10672     return EmitNeonCall(CGM.getIntrinsic(AccInt, Int64Ty), Ops, "vqdmlXl");
10673   }
10674   case NEON::BI__builtin_neon_vget_lane_bf16:
10675   case NEON::BI__builtin_neon_vduph_lane_bf16:
10676   case NEON::BI__builtin_neon_vduph_lane_f16: {
10677     return Builder.CreateExtractElement(Ops[0], EmitScalarExpr(E->getArg(1)),
10678                                         "vget_lane");
10679   }
10680   case NEON::BI__builtin_neon_vgetq_lane_bf16:
10681   case NEON::BI__builtin_neon_vduph_laneq_bf16:
10682   case NEON::BI__builtin_neon_vduph_laneq_f16: {
10683     return Builder.CreateExtractElement(Ops[0], EmitScalarExpr(E->getArg(1)),
10684                                         "vgetq_lane");
10685   }
10686 
10687   case AArch64::BI_InterlockedAdd: {
10688     Value *Arg0 = EmitScalarExpr(E->getArg(0));
10689     Value *Arg1 = EmitScalarExpr(E->getArg(1));
10690     AtomicRMWInst *RMWI = Builder.CreateAtomicRMW(
10691       AtomicRMWInst::Add, Arg0, Arg1,
10692       llvm::AtomicOrdering::SequentiallyConsistent);
10693     return Builder.CreateAdd(RMWI, Arg1);
10694   }
10695   }
10696 
10697   llvm::FixedVectorType *VTy = GetNeonType(this, Type);
10698   llvm::Type *Ty = VTy;
10699   if (!Ty)
10700     return nullptr;
10701 
10702   // Not all intrinsics handled by the common case work for AArch64 yet, so only
10703   // defer to common code if it's been added to our special map.
10704   Builtin = findARMVectorIntrinsicInMap(AArch64SIMDIntrinsicMap, BuiltinID,
10705                                         AArch64SIMDIntrinsicsProvenSorted);
10706 
10707   if (Builtin)
10708     return EmitCommonNeonBuiltinExpr(
10709         Builtin->BuiltinID, Builtin->LLVMIntrinsic, Builtin->AltLLVMIntrinsic,
10710         Builtin->NameHint, Builtin->TypeModifier, E, Ops,
10711         /*never use addresses*/ Address::invalid(), Address::invalid(), Arch);
10712 
10713   if (Value *V = EmitAArch64TblBuiltinExpr(*this, BuiltinID, E, Ops, Arch))
10714     return V;
10715 
10716   unsigned Int;
10717   switch (BuiltinID) {
10718   default: return nullptr;
10719   case NEON::BI__builtin_neon_vbsl_v:
10720   case NEON::BI__builtin_neon_vbslq_v: {
10721     llvm::Type *BitTy = llvm::VectorType::getInteger(VTy);
10722     Ops[0] = Builder.CreateBitCast(Ops[0], BitTy, "vbsl");
10723     Ops[1] = Builder.CreateBitCast(Ops[1], BitTy, "vbsl");
10724     Ops[2] = Builder.CreateBitCast(Ops[2], BitTy, "vbsl");
10725 
10726     Ops[1] = Builder.CreateAnd(Ops[0], Ops[1], "vbsl");
10727     Ops[2] = Builder.CreateAnd(Builder.CreateNot(Ops[0]), Ops[2], "vbsl");
10728     Ops[0] = Builder.CreateOr(Ops[1], Ops[2], "vbsl");
10729     return Builder.CreateBitCast(Ops[0], Ty);
10730   }
10731   case NEON::BI__builtin_neon_vfma_lane_v:
10732   case NEON::BI__builtin_neon_vfmaq_lane_v: { // Only used for FP types
10733     // The ARM builtins (and instructions) have the addend as the first
10734     // operand, but the 'fma' intrinsics have it last. Swap it around here.
10735     Value *Addend = Ops[0];
10736     Value *Multiplicand = Ops[1];
10737     Value *LaneSource = Ops[2];
10738     Ops[0] = Multiplicand;
10739     Ops[1] = LaneSource;
10740     Ops[2] = Addend;
10741 
10742     // Now adjust things to handle the lane access.
10743     auto *SourceTy = BuiltinID == NEON::BI__builtin_neon_vfmaq_lane_v
10744                          ? llvm::FixedVectorType::get(VTy->getElementType(),
10745                                                       VTy->getNumElements() / 2)
10746                          : VTy;
10747     llvm::Constant *cst = cast<Constant>(Ops[3]);
10748     Value *SV = llvm::ConstantVector::getSplat(VTy->getElementCount(), cst);
10749     Ops[1] = Builder.CreateBitCast(Ops[1], SourceTy);
10750     Ops[1] = Builder.CreateShuffleVector(Ops[1], Ops[1], SV, "lane");
10751 
10752     Ops.pop_back();
10753     Int = Builder.getIsFPConstrained() ? Intrinsic::experimental_constrained_fma
10754                                        : Intrinsic::fma;
10755     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "fmla");
10756   }
10757   case NEON::BI__builtin_neon_vfma_laneq_v: {
10758     auto *VTy = cast<llvm::FixedVectorType>(Ty);
10759     // v1f64 fma should be mapped to Neon scalar f64 fma
10760     if (VTy && VTy->getElementType() == DoubleTy) {
10761       Ops[0] = Builder.CreateBitCast(Ops[0], DoubleTy);
10762       Ops[1] = Builder.CreateBitCast(Ops[1], DoubleTy);
10763       llvm::FixedVectorType *VTy =
10764           GetNeonType(this, NeonTypeFlags(NeonTypeFlags::Float64, false, true));
10765       Ops[2] = Builder.CreateBitCast(Ops[2], VTy);
10766       Ops[2] = Builder.CreateExtractElement(Ops[2], Ops[3], "extract");
10767       Value *Result;
10768       Result = emitCallMaybeConstrainedFPBuiltin(
10769           *this, Intrinsic::fma, Intrinsic::experimental_constrained_fma,
10770           DoubleTy, {Ops[1], Ops[2], Ops[0]});
10771       return Builder.CreateBitCast(Result, Ty);
10772     }
10773     Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
10774     Ops[1] = Builder.CreateBitCast(Ops[1], Ty);
10775 
10776     auto *STy = llvm::FixedVectorType::get(VTy->getElementType(),
10777                                            VTy->getNumElements() * 2);
10778     Ops[2] = Builder.CreateBitCast(Ops[2], STy);
10779     Value *SV = llvm::ConstantVector::getSplat(VTy->getElementCount(),
10780                                                cast<ConstantInt>(Ops[3]));
10781     Ops[2] = Builder.CreateShuffleVector(Ops[2], Ops[2], SV, "lane");
10782 
10783     return emitCallMaybeConstrainedFPBuiltin(
10784         *this, Intrinsic::fma, Intrinsic::experimental_constrained_fma, Ty,
10785         {Ops[2], Ops[1], Ops[0]});
10786   }
10787   case NEON::BI__builtin_neon_vfmaq_laneq_v: {
10788     Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
10789     Ops[1] = Builder.CreateBitCast(Ops[1], Ty);
10790 
10791     Ops[2] = Builder.CreateBitCast(Ops[2], Ty);
10792     Ops[2] = EmitNeonSplat(Ops[2], cast<ConstantInt>(Ops[3]));
10793     return emitCallMaybeConstrainedFPBuiltin(
10794         *this, Intrinsic::fma, Intrinsic::experimental_constrained_fma, Ty,
10795         {Ops[2], Ops[1], Ops[0]});
10796   }
10797   case NEON::BI__builtin_neon_vfmah_lane_f16:
10798   case NEON::BI__builtin_neon_vfmas_lane_f32:
10799   case NEON::BI__builtin_neon_vfmah_laneq_f16:
10800   case NEON::BI__builtin_neon_vfmas_laneq_f32:
10801   case NEON::BI__builtin_neon_vfmad_lane_f64:
10802   case NEON::BI__builtin_neon_vfmad_laneq_f64: {
10803     Ops.push_back(EmitScalarExpr(E->getArg(3)));
10804     llvm::Type *Ty = ConvertType(E->getCallReturnType(getContext()));
10805     Ops[2] = Builder.CreateExtractElement(Ops[2], Ops[3], "extract");
10806     return emitCallMaybeConstrainedFPBuiltin(
10807         *this, Intrinsic::fma, Intrinsic::experimental_constrained_fma, Ty,
10808         {Ops[1], Ops[2], Ops[0]});
10809   }
10810   case NEON::BI__builtin_neon_vmull_v:
10811     // FIXME: improve sharing scheme to cope with 3 alternative LLVM intrinsics.
10812     Int = usgn ? Intrinsic::aarch64_neon_umull : Intrinsic::aarch64_neon_smull;
10813     if (Type.isPoly()) Int = Intrinsic::aarch64_neon_pmull;
10814     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vmull");
10815   case NEON::BI__builtin_neon_vmax_v:
10816   case NEON::BI__builtin_neon_vmaxq_v:
10817     // FIXME: improve sharing scheme to cope with 3 alternative LLVM intrinsics.
10818     Int = usgn ? Intrinsic::aarch64_neon_umax : Intrinsic::aarch64_neon_smax;
10819     if (Ty->isFPOrFPVectorTy()) Int = Intrinsic::aarch64_neon_fmax;
10820     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vmax");
10821   case NEON::BI__builtin_neon_vmaxh_f16: {
10822     Ops.push_back(EmitScalarExpr(E->getArg(1)));
10823     Int = Intrinsic::aarch64_neon_fmax;
10824     return EmitNeonCall(CGM.getIntrinsic(Int, HalfTy), Ops, "vmax");
10825   }
10826   case NEON::BI__builtin_neon_vmin_v:
10827   case NEON::BI__builtin_neon_vminq_v:
10828     // FIXME: improve sharing scheme to cope with 3 alternative LLVM intrinsics.
10829     Int = usgn ? Intrinsic::aarch64_neon_umin : Intrinsic::aarch64_neon_smin;
10830     if (Ty->isFPOrFPVectorTy()) Int = Intrinsic::aarch64_neon_fmin;
10831     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vmin");
10832   case NEON::BI__builtin_neon_vminh_f16: {
10833     Ops.push_back(EmitScalarExpr(E->getArg(1)));
10834     Int = Intrinsic::aarch64_neon_fmin;
10835     return EmitNeonCall(CGM.getIntrinsic(Int, HalfTy), Ops, "vmin");
10836   }
10837   case NEON::BI__builtin_neon_vabd_v:
10838   case NEON::BI__builtin_neon_vabdq_v:
10839     // FIXME: improve sharing scheme to cope with 3 alternative LLVM intrinsics.
10840     Int = usgn ? Intrinsic::aarch64_neon_uabd : Intrinsic::aarch64_neon_sabd;
10841     if (Ty->isFPOrFPVectorTy()) Int = Intrinsic::aarch64_neon_fabd;
10842     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vabd");
10843   case NEON::BI__builtin_neon_vpadal_v:
10844   case NEON::BI__builtin_neon_vpadalq_v: {
10845     unsigned ArgElts = VTy->getNumElements();
10846     llvm::IntegerType *EltTy = cast<IntegerType>(VTy->getElementType());
10847     unsigned BitWidth = EltTy->getBitWidth();
10848     auto *ArgTy = llvm::FixedVectorType::get(
10849         llvm::IntegerType::get(getLLVMContext(), BitWidth / 2), 2 * ArgElts);
10850     llvm::Type* Tys[2] = { VTy, ArgTy };
10851     Int = usgn ? Intrinsic::aarch64_neon_uaddlp : Intrinsic::aarch64_neon_saddlp;
10852     SmallVector<llvm::Value*, 1> TmpOps;
10853     TmpOps.push_back(Ops[1]);
10854     Function *F = CGM.getIntrinsic(Int, Tys);
10855     llvm::Value *tmp = EmitNeonCall(F, TmpOps, "vpadal");
10856     llvm::Value *addend = Builder.CreateBitCast(Ops[0], tmp->getType());
10857     return Builder.CreateAdd(tmp, addend);
10858   }
10859   case NEON::BI__builtin_neon_vpmin_v:
10860   case NEON::BI__builtin_neon_vpminq_v:
10861     // FIXME: improve sharing scheme to cope with 3 alternative LLVM intrinsics.
10862     Int = usgn ? Intrinsic::aarch64_neon_uminp : Intrinsic::aarch64_neon_sminp;
10863     if (Ty->isFPOrFPVectorTy()) Int = Intrinsic::aarch64_neon_fminp;
10864     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vpmin");
10865   case NEON::BI__builtin_neon_vpmax_v:
10866   case NEON::BI__builtin_neon_vpmaxq_v:
10867     // FIXME: improve sharing scheme to cope with 3 alternative LLVM intrinsics.
10868     Int = usgn ? Intrinsic::aarch64_neon_umaxp : Intrinsic::aarch64_neon_smaxp;
10869     if (Ty->isFPOrFPVectorTy()) Int = Intrinsic::aarch64_neon_fmaxp;
10870     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vpmax");
10871   case NEON::BI__builtin_neon_vminnm_v:
10872   case NEON::BI__builtin_neon_vminnmq_v:
10873     Int = Intrinsic::aarch64_neon_fminnm;
10874     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vminnm");
10875   case NEON::BI__builtin_neon_vminnmh_f16:
10876     Ops.push_back(EmitScalarExpr(E->getArg(1)));
10877     Int = Intrinsic::aarch64_neon_fminnm;
10878     return EmitNeonCall(CGM.getIntrinsic(Int, HalfTy), Ops, "vminnm");
10879   case NEON::BI__builtin_neon_vmaxnm_v:
10880   case NEON::BI__builtin_neon_vmaxnmq_v:
10881     Int = Intrinsic::aarch64_neon_fmaxnm;
10882     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vmaxnm");
10883   case NEON::BI__builtin_neon_vmaxnmh_f16:
10884     Ops.push_back(EmitScalarExpr(E->getArg(1)));
10885     Int = Intrinsic::aarch64_neon_fmaxnm;
10886     return EmitNeonCall(CGM.getIntrinsic(Int, HalfTy), Ops, "vmaxnm");
10887   case NEON::BI__builtin_neon_vrecpss_f32: {
10888     Ops.push_back(EmitScalarExpr(E->getArg(1)));
10889     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::aarch64_neon_frecps, FloatTy),
10890                         Ops, "vrecps");
10891   }
10892   case NEON::BI__builtin_neon_vrecpsd_f64:
10893     Ops.push_back(EmitScalarExpr(E->getArg(1)));
10894     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::aarch64_neon_frecps, DoubleTy),
10895                         Ops, "vrecps");
10896   case NEON::BI__builtin_neon_vrecpsh_f16:
10897     Ops.push_back(EmitScalarExpr(E->getArg(1)));
10898     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::aarch64_neon_frecps, HalfTy),
10899                         Ops, "vrecps");
10900   case NEON::BI__builtin_neon_vqshrun_n_v:
10901     Int = Intrinsic::aarch64_neon_sqshrun;
10902     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vqshrun_n");
10903   case NEON::BI__builtin_neon_vqrshrun_n_v:
10904     Int = Intrinsic::aarch64_neon_sqrshrun;
10905     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vqrshrun_n");
10906   case NEON::BI__builtin_neon_vqshrn_n_v:
10907     Int = usgn ? Intrinsic::aarch64_neon_uqshrn : Intrinsic::aarch64_neon_sqshrn;
10908     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vqshrn_n");
10909   case NEON::BI__builtin_neon_vrshrn_n_v:
10910     Int = Intrinsic::aarch64_neon_rshrn;
10911     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vrshrn_n");
10912   case NEON::BI__builtin_neon_vqrshrn_n_v:
10913     Int = usgn ? Intrinsic::aarch64_neon_uqrshrn : Intrinsic::aarch64_neon_sqrshrn;
10914     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vqrshrn_n");
10915   case NEON::BI__builtin_neon_vrndah_f16: {
10916     Ops.push_back(EmitScalarExpr(E->getArg(0)));
10917     Int = Builder.getIsFPConstrained()
10918               ? Intrinsic::experimental_constrained_round
10919               : Intrinsic::round;
10920     return EmitNeonCall(CGM.getIntrinsic(Int, HalfTy), Ops, "vrnda");
10921   }
10922   case NEON::BI__builtin_neon_vrnda_v:
10923   case NEON::BI__builtin_neon_vrndaq_v: {
10924     Int = Builder.getIsFPConstrained()
10925               ? Intrinsic::experimental_constrained_round
10926               : Intrinsic::round;
10927     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vrnda");
10928   }
10929   case NEON::BI__builtin_neon_vrndih_f16: {
10930     Ops.push_back(EmitScalarExpr(E->getArg(0)));
10931     Int = Builder.getIsFPConstrained()
10932               ? Intrinsic::experimental_constrained_nearbyint
10933               : Intrinsic::nearbyint;
10934     return EmitNeonCall(CGM.getIntrinsic(Int, HalfTy), Ops, "vrndi");
10935   }
10936   case NEON::BI__builtin_neon_vrndmh_f16: {
10937     Ops.push_back(EmitScalarExpr(E->getArg(0)));
10938     Int = Builder.getIsFPConstrained()
10939               ? Intrinsic::experimental_constrained_floor
10940               : Intrinsic::floor;
10941     return EmitNeonCall(CGM.getIntrinsic(Int, HalfTy), Ops, "vrndm");
10942   }
10943   case NEON::BI__builtin_neon_vrndm_v:
10944   case NEON::BI__builtin_neon_vrndmq_v: {
10945     Int = Builder.getIsFPConstrained()
10946               ? Intrinsic::experimental_constrained_floor
10947               : Intrinsic::floor;
10948     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vrndm");
10949   }
10950   case NEON::BI__builtin_neon_vrndnh_f16: {
10951     Ops.push_back(EmitScalarExpr(E->getArg(0)));
10952     Int = Builder.getIsFPConstrained()
10953               ? Intrinsic::experimental_constrained_roundeven
10954               : Intrinsic::roundeven;
10955     return EmitNeonCall(CGM.getIntrinsic(Int, HalfTy), Ops, "vrndn");
10956   }
10957   case NEON::BI__builtin_neon_vrndn_v:
10958   case NEON::BI__builtin_neon_vrndnq_v: {
10959     Int = Builder.getIsFPConstrained()
10960               ? Intrinsic::experimental_constrained_roundeven
10961               : Intrinsic::roundeven;
10962     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vrndn");
10963   }
10964   case NEON::BI__builtin_neon_vrndns_f32: {
10965     Ops.push_back(EmitScalarExpr(E->getArg(0)));
10966     Int = Builder.getIsFPConstrained()
10967               ? Intrinsic::experimental_constrained_roundeven
10968               : Intrinsic::roundeven;
10969     return EmitNeonCall(CGM.getIntrinsic(Int, FloatTy), Ops, "vrndn");
10970   }
10971   case NEON::BI__builtin_neon_vrndph_f16: {
10972     Ops.push_back(EmitScalarExpr(E->getArg(0)));
10973     Int = Builder.getIsFPConstrained()
10974               ? Intrinsic::experimental_constrained_ceil
10975               : Intrinsic::ceil;
10976     return EmitNeonCall(CGM.getIntrinsic(Int, HalfTy), Ops, "vrndp");
10977   }
10978   case NEON::BI__builtin_neon_vrndp_v:
10979   case NEON::BI__builtin_neon_vrndpq_v: {
10980     Int = Builder.getIsFPConstrained()
10981               ? Intrinsic::experimental_constrained_ceil
10982               : Intrinsic::ceil;
10983     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vrndp");
10984   }
10985   case NEON::BI__builtin_neon_vrndxh_f16: {
10986     Ops.push_back(EmitScalarExpr(E->getArg(0)));
10987     Int = Builder.getIsFPConstrained()
10988               ? Intrinsic::experimental_constrained_rint
10989               : Intrinsic::rint;
10990     return EmitNeonCall(CGM.getIntrinsic(Int, HalfTy), Ops, "vrndx");
10991   }
10992   case NEON::BI__builtin_neon_vrndx_v:
10993   case NEON::BI__builtin_neon_vrndxq_v: {
10994     Int = Builder.getIsFPConstrained()
10995               ? Intrinsic::experimental_constrained_rint
10996               : Intrinsic::rint;
10997     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vrndx");
10998   }
10999   case NEON::BI__builtin_neon_vrndh_f16: {
11000     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11001     Int = Builder.getIsFPConstrained()
11002               ? Intrinsic::experimental_constrained_trunc
11003               : Intrinsic::trunc;
11004     return EmitNeonCall(CGM.getIntrinsic(Int, HalfTy), Ops, "vrndz");
11005   }
11006   case NEON::BI__builtin_neon_vrnd32x_v:
11007   case NEON::BI__builtin_neon_vrnd32xq_v: {
11008     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11009     Int = Intrinsic::aarch64_neon_frint32x;
11010     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vrnd32x");
11011   }
11012   case NEON::BI__builtin_neon_vrnd32z_v:
11013   case NEON::BI__builtin_neon_vrnd32zq_v: {
11014     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11015     Int = Intrinsic::aarch64_neon_frint32z;
11016     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vrnd32z");
11017   }
11018   case NEON::BI__builtin_neon_vrnd64x_v:
11019   case NEON::BI__builtin_neon_vrnd64xq_v: {
11020     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11021     Int = Intrinsic::aarch64_neon_frint64x;
11022     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vrnd64x");
11023   }
11024   case NEON::BI__builtin_neon_vrnd64z_v:
11025   case NEON::BI__builtin_neon_vrnd64zq_v: {
11026     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11027     Int = Intrinsic::aarch64_neon_frint64z;
11028     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vrnd64z");
11029   }
11030   case NEON::BI__builtin_neon_vrnd_v:
11031   case NEON::BI__builtin_neon_vrndq_v: {
11032     Int = Builder.getIsFPConstrained()
11033               ? Intrinsic::experimental_constrained_trunc
11034               : Intrinsic::trunc;
11035     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vrndz");
11036   }
11037   case NEON::BI__builtin_neon_vcvt_f64_v:
11038   case NEON::BI__builtin_neon_vcvtq_f64_v:
11039     Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
11040     Ty = GetNeonType(this, NeonTypeFlags(NeonTypeFlags::Float64, false, quad));
11041     return usgn ? Builder.CreateUIToFP(Ops[0], Ty, "vcvt")
11042                 : Builder.CreateSIToFP(Ops[0], Ty, "vcvt");
11043   case NEON::BI__builtin_neon_vcvt_f64_f32: {
11044     assert(Type.getEltType() == NeonTypeFlags::Float64 && quad &&
11045            "unexpected vcvt_f64_f32 builtin");
11046     NeonTypeFlags SrcFlag = NeonTypeFlags(NeonTypeFlags::Float32, false, false);
11047     Ops[0] = Builder.CreateBitCast(Ops[0], GetNeonType(this, SrcFlag));
11048 
11049     return Builder.CreateFPExt(Ops[0], Ty, "vcvt");
11050   }
11051   case NEON::BI__builtin_neon_vcvt_f32_f64: {
11052     assert(Type.getEltType() == NeonTypeFlags::Float32 &&
11053            "unexpected vcvt_f32_f64 builtin");
11054     NeonTypeFlags SrcFlag = NeonTypeFlags(NeonTypeFlags::Float64, false, true);
11055     Ops[0] = Builder.CreateBitCast(Ops[0], GetNeonType(this, SrcFlag));
11056 
11057     return Builder.CreateFPTrunc(Ops[0], Ty, "vcvt");
11058   }
11059   case NEON::BI__builtin_neon_vcvt_s32_v:
11060   case NEON::BI__builtin_neon_vcvt_u32_v:
11061   case NEON::BI__builtin_neon_vcvt_s64_v:
11062   case NEON::BI__builtin_neon_vcvt_u64_v:
11063   case NEON::BI__builtin_neon_vcvt_s16_v:
11064   case NEON::BI__builtin_neon_vcvt_u16_v:
11065   case NEON::BI__builtin_neon_vcvtq_s32_v:
11066   case NEON::BI__builtin_neon_vcvtq_u32_v:
11067   case NEON::BI__builtin_neon_vcvtq_s64_v:
11068   case NEON::BI__builtin_neon_vcvtq_u64_v:
11069   case NEON::BI__builtin_neon_vcvtq_s16_v:
11070   case NEON::BI__builtin_neon_vcvtq_u16_v: {
11071     Int =
11072         usgn ? Intrinsic::aarch64_neon_fcvtzu : Intrinsic::aarch64_neon_fcvtzs;
11073     llvm::Type *Tys[2] = {Ty, GetFloatNeonType(this, Type)};
11074     return EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vcvtz");
11075   }
11076   case NEON::BI__builtin_neon_vcvta_s16_v:
11077   case NEON::BI__builtin_neon_vcvta_u16_v:
11078   case NEON::BI__builtin_neon_vcvta_s32_v:
11079   case NEON::BI__builtin_neon_vcvtaq_s16_v:
11080   case NEON::BI__builtin_neon_vcvtaq_s32_v:
11081   case NEON::BI__builtin_neon_vcvta_u32_v:
11082   case NEON::BI__builtin_neon_vcvtaq_u16_v:
11083   case NEON::BI__builtin_neon_vcvtaq_u32_v:
11084   case NEON::BI__builtin_neon_vcvta_s64_v:
11085   case NEON::BI__builtin_neon_vcvtaq_s64_v:
11086   case NEON::BI__builtin_neon_vcvta_u64_v:
11087   case NEON::BI__builtin_neon_vcvtaq_u64_v: {
11088     Int = usgn ? Intrinsic::aarch64_neon_fcvtau : Intrinsic::aarch64_neon_fcvtas;
11089     llvm::Type *Tys[2] = { Ty, GetFloatNeonType(this, Type) };
11090     return EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vcvta");
11091   }
11092   case NEON::BI__builtin_neon_vcvtm_s16_v:
11093   case NEON::BI__builtin_neon_vcvtm_s32_v:
11094   case NEON::BI__builtin_neon_vcvtmq_s16_v:
11095   case NEON::BI__builtin_neon_vcvtmq_s32_v:
11096   case NEON::BI__builtin_neon_vcvtm_u16_v:
11097   case NEON::BI__builtin_neon_vcvtm_u32_v:
11098   case NEON::BI__builtin_neon_vcvtmq_u16_v:
11099   case NEON::BI__builtin_neon_vcvtmq_u32_v:
11100   case NEON::BI__builtin_neon_vcvtm_s64_v:
11101   case NEON::BI__builtin_neon_vcvtmq_s64_v:
11102   case NEON::BI__builtin_neon_vcvtm_u64_v:
11103   case NEON::BI__builtin_neon_vcvtmq_u64_v: {
11104     Int = usgn ? Intrinsic::aarch64_neon_fcvtmu : Intrinsic::aarch64_neon_fcvtms;
11105     llvm::Type *Tys[2] = { Ty, GetFloatNeonType(this, Type) };
11106     return EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vcvtm");
11107   }
11108   case NEON::BI__builtin_neon_vcvtn_s16_v:
11109   case NEON::BI__builtin_neon_vcvtn_s32_v:
11110   case NEON::BI__builtin_neon_vcvtnq_s16_v:
11111   case NEON::BI__builtin_neon_vcvtnq_s32_v:
11112   case NEON::BI__builtin_neon_vcvtn_u16_v:
11113   case NEON::BI__builtin_neon_vcvtn_u32_v:
11114   case NEON::BI__builtin_neon_vcvtnq_u16_v:
11115   case NEON::BI__builtin_neon_vcvtnq_u32_v:
11116   case NEON::BI__builtin_neon_vcvtn_s64_v:
11117   case NEON::BI__builtin_neon_vcvtnq_s64_v:
11118   case NEON::BI__builtin_neon_vcvtn_u64_v:
11119   case NEON::BI__builtin_neon_vcvtnq_u64_v: {
11120     Int = usgn ? Intrinsic::aarch64_neon_fcvtnu : Intrinsic::aarch64_neon_fcvtns;
11121     llvm::Type *Tys[2] = { Ty, GetFloatNeonType(this, Type) };
11122     return EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vcvtn");
11123   }
11124   case NEON::BI__builtin_neon_vcvtp_s16_v:
11125   case NEON::BI__builtin_neon_vcvtp_s32_v:
11126   case NEON::BI__builtin_neon_vcvtpq_s16_v:
11127   case NEON::BI__builtin_neon_vcvtpq_s32_v:
11128   case NEON::BI__builtin_neon_vcvtp_u16_v:
11129   case NEON::BI__builtin_neon_vcvtp_u32_v:
11130   case NEON::BI__builtin_neon_vcvtpq_u16_v:
11131   case NEON::BI__builtin_neon_vcvtpq_u32_v:
11132   case NEON::BI__builtin_neon_vcvtp_s64_v:
11133   case NEON::BI__builtin_neon_vcvtpq_s64_v:
11134   case NEON::BI__builtin_neon_vcvtp_u64_v:
11135   case NEON::BI__builtin_neon_vcvtpq_u64_v: {
11136     Int = usgn ? Intrinsic::aarch64_neon_fcvtpu : Intrinsic::aarch64_neon_fcvtps;
11137     llvm::Type *Tys[2] = { Ty, GetFloatNeonType(this, Type) };
11138     return EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vcvtp");
11139   }
11140   case NEON::BI__builtin_neon_vmulx_v:
11141   case NEON::BI__builtin_neon_vmulxq_v: {
11142     Int = Intrinsic::aarch64_neon_fmulx;
11143     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vmulx");
11144   }
11145   case NEON::BI__builtin_neon_vmulxh_lane_f16:
11146   case NEON::BI__builtin_neon_vmulxh_laneq_f16: {
11147     // vmulx_lane should be mapped to Neon scalar mulx after
11148     // extracting the scalar element
11149     Ops.push_back(EmitScalarExpr(E->getArg(2)));
11150     Ops[1] = Builder.CreateExtractElement(Ops[1], Ops[2], "extract");
11151     Ops.pop_back();
11152     Int = Intrinsic::aarch64_neon_fmulx;
11153     return EmitNeonCall(CGM.getIntrinsic(Int, HalfTy), Ops, "vmulx");
11154   }
11155   case NEON::BI__builtin_neon_vmul_lane_v:
11156   case NEON::BI__builtin_neon_vmul_laneq_v: {
11157     // v1f64 vmul_lane should be mapped to Neon scalar mul lane
11158     bool Quad = false;
11159     if (BuiltinID == NEON::BI__builtin_neon_vmul_laneq_v)
11160       Quad = true;
11161     Ops[0] = Builder.CreateBitCast(Ops[0], DoubleTy);
11162     llvm::FixedVectorType *VTy =
11163         GetNeonType(this, NeonTypeFlags(NeonTypeFlags::Float64, false, Quad));
11164     Ops[1] = Builder.CreateBitCast(Ops[1], VTy);
11165     Ops[1] = Builder.CreateExtractElement(Ops[1], Ops[2], "extract");
11166     Value *Result = Builder.CreateFMul(Ops[0], Ops[1]);
11167     return Builder.CreateBitCast(Result, Ty);
11168   }
11169   case NEON::BI__builtin_neon_vnegd_s64:
11170     return Builder.CreateNeg(EmitScalarExpr(E->getArg(0)), "vnegd");
11171   case NEON::BI__builtin_neon_vnegh_f16:
11172     return Builder.CreateFNeg(EmitScalarExpr(E->getArg(0)), "vnegh");
11173   case NEON::BI__builtin_neon_vpmaxnm_v:
11174   case NEON::BI__builtin_neon_vpmaxnmq_v: {
11175     Int = Intrinsic::aarch64_neon_fmaxnmp;
11176     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vpmaxnm");
11177   }
11178   case NEON::BI__builtin_neon_vpminnm_v:
11179   case NEON::BI__builtin_neon_vpminnmq_v: {
11180     Int = Intrinsic::aarch64_neon_fminnmp;
11181     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vpminnm");
11182   }
11183   case NEON::BI__builtin_neon_vsqrth_f16: {
11184     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11185     Int = Builder.getIsFPConstrained()
11186               ? Intrinsic::experimental_constrained_sqrt
11187               : Intrinsic::sqrt;
11188     return EmitNeonCall(CGM.getIntrinsic(Int, HalfTy), Ops, "vsqrt");
11189   }
11190   case NEON::BI__builtin_neon_vsqrt_v:
11191   case NEON::BI__builtin_neon_vsqrtq_v: {
11192     Int = Builder.getIsFPConstrained()
11193               ? Intrinsic::experimental_constrained_sqrt
11194               : Intrinsic::sqrt;
11195     Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
11196     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vsqrt");
11197   }
11198   case NEON::BI__builtin_neon_vrbit_v:
11199   case NEON::BI__builtin_neon_vrbitq_v: {
11200     Int = Intrinsic::bitreverse;
11201     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vrbit");
11202   }
11203   case NEON::BI__builtin_neon_vaddv_u8:
11204     // FIXME: These are handled by the AArch64 scalar code.
11205     usgn = true;
11206     LLVM_FALLTHROUGH;
11207   case NEON::BI__builtin_neon_vaddv_s8: {
11208     Int = usgn ? Intrinsic::aarch64_neon_uaddv : Intrinsic::aarch64_neon_saddv;
11209     Ty = Int32Ty;
11210     VTy = llvm::FixedVectorType::get(Int8Ty, 8);
11211     llvm::Type *Tys[2] = { Ty, VTy };
11212     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11213     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vaddv");
11214     return Builder.CreateTrunc(Ops[0], Int8Ty);
11215   }
11216   case NEON::BI__builtin_neon_vaddv_u16:
11217     usgn = true;
11218     LLVM_FALLTHROUGH;
11219   case NEON::BI__builtin_neon_vaddv_s16: {
11220     Int = usgn ? Intrinsic::aarch64_neon_uaddv : Intrinsic::aarch64_neon_saddv;
11221     Ty = Int32Ty;
11222     VTy = llvm::FixedVectorType::get(Int16Ty, 4);
11223     llvm::Type *Tys[2] = { Ty, VTy };
11224     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11225     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vaddv");
11226     return Builder.CreateTrunc(Ops[0], Int16Ty);
11227   }
11228   case NEON::BI__builtin_neon_vaddvq_u8:
11229     usgn = true;
11230     LLVM_FALLTHROUGH;
11231   case NEON::BI__builtin_neon_vaddvq_s8: {
11232     Int = usgn ? Intrinsic::aarch64_neon_uaddv : Intrinsic::aarch64_neon_saddv;
11233     Ty = Int32Ty;
11234     VTy = llvm::FixedVectorType::get(Int8Ty, 16);
11235     llvm::Type *Tys[2] = { Ty, VTy };
11236     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11237     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vaddv");
11238     return Builder.CreateTrunc(Ops[0], Int8Ty);
11239   }
11240   case NEON::BI__builtin_neon_vaddvq_u16:
11241     usgn = true;
11242     LLVM_FALLTHROUGH;
11243   case NEON::BI__builtin_neon_vaddvq_s16: {
11244     Int = usgn ? Intrinsic::aarch64_neon_uaddv : Intrinsic::aarch64_neon_saddv;
11245     Ty = Int32Ty;
11246     VTy = llvm::FixedVectorType::get(Int16Ty, 8);
11247     llvm::Type *Tys[2] = { Ty, VTy };
11248     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11249     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vaddv");
11250     return Builder.CreateTrunc(Ops[0], Int16Ty);
11251   }
11252   case NEON::BI__builtin_neon_vmaxv_u8: {
11253     Int = Intrinsic::aarch64_neon_umaxv;
11254     Ty = Int32Ty;
11255     VTy = llvm::FixedVectorType::get(Int8Ty, 8);
11256     llvm::Type *Tys[2] = { Ty, VTy };
11257     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11258     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vmaxv");
11259     return Builder.CreateTrunc(Ops[0], Int8Ty);
11260   }
11261   case NEON::BI__builtin_neon_vmaxv_u16: {
11262     Int = Intrinsic::aarch64_neon_umaxv;
11263     Ty = Int32Ty;
11264     VTy = llvm::FixedVectorType::get(Int16Ty, 4);
11265     llvm::Type *Tys[2] = { Ty, VTy };
11266     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11267     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vmaxv");
11268     return Builder.CreateTrunc(Ops[0], Int16Ty);
11269   }
11270   case NEON::BI__builtin_neon_vmaxvq_u8: {
11271     Int = Intrinsic::aarch64_neon_umaxv;
11272     Ty = Int32Ty;
11273     VTy = llvm::FixedVectorType::get(Int8Ty, 16);
11274     llvm::Type *Tys[2] = { Ty, VTy };
11275     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11276     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vmaxv");
11277     return Builder.CreateTrunc(Ops[0], Int8Ty);
11278   }
11279   case NEON::BI__builtin_neon_vmaxvq_u16: {
11280     Int = Intrinsic::aarch64_neon_umaxv;
11281     Ty = Int32Ty;
11282     VTy = llvm::FixedVectorType::get(Int16Ty, 8);
11283     llvm::Type *Tys[2] = { Ty, VTy };
11284     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11285     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vmaxv");
11286     return Builder.CreateTrunc(Ops[0], Int16Ty);
11287   }
11288   case NEON::BI__builtin_neon_vmaxv_s8: {
11289     Int = Intrinsic::aarch64_neon_smaxv;
11290     Ty = Int32Ty;
11291     VTy = llvm::FixedVectorType::get(Int8Ty, 8);
11292     llvm::Type *Tys[2] = { Ty, VTy };
11293     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11294     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vmaxv");
11295     return Builder.CreateTrunc(Ops[0], Int8Ty);
11296   }
11297   case NEON::BI__builtin_neon_vmaxv_s16: {
11298     Int = Intrinsic::aarch64_neon_smaxv;
11299     Ty = Int32Ty;
11300     VTy = llvm::FixedVectorType::get(Int16Ty, 4);
11301     llvm::Type *Tys[2] = { Ty, VTy };
11302     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11303     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vmaxv");
11304     return Builder.CreateTrunc(Ops[0], Int16Ty);
11305   }
11306   case NEON::BI__builtin_neon_vmaxvq_s8: {
11307     Int = Intrinsic::aarch64_neon_smaxv;
11308     Ty = Int32Ty;
11309     VTy = llvm::FixedVectorType::get(Int8Ty, 16);
11310     llvm::Type *Tys[2] = { Ty, VTy };
11311     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11312     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vmaxv");
11313     return Builder.CreateTrunc(Ops[0], Int8Ty);
11314   }
11315   case NEON::BI__builtin_neon_vmaxvq_s16: {
11316     Int = Intrinsic::aarch64_neon_smaxv;
11317     Ty = Int32Ty;
11318     VTy = llvm::FixedVectorType::get(Int16Ty, 8);
11319     llvm::Type *Tys[2] = { Ty, VTy };
11320     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11321     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vmaxv");
11322     return Builder.CreateTrunc(Ops[0], Int16Ty);
11323   }
11324   case NEON::BI__builtin_neon_vmaxv_f16: {
11325     Int = Intrinsic::aarch64_neon_fmaxv;
11326     Ty = HalfTy;
11327     VTy = llvm::FixedVectorType::get(HalfTy, 4);
11328     llvm::Type *Tys[2] = { Ty, VTy };
11329     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11330     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vmaxv");
11331     return Builder.CreateTrunc(Ops[0], HalfTy);
11332   }
11333   case NEON::BI__builtin_neon_vmaxvq_f16: {
11334     Int = Intrinsic::aarch64_neon_fmaxv;
11335     Ty = HalfTy;
11336     VTy = llvm::FixedVectorType::get(HalfTy, 8);
11337     llvm::Type *Tys[2] = { Ty, VTy };
11338     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11339     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vmaxv");
11340     return Builder.CreateTrunc(Ops[0], HalfTy);
11341   }
11342   case NEON::BI__builtin_neon_vminv_u8: {
11343     Int = Intrinsic::aarch64_neon_uminv;
11344     Ty = Int32Ty;
11345     VTy = llvm::FixedVectorType::get(Int8Ty, 8);
11346     llvm::Type *Tys[2] = { Ty, VTy };
11347     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11348     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vminv");
11349     return Builder.CreateTrunc(Ops[0], Int8Ty);
11350   }
11351   case NEON::BI__builtin_neon_vminv_u16: {
11352     Int = Intrinsic::aarch64_neon_uminv;
11353     Ty = Int32Ty;
11354     VTy = llvm::FixedVectorType::get(Int16Ty, 4);
11355     llvm::Type *Tys[2] = { Ty, VTy };
11356     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11357     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vminv");
11358     return Builder.CreateTrunc(Ops[0], Int16Ty);
11359   }
11360   case NEON::BI__builtin_neon_vminvq_u8: {
11361     Int = Intrinsic::aarch64_neon_uminv;
11362     Ty = Int32Ty;
11363     VTy = llvm::FixedVectorType::get(Int8Ty, 16);
11364     llvm::Type *Tys[2] = { Ty, VTy };
11365     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11366     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vminv");
11367     return Builder.CreateTrunc(Ops[0], Int8Ty);
11368   }
11369   case NEON::BI__builtin_neon_vminvq_u16: {
11370     Int = Intrinsic::aarch64_neon_uminv;
11371     Ty = Int32Ty;
11372     VTy = llvm::FixedVectorType::get(Int16Ty, 8);
11373     llvm::Type *Tys[2] = { Ty, VTy };
11374     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11375     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vminv");
11376     return Builder.CreateTrunc(Ops[0], Int16Ty);
11377   }
11378   case NEON::BI__builtin_neon_vminv_s8: {
11379     Int = Intrinsic::aarch64_neon_sminv;
11380     Ty = Int32Ty;
11381     VTy = llvm::FixedVectorType::get(Int8Ty, 8);
11382     llvm::Type *Tys[2] = { Ty, VTy };
11383     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11384     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vminv");
11385     return Builder.CreateTrunc(Ops[0], Int8Ty);
11386   }
11387   case NEON::BI__builtin_neon_vminv_s16: {
11388     Int = Intrinsic::aarch64_neon_sminv;
11389     Ty = Int32Ty;
11390     VTy = llvm::FixedVectorType::get(Int16Ty, 4);
11391     llvm::Type *Tys[2] = { Ty, VTy };
11392     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11393     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vminv");
11394     return Builder.CreateTrunc(Ops[0], Int16Ty);
11395   }
11396   case NEON::BI__builtin_neon_vminvq_s8: {
11397     Int = Intrinsic::aarch64_neon_sminv;
11398     Ty = Int32Ty;
11399     VTy = llvm::FixedVectorType::get(Int8Ty, 16);
11400     llvm::Type *Tys[2] = { Ty, VTy };
11401     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11402     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vminv");
11403     return Builder.CreateTrunc(Ops[0], Int8Ty);
11404   }
11405   case NEON::BI__builtin_neon_vminvq_s16: {
11406     Int = Intrinsic::aarch64_neon_sminv;
11407     Ty = Int32Ty;
11408     VTy = llvm::FixedVectorType::get(Int16Ty, 8);
11409     llvm::Type *Tys[2] = { Ty, VTy };
11410     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11411     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vminv");
11412     return Builder.CreateTrunc(Ops[0], Int16Ty);
11413   }
11414   case NEON::BI__builtin_neon_vminv_f16: {
11415     Int = Intrinsic::aarch64_neon_fminv;
11416     Ty = HalfTy;
11417     VTy = llvm::FixedVectorType::get(HalfTy, 4);
11418     llvm::Type *Tys[2] = { Ty, VTy };
11419     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11420     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vminv");
11421     return Builder.CreateTrunc(Ops[0], HalfTy);
11422   }
11423   case NEON::BI__builtin_neon_vminvq_f16: {
11424     Int = Intrinsic::aarch64_neon_fminv;
11425     Ty = HalfTy;
11426     VTy = llvm::FixedVectorType::get(HalfTy, 8);
11427     llvm::Type *Tys[2] = { Ty, VTy };
11428     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11429     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vminv");
11430     return Builder.CreateTrunc(Ops[0], HalfTy);
11431   }
11432   case NEON::BI__builtin_neon_vmaxnmv_f16: {
11433     Int = Intrinsic::aarch64_neon_fmaxnmv;
11434     Ty = HalfTy;
11435     VTy = llvm::FixedVectorType::get(HalfTy, 4);
11436     llvm::Type *Tys[2] = { Ty, VTy };
11437     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11438     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vmaxnmv");
11439     return Builder.CreateTrunc(Ops[0], HalfTy);
11440   }
11441   case NEON::BI__builtin_neon_vmaxnmvq_f16: {
11442     Int = Intrinsic::aarch64_neon_fmaxnmv;
11443     Ty = HalfTy;
11444     VTy = llvm::FixedVectorType::get(HalfTy, 8);
11445     llvm::Type *Tys[2] = { Ty, VTy };
11446     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11447     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vmaxnmv");
11448     return Builder.CreateTrunc(Ops[0], HalfTy);
11449   }
11450   case NEON::BI__builtin_neon_vminnmv_f16: {
11451     Int = Intrinsic::aarch64_neon_fminnmv;
11452     Ty = HalfTy;
11453     VTy = llvm::FixedVectorType::get(HalfTy, 4);
11454     llvm::Type *Tys[2] = { Ty, VTy };
11455     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11456     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vminnmv");
11457     return Builder.CreateTrunc(Ops[0], HalfTy);
11458   }
11459   case NEON::BI__builtin_neon_vminnmvq_f16: {
11460     Int = Intrinsic::aarch64_neon_fminnmv;
11461     Ty = HalfTy;
11462     VTy = llvm::FixedVectorType::get(HalfTy, 8);
11463     llvm::Type *Tys[2] = { Ty, VTy };
11464     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11465     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vminnmv");
11466     return Builder.CreateTrunc(Ops[0], HalfTy);
11467   }
11468   case NEON::BI__builtin_neon_vmul_n_f64: {
11469     Ops[0] = Builder.CreateBitCast(Ops[0], DoubleTy);
11470     Value *RHS = Builder.CreateBitCast(EmitScalarExpr(E->getArg(1)), DoubleTy);
11471     return Builder.CreateFMul(Ops[0], RHS);
11472   }
11473   case NEON::BI__builtin_neon_vaddlv_u8: {
11474     Int = Intrinsic::aarch64_neon_uaddlv;
11475     Ty = Int32Ty;
11476     VTy = llvm::FixedVectorType::get(Int8Ty, 8);
11477     llvm::Type *Tys[2] = { Ty, VTy };
11478     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11479     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vaddlv");
11480     return Builder.CreateTrunc(Ops[0], Int16Ty);
11481   }
11482   case NEON::BI__builtin_neon_vaddlv_u16: {
11483     Int = Intrinsic::aarch64_neon_uaddlv;
11484     Ty = Int32Ty;
11485     VTy = llvm::FixedVectorType::get(Int16Ty, 4);
11486     llvm::Type *Tys[2] = { Ty, VTy };
11487     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11488     return EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vaddlv");
11489   }
11490   case NEON::BI__builtin_neon_vaddlvq_u8: {
11491     Int = Intrinsic::aarch64_neon_uaddlv;
11492     Ty = Int32Ty;
11493     VTy = llvm::FixedVectorType::get(Int8Ty, 16);
11494     llvm::Type *Tys[2] = { Ty, VTy };
11495     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11496     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vaddlv");
11497     return Builder.CreateTrunc(Ops[0], Int16Ty);
11498   }
11499   case NEON::BI__builtin_neon_vaddlvq_u16: {
11500     Int = Intrinsic::aarch64_neon_uaddlv;
11501     Ty = Int32Ty;
11502     VTy = llvm::FixedVectorType::get(Int16Ty, 8);
11503     llvm::Type *Tys[2] = { Ty, VTy };
11504     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11505     return EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vaddlv");
11506   }
11507   case NEON::BI__builtin_neon_vaddlv_s8: {
11508     Int = Intrinsic::aarch64_neon_saddlv;
11509     Ty = Int32Ty;
11510     VTy = llvm::FixedVectorType::get(Int8Ty, 8);
11511     llvm::Type *Tys[2] = { Ty, VTy };
11512     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11513     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vaddlv");
11514     return Builder.CreateTrunc(Ops[0], Int16Ty);
11515   }
11516   case NEON::BI__builtin_neon_vaddlv_s16: {
11517     Int = Intrinsic::aarch64_neon_saddlv;
11518     Ty = Int32Ty;
11519     VTy = llvm::FixedVectorType::get(Int16Ty, 4);
11520     llvm::Type *Tys[2] = { Ty, VTy };
11521     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11522     return EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vaddlv");
11523   }
11524   case NEON::BI__builtin_neon_vaddlvq_s8: {
11525     Int = Intrinsic::aarch64_neon_saddlv;
11526     Ty = Int32Ty;
11527     VTy = llvm::FixedVectorType::get(Int8Ty, 16);
11528     llvm::Type *Tys[2] = { Ty, VTy };
11529     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11530     Ops[0] = EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vaddlv");
11531     return Builder.CreateTrunc(Ops[0], Int16Ty);
11532   }
11533   case NEON::BI__builtin_neon_vaddlvq_s16: {
11534     Int = Intrinsic::aarch64_neon_saddlv;
11535     Ty = Int32Ty;
11536     VTy = llvm::FixedVectorType::get(Int16Ty, 8);
11537     llvm::Type *Tys[2] = { Ty, VTy };
11538     Ops.push_back(EmitScalarExpr(E->getArg(0)));
11539     return EmitNeonCall(CGM.getIntrinsic(Int, Tys), Ops, "vaddlv");
11540   }
11541   case NEON::BI__builtin_neon_vsri_n_v:
11542   case NEON::BI__builtin_neon_vsriq_n_v: {
11543     Int = Intrinsic::aarch64_neon_vsri;
11544     llvm::Function *Intrin = CGM.getIntrinsic(Int, Ty);
11545     return EmitNeonCall(Intrin, Ops, "vsri_n");
11546   }
11547   case NEON::BI__builtin_neon_vsli_n_v:
11548   case NEON::BI__builtin_neon_vsliq_n_v: {
11549     Int = Intrinsic::aarch64_neon_vsli;
11550     llvm::Function *Intrin = CGM.getIntrinsic(Int, Ty);
11551     return EmitNeonCall(Intrin, Ops, "vsli_n");
11552   }
11553   case NEON::BI__builtin_neon_vsra_n_v:
11554   case NEON::BI__builtin_neon_vsraq_n_v:
11555     Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
11556     Ops[1] = EmitNeonRShiftImm(Ops[1], Ops[2], Ty, usgn, "vsra_n");
11557     return Builder.CreateAdd(Ops[0], Ops[1]);
11558   case NEON::BI__builtin_neon_vrsra_n_v:
11559   case NEON::BI__builtin_neon_vrsraq_n_v: {
11560     Int = usgn ? Intrinsic::aarch64_neon_urshl : Intrinsic::aarch64_neon_srshl;
11561     SmallVector<llvm::Value*,2> TmpOps;
11562     TmpOps.push_back(Ops[1]);
11563     TmpOps.push_back(Ops[2]);
11564     Function* F = CGM.getIntrinsic(Int, Ty);
11565     llvm::Value *tmp = EmitNeonCall(F, TmpOps, "vrshr_n", 1, true);
11566     Ops[0] = Builder.CreateBitCast(Ops[0], VTy);
11567     return Builder.CreateAdd(Ops[0], tmp);
11568   }
11569   case NEON::BI__builtin_neon_vld1_v:
11570   case NEON::BI__builtin_neon_vld1q_v: {
11571     Ops[0] = Builder.CreateBitCast(Ops[0], llvm::PointerType::getUnqual(VTy));
11572     return Builder.CreateAlignedLoad(VTy, Ops[0], PtrOp0.getAlignment());
11573   }
11574   case NEON::BI__builtin_neon_vst1_v:
11575   case NEON::BI__builtin_neon_vst1q_v:
11576     Ops[0] = Builder.CreateBitCast(Ops[0], llvm::PointerType::getUnqual(VTy));
11577     Ops[1] = Builder.CreateBitCast(Ops[1], VTy);
11578     return Builder.CreateAlignedStore(Ops[1], Ops[0], PtrOp0.getAlignment());
11579   case NEON::BI__builtin_neon_vld1_lane_v:
11580   case NEON::BI__builtin_neon_vld1q_lane_v: {
11581     Ops[1] = Builder.CreateBitCast(Ops[1], Ty);
11582     Ty = llvm::PointerType::getUnqual(VTy->getElementType());
11583     Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
11584     Ops[0] = Builder.CreateAlignedLoad(VTy->getElementType(), Ops[0],
11585                                        PtrOp0.getAlignment());
11586     return Builder.CreateInsertElement(Ops[1], Ops[0], Ops[2], "vld1_lane");
11587   }
11588   case NEON::BI__builtin_neon_vld1_dup_v:
11589   case NEON::BI__builtin_neon_vld1q_dup_v: {
11590     Value *V = UndefValue::get(Ty);
11591     Ty = llvm::PointerType::getUnqual(VTy->getElementType());
11592     Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
11593     Ops[0] = Builder.CreateAlignedLoad(VTy->getElementType(), Ops[0],
11594                                        PtrOp0.getAlignment());
11595     llvm::Constant *CI = ConstantInt::get(Int32Ty, 0);
11596     Ops[0] = Builder.CreateInsertElement(V, Ops[0], CI);
11597     return EmitNeonSplat(Ops[0], CI);
11598   }
11599   case NEON::BI__builtin_neon_vst1_lane_v:
11600   case NEON::BI__builtin_neon_vst1q_lane_v:
11601     Ops[1] = Builder.CreateBitCast(Ops[1], Ty);
11602     Ops[1] = Builder.CreateExtractElement(Ops[1], Ops[2]);
11603     Ty = llvm::PointerType::getUnqual(Ops[1]->getType());
11604     return Builder.CreateAlignedStore(Ops[1], Builder.CreateBitCast(Ops[0], Ty),
11605                                       PtrOp0.getAlignment());
11606   case NEON::BI__builtin_neon_vld2_v:
11607   case NEON::BI__builtin_neon_vld2q_v: {
11608     llvm::Type *PTy = llvm::PointerType::getUnqual(VTy);
11609     Ops[1] = Builder.CreateBitCast(Ops[1], PTy);
11610     llvm::Type *Tys[2] = { VTy, PTy };
11611     Function *F = CGM.getIntrinsic(Intrinsic::aarch64_neon_ld2, Tys);
11612     Ops[1] = Builder.CreateCall(F, Ops[1], "vld2");
11613     Ops[0] = Builder.CreateBitCast(Ops[0],
11614                 llvm::PointerType::getUnqual(Ops[1]->getType()));
11615     return Builder.CreateDefaultAlignedStore(Ops[1], Ops[0]);
11616   }
11617   case NEON::BI__builtin_neon_vld3_v:
11618   case NEON::BI__builtin_neon_vld3q_v: {
11619     llvm::Type *PTy = llvm::PointerType::getUnqual(VTy);
11620     Ops[1] = Builder.CreateBitCast(Ops[1], PTy);
11621     llvm::Type *Tys[2] = { VTy, PTy };
11622     Function *F = CGM.getIntrinsic(Intrinsic::aarch64_neon_ld3, Tys);
11623     Ops[1] = Builder.CreateCall(F, Ops[1], "vld3");
11624     Ops[0] = Builder.CreateBitCast(Ops[0],
11625                 llvm::PointerType::getUnqual(Ops[1]->getType()));
11626     return Builder.CreateDefaultAlignedStore(Ops[1], Ops[0]);
11627   }
11628   case NEON::BI__builtin_neon_vld4_v:
11629   case NEON::BI__builtin_neon_vld4q_v: {
11630     llvm::Type *PTy = llvm::PointerType::getUnqual(VTy);
11631     Ops[1] = Builder.CreateBitCast(Ops[1], PTy);
11632     llvm::Type *Tys[2] = { VTy, PTy };
11633     Function *F = CGM.getIntrinsic(Intrinsic::aarch64_neon_ld4, Tys);
11634     Ops[1] = Builder.CreateCall(F, Ops[1], "vld4");
11635     Ops[0] = Builder.CreateBitCast(Ops[0],
11636                 llvm::PointerType::getUnqual(Ops[1]->getType()));
11637     return Builder.CreateDefaultAlignedStore(Ops[1], Ops[0]);
11638   }
11639   case NEON::BI__builtin_neon_vld2_dup_v:
11640   case NEON::BI__builtin_neon_vld2q_dup_v: {
11641     llvm::Type *PTy =
11642       llvm::PointerType::getUnqual(VTy->getElementType());
11643     Ops[1] = Builder.CreateBitCast(Ops[1], PTy);
11644     llvm::Type *Tys[2] = { VTy, PTy };
11645     Function *F = CGM.getIntrinsic(Intrinsic::aarch64_neon_ld2r, Tys);
11646     Ops[1] = Builder.CreateCall(F, Ops[1], "vld2");
11647     Ops[0] = Builder.CreateBitCast(Ops[0],
11648                 llvm::PointerType::getUnqual(Ops[1]->getType()));
11649     return Builder.CreateDefaultAlignedStore(Ops[1], Ops[0]);
11650   }
11651   case NEON::BI__builtin_neon_vld3_dup_v:
11652   case NEON::BI__builtin_neon_vld3q_dup_v: {
11653     llvm::Type *PTy =
11654       llvm::PointerType::getUnqual(VTy->getElementType());
11655     Ops[1] = Builder.CreateBitCast(Ops[1], PTy);
11656     llvm::Type *Tys[2] = { VTy, PTy };
11657     Function *F = CGM.getIntrinsic(Intrinsic::aarch64_neon_ld3r, Tys);
11658     Ops[1] = Builder.CreateCall(F, Ops[1], "vld3");
11659     Ops[0] = Builder.CreateBitCast(Ops[0],
11660                 llvm::PointerType::getUnqual(Ops[1]->getType()));
11661     return Builder.CreateDefaultAlignedStore(Ops[1], Ops[0]);
11662   }
11663   case NEON::BI__builtin_neon_vld4_dup_v:
11664   case NEON::BI__builtin_neon_vld4q_dup_v: {
11665     llvm::Type *PTy =
11666       llvm::PointerType::getUnqual(VTy->getElementType());
11667     Ops[1] = Builder.CreateBitCast(Ops[1], PTy);
11668     llvm::Type *Tys[2] = { VTy, PTy };
11669     Function *F = CGM.getIntrinsic(Intrinsic::aarch64_neon_ld4r, Tys);
11670     Ops[1] = Builder.CreateCall(F, Ops[1], "vld4");
11671     Ops[0] = Builder.CreateBitCast(Ops[0],
11672                 llvm::PointerType::getUnqual(Ops[1]->getType()));
11673     return Builder.CreateDefaultAlignedStore(Ops[1], Ops[0]);
11674   }
11675   case NEON::BI__builtin_neon_vld2_lane_v:
11676   case NEON::BI__builtin_neon_vld2q_lane_v: {
11677     llvm::Type *Tys[2] = { VTy, Ops[1]->getType() };
11678     Function *F = CGM.getIntrinsic(Intrinsic::aarch64_neon_ld2lane, Tys);
11679     std::rotate(Ops.begin() + 1, Ops.begin() + 2, Ops.end());
11680     Ops[1] = Builder.CreateBitCast(Ops[1], Ty);
11681     Ops[2] = Builder.CreateBitCast(Ops[2], Ty);
11682     Ops[3] = Builder.CreateZExt(Ops[3], Int64Ty);
11683     Ops[1] = Builder.CreateCall(F, makeArrayRef(Ops).slice(1), "vld2_lane");
11684     Ty = llvm::PointerType::getUnqual(Ops[1]->getType());
11685     Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
11686     return Builder.CreateDefaultAlignedStore(Ops[1], Ops[0]);
11687   }
11688   case NEON::BI__builtin_neon_vld3_lane_v:
11689   case NEON::BI__builtin_neon_vld3q_lane_v: {
11690     llvm::Type *Tys[2] = { VTy, Ops[1]->getType() };
11691     Function *F = CGM.getIntrinsic(Intrinsic::aarch64_neon_ld3lane, Tys);
11692     std::rotate(Ops.begin() + 1, Ops.begin() + 2, Ops.end());
11693     Ops[1] = Builder.CreateBitCast(Ops[1], Ty);
11694     Ops[2] = Builder.CreateBitCast(Ops[2], Ty);
11695     Ops[3] = Builder.CreateBitCast(Ops[3], Ty);
11696     Ops[4] = Builder.CreateZExt(Ops[4], Int64Ty);
11697     Ops[1] = Builder.CreateCall(F, makeArrayRef(Ops).slice(1), "vld3_lane");
11698     Ty = llvm::PointerType::getUnqual(Ops[1]->getType());
11699     Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
11700     return Builder.CreateDefaultAlignedStore(Ops[1], Ops[0]);
11701   }
11702   case NEON::BI__builtin_neon_vld4_lane_v:
11703   case NEON::BI__builtin_neon_vld4q_lane_v: {
11704     llvm::Type *Tys[2] = { VTy, Ops[1]->getType() };
11705     Function *F = CGM.getIntrinsic(Intrinsic::aarch64_neon_ld4lane, Tys);
11706     std::rotate(Ops.begin() + 1, Ops.begin() + 2, Ops.end());
11707     Ops[1] = Builder.CreateBitCast(Ops[1], Ty);
11708     Ops[2] = Builder.CreateBitCast(Ops[2], Ty);
11709     Ops[3] = Builder.CreateBitCast(Ops[3], Ty);
11710     Ops[4] = Builder.CreateBitCast(Ops[4], Ty);
11711     Ops[5] = Builder.CreateZExt(Ops[5], Int64Ty);
11712     Ops[1] = Builder.CreateCall(F, makeArrayRef(Ops).slice(1), "vld4_lane");
11713     Ty = llvm::PointerType::getUnqual(Ops[1]->getType());
11714     Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
11715     return Builder.CreateDefaultAlignedStore(Ops[1], Ops[0]);
11716   }
11717   case NEON::BI__builtin_neon_vst2_v:
11718   case NEON::BI__builtin_neon_vst2q_v: {
11719     std::rotate(Ops.begin(), Ops.begin() + 1, Ops.end());
11720     llvm::Type *Tys[2] = { VTy, Ops[2]->getType() };
11721     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::aarch64_neon_st2, Tys),
11722                         Ops, "");
11723   }
11724   case NEON::BI__builtin_neon_vst2_lane_v:
11725   case NEON::BI__builtin_neon_vst2q_lane_v: {
11726     std::rotate(Ops.begin(), Ops.begin() + 1, Ops.end());
11727     Ops[2] = Builder.CreateZExt(Ops[2], Int64Ty);
11728     llvm::Type *Tys[2] = { VTy, Ops[3]->getType() };
11729     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::aarch64_neon_st2lane, Tys),
11730                         Ops, "");
11731   }
11732   case NEON::BI__builtin_neon_vst3_v:
11733   case NEON::BI__builtin_neon_vst3q_v: {
11734     std::rotate(Ops.begin(), Ops.begin() + 1, Ops.end());
11735     llvm::Type *Tys[2] = { VTy, Ops[3]->getType() };
11736     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::aarch64_neon_st3, Tys),
11737                         Ops, "");
11738   }
11739   case NEON::BI__builtin_neon_vst3_lane_v:
11740   case NEON::BI__builtin_neon_vst3q_lane_v: {
11741     std::rotate(Ops.begin(), Ops.begin() + 1, Ops.end());
11742     Ops[3] = Builder.CreateZExt(Ops[3], Int64Ty);
11743     llvm::Type *Tys[2] = { VTy, Ops[4]->getType() };
11744     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::aarch64_neon_st3lane, Tys),
11745                         Ops, "");
11746   }
11747   case NEON::BI__builtin_neon_vst4_v:
11748   case NEON::BI__builtin_neon_vst4q_v: {
11749     std::rotate(Ops.begin(), Ops.begin() + 1, Ops.end());
11750     llvm::Type *Tys[2] = { VTy, Ops[4]->getType() };
11751     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::aarch64_neon_st4, Tys),
11752                         Ops, "");
11753   }
11754   case NEON::BI__builtin_neon_vst4_lane_v:
11755   case NEON::BI__builtin_neon_vst4q_lane_v: {
11756     std::rotate(Ops.begin(), Ops.begin() + 1, Ops.end());
11757     Ops[4] = Builder.CreateZExt(Ops[4], Int64Ty);
11758     llvm::Type *Tys[2] = { VTy, Ops[5]->getType() };
11759     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::aarch64_neon_st4lane, Tys),
11760                         Ops, "");
11761   }
11762   case NEON::BI__builtin_neon_vtrn_v:
11763   case NEON::BI__builtin_neon_vtrnq_v: {
11764     Ops[0] = Builder.CreateBitCast(Ops[0], llvm::PointerType::getUnqual(Ty));
11765     Ops[1] = Builder.CreateBitCast(Ops[1], Ty);
11766     Ops[2] = Builder.CreateBitCast(Ops[2], Ty);
11767     Value *SV = nullptr;
11768 
11769     for (unsigned vi = 0; vi != 2; ++vi) {
11770       SmallVector<int, 16> Indices;
11771       for (unsigned i = 0, e = VTy->getNumElements(); i != e; i += 2) {
11772         Indices.push_back(i+vi);
11773         Indices.push_back(i+e+vi);
11774       }
11775       Value *Addr = Builder.CreateConstInBoundsGEP1_32(Ty, Ops[0], vi);
11776       SV = Builder.CreateShuffleVector(Ops[1], Ops[2], Indices, "vtrn");
11777       SV = Builder.CreateDefaultAlignedStore(SV, Addr);
11778     }
11779     return SV;
11780   }
11781   case NEON::BI__builtin_neon_vuzp_v:
11782   case NEON::BI__builtin_neon_vuzpq_v: {
11783     Ops[0] = Builder.CreateBitCast(Ops[0], llvm::PointerType::getUnqual(Ty));
11784     Ops[1] = Builder.CreateBitCast(Ops[1], Ty);
11785     Ops[2] = Builder.CreateBitCast(Ops[2], Ty);
11786     Value *SV = nullptr;
11787 
11788     for (unsigned vi = 0; vi != 2; ++vi) {
11789       SmallVector<int, 16> Indices;
11790       for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i)
11791         Indices.push_back(2*i+vi);
11792 
11793       Value *Addr = Builder.CreateConstInBoundsGEP1_32(Ty, Ops[0], vi);
11794       SV = Builder.CreateShuffleVector(Ops[1], Ops[2], Indices, "vuzp");
11795       SV = Builder.CreateDefaultAlignedStore(SV, Addr);
11796     }
11797     return SV;
11798   }
11799   case NEON::BI__builtin_neon_vzip_v:
11800   case NEON::BI__builtin_neon_vzipq_v: {
11801     Ops[0] = Builder.CreateBitCast(Ops[0], llvm::PointerType::getUnqual(Ty));
11802     Ops[1] = Builder.CreateBitCast(Ops[1], Ty);
11803     Ops[2] = Builder.CreateBitCast(Ops[2], Ty);
11804     Value *SV = nullptr;
11805 
11806     for (unsigned vi = 0; vi != 2; ++vi) {
11807       SmallVector<int, 16> Indices;
11808       for (unsigned i = 0, e = VTy->getNumElements(); i != e; i += 2) {
11809         Indices.push_back((i + vi*e) >> 1);
11810         Indices.push_back(((i + vi*e) >> 1)+e);
11811       }
11812       Value *Addr = Builder.CreateConstInBoundsGEP1_32(Ty, Ops[0], vi);
11813       SV = Builder.CreateShuffleVector(Ops[1], Ops[2], Indices, "vzip");
11814       SV = Builder.CreateDefaultAlignedStore(SV, Addr);
11815     }
11816     return SV;
11817   }
11818   case NEON::BI__builtin_neon_vqtbl1q_v: {
11819     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::aarch64_neon_tbl1, Ty),
11820                         Ops, "vtbl1");
11821   }
11822   case NEON::BI__builtin_neon_vqtbl2q_v: {
11823     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::aarch64_neon_tbl2, Ty),
11824                         Ops, "vtbl2");
11825   }
11826   case NEON::BI__builtin_neon_vqtbl3q_v: {
11827     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::aarch64_neon_tbl3, Ty),
11828                         Ops, "vtbl3");
11829   }
11830   case NEON::BI__builtin_neon_vqtbl4q_v: {
11831     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::aarch64_neon_tbl4, Ty),
11832                         Ops, "vtbl4");
11833   }
11834   case NEON::BI__builtin_neon_vqtbx1q_v: {
11835     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::aarch64_neon_tbx1, Ty),
11836                         Ops, "vtbx1");
11837   }
11838   case NEON::BI__builtin_neon_vqtbx2q_v: {
11839     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::aarch64_neon_tbx2, Ty),
11840                         Ops, "vtbx2");
11841   }
11842   case NEON::BI__builtin_neon_vqtbx3q_v: {
11843     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::aarch64_neon_tbx3, Ty),
11844                         Ops, "vtbx3");
11845   }
11846   case NEON::BI__builtin_neon_vqtbx4q_v: {
11847     return EmitNeonCall(CGM.getIntrinsic(Intrinsic::aarch64_neon_tbx4, Ty),
11848                         Ops, "vtbx4");
11849   }
11850   case NEON::BI__builtin_neon_vsqadd_v:
11851   case NEON::BI__builtin_neon_vsqaddq_v: {
11852     Int = Intrinsic::aarch64_neon_usqadd;
11853     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vsqadd");
11854   }
11855   case NEON::BI__builtin_neon_vuqadd_v:
11856   case NEON::BI__builtin_neon_vuqaddq_v: {
11857     Int = Intrinsic::aarch64_neon_suqadd;
11858     return EmitNeonCall(CGM.getIntrinsic(Int, Ty), Ops, "vuqadd");
11859   }
11860   }
11861 }
11862 
11863 Value *CodeGenFunction::EmitBPFBuiltinExpr(unsigned BuiltinID,
11864                                            const CallExpr *E) {
11865   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
11866           BuiltinID == BPF::BI__builtin_btf_type_id ||
11867           BuiltinID == BPF::BI__builtin_preserve_type_info ||
11868           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
11869          "unexpected BPF builtin");
11870 
11871   // A sequence number, injected into IR builtin functions, to
11872   // prevent CSE given the only difference of the funciton
11873   // may just be the debuginfo metadata.
11874   static uint32_t BuiltinSeqNum;
11875 
11876   switch (BuiltinID) {
11877   default:
11878     llvm_unreachable("Unexpected BPF builtin");
11879   case BPF::BI__builtin_preserve_field_info: {
11880     const Expr *Arg = E->getArg(0);
11881     bool IsBitField = Arg->IgnoreParens()->getObjectKind() == OK_BitField;
11882 
11883     if (!getDebugInfo()) {
11884       CGM.Error(E->getExprLoc(),
11885                 "using __builtin_preserve_field_info() without -g");
11886       return IsBitField ? EmitLValue(Arg).getBitFieldPointer()
11887                         : EmitLValue(Arg).getPointer(*this);
11888     }
11889 
11890     // Enable underlying preserve_*_access_index() generation.
11891     bool OldIsInPreservedAIRegion = IsInPreservedAIRegion;
11892     IsInPreservedAIRegion = true;
11893     Value *FieldAddr = IsBitField ? EmitLValue(Arg).getBitFieldPointer()
11894                                   : EmitLValue(Arg).getPointer(*this);
11895     IsInPreservedAIRegion = OldIsInPreservedAIRegion;
11896 
11897     ConstantInt *C = cast<ConstantInt>(EmitScalarExpr(E->getArg(1)));
11898     Value *InfoKind = ConstantInt::get(Int64Ty, C->getSExtValue());
11899 
11900     // Built the IR for the preserve_field_info intrinsic.
11901     llvm::Function *FnGetFieldInfo = llvm::Intrinsic::getDeclaration(
11902         &CGM.getModule(), llvm::Intrinsic::bpf_preserve_field_info,
11903         {FieldAddr->getType()});
11904     return Builder.CreateCall(FnGetFieldInfo, {FieldAddr, InfoKind});
11905   }
11906   case BPF::BI__builtin_btf_type_id:
11907   case BPF::BI__builtin_preserve_type_info: {
11908     if (!getDebugInfo()) {
11909       CGM.Error(E->getExprLoc(), "using builtin function without -g");
11910       return nullptr;
11911     }
11912 
11913     const Expr *Arg0 = E->getArg(0);
11914     llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateStandaloneType(
11915         Arg0->getType(), Arg0->getExprLoc());
11916 
11917     ConstantInt *Flag = cast<ConstantInt>(EmitScalarExpr(E->getArg(1)));
11918     Value *FlagValue = ConstantInt::get(Int64Ty, Flag->getSExtValue());
11919     Value *SeqNumVal = ConstantInt::get(Int32Ty, BuiltinSeqNum++);
11920 
11921     llvm::Function *FnDecl;
11922     if (BuiltinID == BPF::BI__builtin_btf_type_id)
11923       FnDecl = llvm::Intrinsic::getDeclaration(
11924           &CGM.getModule(), llvm::Intrinsic::bpf_btf_type_id, {});
11925     else
11926       FnDecl = llvm::Intrinsic::getDeclaration(
11927           &CGM.getModule(), llvm::Intrinsic::bpf_preserve_type_info, {});
11928     CallInst *Fn = Builder.CreateCall(FnDecl, {SeqNumVal, FlagValue});
11929     Fn->setMetadata(LLVMContext::MD_preserve_access_index, DbgInfo);
11930     return Fn;
11931   }
11932   case BPF::BI__builtin_preserve_enum_value: {
11933     if (!getDebugInfo()) {
11934       CGM.Error(E->getExprLoc(), "using builtin function without -g");
11935       return nullptr;
11936     }
11937 
11938     const Expr *Arg0 = E->getArg(0);
11939     llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateStandaloneType(
11940         Arg0->getType(), Arg0->getExprLoc());
11941 
11942     // Find enumerator
11943     const auto *UO = cast<UnaryOperator>(Arg0->IgnoreParens());
11944     const auto *CE = cast<CStyleCastExpr>(UO->getSubExpr());
11945     const auto *DR = cast<DeclRefExpr>(CE->getSubExpr());
11946     const auto *Enumerator = cast<EnumConstantDecl>(DR->getDecl());
11947 
11948     auto &InitVal = Enumerator->getInitVal();
11949     std::string InitValStr;
11950     if (InitVal.isNegative() || InitVal > uint64_t(INT64_MAX))
11951       InitValStr = std::to_string(InitVal.getSExtValue());
11952     else
11953       InitValStr = std::to_string(InitVal.getZExtValue());
11954     std::string EnumStr = Enumerator->getNameAsString() + ":" + InitValStr;
11955     Value *EnumStrVal = Builder.CreateGlobalStringPtr(EnumStr);
11956 
11957     ConstantInt *Flag = cast<ConstantInt>(EmitScalarExpr(E->getArg(1)));
11958     Value *FlagValue = ConstantInt::get(Int64Ty, Flag->getSExtValue());
11959     Value *SeqNumVal = ConstantInt::get(Int32Ty, BuiltinSeqNum++);
11960 
11961     llvm::Function *IntrinsicFn = llvm::Intrinsic::getDeclaration(
11962         &CGM.getModule(), llvm::Intrinsic::bpf_preserve_enum_value, {});
11963     CallInst *Fn =
11964         Builder.CreateCall(IntrinsicFn, {SeqNumVal, EnumStrVal, FlagValue});
11965     Fn->setMetadata(LLVMContext::MD_preserve_access_index, DbgInfo);
11966     return Fn;
11967   }
11968   }
11969 }
11970 
11971 llvm::Value *CodeGenFunction::
11972 BuildVector(ArrayRef<llvm::Value*> Ops) {
11973   assert((Ops.size() & (Ops.size() - 1)) == 0 &&
11974          "Not a power-of-two sized vector!");
11975   bool AllConstants = true;
11976   for (unsigned i = 0, e = Ops.size(); i != e && AllConstants; ++i)
11977     AllConstants &= isa<Constant>(Ops[i]);
11978 
11979   // If this is a constant vector, create a ConstantVector.
11980   if (AllConstants) {
11981     SmallVector<llvm::Constant*, 16> CstOps;
11982     for (unsigned i = 0, e = Ops.size(); i != e; ++i)
11983       CstOps.push_back(cast<Constant>(Ops[i]));
11984     return llvm::ConstantVector::get(CstOps);
11985   }
11986 
11987   // Otherwise, insertelement the values to build the vector.
11988   Value *Result = llvm::UndefValue::get(
11989       llvm::FixedVectorType::get(Ops[0]->getType(), Ops.size()));
11990 
11991   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
11992     Result = Builder.CreateInsertElement(Result, Ops[i], Builder.getInt32(i));
11993 
11994   return Result;
11995 }
11996 
11997 // Convert the mask from an integer type to a vector of i1.
11998 static Value *getMaskVecValue(CodeGenFunction &CGF, Value *Mask,
11999                               unsigned NumElts) {
12000 
12001   auto *MaskTy = llvm::FixedVectorType::get(
12002       CGF.Builder.getInt1Ty(),
12003       cast<IntegerType>(Mask->getType())->getBitWidth());
12004   Value *MaskVec = CGF.Builder.CreateBitCast(Mask, MaskTy);
12005 
12006   // If we have less than 8 elements, then the starting mask was an i8 and
12007   // we need to extract down to the right number of elements.
12008   if (NumElts < 8) {
12009     int Indices[4];
12010     for (unsigned i = 0; i != NumElts; ++i)
12011       Indices[i] = i;
12012     MaskVec = CGF.Builder.CreateShuffleVector(MaskVec, MaskVec,
12013                                              makeArrayRef(Indices, NumElts),
12014                                              "extract");
12015   }
12016   return MaskVec;
12017 }
12018 
12019 static Value *EmitX86MaskedStore(CodeGenFunction &CGF, ArrayRef<Value *> Ops,
12020                                  Align Alignment) {
12021   // Cast the pointer to right type.
12022   Value *Ptr = CGF.Builder.CreateBitCast(Ops[0],
12023                                llvm::PointerType::getUnqual(Ops[1]->getType()));
12024 
12025   Value *MaskVec = getMaskVecValue(
12026       CGF, Ops[2],
12027       cast<llvm::FixedVectorType>(Ops[1]->getType())->getNumElements());
12028 
12029   return CGF.Builder.CreateMaskedStore(Ops[1], Ptr, Alignment, MaskVec);
12030 }
12031 
12032 static Value *EmitX86MaskedLoad(CodeGenFunction &CGF, ArrayRef<Value *> Ops,
12033                                 Align Alignment) {
12034   // Cast the pointer to right type.
12035   llvm::Type *Ty = Ops[1]->getType();
12036   Value *Ptr =
12037       CGF.Builder.CreateBitCast(Ops[0], llvm::PointerType::getUnqual(Ty));
12038 
12039   Value *MaskVec = getMaskVecValue(
12040       CGF, Ops[2], cast<llvm::FixedVectorType>(Ty)->getNumElements());
12041 
12042   return CGF.Builder.CreateMaskedLoad(Ty, Ptr, Alignment, MaskVec, Ops[1]);
12043 }
12044 
12045 static Value *EmitX86ExpandLoad(CodeGenFunction &CGF,
12046                                 ArrayRef<Value *> Ops) {
12047   auto *ResultTy = cast<llvm::VectorType>(Ops[1]->getType());
12048   llvm::Type *PtrTy = ResultTy->getElementType();
12049 
12050   // Cast the pointer to element type.
12051   Value *Ptr = CGF.Builder.CreateBitCast(Ops[0],
12052                                          llvm::PointerType::getUnqual(PtrTy));
12053 
12054   Value *MaskVec = getMaskVecValue(
12055       CGF, Ops[2], cast<FixedVectorType>(ResultTy)->getNumElements());
12056 
12057   llvm::Function *F = CGF.CGM.getIntrinsic(Intrinsic::masked_expandload,
12058                                            ResultTy);
12059   return CGF.Builder.CreateCall(F, { Ptr, MaskVec, Ops[1] });
12060 }
12061 
12062 static Value *EmitX86CompressExpand(CodeGenFunction &CGF,
12063                                     ArrayRef<Value *> Ops,
12064                                     bool IsCompress) {
12065   auto *ResultTy = cast<llvm::FixedVectorType>(Ops[1]->getType());
12066 
12067   Value *MaskVec = getMaskVecValue(CGF, Ops[2], ResultTy->getNumElements());
12068 
12069   Intrinsic::ID IID = IsCompress ? Intrinsic::x86_avx512_mask_compress
12070                                  : Intrinsic::x86_avx512_mask_expand;
12071   llvm::Function *F = CGF.CGM.getIntrinsic(IID, ResultTy);
12072   return CGF.Builder.CreateCall(F, { Ops[0], Ops[1], MaskVec });
12073 }
12074 
12075 static Value *EmitX86CompressStore(CodeGenFunction &CGF,
12076                                    ArrayRef<Value *> Ops) {
12077   auto *ResultTy = cast<llvm::FixedVectorType>(Ops[1]->getType());
12078   llvm::Type *PtrTy = ResultTy->getElementType();
12079 
12080   // Cast the pointer to element type.
12081   Value *Ptr = CGF.Builder.CreateBitCast(Ops[0],
12082                                          llvm::PointerType::getUnqual(PtrTy));
12083 
12084   Value *MaskVec = getMaskVecValue(CGF, Ops[2], ResultTy->getNumElements());
12085 
12086   llvm::Function *F = CGF.CGM.getIntrinsic(Intrinsic::masked_compressstore,
12087                                            ResultTy);
12088   return CGF.Builder.CreateCall(F, { Ops[1], Ptr, MaskVec });
12089 }
12090 
12091 static Value *EmitX86MaskLogic(CodeGenFunction &CGF, Instruction::BinaryOps Opc,
12092                               ArrayRef<Value *> Ops,
12093                               bool InvertLHS = false) {
12094   unsigned NumElts = Ops[0]->getType()->getIntegerBitWidth();
12095   Value *LHS = getMaskVecValue(CGF, Ops[0], NumElts);
12096   Value *RHS = getMaskVecValue(CGF, Ops[1], NumElts);
12097 
12098   if (InvertLHS)
12099     LHS = CGF.Builder.CreateNot(LHS);
12100 
12101   return CGF.Builder.CreateBitCast(CGF.Builder.CreateBinOp(Opc, LHS, RHS),
12102                                    Ops[0]->getType());
12103 }
12104 
12105 static Value *EmitX86FunnelShift(CodeGenFunction &CGF, Value *Op0, Value *Op1,
12106                                  Value *Amt, bool IsRight) {
12107   llvm::Type *Ty = Op0->getType();
12108 
12109   // Amount may be scalar immediate, in which case create a splat vector.
12110   // Funnel shifts amounts are treated as modulo and types are all power-of-2 so
12111   // we only care about the lowest log2 bits anyway.
12112   if (Amt->getType() != Ty) {
12113     unsigned NumElts = cast<llvm::FixedVectorType>(Ty)->getNumElements();
12114     Amt = CGF.Builder.CreateIntCast(Amt, Ty->getScalarType(), false);
12115     Amt = CGF.Builder.CreateVectorSplat(NumElts, Amt);
12116   }
12117 
12118   unsigned IID = IsRight ? Intrinsic::fshr : Intrinsic::fshl;
12119   Function *F = CGF.CGM.getIntrinsic(IID, Ty);
12120   return CGF.Builder.CreateCall(F, {Op0, Op1, Amt});
12121 }
12122 
12123 static Value *EmitX86vpcom(CodeGenFunction &CGF, ArrayRef<Value *> Ops,
12124                            bool IsSigned) {
12125   Value *Op0 = Ops[0];
12126   Value *Op1 = Ops[1];
12127   llvm::Type *Ty = Op0->getType();
12128   uint64_t Imm = cast<llvm::ConstantInt>(Ops[2])->getZExtValue() & 0x7;
12129 
12130   CmpInst::Predicate Pred;
12131   switch (Imm) {
12132   case 0x0:
12133     Pred = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
12134     break;
12135   case 0x1:
12136     Pred = IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
12137     break;
12138   case 0x2:
12139     Pred = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
12140     break;
12141   case 0x3:
12142     Pred = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
12143     break;
12144   case 0x4:
12145     Pred = ICmpInst::ICMP_EQ;
12146     break;
12147   case 0x5:
12148     Pred = ICmpInst::ICMP_NE;
12149     break;
12150   case 0x6:
12151     return llvm::Constant::getNullValue(Ty); // FALSE
12152   case 0x7:
12153     return llvm::Constant::getAllOnesValue(Ty); // TRUE
12154   default:
12155     llvm_unreachable("Unexpected XOP vpcom/vpcomu predicate");
12156   }
12157 
12158   Value *Cmp = CGF.Builder.CreateICmp(Pred, Op0, Op1);
12159   Value *Res = CGF.Builder.CreateSExt(Cmp, Ty);
12160   return Res;
12161 }
12162 
12163 static Value *EmitX86Select(CodeGenFunction &CGF,
12164                             Value *Mask, Value *Op0, Value *Op1) {
12165 
12166   // If the mask is all ones just return first argument.
12167   if (const auto *C = dyn_cast<Constant>(Mask))
12168     if (C->isAllOnesValue())
12169       return Op0;
12170 
12171   Mask = getMaskVecValue(
12172       CGF, Mask, cast<llvm::FixedVectorType>(Op0->getType())->getNumElements());
12173 
12174   return CGF.Builder.CreateSelect(Mask, Op0, Op1);
12175 }
12176 
12177 static Value *EmitX86ScalarSelect(CodeGenFunction &CGF,
12178                                   Value *Mask, Value *Op0, Value *Op1) {
12179   // If the mask is all ones just return first argument.
12180   if (const auto *C = dyn_cast<Constant>(Mask))
12181     if (C->isAllOnesValue())
12182       return Op0;
12183 
12184   auto *MaskTy = llvm::FixedVectorType::get(
12185       CGF.Builder.getInt1Ty(), Mask->getType()->getIntegerBitWidth());
12186   Mask = CGF.Builder.CreateBitCast(Mask, MaskTy);
12187   Mask = CGF.Builder.CreateExtractElement(Mask, (uint64_t)0);
12188   return CGF.Builder.CreateSelect(Mask, Op0, Op1);
12189 }
12190 
12191 static Value *EmitX86MaskedCompareResult(CodeGenFunction &CGF, Value *Cmp,
12192                                          unsigned NumElts, Value *MaskIn) {
12193   if (MaskIn) {
12194     const auto *C = dyn_cast<Constant>(MaskIn);
12195     if (!C || !C->isAllOnesValue())
12196       Cmp = CGF.Builder.CreateAnd(Cmp, getMaskVecValue(CGF, MaskIn, NumElts));
12197   }
12198 
12199   if (NumElts < 8) {
12200     int Indices[8];
12201     for (unsigned i = 0; i != NumElts; ++i)
12202       Indices[i] = i;
12203     for (unsigned i = NumElts; i != 8; ++i)
12204       Indices[i] = i % NumElts + NumElts;
12205     Cmp = CGF.Builder.CreateShuffleVector(
12206         Cmp, llvm::Constant::getNullValue(Cmp->getType()), Indices);
12207   }
12208 
12209   return CGF.Builder.CreateBitCast(Cmp,
12210                                    IntegerType::get(CGF.getLLVMContext(),
12211                                                     std::max(NumElts, 8U)));
12212 }
12213 
12214 static Value *EmitX86MaskedCompare(CodeGenFunction &CGF, unsigned CC,
12215                                    bool Signed, ArrayRef<Value *> Ops) {
12216   assert((Ops.size() == 2 || Ops.size() == 4) &&
12217          "Unexpected number of arguments");
12218   unsigned NumElts =
12219       cast<llvm::FixedVectorType>(Ops[0]->getType())->getNumElements();
12220   Value *Cmp;
12221 
12222   if (CC == 3) {
12223     Cmp = Constant::getNullValue(
12224         llvm::FixedVectorType::get(CGF.Builder.getInt1Ty(), NumElts));
12225   } else if (CC == 7) {
12226     Cmp = Constant::getAllOnesValue(
12227         llvm::FixedVectorType::get(CGF.Builder.getInt1Ty(), NumElts));
12228   } else {
12229     ICmpInst::Predicate Pred;
12230     switch (CC) {
12231     default: llvm_unreachable("Unknown condition code");
12232     case 0: Pred = ICmpInst::ICMP_EQ;  break;
12233     case 1: Pred = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; break;
12234     case 2: Pred = Signed ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; break;
12235     case 4: Pred = ICmpInst::ICMP_NE;  break;
12236     case 5: Pred = Signed ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; break;
12237     case 6: Pred = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; break;
12238     }
12239     Cmp = CGF.Builder.CreateICmp(Pred, Ops[0], Ops[1]);
12240   }
12241 
12242   Value *MaskIn = nullptr;
12243   if (Ops.size() == 4)
12244     MaskIn = Ops[3];
12245 
12246   return EmitX86MaskedCompareResult(CGF, Cmp, NumElts, MaskIn);
12247 }
12248 
12249 static Value *EmitX86ConvertToMask(CodeGenFunction &CGF, Value *In) {
12250   Value *Zero = Constant::getNullValue(In->getType());
12251   return EmitX86MaskedCompare(CGF, 1, true, { In, Zero });
12252 }
12253 
12254 static Value *EmitX86ConvertIntToFp(CodeGenFunction &CGF, const CallExpr *E,
12255                                     ArrayRef<Value *> Ops, bool IsSigned) {
12256   unsigned Rnd = cast<llvm::ConstantInt>(Ops[3])->getZExtValue();
12257   llvm::Type *Ty = Ops[1]->getType();
12258 
12259   Value *Res;
12260   if (Rnd != 4) {
12261     Intrinsic::ID IID = IsSigned ? Intrinsic::x86_avx512_sitofp_round
12262                                  : Intrinsic::x86_avx512_uitofp_round;
12263     Function *F = CGF.CGM.getIntrinsic(IID, { Ty, Ops[0]->getType() });
12264     Res = CGF.Builder.CreateCall(F, { Ops[0], Ops[3] });
12265   } else {
12266     CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
12267     Res = IsSigned ? CGF.Builder.CreateSIToFP(Ops[0], Ty)
12268                    : CGF.Builder.CreateUIToFP(Ops[0], Ty);
12269   }
12270 
12271   return EmitX86Select(CGF, Ops[2], Res, Ops[1]);
12272 }
12273 
12274 // Lowers X86 FMA intrinsics to IR.
12275 static Value *EmitX86FMAExpr(CodeGenFunction &CGF, const CallExpr *E,
12276                              ArrayRef<Value *> Ops, unsigned BuiltinID,
12277                              bool IsAddSub) {
12278 
12279   bool Subtract = false;
12280   Intrinsic::ID IID = Intrinsic::not_intrinsic;
12281   switch (BuiltinID) {
12282   default: break;
12283   case clang::X86::BI__builtin_ia32_vfmsubph512_mask3:
12284     Subtract = true;
12285     LLVM_FALLTHROUGH;
12286   case clang::X86::BI__builtin_ia32_vfmaddph512_mask:
12287   case clang::X86::BI__builtin_ia32_vfmaddph512_maskz:
12288   case clang::X86::BI__builtin_ia32_vfmaddph512_mask3:
12289     IID = llvm::Intrinsic::x86_avx512fp16_vfmadd_ph_512;
12290     break;
12291   case clang::X86::BI__builtin_ia32_vfmsubaddph512_mask3:
12292     Subtract = true;
12293     LLVM_FALLTHROUGH;
12294   case clang::X86::BI__builtin_ia32_vfmaddsubph512_mask:
12295   case clang::X86::BI__builtin_ia32_vfmaddsubph512_maskz:
12296   case clang::X86::BI__builtin_ia32_vfmaddsubph512_mask3:
12297     IID = llvm::Intrinsic::x86_avx512fp16_vfmaddsub_ph_512;
12298     break;
12299   case clang::X86::BI__builtin_ia32_vfmsubps512_mask3:
12300     Subtract = true;
12301     LLVM_FALLTHROUGH;
12302   case clang::X86::BI__builtin_ia32_vfmaddps512_mask:
12303   case clang::X86::BI__builtin_ia32_vfmaddps512_maskz:
12304   case clang::X86::BI__builtin_ia32_vfmaddps512_mask3:
12305     IID = llvm::Intrinsic::x86_avx512_vfmadd_ps_512; break;
12306   case clang::X86::BI__builtin_ia32_vfmsubpd512_mask3:
12307     Subtract = true;
12308     LLVM_FALLTHROUGH;
12309   case clang::X86::BI__builtin_ia32_vfmaddpd512_mask:
12310   case clang::X86::BI__builtin_ia32_vfmaddpd512_maskz:
12311   case clang::X86::BI__builtin_ia32_vfmaddpd512_mask3:
12312     IID = llvm::Intrinsic::x86_avx512_vfmadd_pd_512; break;
12313   case clang::X86::BI__builtin_ia32_vfmsubaddps512_mask3:
12314     Subtract = true;
12315     LLVM_FALLTHROUGH;
12316   case clang::X86::BI__builtin_ia32_vfmaddsubps512_mask:
12317   case clang::X86::BI__builtin_ia32_vfmaddsubps512_maskz:
12318   case clang::X86::BI__builtin_ia32_vfmaddsubps512_mask3:
12319     IID = llvm::Intrinsic::x86_avx512_vfmaddsub_ps_512;
12320     break;
12321   case clang::X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
12322     Subtract = true;
12323     LLVM_FALLTHROUGH;
12324   case clang::X86::BI__builtin_ia32_vfmaddsubpd512_mask:
12325   case clang::X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
12326   case clang::X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
12327     IID = llvm::Intrinsic::x86_avx512_vfmaddsub_pd_512;
12328     break;
12329   }
12330 
12331   Value *A = Ops[0];
12332   Value *B = Ops[1];
12333   Value *C = Ops[2];
12334 
12335   if (Subtract)
12336     C = CGF.Builder.CreateFNeg(C);
12337 
12338   Value *Res;
12339 
12340   // Only handle in case of _MM_FROUND_CUR_DIRECTION/4 (no rounding).
12341   if (IID != Intrinsic::not_intrinsic &&
12342       (cast<llvm::ConstantInt>(Ops.back())->getZExtValue() != (uint64_t)4 ||
12343        IsAddSub)) {
12344     Function *Intr = CGF.CGM.getIntrinsic(IID);
12345     Res = CGF.Builder.CreateCall(Intr, {A, B, C, Ops.back() });
12346   } else {
12347     llvm::Type *Ty = A->getType();
12348     Function *FMA;
12349     if (CGF.Builder.getIsFPConstrained()) {
12350       CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
12351       FMA = CGF.CGM.getIntrinsic(Intrinsic::experimental_constrained_fma, Ty);
12352       Res = CGF.Builder.CreateConstrainedFPCall(FMA, {A, B, C});
12353     } else {
12354       FMA = CGF.CGM.getIntrinsic(Intrinsic::fma, Ty);
12355       Res = CGF.Builder.CreateCall(FMA, {A, B, C});
12356     }
12357   }
12358 
12359   // Handle any required masking.
12360   Value *MaskFalseVal = nullptr;
12361   switch (BuiltinID) {
12362   case clang::X86::BI__builtin_ia32_vfmaddph512_mask:
12363   case clang::X86::BI__builtin_ia32_vfmaddps512_mask:
12364   case clang::X86::BI__builtin_ia32_vfmaddpd512_mask:
12365   case clang::X86::BI__builtin_ia32_vfmaddsubph512_mask:
12366   case clang::X86::BI__builtin_ia32_vfmaddsubps512_mask:
12367   case clang::X86::BI__builtin_ia32_vfmaddsubpd512_mask:
12368     MaskFalseVal = Ops[0];
12369     break;
12370   case clang::X86::BI__builtin_ia32_vfmaddph512_maskz:
12371   case clang::X86::BI__builtin_ia32_vfmaddps512_maskz:
12372   case clang::X86::BI__builtin_ia32_vfmaddpd512_maskz:
12373   case clang::X86::BI__builtin_ia32_vfmaddsubph512_maskz:
12374   case clang::X86::BI__builtin_ia32_vfmaddsubps512_maskz:
12375   case clang::X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
12376     MaskFalseVal = Constant::getNullValue(Ops[0]->getType());
12377     break;
12378   case clang::X86::BI__builtin_ia32_vfmsubph512_mask3:
12379   case clang::X86::BI__builtin_ia32_vfmaddph512_mask3:
12380   case clang::X86::BI__builtin_ia32_vfmsubps512_mask3:
12381   case clang::X86::BI__builtin_ia32_vfmaddps512_mask3:
12382   case clang::X86::BI__builtin_ia32_vfmsubpd512_mask3:
12383   case clang::X86::BI__builtin_ia32_vfmaddpd512_mask3:
12384   case clang::X86::BI__builtin_ia32_vfmsubaddph512_mask3:
12385   case clang::X86::BI__builtin_ia32_vfmaddsubph512_mask3:
12386   case clang::X86::BI__builtin_ia32_vfmsubaddps512_mask3:
12387   case clang::X86::BI__builtin_ia32_vfmaddsubps512_mask3:
12388   case clang::X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
12389   case clang::X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
12390     MaskFalseVal = Ops[2];
12391     break;
12392   }
12393 
12394   if (MaskFalseVal)
12395     return EmitX86Select(CGF, Ops[3], Res, MaskFalseVal);
12396 
12397   return Res;
12398 }
12399 
12400 static Value *EmitScalarFMAExpr(CodeGenFunction &CGF, const CallExpr *E,
12401                                 MutableArrayRef<Value *> Ops, Value *Upper,
12402                                 bool ZeroMask = false, unsigned PTIdx = 0,
12403                                 bool NegAcc = false) {
12404   unsigned Rnd = 4;
12405   if (Ops.size() > 4)
12406     Rnd = cast<llvm::ConstantInt>(Ops[4])->getZExtValue();
12407 
12408   if (NegAcc)
12409     Ops[2] = CGF.Builder.CreateFNeg(Ops[2]);
12410 
12411   Ops[0] = CGF.Builder.CreateExtractElement(Ops[0], (uint64_t)0);
12412   Ops[1] = CGF.Builder.CreateExtractElement(Ops[1], (uint64_t)0);
12413   Ops[2] = CGF.Builder.CreateExtractElement(Ops[2], (uint64_t)0);
12414   Value *Res;
12415   if (Rnd != 4) {
12416     Intrinsic::ID IID;
12417 
12418     switch (Ops[0]->getType()->getPrimitiveSizeInBits()) {
12419     case 16:
12420       IID = Intrinsic::x86_avx512fp16_vfmadd_f16;
12421       break;
12422     case 32:
12423       IID = Intrinsic::x86_avx512_vfmadd_f32;
12424       break;
12425     case 64:
12426       IID = Intrinsic::x86_avx512_vfmadd_f64;
12427       break;
12428     default:
12429       llvm_unreachable("Unexpected size");
12430     }
12431     Res = CGF.Builder.CreateCall(CGF.CGM.getIntrinsic(IID),
12432                                  {Ops[0], Ops[1], Ops[2], Ops[4]});
12433   } else if (CGF.Builder.getIsFPConstrained()) {
12434     CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
12435     Function *FMA = CGF.CGM.getIntrinsic(
12436         Intrinsic::experimental_constrained_fma, Ops[0]->getType());
12437     Res = CGF.Builder.CreateConstrainedFPCall(FMA, Ops.slice(0, 3));
12438   } else {
12439     Function *FMA = CGF.CGM.getIntrinsic(Intrinsic::fma, Ops[0]->getType());
12440     Res = CGF.Builder.CreateCall(FMA, Ops.slice(0, 3));
12441   }
12442   // If we have more than 3 arguments, we need to do masking.
12443   if (Ops.size() > 3) {
12444     Value *PassThru = ZeroMask ? Constant::getNullValue(Res->getType())
12445                                : Ops[PTIdx];
12446 
12447     // If we negated the accumulator and the its the PassThru value we need to
12448     // bypass the negate. Conveniently Upper should be the same thing in this
12449     // case.
12450     if (NegAcc && PTIdx == 2)
12451       PassThru = CGF.Builder.CreateExtractElement(Upper, (uint64_t)0);
12452 
12453     Res = EmitX86ScalarSelect(CGF, Ops[3], Res, PassThru);
12454   }
12455   return CGF.Builder.CreateInsertElement(Upper, Res, (uint64_t)0);
12456 }
12457 
12458 static Value *EmitX86Muldq(CodeGenFunction &CGF, bool IsSigned,
12459                            ArrayRef<Value *> Ops) {
12460   llvm::Type *Ty = Ops[0]->getType();
12461   // Arguments have a vXi32 type so cast to vXi64.
12462   Ty = llvm::FixedVectorType::get(CGF.Int64Ty,
12463                                   Ty->getPrimitiveSizeInBits() / 64);
12464   Value *LHS = CGF.Builder.CreateBitCast(Ops[0], Ty);
12465   Value *RHS = CGF.Builder.CreateBitCast(Ops[1], Ty);
12466 
12467   if (IsSigned) {
12468     // Shift left then arithmetic shift right.
12469     Constant *ShiftAmt = ConstantInt::get(Ty, 32);
12470     LHS = CGF.Builder.CreateShl(LHS, ShiftAmt);
12471     LHS = CGF.Builder.CreateAShr(LHS, ShiftAmt);
12472     RHS = CGF.Builder.CreateShl(RHS, ShiftAmt);
12473     RHS = CGF.Builder.CreateAShr(RHS, ShiftAmt);
12474   } else {
12475     // Clear the upper bits.
12476     Constant *Mask = ConstantInt::get(Ty, 0xffffffff);
12477     LHS = CGF.Builder.CreateAnd(LHS, Mask);
12478     RHS = CGF.Builder.CreateAnd(RHS, Mask);
12479   }
12480 
12481   return CGF.Builder.CreateMul(LHS, RHS);
12482 }
12483 
12484 // Emit a masked pternlog intrinsic. This only exists because the header has to
12485 // use a macro and we aren't able to pass the input argument to a pternlog
12486 // builtin and a select builtin without evaluating it twice.
12487 static Value *EmitX86Ternlog(CodeGenFunction &CGF, bool ZeroMask,
12488                              ArrayRef<Value *> Ops) {
12489   llvm::Type *Ty = Ops[0]->getType();
12490 
12491   unsigned VecWidth = Ty->getPrimitiveSizeInBits();
12492   unsigned EltWidth = Ty->getScalarSizeInBits();
12493   Intrinsic::ID IID;
12494   if (VecWidth == 128 && EltWidth == 32)
12495     IID = Intrinsic::x86_avx512_pternlog_d_128;
12496   else if (VecWidth == 256 && EltWidth == 32)
12497     IID = Intrinsic::x86_avx512_pternlog_d_256;
12498   else if (VecWidth == 512 && EltWidth == 32)
12499     IID = Intrinsic::x86_avx512_pternlog_d_512;
12500   else if (VecWidth == 128 && EltWidth == 64)
12501     IID = Intrinsic::x86_avx512_pternlog_q_128;
12502   else if (VecWidth == 256 && EltWidth == 64)
12503     IID = Intrinsic::x86_avx512_pternlog_q_256;
12504   else if (VecWidth == 512 && EltWidth == 64)
12505     IID = Intrinsic::x86_avx512_pternlog_q_512;
12506   else
12507     llvm_unreachable("Unexpected intrinsic");
12508 
12509   Value *Ternlog = CGF.Builder.CreateCall(CGF.CGM.getIntrinsic(IID),
12510                                           Ops.drop_back());
12511   Value *PassThru = ZeroMask ? ConstantAggregateZero::get(Ty) : Ops[0];
12512   return EmitX86Select(CGF, Ops[4], Ternlog, PassThru);
12513 }
12514 
12515 static Value *EmitX86SExtMask(CodeGenFunction &CGF, Value *Op,
12516                               llvm::Type *DstTy) {
12517   unsigned NumberOfElements =
12518       cast<llvm::FixedVectorType>(DstTy)->getNumElements();
12519   Value *Mask = getMaskVecValue(CGF, Op, NumberOfElements);
12520   return CGF.Builder.CreateSExt(Mask, DstTy, "vpmovm2");
12521 }
12522 
12523 // Emit binary intrinsic with the same type used in result/args.
12524 static Value *EmitX86BinaryIntrinsic(CodeGenFunction &CGF,
12525                                      ArrayRef<Value *> Ops, Intrinsic::ID IID) {
12526   llvm::Function *F = CGF.CGM.getIntrinsic(IID, Ops[0]->getType());
12527   return CGF.Builder.CreateCall(F, {Ops[0], Ops[1]});
12528 }
12529 
12530 Value *CodeGenFunction::EmitX86CpuIs(const CallExpr *E) {
12531   const Expr *CPUExpr = E->getArg(0)->IgnoreParenCasts();
12532   StringRef CPUStr = cast<clang::StringLiteral>(CPUExpr)->getString();
12533   return EmitX86CpuIs(CPUStr);
12534 }
12535 
12536 // Convert F16 halfs to floats.
12537 static Value *EmitX86CvtF16ToFloatExpr(CodeGenFunction &CGF,
12538                                        ArrayRef<Value *> Ops,
12539                                        llvm::Type *DstTy) {
12540   assert((Ops.size() == 1 || Ops.size() == 3 || Ops.size() == 4) &&
12541          "Unknown cvtph2ps intrinsic");
12542 
12543   // If the SAE intrinsic doesn't use default rounding then we can't upgrade.
12544   if (Ops.size() == 4 && cast<llvm::ConstantInt>(Ops[3])->getZExtValue() != 4) {
12545     Function *F =
12546         CGF.CGM.getIntrinsic(Intrinsic::x86_avx512_mask_vcvtph2ps_512);
12547     return CGF.Builder.CreateCall(F, {Ops[0], Ops[1], Ops[2], Ops[3]});
12548   }
12549 
12550   unsigned NumDstElts = cast<llvm::FixedVectorType>(DstTy)->getNumElements();
12551   Value *Src = Ops[0];
12552 
12553   // Extract the subvector.
12554   if (NumDstElts !=
12555       cast<llvm::FixedVectorType>(Src->getType())->getNumElements()) {
12556     assert(NumDstElts == 4 && "Unexpected vector size");
12557     Src = CGF.Builder.CreateShuffleVector(Src, ArrayRef<int>{0, 1, 2, 3});
12558   }
12559 
12560   // Bitcast from vXi16 to vXf16.
12561   auto *HalfTy = llvm::FixedVectorType::get(
12562       llvm::Type::getHalfTy(CGF.getLLVMContext()), NumDstElts);
12563   Src = CGF.Builder.CreateBitCast(Src, HalfTy);
12564 
12565   // Perform the fp-extension.
12566   Value *Res = CGF.Builder.CreateFPExt(Src, DstTy, "cvtph2ps");
12567 
12568   if (Ops.size() >= 3)
12569     Res = EmitX86Select(CGF, Ops[2], Res, Ops[1]);
12570   return Res;
12571 }
12572 
12573 // Convert a BF16 to a float.
12574 static Value *EmitX86CvtBF16ToFloatExpr(CodeGenFunction &CGF,
12575                                         const CallExpr *E,
12576                                         ArrayRef<Value *> Ops) {
12577   llvm::Type *Int32Ty = CGF.Builder.getInt32Ty();
12578   Value *ZeroExt = CGF.Builder.CreateZExt(Ops[0], Int32Ty);
12579   Value *Shl = CGF.Builder.CreateShl(ZeroExt, 16);
12580   llvm::Type *ResultType = CGF.ConvertType(E->getType());
12581   Value *BitCast = CGF.Builder.CreateBitCast(Shl, ResultType);
12582   return BitCast;
12583 }
12584 
12585 Value *CodeGenFunction::EmitX86CpuIs(StringRef CPUStr) {
12586 
12587   llvm::Type *Int32Ty = Builder.getInt32Ty();
12588 
12589   // Matching the struct layout from the compiler-rt/libgcc structure that is
12590   // filled in:
12591   // unsigned int __cpu_vendor;
12592   // unsigned int __cpu_type;
12593   // unsigned int __cpu_subtype;
12594   // unsigned int __cpu_features[1];
12595   llvm::Type *STy = llvm::StructType::get(Int32Ty, Int32Ty, Int32Ty,
12596                                           llvm::ArrayType::get(Int32Ty, 1));
12597 
12598   // Grab the global __cpu_model.
12599   llvm::Constant *CpuModel = CGM.CreateRuntimeVariable(STy, "__cpu_model");
12600   cast<llvm::GlobalValue>(CpuModel)->setDSOLocal(true);
12601 
12602   // Calculate the index needed to access the correct field based on the
12603   // range. Also adjust the expected value.
12604   unsigned Index;
12605   unsigned Value;
12606   std::tie(Index, Value) = StringSwitch<std::pair<unsigned, unsigned>>(CPUStr)
12607 #define X86_VENDOR(ENUM, STRING)                                               \
12608   .Case(STRING, {0u, static_cast<unsigned>(llvm::X86::ENUM)})
12609 #define X86_CPU_TYPE_ALIAS(ENUM, ALIAS)                                        \
12610   .Case(ALIAS, {1u, static_cast<unsigned>(llvm::X86::ENUM)})
12611 #define X86_CPU_TYPE(ENUM, STR)                                                \
12612   .Case(STR, {1u, static_cast<unsigned>(llvm::X86::ENUM)})
12613 #define X86_CPU_SUBTYPE(ENUM, STR)                                             \
12614   .Case(STR, {2u, static_cast<unsigned>(llvm::X86::ENUM)})
12615 #include "llvm/Support/X86TargetParser.def"
12616                                .Default({0, 0});
12617   assert(Value != 0 && "Invalid CPUStr passed to CpuIs");
12618 
12619   // Grab the appropriate field from __cpu_model.
12620   llvm::Value *Idxs[] = {ConstantInt::get(Int32Ty, 0),
12621                          ConstantInt::get(Int32Ty, Index)};
12622   llvm::Value *CpuValue = Builder.CreateGEP(STy, CpuModel, Idxs);
12623   CpuValue = Builder.CreateAlignedLoad(Int32Ty, CpuValue,
12624                                        CharUnits::fromQuantity(4));
12625 
12626   // Check the value of the field against the requested value.
12627   return Builder.CreateICmpEQ(CpuValue,
12628                                   llvm::ConstantInt::get(Int32Ty, Value));
12629 }
12630 
12631 Value *CodeGenFunction::EmitX86CpuSupports(const CallExpr *E) {
12632   const Expr *FeatureExpr = E->getArg(0)->IgnoreParenCasts();
12633   StringRef FeatureStr = cast<StringLiteral>(FeatureExpr)->getString();
12634   return EmitX86CpuSupports(FeatureStr);
12635 }
12636 
12637 Value *CodeGenFunction::EmitX86CpuSupports(ArrayRef<StringRef> FeatureStrs) {
12638   return EmitX86CpuSupports(llvm::X86::getCpuSupportsMask(FeatureStrs));
12639 }
12640 
12641 llvm::Value *CodeGenFunction::EmitX86CpuSupports(uint64_t FeaturesMask) {
12642   uint32_t Features1 = Lo_32(FeaturesMask);
12643   uint32_t Features2 = Hi_32(FeaturesMask);
12644 
12645   Value *Result = Builder.getTrue();
12646 
12647   if (Features1 != 0) {
12648     // Matching the struct layout from the compiler-rt/libgcc structure that is
12649     // filled in:
12650     // unsigned int __cpu_vendor;
12651     // unsigned int __cpu_type;
12652     // unsigned int __cpu_subtype;
12653     // unsigned int __cpu_features[1];
12654     llvm::Type *STy = llvm::StructType::get(Int32Ty, Int32Ty, Int32Ty,
12655                                             llvm::ArrayType::get(Int32Ty, 1));
12656 
12657     // Grab the global __cpu_model.
12658     llvm::Constant *CpuModel = CGM.CreateRuntimeVariable(STy, "__cpu_model");
12659     cast<llvm::GlobalValue>(CpuModel)->setDSOLocal(true);
12660 
12661     // Grab the first (0th) element from the field __cpu_features off of the
12662     // global in the struct STy.
12663     Value *Idxs[] = {Builder.getInt32(0), Builder.getInt32(3),
12664                      Builder.getInt32(0)};
12665     Value *CpuFeatures = Builder.CreateGEP(STy, CpuModel, Idxs);
12666     Value *Features = Builder.CreateAlignedLoad(Int32Ty, CpuFeatures,
12667                                                 CharUnits::fromQuantity(4));
12668 
12669     // Check the value of the bit corresponding to the feature requested.
12670     Value *Mask = Builder.getInt32(Features1);
12671     Value *Bitset = Builder.CreateAnd(Features, Mask);
12672     Value *Cmp = Builder.CreateICmpEQ(Bitset, Mask);
12673     Result = Builder.CreateAnd(Result, Cmp);
12674   }
12675 
12676   if (Features2 != 0) {
12677     llvm::Constant *CpuFeatures2 = CGM.CreateRuntimeVariable(Int32Ty,
12678                                                              "__cpu_features2");
12679     cast<llvm::GlobalValue>(CpuFeatures2)->setDSOLocal(true);
12680 
12681     Value *Features = Builder.CreateAlignedLoad(Int32Ty, CpuFeatures2,
12682                                                 CharUnits::fromQuantity(4));
12683 
12684     // Check the value of the bit corresponding to the feature requested.
12685     Value *Mask = Builder.getInt32(Features2);
12686     Value *Bitset = Builder.CreateAnd(Features, Mask);
12687     Value *Cmp = Builder.CreateICmpEQ(Bitset, Mask);
12688     Result = Builder.CreateAnd(Result, Cmp);
12689   }
12690 
12691   return Result;
12692 }
12693 
12694 Value *CodeGenFunction::EmitX86CpuInit() {
12695   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy,
12696                                                     /*Variadic*/ false);
12697   llvm::FunctionCallee Func =
12698       CGM.CreateRuntimeFunction(FTy, "__cpu_indicator_init");
12699   cast<llvm::GlobalValue>(Func.getCallee())->setDSOLocal(true);
12700   cast<llvm::GlobalValue>(Func.getCallee())
12701       ->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
12702   return Builder.CreateCall(Func);
12703 }
12704 
12705 Value *CodeGenFunction::EmitX86BuiltinExpr(unsigned BuiltinID,
12706                                            const CallExpr *E) {
12707   if (BuiltinID == X86::BI__builtin_cpu_is)
12708     return EmitX86CpuIs(E);
12709   if (BuiltinID == X86::BI__builtin_cpu_supports)
12710     return EmitX86CpuSupports(E);
12711   if (BuiltinID == X86::BI__builtin_cpu_init)
12712     return EmitX86CpuInit();
12713 
12714   // Handle MSVC intrinsics before argument evaluation to prevent double
12715   // evaluation.
12716   if (Optional<MSVCIntrin> MsvcIntId = translateX86ToMsvcIntrin(BuiltinID))
12717     return EmitMSVCBuiltinExpr(*MsvcIntId, E);
12718 
12719   SmallVector<Value*, 4> Ops;
12720   bool IsMaskFCmp = false;
12721   bool IsConjFMA = false;
12722 
12723   // Find out if any arguments are required to be integer constant expressions.
12724   unsigned ICEArguments = 0;
12725   ASTContext::GetBuiltinTypeError Error;
12726   getContext().GetBuiltinType(BuiltinID, Error, &ICEArguments);
12727   assert(Error == ASTContext::GE_None && "Should not codegen an error");
12728 
12729   for (unsigned i = 0, e = E->getNumArgs(); i != e; i++) {
12730     // If this is a normal argument, just emit it as a scalar.
12731     if ((ICEArguments & (1 << i)) == 0) {
12732       Ops.push_back(EmitScalarExpr(E->getArg(i)));
12733       continue;
12734     }
12735 
12736     // If this is required to be a constant, constant fold it so that we know
12737     // that the generated intrinsic gets a ConstantInt.
12738     Ops.push_back(llvm::ConstantInt::get(
12739         getLLVMContext(), *E->getArg(i)->getIntegerConstantExpr(getContext())));
12740   }
12741 
12742   // These exist so that the builtin that takes an immediate can be bounds
12743   // checked by clang to avoid passing bad immediates to the backend. Since
12744   // AVX has a larger immediate than SSE we would need separate builtins to
12745   // do the different bounds checking. Rather than create a clang specific
12746   // SSE only builtin, this implements eight separate builtins to match gcc
12747   // implementation.
12748   auto getCmpIntrinsicCall = [this, &Ops](Intrinsic::ID ID, unsigned Imm) {
12749     Ops.push_back(llvm::ConstantInt::get(Int8Ty, Imm));
12750     llvm::Function *F = CGM.getIntrinsic(ID);
12751     return Builder.CreateCall(F, Ops);
12752   };
12753 
12754   // For the vector forms of FP comparisons, translate the builtins directly to
12755   // IR.
12756   // TODO: The builtins could be removed if the SSE header files used vector
12757   // extension comparisons directly (vector ordered/unordered may need
12758   // additional support via __builtin_isnan()).
12759   auto getVectorFCmpIR = [this, &Ops, E](CmpInst::Predicate Pred,
12760                                          bool IsSignaling) {
12761     CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
12762     Value *Cmp;
12763     if (IsSignaling)
12764       Cmp = Builder.CreateFCmpS(Pred, Ops[0], Ops[1]);
12765     else
12766       Cmp = Builder.CreateFCmp(Pred, Ops[0], Ops[1]);
12767     llvm::VectorType *FPVecTy = cast<llvm::VectorType>(Ops[0]->getType());
12768     llvm::VectorType *IntVecTy = llvm::VectorType::getInteger(FPVecTy);
12769     Value *Sext = Builder.CreateSExt(Cmp, IntVecTy);
12770     return Builder.CreateBitCast(Sext, FPVecTy);
12771   };
12772 
12773   switch (BuiltinID) {
12774   default: return nullptr;
12775   case X86::BI_mm_prefetch: {
12776     Value *Address = Ops[0];
12777     ConstantInt *C = cast<ConstantInt>(Ops[1]);
12778     Value *RW = ConstantInt::get(Int32Ty, (C->getZExtValue() >> 2) & 0x1);
12779     Value *Locality = ConstantInt::get(Int32Ty, C->getZExtValue() & 0x3);
12780     Value *Data = ConstantInt::get(Int32Ty, 1);
12781     Function *F = CGM.getIntrinsic(Intrinsic::prefetch, Address->getType());
12782     return Builder.CreateCall(F, {Address, RW, Locality, Data});
12783   }
12784   case X86::BI_mm_clflush: {
12785     return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::x86_sse2_clflush),
12786                               Ops[0]);
12787   }
12788   case X86::BI_mm_lfence: {
12789     return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::x86_sse2_lfence));
12790   }
12791   case X86::BI_mm_mfence: {
12792     return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::x86_sse2_mfence));
12793   }
12794   case X86::BI_mm_sfence: {
12795     return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::x86_sse_sfence));
12796   }
12797   case X86::BI_mm_pause: {
12798     return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::x86_sse2_pause));
12799   }
12800   case X86::BI__rdtsc: {
12801     return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::x86_rdtsc));
12802   }
12803   case X86::BI__builtin_ia32_rdtscp: {
12804     Value *Call = Builder.CreateCall(CGM.getIntrinsic(Intrinsic::x86_rdtscp));
12805     Builder.CreateDefaultAlignedStore(Builder.CreateExtractValue(Call, 1),
12806                                       Ops[0]);
12807     return Builder.CreateExtractValue(Call, 0);
12808   }
12809   case X86::BI__builtin_ia32_lzcnt_u16:
12810   case X86::BI__builtin_ia32_lzcnt_u32:
12811   case X86::BI__builtin_ia32_lzcnt_u64: {
12812     Function *F = CGM.getIntrinsic(Intrinsic::ctlz, Ops[0]->getType());
12813     return Builder.CreateCall(F, {Ops[0], Builder.getInt1(false)});
12814   }
12815   case X86::BI__builtin_ia32_tzcnt_u16:
12816   case X86::BI__builtin_ia32_tzcnt_u32:
12817   case X86::BI__builtin_ia32_tzcnt_u64: {
12818     Function *F = CGM.getIntrinsic(Intrinsic::cttz, Ops[0]->getType());
12819     return Builder.CreateCall(F, {Ops[0], Builder.getInt1(false)});
12820   }
12821   case X86::BI__builtin_ia32_undef128:
12822   case X86::BI__builtin_ia32_undef256:
12823   case X86::BI__builtin_ia32_undef512:
12824     // The x86 definition of "undef" is not the same as the LLVM definition
12825     // (PR32176). We leave optimizing away an unnecessary zero constant to the
12826     // IR optimizer and backend.
12827     // TODO: If we had a "freeze" IR instruction to generate a fixed undef
12828     // value, we should use that here instead of a zero.
12829     return llvm::Constant::getNullValue(ConvertType(E->getType()));
12830   case X86::BI__builtin_ia32_vec_init_v8qi:
12831   case X86::BI__builtin_ia32_vec_init_v4hi:
12832   case X86::BI__builtin_ia32_vec_init_v2si:
12833     return Builder.CreateBitCast(BuildVector(Ops),
12834                                  llvm::Type::getX86_MMXTy(getLLVMContext()));
12835   case X86::BI__builtin_ia32_vec_ext_v2si:
12836   case X86::BI__builtin_ia32_vec_ext_v16qi:
12837   case X86::BI__builtin_ia32_vec_ext_v8hi:
12838   case X86::BI__builtin_ia32_vec_ext_v4si:
12839   case X86::BI__builtin_ia32_vec_ext_v4sf:
12840   case X86::BI__builtin_ia32_vec_ext_v2di:
12841   case X86::BI__builtin_ia32_vec_ext_v32qi:
12842   case X86::BI__builtin_ia32_vec_ext_v16hi:
12843   case X86::BI__builtin_ia32_vec_ext_v8si:
12844   case X86::BI__builtin_ia32_vec_ext_v4di: {
12845     unsigned NumElts =
12846         cast<llvm::FixedVectorType>(Ops[0]->getType())->getNumElements();
12847     uint64_t Index = cast<ConstantInt>(Ops[1])->getZExtValue();
12848     Index &= NumElts - 1;
12849     // These builtins exist so we can ensure the index is an ICE and in range.
12850     // Otherwise we could just do this in the header file.
12851     return Builder.CreateExtractElement(Ops[0], Index);
12852   }
12853   case X86::BI__builtin_ia32_vec_set_v16qi:
12854   case X86::BI__builtin_ia32_vec_set_v8hi:
12855   case X86::BI__builtin_ia32_vec_set_v4si:
12856   case X86::BI__builtin_ia32_vec_set_v2di:
12857   case X86::BI__builtin_ia32_vec_set_v32qi:
12858   case X86::BI__builtin_ia32_vec_set_v16hi:
12859   case X86::BI__builtin_ia32_vec_set_v8si:
12860   case X86::BI__builtin_ia32_vec_set_v4di: {
12861     unsigned NumElts =
12862         cast<llvm::FixedVectorType>(Ops[0]->getType())->getNumElements();
12863     unsigned Index = cast<ConstantInt>(Ops[2])->getZExtValue();
12864     Index &= NumElts - 1;
12865     // These builtins exist so we can ensure the index is an ICE and in range.
12866     // Otherwise we could just do this in the header file.
12867     return Builder.CreateInsertElement(Ops[0], Ops[1], Index);
12868   }
12869   case X86::BI_mm_setcsr:
12870   case X86::BI__builtin_ia32_ldmxcsr: {
12871     Address Tmp = CreateMemTemp(E->getArg(0)->getType());
12872     Builder.CreateStore(Ops[0], Tmp);
12873     return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::x86_sse_ldmxcsr),
12874                           Builder.CreateBitCast(Tmp.getPointer(), Int8PtrTy));
12875   }
12876   case X86::BI_mm_getcsr:
12877   case X86::BI__builtin_ia32_stmxcsr: {
12878     Address Tmp = CreateMemTemp(E->getType());
12879     Builder.CreateCall(CGM.getIntrinsic(Intrinsic::x86_sse_stmxcsr),
12880                        Builder.CreateBitCast(Tmp.getPointer(), Int8PtrTy));
12881     return Builder.CreateLoad(Tmp, "stmxcsr");
12882   }
12883   case X86::BI__builtin_ia32_xsave:
12884   case X86::BI__builtin_ia32_xsave64:
12885   case X86::BI__builtin_ia32_xrstor:
12886   case X86::BI__builtin_ia32_xrstor64:
12887   case X86::BI__builtin_ia32_xsaveopt:
12888   case X86::BI__builtin_ia32_xsaveopt64:
12889   case X86::BI__builtin_ia32_xrstors:
12890   case X86::BI__builtin_ia32_xrstors64:
12891   case X86::BI__builtin_ia32_xsavec:
12892   case X86::BI__builtin_ia32_xsavec64:
12893   case X86::BI__builtin_ia32_xsaves:
12894   case X86::BI__builtin_ia32_xsaves64:
12895   case X86::BI__builtin_ia32_xsetbv:
12896   case X86::BI_xsetbv: {
12897     Intrinsic::ID ID;
12898 #define INTRINSIC_X86_XSAVE_ID(NAME) \
12899     case X86::BI__builtin_ia32_##NAME: \
12900       ID = Intrinsic::x86_##NAME; \
12901       break
12902     switch (BuiltinID) {
12903     default: llvm_unreachable("Unsupported intrinsic!");
12904     INTRINSIC_X86_XSAVE_ID(xsave);
12905     INTRINSIC_X86_XSAVE_ID(xsave64);
12906     INTRINSIC_X86_XSAVE_ID(xrstor);
12907     INTRINSIC_X86_XSAVE_ID(xrstor64);
12908     INTRINSIC_X86_XSAVE_ID(xsaveopt);
12909     INTRINSIC_X86_XSAVE_ID(xsaveopt64);
12910     INTRINSIC_X86_XSAVE_ID(xrstors);
12911     INTRINSIC_X86_XSAVE_ID(xrstors64);
12912     INTRINSIC_X86_XSAVE_ID(xsavec);
12913     INTRINSIC_X86_XSAVE_ID(xsavec64);
12914     INTRINSIC_X86_XSAVE_ID(xsaves);
12915     INTRINSIC_X86_XSAVE_ID(xsaves64);
12916     INTRINSIC_X86_XSAVE_ID(xsetbv);
12917     case X86::BI_xsetbv:
12918       ID = Intrinsic::x86_xsetbv;
12919       break;
12920     }
12921 #undef INTRINSIC_X86_XSAVE_ID
12922     Value *Mhi = Builder.CreateTrunc(
12923       Builder.CreateLShr(Ops[1], ConstantInt::get(Int64Ty, 32)), Int32Ty);
12924     Value *Mlo = Builder.CreateTrunc(Ops[1], Int32Ty);
12925     Ops[1] = Mhi;
12926     Ops.push_back(Mlo);
12927     return Builder.CreateCall(CGM.getIntrinsic(ID), Ops);
12928   }
12929   case X86::BI__builtin_ia32_xgetbv:
12930   case X86::BI_xgetbv:
12931     return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::x86_xgetbv), Ops);
12932   case X86::BI__builtin_ia32_storedqudi128_mask:
12933   case X86::BI__builtin_ia32_storedqusi128_mask:
12934   case X86::BI__builtin_ia32_storedquhi128_mask:
12935   case X86::BI__builtin_ia32_storedquqi128_mask:
12936   case X86::BI__builtin_ia32_storeupd128_mask:
12937   case X86::BI__builtin_ia32_storeups128_mask:
12938   case X86::BI__builtin_ia32_storedqudi256_mask:
12939   case X86::BI__builtin_ia32_storedqusi256_mask:
12940   case X86::BI__builtin_ia32_storedquhi256_mask:
12941   case X86::BI__builtin_ia32_storedquqi256_mask:
12942   case X86::BI__builtin_ia32_storeupd256_mask:
12943   case X86::BI__builtin_ia32_storeups256_mask:
12944   case X86::BI__builtin_ia32_storedqudi512_mask:
12945   case X86::BI__builtin_ia32_storedqusi512_mask:
12946   case X86::BI__builtin_ia32_storedquhi512_mask:
12947   case X86::BI__builtin_ia32_storedquqi512_mask:
12948   case X86::BI__builtin_ia32_storeupd512_mask:
12949   case X86::BI__builtin_ia32_storeups512_mask:
12950     return EmitX86MaskedStore(*this, Ops, Align(1));
12951 
12952   case X86::BI__builtin_ia32_storesh128_mask:
12953   case X86::BI__builtin_ia32_storess128_mask:
12954   case X86::BI__builtin_ia32_storesd128_mask:
12955     return EmitX86MaskedStore(*this, Ops, Align(1));
12956 
12957   case X86::BI__builtin_ia32_vpopcntb_128:
12958   case X86::BI__builtin_ia32_vpopcntd_128:
12959   case X86::BI__builtin_ia32_vpopcntq_128:
12960   case X86::BI__builtin_ia32_vpopcntw_128:
12961   case X86::BI__builtin_ia32_vpopcntb_256:
12962   case X86::BI__builtin_ia32_vpopcntd_256:
12963   case X86::BI__builtin_ia32_vpopcntq_256:
12964   case X86::BI__builtin_ia32_vpopcntw_256:
12965   case X86::BI__builtin_ia32_vpopcntb_512:
12966   case X86::BI__builtin_ia32_vpopcntd_512:
12967   case X86::BI__builtin_ia32_vpopcntq_512:
12968   case X86::BI__builtin_ia32_vpopcntw_512: {
12969     llvm::Type *ResultType = ConvertType(E->getType());
12970     llvm::Function *F = CGM.getIntrinsic(Intrinsic::ctpop, ResultType);
12971     return Builder.CreateCall(F, Ops);
12972   }
12973   case X86::BI__builtin_ia32_cvtmask2b128:
12974   case X86::BI__builtin_ia32_cvtmask2b256:
12975   case X86::BI__builtin_ia32_cvtmask2b512:
12976   case X86::BI__builtin_ia32_cvtmask2w128:
12977   case X86::BI__builtin_ia32_cvtmask2w256:
12978   case X86::BI__builtin_ia32_cvtmask2w512:
12979   case X86::BI__builtin_ia32_cvtmask2d128:
12980   case X86::BI__builtin_ia32_cvtmask2d256:
12981   case X86::BI__builtin_ia32_cvtmask2d512:
12982   case X86::BI__builtin_ia32_cvtmask2q128:
12983   case X86::BI__builtin_ia32_cvtmask2q256:
12984   case X86::BI__builtin_ia32_cvtmask2q512:
12985     return EmitX86SExtMask(*this, Ops[0], ConvertType(E->getType()));
12986 
12987   case X86::BI__builtin_ia32_cvtb2mask128:
12988   case X86::BI__builtin_ia32_cvtb2mask256:
12989   case X86::BI__builtin_ia32_cvtb2mask512:
12990   case X86::BI__builtin_ia32_cvtw2mask128:
12991   case X86::BI__builtin_ia32_cvtw2mask256:
12992   case X86::BI__builtin_ia32_cvtw2mask512:
12993   case X86::BI__builtin_ia32_cvtd2mask128:
12994   case X86::BI__builtin_ia32_cvtd2mask256:
12995   case X86::BI__builtin_ia32_cvtd2mask512:
12996   case X86::BI__builtin_ia32_cvtq2mask128:
12997   case X86::BI__builtin_ia32_cvtq2mask256:
12998   case X86::BI__builtin_ia32_cvtq2mask512:
12999     return EmitX86ConvertToMask(*this, Ops[0]);
13000 
13001   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
13002   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
13003   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
13004   case X86::BI__builtin_ia32_vcvtw2ph512_mask:
13005   case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
13006   case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
13007     return EmitX86ConvertIntToFp(*this, E, Ops, /*IsSigned*/ true);
13008   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
13009   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
13010   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
13011   case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
13012   case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
13013   case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
13014     return EmitX86ConvertIntToFp(*this, E, Ops, /*IsSigned*/ false);
13015 
13016   case X86::BI__builtin_ia32_vfmaddss3:
13017   case X86::BI__builtin_ia32_vfmaddsd3:
13018   case X86::BI__builtin_ia32_vfmaddsh3_mask:
13019   case X86::BI__builtin_ia32_vfmaddss3_mask:
13020   case X86::BI__builtin_ia32_vfmaddsd3_mask:
13021     return EmitScalarFMAExpr(*this, E, Ops, Ops[0]);
13022   case X86::BI__builtin_ia32_vfmaddss:
13023   case X86::BI__builtin_ia32_vfmaddsd:
13024     return EmitScalarFMAExpr(*this, E, Ops,
13025                              Constant::getNullValue(Ops[0]->getType()));
13026   case X86::BI__builtin_ia32_vfmaddsh3_maskz:
13027   case X86::BI__builtin_ia32_vfmaddss3_maskz:
13028   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
13029     return EmitScalarFMAExpr(*this, E, Ops, Ops[0], /*ZeroMask*/ true);
13030   case X86::BI__builtin_ia32_vfmaddsh3_mask3:
13031   case X86::BI__builtin_ia32_vfmaddss3_mask3:
13032   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
13033     return EmitScalarFMAExpr(*this, E, Ops, Ops[2], /*ZeroMask*/ false, 2);
13034   case X86::BI__builtin_ia32_vfmsubsh3_mask3:
13035   case X86::BI__builtin_ia32_vfmsubss3_mask3:
13036   case X86::BI__builtin_ia32_vfmsubsd3_mask3:
13037     return EmitScalarFMAExpr(*this, E, Ops, Ops[2], /*ZeroMask*/ false, 2,
13038                              /*NegAcc*/ true);
13039   case X86::BI__builtin_ia32_vfmaddph:
13040   case X86::BI__builtin_ia32_vfmaddps:
13041   case X86::BI__builtin_ia32_vfmaddpd:
13042   case X86::BI__builtin_ia32_vfmaddph256:
13043   case X86::BI__builtin_ia32_vfmaddps256:
13044   case X86::BI__builtin_ia32_vfmaddpd256:
13045   case X86::BI__builtin_ia32_vfmaddph512_mask:
13046   case X86::BI__builtin_ia32_vfmaddph512_maskz:
13047   case X86::BI__builtin_ia32_vfmaddph512_mask3:
13048   case X86::BI__builtin_ia32_vfmaddps512_mask:
13049   case X86::BI__builtin_ia32_vfmaddps512_maskz:
13050   case X86::BI__builtin_ia32_vfmaddps512_mask3:
13051   case X86::BI__builtin_ia32_vfmsubps512_mask3:
13052   case X86::BI__builtin_ia32_vfmaddpd512_mask:
13053   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
13054   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
13055   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
13056   case X86::BI__builtin_ia32_vfmsubph512_mask3:
13057     return EmitX86FMAExpr(*this, E, Ops, BuiltinID, /*IsAddSub*/ false);
13058   case X86::BI__builtin_ia32_vfmaddsubph512_mask:
13059   case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
13060   case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
13061   case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
13062   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
13063   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
13064   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
13065   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
13066   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
13067   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
13068   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
13069   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
13070     return EmitX86FMAExpr(*this, E, Ops, BuiltinID, /*IsAddSub*/ true);
13071 
13072   case X86::BI__builtin_ia32_movdqa32store128_mask:
13073   case X86::BI__builtin_ia32_movdqa64store128_mask:
13074   case X86::BI__builtin_ia32_storeaps128_mask:
13075   case X86::BI__builtin_ia32_storeapd128_mask:
13076   case X86::BI__builtin_ia32_movdqa32store256_mask:
13077   case X86::BI__builtin_ia32_movdqa64store256_mask:
13078   case X86::BI__builtin_ia32_storeaps256_mask:
13079   case X86::BI__builtin_ia32_storeapd256_mask:
13080   case X86::BI__builtin_ia32_movdqa32store512_mask:
13081   case X86::BI__builtin_ia32_movdqa64store512_mask:
13082   case X86::BI__builtin_ia32_storeaps512_mask:
13083   case X86::BI__builtin_ia32_storeapd512_mask:
13084     return EmitX86MaskedStore(
13085         *this, Ops,
13086         getContext().getTypeAlignInChars(E->getArg(1)->getType()).getAsAlign());
13087 
13088   case X86::BI__builtin_ia32_loadups128_mask:
13089   case X86::BI__builtin_ia32_loadups256_mask:
13090   case X86::BI__builtin_ia32_loadups512_mask:
13091   case X86::BI__builtin_ia32_loadupd128_mask:
13092   case X86::BI__builtin_ia32_loadupd256_mask:
13093   case X86::BI__builtin_ia32_loadupd512_mask:
13094   case X86::BI__builtin_ia32_loaddquqi128_mask:
13095   case X86::BI__builtin_ia32_loaddquqi256_mask:
13096   case X86::BI__builtin_ia32_loaddquqi512_mask:
13097   case X86::BI__builtin_ia32_loaddquhi128_mask:
13098   case X86::BI__builtin_ia32_loaddquhi256_mask:
13099   case X86::BI__builtin_ia32_loaddquhi512_mask:
13100   case X86::BI__builtin_ia32_loaddqusi128_mask:
13101   case X86::BI__builtin_ia32_loaddqusi256_mask:
13102   case X86::BI__builtin_ia32_loaddqusi512_mask:
13103   case X86::BI__builtin_ia32_loaddqudi128_mask:
13104   case X86::BI__builtin_ia32_loaddqudi256_mask:
13105   case X86::BI__builtin_ia32_loaddqudi512_mask:
13106     return EmitX86MaskedLoad(*this, Ops, Align(1));
13107 
13108   case X86::BI__builtin_ia32_loadsh128_mask:
13109   case X86::BI__builtin_ia32_loadss128_mask:
13110   case X86::BI__builtin_ia32_loadsd128_mask:
13111     return EmitX86MaskedLoad(*this, Ops, Align(1));
13112 
13113   case X86::BI__builtin_ia32_loadaps128_mask:
13114   case X86::BI__builtin_ia32_loadaps256_mask:
13115   case X86::BI__builtin_ia32_loadaps512_mask:
13116   case X86::BI__builtin_ia32_loadapd128_mask:
13117   case X86::BI__builtin_ia32_loadapd256_mask:
13118   case X86::BI__builtin_ia32_loadapd512_mask:
13119   case X86::BI__builtin_ia32_movdqa32load128_mask:
13120   case X86::BI__builtin_ia32_movdqa32load256_mask:
13121   case X86::BI__builtin_ia32_movdqa32load512_mask:
13122   case X86::BI__builtin_ia32_movdqa64load128_mask:
13123   case X86::BI__builtin_ia32_movdqa64load256_mask:
13124   case X86::BI__builtin_ia32_movdqa64load512_mask:
13125     return EmitX86MaskedLoad(
13126         *this, Ops,
13127         getContext().getTypeAlignInChars(E->getArg(1)->getType()).getAsAlign());
13128 
13129   case X86::BI__builtin_ia32_expandloaddf128_mask:
13130   case X86::BI__builtin_ia32_expandloaddf256_mask:
13131   case X86::BI__builtin_ia32_expandloaddf512_mask:
13132   case X86::BI__builtin_ia32_expandloadsf128_mask:
13133   case X86::BI__builtin_ia32_expandloadsf256_mask:
13134   case X86::BI__builtin_ia32_expandloadsf512_mask:
13135   case X86::BI__builtin_ia32_expandloaddi128_mask:
13136   case X86::BI__builtin_ia32_expandloaddi256_mask:
13137   case X86::BI__builtin_ia32_expandloaddi512_mask:
13138   case X86::BI__builtin_ia32_expandloadsi128_mask:
13139   case X86::BI__builtin_ia32_expandloadsi256_mask:
13140   case X86::BI__builtin_ia32_expandloadsi512_mask:
13141   case X86::BI__builtin_ia32_expandloadhi128_mask:
13142   case X86::BI__builtin_ia32_expandloadhi256_mask:
13143   case X86::BI__builtin_ia32_expandloadhi512_mask:
13144   case X86::BI__builtin_ia32_expandloadqi128_mask:
13145   case X86::BI__builtin_ia32_expandloadqi256_mask:
13146   case X86::BI__builtin_ia32_expandloadqi512_mask:
13147     return EmitX86ExpandLoad(*this, Ops);
13148 
13149   case X86::BI__builtin_ia32_compressstoredf128_mask:
13150   case X86::BI__builtin_ia32_compressstoredf256_mask:
13151   case X86::BI__builtin_ia32_compressstoredf512_mask:
13152   case X86::BI__builtin_ia32_compressstoresf128_mask:
13153   case X86::BI__builtin_ia32_compressstoresf256_mask:
13154   case X86::BI__builtin_ia32_compressstoresf512_mask:
13155   case X86::BI__builtin_ia32_compressstoredi128_mask:
13156   case X86::BI__builtin_ia32_compressstoredi256_mask:
13157   case X86::BI__builtin_ia32_compressstoredi512_mask:
13158   case X86::BI__builtin_ia32_compressstoresi128_mask:
13159   case X86::BI__builtin_ia32_compressstoresi256_mask:
13160   case X86::BI__builtin_ia32_compressstoresi512_mask:
13161   case X86::BI__builtin_ia32_compressstorehi128_mask:
13162   case X86::BI__builtin_ia32_compressstorehi256_mask:
13163   case X86::BI__builtin_ia32_compressstorehi512_mask:
13164   case X86::BI__builtin_ia32_compressstoreqi128_mask:
13165   case X86::BI__builtin_ia32_compressstoreqi256_mask:
13166   case X86::BI__builtin_ia32_compressstoreqi512_mask:
13167     return EmitX86CompressStore(*this, Ops);
13168 
13169   case X86::BI__builtin_ia32_expanddf128_mask:
13170   case X86::BI__builtin_ia32_expanddf256_mask:
13171   case X86::BI__builtin_ia32_expanddf512_mask:
13172   case X86::BI__builtin_ia32_expandsf128_mask:
13173   case X86::BI__builtin_ia32_expandsf256_mask:
13174   case X86::BI__builtin_ia32_expandsf512_mask:
13175   case X86::BI__builtin_ia32_expanddi128_mask:
13176   case X86::BI__builtin_ia32_expanddi256_mask:
13177   case X86::BI__builtin_ia32_expanddi512_mask:
13178   case X86::BI__builtin_ia32_expandsi128_mask:
13179   case X86::BI__builtin_ia32_expandsi256_mask:
13180   case X86::BI__builtin_ia32_expandsi512_mask:
13181   case X86::BI__builtin_ia32_expandhi128_mask:
13182   case X86::BI__builtin_ia32_expandhi256_mask:
13183   case X86::BI__builtin_ia32_expandhi512_mask:
13184   case X86::BI__builtin_ia32_expandqi128_mask:
13185   case X86::BI__builtin_ia32_expandqi256_mask:
13186   case X86::BI__builtin_ia32_expandqi512_mask:
13187     return EmitX86CompressExpand(*this, Ops, /*IsCompress*/false);
13188 
13189   case X86::BI__builtin_ia32_compressdf128_mask:
13190   case X86::BI__builtin_ia32_compressdf256_mask:
13191   case X86::BI__builtin_ia32_compressdf512_mask:
13192   case X86::BI__builtin_ia32_compresssf128_mask:
13193   case X86::BI__builtin_ia32_compresssf256_mask:
13194   case X86::BI__builtin_ia32_compresssf512_mask:
13195   case X86::BI__builtin_ia32_compressdi128_mask:
13196   case X86::BI__builtin_ia32_compressdi256_mask:
13197   case X86::BI__builtin_ia32_compressdi512_mask:
13198   case X86::BI__builtin_ia32_compresssi128_mask:
13199   case X86::BI__builtin_ia32_compresssi256_mask:
13200   case X86::BI__builtin_ia32_compresssi512_mask:
13201   case X86::BI__builtin_ia32_compresshi128_mask:
13202   case X86::BI__builtin_ia32_compresshi256_mask:
13203   case X86::BI__builtin_ia32_compresshi512_mask:
13204   case X86::BI__builtin_ia32_compressqi128_mask:
13205   case X86::BI__builtin_ia32_compressqi256_mask:
13206   case X86::BI__builtin_ia32_compressqi512_mask:
13207     return EmitX86CompressExpand(*this, Ops, /*IsCompress*/true);
13208 
13209   case X86::BI__builtin_ia32_gather3div2df:
13210   case X86::BI__builtin_ia32_gather3div2di:
13211   case X86::BI__builtin_ia32_gather3div4df:
13212   case X86::BI__builtin_ia32_gather3div4di:
13213   case X86::BI__builtin_ia32_gather3div4sf:
13214   case X86::BI__builtin_ia32_gather3div4si:
13215   case X86::BI__builtin_ia32_gather3div8sf:
13216   case X86::BI__builtin_ia32_gather3div8si:
13217   case X86::BI__builtin_ia32_gather3siv2df:
13218   case X86::BI__builtin_ia32_gather3siv2di:
13219   case X86::BI__builtin_ia32_gather3siv4df:
13220   case X86::BI__builtin_ia32_gather3siv4di:
13221   case X86::BI__builtin_ia32_gather3siv4sf:
13222   case X86::BI__builtin_ia32_gather3siv4si:
13223   case X86::BI__builtin_ia32_gather3siv8sf:
13224   case X86::BI__builtin_ia32_gather3siv8si:
13225   case X86::BI__builtin_ia32_gathersiv8df:
13226   case X86::BI__builtin_ia32_gathersiv16sf:
13227   case X86::BI__builtin_ia32_gatherdiv8df:
13228   case X86::BI__builtin_ia32_gatherdiv16sf:
13229   case X86::BI__builtin_ia32_gathersiv8di:
13230   case X86::BI__builtin_ia32_gathersiv16si:
13231   case X86::BI__builtin_ia32_gatherdiv8di:
13232   case X86::BI__builtin_ia32_gatherdiv16si: {
13233     Intrinsic::ID IID;
13234     switch (BuiltinID) {
13235     default: llvm_unreachable("Unexpected builtin");
13236     case X86::BI__builtin_ia32_gather3div2df:
13237       IID = Intrinsic::x86_avx512_mask_gather3div2_df;
13238       break;
13239     case X86::BI__builtin_ia32_gather3div2di:
13240       IID = Intrinsic::x86_avx512_mask_gather3div2_di;
13241       break;
13242     case X86::BI__builtin_ia32_gather3div4df:
13243       IID = Intrinsic::x86_avx512_mask_gather3div4_df;
13244       break;
13245     case X86::BI__builtin_ia32_gather3div4di:
13246       IID = Intrinsic::x86_avx512_mask_gather3div4_di;
13247       break;
13248     case X86::BI__builtin_ia32_gather3div4sf:
13249       IID = Intrinsic::x86_avx512_mask_gather3div4_sf;
13250       break;
13251     case X86::BI__builtin_ia32_gather3div4si:
13252       IID = Intrinsic::x86_avx512_mask_gather3div4_si;
13253       break;
13254     case X86::BI__builtin_ia32_gather3div8sf:
13255       IID = Intrinsic::x86_avx512_mask_gather3div8_sf;
13256       break;
13257     case X86::BI__builtin_ia32_gather3div8si:
13258       IID = Intrinsic::x86_avx512_mask_gather3div8_si;
13259       break;
13260     case X86::BI__builtin_ia32_gather3siv2df:
13261       IID = Intrinsic::x86_avx512_mask_gather3siv2_df;
13262       break;
13263     case X86::BI__builtin_ia32_gather3siv2di:
13264       IID = Intrinsic::x86_avx512_mask_gather3siv2_di;
13265       break;
13266     case X86::BI__builtin_ia32_gather3siv4df:
13267       IID = Intrinsic::x86_avx512_mask_gather3siv4_df;
13268       break;
13269     case X86::BI__builtin_ia32_gather3siv4di:
13270       IID = Intrinsic::x86_avx512_mask_gather3siv4_di;
13271       break;
13272     case X86::BI__builtin_ia32_gather3siv4sf:
13273       IID = Intrinsic::x86_avx512_mask_gather3siv4_sf;
13274       break;
13275     case X86::BI__builtin_ia32_gather3siv4si:
13276       IID = Intrinsic::x86_avx512_mask_gather3siv4_si;
13277       break;
13278     case X86::BI__builtin_ia32_gather3siv8sf:
13279       IID = Intrinsic::x86_avx512_mask_gather3siv8_sf;
13280       break;
13281     case X86::BI__builtin_ia32_gather3siv8si:
13282       IID = Intrinsic::x86_avx512_mask_gather3siv8_si;
13283       break;
13284     case X86::BI__builtin_ia32_gathersiv8df:
13285       IID = Intrinsic::x86_avx512_mask_gather_dpd_512;
13286       break;
13287     case X86::BI__builtin_ia32_gathersiv16sf:
13288       IID = Intrinsic::x86_avx512_mask_gather_dps_512;
13289       break;
13290     case X86::BI__builtin_ia32_gatherdiv8df:
13291       IID = Intrinsic::x86_avx512_mask_gather_qpd_512;
13292       break;
13293     case X86::BI__builtin_ia32_gatherdiv16sf:
13294       IID = Intrinsic::x86_avx512_mask_gather_qps_512;
13295       break;
13296     case X86::BI__builtin_ia32_gathersiv8di:
13297       IID = Intrinsic::x86_avx512_mask_gather_dpq_512;
13298       break;
13299     case X86::BI__builtin_ia32_gathersiv16si:
13300       IID = Intrinsic::x86_avx512_mask_gather_dpi_512;
13301       break;
13302     case X86::BI__builtin_ia32_gatherdiv8di:
13303       IID = Intrinsic::x86_avx512_mask_gather_qpq_512;
13304       break;
13305     case X86::BI__builtin_ia32_gatherdiv16si:
13306       IID = Intrinsic::x86_avx512_mask_gather_qpi_512;
13307       break;
13308     }
13309 
13310     unsigned MinElts = std::min(
13311         cast<llvm::FixedVectorType>(Ops[0]->getType())->getNumElements(),
13312         cast<llvm::FixedVectorType>(Ops[2]->getType())->getNumElements());
13313     Ops[3] = getMaskVecValue(*this, Ops[3], MinElts);
13314     Function *Intr = CGM.getIntrinsic(IID);
13315     return Builder.CreateCall(Intr, Ops);
13316   }
13317 
13318   case X86::BI__builtin_ia32_scattersiv8df:
13319   case X86::BI__builtin_ia32_scattersiv16sf:
13320   case X86::BI__builtin_ia32_scatterdiv8df:
13321   case X86::BI__builtin_ia32_scatterdiv16sf:
13322   case X86::BI__builtin_ia32_scattersiv8di:
13323   case X86::BI__builtin_ia32_scattersiv16si:
13324   case X86::BI__builtin_ia32_scatterdiv8di:
13325   case X86::BI__builtin_ia32_scatterdiv16si:
13326   case X86::BI__builtin_ia32_scatterdiv2df:
13327   case X86::BI__builtin_ia32_scatterdiv2di:
13328   case X86::BI__builtin_ia32_scatterdiv4df:
13329   case X86::BI__builtin_ia32_scatterdiv4di:
13330   case X86::BI__builtin_ia32_scatterdiv4sf:
13331   case X86::BI__builtin_ia32_scatterdiv4si:
13332   case X86::BI__builtin_ia32_scatterdiv8sf:
13333   case X86::BI__builtin_ia32_scatterdiv8si:
13334   case X86::BI__builtin_ia32_scattersiv2df:
13335   case X86::BI__builtin_ia32_scattersiv2di:
13336   case X86::BI__builtin_ia32_scattersiv4df:
13337   case X86::BI__builtin_ia32_scattersiv4di:
13338   case X86::BI__builtin_ia32_scattersiv4sf:
13339   case X86::BI__builtin_ia32_scattersiv4si:
13340   case X86::BI__builtin_ia32_scattersiv8sf:
13341   case X86::BI__builtin_ia32_scattersiv8si: {
13342     Intrinsic::ID IID;
13343     switch (BuiltinID) {
13344     default: llvm_unreachable("Unexpected builtin");
13345     case X86::BI__builtin_ia32_scattersiv8df:
13346       IID = Intrinsic::x86_avx512_mask_scatter_dpd_512;
13347       break;
13348     case X86::BI__builtin_ia32_scattersiv16sf:
13349       IID = Intrinsic::x86_avx512_mask_scatter_dps_512;
13350       break;
13351     case X86::BI__builtin_ia32_scatterdiv8df:
13352       IID = Intrinsic::x86_avx512_mask_scatter_qpd_512;
13353       break;
13354     case X86::BI__builtin_ia32_scatterdiv16sf:
13355       IID = Intrinsic::x86_avx512_mask_scatter_qps_512;
13356       break;
13357     case X86::BI__builtin_ia32_scattersiv8di:
13358       IID = Intrinsic::x86_avx512_mask_scatter_dpq_512;
13359       break;
13360     case X86::BI__builtin_ia32_scattersiv16si:
13361       IID = Intrinsic::x86_avx512_mask_scatter_dpi_512;
13362       break;
13363     case X86::BI__builtin_ia32_scatterdiv8di:
13364       IID = Intrinsic::x86_avx512_mask_scatter_qpq_512;
13365       break;
13366     case X86::BI__builtin_ia32_scatterdiv16si:
13367       IID = Intrinsic::x86_avx512_mask_scatter_qpi_512;
13368       break;
13369     case X86::BI__builtin_ia32_scatterdiv2df:
13370       IID = Intrinsic::x86_avx512_mask_scatterdiv2_df;
13371       break;
13372     case X86::BI__builtin_ia32_scatterdiv2di:
13373       IID = Intrinsic::x86_avx512_mask_scatterdiv2_di;
13374       break;
13375     case X86::BI__builtin_ia32_scatterdiv4df:
13376       IID = Intrinsic::x86_avx512_mask_scatterdiv4_df;
13377       break;
13378     case X86::BI__builtin_ia32_scatterdiv4di:
13379       IID = Intrinsic::x86_avx512_mask_scatterdiv4_di;
13380       break;
13381     case X86::BI__builtin_ia32_scatterdiv4sf:
13382       IID = Intrinsic::x86_avx512_mask_scatterdiv4_sf;
13383       break;
13384     case X86::BI__builtin_ia32_scatterdiv4si:
13385       IID = Intrinsic::x86_avx512_mask_scatterdiv4_si;
13386       break;
13387     case X86::BI__builtin_ia32_scatterdiv8sf:
13388       IID = Intrinsic::x86_avx512_mask_scatterdiv8_sf;
13389       break;
13390     case X86::BI__builtin_ia32_scatterdiv8si:
13391       IID = Intrinsic::x86_avx512_mask_scatterdiv8_si;
13392       break;
13393     case X86::BI__builtin_ia32_scattersiv2df:
13394       IID = Intrinsic::x86_avx512_mask_scattersiv2_df;
13395       break;
13396     case X86::BI__builtin_ia32_scattersiv2di:
13397       IID = Intrinsic::x86_avx512_mask_scattersiv2_di;
13398       break;
13399     case X86::BI__builtin_ia32_scattersiv4df:
13400       IID = Intrinsic::x86_avx512_mask_scattersiv4_df;
13401       break;
13402     case X86::BI__builtin_ia32_scattersiv4di:
13403       IID = Intrinsic::x86_avx512_mask_scattersiv4_di;
13404       break;
13405     case X86::BI__builtin_ia32_scattersiv4sf:
13406       IID = Intrinsic::x86_avx512_mask_scattersiv4_sf;
13407       break;
13408     case X86::BI__builtin_ia32_scattersiv4si:
13409       IID = Intrinsic::x86_avx512_mask_scattersiv4_si;
13410       break;
13411     case X86::BI__builtin_ia32_scattersiv8sf:
13412       IID = Intrinsic::x86_avx512_mask_scattersiv8_sf;
13413       break;
13414     case X86::BI__builtin_ia32_scattersiv8si:
13415       IID = Intrinsic::x86_avx512_mask_scattersiv8_si;
13416       break;
13417     }
13418 
13419     unsigned MinElts = std::min(
13420         cast<llvm::FixedVectorType>(Ops[2]->getType())->getNumElements(),
13421         cast<llvm::FixedVectorType>(Ops[3]->getType())->getNumElements());
13422     Ops[1] = getMaskVecValue(*this, Ops[1], MinElts);
13423     Function *Intr = CGM.getIntrinsic(IID);
13424     return Builder.CreateCall(Intr, Ops);
13425   }
13426 
13427   case X86::BI__builtin_ia32_vextractf128_pd256:
13428   case X86::BI__builtin_ia32_vextractf128_ps256:
13429   case X86::BI__builtin_ia32_vextractf128_si256:
13430   case X86::BI__builtin_ia32_extract128i256:
13431   case X86::BI__builtin_ia32_extractf64x4_mask:
13432   case X86::BI__builtin_ia32_extractf32x4_mask:
13433   case X86::BI__builtin_ia32_extracti64x4_mask:
13434   case X86::BI__builtin_ia32_extracti32x4_mask:
13435   case X86::BI__builtin_ia32_extractf32x8_mask:
13436   case X86::BI__builtin_ia32_extracti32x8_mask:
13437   case X86::BI__builtin_ia32_extractf32x4_256_mask:
13438   case X86::BI__builtin_ia32_extracti32x4_256_mask:
13439   case X86::BI__builtin_ia32_extractf64x2_256_mask:
13440   case X86::BI__builtin_ia32_extracti64x2_256_mask:
13441   case X86::BI__builtin_ia32_extractf64x2_512_mask:
13442   case X86::BI__builtin_ia32_extracti64x2_512_mask: {
13443     auto *DstTy = cast<llvm::FixedVectorType>(ConvertType(E->getType()));
13444     unsigned NumElts = DstTy->getNumElements();
13445     unsigned SrcNumElts =
13446         cast<llvm::FixedVectorType>(Ops[0]->getType())->getNumElements();
13447     unsigned SubVectors = SrcNumElts / NumElts;
13448     unsigned Index = cast<ConstantInt>(Ops[1])->getZExtValue();
13449     assert(llvm::isPowerOf2_32(SubVectors) && "Expected power of 2 subvectors");
13450     Index &= SubVectors - 1; // Remove any extra bits.
13451     Index *= NumElts;
13452 
13453     int Indices[16];
13454     for (unsigned i = 0; i != NumElts; ++i)
13455       Indices[i] = i + Index;
13456 
13457     Value *Res = Builder.CreateShuffleVector(Ops[0],
13458                                              makeArrayRef(Indices, NumElts),
13459                                              "extract");
13460 
13461     if (Ops.size() == 4)
13462       Res = EmitX86Select(*this, Ops[3], Res, Ops[2]);
13463 
13464     return Res;
13465   }
13466   case X86::BI__builtin_ia32_vinsertf128_pd256:
13467   case X86::BI__builtin_ia32_vinsertf128_ps256:
13468   case X86::BI__builtin_ia32_vinsertf128_si256:
13469   case X86::BI__builtin_ia32_insert128i256:
13470   case X86::BI__builtin_ia32_insertf64x4:
13471   case X86::BI__builtin_ia32_insertf32x4:
13472   case X86::BI__builtin_ia32_inserti64x4:
13473   case X86::BI__builtin_ia32_inserti32x4:
13474   case X86::BI__builtin_ia32_insertf32x8:
13475   case X86::BI__builtin_ia32_inserti32x8:
13476   case X86::BI__builtin_ia32_insertf32x4_256:
13477   case X86::BI__builtin_ia32_inserti32x4_256:
13478   case X86::BI__builtin_ia32_insertf64x2_256:
13479   case X86::BI__builtin_ia32_inserti64x2_256:
13480   case X86::BI__builtin_ia32_insertf64x2_512:
13481   case X86::BI__builtin_ia32_inserti64x2_512: {
13482     unsigned DstNumElts =
13483         cast<llvm::FixedVectorType>(Ops[0]->getType())->getNumElements();
13484     unsigned SrcNumElts =
13485         cast<llvm::FixedVectorType>(Ops[1]->getType())->getNumElements();
13486     unsigned SubVectors = DstNumElts / SrcNumElts;
13487     unsigned Index = cast<ConstantInt>(Ops[2])->getZExtValue();
13488     assert(llvm::isPowerOf2_32(SubVectors) && "Expected power of 2 subvectors");
13489     Index &= SubVectors - 1; // Remove any extra bits.
13490     Index *= SrcNumElts;
13491 
13492     int Indices[16];
13493     for (unsigned i = 0; i != DstNumElts; ++i)
13494       Indices[i] = (i >= SrcNumElts) ? SrcNumElts + (i % SrcNumElts) : i;
13495 
13496     Value *Op1 = Builder.CreateShuffleVector(Ops[1],
13497                                              makeArrayRef(Indices, DstNumElts),
13498                                              "widen");
13499 
13500     for (unsigned i = 0; i != DstNumElts; ++i) {
13501       if (i >= Index && i < (Index + SrcNumElts))
13502         Indices[i] = (i - Index) + DstNumElts;
13503       else
13504         Indices[i] = i;
13505     }
13506 
13507     return Builder.CreateShuffleVector(Ops[0], Op1,
13508                                        makeArrayRef(Indices, DstNumElts),
13509                                        "insert");
13510   }
13511   case X86::BI__builtin_ia32_pmovqd512_mask:
13512   case X86::BI__builtin_ia32_pmovwb512_mask: {
13513     Value *Res = Builder.CreateTrunc(Ops[0], Ops[1]->getType());
13514     return EmitX86Select(*this, Ops[2], Res, Ops[1]);
13515   }
13516   case X86::BI__builtin_ia32_pmovdb512_mask:
13517   case X86::BI__builtin_ia32_pmovdw512_mask:
13518   case X86::BI__builtin_ia32_pmovqw512_mask: {
13519     if (const auto *C = dyn_cast<Constant>(Ops[2]))
13520       if (C->isAllOnesValue())
13521         return Builder.CreateTrunc(Ops[0], Ops[1]->getType());
13522 
13523     Intrinsic::ID IID;
13524     switch (BuiltinID) {
13525     default: llvm_unreachable("Unsupported intrinsic!");
13526     case X86::BI__builtin_ia32_pmovdb512_mask:
13527       IID = Intrinsic::x86_avx512_mask_pmov_db_512;
13528       break;
13529     case X86::BI__builtin_ia32_pmovdw512_mask:
13530       IID = Intrinsic::x86_avx512_mask_pmov_dw_512;
13531       break;
13532     case X86::BI__builtin_ia32_pmovqw512_mask:
13533       IID = Intrinsic::x86_avx512_mask_pmov_qw_512;
13534       break;
13535     }
13536 
13537     Function *Intr = CGM.getIntrinsic(IID);
13538     return Builder.CreateCall(Intr, Ops);
13539   }
13540   case X86::BI__builtin_ia32_pblendw128:
13541   case X86::BI__builtin_ia32_blendpd:
13542   case X86::BI__builtin_ia32_blendps:
13543   case X86::BI__builtin_ia32_blendpd256:
13544   case X86::BI__builtin_ia32_blendps256:
13545   case X86::BI__builtin_ia32_pblendw256:
13546   case X86::BI__builtin_ia32_pblendd128:
13547   case X86::BI__builtin_ia32_pblendd256: {
13548     unsigned NumElts =
13549         cast<llvm::FixedVectorType>(Ops[0]->getType())->getNumElements();
13550     unsigned Imm = cast<llvm::ConstantInt>(Ops[2])->getZExtValue();
13551 
13552     int Indices[16];
13553     // If there are more than 8 elements, the immediate is used twice so make
13554     // sure we handle that.
13555     for (unsigned i = 0; i != NumElts; ++i)
13556       Indices[i] = ((Imm >> (i % 8)) & 0x1) ? NumElts + i : i;
13557 
13558     return Builder.CreateShuffleVector(Ops[0], Ops[1],
13559                                        makeArrayRef(Indices, NumElts),
13560                                        "blend");
13561   }
13562   case X86::BI__builtin_ia32_pshuflw:
13563   case X86::BI__builtin_ia32_pshuflw256:
13564   case X86::BI__builtin_ia32_pshuflw512: {
13565     uint32_t Imm = cast<llvm::ConstantInt>(Ops[1])->getZExtValue();
13566     auto *Ty = cast<llvm::FixedVectorType>(Ops[0]->getType());
13567     unsigned NumElts = Ty->getNumElements();
13568 
13569     // Splat the 8-bits of immediate 4 times to help the loop wrap around.
13570     Imm = (Imm & 0xff) * 0x01010101;
13571 
13572     int Indices[32];
13573     for (unsigned l = 0; l != NumElts; l += 8) {
13574       for (unsigned i = 0; i != 4; ++i) {
13575         Indices[l + i] = l + (Imm & 3);
13576         Imm >>= 2;
13577       }
13578       for (unsigned i = 4; i != 8; ++i)
13579         Indices[l + i] = l + i;
13580     }
13581 
13582     return Builder.CreateShuffleVector(Ops[0], makeArrayRef(Indices, NumElts),
13583                                        "pshuflw");
13584   }
13585   case X86::BI__builtin_ia32_pshufhw:
13586   case X86::BI__builtin_ia32_pshufhw256:
13587   case X86::BI__builtin_ia32_pshufhw512: {
13588     uint32_t Imm = cast<llvm::ConstantInt>(Ops[1])->getZExtValue();
13589     auto *Ty = cast<llvm::FixedVectorType>(Ops[0]->getType());
13590     unsigned NumElts = Ty->getNumElements();
13591 
13592     // Splat the 8-bits of immediate 4 times to help the loop wrap around.
13593     Imm = (Imm & 0xff) * 0x01010101;
13594 
13595     int Indices[32];
13596     for (unsigned l = 0; l != NumElts; l += 8) {
13597       for (unsigned i = 0; i != 4; ++i)
13598         Indices[l + i] = l + i;
13599       for (unsigned i = 4; i != 8; ++i) {
13600         Indices[l + i] = l + 4 + (Imm & 3);
13601         Imm >>= 2;
13602       }
13603     }
13604 
13605     return Builder.CreateShuffleVector(Ops[0], makeArrayRef(Indices, NumElts),
13606                                        "pshufhw");
13607   }
13608   case X86::BI__builtin_ia32_pshufd:
13609   case X86::BI__builtin_ia32_pshufd256:
13610   case X86::BI__builtin_ia32_pshufd512:
13611   case X86::BI__builtin_ia32_vpermilpd:
13612   case X86::BI__builtin_ia32_vpermilps:
13613   case X86::BI__builtin_ia32_vpermilpd256:
13614   case X86::BI__builtin_ia32_vpermilps256:
13615   case X86::BI__builtin_ia32_vpermilpd512:
13616   case X86::BI__builtin_ia32_vpermilps512: {
13617     uint32_t Imm = cast<llvm::ConstantInt>(Ops[1])->getZExtValue();
13618     auto *Ty = cast<llvm::FixedVectorType>(Ops[0]->getType());
13619     unsigned NumElts = Ty->getNumElements();
13620     unsigned NumLanes = Ty->getPrimitiveSizeInBits() / 128;
13621     unsigned NumLaneElts = NumElts / NumLanes;
13622 
13623     // Splat the 8-bits of immediate 4 times to help the loop wrap around.
13624     Imm = (Imm & 0xff) * 0x01010101;
13625 
13626     int Indices[16];
13627     for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
13628       for (unsigned i = 0; i != NumLaneElts; ++i) {
13629         Indices[i + l] = (Imm % NumLaneElts) + l;
13630         Imm /= NumLaneElts;
13631       }
13632     }
13633 
13634     return Builder.CreateShuffleVector(Ops[0], makeArrayRef(Indices, NumElts),
13635                                        "permil");
13636   }
13637   case X86::BI__builtin_ia32_shufpd:
13638   case X86::BI__builtin_ia32_shufpd256:
13639   case X86::BI__builtin_ia32_shufpd512:
13640   case X86::BI__builtin_ia32_shufps:
13641   case X86::BI__builtin_ia32_shufps256:
13642   case X86::BI__builtin_ia32_shufps512: {
13643     uint32_t Imm = cast<llvm::ConstantInt>(Ops[2])->getZExtValue();
13644     auto *Ty = cast<llvm::FixedVectorType>(Ops[0]->getType());
13645     unsigned NumElts = Ty->getNumElements();
13646     unsigned NumLanes = Ty->getPrimitiveSizeInBits() / 128;
13647     unsigned NumLaneElts = NumElts / NumLanes;
13648 
13649     // Splat the 8-bits of immediate 4 times to help the loop wrap around.
13650     Imm = (Imm & 0xff) * 0x01010101;
13651 
13652     int Indices[16];
13653     for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
13654       for (unsigned i = 0; i != NumLaneElts; ++i) {
13655         unsigned Index = Imm % NumLaneElts;
13656         Imm /= NumLaneElts;
13657         if (i >= (NumLaneElts / 2))
13658           Index += NumElts;
13659         Indices[l + i] = l + Index;
13660       }
13661     }
13662 
13663     return Builder.CreateShuffleVector(Ops[0], Ops[1],
13664                                        makeArrayRef(Indices, NumElts),
13665                                        "shufp");
13666   }
13667   case X86::BI__builtin_ia32_permdi256:
13668   case X86::BI__builtin_ia32_permdf256:
13669   case X86::BI__builtin_ia32_permdi512:
13670   case X86::BI__builtin_ia32_permdf512: {
13671     unsigned Imm = cast<llvm::ConstantInt>(Ops[1])->getZExtValue();
13672     auto *Ty = cast<llvm::FixedVectorType>(Ops[0]->getType());
13673     unsigned NumElts = Ty->getNumElements();
13674 
13675     // These intrinsics operate on 256-bit lanes of four 64-bit elements.
13676     int Indices[8];
13677     for (unsigned l = 0; l != NumElts; l += 4)
13678       for (unsigned i = 0; i != 4; ++i)
13679         Indices[l + i] = l + ((Imm >> (2 * i)) & 0x3);
13680 
13681     return Builder.CreateShuffleVector(Ops[0], makeArrayRef(Indices, NumElts),
13682                                        "perm");
13683   }
13684   case X86::BI__builtin_ia32_palignr128:
13685   case X86::BI__builtin_ia32_palignr256:
13686   case X86::BI__builtin_ia32_palignr512: {
13687     unsigned ShiftVal = cast<llvm::ConstantInt>(Ops[2])->getZExtValue() & 0xff;
13688 
13689     unsigned NumElts =
13690         cast<llvm::FixedVectorType>(Ops[0]->getType())->getNumElements();
13691     assert(NumElts % 16 == 0);
13692 
13693     // If palignr is shifting the pair of vectors more than the size of two
13694     // lanes, emit zero.
13695     if (ShiftVal >= 32)
13696       return llvm::Constant::getNullValue(ConvertType(E->getType()));
13697 
13698     // If palignr is shifting the pair of input vectors more than one lane,
13699     // but less than two lanes, convert to shifting in zeroes.
13700     if (ShiftVal > 16) {
13701       ShiftVal -= 16;
13702       Ops[1] = Ops[0];
13703       Ops[0] = llvm::Constant::getNullValue(Ops[0]->getType());
13704     }
13705 
13706     int Indices[64];
13707     // 256-bit palignr operates on 128-bit lanes so we need to handle that
13708     for (unsigned l = 0; l != NumElts; l += 16) {
13709       for (unsigned i = 0; i != 16; ++i) {
13710         unsigned Idx = ShiftVal + i;
13711         if (Idx >= 16)
13712           Idx += NumElts - 16; // End of lane, switch operand.
13713         Indices[l + i] = Idx + l;
13714       }
13715     }
13716 
13717     return Builder.CreateShuffleVector(Ops[1], Ops[0],
13718                                        makeArrayRef(Indices, NumElts),
13719                                        "palignr");
13720   }
13721   case X86::BI__builtin_ia32_alignd128:
13722   case X86::BI__builtin_ia32_alignd256:
13723   case X86::BI__builtin_ia32_alignd512:
13724   case X86::BI__builtin_ia32_alignq128:
13725   case X86::BI__builtin_ia32_alignq256:
13726   case X86::BI__builtin_ia32_alignq512: {
13727     unsigned NumElts =
13728         cast<llvm::FixedVectorType>(Ops[0]->getType())->getNumElements();
13729     unsigned ShiftVal = cast<llvm::ConstantInt>(Ops[2])->getZExtValue() & 0xff;
13730 
13731     // Mask the shift amount to width of a vector.
13732     ShiftVal &= NumElts - 1;
13733 
13734     int Indices[16];
13735     for (unsigned i = 0; i != NumElts; ++i)
13736       Indices[i] = i + ShiftVal;
13737 
13738     return Builder.CreateShuffleVector(Ops[1], Ops[0],
13739                                        makeArrayRef(Indices, NumElts),
13740                                        "valign");
13741   }
13742   case X86::BI__builtin_ia32_shuf_f32x4_256:
13743   case X86::BI__builtin_ia32_shuf_f64x2_256:
13744   case X86::BI__builtin_ia32_shuf_i32x4_256:
13745   case X86::BI__builtin_ia32_shuf_i64x2_256:
13746   case X86::BI__builtin_ia32_shuf_f32x4:
13747   case X86::BI__builtin_ia32_shuf_f64x2:
13748   case X86::BI__builtin_ia32_shuf_i32x4:
13749   case X86::BI__builtin_ia32_shuf_i64x2: {
13750     unsigned Imm = cast<llvm::ConstantInt>(Ops[2])->getZExtValue();
13751     auto *Ty = cast<llvm::FixedVectorType>(Ops[0]->getType());
13752     unsigned NumElts = Ty->getNumElements();
13753     unsigned NumLanes = Ty->getPrimitiveSizeInBits() == 512 ? 4 : 2;
13754     unsigned NumLaneElts = NumElts / NumLanes;
13755 
13756     int Indices[16];
13757     for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
13758       unsigned Index = (Imm % NumLanes) * NumLaneElts;
13759       Imm /= NumLanes; // Discard the bits we just used.
13760       if (l >= (NumElts / 2))
13761         Index += NumElts; // Switch to other source.
13762       for (unsigned i = 0; i != NumLaneElts; ++i) {
13763         Indices[l + i] = Index + i;
13764       }
13765     }
13766 
13767     return Builder.CreateShuffleVector(Ops[0], Ops[1],
13768                                        makeArrayRef(Indices, NumElts),
13769                                        "shuf");
13770   }
13771 
13772   case X86::BI__builtin_ia32_vperm2f128_pd256:
13773   case X86::BI__builtin_ia32_vperm2f128_ps256:
13774   case X86::BI__builtin_ia32_vperm2f128_si256:
13775   case X86::BI__builtin_ia32_permti256: {
13776     unsigned Imm = cast<llvm::ConstantInt>(Ops[2])->getZExtValue();
13777     unsigned NumElts =
13778         cast<llvm::FixedVectorType>(Ops[0]->getType())->getNumElements();
13779 
13780     // This takes a very simple approach since there are two lanes and a
13781     // shuffle can have 2 inputs. So we reserve the first input for the first
13782     // lane and the second input for the second lane. This may result in
13783     // duplicate sources, but this can be dealt with in the backend.
13784 
13785     Value *OutOps[2];
13786     int Indices[8];
13787     for (unsigned l = 0; l != 2; ++l) {
13788       // Determine the source for this lane.
13789       if (Imm & (1 << ((l * 4) + 3)))
13790         OutOps[l] = llvm::ConstantAggregateZero::get(Ops[0]->getType());
13791       else if (Imm & (1 << ((l * 4) + 1)))
13792         OutOps[l] = Ops[1];
13793       else
13794         OutOps[l] = Ops[0];
13795 
13796       for (unsigned i = 0; i != NumElts/2; ++i) {
13797         // Start with ith element of the source for this lane.
13798         unsigned Idx = (l * NumElts) + i;
13799         // If bit 0 of the immediate half is set, switch to the high half of
13800         // the source.
13801         if (Imm & (1 << (l * 4)))
13802           Idx += NumElts/2;
13803         Indices[(l * (NumElts/2)) + i] = Idx;
13804       }
13805     }
13806 
13807     return Builder.CreateShuffleVector(OutOps[0], OutOps[1],
13808                                        makeArrayRef(Indices, NumElts),
13809                                        "vperm");
13810   }
13811 
13812   case X86::BI__builtin_ia32_pslldqi128_byteshift:
13813   case X86::BI__builtin_ia32_pslldqi256_byteshift:
13814   case X86::BI__builtin_ia32_pslldqi512_byteshift: {
13815     unsigned ShiftVal = cast<llvm::ConstantInt>(Ops[1])->getZExtValue() & 0xff;
13816     auto *ResultType = cast<llvm::FixedVectorType>(Ops[0]->getType());
13817     // Builtin type is vXi64 so multiply by 8 to get bytes.
13818     unsigned NumElts = ResultType->getNumElements() * 8;
13819 
13820     // If pslldq is shifting the vector more than 15 bytes, emit zero.
13821     if (ShiftVal >= 16)
13822       return llvm::Constant::getNullValue(ResultType);
13823 
13824     int Indices[64];
13825     // 256/512-bit pslldq operates on 128-bit lanes so we need to handle that
13826     for (unsigned l = 0; l != NumElts; l += 16) {
13827       for (unsigned i = 0; i != 16; ++i) {
13828         unsigned Idx = NumElts + i - ShiftVal;
13829         if (Idx < NumElts) Idx -= NumElts - 16; // end of lane, switch operand.
13830         Indices[l + i] = Idx + l;
13831       }
13832     }
13833 
13834     auto *VecTy = llvm::FixedVectorType::get(Int8Ty, NumElts);
13835     Value *Cast = Builder.CreateBitCast(Ops[0], VecTy, "cast");
13836     Value *Zero = llvm::Constant::getNullValue(VecTy);
13837     Value *SV = Builder.CreateShuffleVector(Zero, Cast,
13838                                             makeArrayRef(Indices, NumElts),
13839                                             "pslldq");
13840     return Builder.CreateBitCast(SV, Ops[0]->getType(), "cast");
13841   }
13842   case X86::BI__builtin_ia32_psrldqi128_byteshift:
13843   case X86::BI__builtin_ia32_psrldqi256_byteshift:
13844   case X86::BI__builtin_ia32_psrldqi512_byteshift: {
13845     unsigned ShiftVal = cast<llvm::ConstantInt>(Ops[1])->getZExtValue() & 0xff;
13846     auto *ResultType = cast<llvm::FixedVectorType>(Ops[0]->getType());
13847     // Builtin type is vXi64 so multiply by 8 to get bytes.
13848     unsigned NumElts = ResultType->getNumElements() * 8;
13849 
13850     // If psrldq is shifting the vector more than 15 bytes, emit zero.
13851     if (ShiftVal >= 16)
13852       return llvm::Constant::getNullValue(ResultType);
13853 
13854     int Indices[64];
13855     // 256/512-bit psrldq operates on 128-bit lanes so we need to handle that
13856     for (unsigned l = 0; l != NumElts; l += 16) {
13857       for (unsigned i = 0; i != 16; ++i) {
13858         unsigned Idx = i + ShiftVal;
13859         if (Idx >= 16) Idx += NumElts - 16; // end of lane, switch operand.
13860         Indices[l + i] = Idx + l;
13861       }
13862     }
13863 
13864     auto *VecTy = llvm::FixedVectorType::get(Int8Ty, NumElts);
13865     Value *Cast = Builder.CreateBitCast(Ops[0], VecTy, "cast");
13866     Value *Zero = llvm::Constant::getNullValue(VecTy);
13867     Value *SV = Builder.CreateShuffleVector(Cast, Zero,
13868                                             makeArrayRef(Indices, NumElts),
13869                                             "psrldq");
13870     return Builder.CreateBitCast(SV, ResultType, "cast");
13871   }
13872   case X86::BI__builtin_ia32_kshiftliqi:
13873   case X86::BI__builtin_ia32_kshiftlihi:
13874   case X86::BI__builtin_ia32_kshiftlisi:
13875   case X86::BI__builtin_ia32_kshiftlidi: {
13876     unsigned ShiftVal = cast<llvm::ConstantInt>(Ops[1])->getZExtValue() & 0xff;
13877     unsigned NumElts = Ops[0]->getType()->getIntegerBitWidth();
13878 
13879     if (ShiftVal >= NumElts)
13880       return llvm::Constant::getNullValue(Ops[0]->getType());
13881 
13882     Value *In = getMaskVecValue(*this, Ops[0], NumElts);
13883 
13884     int Indices[64];
13885     for (unsigned i = 0; i != NumElts; ++i)
13886       Indices[i] = NumElts + i - ShiftVal;
13887 
13888     Value *Zero = llvm::Constant::getNullValue(In->getType());
13889     Value *SV = Builder.CreateShuffleVector(Zero, In,
13890                                             makeArrayRef(Indices, NumElts),
13891                                             "kshiftl");
13892     return Builder.CreateBitCast(SV, Ops[0]->getType());
13893   }
13894   case X86::BI__builtin_ia32_kshiftriqi:
13895   case X86::BI__builtin_ia32_kshiftrihi:
13896   case X86::BI__builtin_ia32_kshiftrisi:
13897   case X86::BI__builtin_ia32_kshiftridi: {
13898     unsigned ShiftVal = cast<llvm::ConstantInt>(Ops[1])->getZExtValue() & 0xff;
13899     unsigned NumElts = Ops[0]->getType()->getIntegerBitWidth();
13900 
13901     if (ShiftVal >= NumElts)
13902       return llvm::Constant::getNullValue(Ops[0]->getType());
13903 
13904     Value *In = getMaskVecValue(*this, Ops[0], NumElts);
13905 
13906     int Indices[64];
13907     for (unsigned i = 0; i != NumElts; ++i)
13908       Indices[i] = i + ShiftVal;
13909 
13910     Value *Zero = llvm::Constant::getNullValue(In->getType());
13911     Value *SV = Builder.CreateShuffleVector(In, Zero,
13912                                             makeArrayRef(Indices, NumElts),
13913                                             "kshiftr");
13914     return Builder.CreateBitCast(SV, Ops[0]->getType());
13915   }
13916   case X86::BI__builtin_ia32_movnti:
13917   case X86::BI__builtin_ia32_movnti64:
13918   case X86::BI__builtin_ia32_movntsd:
13919   case X86::BI__builtin_ia32_movntss: {
13920     llvm::MDNode *Node = llvm::MDNode::get(
13921         getLLVMContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
13922 
13923     Value *Ptr = Ops[0];
13924     Value *Src = Ops[1];
13925 
13926     // Extract the 0'th element of the source vector.
13927     if (BuiltinID == X86::BI__builtin_ia32_movntsd ||
13928         BuiltinID == X86::BI__builtin_ia32_movntss)
13929       Src = Builder.CreateExtractElement(Src, (uint64_t)0, "extract");
13930 
13931     // Convert the type of the pointer to a pointer to the stored type.
13932     Value *BC = Builder.CreateBitCast(
13933         Ptr, llvm::PointerType::getUnqual(Src->getType()), "cast");
13934 
13935     // Unaligned nontemporal store of the scalar value.
13936     StoreInst *SI = Builder.CreateDefaultAlignedStore(Src, BC);
13937     SI->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
13938     SI->setAlignment(llvm::Align(1));
13939     return SI;
13940   }
13941   // Rotate is a special case of funnel shift - 1st 2 args are the same.
13942   case X86::BI__builtin_ia32_vprotb:
13943   case X86::BI__builtin_ia32_vprotw:
13944   case X86::BI__builtin_ia32_vprotd:
13945   case X86::BI__builtin_ia32_vprotq:
13946   case X86::BI__builtin_ia32_vprotbi:
13947   case X86::BI__builtin_ia32_vprotwi:
13948   case X86::BI__builtin_ia32_vprotdi:
13949   case X86::BI__builtin_ia32_vprotqi:
13950   case X86::BI__builtin_ia32_prold128:
13951   case X86::BI__builtin_ia32_prold256:
13952   case X86::BI__builtin_ia32_prold512:
13953   case X86::BI__builtin_ia32_prolq128:
13954   case X86::BI__builtin_ia32_prolq256:
13955   case X86::BI__builtin_ia32_prolq512:
13956   case X86::BI__builtin_ia32_prolvd128:
13957   case X86::BI__builtin_ia32_prolvd256:
13958   case X86::BI__builtin_ia32_prolvd512:
13959   case X86::BI__builtin_ia32_prolvq128:
13960   case X86::BI__builtin_ia32_prolvq256:
13961   case X86::BI__builtin_ia32_prolvq512:
13962     return EmitX86FunnelShift(*this, Ops[0], Ops[0], Ops[1], false);
13963   case X86::BI__builtin_ia32_prord128:
13964   case X86::BI__builtin_ia32_prord256:
13965   case X86::BI__builtin_ia32_prord512:
13966   case X86::BI__builtin_ia32_prorq128:
13967   case X86::BI__builtin_ia32_prorq256:
13968   case X86::BI__builtin_ia32_prorq512:
13969   case X86::BI__builtin_ia32_prorvd128:
13970   case X86::BI__builtin_ia32_prorvd256:
13971   case X86::BI__builtin_ia32_prorvd512:
13972   case X86::BI__builtin_ia32_prorvq128:
13973   case X86::BI__builtin_ia32_prorvq256:
13974   case X86::BI__builtin_ia32_prorvq512:
13975     return EmitX86FunnelShift(*this, Ops[0], Ops[0], Ops[1], true);
13976   case X86::BI__builtin_ia32_selectb_128:
13977   case X86::BI__builtin_ia32_selectb_256:
13978   case X86::BI__builtin_ia32_selectb_512:
13979   case X86::BI__builtin_ia32_selectw_128:
13980   case X86::BI__builtin_ia32_selectw_256:
13981   case X86::BI__builtin_ia32_selectw_512:
13982   case X86::BI__builtin_ia32_selectd_128:
13983   case X86::BI__builtin_ia32_selectd_256:
13984   case X86::BI__builtin_ia32_selectd_512:
13985   case X86::BI__builtin_ia32_selectq_128:
13986   case X86::BI__builtin_ia32_selectq_256:
13987   case X86::BI__builtin_ia32_selectq_512:
13988   case X86::BI__builtin_ia32_selectph_128:
13989   case X86::BI__builtin_ia32_selectph_256:
13990   case X86::BI__builtin_ia32_selectph_512:
13991   case X86::BI__builtin_ia32_selectps_128:
13992   case X86::BI__builtin_ia32_selectps_256:
13993   case X86::BI__builtin_ia32_selectps_512:
13994   case X86::BI__builtin_ia32_selectpd_128:
13995   case X86::BI__builtin_ia32_selectpd_256:
13996   case X86::BI__builtin_ia32_selectpd_512:
13997     return EmitX86Select(*this, Ops[0], Ops[1], Ops[2]);
13998   case X86::BI__builtin_ia32_selectsh_128:
13999   case X86::BI__builtin_ia32_selectss_128:
14000   case X86::BI__builtin_ia32_selectsd_128: {
14001     Value *A = Builder.CreateExtractElement(Ops[1], (uint64_t)0);
14002     Value *B = Builder.CreateExtractElement(Ops[2], (uint64_t)0);
14003     A = EmitX86ScalarSelect(*this, Ops[0], A, B);
14004     return Builder.CreateInsertElement(Ops[1], A, (uint64_t)0);
14005   }
14006   case X86::BI__builtin_ia32_cmpb128_mask:
14007   case X86::BI__builtin_ia32_cmpb256_mask:
14008   case X86::BI__builtin_ia32_cmpb512_mask:
14009   case X86::BI__builtin_ia32_cmpw128_mask:
14010   case X86::BI__builtin_ia32_cmpw256_mask:
14011   case X86::BI__builtin_ia32_cmpw512_mask:
14012   case X86::BI__builtin_ia32_cmpd128_mask:
14013   case X86::BI__builtin_ia32_cmpd256_mask:
14014   case X86::BI__builtin_ia32_cmpd512_mask:
14015   case X86::BI__builtin_ia32_cmpq128_mask:
14016   case X86::BI__builtin_ia32_cmpq256_mask:
14017   case X86::BI__builtin_ia32_cmpq512_mask: {
14018     unsigned CC = cast<llvm::ConstantInt>(Ops[2])->getZExtValue() & 0x7;
14019     return EmitX86MaskedCompare(*this, CC, true, Ops);
14020   }
14021   case X86::BI__builtin_ia32_ucmpb128_mask:
14022   case X86::BI__builtin_ia32_ucmpb256_mask:
14023   case X86::BI__builtin_ia32_ucmpb512_mask:
14024   case X86::BI__builtin_ia32_ucmpw128_mask:
14025   case X86::BI__builtin_ia32_ucmpw256_mask:
14026   case X86::BI__builtin_ia32_ucmpw512_mask:
14027   case X86::BI__builtin_ia32_ucmpd128_mask:
14028   case X86::BI__builtin_ia32_ucmpd256_mask:
14029   case X86::BI__builtin_ia32_ucmpd512_mask:
14030   case X86::BI__builtin_ia32_ucmpq128_mask:
14031   case X86::BI__builtin_ia32_ucmpq256_mask:
14032   case X86::BI__builtin_ia32_ucmpq512_mask: {
14033     unsigned CC = cast<llvm::ConstantInt>(Ops[2])->getZExtValue() & 0x7;
14034     return EmitX86MaskedCompare(*this, CC, false, Ops);
14035   }
14036   case X86::BI__builtin_ia32_vpcomb:
14037   case X86::BI__builtin_ia32_vpcomw:
14038   case X86::BI__builtin_ia32_vpcomd:
14039   case X86::BI__builtin_ia32_vpcomq:
14040     return EmitX86vpcom(*this, Ops, true);
14041   case X86::BI__builtin_ia32_vpcomub:
14042   case X86::BI__builtin_ia32_vpcomuw:
14043   case X86::BI__builtin_ia32_vpcomud:
14044   case X86::BI__builtin_ia32_vpcomuq:
14045     return EmitX86vpcom(*this, Ops, false);
14046 
14047   case X86::BI__builtin_ia32_kortestcqi:
14048   case X86::BI__builtin_ia32_kortestchi:
14049   case X86::BI__builtin_ia32_kortestcsi:
14050   case X86::BI__builtin_ia32_kortestcdi: {
14051     Value *Or = EmitX86MaskLogic(*this, Instruction::Or, Ops);
14052     Value *C = llvm::Constant::getAllOnesValue(Ops[0]->getType());
14053     Value *Cmp = Builder.CreateICmpEQ(Or, C);
14054     return Builder.CreateZExt(Cmp, ConvertType(E->getType()));
14055   }
14056   case X86::BI__builtin_ia32_kortestzqi:
14057   case X86::BI__builtin_ia32_kortestzhi:
14058   case X86::BI__builtin_ia32_kortestzsi:
14059   case X86::BI__builtin_ia32_kortestzdi: {
14060     Value *Or = EmitX86MaskLogic(*this, Instruction::Or, Ops);
14061     Value *C = llvm::Constant::getNullValue(Ops[0]->getType());
14062     Value *Cmp = Builder.CreateICmpEQ(Or, C);
14063     return Builder.CreateZExt(Cmp, ConvertType(E->getType()));
14064   }
14065 
14066   case X86::BI__builtin_ia32_ktestcqi:
14067   case X86::BI__builtin_ia32_ktestzqi:
14068   case X86::BI__builtin_ia32_ktestchi:
14069   case X86::BI__builtin_ia32_ktestzhi:
14070   case X86::BI__builtin_ia32_ktestcsi:
14071   case X86::BI__builtin_ia32_ktestzsi:
14072   case X86::BI__builtin_ia32_ktestcdi:
14073   case X86::BI__builtin_ia32_ktestzdi: {
14074     Intrinsic::ID IID;
14075     switch (BuiltinID) {
14076     default: llvm_unreachable("Unsupported intrinsic!");
14077     case X86::BI__builtin_ia32_ktestcqi:
14078       IID = Intrinsic::x86_avx512_ktestc_b;
14079       break;
14080     case X86::BI__builtin_ia32_ktestzqi:
14081       IID = Intrinsic::x86_avx512_ktestz_b;
14082       break;
14083     case X86::BI__builtin_ia32_ktestchi:
14084       IID = Intrinsic::x86_avx512_ktestc_w;
14085       break;
14086     case X86::BI__builtin_ia32_ktestzhi:
14087       IID = Intrinsic::x86_avx512_ktestz_w;
14088       break;
14089     case X86::BI__builtin_ia32_ktestcsi:
14090       IID = Intrinsic::x86_avx512_ktestc_d;
14091       break;
14092     case X86::BI__builtin_ia32_ktestzsi:
14093       IID = Intrinsic::x86_avx512_ktestz_d;
14094       break;
14095     case X86::BI__builtin_ia32_ktestcdi:
14096       IID = Intrinsic::x86_avx512_ktestc_q;
14097       break;
14098     case X86::BI__builtin_ia32_ktestzdi:
14099       IID = Intrinsic::x86_avx512_ktestz_q;
14100       break;
14101     }
14102 
14103     unsigned NumElts = Ops[0]->getType()->getIntegerBitWidth();
14104     Value *LHS = getMaskVecValue(*this, Ops[0], NumElts);
14105     Value *RHS = getMaskVecValue(*this, Ops[1], NumElts);
14106     Function *Intr = CGM.getIntrinsic(IID);
14107     return Builder.CreateCall(Intr, {LHS, RHS});
14108   }
14109 
14110   case X86::BI__builtin_ia32_kaddqi:
14111   case X86::BI__builtin_ia32_kaddhi:
14112   case X86::BI__builtin_ia32_kaddsi:
14113   case X86::BI__builtin_ia32_kadddi: {
14114     Intrinsic::ID IID;
14115     switch (BuiltinID) {
14116     default: llvm_unreachable("Unsupported intrinsic!");
14117     case X86::BI__builtin_ia32_kaddqi:
14118       IID = Intrinsic::x86_avx512_kadd_b;
14119       break;
14120     case X86::BI__builtin_ia32_kaddhi:
14121       IID = Intrinsic::x86_avx512_kadd_w;
14122       break;
14123     case X86::BI__builtin_ia32_kaddsi:
14124       IID = Intrinsic::x86_avx512_kadd_d;
14125       break;
14126     case X86::BI__builtin_ia32_kadddi:
14127       IID = Intrinsic::x86_avx512_kadd_q;
14128       break;
14129     }
14130 
14131     unsigned NumElts = Ops[0]->getType()->getIntegerBitWidth();
14132     Value *LHS = getMaskVecValue(*this, Ops[0], NumElts);
14133     Value *RHS = getMaskVecValue(*this, Ops[1], NumElts);
14134     Function *Intr = CGM.getIntrinsic(IID);
14135     Value *Res = Builder.CreateCall(Intr, {LHS, RHS});
14136     return Builder.CreateBitCast(Res, Ops[0]->getType());
14137   }
14138   case X86::BI__builtin_ia32_kandqi:
14139   case X86::BI__builtin_ia32_kandhi:
14140   case X86::BI__builtin_ia32_kandsi:
14141   case X86::BI__builtin_ia32_kanddi:
14142     return EmitX86MaskLogic(*this, Instruction::And, Ops);
14143   case X86::BI__builtin_ia32_kandnqi:
14144   case X86::BI__builtin_ia32_kandnhi:
14145   case X86::BI__builtin_ia32_kandnsi:
14146   case X86::BI__builtin_ia32_kandndi:
14147     return EmitX86MaskLogic(*this, Instruction::And, Ops, true);
14148   case X86::BI__builtin_ia32_korqi:
14149   case X86::BI__builtin_ia32_korhi:
14150   case X86::BI__builtin_ia32_korsi:
14151   case X86::BI__builtin_ia32_kordi:
14152     return EmitX86MaskLogic(*this, Instruction::Or, Ops);
14153   case X86::BI__builtin_ia32_kxnorqi:
14154   case X86::BI__builtin_ia32_kxnorhi:
14155   case X86::BI__builtin_ia32_kxnorsi:
14156   case X86::BI__builtin_ia32_kxnordi:
14157     return EmitX86MaskLogic(*this, Instruction::Xor, Ops, true);
14158   case X86::BI__builtin_ia32_kxorqi:
14159   case X86::BI__builtin_ia32_kxorhi:
14160   case X86::BI__builtin_ia32_kxorsi:
14161   case X86::BI__builtin_ia32_kxordi:
14162     return EmitX86MaskLogic(*this, Instruction::Xor,  Ops);
14163   case X86::BI__builtin_ia32_knotqi:
14164   case X86::BI__builtin_ia32_knothi:
14165   case X86::BI__builtin_ia32_knotsi:
14166   case X86::BI__builtin_ia32_knotdi: {
14167     unsigned NumElts = Ops[0]->getType()->getIntegerBitWidth();
14168     Value *Res = getMaskVecValue(*this, Ops[0], NumElts);
14169     return Builder.CreateBitCast(Builder.CreateNot(Res),
14170                                  Ops[0]->getType());
14171   }
14172   case X86::BI__builtin_ia32_kmovb:
14173   case X86::BI__builtin_ia32_kmovw:
14174   case X86::BI__builtin_ia32_kmovd:
14175   case X86::BI__builtin_ia32_kmovq: {
14176     // Bitcast to vXi1 type and then back to integer. This gets the mask
14177     // register type into the IR, but might be optimized out depending on
14178     // what's around it.
14179     unsigned NumElts = Ops[0]->getType()->getIntegerBitWidth();
14180     Value *Res = getMaskVecValue(*this, Ops[0], NumElts);
14181     return Builder.CreateBitCast(Res, Ops[0]->getType());
14182   }
14183 
14184   case X86::BI__builtin_ia32_kunpckdi:
14185   case X86::BI__builtin_ia32_kunpcksi:
14186   case X86::BI__builtin_ia32_kunpckhi: {
14187     unsigned NumElts = Ops[0]->getType()->getIntegerBitWidth();
14188     Value *LHS = getMaskVecValue(*this, Ops[0], NumElts);
14189     Value *RHS = getMaskVecValue(*this, Ops[1], NumElts);
14190     int Indices[64];
14191     for (unsigned i = 0; i != NumElts; ++i)
14192       Indices[i] = i;
14193 
14194     // First extract half of each vector. This gives better codegen than
14195     // doing it in a single shuffle.
14196     LHS = Builder.CreateShuffleVector(LHS, LHS,
14197                                       makeArrayRef(Indices, NumElts / 2));
14198     RHS = Builder.CreateShuffleVector(RHS, RHS,
14199                                       makeArrayRef(Indices, NumElts / 2));
14200     // Concat the vectors.
14201     // NOTE: Operands are swapped to match the intrinsic definition.
14202     Value *Res = Builder.CreateShuffleVector(RHS, LHS,
14203                                              makeArrayRef(Indices, NumElts));
14204     return Builder.CreateBitCast(Res, Ops[0]->getType());
14205   }
14206 
14207   case X86::BI__builtin_ia32_vplzcntd_128:
14208   case X86::BI__builtin_ia32_vplzcntd_256:
14209   case X86::BI__builtin_ia32_vplzcntd_512:
14210   case X86::BI__builtin_ia32_vplzcntq_128:
14211   case X86::BI__builtin_ia32_vplzcntq_256:
14212   case X86::BI__builtin_ia32_vplzcntq_512: {
14213     Function *F = CGM.getIntrinsic(Intrinsic::ctlz, Ops[0]->getType());
14214     return Builder.CreateCall(F, {Ops[0],Builder.getInt1(false)});
14215   }
14216   case X86::BI__builtin_ia32_sqrtss:
14217   case X86::BI__builtin_ia32_sqrtsd: {
14218     Value *A = Builder.CreateExtractElement(Ops[0], (uint64_t)0);
14219     Function *F;
14220     if (Builder.getIsFPConstrained()) {
14221       CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
14222       F = CGM.getIntrinsic(Intrinsic::experimental_constrained_sqrt,
14223                            A->getType());
14224       A = Builder.CreateConstrainedFPCall(F, {A});
14225     } else {
14226       F = CGM.getIntrinsic(Intrinsic::sqrt, A->getType());
14227       A = Builder.CreateCall(F, {A});
14228     }
14229     return Builder.CreateInsertElement(Ops[0], A, (uint64_t)0);
14230   }
14231   case X86::BI__builtin_ia32_sqrtsh_round_mask:
14232   case X86::BI__builtin_ia32_sqrtsd_round_mask:
14233   case X86::BI__builtin_ia32_sqrtss_round_mask: {
14234     unsigned CC = cast<llvm::ConstantInt>(Ops[4])->getZExtValue();
14235     // Support only if the rounding mode is 4 (AKA CUR_DIRECTION),
14236     // otherwise keep the intrinsic.
14237     if (CC != 4) {
14238       Intrinsic::ID IID;
14239 
14240       switch (BuiltinID) {
14241       default:
14242         llvm_unreachable("Unsupported intrinsic!");
14243       case X86::BI__builtin_ia32_sqrtsh_round_mask:
14244         IID = Intrinsic::x86_avx512fp16_mask_sqrt_sh;
14245         break;
14246       case X86::BI__builtin_ia32_sqrtsd_round_mask:
14247         IID = Intrinsic::x86_avx512_mask_sqrt_sd;
14248         break;
14249       case X86::BI__builtin_ia32_sqrtss_round_mask:
14250         IID = Intrinsic::x86_avx512_mask_sqrt_ss;
14251         break;
14252       }
14253       return Builder.CreateCall(CGM.getIntrinsic(IID), Ops);
14254     }
14255     Value *A = Builder.CreateExtractElement(Ops[1], (uint64_t)0);
14256     Function *F;
14257     if (Builder.getIsFPConstrained()) {
14258       CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
14259       F = CGM.getIntrinsic(Intrinsic::experimental_constrained_sqrt,
14260                            A->getType());
14261       A = Builder.CreateConstrainedFPCall(F, A);
14262     } else {
14263       F = CGM.getIntrinsic(Intrinsic::sqrt, A->getType());
14264       A = Builder.CreateCall(F, A);
14265     }
14266     Value *Src = Builder.CreateExtractElement(Ops[2], (uint64_t)0);
14267     A = EmitX86ScalarSelect(*this, Ops[3], A, Src);
14268     return Builder.CreateInsertElement(Ops[0], A, (uint64_t)0);
14269   }
14270   case X86::BI__builtin_ia32_sqrtpd256:
14271   case X86::BI__builtin_ia32_sqrtpd:
14272   case X86::BI__builtin_ia32_sqrtps256:
14273   case X86::BI__builtin_ia32_sqrtps:
14274   case X86::BI__builtin_ia32_sqrtph256:
14275   case X86::BI__builtin_ia32_sqrtph:
14276   case X86::BI__builtin_ia32_sqrtph512:
14277   case X86::BI__builtin_ia32_sqrtps512:
14278   case X86::BI__builtin_ia32_sqrtpd512: {
14279     if (Ops.size() == 2) {
14280       unsigned CC = cast<llvm::ConstantInt>(Ops[1])->getZExtValue();
14281       // Support only if the rounding mode is 4 (AKA CUR_DIRECTION),
14282       // otherwise keep the intrinsic.
14283       if (CC != 4) {
14284         Intrinsic::ID IID;
14285 
14286         switch (BuiltinID) {
14287         default:
14288           llvm_unreachable("Unsupported intrinsic!");
14289         case X86::BI__builtin_ia32_sqrtph512:
14290           IID = Intrinsic::x86_avx512fp16_sqrt_ph_512;
14291           break;
14292         case X86::BI__builtin_ia32_sqrtps512:
14293           IID = Intrinsic::x86_avx512_sqrt_ps_512;
14294           break;
14295         case X86::BI__builtin_ia32_sqrtpd512:
14296           IID = Intrinsic::x86_avx512_sqrt_pd_512;
14297           break;
14298         }
14299         return Builder.CreateCall(CGM.getIntrinsic(IID), Ops);
14300       }
14301     }
14302     if (Builder.getIsFPConstrained()) {
14303       CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
14304       Function *F = CGM.getIntrinsic(Intrinsic::experimental_constrained_sqrt,
14305                                      Ops[0]->getType());
14306       return Builder.CreateConstrainedFPCall(F, Ops[0]);
14307     } else {
14308       Function *F = CGM.getIntrinsic(Intrinsic::sqrt, Ops[0]->getType());
14309       return Builder.CreateCall(F, Ops[0]);
14310     }
14311   }
14312 
14313   case X86::BI__builtin_ia32_pmuludq128:
14314   case X86::BI__builtin_ia32_pmuludq256:
14315   case X86::BI__builtin_ia32_pmuludq512:
14316     return EmitX86Muldq(*this, /*IsSigned*/false, Ops);
14317 
14318   case X86::BI__builtin_ia32_pmuldq128:
14319   case X86::BI__builtin_ia32_pmuldq256:
14320   case X86::BI__builtin_ia32_pmuldq512:
14321     return EmitX86Muldq(*this, /*IsSigned*/true, Ops);
14322 
14323   case X86::BI__builtin_ia32_pternlogd512_mask:
14324   case X86::BI__builtin_ia32_pternlogq512_mask:
14325   case X86::BI__builtin_ia32_pternlogd128_mask:
14326   case X86::BI__builtin_ia32_pternlogd256_mask:
14327   case X86::BI__builtin_ia32_pternlogq128_mask:
14328   case X86::BI__builtin_ia32_pternlogq256_mask:
14329     return EmitX86Ternlog(*this, /*ZeroMask*/false, Ops);
14330 
14331   case X86::BI__builtin_ia32_pternlogd512_maskz:
14332   case X86::BI__builtin_ia32_pternlogq512_maskz:
14333   case X86::BI__builtin_ia32_pternlogd128_maskz:
14334   case X86::BI__builtin_ia32_pternlogd256_maskz:
14335   case X86::BI__builtin_ia32_pternlogq128_maskz:
14336   case X86::BI__builtin_ia32_pternlogq256_maskz:
14337     return EmitX86Ternlog(*this, /*ZeroMask*/true, Ops);
14338 
14339   case X86::BI__builtin_ia32_vpshldd128:
14340   case X86::BI__builtin_ia32_vpshldd256:
14341   case X86::BI__builtin_ia32_vpshldd512:
14342   case X86::BI__builtin_ia32_vpshldq128:
14343   case X86::BI__builtin_ia32_vpshldq256:
14344   case X86::BI__builtin_ia32_vpshldq512:
14345   case X86::BI__builtin_ia32_vpshldw128:
14346   case X86::BI__builtin_ia32_vpshldw256:
14347   case X86::BI__builtin_ia32_vpshldw512:
14348     return EmitX86FunnelShift(*this, Ops[0], Ops[1], Ops[2], false);
14349 
14350   case X86::BI__builtin_ia32_vpshrdd128:
14351   case X86::BI__builtin_ia32_vpshrdd256:
14352   case X86::BI__builtin_ia32_vpshrdd512:
14353   case X86::BI__builtin_ia32_vpshrdq128:
14354   case X86::BI__builtin_ia32_vpshrdq256:
14355   case X86::BI__builtin_ia32_vpshrdq512:
14356   case X86::BI__builtin_ia32_vpshrdw128:
14357   case X86::BI__builtin_ia32_vpshrdw256:
14358   case X86::BI__builtin_ia32_vpshrdw512:
14359     // Ops 0 and 1 are swapped.
14360     return EmitX86FunnelShift(*this, Ops[1], Ops[0], Ops[2], true);
14361 
14362   case X86::BI__builtin_ia32_vpshldvd128:
14363   case X86::BI__builtin_ia32_vpshldvd256:
14364   case X86::BI__builtin_ia32_vpshldvd512:
14365   case X86::BI__builtin_ia32_vpshldvq128:
14366   case X86::BI__builtin_ia32_vpshldvq256:
14367   case X86::BI__builtin_ia32_vpshldvq512:
14368   case X86::BI__builtin_ia32_vpshldvw128:
14369   case X86::BI__builtin_ia32_vpshldvw256:
14370   case X86::BI__builtin_ia32_vpshldvw512:
14371     return EmitX86FunnelShift(*this, Ops[0], Ops[1], Ops[2], false);
14372 
14373   case X86::BI__builtin_ia32_vpshrdvd128:
14374   case X86::BI__builtin_ia32_vpshrdvd256:
14375   case X86::BI__builtin_ia32_vpshrdvd512:
14376   case X86::BI__builtin_ia32_vpshrdvq128:
14377   case X86::BI__builtin_ia32_vpshrdvq256:
14378   case X86::BI__builtin_ia32_vpshrdvq512:
14379   case X86::BI__builtin_ia32_vpshrdvw128:
14380   case X86::BI__builtin_ia32_vpshrdvw256:
14381   case X86::BI__builtin_ia32_vpshrdvw512:
14382     // Ops 0 and 1 are swapped.
14383     return EmitX86FunnelShift(*this, Ops[1], Ops[0], Ops[2], true);
14384 
14385   // Reductions
14386   case X86::BI__builtin_ia32_reduce_add_d512:
14387   case X86::BI__builtin_ia32_reduce_add_q512: {
14388     Function *F =
14389         CGM.getIntrinsic(Intrinsic::vector_reduce_add, Ops[0]->getType());
14390     return Builder.CreateCall(F, {Ops[0]});
14391   }
14392   case X86::BI__builtin_ia32_reduce_fadd_pd512:
14393   case X86::BI__builtin_ia32_reduce_fadd_ps512:
14394   case X86::BI__builtin_ia32_reduce_fadd_ph512:
14395   case X86::BI__builtin_ia32_reduce_fadd_ph256:
14396   case X86::BI__builtin_ia32_reduce_fadd_ph128: {
14397     Function *F =
14398         CGM.getIntrinsic(Intrinsic::vector_reduce_fadd, Ops[1]->getType());
14399     Builder.getFastMathFlags().setAllowReassoc();
14400     return Builder.CreateCall(F, {Ops[0], Ops[1]});
14401   }
14402   case X86::BI__builtin_ia32_reduce_fmul_pd512:
14403   case X86::BI__builtin_ia32_reduce_fmul_ps512:
14404   case X86::BI__builtin_ia32_reduce_fmul_ph512:
14405   case X86::BI__builtin_ia32_reduce_fmul_ph256:
14406   case X86::BI__builtin_ia32_reduce_fmul_ph128: {
14407     Function *F =
14408         CGM.getIntrinsic(Intrinsic::vector_reduce_fmul, Ops[1]->getType());
14409     Builder.getFastMathFlags().setAllowReassoc();
14410     return Builder.CreateCall(F, {Ops[0], Ops[1]});
14411   }
14412   case X86::BI__builtin_ia32_reduce_fmax_pd512:
14413   case X86::BI__builtin_ia32_reduce_fmax_ps512:
14414   case X86::BI__builtin_ia32_reduce_fmax_ph512:
14415   case X86::BI__builtin_ia32_reduce_fmax_ph256:
14416   case X86::BI__builtin_ia32_reduce_fmax_ph128: {
14417     Function *F =
14418         CGM.getIntrinsic(Intrinsic::vector_reduce_fmax, Ops[0]->getType());
14419     Builder.getFastMathFlags().setNoNaNs();
14420     return Builder.CreateCall(F, {Ops[0]});
14421   }
14422   case X86::BI__builtin_ia32_reduce_fmin_pd512:
14423   case X86::BI__builtin_ia32_reduce_fmin_ps512:
14424   case X86::BI__builtin_ia32_reduce_fmin_ph512:
14425   case X86::BI__builtin_ia32_reduce_fmin_ph256:
14426   case X86::BI__builtin_ia32_reduce_fmin_ph128: {
14427     Function *F =
14428         CGM.getIntrinsic(Intrinsic::vector_reduce_fmin, Ops[0]->getType());
14429     Builder.getFastMathFlags().setNoNaNs();
14430     return Builder.CreateCall(F, {Ops[0]});
14431   }
14432   case X86::BI__builtin_ia32_reduce_mul_d512:
14433   case X86::BI__builtin_ia32_reduce_mul_q512: {
14434     Function *F =
14435         CGM.getIntrinsic(Intrinsic::vector_reduce_mul, Ops[0]->getType());
14436     return Builder.CreateCall(F, {Ops[0]});
14437   }
14438 
14439   // 3DNow!
14440   case X86::BI__builtin_ia32_pswapdsf:
14441   case X86::BI__builtin_ia32_pswapdsi: {
14442     llvm::Type *MMXTy = llvm::Type::getX86_MMXTy(getLLVMContext());
14443     Ops[0] = Builder.CreateBitCast(Ops[0], MMXTy, "cast");
14444     llvm::Function *F = CGM.getIntrinsic(Intrinsic::x86_3dnowa_pswapd);
14445     return Builder.CreateCall(F, Ops, "pswapd");
14446   }
14447   case X86::BI__builtin_ia32_rdrand16_step:
14448   case X86::BI__builtin_ia32_rdrand32_step:
14449   case X86::BI__builtin_ia32_rdrand64_step:
14450   case X86::BI__builtin_ia32_rdseed16_step:
14451   case X86::BI__builtin_ia32_rdseed32_step:
14452   case X86::BI__builtin_ia32_rdseed64_step: {
14453     Intrinsic::ID ID;
14454     switch (BuiltinID) {
14455     default: llvm_unreachable("Unsupported intrinsic!");
14456     case X86::BI__builtin_ia32_rdrand16_step:
14457       ID = Intrinsic::x86_rdrand_16;
14458       break;
14459     case X86::BI__builtin_ia32_rdrand32_step:
14460       ID = Intrinsic::x86_rdrand_32;
14461       break;
14462     case X86::BI__builtin_ia32_rdrand64_step:
14463       ID = Intrinsic::x86_rdrand_64;
14464       break;
14465     case X86::BI__builtin_ia32_rdseed16_step:
14466       ID = Intrinsic::x86_rdseed_16;
14467       break;
14468     case X86::BI__builtin_ia32_rdseed32_step:
14469       ID = Intrinsic::x86_rdseed_32;
14470       break;
14471     case X86::BI__builtin_ia32_rdseed64_step:
14472       ID = Intrinsic::x86_rdseed_64;
14473       break;
14474     }
14475 
14476     Value *Call = Builder.CreateCall(CGM.getIntrinsic(ID));
14477     Builder.CreateDefaultAlignedStore(Builder.CreateExtractValue(Call, 0),
14478                                       Ops[0]);
14479     return Builder.CreateExtractValue(Call, 1);
14480   }
14481   case X86::BI__builtin_ia32_addcarryx_u32:
14482   case X86::BI__builtin_ia32_addcarryx_u64:
14483   case X86::BI__builtin_ia32_subborrow_u32:
14484   case X86::BI__builtin_ia32_subborrow_u64: {
14485     Intrinsic::ID IID;
14486     switch (BuiltinID) {
14487     default: llvm_unreachable("Unsupported intrinsic!");
14488     case X86::BI__builtin_ia32_addcarryx_u32:
14489       IID = Intrinsic::x86_addcarry_32;
14490       break;
14491     case X86::BI__builtin_ia32_addcarryx_u64:
14492       IID = Intrinsic::x86_addcarry_64;
14493       break;
14494     case X86::BI__builtin_ia32_subborrow_u32:
14495       IID = Intrinsic::x86_subborrow_32;
14496       break;
14497     case X86::BI__builtin_ia32_subborrow_u64:
14498       IID = Intrinsic::x86_subborrow_64;
14499       break;
14500     }
14501 
14502     Value *Call = Builder.CreateCall(CGM.getIntrinsic(IID),
14503                                      { Ops[0], Ops[1], Ops[2] });
14504     Builder.CreateDefaultAlignedStore(Builder.CreateExtractValue(Call, 1),
14505                                       Ops[3]);
14506     return Builder.CreateExtractValue(Call, 0);
14507   }
14508 
14509   case X86::BI__builtin_ia32_fpclassps128_mask:
14510   case X86::BI__builtin_ia32_fpclassps256_mask:
14511   case X86::BI__builtin_ia32_fpclassps512_mask:
14512   case X86::BI__builtin_ia32_fpclassph128_mask:
14513   case X86::BI__builtin_ia32_fpclassph256_mask:
14514   case X86::BI__builtin_ia32_fpclassph512_mask:
14515   case X86::BI__builtin_ia32_fpclasspd128_mask:
14516   case X86::BI__builtin_ia32_fpclasspd256_mask:
14517   case X86::BI__builtin_ia32_fpclasspd512_mask: {
14518     unsigned NumElts =
14519         cast<llvm::FixedVectorType>(Ops[0]->getType())->getNumElements();
14520     Value *MaskIn = Ops[2];
14521     Ops.erase(&Ops[2]);
14522 
14523     Intrinsic::ID ID;
14524     switch (BuiltinID) {
14525     default: llvm_unreachable("Unsupported intrinsic!");
14526     case X86::BI__builtin_ia32_fpclassph128_mask:
14527       ID = Intrinsic::x86_avx512fp16_fpclass_ph_128;
14528       break;
14529     case X86::BI__builtin_ia32_fpclassph256_mask:
14530       ID = Intrinsic::x86_avx512fp16_fpclass_ph_256;
14531       break;
14532     case X86::BI__builtin_ia32_fpclassph512_mask:
14533       ID = Intrinsic::x86_avx512fp16_fpclass_ph_512;
14534       break;
14535     case X86::BI__builtin_ia32_fpclassps128_mask:
14536       ID = Intrinsic::x86_avx512_fpclass_ps_128;
14537       break;
14538     case X86::BI__builtin_ia32_fpclassps256_mask:
14539       ID = Intrinsic::x86_avx512_fpclass_ps_256;
14540       break;
14541     case X86::BI__builtin_ia32_fpclassps512_mask:
14542       ID = Intrinsic::x86_avx512_fpclass_ps_512;
14543       break;
14544     case X86::BI__builtin_ia32_fpclasspd128_mask:
14545       ID = Intrinsic::x86_avx512_fpclass_pd_128;
14546       break;
14547     case X86::BI__builtin_ia32_fpclasspd256_mask:
14548       ID = Intrinsic::x86_avx512_fpclass_pd_256;
14549       break;
14550     case X86::BI__builtin_ia32_fpclasspd512_mask:
14551       ID = Intrinsic::x86_avx512_fpclass_pd_512;
14552       break;
14553     }
14554 
14555     Value *Fpclass = Builder.CreateCall(CGM.getIntrinsic(ID), Ops);
14556     return EmitX86MaskedCompareResult(*this, Fpclass, NumElts, MaskIn);
14557   }
14558 
14559   case X86::BI__builtin_ia32_vp2intersect_q_512:
14560   case X86::BI__builtin_ia32_vp2intersect_q_256:
14561   case X86::BI__builtin_ia32_vp2intersect_q_128:
14562   case X86::BI__builtin_ia32_vp2intersect_d_512:
14563   case X86::BI__builtin_ia32_vp2intersect_d_256:
14564   case X86::BI__builtin_ia32_vp2intersect_d_128: {
14565     unsigned NumElts =
14566         cast<llvm::FixedVectorType>(Ops[0]->getType())->getNumElements();
14567     Intrinsic::ID ID;
14568 
14569     switch (BuiltinID) {
14570     default: llvm_unreachable("Unsupported intrinsic!");
14571     case X86::BI__builtin_ia32_vp2intersect_q_512:
14572       ID = Intrinsic::x86_avx512_vp2intersect_q_512;
14573       break;
14574     case X86::BI__builtin_ia32_vp2intersect_q_256:
14575       ID = Intrinsic::x86_avx512_vp2intersect_q_256;
14576       break;
14577     case X86::BI__builtin_ia32_vp2intersect_q_128:
14578       ID = Intrinsic::x86_avx512_vp2intersect_q_128;
14579       break;
14580     case X86::BI__builtin_ia32_vp2intersect_d_512:
14581       ID = Intrinsic::x86_avx512_vp2intersect_d_512;
14582       break;
14583     case X86::BI__builtin_ia32_vp2intersect_d_256:
14584       ID = Intrinsic::x86_avx512_vp2intersect_d_256;
14585       break;
14586     case X86::BI__builtin_ia32_vp2intersect_d_128:
14587       ID = Intrinsic::x86_avx512_vp2intersect_d_128;
14588       break;
14589     }
14590 
14591     Value *Call = Builder.CreateCall(CGM.getIntrinsic(ID), {Ops[0], Ops[1]});
14592     Value *Result = Builder.CreateExtractValue(Call, 0);
14593     Result = EmitX86MaskedCompareResult(*this, Result, NumElts, nullptr);
14594     Builder.CreateDefaultAlignedStore(Result, Ops[2]);
14595 
14596     Result = Builder.CreateExtractValue(Call, 1);
14597     Result = EmitX86MaskedCompareResult(*this, Result, NumElts, nullptr);
14598     return Builder.CreateDefaultAlignedStore(Result, Ops[3]);
14599   }
14600 
14601   case X86::BI__builtin_ia32_vpmultishiftqb128:
14602   case X86::BI__builtin_ia32_vpmultishiftqb256:
14603   case X86::BI__builtin_ia32_vpmultishiftqb512: {
14604     Intrinsic::ID ID;
14605     switch (BuiltinID) {
14606     default: llvm_unreachable("Unsupported intrinsic!");
14607     case X86::BI__builtin_ia32_vpmultishiftqb128:
14608       ID = Intrinsic::x86_avx512_pmultishift_qb_128;
14609       break;
14610     case X86::BI__builtin_ia32_vpmultishiftqb256:
14611       ID = Intrinsic::x86_avx512_pmultishift_qb_256;
14612       break;
14613     case X86::BI__builtin_ia32_vpmultishiftqb512:
14614       ID = Intrinsic::x86_avx512_pmultishift_qb_512;
14615       break;
14616     }
14617 
14618     return Builder.CreateCall(CGM.getIntrinsic(ID), Ops);
14619   }
14620 
14621   case X86::BI__builtin_ia32_vpshufbitqmb128_mask:
14622   case X86::BI__builtin_ia32_vpshufbitqmb256_mask:
14623   case X86::BI__builtin_ia32_vpshufbitqmb512_mask: {
14624     unsigned NumElts =
14625         cast<llvm::FixedVectorType>(Ops[0]->getType())->getNumElements();
14626     Value *MaskIn = Ops[2];
14627     Ops.erase(&Ops[2]);
14628 
14629     Intrinsic::ID ID;
14630     switch (BuiltinID) {
14631     default: llvm_unreachable("Unsupported intrinsic!");
14632     case X86::BI__builtin_ia32_vpshufbitqmb128_mask:
14633       ID = Intrinsic::x86_avx512_vpshufbitqmb_128;
14634       break;
14635     case X86::BI__builtin_ia32_vpshufbitqmb256_mask:
14636       ID = Intrinsic::x86_avx512_vpshufbitqmb_256;
14637       break;
14638     case X86::BI__builtin_ia32_vpshufbitqmb512_mask:
14639       ID = Intrinsic::x86_avx512_vpshufbitqmb_512;
14640       break;
14641     }
14642 
14643     Value *Shufbit = Builder.CreateCall(CGM.getIntrinsic(ID), Ops);
14644     return EmitX86MaskedCompareResult(*this, Shufbit, NumElts, MaskIn);
14645   }
14646 
14647   // packed comparison intrinsics
14648   case X86::BI__builtin_ia32_cmpeqps:
14649   case X86::BI__builtin_ia32_cmpeqpd:
14650     return getVectorFCmpIR(CmpInst::FCMP_OEQ, /*IsSignaling*/false);
14651   case X86::BI__builtin_ia32_cmpltps:
14652   case X86::BI__builtin_ia32_cmpltpd:
14653     return getVectorFCmpIR(CmpInst::FCMP_OLT, /*IsSignaling*/true);
14654   case X86::BI__builtin_ia32_cmpleps:
14655   case X86::BI__builtin_ia32_cmplepd:
14656     return getVectorFCmpIR(CmpInst::FCMP_OLE, /*IsSignaling*/true);
14657   case X86::BI__builtin_ia32_cmpunordps:
14658   case X86::BI__builtin_ia32_cmpunordpd:
14659     return getVectorFCmpIR(CmpInst::FCMP_UNO, /*IsSignaling*/false);
14660   case X86::BI__builtin_ia32_cmpneqps:
14661   case X86::BI__builtin_ia32_cmpneqpd:
14662     return getVectorFCmpIR(CmpInst::FCMP_UNE, /*IsSignaling*/false);
14663   case X86::BI__builtin_ia32_cmpnltps:
14664   case X86::BI__builtin_ia32_cmpnltpd:
14665     return getVectorFCmpIR(CmpInst::FCMP_UGE, /*IsSignaling*/true);
14666   case X86::BI__builtin_ia32_cmpnleps:
14667   case X86::BI__builtin_ia32_cmpnlepd:
14668     return getVectorFCmpIR(CmpInst::FCMP_UGT, /*IsSignaling*/true);
14669   case X86::BI__builtin_ia32_cmpordps:
14670   case X86::BI__builtin_ia32_cmpordpd:
14671     return getVectorFCmpIR(CmpInst::FCMP_ORD, /*IsSignaling*/false);
14672   case X86::BI__builtin_ia32_cmpph128_mask:
14673   case X86::BI__builtin_ia32_cmpph256_mask:
14674   case X86::BI__builtin_ia32_cmpph512_mask:
14675   case X86::BI__builtin_ia32_cmpps128_mask:
14676   case X86::BI__builtin_ia32_cmpps256_mask:
14677   case X86::BI__builtin_ia32_cmpps512_mask:
14678   case X86::BI__builtin_ia32_cmppd128_mask:
14679   case X86::BI__builtin_ia32_cmppd256_mask:
14680   case X86::BI__builtin_ia32_cmppd512_mask:
14681     IsMaskFCmp = true;
14682     LLVM_FALLTHROUGH;
14683   case X86::BI__builtin_ia32_cmpps:
14684   case X86::BI__builtin_ia32_cmpps256:
14685   case X86::BI__builtin_ia32_cmppd:
14686   case X86::BI__builtin_ia32_cmppd256: {
14687     // Lowering vector comparisons to fcmp instructions, while
14688     // ignoring signalling behaviour requested
14689     // ignoring rounding mode requested
14690     // This is only possible if fp-model is not strict and FENV_ACCESS is off.
14691 
14692     // The third argument is the comparison condition, and integer in the
14693     // range [0, 31]
14694     unsigned CC = cast<llvm::ConstantInt>(Ops[2])->getZExtValue() & 0x1f;
14695 
14696     // Lowering to IR fcmp instruction.
14697     // Ignoring requested signaling behaviour,
14698     // e.g. both _CMP_GT_OS & _CMP_GT_OQ are translated to FCMP_OGT.
14699     FCmpInst::Predicate Pred;
14700     bool IsSignaling;
14701     // Predicates for 16-31 repeat the 0-15 predicates. Only the signalling
14702     // behavior is inverted. We'll handle that after the switch.
14703     switch (CC & 0xf) {
14704     case 0x00: Pred = FCmpInst::FCMP_OEQ;   IsSignaling = false; break;
14705     case 0x01: Pred = FCmpInst::FCMP_OLT;   IsSignaling = true;  break;
14706     case 0x02: Pred = FCmpInst::FCMP_OLE;   IsSignaling = true;  break;
14707     case 0x03: Pred = FCmpInst::FCMP_UNO;   IsSignaling = false; break;
14708     case 0x04: Pred = FCmpInst::FCMP_UNE;   IsSignaling = false; break;
14709     case 0x05: Pred = FCmpInst::FCMP_UGE;   IsSignaling = true;  break;
14710     case 0x06: Pred = FCmpInst::FCMP_UGT;   IsSignaling = true;  break;
14711     case 0x07: Pred = FCmpInst::FCMP_ORD;   IsSignaling = false; break;
14712     case 0x08: Pred = FCmpInst::FCMP_UEQ;   IsSignaling = false; break;
14713     case 0x09: Pred = FCmpInst::FCMP_ULT;   IsSignaling = true;  break;
14714     case 0x0a: Pred = FCmpInst::FCMP_ULE;   IsSignaling = true;  break;
14715     case 0x0b: Pred = FCmpInst::FCMP_FALSE; IsSignaling = false; break;
14716     case 0x0c: Pred = FCmpInst::FCMP_ONE;   IsSignaling = false; break;
14717     case 0x0d: Pred = FCmpInst::FCMP_OGE;   IsSignaling = true;  break;
14718     case 0x0e: Pred = FCmpInst::FCMP_OGT;   IsSignaling = true;  break;
14719     case 0x0f: Pred = FCmpInst::FCMP_TRUE;  IsSignaling = false; break;
14720     default: llvm_unreachable("Unhandled CC");
14721     }
14722 
14723     // Invert the signalling behavior for 16-31.
14724     if (CC & 0x10)
14725       IsSignaling = !IsSignaling;
14726 
14727     // If the predicate is true or false and we're using constrained intrinsics,
14728     // we don't have a compare intrinsic we can use. Just use the legacy X86
14729     // specific intrinsic.
14730     // If the intrinsic is mask enabled and we're using constrained intrinsics,
14731     // use the legacy X86 specific intrinsic.
14732     if (Builder.getIsFPConstrained() &&
14733         (Pred == FCmpInst::FCMP_TRUE || Pred == FCmpInst::FCMP_FALSE ||
14734          IsMaskFCmp)) {
14735 
14736       Intrinsic::ID IID;
14737       switch (BuiltinID) {
14738       default: llvm_unreachable("Unexpected builtin");
14739       case X86::BI__builtin_ia32_cmpps:
14740         IID = Intrinsic::x86_sse_cmp_ps;
14741         break;
14742       case X86::BI__builtin_ia32_cmpps256:
14743         IID = Intrinsic::x86_avx_cmp_ps_256;
14744         break;
14745       case X86::BI__builtin_ia32_cmppd:
14746         IID = Intrinsic::x86_sse2_cmp_pd;
14747         break;
14748       case X86::BI__builtin_ia32_cmppd256:
14749         IID = Intrinsic::x86_avx_cmp_pd_256;
14750         break;
14751       case X86::BI__builtin_ia32_cmpps512_mask:
14752         IID = Intrinsic::x86_avx512_mask_cmp_ps_512;
14753         break;
14754       case X86::BI__builtin_ia32_cmppd512_mask:
14755         IID = Intrinsic::x86_avx512_mask_cmp_pd_512;
14756         break;
14757       case X86::BI__builtin_ia32_cmpps128_mask:
14758         IID = Intrinsic::x86_avx512_mask_cmp_ps_128;
14759         break;
14760       case X86::BI__builtin_ia32_cmpps256_mask:
14761         IID = Intrinsic::x86_avx512_mask_cmp_ps_256;
14762         break;
14763       case X86::BI__builtin_ia32_cmppd128_mask:
14764         IID = Intrinsic::x86_avx512_mask_cmp_pd_128;
14765         break;
14766       case X86::BI__builtin_ia32_cmppd256_mask:
14767         IID = Intrinsic::x86_avx512_mask_cmp_pd_256;
14768         break;
14769       }
14770 
14771       Function *Intr = CGM.getIntrinsic(IID);
14772       if (IsMaskFCmp) {
14773         unsigned NumElts =
14774             cast<llvm::FixedVectorType>(Ops[0]->getType())->getNumElements();
14775         Ops[3] = getMaskVecValue(*this, Ops[3], NumElts);
14776         Value *Cmp = Builder.CreateCall(Intr, Ops);
14777         return EmitX86MaskedCompareResult(*this, Cmp, NumElts, nullptr);
14778       }
14779 
14780       return Builder.CreateCall(Intr, Ops);
14781     }
14782 
14783     // Builtins without the _mask suffix return a vector of integers
14784     // of the same width as the input vectors
14785     if (IsMaskFCmp) {
14786       // We ignore SAE if strict FP is disabled. We only keep precise
14787       // exception behavior under strict FP.
14788       // NOTE: If strict FP does ever go through here a CGFPOptionsRAII
14789       // object will be required.
14790       unsigned NumElts =
14791           cast<llvm::FixedVectorType>(Ops[0]->getType())->getNumElements();
14792       Value *Cmp;
14793       if (IsSignaling)
14794         Cmp = Builder.CreateFCmpS(Pred, Ops[0], Ops[1]);
14795       else
14796         Cmp = Builder.CreateFCmp(Pred, Ops[0], Ops[1]);
14797       return EmitX86MaskedCompareResult(*this, Cmp, NumElts, Ops[3]);
14798     }
14799 
14800     return getVectorFCmpIR(Pred, IsSignaling);
14801   }
14802 
14803   // SSE scalar comparison intrinsics
14804   case X86::BI__builtin_ia32_cmpeqss:
14805     return getCmpIntrinsicCall(Intrinsic::x86_sse_cmp_ss, 0);
14806   case X86::BI__builtin_ia32_cmpltss:
14807     return getCmpIntrinsicCall(Intrinsic::x86_sse_cmp_ss, 1);
14808   case X86::BI__builtin_ia32_cmpless:
14809     return getCmpIntrinsicCall(Intrinsic::x86_sse_cmp_ss, 2);
14810   case X86::BI__builtin_ia32_cmpunordss:
14811     return getCmpIntrinsicCall(Intrinsic::x86_sse_cmp_ss, 3);
14812   case X86::BI__builtin_ia32_cmpneqss:
14813     return getCmpIntrinsicCall(Intrinsic::x86_sse_cmp_ss, 4);
14814   case X86::BI__builtin_ia32_cmpnltss:
14815     return getCmpIntrinsicCall(Intrinsic::x86_sse_cmp_ss, 5);
14816   case X86::BI__builtin_ia32_cmpnless:
14817     return getCmpIntrinsicCall(Intrinsic::x86_sse_cmp_ss, 6);
14818   case X86::BI__builtin_ia32_cmpordss:
14819     return getCmpIntrinsicCall(Intrinsic::x86_sse_cmp_ss, 7);
14820   case X86::BI__builtin_ia32_cmpeqsd:
14821     return getCmpIntrinsicCall(Intrinsic::x86_sse2_cmp_sd, 0);
14822   case X86::BI__builtin_ia32_cmpltsd:
14823     return getCmpIntrinsicCall(Intrinsic::x86_sse2_cmp_sd, 1);
14824   case X86::BI__builtin_ia32_cmplesd:
14825     return getCmpIntrinsicCall(Intrinsic::x86_sse2_cmp_sd, 2);
14826   case X86::BI__builtin_ia32_cmpunordsd:
14827     return getCmpIntrinsicCall(Intrinsic::x86_sse2_cmp_sd, 3);
14828   case X86::BI__builtin_ia32_cmpneqsd:
14829     return getCmpIntrinsicCall(Intrinsic::x86_sse2_cmp_sd, 4);
14830   case X86::BI__builtin_ia32_cmpnltsd:
14831     return getCmpIntrinsicCall(Intrinsic::x86_sse2_cmp_sd, 5);
14832   case X86::BI__builtin_ia32_cmpnlesd:
14833     return getCmpIntrinsicCall(Intrinsic::x86_sse2_cmp_sd, 6);
14834   case X86::BI__builtin_ia32_cmpordsd:
14835     return getCmpIntrinsicCall(Intrinsic::x86_sse2_cmp_sd, 7);
14836 
14837   // f16c half2float intrinsics
14838   case X86::BI__builtin_ia32_vcvtph2ps:
14839   case X86::BI__builtin_ia32_vcvtph2ps256:
14840   case X86::BI__builtin_ia32_vcvtph2ps_mask:
14841   case X86::BI__builtin_ia32_vcvtph2ps256_mask:
14842   case X86::BI__builtin_ia32_vcvtph2ps512_mask: {
14843     CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
14844     return EmitX86CvtF16ToFloatExpr(*this, Ops, ConvertType(E->getType()));
14845   }
14846 
14847 // AVX512 bf16 intrinsics
14848   case X86::BI__builtin_ia32_cvtneps2bf16_128_mask: {
14849     Ops[2] = getMaskVecValue(
14850         *this, Ops[2],
14851         cast<llvm::FixedVectorType>(Ops[0]->getType())->getNumElements());
14852     Intrinsic::ID IID = Intrinsic::x86_avx512bf16_mask_cvtneps2bf16_128;
14853     return Builder.CreateCall(CGM.getIntrinsic(IID), Ops);
14854   }
14855   case X86::BI__builtin_ia32_cvtsbf162ss_32:
14856     return EmitX86CvtBF16ToFloatExpr(*this, E, Ops);
14857 
14858   case X86::BI__builtin_ia32_cvtneps2bf16_256_mask:
14859   case X86::BI__builtin_ia32_cvtneps2bf16_512_mask: {
14860     Intrinsic::ID IID;
14861     switch (BuiltinID) {
14862     default: llvm_unreachable("Unsupported intrinsic!");
14863     case X86::BI__builtin_ia32_cvtneps2bf16_256_mask:
14864       IID = Intrinsic::x86_avx512bf16_cvtneps2bf16_256;
14865       break;
14866     case X86::BI__builtin_ia32_cvtneps2bf16_512_mask:
14867       IID = Intrinsic::x86_avx512bf16_cvtneps2bf16_512;
14868       break;
14869     }
14870     Value *Res = Builder.CreateCall(CGM.getIntrinsic(IID), Ops[0]);
14871     return EmitX86Select(*this, Ops[2], Res, Ops[1]);
14872   }
14873 
14874   case X86::BI__emul:
14875   case X86::BI__emulu: {
14876     llvm::Type *Int64Ty = llvm::IntegerType::get(getLLVMContext(), 64);
14877     bool isSigned = (BuiltinID == X86::BI__emul);
14878     Value *LHS = Builder.CreateIntCast(Ops[0], Int64Ty, isSigned);
14879     Value *RHS = Builder.CreateIntCast(Ops[1], Int64Ty, isSigned);
14880     return Builder.CreateMul(LHS, RHS, "", !isSigned, isSigned);
14881   }
14882   case X86::BI__mulh:
14883   case X86::BI__umulh:
14884   case X86::BI_mul128:
14885   case X86::BI_umul128: {
14886     llvm::Type *ResType = ConvertType(E->getType());
14887     llvm::Type *Int128Ty = llvm::IntegerType::get(getLLVMContext(), 128);
14888 
14889     bool IsSigned = (BuiltinID == X86::BI__mulh || BuiltinID == X86::BI_mul128);
14890     Value *LHS = Builder.CreateIntCast(Ops[0], Int128Ty, IsSigned);
14891     Value *RHS = Builder.CreateIntCast(Ops[1], Int128Ty, IsSigned);
14892 
14893     Value *MulResult, *HigherBits;
14894     if (IsSigned) {
14895       MulResult = Builder.CreateNSWMul(LHS, RHS);
14896       HigherBits = Builder.CreateAShr(MulResult, 64);
14897     } else {
14898       MulResult = Builder.CreateNUWMul(LHS, RHS);
14899       HigherBits = Builder.CreateLShr(MulResult, 64);
14900     }
14901     HigherBits = Builder.CreateIntCast(HigherBits, ResType, IsSigned);
14902 
14903     if (BuiltinID == X86::BI__mulh || BuiltinID == X86::BI__umulh)
14904       return HigherBits;
14905 
14906     Address HighBitsAddress = EmitPointerWithAlignment(E->getArg(2));
14907     Builder.CreateStore(HigherBits, HighBitsAddress);
14908     return Builder.CreateIntCast(MulResult, ResType, IsSigned);
14909   }
14910 
14911   case X86::BI__faststorefence: {
14912     return Builder.CreateFence(llvm::AtomicOrdering::SequentiallyConsistent,
14913                                llvm::SyncScope::System);
14914   }
14915   case X86::BI__shiftleft128:
14916   case X86::BI__shiftright128: {
14917     llvm::Function *F = CGM.getIntrinsic(
14918         BuiltinID == X86::BI__shiftleft128 ? Intrinsic::fshl : Intrinsic::fshr,
14919         Int64Ty);
14920     // Flip low/high ops and zero-extend amount to matching type.
14921     // shiftleft128(Low, High, Amt) -> fshl(High, Low, Amt)
14922     // shiftright128(Low, High, Amt) -> fshr(High, Low, Amt)
14923     std::swap(Ops[0], Ops[1]);
14924     Ops[2] = Builder.CreateZExt(Ops[2], Int64Ty);
14925     return Builder.CreateCall(F, Ops);
14926   }
14927   case X86::BI_ReadWriteBarrier:
14928   case X86::BI_ReadBarrier:
14929   case X86::BI_WriteBarrier: {
14930     return Builder.CreateFence(llvm::AtomicOrdering::SequentiallyConsistent,
14931                                llvm::SyncScope::SingleThread);
14932   }
14933 
14934   case X86::BI_AddressOfReturnAddress: {
14935     Function *F =
14936         CGM.getIntrinsic(Intrinsic::addressofreturnaddress, AllocaInt8PtrTy);
14937     return Builder.CreateCall(F);
14938   }
14939   case X86::BI__stosb: {
14940     // We treat __stosb as a volatile memset - it may not generate "rep stosb"
14941     // instruction, but it will create a memset that won't be optimized away.
14942     return Builder.CreateMemSet(Ops[0], Ops[1], Ops[2], Align(1), true);
14943   }
14944   case X86::BI__ud2:
14945     // llvm.trap makes a ud2a instruction on x86.
14946     return EmitTrapCall(Intrinsic::trap);
14947   case X86::BI__int2c: {
14948     // This syscall signals a driver assertion failure in x86 NT kernels.
14949     llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
14950     llvm::InlineAsm *IA =
14951         llvm::InlineAsm::get(FTy, "int $$0x2c", "", /*hasSideEffects=*/true);
14952     llvm::AttributeList NoReturnAttr = llvm::AttributeList::get(
14953         getLLVMContext(), llvm::AttributeList::FunctionIndex,
14954         llvm::Attribute::NoReturn);
14955     llvm::CallInst *CI = Builder.CreateCall(IA);
14956     CI->setAttributes(NoReturnAttr);
14957     return CI;
14958   }
14959   case X86::BI__readfsbyte:
14960   case X86::BI__readfsword:
14961   case X86::BI__readfsdword:
14962   case X86::BI__readfsqword: {
14963     llvm::Type *IntTy = ConvertType(E->getType());
14964     Value *Ptr =
14965         Builder.CreateIntToPtr(Ops[0], llvm::PointerType::get(IntTy, 257));
14966     LoadInst *Load = Builder.CreateAlignedLoad(
14967         IntTy, Ptr, getContext().getTypeAlignInChars(E->getType()));
14968     Load->setVolatile(true);
14969     return Load;
14970   }
14971   case X86::BI__readgsbyte:
14972   case X86::BI__readgsword:
14973   case X86::BI__readgsdword:
14974   case X86::BI__readgsqword: {
14975     llvm::Type *IntTy = ConvertType(E->getType());
14976     Value *Ptr =
14977         Builder.CreateIntToPtr(Ops[0], llvm::PointerType::get(IntTy, 256));
14978     LoadInst *Load = Builder.CreateAlignedLoad(
14979         IntTy, Ptr, getContext().getTypeAlignInChars(E->getType()));
14980     Load->setVolatile(true);
14981     return Load;
14982   }
14983   case X86::BI__builtin_ia32_paddsb512:
14984   case X86::BI__builtin_ia32_paddsw512:
14985   case X86::BI__builtin_ia32_paddsb256:
14986   case X86::BI__builtin_ia32_paddsw256:
14987   case X86::BI__builtin_ia32_paddsb128:
14988   case X86::BI__builtin_ia32_paddsw128:
14989     return EmitX86BinaryIntrinsic(*this, Ops, Intrinsic::sadd_sat);
14990   case X86::BI__builtin_ia32_paddusb512:
14991   case X86::BI__builtin_ia32_paddusw512:
14992   case X86::BI__builtin_ia32_paddusb256:
14993   case X86::BI__builtin_ia32_paddusw256:
14994   case X86::BI__builtin_ia32_paddusb128:
14995   case X86::BI__builtin_ia32_paddusw128:
14996     return EmitX86BinaryIntrinsic(*this, Ops, Intrinsic::uadd_sat);
14997   case X86::BI__builtin_ia32_psubsb512:
14998   case X86::BI__builtin_ia32_psubsw512:
14999   case X86::BI__builtin_ia32_psubsb256:
15000   case X86::BI__builtin_ia32_psubsw256:
15001   case X86::BI__builtin_ia32_psubsb128:
15002   case X86::BI__builtin_ia32_psubsw128:
15003     return EmitX86BinaryIntrinsic(*this, Ops, Intrinsic::ssub_sat);
15004   case X86::BI__builtin_ia32_psubusb512:
15005   case X86::BI__builtin_ia32_psubusw512:
15006   case X86::BI__builtin_ia32_psubusb256:
15007   case X86::BI__builtin_ia32_psubusw256:
15008   case X86::BI__builtin_ia32_psubusb128:
15009   case X86::BI__builtin_ia32_psubusw128:
15010     return EmitX86BinaryIntrinsic(*this, Ops, Intrinsic::usub_sat);
15011   case X86::BI__builtin_ia32_encodekey128_u32: {
15012     Intrinsic::ID IID = Intrinsic::x86_encodekey128;
15013 
15014     Value *Call = Builder.CreateCall(CGM.getIntrinsic(IID), {Ops[0], Ops[1]});
15015 
15016     for (int i = 0; i < 3; ++i) {
15017       Value *Extract = Builder.CreateExtractValue(Call, i + 1);
15018       Value *Ptr = Builder.CreateConstGEP1_32(Int8Ty, Ops[2], i * 16);
15019       Ptr = Builder.CreateBitCast(
15020           Ptr, llvm::PointerType::getUnqual(Extract->getType()));
15021       Builder.CreateAlignedStore(Extract, Ptr, Align(1));
15022     }
15023 
15024     return Builder.CreateExtractValue(Call, 0);
15025   }
15026   case X86::BI__builtin_ia32_encodekey256_u32: {
15027     Intrinsic::ID IID = Intrinsic::x86_encodekey256;
15028 
15029     Value *Call =
15030         Builder.CreateCall(CGM.getIntrinsic(IID), {Ops[0], Ops[1], Ops[2]});
15031 
15032     for (int i = 0; i < 4; ++i) {
15033       Value *Extract = Builder.CreateExtractValue(Call, i + 1);
15034       Value *Ptr = Builder.CreateConstGEP1_32(Int8Ty, Ops[3], i * 16);
15035       Ptr = Builder.CreateBitCast(
15036           Ptr, llvm::PointerType::getUnqual(Extract->getType()));
15037       Builder.CreateAlignedStore(Extract, Ptr, Align(1));
15038     }
15039 
15040     return Builder.CreateExtractValue(Call, 0);
15041   }
15042   case X86::BI__builtin_ia32_aesenc128kl_u8:
15043   case X86::BI__builtin_ia32_aesdec128kl_u8:
15044   case X86::BI__builtin_ia32_aesenc256kl_u8:
15045   case X86::BI__builtin_ia32_aesdec256kl_u8: {
15046     Intrinsic::ID IID;
15047     StringRef BlockName;
15048     switch (BuiltinID) {
15049     default:
15050       llvm_unreachable("Unexpected builtin");
15051     case X86::BI__builtin_ia32_aesenc128kl_u8:
15052       IID = Intrinsic::x86_aesenc128kl;
15053       BlockName = "aesenc128kl";
15054       break;
15055     case X86::BI__builtin_ia32_aesdec128kl_u8:
15056       IID = Intrinsic::x86_aesdec128kl;
15057       BlockName = "aesdec128kl";
15058       break;
15059     case X86::BI__builtin_ia32_aesenc256kl_u8:
15060       IID = Intrinsic::x86_aesenc256kl;
15061       BlockName = "aesenc256kl";
15062       break;
15063     case X86::BI__builtin_ia32_aesdec256kl_u8:
15064       IID = Intrinsic::x86_aesdec256kl;
15065       BlockName = "aesdec256kl";
15066       break;
15067     }
15068 
15069     Value *Call = Builder.CreateCall(CGM.getIntrinsic(IID), {Ops[1], Ops[2]});
15070 
15071     BasicBlock *NoError =
15072         createBasicBlock(BlockName + "_no_error", this->CurFn);
15073     BasicBlock *Error = createBasicBlock(BlockName + "_error", this->CurFn);
15074     BasicBlock *End = createBasicBlock(BlockName + "_end", this->CurFn);
15075 
15076     Value *Ret = Builder.CreateExtractValue(Call, 0);
15077     Value *Succ = Builder.CreateTrunc(Ret, Builder.getInt1Ty());
15078     Value *Out = Builder.CreateExtractValue(Call, 1);
15079     Builder.CreateCondBr(Succ, NoError, Error);
15080 
15081     Builder.SetInsertPoint(NoError);
15082     Builder.CreateDefaultAlignedStore(Out, Ops[0]);
15083     Builder.CreateBr(End);
15084 
15085     Builder.SetInsertPoint(Error);
15086     Constant *Zero = llvm::Constant::getNullValue(Out->getType());
15087     Builder.CreateDefaultAlignedStore(Zero, Ops[0]);
15088     Builder.CreateBr(End);
15089 
15090     Builder.SetInsertPoint(End);
15091     return Builder.CreateExtractValue(Call, 0);
15092   }
15093   case X86::BI__builtin_ia32_aesencwide128kl_u8:
15094   case X86::BI__builtin_ia32_aesdecwide128kl_u8:
15095   case X86::BI__builtin_ia32_aesencwide256kl_u8:
15096   case X86::BI__builtin_ia32_aesdecwide256kl_u8: {
15097     Intrinsic::ID IID;
15098     StringRef BlockName;
15099     switch (BuiltinID) {
15100     case X86::BI__builtin_ia32_aesencwide128kl_u8:
15101       IID = Intrinsic::x86_aesencwide128kl;
15102       BlockName = "aesencwide128kl";
15103       break;
15104     case X86::BI__builtin_ia32_aesdecwide128kl_u8:
15105       IID = Intrinsic::x86_aesdecwide128kl;
15106       BlockName = "aesdecwide128kl";
15107       break;
15108     case X86::BI__builtin_ia32_aesencwide256kl_u8:
15109       IID = Intrinsic::x86_aesencwide256kl;
15110       BlockName = "aesencwide256kl";
15111       break;
15112     case X86::BI__builtin_ia32_aesdecwide256kl_u8:
15113       IID = Intrinsic::x86_aesdecwide256kl;
15114       BlockName = "aesdecwide256kl";
15115       break;
15116     }
15117 
15118     llvm::Type *Ty = FixedVectorType::get(Builder.getInt64Ty(), 2);
15119     Value *InOps[9];
15120     InOps[0] = Ops[2];
15121     for (int i = 0; i != 8; ++i) {
15122       Value *Ptr = Builder.CreateConstGEP1_32(Ty, Ops[1], i);
15123       InOps[i + 1] = Builder.CreateAlignedLoad(Ty, Ptr, Align(16));
15124     }
15125 
15126     Value *Call = Builder.CreateCall(CGM.getIntrinsic(IID), InOps);
15127 
15128     BasicBlock *NoError =
15129         createBasicBlock(BlockName + "_no_error", this->CurFn);
15130     BasicBlock *Error = createBasicBlock(BlockName + "_error", this->CurFn);
15131     BasicBlock *End = createBasicBlock(BlockName + "_end", this->CurFn);
15132 
15133     Value *Ret = Builder.CreateExtractValue(Call, 0);
15134     Value *Succ = Builder.CreateTrunc(Ret, Builder.getInt1Ty());
15135     Builder.CreateCondBr(Succ, NoError, Error);
15136 
15137     Builder.SetInsertPoint(NoError);
15138     for (int i = 0; i != 8; ++i) {
15139       Value *Extract = Builder.CreateExtractValue(Call, i + 1);
15140       Value *Ptr = Builder.CreateConstGEP1_32(Extract->getType(), Ops[0], i);
15141       Builder.CreateAlignedStore(Extract, Ptr, Align(16));
15142     }
15143     Builder.CreateBr(End);
15144 
15145     Builder.SetInsertPoint(Error);
15146     for (int i = 0; i != 8; ++i) {
15147       Value *Out = Builder.CreateExtractValue(Call, i + 1);
15148       Constant *Zero = llvm::Constant::getNullValue(Out->getType());
15149       Value *Ptr = Builder.CreateConstGEP1_32(Out->getType(), Ops[0], i);
15150       Builder.CreateAlignedStore(Zero, Ptr, Align(16));
15151     }
15152     Builder.CreateBr(End);
15153 
15154     Builder.SetInsertPoint(End);
15155     return Builder.CreateExtractValue(Call, 0);
15156   }
15157   case X86::BI__builtin_ia32_vfcmaddcph512_mask:
15158     IsConjFMA = true;
15159     LLVM_FALLTHROUGH;
15160   case X86::BI__builtin_ia32_vfmaddcph512_mask: {
15161     Intrinsic::ID IID = IsConjFMA
15162                             ? Intrinsic::x86_avx512fp16_mask_vfcmadd_cph_512
15163                             : Intrinsic::x86_avx512fp16_mask_vfmadd_cph_512;
15164     Value *Call = Builder.CreateCall(CGM.getIntrinsic(IID), Ops);
15165     return EmitX86Select(*this, Ops[3], Call, Ops[0]);
15166   }
15167   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask:
15168     IsConjFMA = true;
15169     LLVM_FALLTHROUGH;
15170   case X86::BI__builtin_ia32_vfmaddcsh_round_mask: {
15171     Intrinsic::ID IID = IsConjFMA ? Intrinsic::x86_avx512fp16_mask_vfcmadd_csh
15172                                   : Intrinsic::x86_avx512fp16_mask_vfmadd_csh;
15173     Value *Call = Builder.CreateCall(CGM.getIntrinsic(IID), Ops);
15174     Value *And = Builder.CreateAnd(Ops[3], llvm::ConstantInt::get(Int8Ty, 1));
15175     return EmitX86Select(*this, And, Call, Ops[0]);
15176   }
15177   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3:
15178     IsConjFMA = true;
15179     LLVM_FALLTHROUGH;
15180   case X86::BI__builtin_ia32_vfmaddcsh_round_mask3: {
15181     Intrinsic::ID IID = IsConjFMA ? Intrinsic::x86_avx512fp16_mask_vfcmadd_csh
15182                                   : Intrinsic::x86_avx512fp16_mask_vfmadd_csh;
15183     Value *Call = Builder.CreateCall(CGM.getIntrinsic(IID), Ops);
15184     static constexpr int Mask[] = {0, 5, 6, 7};
15185     return Builder.CreateShuffleVector(Call, Ops[2], Mask);
15186   }
15187   }
15188 }
15189 
15190 Value *CodeGenFunction::EmitPPCBuiltinExpr(unsigned BuiltinID,
15191                                            const CallExpr *E) {
15192   SmallVector<Value*, 4> Ops;
15193 
15194   for (unsigned i = 0, e = E->getNumArgs(); i != e; i++) {
15195     if (E->getArg(i)->getType()->isArrayType())
15196       Ops.push_back(EmitArrayToPointerDecay(E->getArg(i)).getPointer());
15197     else
15198       Ops.push_back(EmitScalarExpr(E->getArg(i)));
15199   }
15200 
15201   Intrinsic::ID ID = Intrinsic::not_intrinsic;
15202 
15203   switch (BuiltinID) {
15204   default: return nullptr;
15205 
15206   // __builtin_ppc_get_timebase is GCC 4.8+'s PowerPC-specific name for what we
15207   // call __builtin_readcyclecounter.
15208   case PPC::BI__builtin_ppc_get_timebase:
15209     return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::readcyclecounter));
15210 
15211   // vec_ld, vec_xl_be, vec_lvsl, vec_lvsr
15212   case PPC::BI__builtin_altivec_lvx:
15213   case PPC::BI__builtin_altivec_lvxl:
15214   case PPC::BI__builtin_altivec_lvebx:
15215   case PPC::BI__builtin_altivec_lvehx:
15216   case PPC::BI__builtin_altivec_lvewx:
15217   case PPC::BI__builtin_altivec_lvsl:
15218   case PPC::BI__builtin_altivec_lvsr:
15219   case PPC::BI__builtin_vsx_lxvd2x:
15220   case PPC::BI__builtin_vsx_lxvw4x:
15221   case PPC::BI__builtin_vsx_lxvd2x_be:
15222   case PPC::BI__builtin_vsx_lxvw4x_be:
15223   case PPC::BI__builtin_vsx_lxvl:
15224   case PPC::BI__builtin_vsx_lxvll:
15225   {
15226     if(BuiltinID == PPC::BI__builtin_vsx_lxvl ||
15227        BuiltinID == PPC::BI__builtin_vsx_lxvll){
15228       Ops[0] = Builder.CreateBitCast(Ops[0], Int8PtrTy);
15229     }else {
15230       Ops[1] = Builder.CreateBitCast(Ops[1], Int8PtrTy);
15231       Ops[0] = Builder.CreateGEP(Int8Ty, Ops[1], Ops[0]);
15232       Ops.pop_back();
15233     }
15234 
15235     switch (BuiltinID) {
15236     default: llvm_unreachable("Unsupported ld/lvsl/lvsr intrinsic!");
15237     case PPC::BI__builtin_altivec_lvx:
15238       ID = Intrinsic::ppc_altivec_lvx;
15239       break;
15240     case PPC::BI__builtin_altivec_lvxl:
15241       ID = Intrinsic::ppc_altivec_lvxl;
15242       break;
15243     case PPC::BI__builtin_altivec_lvebx:
15244       ID = Intrinsic::ppc_altivec_lvebx;
15245       break;
15246     case PPC::BI__builtin_altivec_lvehx:
15247       ID = Intrinsic::ppc_altivec_lvehx;
15248       break;
15249     case PPC::BI__builtin_altivec_lvewx:
15250       ID = Intrinsic::ppc_altivec_lvewx;
15251       break;
15252     case PPC::BI__builtin_altivec_lvsl:
15253       ID = Intrinsic::ppc_altivec_lvsl;
15254       break;
15255     case PPC::BI__builtin_altivec_lvsr:
15256       ID = Intrinsic::ppc_altivec_lvsr;
15257       break;
15258     case PPC::BI__builtin_vsx_lxvd2x:
15259       ID = Intrinsic::ppc_vsx_lxvd2x;
15260       break;
15261     case PPC::BI__builtin_vsx_lxvw4x:
15262       ID = Intrinsic::ppc_vsx_lxvw4x;
15263       break;
15264     case PPC::BI__builtin_vsx_lxvd2x_be:
15265       ID = Intrinsic::ppc_vsx_lxvd2x_be;
15266       break;
15267     case PPC::BI__builtin_vsx_lxvw4x_be:
15268       ID = Intrinsic::ppc_vsx_lxvw4x_be;
15269       break;
15270     case PPC::BI__builtin_vsx_lxvl:
15271       ID = Intrinsic::ppc_vsx_lxvl;
15272       break;
15273     case PPC::BI__builtin_vsx_lxvll:
15274       ID = Intrinsic::ppc_vsx_lxvll;
15275       break;
15276     }
15277     llvm::Function *F = CGM.getIntrinsic(ID);
15278     return Builder.CreateCall(F, Ops, "");
15279   }
15280 
15281   // vec_st, vec_xst_be
15282   case PPC::BI__builtin_altivec_stvx:
15283   case PPC::BI__builtin_altivec_stvxl:
15284   case PPC::BI__builtin_altivec_stvebx:
15285   case PPC::BI__builtin_altivec_stvehx:
15286   case PPC::BI__builtin_altivec_stvewx:
15287   case PPC::BI__builtin_vsx_stxvd2x:
15288   case PPC::BI__builtin_vsx_stxvw4x:
15289   case PPC::BI__builtin_vsx_stxvd2x_be:
15290   case PPC::BI__builtin_vsx_stxvw4x_be:
15291   case PPC::BI__builtin_vsx_stxvl:
15292   case PPC::BI__builtin_vsx_stxvll:
15293   {
15294     if(BuiltinID == PPC::BI__builtin_vsx_stxvl ||
15295       BuiltinID == PPC::BI__builtin_vsx_stxvll ){
15296       Ops[1] = Builder.CreateBitCast(Ops[1], Int8PtrTy);
15297     }else {
15298       Ops[2] = Builder.CreateBitCast(Ops[2], Int8PtrTy);
15299       Ops[1] = Builder.CreateGEP(Int8Ty, Ops[2], Ops[1]);
15300       Ops.pop_back();
15301     }
15302 
15303     switch (BuiltinID) {
15304     default: llvm_unreachable("Unsupported st intrinsic!");
15305     case PPC::BI__builtin_altivec_stvx:
15306       ID = Intrinsic::ppc_altivec_stvx;
15307       break;
15308     case PPC::BI__builtin_altivec_stvxl:
15309       ID = Intrinsic::ppc_altivec_stvxl;
15310       break;
15311     case PPC::BI__builtin_altivec_stvebx:
15312       ID = Intrinsic::ppc_altivec_stvebx;
15313       break;
15314     case PPC::BI__builtin_altivec_stvehx:
15315       ID = Intrinsic::ppc_altivec_stvehx;
15316       break;
15317     case PPC::BI__builtin_altivec_stvewx:
15318       ID = Intrinsic::ppc_altivec_stvewx;
15319       break;
15320     case PPC::BI__builtin_vsx_stxvd2x:
15321       ID = Intrinsic::ppc_vsx_stxvd2x;
15322       break;
15323     case PPC::BI__builtin_vsx_stxvw4x:
15324       ID = Intrinsic::ppc_vsx_stxvw4x;
15325       break;
15326     case PPC::BI__builtin_vsx_stxvd2x_be:
15327       ID = Intrinsic::ppc_vsx_stxvd2x_be;
15328       break;
15329     case PPC::BI__builtin_vsx_stxvw4x_be:
15330       ID = Intrinsic::ppc_vsx_stxvw4x_be;
15331       break;
15332     case PPC::BI__builtin_vsx_stxvl:
15333       ID = Intrinsic::ppc_vsx_stxvl;
15334       break;
15335     case PPC::BI__builtin_vsx_stxvll:
15336       ID = Intrinsic::ppc_vsx_stxvll;
15337       break;
15338     }
15339     llvm::Function *F = CGM.getIntrinsic(ID);
15340     return Builder.CreateCall(F, Ops, "");
15341   }
15342   case PPC::BI__builtin_vsx_ldrmb: {
15343     // Essentially boils down to performing an unaligned VMX load sequence so
15344     // as to avoid crossing a page boundary and then shuffling the elements
15345     // into the right side of the vector register.
15346     int64_t NumBytes = cast<ConstantInt>(Ops[1])->getZExtValue();
15347     llvm::Type *ResTy = ConvertType(E->getType());
15348     bool IsLE = getTarget().isLittleEndian();
15349 
15350     // If the user wants the entire vector, just load the entire vector.
15351     if (NumBytes == 16) {
15352       Value *BC = Builder.CreateBitCast(Ops[0], ResTy->getPointerTo());
15353       Value *LD =
15354           Builder.CreateLoad(Address(BC, ResTy, CharUnits::fromQuantity(1)));
15355       if (!IsLE)
15356         return LD;
15357 
15358       // Reverse the bytes on LE.
15359       SmallVector<int, 16> RevMask;
15360       for (int Idx = 0; Idx < 16; Idx++)
15361         RevMask.push_back(15 - Idx);
15362       return Builder.CreateShuffleVector(LD, LD, RevMask);
15363     }
15364 
15365     llvm::Function *Lvx = CGM.getIntrinsic(Intrinsic::ppc_altivec_lvx);
15366     llvm::Function *Lvs = CGM.getIntrinsic(IsLE ? Intrinsic::ppc_altivec_lvsr
15367                                                 : Intrinsic::ppc_altivec_lvsl);
15368     llvm::Function *Vperm = CGM.getIntrinsic(Intrinsic::ppc_altivec_vperm);
15369     Value *HiMem = Builder.CreateGEP(
15370         Int8Ty, Ops[0], ConstantInt::get(Ops[1]->getType(), NumBytes - 1));
15371     Value *LoLd = Builder.CreateCall(Lvx, Ops[0], "ld.lo");
15372     Value *HiLd = Builder.CreateCall(Lvx, HiMem, "ld.hi");
15373     Value *Mask1 = Builder.CreateCall(Lvs, Ops[0], "mask1");
15374 
15375     Ops.clear();
15376     Ops.push_back(IsLE ? HiLd : LoLd);
15377     Ops.push_back(IsLE ? LoLd : HiLd);
15378     Ops.push_back(Mask1);
15379     Value *AllElts = Builder.CreateCall(Vperm, Ops, "shuffle1");
15380     Constant *Zero = llvm::Constant::getNullValue(IsLE ? ResTy : AllElts->getType());
15381 
15382     if (IsLE) {
15383       SmallVector<int, 16> Consts;
15384       for (int Idx = 0; Idx < 16; Idx++) {
15385         int Val = (NumBytes - Idx - 1 >= 0) ? (NumBytes - Idx - 1)
15386                                             : 16 - (NumBytes - Idx);
15387         Consts.push_back(Val);
15388       }
15389       return Builder.CreateShuffleVector(Builder.CreateBitCast(AllElts, ResTy),
15390                                          Zero, Consts);
15391     }
15392     SmallVector<Constant *, 16> Consts;
15393     for (int Idx = 0; Idx < 16; Idx++)
15394       Consts.push_back(Builder.getInt8(NumBytes + Idx));
15395     Value *Mask2 = ConstantVector::get(Consts);
15396     return Builder.CreateBitCast(
15397         Builder.CreateCall(Vperm, {Zero, AllElts, Mask2}, "shuffle2"), ResTy);
15398   }
15399   case PPC::BI__builtin_vsx_strmb: {
15400     int64_t NumBytes = cast<ConstantInt>(Ops[1])->getZExtValue();
15401     bool IsLE = getTarget().isLittleEndian();
15402     auto StoreSubVec = [&](unsigned Width, unsigned Offset, unsigned EltNo) {
15403       // Storing the whole vector, simply store it on BE and reverse bytes and
15404       // store on LE.
15405       if (Width == 16) {
15406         Value *BC =
15407             Builder.CreateBitCast(Ops[0], Ops[2]->getType()->getPointerTo());
15408         Value *StVec = Ops[2];
15409         if (IsLE) {
15410           SmallVector<int, 16> RevMask;
15411           for (int Idx = 0; Idx < 16; Idx++)
15412             RevMask.push_back(15 - Idx);
15413           StVec = Builder.CreateShuffleVector(Ops[2], Ops[2], RevMask);
15414         }
15415         return Builder.CreateStore(
15416             StVec, Address(BC, Ops[2]->getType(), CharUnits::fromQuantity(1)));
15417       }
15418       auto *ConvTy = Int64Ty;
15419       unsigned NumElts = 0;
15420       switch (Width) {
15421       default:
15422         llvm_unreachable("width for stores must be a power of 2");
15423       case 8:
15424         ConvTy = Int64Ty;
15425         NumElts = 2;
15426         break;
15427       case 4:
15428         ConvTy = Int32Ty;
15429         NumElts = 4;
15430         break;
15431       case 2:
15432         ConvTy = Int16Ty;
15433         NumElts = 8;
15434         break;
15435       case 1:
15436         ConvTy = Int8Ty;
15437         NumElts = 16;
15438         break;
15439       }
15440       Value *Vec = Builder.CreateBitCast(
15441           Ops[2], llvm::FixedVectorType::get(ConvTy, NumElts));
15442       Value *Ptr = Builder.CreateGEP(Int8Ty, Ops[0],
15443                                      ConstantInt::get(Int64Ty, Offset));
15444       Value *PtrBC = Builder.CreateBitCast(Ptr, ConvTy->getPointerTo());
15445       Value *Elt = Builder.CreateExtractElement(Vec, EltNo);
15446       if (IsLE && Width > 1) {
15447         Function *F = CGM.getIntrinsic(Intrinsic::bswap, ConvTy);
15448         Elt = Builder.CreateCall(F, Elt);
15449       }
15450       return Builder.CreateStore(
15451           Elt, Address(PtrBC, ConvTy, CharUnits::fromQuantity(1)));
15452     };
15453     unsigned Stored = 0;
15454     unsigned RemainingBytes = NumBytes;
15455     Value *Result;
15456     if (NumBytes == 16)
15457       return StoreSubVec(16, 0, 0);
15458     if (NumBytes >= 8) {
15459       Result = StoreSubVec(8, NumBytes - 8, IsLE ? 0 : 1);
15460       RemainingBytes -= 8;
15461       Stored += 8;
15462     }
15463     if (RemainingBytes >= 4) {
15464       Result = StoreSubVec(4, NumBytes - Stored - 4,
15465                            IsLE ? (Stored >> 2) : 3 - (Stored >> 2));
15466       RemainingBytes -= 4;
15467       Stored += 4;
15468     }
15469     if (RemainingBytes >= 2) {
15470       Result = StoreSubVec(2, NumBytes - Stored - 2,
15471                            IsLE ? (Stored >> 1) : 7 - (Stored >> 1));
15472       RemainingBytes -= 2;
15473       Stored += 2;
15474     }
15475     if (RemainingBytes)
15476       Result =
15477           StoreSubVec(1, NumBytes - Stored - 1, IsLE ? Stored : 15 - Stored);
15478     return Result;
15479   }
15480   // Square root
15481   case PPC::BI__builtin_vsx_xvsqrtsp:
15482   case PPC::BI__builtin_vsx_xvsqrtdp: {
15483     llvm::Type *ResultType = ConvertType(E->getType());
15484     Value *X = EmitScalarExpr(E->getArg(0));
15485     if (Builder.getIsFPConstrained()) {
15486       llvm::Function *F = CGM.getIntrinsic(
15487           Intrinsic::experimental_constrained_sqrt, ResultType);
15488       return Builder.CreateConstrainedFPCall(F, X);
15489     } else {
15490       llvm::Function *F = CGM.getIntrinsic(Intrinsic::sqrt, ResultType);
15491       return Builder.CreateCall(F, X);
15492     }
15493   }
15494   // Count leading zeros
15495   case PPC::BI__builtin_altivec_vclzb:
15496   case PPC::BI__builtin_altivec_vclzh:
15497   case PPC::BI__builtin_altivec_vclzw:
15498   case PPC::BI__builtin_altivec_vclzd: {
15499     llvm::Type *ResultType = ConvertType(E->getType());
15500     Value *X = EmitScalarExpr(E->getArg(0));
15501     Value *Undef = ConstantInt::get(Builder.getInt1Ty(), false);
15502     Function *F = CGM.getIntrinsic(Intrinsic::ctlz, ResultType);
15503     return Builder.CreateCall(F, {X, Undef});
15504   }
15505   case PPC::BI__builtin_altivec_vctzb:
15506   case PPC::BI__builtin_altivec_vctzh:
15507   case PPC::BI__builtin_altivec_vctzw:
15508   case PPC::BI__builtin_altivec_vctzd: {
15509     llvm::Type *ResultType = ConvertType(E->getType());
15510     Value *X = EmitScalarExpr(E->getArg(0));
15511     Value *Undef = ConstantInt::get(Builder.getInt1Ty(), false);
15512     Function *F = CGM.getIntrinsic(Intrinsic::cttz, ResultType);
15513     return Builder.CreateCall(F, {X, Undef});
15514   }
15515   case PPC::BI__builtin_altivec_vec_replace_elt:
15516   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
15517     // The third argument of vec_replace_elt and vec_replace_unaligned must
15518     // be a compile time constant and will be emitted either to the vinsw
15519     // or vinsd instruction.
15520     ConstantInt *ArgCI = dyn_cast<ConstantInt>(Ops[2]);
15521     assert(ArgCI &&
15522            "Third Arg to vinsw/vinsd intrinsic must be a constant integer!");
15523     llvm::Type *ResultType = ConvertType(E->getType());
15524     llvm::Function *F = nullptr;
15525     Value *Call = nullptr;
15526     int64_t ConstArg = ArgCI->getSExtValue();
15527     unsigned ArgWidth = Ops[1]->getType()->getPrimitiveSizeInBits();
15528     bool Is32Bit = false;
15529     assert((ArgWidth == 32 || ArgWidth == 64) && "Invalid argument width");
15530     // The input to vec_replace_elt is an element index, not a byte index.
15531     if (BuiltinID == PPC::BI__builtin_altivec_vec_replace_elt)
15532       ConstArg *= ArgWidth / 8;
15533     if (ArgWidth == 32) {
15534       Is32Bit = true;
15535       // When the second argument is 32 bits, it can either be an integer or
15536       // a float. The vinsw intrinsic is used in this case.
15537       F = CGM.getIntrinsic(Intrinsic::ppc_altivec_vinsw);
15538       // Fix the constant according to endianess.
15539       if (getTarget().isLittleEndian())
15540         ConstArg = 12 - ConstArg;
15541     } else {
15542       // When the second argument is 64 bits, it can either be a long long or
15543       // a double. The vinsd intrinsic is used in this case.
15544       F = CGM.getIntrinsic(Intrinsic::ppc_altivec_vinsd);
15545       // Fix the constant for little endian.
15546       if (getTarget().isLittleEndian())
15547         ConstArg = 8 - ConstArg;
15548     }
15549     Ops[2] = ConstantInt::getSigned(Int32Ty, ConstArg);
15550     // Depending on ArgWidth, the input vector could be a float or a double.
15551     // If the input vector is a float type, bitcast the inputs to integers. Or,
15552     // if the input vector is a double, bitcast the inputs to 64-bit integers.
15553     if (!Ops[1]->getType()->isIntegerTy(ArgWidth)) {
15554       Ops[0] = Builder.CreateBitCast(
15555           Ops[0], Is32Bit ? llvm::FixedVectorType::get(Int32Ty, 4)
15556                           : llvm::FixedVectorType::get(Int64Ty, 2));
15557       Ops[1] = Builder.CreateBitCast(Ops[1], Is32Bit ? Int32Ty : Int64Ty);
15558     }
15559     // Emit the call to vinsw or vinsd.
15560     Call = Builder.CreateCall(F, Ops);
15561     // Depending on the builtin, bitcast to the approriate result type.
15562     if (BuiltinID == PPC::BI__builtin_altivec_vec_replace_elt &&
15563         !Ops[1]->getType()->isIntegerTy())
15564       return Builder.CreateBitCast(Call, ResultType);
15565     else if (BuiltinID == PPC::BI__builtin_altivec_vec_replace_elt &&
15566              Ops[1]->getType()->isIntegerTy())
15567       return Call;
15568     else
15569       return Builder.CreateBitCast(Call,
15570                                    llvm::FixedVectorType::get(Int8Ty, 16));
15571   }
15572   case PPC::BI__builtin_altivec_vpopcntb:
15573   case PPC::BI__builtin_altivec_vpopcnth:
15574   case PPC::BI__builtin_altivec_vpopcntw:
15575   case PPC::BI__builtin_altivec_vpopcntd: {
15576     llvm::Type *ResultType = ConvertType(E->getType());
15577     Value *X = EmitScalarExpr(E->getArg(0));
15578     llvm::Function *F = CGM.getIntrinsic(Intrinsic::ctpop, ResultType);
15579     return Builder.CreateCall(F, X);
15580   }
15581   case PPC::BI__builtin_altivec_vadduqm:
15582   case PPC::BI__builtin_altivec_vsubuqm: {
15583     llvm::Type *Int128Ty = llvm::IntegerType::get(getLLVMContext(), 128);
15584     Ops[0] =
15585         Builder.CreateBitCast(Ops[0], llvm::FixedVectorType::get(Int128Ty, 1));
15586     Ops[1] =
15587         Builder.CreateBitCast(Ops[1], llvm::FixedVectorType::get(Int128Ty, 1));
15588     if (BuiltinID == PPC::BI__builtin_altivec_vadduqm)
15589       return Builder.CreateAdd(Ops[0], Ops[1], "vadduqm");
15590     else
15591       return Builder.CreateSub(Ops[0], Ops[1], "vsubuqm");
15592   }
15593   // Rotate and insert under mask operation.
15594   // __rldimi(rs, is, shift, mask)
15595   // (rotl64(rs, shift) & mask) | (is & ~mask)
15596   // __rlwimi(rs, is, shift, mask)
15597   // (rotl(rs, shift) & mask) | (is & ~mask)
15598   case PPC::BI__builtin_ppc_rldimi:
15599   case PPC::BI__builtin_ppc_rlwimi: {
15600     llvm::Type *Ty = Ops[0]->getType();
15601     Function *F = CGM.getIntrinsic(Intrinsic::fshl, Ty);
15602     if (BuiltinID == PPC::BI__builtin_ppc_rldimi)
15603       Ops[2] = Builder.CreateZExt(Ops[2], Int64Ty);
15604     Value *Shift = Builder.CreateCall(F, {Ops[0], Ops[0], Ops[2]});
15605     Value *X = Builder.CreateAnd(Shift, Ops[3]);
15606     Value *Y = Builder.CreateAnd(Ops[1], Builder.CreateNot(Ops[3]));
15607     return Builder.CreateOr(X, Y);
15608   }
15609   // Rotate and insert under mask operation.
15610   // __rlwnm(rs, shift, mask)
15611   // rotl(rs, shift) & mask
15612   case PPC::BI__builtin_ppc_rlwnm: {
15613     llvm::Type *Ty = Ops[0]->getType();
15614     Function *F = CGM.getIntrinsic(Intrinsic::fshl, Ty);
15615     Value *Shift = Builder.CreateCall(F, {Ops[0], Ops[0], Ops[1]});
15616     return Builder.CreateAnd(Shift, Ops[2]);
15617   }
15618   case PPC::BI__builtin_ppc_poppar4:
15619   case PPC::BI__builtin_ppc_poppar8: {
15620     llvm::Type *ArgType = Ops[0]->getType();
15621     Function *F = CGM.getIntrinsic(Intrinsic::ctpop, ArgType);
15622     Value *Tmp = Builder.CreateCall(F, Ops[0]);
15623 
15624     llvm::Type *ResultType = ConvertType(E->getType());
15625     Value *Result = Builder.CreateAnd(Tmp, llvm::ConstantInt::get(ArgType, 1));
15626     if (Result->getType() != ResultType)
15627       Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
15628                                      "cast");
15629     return Result;
15630   }
15631   case PPC::BI__builtin_ppc_cmpb: {
15632     if (getTarget().getTriple().isPPC64()) {
15633       Function *F =
15634           CGM.getIntrinsic(Intrinsic::ppc_cmpb, {Int64Ty, Int64Ty, Int64Ty});
15635       return Builder.CreateCall(F, Ops, "cmpb");
15636     }
15637     // For 32 bit, emit the code as below:
15638     // %conv = trunc i64 %a to i32
15639     // %conv1 = trunc i64 %b to i32
15640     // %shr = lshr i64 %a, 32
15641     // %conv2 = trunc i64 %shr to i32
15642     // %shr3 = lshr i64 %b, 32
15643     // %conv4 = trunc i64 %shr3 to i32
15644     // %0 = tail call i32 @llvm.ppc.cmpb32(i32 %conv, i32 %conv1)
15645     // %conv5 = zext i32 %0 to i64
15646     // %1 = tail call i32 @llvm.ppc.cmpb32(i32 %conv2, i32 %conv4)
15647     // %conv614 = zext i32 %1 to i64
15648     // %shl = shl nuw i64 %conv614, 32
15649     // %or = or i64 %shl, %conv5
15650     // ret i64 %or
15651     Function *F =
15652         CGM.getIntrinsic(Intrinsic::ppc_cmpb, {Int32Ty, Int32Ty, Int32Ty});
15653     Value *ArgOneLo = Builder.CreateTrunc(Ops[0], Int32Ty);
15654     Value *ArgTwoLo = Builder.CreateTrunc(Ops[1], Int32Ty);
15655     Constant *ShiftAmt = ConstantInt::get(Int64Ty, 32);
15656     Value *ArgOneHi =
15657         Builder.CreateTrunc(Builder.CreateLShr(Ops[0], ShiftAmt), Int32Ty);
15658     Value *ArgTwoHi =
15659         Builder.CreateTrunc(Builder.CreateLShr(Ops[1], ShiftAmt), Int32Ty);
15660     Value *ResLo = Builder.CreateZExt(
15661         Builder.CreateCall(F, {ArgOneLo, ArgTwoLo}, "cmpb"), Int64Ty);
15662     Value *ResHiShift = Builder.CreateZExt(
15663         Builder.CreateCall(F, {ArgOneHi, ArgTwoHi}, "cmpb"), Int64Ty);
15664     Value *ResHi = Builder.CreateShl(ResHiShift, ShiftAmt);
15665     return Builder.CreateOr(ResLo, ResHi);
15666   }
15667   // Copy sign
15668   case PPC::BI__builtin_vsx_xvcpsgnsp:
15669   case PPC::BI__builtin_vsx_xvcpsgndp: {
15670     llvm::Type *ResultType = ConvertType(E->getType());
15671     Value *X = EmitScalarExpr(E->getArg(0));
15672     Value *Y = EmitScalarExpr(E->getArg(1));
15673     ID = Intrinsic::copysign;
15674     llvm::Function *F = CGM.getIntrinsic(ID, ResultType);
15675     return Builder.CreateCall(F, {X, Y});
15676   }
15677   // Rounding/truncation
15678   case PPC::BI__builtin_vsx_xvrspip:
15679   case PPC::BI__builtin_vsx_xvrdpip:
15680   case PPC::BI__builtin_vsx_xvrdpim:
15681   case PPC::BI__builtin_vsx_xvrspim:
15682   case PPC::BI__builtin_vsx_xvrdpi:
15683   case PPC::BI__builtin_vsx_xvrspi:
15684   case PPC::BI__builtin_vsx_xvrdpic:
15685   case PPC::BI__builtin_vsx_xvrspic:
15686   case PPC::BI__builtin_vsx_xvrdpiz:
15687   case PPC::BI__builtin_vsx_xvrspiz: {
15688     llvm::Type *ResultType = ConvertType(E->getType());
15689     Value *X = EmitScalarExpr(E->getArg(0));
15690     if (BuiltinID == PPC::BI__builtin_vsx_xvrdpim ||
15691         BuiltinID == PPC::BI__builtin_vsx_xvrspim)
15692       ID = Builder.getIsFPConstrained()
15693                ? Intrinsic::experimental_constrained_floor
15694                : Intrinsic::floor;
15695     else if (BuiltinID == PPC::BI__builtin_vsx_xvrdpi ||
15696              BuiltinID == PPC::BI__builtin_vsx_xvrspi)
15697       ID = Builder.getIsFPConstrained()
15698                ? Intrinsic::experimental_constrained_round
15699                : Intrinsic::round;
15700     else if (BuiltinID == PPC::BI__builtin_vsx_xvrdpic ||
15701              BuiltinID == PPC::BI__builtin_vsx_xvrspic)
15702       ID = Builder.getIsFPConstrained()
15703                ? Intrinsic::experimental_constrained_rint
15704                : Intrinsic::rint;
15705     else if (BuiltinID == PPC::BI__builtin_vsx_xvrdpip ||
15706              BuiltinID == PPC::BI__builtin_vsx_xvrspip)
15707       ID = Builder.getIsFPConstrained()
15708                ? Intrinsic::experimental_constrained_ceil
15709                : Intrinsic::ceil;
15710     else if (BuiltinID == PPC::BI__builtin_vsx_xvrdpiz ||
15711              BuiltinID == PPC::BI__builtin_vsx_xvrspiz)
15712       ID = Builder.getIsFPConstrained()
15713                ? Intrinsic::experimental_constrained_trunc
15714                : Intrinsic::trunc;
15715     llvm::Function *F = CGM.getIntrinsic(ID, ResultType);
15716     return Builder.getIsFPConstrained() ? Builder.CreateConstrainedFPCall(F, X)
15717                                         : Builder.CreateCall(F, X);
15718   }
15719 
15720   // Absolute value
15721   case PPC::BI__builtin_vsx_xvabsdp:
15722   case PPC::BI__builtin_vsx_xvabssp: {
15723     llvm::Type *ResultType = ConvertType(E->getType());
15724     Value *X = EmitScalarExpr(E->getArg(0));
15725     llvm::Function *F = CGM.getIntrinsic(Intrinsic::fabs, ResultType);
15726     return Builder.CreateCall(F, X);
15727   }
15728 
15729   // Fastmath by default
15730   case PPC::BI__builtin_ppc_recipdivf:
15731   case PPC::BI__builtin_ppc_recipdivd:
15732   case PPC::BI__builtin_ppc_rsqrtf:
15733   case PPC::BI__builtin_ppc_rsqrtd: {
15734     FastMathFlags FMF = Builder.getFastMathFlags();
15735     Builder.getFastMathFlags().setFast();
15736     llvm::Type *ResultType = ConvertType(E->getType());
15737     Value *X = EmitScalarExpr(E->getArg(0));
15738 
15739     if (BuiltinID == PPC::BI__builtin_ppc_recipdivf ||
15740         BuiltinID == PPC::BI__builtin_ppc_recipdivd) {
15741       Value *Y = EmitScalarExpr(E->getArg(1));
15742       Value *FDiv = Builder.CreateFDiv(X, Y, "recipdiv");
15743       Builder.getFastMathFlags() &= (FMF);
15744       return FDiv;
15745     }
15746     auto *One = ConstantFP::get(ResultType, 1.0);
15747     llvm::Function *F = CGM.getIntrinsic(Intrinsic::sqrt, ResultType);
15748     Value *FDiv = Builder.CreateFDiv(One, Builder.CreateCall(F, X), "rsqrt");
15749     Builder.getFastMathFlags() &= (FMF);
15750     return FDiv;
15751   }
15752   case PPC::BI__builtin_ppc_alignx: {
15753     ConstantInt *AlignmentCI = cast<ConstantInt>(Ops[0]);
15754     if (AlignmentCI->getValue().ugt(llvm::Value::MaximumAlignment))
15755       AlignmentCI = ConstantInt::get(AlignmentCI->getType(),
15756                                      llvm::Value::MaximumAlignment);
15757 
15758     emitAlignmentAssumption(Ops[1], E->getArg(1),
15759                             /*The expr loc is sufficient.*/ SourceLocation(),
15760                             AlignmentCI, nullptr);
15761     return Ops[1];
15762   }
15763   case PPC::BI__builtin_ppc_rdlam: {
15764     llvm::Type *Ty = Ops[0]->getType();
15765     Value *ShiftAmt = Builder.CreateIntCast(Ops[1], Ty, false);
15766     Function *F = CGM.getIntrinsic(Intrinsic::fshl, Ty);
15767     Value *Rotate = Builder.CreateCall(F, {Ops[0], Ops[0], ShiftAmt});
15768     return Builder.CreateAnd(Rotate, Ops[2]);
15769   }
15770   case PPC::BI__builtin_ppc_load2r: {
15771     Function *F = CGM.getIntrinsic(Intrinsic::ppc_load2r);
15772     Ops[0] = Builder.CreateBitCast(Ops[0], Int8PtrTy);
15773     Value *LoadIntrinsic = Builder.CreateCall(F, Ops);
15774     return Builder.CreateTrunc(LoadIntrinsic, Int16Ty);
15775   }
15776   // FMA variations
15777   case PPC::BI__builtin_vsx_xvmaddadp:
15778   case PPC::BI__builtin_vsx_xvmaddasp:
15779   case PPC::BI__builtin_vsx_xvnmaddadp:
15780   case PPC::BI__builtin_vsx_xvnmaddasp:
15781   case PPC::BI__builtin_vsx_xvmsubadp:
15782   case PPC::BI__builtin_vsx_xvmsubasp:
15783   case PPC::BI__builtin_vsx_xvnmsubadp:
15784   case PPC::BI__builtin_vsx_xvnmsubasp: {
15785     llvm::Type *ResultType = ConvertType(E->getType());
15786     Value *X = EmitScalarExpr(E->getArg(0));
15787     Value *Y = EmitScalarExpr(E->getArg(1));
15788     Value *Z = EmitScalarExpr(E->getArg(2));
15789     llvm::Function *F;
15790     if (Builder.getIsFPConstrained())
15791       F = CGM.getIntrinsic(Intrinsic::experimental_constrained_fma, ResultType);
15792     else
15793       F = CGM.getIntrinsic(Intrinsic::fma, ResultType);
15794     switch (BuiltinID) {
15795       case PPC::BI__builtin_vsx_xvmaddadp:
15796       case PPC::BI__builtin_vsx_xvmaddasp:
15797         if (Builder.getIsFPConstrained())
15798           return Builder.CreateConstrainedFPCall(F, {X, Y, Z});
15799         else
15800           return Builder.CreateCall(F, {X, Y, Z});
15801       case PPC::BI__builtin_vsx_xvnmaddadp:
15802       case PPC::BI__builtin_vsx_xvnmaddasp:
15803         if (Builder.getIsFPConstrained())
15804           return Builder.CreateFNeg(
15805               Builder.CreateConstrainedFPCall(F, {X, Y, Z}), "neg");
15806         else
15807           return Builder.CreateFNeg(Builder.CreateCall(F, {X, Y, Z}), "neg");
15808       case PPC::BI__builtin_vsx_xvmsubadp:
15809       case PPC::BI__builtin_vsx_xvmsubasp:
15810         if (Builder.getIsFPConstrained())
15811           return Builder.CreateConstrainedFPCall(
15812               F, {X, Y, Builder.CreateFNeg(Z, "neg")});
15813         else
15814           return Builder.CreateCall(F, {X, Y, Builder.CreateFNeg(Z, "neg")});
15815       case PPC::BI__builtin_vsx_xvnmsubadp:
15816       case PPC::BI__builtin_vsx_xvnmsubasp:
15817         if (Builder.getIsFPConstrained())
15818           return Builder.CreateFNeg(
15819               Builder.CreateConstrainedFPCall(
15820                   F, {X, Y, Builder.CreateFNeg(Z, "neg")}),
15821               "neg");
15822         else
15823           return Builder.CreateFNeg(
15824               Builder.CreateCall(F, {X, Y, Builder.CreateFNeg(Z, "neg")}),
15825               "neg");
15826     }
15827     llvm_unreachable("Unknown FMA operation");
15828     return nullptr; // Suppress no-return warning
15829   }
15830 
15831   case PPC::BI__builtin_vsx_insertword: {
15832     llvm::Function *F = CGM.getIntrinsic(Intrinsic::ppc_vsx_xxinsertw);
15833 
15834     // Third argument is a compile time constant int. It must be clamped to
15835     // to the range [0, 12].
15836     ConstantInt *ArgCI = dyn_cast<ConstantInt>(Ops[2]);
15837     assert(ArgCI &&
15838            "Third arg to xxinsertw intrinsic must be constant integer");
15839     const int64_t MaxIndex = 12;
15840     int64_t Index = clamp(ArgCI->getSExtValue(), 0, MaxIndex);
15841 
15842     // The builtin semantics don't exactly match the xxinsertw instructions
15843     // semantics (which ppc_vsx_xxinsertw follows). The builtin extracts the
15844     // word from the first argument, and inserts it in the second argument. The
15845     // instruction extracts the word from its second input register and inserts
15846     // it into its first input register, so swap the first and second arguments.
15847     std::swap(Ops[0], Ops[1]);
15848 
15849     // Need to cast the second argument from a vector of unsigned int to a
15850     // vector of long long.
15851     Ops[1] =
15852         Builder.CreateBitCast(Ops[1], llvm::FixedVectorType::get(Int64Ty, 2));
15853 
15854     if (getTarget().isLittleEndian()) {
15855       // Reverse the double words in the vector we will extract from.
15856       Ops[0] =
15857           Builder.CreateBitCast(Ops[0], llvm::FixedVectorType::get(Int64Ty, 2));
15858       Ops[0] = Builder.CreateShuffleVector(Ops[0], Ops[0], ArrayRef<int>{1, 0});
15859 
15860       // Reverse the index.
15861       Index = MaxIndex - Index;
15862     }
15863 
15864     // Intrinsic expects the first arg to be a vector of int.
15865     Ops[0] =
15866         Builder.CreateBitCast(Ops[0], llvm::FixedVectorType::get(Int32Ty, 4));
15867     Ops[2] = ConstantInt::getSigned(Int32Ty, Index);
15868     return Builder.CreateCall(F, Ops);
15869   }
15870 
15871   case PPC::BI__builtin_vsx_extractuword: {
15872     llvm::Function *F = CGM.getIntrinsic(Intrinsic::ppc_vsx_xxextractuw);
15873 
15874     // Intrinsic expects the first argument to be a vector of doublewords.
15875     Ops[0] =
15876         Builder.CreateBitCast(Ops[0], llvm::FixedVectorType::get(Int64Ty, 2));
15877 
15878     // The second argument is a compile time constant int that needs to
15879     // be clamped to the range [0, 12].
15880     ConstantInt *ArgCI = dyn_cast<ConstantInt>(Ops[1]);
15881     assert(ArgCI &&
15882            "Second Arg to xxextractuw intrinsic must be a constant integer!");
15883     const int64_t MaxIndex = 12;
15884     int64_t Index = clamp(ArgCI->getSExtValue(), 0, MaxIndex);
15885 
15886     if (getTarget().isLittleEndian()) {
15887       // Reverse the index.
15888       Index = MaxIndex - Index;
15889       Ops[1] = ConstantInt::getSigned(Int32Ty, Index);
15890 
15891       // Emit the call, then reverse the double words of the results vector.
15892       Value *Call = Builder.CreateCall(F, Ops);
15893 
15894       Value *ShuffleCall =
15895           Builder.CreateShuffleVector(Call, Call, ArrayRef<int>{1, 0});
15896       return ShuffleCall;
15897     } else {
15898       Ops[1] = ConstantInt::getSigned(Int32Ty, Index);
15899       return Builder.CreateCall(F, Ops);
15900     }
15901   }
15902 
15903   case PPC::BI__builtin_vsx_xxpermdi: {
15904     ConstantInt *ArgCI = dyn_cast<ConstantInt>(Ops[2]);
15905     assert(ArgCI && "Third arg must be constant integer!");
15906 
15907     unsigned Index = ArgCI->getZExtValue();
15908     Ops[0] =
15909         Builder.CreateBitCast(Ops[0], llvm::FixedVectorType::get(Int64Ty, 2));
15910     Ops[1] =
15911         Builder.CreateBitCast(Ops[1], llvm::FixedVectorType::get(Int64Ty, 2));
15912 
15913     // Account for endianness by treating this as just a shuffle. So we use the
15914     // same indices for both LE and BE in order to produce expected results in
15915     // both cases.
15916     int ElemIdx0 = (Index & 2) >> 1;
15917     int ElemIdx1 = 2 + (Index & 1);
15918 
15919     int ShuffleElts[2] = {ElemIdx0, ElemIdx1};
15920     Value *ShuffleCall =
15921         Builder.CreateShuffleVector(Ops[0], Ops[1], ShuffleElts);
15922     QualType BIRetType = E->getType();
15923     auto RetTy = ConvertType(BIRetType);
15924     return Builder.CreateBitCast(ShuffleCall, RetTy);
15925   }
15926 
15927   case PPC::BI__builtin_vsx_xxsldwi: {
15928     ConstantInt *ArgCI = dyn_cast<ConstantInt>(Ops[2]);
15929     assert(ArgCI && "Third argument must be a compile time constant");
15930     unsigned Index = ArgCI->getZExtValue() & 0x3;
15931     Ops[0] =
15932         Builder.CreateBitCast(Ops[0], llvm::FixedVectorType::get(Int32Ty, 4));
15933     Ops[1] =
15934         Builder.CreateBitCast(Ops[1], llvm::FixedVectorType::get(Int32Ty, 4));
15935 
15936     // Create a shuffle mask
15937     int ElemIdx0;
15938     int ElemIdx1;
15939     int ElemIdx2;
15940     int ElemIdx3;
15941     if (getTarget().isLittleEndian()) {
15942       // Little endian element N comes from element 8+N-Index of the
15943       // concatenated wide vector (of course, using modulo arithmetic on
15944       // the total number of elements).
15945       ElemIdx0 = (8 - Index) % 8;
15946       ElemIdx1 = (9 - Index) % 8;
15947       ElemIdx2 = (10 - Index) % 8;
15948       ElemIdx3 = (11 - Index) % 8;
15949     } else {
15950       // Big endian ElemIdx<N> = Index + N
15951       ElemIdx0 = Index;
15952       ElemIdx1 = Index + 1;
15953       ElemIdx2 = Index + 2;
15954       ElemIdx3 = Index + 3;
15955     }
15956 
15957     int ShuffleElts[4] = {ElemIdx0, ElemIdx1, ElemIdx2, ElemIdx3};
15958     Value *ShuffleCall =
15959         Builder.CreateShuffleVector(Ops[0], Ops[1], ShuffleElts);
15960     QualType BIRetType = E->getType();
15961     auto RetTy = ConvertType(BIRetType);
15962     return Builder.CreateBitCast(ShuffleCall, RetTy);
15963   }
15964 
15965   case PPC::BI__builtin_pack_vector_int128: {
15966     bool isLittleEndian = getTarget().isLittleEndian();
15967     Value *UndefValue =
15968         llvm::UndefValue::get(llvm::FixedVectorType::get(Ops[0]->getType(), 2));
15969     Value *Res = Builder.CreateInsertElement(
15970         UndefValue, Ops[0], (uint64_t)(isLittleEndian ? 1 : 0));
15971     Res = Builder.CreateInsertElement(Res, Ops[1],
15972                                       (uint64_t)(isLittleEndian ? 0 : 1));
15973     return Builder.CreateBitCast(Res, ConvertType(E->getType()));
15974   }
15975 
15976   case PPC::BI__builtin_unpack_vector_int128: {
15977     ConstantInt *Index = cast<ConstantInt>(Ops[1]);
15978     Value *Unpacked = Builder.CreateBitCast(
15979         Ops[0], llvm::FixedVectorType::get(ConvertType(E->getType()), 2));
15980 
15981     if (getTarget().isLittleEndian())
15982       Index = ConstantInt::get(Index->getType(), 1 - Index->getZExtValue());
15983 
15984     return Builder.CreateExtractElement(Unpacked, Index);
15985   }
15986 
15987   case PPC::BI__builtin_ppc_sthcx: {
15988     llvm::Function *F = CGM.getIntrinsic(Intrinsic::ppc_sthcx);
15989     Ops[0] = Builder.CreateBitCast(Ops[0], Int8PtrTy);
15990     Ops[1] = Builder.CreateSExt(Ops[1], Int32Ty);
15991     return Builder.CreateCall(F, Ops);
15992   }
15993 
15994   // The PPC MMA builtins take a pointer to a __vector_quad as an argument.
15995   // Some of the MMA instructions accumulate their result into an existing
15996   // accumulator whereas the others generate a new accumulator. So we need to
15997   // use custom code generation to expand a builtin call with a pointer to a
15998   // load (if the corresponding instruction accumulates its result) followed by
15999   // the call to the intrinsic and a store of the result.
16000 #define CUSTOM_BUILTIN(Name, Intr, Types, Accumulate) \
16001   case PPC::BI__builtin_##Name:
16002 #include "clang/Basic/BuiltinsPPC.def"
16003   {
16004     // The first argument of these two builtins is a pointer used to store their
16005     // result. However, the llvm intrinsics return their result in multiple
16006     // return values. So, here we emit code extracting these values from the
16007     // intrinsic results and storing them using that pointer.
16008     if (BuiltinID == PPC::BI__builtin_mma_disassemble_acc ||
16009         BuiltinID == PPC::BI__builtin_vsx_disassemble_pair ||
16010         BuiltinID == PPC::BI__builtin_mma_disassemble_pair) {
16011       unsigned NumVecs = 2;
16012       auto Intrinsic = Intrinsic::ppc_vsx_disassemble_pair;
16013       if (BuiltinID == PPC::BI__builtin_mma_disassemble_acc) {
16014         NumVecs = 4;
16015         Intrinsic = Intrinsic::ppc_mma_disassemble_acc;
16016       }
16017       llvm::Function *F = CGM.getIntrinsic(Intrinsic);
16018       Address Addr = EmitPointerWithAlignment(E->getArg(1));
16019       Value *Vec = Builder.CreateLoad(Addr);
16020       Value *Call = Builder.CreateCall(F, {Vec});
16021       llvm::Type *VTy = llvm::FixedVectorType::get(Int8Ty, 16);
16022       Value *Ptr = Builder.CreateBitCast(Ops[0], VTy->getPointerTo());
16023       for (unsigned i=0; i<NumVecs; i++) {
16024         Value *Vec = Builder.CreateExtractValue(Call, i);
16025         llvm::ConstantInt* Index = llvm::ConstantInt::get(IntTy, i);
16026         Value *GEP = Builder.CreateInBoundsGEP(VTy, Ptr, Index);
16027         Builder.CreateAlignedStore(Vec, GEP, MaybeAlign(16));
16028       }
16029       return Call;
16030     }
16031     if (BuiltinID == PPC::BI__builtin_vsx_build_pair ||
16032         BuiltinID == PPC::BI__builtin_mma_build_acc) {
16033       // Reverse the order of the operands for LE, so the
16034       // same builtin call can be used on both LE and BE
16035       // without the need for the programmer to swap operands.
16036       // The operands are reversed starting from the second argument,
16037       // the first operand is the pointer to the pair/accumulator
16038       // that is being built.
16039       if (getTarget().isLittleEndian())
16040         std::reverse(Ops.begin() + 1, Ops.end());
16041     }
16042     bool Accumulate;
16043     switch (BuiltinID) {
16044   #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \
16045     case PPC::BI__builtin_##Name: \
16046       ID = Intrinsic::ppc_##Intr; \
16047       Accumulate = Acc; \
16048       break;
16049   #include "clang/Basic/BuiltinsPPC.def"
16050     }
16051     if (BuiltinID == PPC::BI__builtin_vsx_lxvp ||
16052         BuiltinID == PPC::BI__builtin_vsx_stxvp ||
16053         BuiltinID == PPC::BI__builtin_mma_lxvp ||
16054         BuiltinID == PPC::BI__builtin_mma_stxvp) {
16055       if (BuiltinID == PPC::BI__builtin_vsx_lxvp ||
16056           BuiltinID == PPC::BI__builtin_mma_lxvp) {
16057         Ops[1] = Builder.CreateBitCast(Ops[1], Int8PtrTy);
16058         Ops[0] = Builder.CreateGEP(Int8Ty, Ops[1], Ops[0]);
16059       } else {
16060         Ops[2] = Builder.CreateBitCast(Ops[2], Int8PtrTy);
16061         Ops[1] = Builder.CreateGEP(Int8Ty, Ops[2], Ops[1]);
16062       }
16063       Ops.pop_back();
16064       llvm::Function *F = CGM.getIntrinsic(ID);
16065       return Builder.CreateCall(F, Ops, "");
16066     }
16067     SmallVector<Value*, 4> CallOps;
16068     if (Accumulate) {
16069       Address Addr = EmitPointerWithAlignment(E->getArg(0));
16070       Value *Acc = Builder.CreateLoad(Addr);
16071       CallOps.push_back(Acc);
16072     }
16073     for (unsigned i=1; i<Ops.size(); i++)
16074       CallOps.push_back(Ops[i]);
16075     llvm::Function *F = CGM.getIntrinsic(ID);
16076     Value *Call = Builder.CreateCall(F, CallOps);
16077     return Builder.CreateAlignedStore(Call, Ops[0], MaybeAlign(64));
16078   }
16079 
16080   case PPC::BI__builtin_ppc_compare_and_swap:
16081   case PPC::BI__builtin_ppc_compare_and_swaplp: {
16082     Address Addr = EmitPointerWithAlignment(E->getArg(0));
16083     Address OldValAddr = EmitPointerWithAlignment(E->getArg(1));
16084     Value *OldVal = Builder.CreateLoad(OldValAddr);
16085     QualType AtomicTy = E->getArg(0)->getType()->getPointeeType();
16086     LValue LV = MakeAddrLValue(Addr, AtomicTy);
16087     auto Pair = EmitAtomicCompareExchange(
16088         LV, RValue::get(OldVal), RValue::get(Ops[2]), E->getExprLoc(),
16089         llvm::AtomicOrdering::Monotonic, llvm::AtomicOrdering::Monotonic, true);
16090     // Unlike c11's atomic_compare_exchange, accroding to
16091     // https://www.ibm.com/docs/en/xl-c-and-cpp-aix/16.1?topic=functions-compare-swap-compare-swaplp
16092     // > In either case, the contents of the memory location specified by addr
16093     // > are copied into the memory location specified by old_val_addr.
16094     // But it hasn't specified storing to OldValAddr is atomic or not and
16095     // which order to use. Now following XL's codegen, treat it as a normal
16096     // store.
16097     Value *LoadedVal = Pair.first.getScalarVal();
16098     Builder.CreateStore(LoadedVal, OldValAddr);
16099     return Builder.CreateZExt(Pair.second, Builder.getInt32Ty());
16100   }
16101   case PPC::BI__builtin_ppc_fetch_and_add:
16102   case PPC::BI__builtin_ppc_fetch_and_addlp: {
16103     return MakeBinaryAtomicValue(*this, AtomicRMWInst::Add, E,
16104                                  llvm::AtomicOrdering::Monotonic);
16105   }
16106   case PPC::BI__builtin_ppc_fetch_and_and:
16107   case PPC::BI__builtin_ppc_fetch_and_andlp: {
16108     return MakeBinaryAtomicValue(*this, AtomicRMWInst::And, E,
16109                                  llvm::AtomicOrdering::Monotonic);
16110   }
16111 
16112   case PPC::BI__builtin_ppc_fetch_and_or:
16113   case PPC::BI__builtin_ppc_fetch_and_orlp: {
16114     return MakeBinaryAtomicValue(*this, AtomicRMWInst::Or, E,
16115                                  llvm::AtomicOrdering::Monotonic);
16116   }
16117   case PPC::BI__builtin_ppc_fetch_and_swap:
16118   case PPC::BI__builtin_ppc_fetch_and_swaplp: {
16119     return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xchg, E,
16120                                  llvm::AtomicOrdering::Monotonic);
16121   }
16122   case PPC::BI__builtin_ppc_ldarx:
16123   case PPC::BI__builtin_ppc_lwarx:
16124   case PPC::BI__builtin_ppc_lharx:
16125   case PPC::BI__builtin_ppc_lbarx:
16126     return emitPPCLoadReserveIntrinsic(*this, BuiltinID, E);
16127   case PPC::BI__builtin_ppc_mfspr: {
16128     llvm::Type *RetType = CGM.getDataLayout().getTypeSizeInBits(VoidPtrTy) == 32
16129                               ? Int32Ty
16130                               : Int64Ty;
16131     Function *F = CGM.getIntrinsic(Intrinsic::ppc_mfspr, RetType);
16132     return Builder.CreateCall(F, Ops);
16133   }
16134   case PPC::BI__builtin_ppc_mtspr: {
16135     llvm::Type *RetType = CGM.getDataLayout().getTypeSizeInBits(VoidPtrTy) == 32
16136                               ? Int32Ty
16137                               : Int64Ty;
16138     Function *F = CGM.getIntrinsic(Intrinsic::ppc_mtspr, RetType);
16139     return Builder.CreateCall(F, Ops);
16140   }
16141   case PPC::BI__builtin_ppc_popcntb: {
16142     Value *ArgValue = EmitScalarExpr(E->getArg(0));
16143     llvm::Type *ArgType = ArgValue->getType();
16144     Function *F = CGM.getIntrinsic(Intrinsic::ppc_popcntb, {ArgType, ArgType});
16145     return Builder.CreateCall(F, Ops, "popcntb");
16146   }
16147   case PPC::BI__builtin_ppc_mtfsf: {
16148     // The builtin takes a uint32 that needs to be cast to an
16149     // f64 to be passed to the intrinsic.
16150     Value *Cast = Builder.CreateUIToFP(Ops[1], DoubleTy);
16151     llvm::Function *F = CGM.getIntrinsic(Intrinsic::ppc_mtfsf);
16152     return Builder.CreateCall(F, {Ops[0], Cast}, "");
16153   }
16154 
16155   case PPC::BI__builtin_ppc_swdiv_nochk:
16156   case PPC::BI__builtin_ppc_swdivs_nochk: {
16157     FastMathFlags FMF = Builder.getFastMathFlags();
16158     Builder.getFastMathFlags().setFast();
16159     Value *FDiv = Builder.CreateFDiv(Ops[0], Ops[1], "swdiv_nochk");
16160     Builder.getFastMathFlags() &= (FMF);
16161     return FDiv;
16162   }
16163   case PPC::BI__builtin_ppc_fric:
16164     return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(
16165                            *this, E, Intrinsic::rint,
16166                            Intrinsic::experimental_constrained_rint))
16167         .getScalarVal();
16168   case PPC::BI__builtin_ppc_frim:
16169   case PPC::BI__builtin_ppc_frims:
16170     return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(
16171                            *this, E, Intrinsic::floor,
16172                            Intrinsic::experimental_constrained_floor))
16173         .getScalarVal();
16174   case PPC::BI__builtin_ppc_frin:
16175   case PPC::BI__builtin_ppc_frins:
16176     return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(
16177                            *this, E, Intrinsic::round,
16178                            Intrinsic::experimental_constrained_round))
16179         .getScalarVal();
16180   case PPC::BI__builtin_ppc_frip:
16181   case PPC::BI__builtin_ppc_frips:
16182     return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(
16183                            *this, E, Intrinsic::ceil,
16184                            Intrinsic::experimental_constrained_ceil))
16185         .getScalarVal();
16186   case PPC::BI__builtin_ppc_friz:
16187   case PPC::BI__builtin_ppc_frizs:
16188     return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(
16189                            *this, E, Intrinsic::trunc,
16190                            Intrinsic::experimental_constrained_trunc))
16191         .getScalarVal();
16192   case PPC::BI__builtin_ppc_fsqrt:
16193   case PPC::BI__builtin_ppc_fsqrts:
16194     return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(
16195                            *this, E, Intrinsic::sqrt,
16196                            Intrinsic::experimental_constrained_sqrt))
16197         .getScalarVal();
16198   case PPC::BI__builtin_ppc_test_data_class: {
16199     llvm::Type *ArgType = EmitScalarExpr(E->getArg(0))->getType();
16200     unsigned IntrinsicID;
16201     if (ArgType->isDoubleTy())
16202       IntrinsicID = Intrinsic::ppc_test_data_class_d;
16203     else if (ArgType->isFloatTy())
16204       IntrinsicID = Intrinsic::ppc_test_data_class_f;
16205     else
16206       llvm_unreachable("Invalid Argument Type");
16207     return Builder.CreateCall(CGM.getIntrinsic(IntrinsicID), Ops,
16208                               "test_data_class");
16209   }
16210   case PPC::BI__builtin_ppc_swdiv:
16211   case PPC::BI__builtin_ppc_swdivs:
16212     return Builder.CreateFDiv(Ops[0], Ops[1], "swdiv");
16213   }
16214 }
16215 
16216 namespace {
16217 // If \p E is not null pointer, insert address space cast to match return
16218 // type of \p E if necessary.
16219 Value *EmitAMDGPUDispatchPtr(CodeGenFunction &CGF,
16220                              const CallExpr *E = nullptr) {
16221   auto *F = CGF.CGM.getIntrinsic(Intrinsic::amdgcn_dispatch_ptr);
16222   auto *Call = CGF.Builder.CreateCall(F);
16223   Call->addRetAttr(
16224       Attribute::getWithDereferenceableBytes(Call->getContext(), 64));
16225   Call->addRetAttr(Attribute::getWithAlignment(Call->getContext(), Align(4)));
16226   if (!E)
16227     return Call;
16228   QualType BuiltinRetType = E->getType();
16229   auto *RetTy = cast<llvm::PointerType>(CGF.ConvertType(BuiltinRetType));
16230   if (RetTy == Call->getType())
16231     return Call;
16232   return CGF.Builder.CreateAddrSpaceCast(Call, RetTy);
16233 }
16234 
16235 // \p Index is 0, 1, and 2 for x, y, and z dimension, respectively.
16236 Value *EmitAMDGPUWorkGroupSize(CodeGenFunction &CGF, unsigned Index) {
16237   const unsigned XOffset = 4;
16238   auto *DP = EmitAMDGPUDispatchPtr(CGF);
16239   // Indexing the HSA kernel_dispatch_packet struct.
16240   auto *Offset = llvm::ConstantInt::get(CGF.Int32Ty, XOffset + Index * 2);
16241   auto *GEP = CGF.Builder.CreateGEP(CGF.Int8Ty, DP, Offset);
16242   auto *DstTy =
16243       CGF.Int16Ty->getPointerTo(GEP->getType()->getPointerAddressSpace());
16244   auto *Cast = CGF.Builder.CreateBitCast(GEP, DstTy);
16245   auto *LD = CGF.Builder.CreateLoad(
16246       Address(Cast, CGF.Int16Ty, CharUnits::fromQuantity(2)));
16247   llvm::MDBuilder MDHelper(CGF.getLLVMContext());
16248   llvm::MDNode *RNode = MDHelper.createRange(APInt(16, 1),
16249       APInt(16, CGF.getTarget().getMaxOpenCLWorkGroupSize() + 1));
16250   LD->setMetadata(llvm::LLVMContext::MD_range, RNode);
16251   LD->setMetadata(llvm::LLVMContext::MD_invariant_load,
16252       llvm::MDNode::get(CGF.getLLVMContext(), None));
16253   return LD;
16254 }
16255 
16256 // \p Index is 0, 1, and 2 for x, y, and z dimension, respectively.
16257 Value *EmitAMDGPUGridSize(CodeGenFunction &CGF, unsigned Index) {
16258   const unsigned XOffset = 12;
16259   auto *DP = EmitAMDGPUDispatchPtr(CGF);
16260   // Indexing the HSA kernel_dispatch_packet struct.
16261   auto *Offset = llvm::ConstantInt::get(CGF.Int32Ty, XOffset + Index * 4);
16262   auto *GEP = CGF.Builder.CreateGEP(CGF.Int8Ty, DP, Offset);
16263   auto *DstTy =
16264       CGF.Int32Ty->getPointerTo(GEP->getType()->getPointerAddressSpace());
16265   auto *Cast = CGF.Builder.CreateBitCast(GEP, DstTy);
16266   auto *LD = CGF.Builder.CreateLoad(
16267       Address(Cast, CGF.Int32Ty, CharUnits::fromQuantity(4)));
16268   LD->setMetadata(llvm::LLVMContext::MD_invariant_load,
16269                   llvm::MDNode::get(CGF.getLLVMContext(), None));
16270   return LD;
16271 }
16272 } // namespace
16273 
16274 // For processing memory ordering and memory scope arguments of various
16275 // amdgcn builtins.
16276 // \p Order takes a C++11 comptabile memory-ordering specifier and converts
16277 // it into LLVM's memory ordering specifier using atomic C ABI, and writes
16278 // to \p AO. \p Scope takes a const char * and converts it into AMDGCN
16279 // specific SyncScopeID and writes it to \p SSID.
16280 bool CodeGenFunction::ProcessOrderScopeAMDGCN(Value *Order, Value *Scope,
16281                                               llvm::AtomicOrdering &AO,
16282                                               llvm::SyncScope::ID &SSID) {
16283   if (isa<llvm::ConstantInt>(Order)) {
16284     int ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
16285 
16286     // Map C11/C++11 memory ordering to LLVM memory ordering
16287     assert(llvm::isValidAtomicOrderingCABI(ord));
16288     switch (static_cast<llvm::AtomicOrderingCABI>(ord)) {
16289     case llvm::AtomicOrderingCABI::acquire:
16290     case llvm::AtomicOrderingCABI::consume:
16291       AO = llvm::AtomicOrdering::Acquire;
16292       break;
16293     case llvm::AtomicOrderingCABI::release:
16294       AO = llvm::AtomicOrdering::Release;
16295       break;
16296     case llvm::AtomicOrderingCABI::acq_rel:
16297       AO = llvm::AtomicOrdering::AcquireRelease;
16298       break;
16299     case llvm::AtomicOrderingCABI::seq_cst:
16300       AO = llvm::AtomicOrdering::SequentiallyConsistent;
16301       break;
16302     case llvm::AtomicOrderingCABI::relaxed:
16303       AO = llvm::AtomicOrdering::Monotonic;
16304       break;
16305     }
16306 
16307     StringRef scp;
16308     llvm::getConstantStringInfo(Scope, scp);
16309     SSID = getLLVMContext().getOrInsertSyncScopeID(scp);
16310     return true;
16311   }
16312   return false;
16313 }
16314 
16315 Value *CodeGenFunction::EmitAMDGPUBuiltinExpr(unsigned BuiltinID,
16316                                               const CallExpr *E) {
16317   llvm::AtomicOrdering AO = llvm::AtomicOrdering::SequentiallyConsistent;
16318   llvm::SyncScope::ID SSID;
16319   switch (BuiltinID) {
16320   case AMDGPU::BI__builtin_amdgcn_div_scale:
16321   case AMDGPU::BI__builtin_amdgcn_div_scalef: {
16322     // Translate from the intrinsics's struct return to the builtin's out
16323     // argument.
16324 
16325     Address FlagOutPtr = EmitPointerWithAlignment(E->getArg(3));
16326 
16327     llvm::Value *X = EmitScalarExpr(E->getArg(0));
16328     llvm::Value *Y = EmitScalarExpr(E->getArg(1));
16329     llvm::Value *Z = EmitScalarExpr(E->getArg(2));
16330 
16331     llvm::Function *Callee = CGM.getIntrinsic(Intrinsic::amdgcn_div_scale,
16332                                            X->getType());
16333 
16334     llvm::Value *Tmp = Builder.CreateCall(Callee, {X, Y, Z});
16335 
16336     llvm::Value *Result = Builder.CreateExtractValue(Tmp, 0);
16337     llvm::Value *Flag = Builder.CreateExtractValue(Tmp, 1);
16338 
16339     llvm::Type *RealFlagType = FlagOutPtr.getElementType();
16340 
16341     llvm::Value *FlagExt = Builder.CreateZExt(Flag, RealFlagType);
16342     Builder.CreateStore(FlagExt, FlagOutPtr);
16343     return Result;
16344   }
16345   case AMDGPU::BI__builtin_amdgcn_div_fmas:
16346   case AMDGPU::BI__builtin_amdgcn_div_fmasf: {
16347     llvm::Value *Src0 = EmitScalarExpr(E->getArg(0));
16348     llvm::Value *Src1 = EmitScalarExpr(E->getArg(1));
16349     llvm::Value *Src2 = EmitScalarExpr(E->getArg(2));
16350     llvm::Value *Src3 = EmitScalarExpr(E->getArg(3));
16351 
16352     llvm::Function *F = CGM.getIntrinsic(Intrinsic::amdgcn_div_fmas,
16353                                       Src0->getType());
16354     llvm::Value *Src3ToBool = Builder.CreateIsNotNull(Src3);
16355     return Builder.CreateCall(F, {Src0, Src1, Src2, Src3ToBool});
16356   }
16357 
16358   case AMDGPU::BI__builtin_amdgcn_ds_swizzle:
16359     return emitBinaryBuiltin(*this, E, Intrinsic::amdgcn_ds_swizzle);
16360   case AMDGPU::BI__builtin_amdgcn_mov_dpp8:
16361     return emitBinaryBuiltin(*this, E, Intrinsic::amdgcn_mov_dpp8);
16362   case AMDGPU::BI__builtin_amdgcn_mov_dpp:
16363   case AMDGPU::BI__builtin_amdgcn_update_dpp: {
16364     llvm::SmallVector<llvm::Value *, 6> Args;
16365     for (unsigned I = 0; I != E->getNumArgs(); ++I)
16366       Args.push_back(EmitScalarExpr(E->getArg(I)));
16367     assert(Args.size() == 5 || Args.size() == 6);
16368     if (Args.size() == 5)
16369       Args.insert(Args.begin(), llvm::UndefValue::get(Args[0]->getType()));
16370     Function *F =
16371         CGM.getIntrinsic(Intrinsic::amdgcn_update_dpp, Args[0]->getType());
16372     return Builder.CreateCall(F, Args);
16373   }
16374   case AMDGPU::BI__builtin_amdgcn_div_fixup:
16375   case AMDGPU::BI__builtin_amdgcn_div_fixupf:
16376   case AMDGPU::BI__builtin_amdgcn_div_fixuph:
16377     return emitTernaryBuiltin(*this, E, Intrinsic::amdgcn_div_fixup);
16378   case AMDGPU::BI__builtin_amdgcn_trig_preop:
16379   case AMDGPU::BI__builtin_amdgcn_trig_preopf:
16380     return emitFPIntBuiltin(*this, E, Intrinsic::amdgcn_trig_preop);
16381   case AMDGPU::BI__builtin_amdgcn_rcp:
16382   case AMDGPU::BI__builtin_amdgcn_rcpf:
16383   case AMDGPU::BI__builtin_amdgcn_rcph:
16384     return emitUnaryBuiltin(*this, E, Intrinsic::amdgcn_rcp);
16385   case AMDGPU::BI__builtin_amdgcn_sqrt:
16386   case AMDGPU::BI__builtin_amdgcn_sqrtf:
16387   case AMDGPU::BI__builtin_amdgcn_sqrth:
16388     return emitUnaryBuiltin(*this, E, Intrinsic::amdgcn_sqrt);
16389   case AMDGPU::BI__builtin_amdgcn_rsq:
16390   case AMDGPU::BI__builtin_amdgcn_rsqf:
16391   case AMDGPU::BI__builtin_amdgcn_rsqh:
16392     return emitUnaryBuiltin(*this, E, Intrinsic::amdgcn_rsq);
16393   case AMDGPU::BI__builtin_amdgcn_rsq_clamp:
16394   case AMDGPU::BI__builtin_amdgcn_rsq_clampf:
16395     return emitUnaryBuiltin(*this, E, Intrinsic::amdgcn_rsq_clamp);
16396   case AMDGPU::BI__builtin_amdgcn_sinf:
16397   case AMDGPU::BI__builtin_amdgcn_sinh:
16398     return emitUnaryBuiltin(*this, E, Intrinsic::amdgcn_sin);
16399   case AMDGPU::BI__builtin_amdgcn_cosf:
16400   case AMDGPU::BI__builtin_amdgcn_cosh:
16401     return emitUnaryBuiltin(*this, E, Intrinsic::amdgcn_cos);
16402   case AMDGPU::BI__builtin_amdgcn_dispatch_ptr:
16403     return EmitAMDGPUDispatchPtr(*this, E);
16404   case AMDGPU::BI__builtin_amdgcn_log_clampf:
16405     return emitUnaryBuiltin(*this, E, Intrinsic::amdgcn_log_clamp);
16406   case AMDGPU::BI__builtin_amdgcn_ldexp:
16407   case AMDGPU::BI__builtin_amdgcn_ldexpf:
16408   case AMDGPU::BI__builtin_amdgcn_ldexph:
16409     return emitFPIntBuiltin(*this, E, Intrinsic::amdgcn_ldexp);
16410   case AMDGPU::BI__builtin_amdgcn_frexp_mant:
16411   case AMDGPU::BI__builtin_amdgcn_frexp_mantf:
16412   case AMDGPU::BI__builtin_amdgcn_frexp_manth:
16413     return emitUnaryBuiltin(*this, E, Intrinsic::amdgcn_frexp_mant);
16414   case AMDGPU::BI__builtin_amdgcn_frexp_exp:
16415   case AMDGPU::BI__builtin_amdgcn_frexp_expf: {
16416     Value *Src0 = EmitScalarExpr(E->getArg(0));
16417     Function *F = CGM.getIntrinsic(Intrinsic::amdgcn_frexp_exp,
16418                                 { Builder.getInt32Ty(), Src0->getType() });
16419     return Builder.CreateCall(F, Src0);
16420   }
16421   case AMDGPU::BI__builtin_amdgcn_frexp_exph: {
16422     Value *Src0 = EmitScalarExpr(E->getArg(0));
16423     Function *F = CGM.getIntrinsic(Intrinsic::amdgcn_frexp_exp,
16424                                 { Builder.getInt16Ty(), Src0->getType() });
16425     return Builder.CreateCall(F, Src0);
16426   }
16427   case AMDGPU::BI__builtin_amdgcn_fract:
16428   case AMDGPU::BI__builtin_amdgcn_fractf:
16429   case AMDGPU::BI__builtin_amdgcn_fracth:
16430     return emitUnaryBuiltin(*this, E, Intrinsic::amdgcn_fract);
16431   case AMDGPU::BI__builtin_amdgcn_lerp:
16432     return emitTernaryBuiltin(*this, E, Intrinsic::amdgcn_lerp);
16433   case AMDGPU::BI__builtin_amdgcn_ubfe:
16434     return emitTernaryBuiltin(*this, E, Intrinsic::amdgcn_ubfe);
16435   case AMDGPU::BI__builtin_amdgcn_sbfe:
16436     return emitTernaryBuiltin(*this, E, Intrinsic::amdgcn_sbfe);
16437   case AMDGPU::BI__builtin_amdgcn_uicmp:
16438   case AMDGPU::BI__builtin_amdgcn_uicmpl:
16439   case AMDGPU::BI__builtin_amdgcn_sicmp:
16440   case AMDGPU::BI__builtin_amdgcn_sicmpl: {
16441     llvm::Value *Src0 = EmitScalarExpr(E->getArg(0));
16442     llvm::Value *Src1 = EmitScalarExpr(E->getArg(1));
16443     llvm::Value *Src2 = EmitScalarExpr(E->getArg(2));
16444 
16445     // FIXME-GFX10: How should 32 bit mask be handled?
16446     Function *F = CGM.getIntrinsic(Intrinsic::amdgcn_icmp,
16447       { Builder.getInt64Ty(), Src0->getType() });
16448     return Builder.CreateCall(F, { Src0, Src1, Src2 });
16449   }
16450   case AMDGPU::BI__builtin_amdgcn_fcmp:
16451   case AMDGPU::BI__builtin_amdgcn_fcmpf: {
16452     llvm::Value *Src0 = EmitScalarExpr(E->getArg(0));
16453     llvm::Value *Src1 = EmitScalarExpr(E->getArg(1));
16454     llvm::Value *Src2 = EmitScalarExpr(E->getArg(2));
16455 
16456     // FIXME-GFX10: How should 32 bit mask be handled?
16457     Function *F = CGM.getIntrinsic(Intrinsic::amdgcn_fcmp,
16458       { Builder.getInt64Ty(), Src0->getType() });
16459     return Builder.CreateCall(F, { Src0, Src1, Src2 });
16460   }
16461   case AMDGPU::BI__builtin_amdgcn_class:
16462   case AMDGPU::BI__builtin_amdgcn_classf:
16463   case AMDGPU::BI__builtin_amdgcn_classh:
16464     return emitFPIntBuiltin(*this, E, Intrinsic::amdgcn_class);
16465   case AMDGPU::BI__builtin_amdgcn_fmed3f:
16466   case AMDGPU::BI__builtin_amdgcn_fmed3h:
16467     return emitTernaryBuiltin(*this, E, Intrinsic::amdgcn_fmed3);
16468   case AMDGPU::BI__builtin_amdgcn_ds_append:
16469   case AMDGPU::BI__builtin_amdgcn_ds_consume: {
16470     Intrinsic::ID Intrin = BuiltinID == AMDGPU::BI__builtin_amdgcn_ds_append ?
16471       Intrinsic::amdgcn_ds_append : Intrinsic::amdgcn_ds_consume;
16472     Value *Src0 = EmitScalarExpr(E->getArg(0));
16473     Function *F = CGM.getIntrinsic(Intrin, { Src0->getType() });
16474     return Builder.CreateCall(F, { Src0, Builder.getFalse() });
16475   }
16476   case AMDGPU::BI__builtin_amdgcn_ds_faddf:
16477   case AMDGPU::BI__builtin_amdgcn_ds_fminf:
16478   case AMDGPU::BI__builtin_amdgcn_ds_fmaxf: {
16479     Intrinsic::ID Intrin;
16480     switch (BuiltinID) {
16481     case AMDGPU::BI__builtin_amdgcn_ds_faddf:
16482       Intrin = Intrinsic::amdgcn_ds_fadd;
16483       break;
16484     case AMDGPU::BI__builtin_amdgcn_ds_fminf:
16485       Intrin = Intrinsic::amdgcn_ds_fmin;
16486       break;
16487     case AMDGPU::BI__builtin_amdgcn_ds_fmaxf:
16488       Intrin = Intrinsic::amdgcn_ds_fmax;
16489       break;
16490     }
16491     llvm::Value *Src0 = EmitScalarExpr(E->getArg(0));
16492     llvm::Value *Src1 = EmitScalarExpr(E->getArg(1));
16493     llvm::Value *Src2 = EmitScalarExpr(E->getArg(2));
16494     llvm::Value *Src3 = EmitScalarExpr(E->getArg(3));
16495     llvm::Value *Src4 = EmitScalarExpr(E->getArg(4));
16496     llvm::Function *F = CGM.getIntrinsic(Intrin, { Src1->getType() });
16497     llvm::FunctionType *FTy = F->getFunctionType();
16498     llvm::Type *PTy = FTy->getParamType(0);
16499     Src0 = Builder.CreatePointerBitCastOrAddrSpaceCast(Src0, PTy);
16500     return Builder.CreateCall(F, { Src0, Src1, Src2, Src3, Src4 });
16501   }
16502   case AMDGPU::BI__builtin_amdgcn_global_atomic_fadd_f64:
16503   case AMDGPU::BI__builtin_amdgcn_global_atomic_fadd_f32:
16504   case AMDGPU::BI__builtin_amdgcn_global_atomic_fadd_v2f16:
16505   case AMDGPU::BI__builtin_amdgcn_global_atomic_fmin_f64:
16506   case AMDGPU::BI__builtin_amdgcn_global_atomic_fmax_f64:
16507   case AMDGPU::BI__builtin_amdgcn_flat_atomic_fadd_f64:
16508   case AMDGPU::BI__builtin_amdgcn_flat_atomic_fmin_f64:
16509   case AMDGPU::BI__builtin_amdgcn_flat_atomic_fmax_f64: {
16510     Intrinsic::ID IID;
16511     llvm::Type *ArgTy = llvm::Type::getDoubleTy(getLLVMContext());
16512     switch (BuiltinID) {
16513     case AMDGPU::BI__builtin_amdgcn_global_atomic_fadd_f32:
16514       ArgTy = llvm::Type::getFloatTy(getLLVMContext());
16515       IID = Intrinsic::amdgcn_global_atomic_fadd;
16516       break;
16517     case AMDGPU::BI__builtin_amdgcn_global_atomic_fadd_v2f16:
16518       ArgTy = llvm::FixedVectorType::get(
16519           llvm::Type::getHalfTy(getLLVMContext()), 2);
16520       IID = Intrinsic::amdgcn_global_atomic_fadd;
16521       break;
16522     case AMDGPU::BI__builtin_amdgcn_global_atomic_fadd_f64:
16523       IID = Intrinsic::amdgcn_global_atomic_fadd;
16524       break;
16525     case AMDGPU::BI__builtin_amdgcn_global_atomic_fmin_f64:
16526       IID = Intrinsic::amdgcn_global_atomic_fmin;
16527       break;
16528     case AMDGPU::BI__builtin_amdgcn_global_atomic_fmax_f64:
16529       IID = Intrinsic::amdgcn_global_atomic_fmax;
16530       break;
16531     case AMDGPU::BI__builtin_amdgcn_flat_atomic_fadd_f64:
16532       IID = Intrinsic::amdgcn_flat_atomic_fadd;
16533       break;
16534     case AMDGPU::BI__builtin_amdgcn_flat_atomic_fmin_f64:
16535       IID = Intrinsic::amdgcn_flat_atomic_fmin;
16536       break;
16537     case AMDGPU::BI__builtin_amdgcn_flat_atomic_fmax_f64:
16538       IID = Intrinsic::amdgcn_flat_atomic_fmax;
16539       break;
16540     }
16541     llvm::Value *Addr = EmitScalarExpr(E->getArg(0));
16542     llvm::Value *Val = EmitScalarExpr(E->getArg(1));
16543     llvm::Function *F =
16544         CGM.getIntrinsic(IID, {ArgTy, Addr->getType(), Val->getType()});
16545     return Builder.CreateCall(F, {Addr, Val});
16546   }
16547   case AMDGPU::BI__builtin_amdgcn_ds_atomic_fadd_f64:
16548   case AMDGPU::BI__builtin_amdgcn_ds_atomic_fadd_f32: {
16549     Intrinsic::ID IID;
16550     llvm::Type *ArgTy;
16551     switch (BuiltinID) {
16552     case AMDGPU::BI__builtin_amdgcn_ds_atomic_fadd_f32:
16553       ArgTy = llvm::Type::getFloatTy(getLLVMContext());
16554       IID = Intrinsic::amdgcn_ds_fadd;
16555       break;
16556     case AMDGPU::BI__builtin_amdgcn_ds_atomic_fadd_f64:
16557       ArgTy = llvm::Type::getDoubleTy(getLLVMContext());
16558       IID = Intrinsic::amdgcn_ds_fadd;
16559       break;
16560     }
16561     llvm::Value *Addr = EmitScalarExpr(E->getArg(0));
16562     llvm::Value *Val = EmitScalarExpr(E->getArg(1));
16563     llvm::Constant *ZeroI32 = llvm::ConstantInt::getIntegerValue(
16564         llvm::Type::getInt32Ty(getLLVMContext()), APInt(32, 0, true));
16565     llvm::Constant *ZeroI1 = llvm::ConstantInt::getIntegerValue(
16566         llvm::Type::getInt1Ty(getLLVMContext()), APInt(1, 0));
16567     llvm::Function *F = CGM.getIntrinsic(IID, {ArgTy});
16568     return Builder.CreateCall(F, {Addr, Val, ZeroI32, ZeroI32, ZeroI1});
16569   }
16570   case AMDGPU::BI__builtin_amdgcn_read_exec: {
16571     CallInst *CI = cast<CallInst>(
16572       EmitSpecialRegisterBuiltin(*this, E, Int64Ty, Int64Ty, NormalRead, "exec"));
16573     CI->setConvergent();
16574     return CI;
16575   }
16576   case AMDGPU::BI__builtin_amdgcn_read_exec_lo:
16577   case AMDGPU::BI__builtin_amdgcn_read_exec_hi: {
16578     StringRef RegName = BuiltinID == AMDGPU::BI__builtin_amdgcn_read_exec_lo ?
16579       "exec_lo" : "exec_hi";
16580     CallInst *CI = cast<CallInst>(
16581       EmitSpecialRegisterBuiltin(*this, E, Int32Ty, Int32Ty, NormalRead, RegName));
16582     CI->setConvergent();
16583     return CI;
16584   }
16585   case AMDGPU::BI__builtin_amdgcn_image_bvh_intersect_ray:
16586   case AMDGPU::BI__builtin_amdgcn_image_bvh_intersect_ray_h:
16587   case AMDGPU::BI__builtin_amdgcn_image_bvh_intersect_ray_l:
16588   case AMDGPU::BI__builtin_amdgcn_image_bvh_intersect_ray_lh: {
16589     llvm::Value *NodePtr = EmitScalarExpr(E->getArg(0));
16590     llvm::Value *RayExtent = EmitScalarExpr(E->getArg(1));
16591     llvm::Value *RayOrigin = EmitScalarExpr(E->getArg(2));
16592     llvm::Value *RayDir = EmitScalarExpr(E->getArg(3));
16593     llvm::Value *RayInverseDir = EmitScalarExpr(E->getArg(4));
16594     llvm::Value *TextureDescr = EmitScalarExpr(E->getArg(5));
16595 
16596     // The builtins take these arguments as vec4 where the last element is
16597     // ignored. The intrinsic takes them as vec3.
16598     RayOrigin = Builder.CreateShuffleVector(RayOrigin, RayOrigin,
16599                                             ArrayRef<int>{0, 1, 2});
16600     RayDir =
16601         Builder.CreateShuffleVector(RayDir, RayDir, ArrayRef<int>{0, 1, 2});
16602     RayInverseDir = Builder.CreateShuffleVector(RayInverseDir, RayInverseDir,
16603                                                 ArrayRef<int>{0, 1, 2});
16604 
16605     Function *F = CGM.getIntrinsic(Intrinsic::amdgcn_image_bvh_intersect_ray,
16606                                    {NodePtr->getType(), RayDir->getType()});
16607     return Builder.CreateCall(F, {NodePtr, RayExtent, RayOrigin, RayDir,
16608                                   RayInverseDir, TextureDescr});
16609   }
16610 
16611   // amdgcn workitem
16612   case AMDGPU::BI__builtin_amdgcn_workitem_id_x:
16613     return emitRangedBuiltin(*this, Intrinsic::amdgcn_workitem_id_x, 0, 1024);
16614   case AMDGPU::BI__builtin_amdgcn_workitem_id_y:
16615     return emitRangedBuiltin(*this, Intrinsic::amdgcn_workitem_id_y, 0, 1024);
16616   case AMDGPU::BI__builtin_amdgcn_workitem_id_z:
16617     return emitRangedBuiltin(*this, Intrinsic::amdgcn_workitem_id_z, 0, 1024);
16618 
16619   // amdgcn workgroup size
16620   case AMDGPU::BI__builtin_amdgcn_workgroup_size_x:
16621     return EmitAMDGPUWorkGroupSize(*this, 0);
16622   case AMDGPU::BI__builtin_amdgcn_workgroup_size_y:
16623     return EmitAMDGPUWorkGroupSize(*this, 1);
16624   case AMDGPU::BI__builtin_amdgcn_workgroup_size_z:
16625     return EmitAMDGPUWorkGroupSize(*this, 2);
16626 
16627   // amdgcn grid size
16628   case AMDGPU::BI__builtin_amdgcn_grid_size_x:
16629     return EmitAMDGPUGridSize(*this, 0);
16630   case AMDGPU::BI__builtin_amdgcn_grid_size_y:
16631     return EmitAMDGPUGridSize(*this, 1);
16632   case AMDGPU::BI__builtin_amdgcn_grid_size_z:
16633     return EmitAMDGPUGridSize(*this, 2);
16634 
16635   // r600 intrinsics
16636   case AMDGPU::BI__builtin_r600_recipsqrt_ieee:
16637   case AMDGPU::BI__builtin_r600_recipsqrt_ieeef:
16638     return emitUnaryBuiltin(*this, E, Intrinsic::r600_recipsqrt_ieee);
16639   case AMDGPU::BI__builtin_r600_read_tidig_x:
16640     return emitRangedBuiltin(*this, Intrinsic::r600_read_tidig_x, 0, 1024);
16641   case AMDGPU::BI__builtin_r600_read_tidig_y:
16642     return emitRangedBuiltin(*this, Intrinsic::r600_read_tidig_y, 0, 1024);
16643   case AMDGPU::BI__builtin_r600_read_tidig_z:
16644     return emitRangedBuiltin(*this, Intrinsic::r600_read_tidig_z, 0, 1024);
16645   case AMDGPU::BI__builtin_amdgcn_alignbit: {
16646     llvm::Value *Src0 = EmitScalarExpr(E->getArg(0));
16647     llvm::Value *Src1 = EmitScalarExpr(E->getArg(1));
16648     llvm::Value *Src2 = EmitScalarExpr(E->getArg(2));
16649     Function *F = CGM.getIntrinsic(Intrinsic::fshr, Src0->getType());
16650     return Builder.CreateCall(F, { Src0, Src1, Src2 });
16651   }
16652 
16653   case AMDGPU::BI__builtin_amdgcn_fence: {
16654     if (ProcessOrderScopeAMDGCN(EmitScalarExpr(E->getArg(0)),
16655                                 EmitScalarExpr(E->getArg(1)), AO, SSID))
16656       return Builder.CreateFence(AO, SSID);
16657     LLVM_FALLTHROUGH;
16658   }
16659   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
16660   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
16661   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
16662   case AMDGPU::BI__builtin_amdgcn_atomic_dec64: {
16663     unsigned BuiltinAtomicOp;
16664     llvm::Type *ResultType = ConvertType(E->getType());
16665 
16666     switch (BuiltinID) {
16667     case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
16668     case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
16669       BuiltinAtomicOp = Intrinsic::amdgcn_atomic_inc;
16670       break;
16671     case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
16672     case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
16673       BuiltinAtomicOp = Intrinsic::amdgcn_atomic_dec;
16674       break;
16675     }
16676 
16677     Value *Ptr = EmitScalarExpr(E->getArg(0));
16678     Value *Val = EmitScalarExpr(E->getArg(1));
16679 
16680     llvm::Function *F =
16681         CGM.getIntrinsic(BuiltinAtomicOp, {ResultType, Ptr->getType()});
16682 
16683     if (ProcessOrderScopeAMDGCN(EmitScalarExpr(E->getArg(2)),
16684                                 EmitScalarExpr(E->getArg(3)), AO, SSID)) {
16685 
16686       // llvm.amdgcn.atomic.inc and llvm.amdgcn.atomic.dec expects ordering and
16687       // scope as unsigned values
16688       Value *MemOrder = Builder.getInt32(static_cast<int>(AO));
16689       Value *MemScope = Builder.getInt32(static_cast<int>(SSID));
16690 
16691       QualType PtrTy = E->getArg(0)->IgnoreImpCasts()->getType();
16692       bool Volatile =
16693           PtrTy->castAs<PointerType>()->getPointeeType().isVolatileQualified();
16694       Value *IsVolatile = Builder.getInt1(static_cast<bool>(Volatile));
16695 
16696       return Builder.CreateCall(F, {Ptr, Val, MemOrder, MemScope, IsVolatile});
16697     }
16698     LLVM_FALLTHROUGH;
16699   }
16700   default:
16701     return nullptr;
16702   }
16703 }
16704 
16705 /// Handle a SystemZ function in which the final argument is a pointer
16706 /// to an int that receives the post-instruction CC value.  At the LLVM level
16707 /// this is represented as a function that returns a {result, cc} pair.
16708 static Value *EmitSystemZIntrinsicWithCC(CodeGenFunction &CGF,
16709                                          unsigned IntrinsicID,
16710                                          const CallExpr *E) {
16711   unsigned NumArgs = E->getNumArgs() - 1;
16712   SmallVector<Value *, 8> Args(NumArgs);
16713   for (unsigned I = 0; I < NumArgs; ++I)
16714     Args[I] = CGF.EmitScalarExpr(E->getArg(I));
16715   Address CCPtr = CGF.EmitPointerWithAlignment(E->getArg(NumArgs));
16716   Function *F = CGF.CGM.getIntrinsic(IntrinsicID);
16717   Value *Call = CGF.Builder.CreateCall(F, Args);
16718   Value *CC = CGF.Builder.CreateExtractValue(Call, 1);
16719   CGF.Builder.CreateStore(CC, CCPtr);
16720   return CGF.Builder.CreateExtractValue(Call, 0);
16721 }
16722 
16723 Value *CodeGenFunction::EmitSystemZBuiltinExpr(unsigned BuiltinID,
16724                                                const CallExpr *E) {
16725   switch (BuiltinID) {
16726   case SystemZ::BI__builtin_tbegin: {
16727     Value *TDB = EmitScalarExpr(E->getArg(0));
16728     Value *Control = llvm::ConstantInt::get(Int32Ty, 0xff0c);
16729     Function *F = CGM.getIntrinsic(Intrinsic::s390_tbegin);
16730     return Builder.CreateCall(F, {TDB, Control});
16731   }
16732   case SystemZ::BI__builtin_tbegin_nofloat: {
16733     Value *TDB = EmitScalarExpr(E->getArg(0));
16734     Value *Control = llvm::ConstantInt::get(Int32Ty, 0xff0c);
16735     Function *F = CGM.getIntrinsic(Intrinsic::s390_tbegin_nofloat);
16736     return Builder.CreateCall(F, {TDB, Control});
16737   }
16738   case SystemZ::BI__builtin_tbeginc: {
16739     Value *TDB = llvm::ConstantPointerNull::get(Int8PtrTy);
16740     Value *Control = llvm::ConstantInt::get(Int32Ty, 0xff08);
16741     Function *F = CGM.getIntrinsic(Intrinsic::s390_tbeginc);
16742     return Builder.CreateCall(F, {TDB, Control});
16743   }
16744   case SystemZ::BI__builtin_tabort: {
16745     Value *Data = EmitScalarExpr(E->getArg(0));
16746     Function *F = CGM.getIntrinsic(Intrinsic::s390_tabort);
16747     return Builder.CreateCall(F, Builder.CreateSExt(Data, Int64Ty, "tabort"));
16748   }
16749   case SystemZ::BI__builtin_non_tx_store: {
16750     Value *Address = EmitScalarExpr(E->getArg(0));
16751     Value *Data = EmitScalarExpr(E->getArg(1));
16752     Function *F = CGM.getIntrinsic(Intrinsic::s390_ntstg);
16753     return Builder.CreateCall(F, {Data, Address});
16754   }
16755 
16756   // Vector builtins.  Note that most vector builtins are mapped automatically
16757   // to target-specific LLVM intrinsics.  The ones handled specially here can
16758   // be represented via standard LLVM IR, which is preferable to enable common
16759   // LLVM optimizations.
16760 
16761   case SystemZ::BI__builtin_s390_vpopctb:
16762   case SystemZ::BI__builtin_s390_vpopcth:
16763   case SystemZ::BI__builtin_s390_vpopctf:
16764   case SystemZ::BI__builtin_s390_vpopctg: {
16765     llvm::Type *ResultType = ConvertType(E->getType());
16766     Value *X = EmitScalarExpr(E->getArg(0));
16767     Function *F = CGM.getIntrinsic(Intrinsic::ctpop, ResultType);
16768     return Builder.CreateCall(F, X);
16769   }
16770 
16771   case SystemZ::BI__builtin_s390_vclzb:
16772   case SystemZ::BI__builtin_s390_vclzh:
16773   case SystemZ::BI__builtin_s390_vclzf:
16774   case SystemZ::BI__builtin_s390_vclzg: {
16775     llvm::Type *ResultType = ConvertType(E->getType());
16776     Value *X = EmitScalarExpr(E->getArg(0));
16777     Value *Undef = ConstantInt::get(Builder.getInt1Ty(), false);
16778     Function *F = CGM.getIntrinsic(Intrinsic::ctlz, ResultType);
16779     return Builder.CreateCall(F, {X, Undef});
16780   }
16781 
16782   case SystemZ::BI__builtin_s390_vctzb:
16783   case SystemZ::BI__builtin_s390_vctzh:
16784   case SystemZ::BI__builtin_s390_vctzf:
16785   case SystemZ::BI__builtin_s390_vctzg: {
16786     llvm::Type *ResultType = ConvertType(E->getType());
16787     Value *X = EmitScalarExpr(E->getArg(0));
16788     Value *Undef = ConstantInt::get(Builder.getInt1Ty(), false);
16789     Function *F = CGM.getIntrinsic(Intrinsic::cttz, ResultType);
16790     return Builder.CreateCall(F, {X, Undef});
16791   }
16792 
16793   case SystemZ::BI__builtin_s390_vfsqsb:
16794   case SystemZ::BI__builtin_s390_vfsqdb: {
16795     llvm::Type *ResultType = ConvertType(E->getType());
16796     Value *X = EmitScalarExpr(E->getArg(0));
16797     if (Builder.getIsFPConstrained()) {
16798       Function *F = CGM.getIntrinsic(Intrinsic::experimental_constrained_sqrt, ResultType);
16799       return Builder.CreateConstrainedFPCall(F, { X });
16800     } else {
16801       Function *F = CGM.getIntrinsic(Intrinsic::sqrt, ResultType);
16802       return Builder.CreateCall(F, X);
16803     }
16804   }
16805   case SystemZ::BI__builtin_s390_vfmasb:
16806   case SystemZ::BI__builtin_s390_vfmadb: {
16807     llvm::Type *ResultType = ConvertType(E->getType());
16808     Value *X = EmitScalarExpr(E->getArg(0));
16809     Value *Y = EmitScalarExpr(E->getArg(1));
16810     Value *Z = EmitScalarExpr(E->getArg(2));
16811     if (Builder.getIsFPConstrained()) {
16812       Function *F = CGM.getIntrinsic(Intrinsic::experimental_constrained_fma, ResultType);
16813       return Builder.CreateConstrainedFPCall(F, {X, Y, Z});
16814     } else {
16815       Function *F = CGM.getIntrinsic(Intrinsic::fma, ResultType);
16816       return Builder.CreateCall(F, {X, Y, Z});
16817     }
16818   }
16819   case SystemZ::BI__builtin_s390_vfmssb:
16820   case SystemZ::BI__builtin_s390_vfmsdb: {
16821     llvm::Type *ResultType = ConvertType(E->getType());
16822     Value *X = EmitScalarExpr(E->getArg(0));
16823     Value *Y = EmitScalarExpr(E->getArg(1));
16824     Value *Z = EmitScalarExpr(E->getArg(2));
16825     if (Builder.getIsFPConstrained()) {
16826       Function *F = CGM.getIntrinsic(Intrinsic::experimental_constrained_fma, ResultType);
16827       return Builder.CreateConstrainedFPCall(F, {X, Y, Builder.CreateFNeg(Z, "neg")});
16828     } else {
16829       Function *F = CGM.getIntrinsic(Intrinsic::fma, ResultType);
16830       return Builder.CreateCall(F, {X, Y, Builder.CreateFNeg(Z, "neg")});
16831     }
16832   }
16833   case SystemZ::BI__builtin_s390_vfnmasb:
16834   case SystemZ::BI__builtin_s390_vfnmadb: {
16835     llvm::Type *ResultType = ConvertType(E->getType());
16836     Value *X = EmitScalarExpr(E->getArg(0));
16837     Value *Y = EmitScalarExpr(E->getArg(1));
16838     Value *Z = EmitScalarExpr(E->getArg(2));
16839     if (Builder.getIsFPConstrained()) {
16840       Function *F = CGM.getIntrinsic(Intrinsic::experimental_constrained_fma, ResultType);
16841       return Builder.CreateFNeg(Builder.CreateConstrainedFPCall(F, {X, Y,  Z}), "neg");
16842     } else {
16843       Function *F = CGM.getIntrinsic(Intrinsic::fma, ResultType);
16844       return Builder.CreateFNeg(Builder.CreateCall(F, {X, Y, Z}), "neg");
16845     }
16846   }
16847   case SystemZ::BI__builtin_s390_vfnmssb:
16848   case SystemZ::BI__builtin_s390_vfnmsdb: {
16849     llvm::Type *ResultType = ConvertType(E->getType());
16850     Value *X = EmitScalarExpr(E->getArg(0));
16851     Value *Y = EmitScalarExpr(E->getArg(1));
16852     Value *Z = EmitScalarExpr(E->getArg(2));
16853     if (Builder.getIsFPConstrained()) {
16854       Function *F = CGM.getIntrinsic(Intrinsic::experimental_constrained_fma, ResultType);
16855       Value *NegZ = Builder.CreateFNeg(Z, "sub");
16856       return Builder.CreateFNeg(Builder.CreateConstrainedFPCall(F, {X, Y, NegZ}));
16857     } else {
16858       Function *F = CGM.getIntrinsic(Intrinsic::fma, ResultType);
16859       Value *NegZ = Builder.CreateFNeg(Z, "neg");
16860       return Builder.CreateFNeg(Builder.CreateCall(F, {X, Y, NegZ}));
16861     }
16862   }
16863   case SystemZ::BI__builtin_s390_vflpsb:
16864   case SystemZ::BI__builtin_s390_vflpdb: {
16865     llvm::Type *ResultType = ConvertType(E->getType());
16866     Value *X = EmitScalarExpr(E->getArg(0));
16867     Function *F = CGM.getIntrinsic(Intrinsic::fabs, ResultType);
16868     return Builder.CreateCall(F, X);
16869   }
16870   case SystemZ::BI__builtin_s390_vflnsb:
16871   case SystemZ::BI__builtin_s390_vflndb: {
16872     llvm::Type *ResultType = ConvertType(E->getType());
16873     Value *X = EmitScalarExpr(E->getArg(0));
16874     Function *F = CGM.getIntrinsic(Intrinsic::fabs, ResultType);
16875     return Builder.CreateFNeg(Builder.CreateCall(F, X), "neg");
16876   }
16877   case SystemZ::BI__builtin_s390_vfisb:
16878   case SystemZ::BI__builtin_s390_vfidb: {
16879     llvm::Type *ResultType = ConvertType(E->getType());
16880     Value *X = EmitScalarExpr(E->getArg(0));
16881     // Constant-fold the M4 and M5 mask arguments.
16882     llvm::APSInt M4 = *E->getArg(1)->getIntegerConstantExpr(getContext());
16883     llvm::APSInt M5 = *E->getArg(2)->getIntegerConstantExpr(getContext());
16884     // Check whether this instance can be represented via a LLVM standard
16885     // intrinsic.  We only support some combinations of M4 and M5.
16886     Intrinsic::ID ID = Intrinsic::not_intrinsic;
16887     Intrinsic::ID CI;
16888     switch (M4.getZExtValue()) {
16889     default: break;
16890     case 0:  // IEEE-inexact exception allowed
16891       switch (M5.getZExtValue()) {
16892       default: break;
16893       case 0: ID = Intrinsic::rint;
16894               CI = Intrinsic::experimental_constrained_rint; break;
16895       }
16896       break;
16897     case 4:  // IEEE-inexact exception suppressed
16898       switch (M5.getZExtValue()) {
16899       default: break;
16900       case 0: ID = Intrinsic::nearbyint;
16901               CI = Intrinsic::experimental_constrained_nearbyint; break;
16902       case 1: ID = Intrinsic::round;
16903               CI = Intrinsic::experimental_constrained_round; break;
16904       case 5: ID = Intrinsic::trunc;
16905               CI = Intrinsic::experimental_constrained_trunc; break;
16906       case 6: ID = Intrinsic::ceil;
16907               CI = Intrinsic::experimental_constrained_ceil; break;
16908       case 7: ID = Intrinsic::floor;
16909               CI = Intrinsic::experimental_constrained_floor; break;
16910       }
16911       break;
16912     }
16913     if (ID != Intrinsic::not_intrinsic) {
16914       if (Builder.getIsFPConstrained()) {
16915         Function *F = CGM.getIntrinsic(CI, ResultType);
16916         return Builder.CreateConstrainedFPCall(F, X);
16917       } else {
16918         Function *F = CGM.getIntrinsic(ID, ResultType);
16919         return Builder.CreateCall(F, X);
16920       }
16921     }
16922     switch (BuiltinID) { // FIXME: constrained version?
16923       case SystemZ::BI__builtin_s390_vfisb: ID = Intrinsic::s390_vfisb; break;
16924       case SystemZ::BI__builtin_s390_vfidb: ID = Intrinsic::s390_vfidb; break;
16925       default: llvm_unreachable("Unknown BuiltinID");
16926     }
16927     Function *F = CGM.getIntrinsic(ID);
16928     Value *M4Value = llvm::ConstantInt::get(getLLVMContext(), M4);
16929     Value *M5Value = llvm::ConstantInt::get(getLLVMContext(), M5);
16930     return Builder.CreateCall(F, {X, M4Value, M5Value});
16931   }
16932   case SystemZ::BI__builtin_s390_vfmaxsb:
16933   case SystemZ::BI__builtin_s390_vfmaxdb: {
16934     llvm::Type *ResultType = ConvertType(E->getType());
16935     Value *X = EmitScalarExpr(E->getArg(0));
16936     Value *Y = EmitScalarExpr(E->getArg(1));
16937     // Constant-fold the M4 mask argument.
16938     llvm::APSInt M4 = *E->getArg(2)->getIntegerConstantExpr(getContext());
16939     // Check whether this instance can be represented via a LLVM standard
16940     // intrinsic.  We only support some values of M4.
16941     Intrinsic::ID ID = Intrinsic::not_intrinsic;
16942     Intrinsic::ID CI;
16943     switch (M4.getZExtValue()) {
16944     default: break;
16945     case 4: ID = Intrinsic::maxnum;
16946             CI = Intrinsic::experimental_constrained_maxnum; break;
16947     }
16948     if (ID != Intrinsic::not_intrinsic) {
16949       if (Builder.getIsFPConstrained()) {
16950         Function *F = CGM.getIntrinsic(CI, ResultType);
16951         return Builder.CreateConstrainedFPCall(F, {X, Y});
16952       } else {
16953         Function *F = CGM.getIntrinsic(ID, ResultType);
16954         return Builder.CreateCall(F, {X, Y});
16955       }
16956     }
16957     switch (BuiltinID) {
16958       case SystemZ::BI__builtin_s390_vfmaxsb: ID = Intrinsic::s390_vfmaxsb; break;
16959       case SystemZ::BI__builtin_s390_vfmaxdb: ID = Intrinsic::s390_vfmaxdb; break;
16960       default: llvm_unreachable("Unknown BuiltinID");
16961     }
16962     Function *F = CGM.getIntrinsic(ID);
16963     Value *M4Value = llvm::ConstantInt::get(getLLVMContext(), M4);
16964     return Builder.CreateCall(F, {X, Y, M4Value});
16965   }
16966   case SystemZ::BI__builtin_s390_vfminsb:
16967   case SystemZ::BI__builtin_s390_vfmindb: {
16968     llvm::Type *ResultType = ConvertType(E->getType());
16969     Value *X = EmitScalarExpr(E->getArg(0));
16970     Value *Y = EmitScalarExpr(E->getArg(1));
16971     // Constant-fold the M4 mask argument.
16972     llvm::APSInt M4 = *E->getArg(2)->getIntegerConstantExpr(getContext());
16973     // Check whether this instance can be represented via a LLVM standard
16974     // intrinsic.  We only support some values of M4.
16975     Intrinsic::ID ID = Intrinsic::not_intrinsic;
16976     Intrinsic::ID CI;
16977     switch (M4.getZExtValue()) {
16978     default: break;
16979     case 4: ID = Intrinsic::minnum;
16980             CI = Intrinsic::experimental_constrained_minnum; break;
16981     }
16982     if (ID != Intrinsic::not_intrinsic) {
16983       if (Builder.getIsFPConstrained()) {
16984         Function *F = CGM.getIntrinsic(CI, ResultType);
16985         return Builder.CreateConstrainedFPCall(F, {X, Y});
16986       } else {
16987         Function *F = CGM.getIntrinsic(ID, ResultType);
16988         return Builder.CreateCall(F, {X, Y});
16989       }
16990     }
16991     switch (BuiltinID) {
16992       case SystemZ::BI__builtin_s390_vfminsb: ID = Intrinsic::s390_vfminsb; break;
16993       case SystemZ::BI__builtin_s390_vfmindb: ID = Intrinsic::s390_vfmindb; break;
16994       default: llvm_unreachable("Unknown BuiltinID");
16995     }
16996     Function *F = CGM.getIntrinsic(ID);
16997     Value *M4Value = llvm::ConstantInt::get(getLLVMContext(), M4);
16998     return Builder.CreateCall(F, {X, Y, M4Value});
16999   }
17000 
17001   case SystemZ::BI__builtin_s390_vlbrh:
17002   case SystemZ::BI__builtin_s390_vlbrf:
17003   case SystemZ::BI__builtin_s390_vlbrg: {
17004     llvm::Type *ResultType = ConvertType(E->getType());
17005     Value *X = EmitScalarExpr(E->getArg(0));
17006     Function *F = CGM.getIntrinsic(Intrinsic::bswap, ResultType);
17007     return Builder.CreateCall(F, X);
17008   }
17009 
17010   // Vector intrinsics that output the post-instruction CC value.
17011 
17012 #define INTRINSIC_WITH_CC(NAME) \
17013     case SystemZ::BI__builtin_##NAME: \
17014       return EmitSystemZIntrinsicWithCC(*this, Intrinsic::NAME, E)
17015 
17016   INTRINSIC_WITH_CC(s390_vpkshs);
17017   INTRINSIC_WITH_CC(s390_vpksfs);
17018   INTRINSIC_WITH_CC(s390_vpksgs);
17019 
17020   INTRINSIC_WITH_CC(s390_vpklshs);
17021   INTRINSIC_WITH_CC(s390_vpklsfs);
17022   INTRINSIC_WITH_CC(s390_vpklsgs);
17023 
17024   INTRINSIC_WITH_CC(s390_vceqbs);
17025   INTRINSIC_WITH_CC(s390_vceqhs);
17026   INTRINSIC_WITH_CC(s390_vceqfs);
17027   INTRINSIC_WITH_CC(s390_vceqgs);
17028 
17029   INTRINSIC_WITH_CC(s390_vchbs);
17030   INTRINSIC_WITH_CC(s390_vchhs);
17031   INTRINSIC_WITH_CC(s390_vchfs);
17032   INTRINSIC_WITH_CC(s390_vchgs);
17033 
17034   INTRINSIC_WITH_CC(s390_vchlbs);
17035   INTRINSIC_WITH_CC(s390_vchlhs);
17036   INTRINSIC_WITH_CC(s390_vchlfs);
17037   INTRINSIC_WITH_CC(s390_vchlgs);
17038 
17039   INTRINSIC_WITH_CC(s390_vfaebs);
17040   INTRINSIC_WITH_CC(s390_vfaehs);
17041   INTRINSIC_WITH_CC(s390_vfaefs);
17042 
17043   INTRINSIC_WITH_CC(s390_vfaezbs);
17044   INTRINSIC_WITH_CC(s390_vfaezhs);
17045   INTRINSIC_WITH_CC(s390_vfaezfs);
17046 
17047   INTRINSIC_WITH_CC(s390_vfeebs);
17048   INTRINSIC_WITH_CC(s390_vfeehs);
17049   INTRINSIC_WITH_CC(s390_vfeefs);
17050 
17051   INTRINSIC_WITH_CC(s390_vfeezbs);
17052   INTRINSIC_WITH_CC(s390_vfeezhs);
17053   INTRINSIC_WITH_CC(s390_vfeezfs);
17054 
17055   INTRINSIC_WITH_CC(s390_vfenebs);
17056   INTRINSIC_WITH_CC(s390_vfenehs);
17057   INTRINSIC_WITH_CC(s390_vfenefs);
17058 
17059   INTRINSIC_WITH_CC(s390_vfenezbs);
17060   INTRINSIC_WITH_CC(s390_vfenezhs);
17061   INTRINSIC_WITH_CC(s390_vfenezfs);
17062 
17063   INTRINSIC_WITH_CC(s390_vistrbs);
17064   INTRINSIC_WITH_CC(s390_vistrhs);
17065   INTRINSIC_WITH_CC(s390_vistrfs);
17066 
17067   INTRINSIC_WITH_CC(s390_vstrcbs);
17068   INTRINSIC_WITH_CC(s390_vstrchs);
17069   INTRINSIC_WITH_CC(s390_vstrcfs);
17070 
17071   INTRINSIC_WITH_CC(s390_vstrczbs);
17072   INTRINSIC_WITH_CC(s390_vstrczhs);
17073   INTRINSIC_WITH_CC(s390_vstrczfs);
17074 
17075   INTRINSIC_WITH_CC(s390_vfcesbs);
17076   INTRINSIC_WITH_CC(s390_vfcedbs);
17077   INTRINSIC_WITH_CC(s390_vfchsbs);
17078   INTRINSIC_WITH_CC(s390_vfchdbs);
17079   INTRINSIC_WITH_CC(s390_vfchesbs);
17080   INTRINSIC_WITH_CC(s390_vfchedbs);
17081 
17082   INTRINSIC_WITH_CC(s390_vftcisb);
17083   INTRINSIC_WITH_CC(s390_vftcidb);
17084 
17085   INTRINSIC_WITH_CC(s390_vstrsb);
17086   INTRINSIC_WITH_CC(s390_vstrsh);
17087   INTRINSIC_WITH_CC(s390_vstrsf);
17088 
17089   INTRINSIC_WITH_CC(s390_vstrszb);
17090   INTRINSIC_WITH_CC(s390_vstrszh);
17091   INTRINSIC_WITH_CC(s390_vstrszf);
17092 
17093 #undef INTRINSIC_WITH_CC
17094 
17095   default:
17096     return nullptr;
17097   }
17098 }
17099 
17100 namespace {
17101 // Helper classes for mapping MMA builtins to particular LLVM intrinsic variant.
17102 struct NVPTXMmaLdstInfo {
17103   unsigned NumResults;  // Number of elements to load/store
17104   // Intrinsic IDs for row/col variants. 0 if particular layout is unsupported.
17105   unsigned IID_col;
17106   unsigned IID_row;
17107 };
17108 
17109 #define MMA_INTR(geom_op_type, layout) \
17110   Intrinsic::nvvm_wmma_##geom_op_type##_##layout##_stride
17111 #define MMA_LDST(n, geom_op_type)                                              \
17112   { n, MMA_INTR(geom_op_type, col), MMA_INTR(geom_op_type, row) }
17113 
17114 static NVPTXMmaLdstInfo getNVPTXMmaLdstInfo(unsigned BuiltinID) {
17115   switch (BuiltinID) {
17116   // FP MMA loads
17117   case NVPTX::BI__hmma_m16n16k16_ld_a:
17118     return MMA_LDST(8, m16n16k16_load_a_f16);
17119   case NVPTX::BI__hmma_m16n16k16_ld_b:
17120     return MMA_LDST(8, m16n16k16_load_b_f16);
17121   case NVPTX::BI__hmma_m16n16k16_ld_c_f16:
17122     return MMA_LDST(4, m16n16k16_load_c_f16);
17123   case NVPTX::BI__hmma_m16n16k16_ld_c_f32:
17124     return MMA_LDST(8, m16n16k16_load_c_f32);
17125   case NVPTX::BI__hmma_m32n8k16_ld_a:
17126     return MMA_LDST(8, m32n8k16_load_a_f16);
17127   case NVPTX::BI__hmma_m32n8k16_ld_b:
17128     return MMA_LDST(8, m32n8k16_load_b_f16);
17129   case NVPTX::BI__hmma_m32n8k16_ld_c_f16:
17130     return MMA_LDST(4, m32n8k16_load_c_f16);
17131   case NVPTX::BI__hmma_m32n8k16_ld_c_f32:
17132     return MMA_LDST(8, m32n8k16_load_c_f32);
17133   case NVPTX::BI__hmma_m8n32k16_ld_a:
17134     return MMA_LDST(8, m8n32k16_load_a_f16);
17135   case NVPTX::BI__hmma_m8n32k16_ld_b:
17136     return MMA_LDST(8, m8n32k16_load_b_f16);
17137   case NVPTX::BI__hmma_m8n32k16_ld_c_f16:
17138     return MMA_LDST(4, m8n32k16_load_c_f16);
17139   case NVPTX::BI__hmma_m8n32k16_ld_c_f32:
17140     return MMA_LDST(8, m8n32k16_load_c_f32);
17141 
17142   // Integer MMA loads
17143   case NVPTX::BI__imma_m16n16k16_ld_a_s8:
17144     return MMA_LDST(2, m16n16k16_load_a_s8);
17145   case NVPTX::BI__imma_m16n16k16_ld_a_u8:
17146     return MMA_LDST(2, m16n16k16_load_a_u8);
17147   case NVPTX::BI__imma_m16n16k16_ld_b_s8:
17148     return MMA_LDST(2, m16n16k16_load_b_s8);
17149   case NVPTX::BI__imma_m16n16k16_ld_b_u8:
17150     return MMA_LDST(2, m16n16k16_load_b_u8);
17151   case NVPTX::BI__imma_m16n16k16_ld_c:
17152     return MMA_LDST(8, m16n16k16_load_c_s32);
17153   case NVPTX::BI__imma_m32n8k16_ld_a_s8:
17154     return MMA_LDST(4, m32n8k16_load_a_s8);
17155   case NVPTX::BI__imma_m32n8k16_ld_a_u8:
17156     return MMA_LDST(4, m32n8k16_load_a_u8);
17157   case NVPTX::BI__imma_m32n8k16_ld_b_s8:
17158     return MMA_LDST(1, m32n8k16_load_b_s8);
17159   case NVPTX::BI__imma_m32n8k16_ld_b_u8:
17160     return MMA_LDST(1, m32n8k16_load_b_u8);
17161   case NVPTX::BI__imma_m32n8k16_ld_c:
17162     return MMA_LDST(8, m32n8k16_load_c_s32);
17163   case NVPTX::BI__imma_m8n32k16_ld_a_s8:
17164     return MMA_LDST(1, m8n32k16_load_a_s8);
17165   case NVPTX::BI__imma_m8n32k16_ld_a_u8:
17166     return MMA_LDST(1, m8n32k16_load_a_u8);
17167   case NVPTX::BI__imma_m8n32k16_ld_b_s8:
17168     return MMA_LDST(4, m8n32k16_load_b_s8);
17169   case NVPTX::BI__imma_m8n32k16_ld_b_u8:
17170     return MMA_LDST(4, m8n32k16_load_b_u8);
17171   case NVPTX::BI__imma_m8n32k16_ld_c:
17172     return MMA_LDST(8, m8n32k16_load_c_s32);
17173 
17174   // Sub-integer MMA loads.
17175   // Only row/col layout is supported by A/B fragments.
17176   case NVPTX::BI__imma_m8n8k32_ld_a_s4:
17177     return {1, 0, MMA_INTR(m8n8k32_load_a_s4, row)};
17178   case NVPTX::BI__imma_m8n8k32_ld_a_u4:
17179     return {1, 0, MMA_INTR(m8n8k32_load_a_u4, row)};
17180   case NVPTX::BI__imma_m8n8k32_ld_b_s4:
17181     return {1, MMA_INTR(m8n8k32_load_b_s4, col), 0};
17182   case NVPTX::BI__imma_m8n8k32_ld_b_u4:
17183     return {1, MMA_INTR(m8n8k32_load_b_u4, col), 0};
17184   case NVPTX::BI__imma_m8n8k32_ld_c:
17185     return MMA_LDST(2, m8n8k32_load_c_s32);
17186   case NVPTX::BI__bmma_m8n8k128_ld_a_b1:
17187     return {1, 0, MMA_INTR(m8n8k128_load_a_b1, row)};
17188   case NVPTX::BI__bmma_m8n8k128_ld_b_b1:
17189     return {1, MMA_INTR(m8n8k128_load_b_b1, col), 0};
17190   case NVPTX::BI__bmma_m8n8k128_ld_c:
17191     return MMA_LDST(2, m8n8k128_load_c_s32);
17192 
17193   // Double MMA loads
17194   case NVPTX::BI__dmma_m8n8k4_ld_a:
17195     return MMA_LDST(1, m8n8k4_load_a_f64);
17196   case NVPTX::BI__dmma_m8n8k4_ld_b:
17197     return MMA_LDST(1, m8n8k4_load_b_f64);
17198   case NVPTX::BI__dmma_m8n8k4_ld_c:
17199     return MMA_LDST(2, m8n8k4_load_c_f64);
17200 
17201   // Alternate float MMA loads
17202   case NVPTX::BI__mma_bf16_m16n16k16_ld_a:
17203     return MMA_LDST(4, m16n16k16_load_a_bf16);
17204   case NVPTX::BI__mma_bf16_m16n16k16_ld_b:
17205     return MMA_LDST(4, m16n16k16_load_b_bf16);
17206   case NVPTX::BI__mma_bf16_m8n32k16_ld_a:
17207     return MMA_LDST(2, m8n32k16_load_a_bf16);
17208   case NVPTX::BI__mma_bf16_m8n32k16_ld_b:
17209     return MMA_LDST(8, m8n32k16_load_b_bf16);
17210   case NVPTX::BI__mma_bf16_m32n8k16_ld_a:
17211     return MMA_LDST(8, m32n8k16_load_a_bf16);
17212   case NVPTX::BI__mma_bf16_m32n8k16_ld_b:
17213     return MMA_LDST(2, m32n8k16_load_b_bf16);
17214   case NVPTX::BI__mma_tf32_m16n16k8_ld_a:
17215     return MMA_LDST(4, m16n16k8_load_a_tf32);
17216   case NVPTX::BI__mma_tf32_m16n16k8_ld_b:
17217     return MMA_LDST(4, m16n16k8_load_b_tf32);
17218   case NVPTX::BI__mma_tf32_m16n16k8_ld_c:
17219     return MMA_LDST(8, m16n16k8_load_c_f32);
17220 
17221   // NOTE: We need to follow inconsitent naming scheme used by NVCC.  Unlike
17222   // PTX and LLVM IR where stores always use fragment D, NVCC builtins always
17223   // use fragment C for both loads and stores.
17224   // FP MMA stores.
17225   case NVPTX::BI__hmma_m16n16k16_st_c_f16:
17226     return MMA_LDST(4, m16n16k16_store_d_f16);
17227   case NVPTX::BI__hmma_m16n16k16_st_c_f32:
17228     return MMA_LDST(8, m16n16k16_store_d_f32);
17229   case NVPTX::BI__hmma_m32n8k16_st_c_f16:
17230     return MMA_LDST(4, m32n8k16_store_d_f16);
17231   case NVPTX::BI__hmma_m32n8k16_st_c_f32:
17232     return MMA_LDST(8, m32n8k16_store_d_f32);
17233   case NVPTX::BI__hmma_m8n32k16_st_c_f16:
17234     return MMA_LDST(4, m8n32k16_store_d_f16);
17235   case NVPTX::BI__hmma_m8n32k16_st_c_f32:
17236     return MMA_LDST(8, m8n32k16_store_d_f32);
17237 
17238   // Integer and sub-integer MMA stores.
17239   // Another naming quirk. Unlike other MMA builtins that use PTX types in the
17240   // name, integer loads/stores use LLVM's i32.
17241   case NVPTX::BI__imma_m16n16k16_st_c_i32:
17242     return MMA_LDST(8, m16n16k16_store_d_s32);
17243   case NVPTX::BI__imma_m32n8k16_st_c_i32:
17244     return MMA_LDST(8, m32n8k16_store_d_s32);
17245   case NVPTX::BI__imma_m8n32k16_st_c_i32:
17246     return MMA_LDST(8, m8n32k16_store_d_s32);
17247   case NVPTX::BI__imma_m8n8k32_st_c_i32:
17248     return MMA_LDST(2, m8n8k32_store_d_s32);
17249   case NVPTX::BI__bmma_m8n8k128_st_c_i32:
17250     return MMA_LDST(2, m8n8k128_store_d_s32);
17251 
17252   // Double MMA store
17253   case NVPTX::BI__dmma_m8n8k4_st_c_f64:
17254     return MMA_LDST(2, m8n8k4_store_d_f64);
17255 
17256   // Alternate float MMA store
17257   case NVPTX::BI__mma_m16n16k8_st_c_f32:
17258     return MMA_LDST(8, m16n16k8_store_d_f32);
17259 
17260   default:
17261     llvm_unreachable("Unknown MMA builtin");
17262   }
17263 }
17264 #undef MMA_LDST
17265 #undef MMA_INTR
17266 
17267 
17268 struct NVPTXMmaInfo {
17269   unsigned NumEltsA;
17270   unsigned NumEltsB;
17271   unsigned NumEltsC;
17272   unsigned NumEltsD;
17273 
17274   // Variants are ordered by layout-A/layout-B/satf, where 'row' has priority
17275   // over 'col' for layout. The index of non-satf variants is expected to match
17276   // the undocumented layout constants used by CUDA's mma.hpp.
17277   std::array<unsigned, 8> Variants;
17278 
17279   unsigned getMMAIntrinsic(int Layout, bool Satf) {
17280     unsigned Index = Layout + 4 * Satf;
17281     if (Index >= Variants.size())
17282       return 0;
17283     return Variants[Index];
17284   }
17285 };
17286 
17287   // Returns an intrinsic that matches Layout and Satf for valid combinations of
17288   // Layout and Satf, 0 otherwise.
17289 static NVPTXMmaInfo getNVPTXMmaInfo(unsigned BuiltinID) {
17290   // clang-format off
17291 #define MMA_VARIANTS(geom, type)                                    \
17292       Intrinsic::nvvm_wmma_##geom##_mma_row_row_##type,             \
17293       Intrinsic::nvvm_wmma_##geom##_mma_row_col_##type,             \
17294       Intrinsic::nvvm_wmma_##geom##_mma_col_row_##type,             \
17295       Intrinsic::nvvm_wmma_##geom##_mma_col_col_##type
17296 #define MMA_SATF_VARIANTS(geom, type)                               \
17297       MMA_VARIANTS(geom, type),                                     \
17298       Intrinsic::nvvm_wmma_##geom##_mma_row_row_##type##_satfinite, \
17299       Intrinsic::nvvm_wmma_##geom##_mma_row_col_##type##_satfinite, \
17300       Intrinsic::nvvm_wmma_##geom##_mma_col_row_##type##_satfinite, \
17301       Intrinsic::nvvm_wmma_##geom##_mma_col_col_##type##_satfinite
17302 // Sub-integer MMA only supports row.col layout.
17303 #define MMA_VARIANTS_I4(geom, type) \
17304       0, \
17305       Intrinsic::nvvm_wmma_##geom##_mma_row_col_##type,             \
17306       0, \
17307       0, \
17308       0, \
17309       Intrinsic::nvvm_wmma_##geom##_mma_row_col_##type##_satfinite, \
17310       0, \
17311       0
17312 // b1 MMA does not support .satfinite.
17313 #define MMA_VARIANTS_B1_XOR(geom, type) \
17314       0, \
17315       Intrinsic::nvvm_wmma_##geom##_mma_xor_popc_row_col_##type,             \
17316       0, \
17317       0, \
17318       0, \
17319       0, \
17320       0, \
17321       0
17322 #define MMA_VARIANTS_B1_AND(geom, type) \
17323       0, \
17324       Intrinsic::nvvm_wmma_##geom##_mma_and_popc_row_col_##type,             \
17325       0, \
17326       0, \
17327       0, \
17328       0, \
17329       0, \
17330       0
17331   // clang-format on
17332   switch (BuiltinID) {
17333   // FP MMA
17334   // Note that 'type' argument of MMA_SATF_VARIANTS uses D_C notation, while
17335   // NumEltsN of return value are ordered as A,B,C,D.
17336   case NVPTX::BI__hmma_m16n16k16_mma_f16f16:
17337     return {8, 8, 4, 4, {{MMA_SATF_VARIANTS(m16n16k16, f16_f16)}}};
17338   case NVPTX::BI__hmma_m16n16k16_mma_f32f16:
17339     return {8, 8, 4, 8, {{MMA_SATF_VARIANTS(m16n16k16, f32_f16)}}};
17340   case NVPTX::BI__hmma_m16n16k16_mma_f16f32:
17341     return {8, 8, 8, 4, {{MMA_SATF_VARIANTS(m16n16k16, f16_f32)}}};
17342   case NVPTX::BI__hmma_m16n16k16_mma_f32f32:
17343     return {8, 8, 8, 8, {{MMA_SATF_VARIANTS(m16n16k16, f32_f32)}}};
17344   case NVPTX::BI__hmma_m32n8k16_mma_f16f16:
17345     return {8, 8, 4, 4, {{MMA_SATF_VARIANTS(m32n8k16, f16_f16)}}};
17346   case NVPTX::BI__hmma_m32n8k16_mma_f32f16:
17347     return {8, 8, 4, 8, {{MMA_SATF_VARIANTS(m32n8k16, f32_f16)}}};
17348   case NVPTX::BI__hmma_m32n8k16_mma_f16f32:
17349     return {8, 8, 8, 4, {{MMA_SATF_VARIANTS(m32n8k16, f16_f32)}}};
17350   case NVPTX::BI__hmma_m32n8k16_mma_f32f32:
17351     return {8, 8, 8, 8, {{MMA_SATF_VARIANTS(m32n8k16, f32_f32)}}};
17352   case NVPTX::BI__hmma_m8n32k16_mma_f16f16:
17353     return {8, 8, 4, 4, {{MMA_SATF_VARIANTS(m8n32k16, f16_f16)}}};
17354   case NVPTX::BI__hmma_m8n32k16_mma_f32f16:
17355     return {8, 8, 4, 8, {{MMA_SATF_VARIANTS(m8n32k16, f32_f16)}}};
17356   case NVPTX::BI__hmma_m8n32k16_mma_f16f32:
17357     return {8, 8, 8, 4, {{MMA_SATF_VARIANTS(m8n32k16, f16_f32)}}};
17358   case NVPTX::BI__hmma_m8n32k16_mma_f32f32:
17359     return {8, 8, 8, 8, {{MMA_SATF_VARIANTS(m8n32k16, f32_f32)}}};
17360 
17361   // Integer MMA
17362   case NVPTX::BI__imma_m16n16k16_mma_s8:
17363     return {2, 2, 8, 8, {{MMA_SATF_VARIANTS(m16n16k16, s8)}}};
17364   case NVPTX::BI__imma_m16n16k16_mma_u8:
17365     return {2, 2, 8, 8, {{MMA_SATF_VARIANTS(m16n16k16, u8)}}};
17366   case NVPTX::BI__imma_m32n8k16_mma_s8:
17367     return {4, 1, 8, 8, {{MMA_SATF_VARIANTS(m32n8k16, s8)}}};
17368   case NVPTX::BI__imma_m32n8k16_mma_u8:
17369     return {4, 1, 8, 8, {{MMA_SATF_VARIANTS(m32n8k16, u8)}}};
17370   case NVPTX::BI__imma_m8n32k16_mma_s8:
17371     return {1, 4, 8, 8, {{MMA_SATF_VARIANTS(m8n32k16, s8)}}};
17372   case NVPTX::BI__imma_m8n32k16_mma_u8:
17373     return {1, 4, 8, 8, {{MMA_SATF_VARIANTS(m8n32k16, u8)}}};
17374 
17375   // Sub-integer MMA
17376   case NVPTX::BI__imma_m8n8k32_mma_s4:
17377     return {1, 1, 2, 2, {{MMA_VARIANTS_I4(m8n8k32, s4)}}};
17378   case NVPTX::BI__imma_m8n8k32_mma_u4:
17379     return {1, 1, 2, 2, {{MMA_VARIANTS_I4(m8n8k32, u4)}}};
17380   case NVPTX::BI__bmma_m8n8k128_mma_xor_popc_b1:
17381     return {1, 1, 2, 2, {{MMA_VARIANTS_B1_XOR(m8n8k128, b1)}}};
17382   case NVPTX::BI__bmma_m8n8k128_mma_and_popc_b1:
17383     return {1, 1, 2, 2, {{MMA_VARIANTS_B1_AND(m8n8k128, b1)}}};
17384 
17385   // Double MMA
17386   case NVPTX::BI__dmma_m8n8k4_mma_f64:
17387     return {1, 1, 2, 2, {{MMA_VARIANTS(m8n8k4, f64)}}};
17388 
17389   // Alternate FP MMA
17390   case NVPTX::BI__mma_bf16_m16n16k16_mma_f32:
17391     return {4, 4, 8, 8, {{MMA_VARIANTS(m16n16k16, bf16)}}};
17392   case NVPTX::BI__mma_bf16_m8n32k16_mma_f32:
17393     return {2, 8, 8, 8, {{MMA_VARIANTS(m8n32k16, bf16)}}};
17394   case NVPTX::BI__mma_bf16_m32n8k16_mma_f32:
17395     return {8, 2, 8, 8, {{MMA_VARIANTS(m32n8k16, bf16)}}};
17396   case NVPTX::BI__mma_tf32_m16n16k8_mma_f32:
17397     return {4, 4, 8, 8, {{MMA_VARIANTS(m16n16k8, tf32)}}};
17398   default:
17399     llvm_unreachable("Unexpected builtin ID.");
17400   }
17401 #undef MMA_VARIANTS
17402 #undef MMA_SATF_VARIANTS
17403 #undef MMA_VARIANTS_I4
17404 #undef MMA_VARIANTS_B1_AND
17405 #undef MMA_VARIANTS_B1_XOR
17406 }
17407 
17408 } // namespace
17409 
17410 Value *
17411 CodeGenFunction::EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E) {
17412   auto MakeLdg = [&](unsigned IntrinsicID) {
17413     Value *Ptr = EmitScalarExpr(E->getArg(0));
17414     clang::CharUnits Align =
17415         CGM.getNaturalPointeeTypeAlignment(E->getArg(0)->getType());
17416     return Builder.CreateCall(
17417         CGM.getIntrinsic(IntrinsicID, {Ptr->getType()->getPointerElementType(),
17418                                        Ptr->getType()}),
17419         {Ptr, ConstantInt::get(Builder.getInt32Ty(), Align.getQuantity())});
17420   };
17421   auto MakeScopedAtomic = [&](unsigned IntrinsicID) {
17422     Value *Ptr = EmitScalarExpr(E->getArg(0));
17423     return Builder.CreateCall(
17424         CGM.getIntrinsic(IntrinsicID, {Ptr->getType()->getPointerElementType(),
17425                                        Ptr->getType()}),
17426         {Ptr, EmitScalarExpr(E->getArg(1))});
17427   };
17428   switch (BuiltinID) {
17429   case NVPTX::BI__nvvm_atom_add_gen_i:
17430   case NVPTX::BI__nvvm_atom_add_gen_l:
17431   case NVPTX::BI__nvvm_atom_add_gen_ll:
17432     return MakeBinaryAtomicValue(*this, llvm::AtomicRMWInst::Add, E);
17433 
17434   case NVPTX::BI__nvvm_atom_sub_gen_i:
17435   case NVPTX::BI__nvvm_atom_sub_gen_l:
17436   case NVPTX::BI__nvvm_atom_sub_gen_ll:
17437     return MakeBinaryAtomicValue(*this, llvm::AtomicRMWInst::Sub, E);
17438 
17439   case NVPTX::BI__nvvm_atom_and_gen_i:
17440   case NVPTX::BI__nvvm_atom_and_gen_l:
17441   case NVPTX::BI__nvvm_atom_and_gen_ll:
17442     return MakeBinaryAtomicValue(*this, llvm::AtomicRMWInst::And, E);
17443 
17444   case NVPTX::BI__nvvm_atom_or_gen_i:
17445   case NVPTX::BI__nvvm_atom_or_gen_l:
17446   case NVPTX::BI__nvvm_atom_or_gen_ll:
17447     return MakeBinaryAtomicValue(*this, llvm::AtomicRMWInst::Or, E);
17448 
17449   case NVPTX::BI__nvvm_atom_xor_gen_i:
17450   case NVPTX::BI__nvvm_atom_xor_gen_l:
17451   case NVPTX::BI__nvvm_atom_xor_gen_ll:
17452     return MakeBinaryAtomicValue(*this, llvm::AtomicRMWInst::Xor, E);
17453 
17454   case NVPTX::BI__nvvm_atom_xchg_gen_i:
17455   case NVPTX::BI__nvvm_atom_xchg_gen_l:
17456   case NVPTX::BI__nvvm_atom_xchg_gen_ll:
17457     return MakeBinaryAtomicValue(*this, llvm::AtomicRMWInst::Xchg, E);
17458 
17459   case NVPTX::BI__nvvm_atom_max_gen_i:
17460   case NVPTX::BI__nvvm_atom_max_gen_l:
17461   case NVPTX::BI__nvvm_atom_max_gen_ll:
17462     return MakeBinaryAtomicValue(*this, llvm::AtomicRMWInst::Max, E);
17463 
17464   case NVPTX::BI__nvvm_atom_max_gen_ui:
17465   case NVPTX::BI__nvvm_atom_max_gen_ul:
17466   case NVPTX::BI__nvvm_atom_max_gen_ull:
17467     return MakeBinaryAtomicValue(*this, llvm::AtomicRMWInst::UMax, E);
17468 
17469   case NVPTX::BI__nvvm_atom_min_gen_i:
17470   case NVPTX::BI__nvvm_atom_min_gen_l:
17471   case NVPTX::BI__nvvm_atom_min_gen_ll:
17472     return MakeBinaryAtomicValue(*this, llvm::AtomicRMWInst::Min, E);
17473 
17474   case NVPTX::BI__nvvm_atom_min_gen_ui:
17475   case NVPTX::BI__nvvm_atom_min_gen_ul:
17476   case NVPTX::BI__nvvm_atom_min_gen_ull:
17477     return MakeBinaryAtomicValue(*this, llvm::AtomicRMWInst::UMin, E);
17478 
17479   case NVPTX::BI__nvvm_atom_cas_gen_i:
17480   case NVPTX::BI__nvvm_atom_cas_gen_l:
17481   case NVPTX::BI__nvvm_atom_cas_gen_ll:
17482     // __nvvm_atom_cas_gen_* should return the old value rather than the
17483     // success flag.
17484     return MakeAtomicCmpXchgValue(*this, E, /*ReturnBool=*/false);
17485 
17486   case NVPTX::BI__nvvm_atom_add_gen_f:
17487   case NVPTX::BI__nvvm_atom_add_gen_d: {
17488     Value *Ptr = EmitScalarExpr(E->getArg(0));
17489     Value *Val = EmitScalarExpr(E->getArg(1));
17490     return Builder.CreateAtomicRMW(llvm::AtomicRMWInst::FAdd, Ptr, Val,
17491                                    AtomicOrdering::SequentiallyConsistent);
17492   }
17493 
17494   case NVPTX::BI__nvvm_atom_inc_gen_ui: {
17495     Value *Ptr = EmitScalarExpr(E->getArg(0));
17496     Value *Val = EmitScalarExpr(E->getArg(1));
17497     Function *FnALI32 =
17498         CGM.getIntrinsic(Intrinsic::nvvm_atomic_load_inc_32, Ptr->getType());
17499     return Builder.CreateCall(FnALI32, {Ptr, Val});
17500   }
17501 
17502   case NVPTX::BI__nvvm_atom_dec_gen_ui: {
17503     Value *Ptr = EmitScalarExpr(E->getArg(0));
17504     Value *Val = EmitScalarExpr(E->getArg(1));
17505     Function *FnALD32 =
17506         CGM.getIntrinsic(Intrinsic::nvvm_atomic_load_dec_32, Ptr->getType());
17507     return Builder.CreateCall(FnALD32, {Ptr, Val});
17508   }
17509 
17510   case NVPTX::BI__nvvm_ldg_c:
17511   case NVPTX::BI__nvvm_ldg_c2:
17512   case NVPTX::BI__nvvm_ldg_c4:
17513   case NVPTX::BI__nvvm_ldg_s:
17514   case NVPTX::BI__nvvm_ldg_s2:
17515   case NVPTX::BI__nvvm_ldg_s4:
17516   case NVPTX::BI__nvvm_ldg_i:
17517   case NVPTX::BI__nvvm_ldg_i2:
17518   case NVPTX::BI__nvvm_ldg_i4:
17519   case NVPTX::BI__nvvm_ldg_l:
17520   case NVPTX::BI__nvvm_ldg_ll:
17521   case NVPTX::BI__nvvm_ldg_ll2:
17522   case NVPTX::BI__nvvm_ldg_uc:
17523   case NVPTX::BI__nvvm_ldg_uc2:
17524   case NVPTX::BI__nvvm_ldg_uc4:
17525   case NVPTX::BI__nvvm_ldg_us:
17526   case NVPTX::BI__nvvm_ldg_us2:
17527   case NVPTX::BI__nvvm_ldg_us4:
17528   case NVPTX::BI__nvvm_ldg_ui:
17529   case NVPTX::BI__nvvm_ldg_ui2:
17530   case NVPTX::BI__nvvm_ldg_ui4:
17531   case NVPTX::BI__nvvm_ldg_ul:
17532   case NVPTX::BI__nvvm_ldg_ull:
17533   case NVPTX::BI__nvvm_ldg_ull2:
17534     // PTX Interoperability section 2.2: "For a vector with an even number of
17535     // elements, its alignment is set to number of elements times the alignment
17536     // of its member: n*alignof(t)."
17537     return MakeLdg(Intrinsic::nvvm_ldg_global_i);
17538   case NVPTX::BI__nvvm_ldg_f:
17539   case NVPTX::BI__nvvm_ldg_f2:
17540   case NVPTX::BI__nvvm_ldg_f4:
17541   case NVPTX::BI__nvvm_ldg_d:
17542   case NVPTX::BI__nvvm_ldg_d2:
17543     return MakeLdg(Intrinsic::nvvm_ldg_global_f);
17544 
17545   case NVPTX::BI__nvvm_atom_cta_add_gen_i:
17546   case NVPTX::BI__nvvm_atom_cta_add_gen_l:
17547   case NVPTX::BI__nvvm_atom_cta_add_gen_ll:
17548     return MakeScopedAtomic(Intrinsic::nvvm_atomic_add_gen_i_cta);
17549   case NVPTX::BI__nvvm_atom_sys_add_gen_i:
17550   case NVPTX::BI__nvvm_atom_sys_add_gen_l:
17551   case NVPTX::BI__nvvm_atom_sys_add_gen_ll:
17552     return MakeScopedAtomic(Intrinsic::nvvm_atomic_add_gen_i_sys);
17553   case NVPTX::BI__nvvm_atom_cta_add_gen_f:
17554   case NVPTX::BI__nvvm_atom_cta_add_gen_d:
17555     return MakeScopedAtomic(Intrinsic::nvvm_atomic_add_gen_f_cta);
17556   case NVPTX::BI__nvvm_atom_sys_add_gen_f:
17557   case NVPTX::BI__nvvm_atom_sys_add_gen_d:
17558     return MakeScopedAtomic(Intrinsic::nvvm_atomic_add_gen_f_sys);
17559   case NVPTX::BI__nvvm_atom_cta_xchg_gen_i:
17560   case NVPTX::BI__nvvm_atom_cta_xchg_gen_l:
17561   case NVPTX::BI__nvvm_atom_cta_xchg_gen_ll:
17562     return MakeScopedAtomic(Intrinsic::nvvm_atomic_exch_gen_i_cta);
17563   case NVPTX::BI__nvvm_atom_sys_xchg_gen_i:
17564   case NVPTX::BI__nvvm_atom_sys_xchg_gen_l:
17565   case NVPTX::BI__nvvm_atom_sys_xchg_gen_ll:
17566     return MakeScopedAtomic(Intrinsic::nvvm_atomic_exch_gen_i_sys);
17567   case NVPTX::BI__nvvm_atom_cta_max_gen_i:
17568   case NVPTX::BI__nvvm_atom_cta_max_gen_ui:
17569   case NVPTX::BI__nvvm_atom_cta_max_gen_l:
17570   case NVPTX::BI__nvvm_atom_cta_max_gen_ul:
17571   case NVPTX::BI__nvvm_atom_cta_max_gen_ll:
17572   case NVPTX::BI__nvvm_atom_cta_max_gen_ull:
17573     return MakeScopedAtomic(Intrinsic::nvvm_atomic_max_gen_i_cta);
17574   case NVPTX::BI__nvvm_atom_sys_max_gen_i:
17575   case NVPTX::BI__nvvm_atom_sys_max_gen_ui:
17576   case NVPTX::BI__nvvm_atom_sys_max_gen_l:
17577   case NVPTX::BI__nvvm_atom_sys_max_gen_ul:
17578   case NVPTX::BI__nvvm_atom_sys_max_gen_ll:
17579   case NVPTX::BI__nvvm_atom_sys_max_gen_ull:
17580     return MakeScopedAtomic(Intrinsic::nvvm_atomic_max_gen_i_sys);
17581   case NVPTX::BI__nvvm_atom_cta_min_gen_i:
17582   case NVPTX::BI__nvvm_atom_cta_min_gen_ui:
17583   case NVPTX::BI__nvvm_atom_cta_min_gen_l:
17584   case NVPTX::BI__nvvm_atom_cta_min_gen_ul:
17585   case NVPTX::BI__nvvm_atom_cta_min_gen_ll:
17586   case NVPTX::BI__nvvm_atom_cta_min_gen_ull:
17587     return MakeScopedAtomic(Intrinsic::nvvm_atomic_min_gen_i_cta);
17588   case NVPTX::BI__nvvm_atom_sys_min_gen_i:
17589   case NVPTX::BI__nvvm_atom_sys_min_gen_ui:
17590   case NVPTX::BI__nvvm_atom_sys_min_gen_l:
17591   case NVPTX::BI__nvvm_atom_sys_min_gen_ul:
17592   case NVPTX::BI__nvvm_atom_sys_min_gen_ll:
17593   case NVPTX::BI__nvvm_atom_sys_min_gen_ull:
17594     return MakeScopedAtomic(Intrinsic::nvvm_atomic_min_gen_i_sys);
17595   case NVPTX::BI__nvvm_atom_cta_inc_gen_ui:
17596     return MakeScopedAtomic(Intrinsic::nvvm_atomic_inc_gen_i_cta);
17597   case NVPTX::BI__nvvm_atom_cta_dec_gen_ui:
17598     return MakeScopedAtomic(Intrinsic::nvvm_atomic_dec_gen_i_cta);
17599   case NVPTX::BI__nvvm_atom_sys_inc_gen_ui:
17600     return MakeScopedAtomic(Intrinsic::nvvm_atomic_inc_gen_i_sys);
17601   case NVPTX::BI__nvvm_atom_sys_dec_gen_ui:
17602     return MakeScopedAtomic(Intrinsic::nvvm_atomic_dec_gen_i_sys);
17603   case NVPTX::BI__nvvm_atom_cta_and_gen_i:
17604   case NVPTX::BI__nvvm_atom_cta_and_gen_l:
17605   case NVPTX::BI__nvvm_atom_cta_and_gen_ll:
17606     return MakeScopedAtomic(Intrinsic::nvvm_atomic_and_gen_i_cta);
17607   case NVPTX::BI__nvvm_atom_sys_and_gen_i:
17608   case NVPTX::BI__nvvm_atom_sys_and_gen_l:
17609   case NVPTX::BI__nvvm_atom_sys_and_gen_ll:
17610     return MakeScopedAtomic(Intrinsic::nvvm_atomic_and_gen_i_sys);
17611   case NVPTX::BI__nvvm_atom_cta_or_gen_i:
17612   case NVPTX::BI__nvvm_atom_cta_or_gen_l:
17613   case NVPTX::BI__nvvm_atom_cta_or_gen_ll:
17614     return MakeScopedAtomic(Intrinsic::nvvm_atomic_or_gen_i_cta);
17615   case NVPTX::BI__nvvm_atom_sys_or_gen_i:
17616   case NVPTX::BI__nvvm_atom_sys_or_gen_l:
17617   case NVPTX::BI__nvvm_atom_sys_or_gen_ll:
17618     return MakeScopedAtomic(Intrinsic::nvvm_atomic_or_gen_i_sys);
17619   case NVPTX::BI__nvvm_atom_cta_xor_gen_i:
17620   case NVPTX::BI__nvvm_atom_cta_xor_gen_l:
17621   case NVPTX::BI__nvvm_atom_cta_xor_gen_ll:
17622     return MakeScopedAtomic(Intrinsic::nvvm_atomic_xor_gen_i_cta);
17623   case NVPTX::BI__nvvm_atom_sys_xor_gen_i:
17624   case NVPTX::BI__nvvm_atom_sys_xor_gen_l:
17625   case NVPTX::BI__nvvm_atom_sys_xor_gen_ll:
17626     return MakeScopedAtomic(Intrinsic::nvvm_atomic_xor_gen_i_sys);
17627   case NVPTX::BI__nvvm_atom_cta_cas_gen_i:
17628   case NVPTX::BI__nvvm_atom_cta_cas_gen_l:
17629   case NVPTX::BI__nvvm_atom_cta_cas_gen_ll: {
17630     Value *Ptr = EmitScalarExpr(E->getArg(0));
17631     return Builder.CreateCall(
17632         CGM.getIntrinsic(
17633             Intrinsic::nvvm_atomic_cas_gen_i_cta,
17634             {Ptr->getType()->getPointerElementType(), Ptr->getType()}),
17635         {Ptr, EmitScalarExpr(E->getArg(1)), EmitScalarExpr(E->getArg(2))});
17636   }
17637   case NVPTX::BI__nvvm_atom_sys_cas_gen_i:
17638   case NVPTX::BI__nvvm_atom_sys_cas_gen_l:
17639   case NVPTX::BI__nvvm_atom_sys_cas_gen_ll: {
17640     Value *Ptr = EmitScalarExpr(E->getArg(0));
17641     return Builder.CreateCall(
17642         CGM.getIntrinsic(
17643             Intrinsic::nvvm_atomic_cas_gen_i_sys,
17644             {Ptr->getType()->getPointerElementType(), Ptr->getType()}),
17645         {Ptr, EmitScalarExpr(E->getArg(1)), EmitScalarExpr(E->getArg(2))});
17646   }
17647   case NVPTX::BI__nvvm_match_all_sync_i32p:
17648   case NVPTX::BI__nvvm_match_all_sync_i64p: {
17649     Value *Mask = EmitScalarExpr(E->getArg(0));
17650     Value *Val = EmitScalarExpr(E->getArg(1));
17651     Address PredOutPtr = EmitPointerWithAlignment(E->getArg(2));
17652     Value *ResultPair = Builder.CreateCall(
17653         CGM.getIntrinsic(BuiltinID == NVPTX::BI__nvvm_match_all_sync_i32p
17654                              ? Intrinsic::nvvm_match_all_sync_i32p
17655                              : Intrinsic::nvvm_match_all_sync_i64p),
17656         {Mask, Val});
17657     Value *Pred = Builder.CreateZExt(Builder.CreateExtractValue(ResultPair, 1),
17658                                      PredOutPtr.getElementType());
17659     Builder.CreateStore(Pred, PredOutPtr);
17660     return Builder.CreateExtractValue(ResultPair, 0);
17661   }
17662 
17663   // FP MMA loads
17664   case NVPTX::BI__hmma_m16n16k16_ld_a:
17665   case NVPTX::BI__hmma_m16n16k16_ld_b:
17666   case NVPTX::BI__hmma_m16n16k16_ld_c_f16:
17667   case NVPTX::BI__hmma_m16n16k16_ld_c_f32:
17668   case NVPTX::BI__hmma_m32n8k16_ld_a:
17669   case NVPTX::BI__hmma_m32n8k16_ld_b:
17670   case NVPTX::BI__hmma_m32n8k16_ld_c_f16:
17671   case NVPTX::BI__hmma_m32n8k16_ld_c_f32:
17672   case NVPTX::BI__hmma_m8n32k16_ld_a:
17673   case NVPTX::BI__hmma_m8n32k16_ld_b:
17674   case NVPTX::BI__hmma_m8n32k16_ld_c_f16:
17675   case NVPTX::BI__hmma_m8n32k16_ld_c_f32:
17676   // Integer MMA loads.
17677   case NVPTX::BI__imma_m16n16k16_ld_a_s8:
17678   case NVPTX::BI__imma_m16n16k16_ld_a_u8:
17679   case NVPTX::BI__imma_m16n16k16_ld_b_s8:
17680   case NVPTX::BI__imma_m16n16k16_ld_b_u8:
17681   case NVPTX::BI__imma_m16n16k16_ld_c:
17682   case NVPTX::BI__imma_m32n8k16_ld_a_s8:
17683   case NVPTX::BI__imma_m32n8k16_ld_a_u8:
17684   case NVPTX::BI__imma_m32n8k16_ld_b_s8:
17685   case NVPTX::BI__imma_m32n8k16_ld_b_u8:
17686   case NVPTX::BI__imma_m32n8k16_ld_c:
17687   case NVPTX::BI__imma_m8n32k16_ld_a_s8:
17688   case NVPTX::BI__imma_m8n32k16_ld_a_u8:
17689   case NVPTX::BI__imma_m8n32k16_ld_b_s8:
17690   case NVPTX::BI__imma_m8n32k16_ld_b_u8:
17691   case NVPTX::BI__imma_m8n32k16_ld_c:
17692   // Sub-integer MMA loads.
17693   case NVPTX::BI__imma_m8n8k32_ld_a_s4:
17694   case NVPTX::BI__imma_m8n8k32_ld_a_u4:
17695   case NVPTX::BI__imma_m8n8k32_ld_b_s4:
17696   case NVPTX::BI__imma_m8n8k32_ld_b_u4:
17697   case NVPTX::BI__imma_m8n8k32_ld_c:
17698   case NVPTX::BI__bmma_m8n8k128_ld_a_b1:
17699   case NVPTX::BI__bmma_m8n8k128_ld_b_b1:
17700   case NVPTX::BI__bmma_m8n8k128_ld_c:
17701   // Double MMA loads.
17702   case NVPTX::BI__dmma_m8n8k4_ld_a:
17703   case NVPTX::BI__dmma_m8n8k4_ld_b:
17704   case NVPTX::BI__dmma_m8n8k4_ld_c:
17705   // Alternate float MMA loads.
17706   case NVPTX::BI__mma_bf16_m16n16k16_ld_a:
17707   case NVPTX::BI__mma_bf16_m16n16k16_ld_b:
17708   case NVPTX::BI__mma_bf16_m8n32k16_ld_a:
17709   case NVPTX::BI__mma_bf16_m8n32k16_ld_b:
17710   case NVPTX::BI__mma_bf16_m32n8k16_ld_a:
17711   case NVPTX::BI__mma_bf16_m32n8k16_ld_b:
17712   case NVPTX::BI__mma_tf32_m16n16k8_ld_a:
17713   case NVPTX::BI__mma_tf32_m16n16k8_ld_b:
17714   case NVPTX::BI__mma_tf32_m16n16k8_ld_c: {
17715     Address Dst = EmitPointerWithAlignment(E->getArg(0));
17716     Value *Src = EmitScalarExpr(E->getArg(1));
17717     Value *Ldm = EmitScalarExpr(E->getArg(2));
17718     Optional<llvm::APSInt> isColMajorArg =
17719         E->getArg(3)->getIntegerConstantExpr(getContext());
17720     if (!isColMajorArg)
17721       return nullptr;
17722     bool isColMajor = isColMajorArg->getSExtValue();
17723     NVPTXMmaLdstInfo II = getNVPTXMmaLdstInfo(BuiltinID);
17724     unsigned IID = isColMajor ? II.IID_col : II.IID_row;
17725     if (IID == 0)
17726       return nullptr;
17727 
17728     Value *Result =
17729         Builder.CreateCall(CGM.getIntrinsic(IID, Src->getType()), {Src, Ldm});
17730 
17731     // Save returned values.
17732     assert(II.NumResults);
17733     if (II.NumResults == 1) {
17734       Builder.CreateAlignedStore(Result, Dst.getPointer(),
17735                                  CharUnits::fromQuantity(4));
17736     } else {
17737       for (unsigned i = 0; i < II.NumResults; ++i) {
17738         Builder.CreateAlignedStore(
17739             Builder.CreateBitCast(Builder.CreateExtractValue(Result, i),
17740                                   Dst.getElementType()),
17741             Builder.CreateGEP(Dst.getElementType(), Dst.getPointer(),
17742                               llvm::ConstantInt::get(IntTy, i)),
17743             CharUnits::fromQuantity(4));
17744       }
17745     }
17746     return Result;
17747   }
17748 
17749   case NVPTX::BI__hmma_m16n16k16_st_c_f16:
17750   case NVPTX::BI__hmma_m16n16k16_st_c_f32:
17751   case NVPTX::BI__hmma_m32n8k16_st_c_f16:
17752   case NVPTX::BI__hmma_m32n8k16_st_c_f32:
17753   case NVPTX::BI__hmma_m8n32k16_st_c_f16:
17754   case NVPTX::BI__hmma_m8n32k16_st_c_f32:
17755   case NVPTX::BI__imma_m16n16k16_st_c_i32:
17756   case NVPTX::BI__imma_m32n8k16_st_c_i32:
17757   case NVPTX::BI__imma_m8n32k16_st_c_i32:
17758   case NVPTX::BI__imma_m8n8k32_st_c_i32:
17759   case NVPTX::BI__bmma_m8n8k128_st_c_i32:
17760   case NVPTX::BI__dmma_m8n8k4_st_c_f64:
17761   case NVPTX::BI__mma_m16n16k8_st_c_f32: {
17762     Value *Dst = EmitScalarExpr(E->getArg(0));
17763     Address Src = EmitPointerWithAlignment(E->getArg(1));
17764     Value *Ldm = EmitScalarExpr(E->getArg(2));
17765     Optional<llvm::APSInt> isColMajorArg =
17766         E->getArg(3)->getIntegerConstantExpr(getContext());
17767     if (!isColMajorArg)
17768       return nullptr;
17769     bool isColMajor = isColMajorArg->getSExtValue();
17770     NVPTXMmaLdstInfo II = getNVPTXMmaLdstInfo(BuiltinID);
17771     unsigned IID = isColMajor ? II.IID_col : II.IID_row;
17772     if (IID == 0)
17773       return nullptr;
17774     Function *Intrinsic =
17775         CGM.getIntrinsic(IID, Dst->getType());
17776     llvm::Type *ParamType = Intrinsic->getFunctionType()->getParamType(1);
17777     SmallVector<Value *, 10> Values = {Dst};
17778     for (unsigned i = 0; i < II.NumResults; ++i) {
17779       Value *V = Builder.CreateAlignedLoad(
17780           Src.getElementType(),
17781           Builder.CreateGEP(Src.getElementType(), Src.getPointer(),
17782                             llvm::ConstantInt::get(IntTy, i)),
17783           CharUnits::fromQuantity(4));
17784       Values.push_back(Builder.CreateBitCast(V, ParamType));
17785     }
17786     Values.push_back(Ldm);
17787     Value *Result = Builder.CreateCall(Intrinsic, Values);
17788     return Result;
17789   }
17790 
17791   // BI__hmma_m16n16k16_mma_<Dtype><CType>(d, a, b, c, layout, satf) -->
17792   // Intrinsic::nvvm_wmma_m16n16k16_mma_sync<layout A,B><DType><CType><Satf>
17793   case NVPTX::BI__hmma_m16n16k16_mma_f16f16:
17794   case NVPTX::BI__hmma_m16n16k16_mma_f32f16:
17795   case NVPTX::BI__hmma_m16n16k16_mma_f32f32:
17796   case NVPTX::BI__hmma_m16n16k16_mma_f16f32:
17797   case NVPTX::BI__hmma_m32n8k16_mma_f16f16:
17798   case NVPTX::BI__hmma_m32n8k16_mma_f32f16:
17799   case NVPTX::BI__hmma_m32n8k16_mma_f32f32:
17800   case NVPTX::BI__hmma_m32n8k16_mma_f16f32:
17801   case NVPTX::BI__hmma_m8n32k16_mma_f16f16:
17802   case NVPTX::BI__hmma_m8n32k16_mma_f32f16:
17803   case NVPTX::BI__hmma_m8n32k16_mma_f32f32:
17804   case NVPTX::BI__hmma_m8n32k16_mma_f16f32:
17805   case NVPTX::BI__imma_m16n16k16_mma_s8:
17806   case NVPTX::BI__imma_m16n16k16_mma_u8:
17807   case NVPTX::BI__imma_m32n8k16_mma_s8:
17808   case NVPTX::BI__imma_m32n8k16_mma_u8:
17809   case NVPTX::BI__imma_m8n32k16_mma_s8:
17810   case NVPTX::BI__imma_m8n32k16_mma_u8:
17811   case NVPTX::BI__imma_m8n8k32_mma_s4:
17812   case NVPTX::BI__imma_m8n8k32_mma_u4:
17813   case NVPTX::BI__bmma_m8n8k128_mma_xor_popc_b1:
17814   case NVPTX::BI__bmma_m8n8k128_mma_and_popc_b1:
17815   case NVPTX::BI__dmma_m8n8k4_mma_f64:
17816   case NVPTX::BI__mma_bf16_m16n16k16_mma_f32:
17817   case NVPTX::BI__mma_bf16_m8n32k16_mma_f32:
17818   case NVPTX::BI__mma_bf16_m32n8k16_mma_f32:
17819   case NVPTX::BI__mma_tf32_m16n16k8_mma_f32: {
17820     Address Dst = EmitPointerWithAlignment(E->getArg(0));
17821     Address SrcA = EmitPointerWithAlignment(E->getArg(1));
17822     Address SrcB = EmitPointerWithAlignment(E->getArg(2));
17823     Address SrcC = EmitPointerWithAlignment(E->getArg(3));
17824     Optional<llvm::APSInt> LayoutArg =
17825         E->getArg(4)->getIntegerConstantExpr(getContext());
17826     if (!LayoutArg)
17827       return nullptr;
17828     int Layout = LayoutArg->getSExtValue();
17829     if (Layout < 0 || Layout > 3)
17830       return nullptr;
17831     llvm::APSInt SatfArg;
17832     if (BuiltinID == NVPTX::BI__bmma_m8n8k128_mma_xor_popc_b1 ||
17833         BuiltinID == NVPTX::BI__bmma_m8n8k128_mma_and_popc_b1)
17834       SatfArg = 0;  // .b1 does not have satf argument.
17835     else if (Optional<llvm::APSInt> OptSatfArg =
17836                  E->getArg(5)->getIntegerConstantExpr(getContext()))
17837       SatfArg = *OptSatfArg;
17838     else
17839       return nullptr;
17840     bool Satf = SatfArg.getSExtValue();
17841     NVPTXMmaInfo MI = getNVPTXMmaInfo(BuiltinID);
17842     unsigned IID = MI.getMMAIntrinsic(Layout, Satf);
17843     if (IID == 0)  // Unsupported combination of Layout/Satf.
17844       return nullptr;
17845 
17846     SmallVector<Value *, 24> Values;
17847     Function *Intrinsic = CGM.getIntrinsic(IID);
17848     llvm::Type *AType = Intrinsic->getFunctionType()->getParamType(0);
17849     // Load A
17850     for (unsigned i = 0; i < MI.NumEltsA; ++i) {
17851       Value *V = Builder.CreateAlignedLoad(
17852           SrcA.getElementType(),
17853           Builder.CreateGEP(SrcA.getElementType(), SrcA.getPointer(),
17854                             llvm::ConstantInt::get(IntTy, i)),
17855           CharUnits::fromQuantity(4));
17856       Values.push_back(Builder.CreateBitCast(V, AType));
17857     }
17858     // Load B
17859     llvm::Type *BType = Intrinsic->getFunctionType()->getParamType(MI.NumEltsA);
17860     for (unsigned i = 0; i < MI.NumEltsB; ++i) {
17861       Value *V = Builder.CreateAlignedLoad(
17862           SrcB.getElementType(),
17863           Builder.CreateGEP(SrcB.getElementType(), SrcB.getPointer(),
17864                             llvm::ConstantInt::get(IntTy, i)),
17865           CharUnits::fromQuantity(4));
17866       Values.push_back(Builder.CreateBitCast(V, BType));
17867     }
17868     // Load C
17869     llvm::Type *CType =
17870         Intrinsic->getFunctionType()->getParamType(MI.NumEltsA + MI.NumEltsB);
17871     for (unsigned i = 0; i < MI.NumEltsC; ++i) {
17872       Value *V = Builder.CreateAlignedLoad(
17873           SrcC.getElementType(),
17874           Builder.CreateGEP(SrcC.getElementType(), SrcC.getPointer(),
17875                             llvm::ConstantInt::get(IntTy, i)),
17876           CharUnits::fromQuantity(4));
17877       Values.push_back(Builder.CreateBitCast(V, CType));
17878     }
17879     Value *Result = Builder.CreateCall(Intrinsic, Values);
17880     llvm::Type *DType = Dst.getElementType();
17881     for (unsigned i = 0; i < MI.NumEltsD; ++i)
17882       Builder.CreateAlignedStore(
17883           Builder.CreateBitCast(Builder.CreateExtractValue(Result, i), DType),
17884           Builder.CreateGEP(Dst.getElementType(), Dst.getPointer(),
17885                             llvm::ConstantInt::get(IntTy, i)),
17886           CharUnits::fromQuantity(4));
17887     return Result;
17888   }
17889   default:
17890     return nullptr;
17891   }
17892 }
17893 
17894 namespace {
17895 struct BuiltinAlignArgs {
17896   llvm::Value *Src = nullptr;
17897   llvm::Type *SrcType = nullptr;
17898   llvm::Value *Alignment = nullptr;
17899   llvm::Value *Mask = nullptr;
17900   llvm::IntegerType *IntType = nullptr;
17901 
17902   BuiltinAlignArgs(const CallExpr *E, CodeGenFunction &CGF) {
17903     QualType AstType = E->getArg(0)->getType();
17904     if (AstType->isArrayType())
17905       Src = CGF.EmitArrayToPointerDecay(E->getArg(0)).getPointer();
17906     else
17907       Src = CGF.EmitScalarExpr(E->getArg(0));
17908     SrcType = Src->getType();
17909     if (SrcType->isPointerTy()) {
17910       IntType = IntegerType::get(
17911           CGF.getLLVMContext(),
17912           CGF.CGM.getDataLayout().getIndexTypeSizeInBits(SrcType));
17913     } else {
17914       assert(SrcType->isIntegerTy());
17915       IntType = cast<llvm::IntegerType>(SrcType);
17916     }
17917     Alignment = CGF.EmitScalarExpr(E->getArg(1));
17918     Alignment = CGF.Builder.CreateZExtOrTrunc(Alignment, IntType, "alignment");
17919     auto *One = llvm::ConstantInt::get(IntType, 1);
17920     Mask = CGF.Builder.CreateSub(Alignment, One, "mask");
17921   }
17922 };
17923 } // namespace
17924 
17925 /// Generate (x & (y-1)) == 0.
17926 RValue CodeGenFunction::EmitBuiltinIsAligned(const CallExpr *E) {
17927   BuiltinAlignArgs Args(E, *this);
17928   llvm::Value *SrcAddress = Args.Src;
17929   if (Args.SrcType->isPointerTy())
17930     SrcAddress =
17931         Builder.CreateBitOrPointerCast(Args.Src, Args.IntType, "src_addr");
17932   return RValue::get(Builder.CreateICmpEQ(
17933       Builder.CreateAnd(SrcAddress, Args.Mask, "set_bits"),
17934       llvm::Constant::getNullValue(Args.IntType), "is_aligned"));
17935 }
17936 
17937 /// Generate (x & ~(y-1)) to align down or ((x+(y-1)) & ~(y-1)) to align up.
17938 /// Note: For pointer types we can avoid ptrtoint/inttoptr pairs by using the
17939 /// llvm.ptrmask instrinsic (with a GEP before in the align_up case).
17940 /// TODO: actually use ptrmask once most optimization passes know about it.
17941 RValue CodeGenFunction::EmitBuiltinAlignTo(const CallExpr *E, bool AlignUp) {
17942   BuiltinAlignArgs Args(E, *this);
17943   llvm::Value *SrcAddr = Args.Src;
17944   if (Args.Src->getType()->isPointerTy())
17945     SrcAddr = Builder.CreatePtrToInt(Args.Src, Args.IntType, "intptr");
17946   llvm::Value *SrcForMask = SrcAddr;
17947   if (AlignUp) {
17948     // When aligning up we have to first add the mask to ensure we go over the
17949     // next alignment value and then align down to the next valid multiple.
17950     // By adding the mask, we ensure that align_up on an already aligned
17951     // value will not change the value.
17952     SrcForMask = Builder.CreateAdd(SrcForMask, Args.Mask, "over_boundary");
17953   }
17954   // Invert the mask to only clear the lower bits.
17955   llvm::Value *InvertedMask = Builder.CreateNot(Args.Mask, "inverted_mask");
17956   llvm::Value *Result =
17957       Builder.CreateAnd(SrcForMask, InvertedMask, "aligned_result");
17958   if (Args.Src->getType()->isPointerTy()) {
17959     /// TODO: Use ptrmask instead of ptrtoint+gep once it is optimized well.
17960     // Result = Builder.CreateIntrinsic(
17961     //  Intrinsic::ptrmask, {Args.SrcType, SrcForMask->getType(), Args.IntType},
17962     //  {SrcForMask, NegatedMask}, nullptr, "aligned_result");
17963     Result->setName("aligned_intptr");
17964     llvm::Value *Difference = Builder.CreateSub(Result, SrcAddr, "diff");
17965     // The result must point to the same underlying allocation. This means we
17966     // can use an inbounds GEP to enable better optimization.
17967     Value *Base = EmitCastToVoidPtr(Args.Src);
17968     if (getLangOpts().isSignedOverflowDefined())
17969       Result = Builder.CreateGEP(Int8Ty, Base, Difference, "aligned_result");
17970     else
17971       Result = EmitCheckedInBoundsGEP(Int8Ty, Base, Difference,
17972                                       /*SignedIndices=*/true,
17973                                       /*isSubtraction=*/!AlignUp,
17974                                       E->getExprLoc(), "aligned_result");
17975     Result = Builder.CreatePointerCast(Result, Args.SrcType);
17976     // Emit an alignment assumption to ensure that the new alignment is
17977     // propagated to loads/stores, etc.
17978     emitAlignmentAssumption(Result, E, E->getExprLoc(), Args.Alignment);
17979   }
17980   assert(Result->getType() == Args.SrcType);
17981   return RValue::get(Result);
17982 }
17983 
17984 Value *CodeGenFunction::EmitWebAssemblyBuiltinExpr(unsigned BuiltinID,
17985                                                    const CallExpr *E) {
17986   switch (BuiltinID) {
17987   case WebAssembly::BI__builtin_wasm_memory_size: {
17988     llvm::Type *ResultType = ConvertType(E->getType());
17989     Value *I = EmitScalarExpr(E->getArg(0));
17990     Function *Callee =
17991         CGM.getIntrinsic(Intrinsic::wasm_memory_size, ResultType);
17992     return Builder.CreateCall(Callee, I);
17993   }
17994   case WebAssembly::BI__builtin_wasm_memory_grow: {
17995     llvm::Type *ResultType = ConvertType(E->getType());
17996     Value *Args[] = {EmitScalarExpr(E->getArg(0)),
17997                      EmitScalarExpr(E->getArg(1))};
17998     Function *Callee =
17999         CGM.getIntrinsic(Intrinsic::wasm_memory_grow, ResultType);
18000     return Builder.CreateCall(Callee, Args);
18001   }
18002   case WebAssembly::BI__builtin_wasm_tls_size: {
18003     llvm::Type *ResultType = ConvertType(E->getType());
18004     Function *Callee = CGM.getIntrinsic(Intrinsic::wasm_tls_size, ResultType);
18005     return Builder.CreateCall(Callee);
18006   }
18007   case WebAssembly::BI__builtin_wasm_tls_align: {
18008     llvm::Type *ResultType = ConvertType(E->getType());
18009     Function *Callee = CGM.getIntrinsic(Intrinsic::wasm_tls_align, ResultType);
18010     return Builder.CreateCall(Callee);
18011   }
18012   case WebAssembly::BI__builtin_wasm_tls_base: {
18013     Function *Callee = CGM.getIntrinsic(Intrinsic::wasm_tls_base);
18014     return Builder.CreateCall(Callee);
18015   }
18016   case WebAssembly::BI__builtin_wasm_throw: {
18017     Value *Tag = EmitScalarExpr(E->getArg(0));
18018     Value *Obj = EmitScalarExpr(E->getArg(1));
18019     Function *Callee = CGM.getIntrinsic(Intrinsic::wasm_throw);
18020     return Builder.CreateCall(Callee, {Tag, Obj});
18021   }
18022   case WebAssembly::BI__builtin_wasm_rethrow: {
18023     Function *Callee = CGM.getIntrinsic(Intrinsic::wasm_rethrow);
18024     return Builder.CreateCall(Callee);
18025   }
18026   case WebAssembly::BI__builtin_wasm_memory_atomic_wait32: {
18027     Value *Addr = EmitScalarExpr(E->getArg(0));
18028     Value *Expected = EmitScalarExpr(E->getArg(1));
18029     Value *Timeout = EmitScalarExpr(E->getArg(2));
18030     Function *Callee = CGM.getIntrinsic(Intrinsic::wasm_memory_atomic_wait32);
18031     return Builder.CreateCall(Callee, {Addr, Expected, Timeout});
18032   }
18033   case WebAssembly::BI__builtin_wasm_memory_atomic_wait64: {
18034     Value *Addr = EmitScalarExpr(E->getArg(0));
18035     Value *Expected = EmitScalarExpr(E->getArg(1));
18036     Value *Timeout = EmitScalarExpr(E->getArg(2));
18037     Function *Callee = CGM.getIntrinsic(Intrinsic::wasm_memory_atomic_wait64);
18038     return Builder.CreateCall(Callee, {Addr, Expected, Timeout});
18039   }
18040   case WebAssembly::BI__builtin_wasm_memory_atomic_notify: {
18041     Value *Addr = EmitScalarExpr(E->getArg(0));
18042     Value *Count = EmitScalarExpr(E->getArg(1));
18043     Function *Callee = CGM.getIntrinsic(Intrinsic::wasm_memory_atomic_notify);
18044     return Builder.CreateCall(Callee, {Addr, Count});
18045   }
18046   case WebAssembly::BI__builtin_wasm_trunc_s_i32_f32:
18047   case WebAssembly::BI__builtin_wasm_trunc_s_i32_f64:
18048   case WebAssembly::BI__builtin_wasm_trunc_s_i64_f32:
18049   case WebAssembly::BI__builtin_wasm_trunc_s_i64_f64: {
18050     Value *Src = EmitScalarExpr(E->getArg(0));
18051     llvm::Type *ResT = ConvertType(E->getType());
18052     Function *Callee =
18053         CGM.getIntrinsic(Intrinsic::wasm_trunc_signed, {ResT, Src->getType()});
18054     return Builder.CreateCall(Callee, {Src});
18055   }
18056   case WebAssembly::BI__builtin_wasm_trunc_u_i32_f32:
18057   case WebAssembly::BI__builtin_wasm_trunc_u_i32_f64:
18058   case WebAssembly::BI__builtin_wasm_trunc_u_i64_f32:
18059   case WebAssembly::BI__builtin_wasm_trunc_u_i64_f64: {
18060     Value *Src = EmitScalarExpr(E->getArg(0));
18061     llvm::Type *ResT = ConvertType(E->getType());
18062     Function *Callee = CGM.getIntrinsic(Intrinsic::wasm_trunc_unsigned,
18063                                         {ResT, Src->getType()});
18064     return Builder.CreateCall(Callee, {Src});
18065   }
18066   case WebAssembly::BI__builtin_wasm_trunc_saturate_s_i32_f32:
18067   case WebAssembly::BI__builtin_wasm_trunc_saturate_s_i32_f64:
18068   case WebAssembly::BI__builtin_wasm_trunc_saturate_s_i64_f32:
18069   case WebAssembly::BI__builtin_wasm_trunc_saturate_s_i64_f64:
18070   case WebAssembly::BI__builtin_wasm_trunc_saturate_s_i32x4_f32x4: {
18071     Value *Src = EmitScalarExpr(E->getArg(0));
18072     llvm::Type *ResT = ConvertType(E->getType());
18073     Function *Callee =
18074         CGM.getIntrinsic(Intrinsic::fptosi_sat, {ResT, Src->getType()});
18075     return Builder.CreateCall(Callee, {Src});
18076   }
18077   case WebAssembly::BI__builtin_wasm_trunc_saturate_u_i32_f32:
18078   case WebAssembly::BI__builtin_wasm_trunc_saturate_u_i32_f64:
18079   case WebAssembly::BI__builtin_wasm_trunc_saturate_u_i64_f32:
18080   case WebAssembly::BI__builtin_wasm_trunc_saturate_u_i64_f64:
18081   case WebAssembly::BI__builtin_wasm_trunc_saturate_u_i32x4_f32x4: {
18082     Value *Src = EmitScalarExpr(E->getArg(0));
18083     llvm::Type *ResT = ConvertType(E->getType());
18084     Function *Callee =
18085         CGM.getIntrinsic(Intrinsic::fptoui_sat, {ResT, Src->getType()});
18086     return Builder.CreateCall(Callee, {Src});
18087   }
18088   case WebAssembly::BI__builtin_wasm_min_f32:
18089   case WebAssembly::BI__builtin_wasm_min_f64:
18090   case WebAssembly::BI__builtin_wasm_min_f32x4:
18091   case WebAssembly::BI__builtin_wasm_min_f64x2: {
18092     Value *LHS = EmitScalarExpr(E->getArg(0));
18093     Value *RHS = EmitScalarExpr(E->getArg(1));
18094     Function *Callee =
18095         CGM.getIntrinsic(Intrinsic::minimum, ConvertType(E->getType()));
18096     return Builder.CreateCall(Callee, {LHS, RHS});
18097   }
18098   case WebAssembly::BI__builtin_wasm_max_f32:
18099   case WebAssembly::BI__builtin_wasm_max_f64:
18100   case WebAssembly::BI__builtin_wasm_max_f32x4:
18101   case WebAssembly::BI__builtin_wasm_max_f64x2: {
18102     Value *LHS = EmitScalarExpr(E->getArg(0));
18103     Value *RHS = EmitScalarExpr(E->getArg(1));
18104     Function *Callee =
18105         CGM.getIntrinsic(Intrinsic::maximum, ConvertType(E->getType()));
18106     return Builder.CreateCall(Callee, {LHS, RHS});
18107   }
18108   case WebAssembly::BI__builtin_wasm_pmin_f32x4:
18109   case WebAssembly::BI__builtin_wasm_pmin_f64x2: {
18110     Value *LHS = EmitScalarExpr(E->getArg(0));
18111     Value *RHS = EmitScalarExpr(E->getArg(1));
18112     Function *Callee =
18113         CGM.getIntrinsic(Intrinsic::wasm_pmin, ConvertType(E->getType()));
18114     return Builder.CreateCall(Callee, {LHS, RHS});
18115   }
18116   case WebAssembly::BI__builtin_wasm_pmax_f32x4:
18117   case WebAssembly::BI__builtin_wasm_pmax_f64x2: {
18118     Value *LHS = EmitScalarExpr(E->getArg(0));
18119     Value *RHS = EmitScalarExpr(E->getArg(1));
18120     Function *Callee =
18121         CGM.getIntrinsic(Intrinsic::wasm_pmax, ConvertType(E->getType()));
18122     return Builder.CreateCall(Callee, {LHS, RHS});
18123   }
18124   case WebAssembly::BI__builtin_wasm_ceil_f32x4:
18125   case WebAssembly::BI__builtin_wasm_floor_f32x4:
18126   case WebAssembly::BI__builtin_wasm_trunc_f32x4:
18127   case WebAssembly::BI__builtin_wasm_nearest_f32x4:
18128   case WebAssembly::BI__builtin_wasm_ceil_f64x2:
18129   case WebAssembly::BI__builtin_wasm_floor_f64x2:
18130   case WebAssembly::BI__builtin_wasm_trunc_f64x2:
18131   case WebAssembly::BI__builtin_wasm_nearest_f64x2: {
18132     unsigned IntNo;
18133     switch (BuiltinID) {
18134     case WebAssembly::BI__builtin_wasm_ceil_f32x4:
18135     case WebAssembly::BI__builtin_wasm_ceil_f64x2:
18136       IntNo = Intrinsic::ceil;
18137       break;
18138     case WebAssembly::BI__builtin_wasm_floor_f32x4:
18139     case WebAssembly::BI__builtin_wasm_floor_f64x2:
18140       IntNo = Intrinsic::floor;
18141       break;
18142     case WebAssembly::BI__builtin_wasm_trunc_f32x4:
18143     case WebAssembly::BI__builtin_wasm_trunc_f64x2:
18144       IntNo = Intrinsic::trunc;
18145       break;
18146     case WebAssembly::BI__builtin_wasm_nearest_f32x4:
18147     case WebAssembly::BI__builtin_wasm_nearest_f64x2:
18148       IntNo = Intrinsic::nearbyint;
18149       break;
18150     default:
18151       llvm_unreachable("unexpected builtin ID");
18152     }
18153     Value *Value = EmitScalarExpr(E->getArg(0));
18154     Function *Callee = CGM.getIntrinsic(IntNo, ConvertType(E->getType()));
18155     return Builder.CreateCall(Callee, Value);
18156   }
18157   case WebAssembly::BI__builtin_wasm_swizzle_i8x16: {
18158     Value *Src = EmitScalarExpr(E->getArg(0));
18159     Value *Indices = EmitScalarExpr(E->getArg(1));
18160     Function *Callee = CGM.getIntrinsic(Intrinsic::wasm_swizzle);
18161     return Builder.CreateCall(Callee, {Src, Indices});
18162   }
18163   case WebAssembly::BI__builtin_wasm_add_sat_s_i8x16:
18164   case WebAssembly::BI__builtin_wasm_add_sat_u_i8x16:
18165   case WebAssembly::BI__builtin_wasm_add_sat_s_i16x8:
18166   case WebAssembly::BI__builtin_wasm_add_sat_u_i16x8:
18167   case WebAssembly::BI__builtin_wasm_sub_sat_s_i8x16:
18168   case WebAssembly::BI__builtin_wasm_sub_sat_u_i8x16:
18169   case WebAssembly::BI__builtin_wasm_sub_sat_s_i16x8:
18170   case WebAssembly::BI__builtin_wasm_sub_sat_u_i16x8: {
18171     unsigned IntNo;
18172     switch (BuiltinID) {
18173     case WebAssembly::BI__builtin_wasm_add_sat_s_i8x16:
18174     case WebAssembly::BI__builtin_wasm_add_sat_s_i16x8:
18175       IntNo = Intrinsic::sadd_sat;
18176       break;
18177     case WebAssembly::BI__builtin_wasm_add_sat_u_i8x16:
18178     case WebAssembly::BI__builtin_wasm_add_sat_u_i16x8:
18179       IntNo = Intrinsic::uadd_sat;
18180       break;
18181     case WebAssembly::BI__builtin_wasm_sub_sat_s_i8x16:
18182     case WebAssembly::BI__builtin_wasm_sub_sat_s_i16x8:
18183       IntNo = Intrinsic::wasm_sub_sat_signed;
18184       break;
18185     case WebAssembly::BI__builtin_wasm_sub_sat_u_i8x16:
18186     case WebAssembly::BI__builtin_wasm_sub_sat_u_i16x8:
18187       IntNo = Intrinsic::wasm_sub_sat_unsigned;
18188       break;
18189     default:
18190       llvm_unreachable("unexpected builtin ID");
18191     }
18192     Value *LHS = EmitScalarExpr(E->getArg(0));
18193     Value *RHS = EmitScalarExpr(E->getArg(1));
18194     Function *Callee = CGM.getIntrinsic(IntNo, ConvertType(E->getType()));
18195     return Builder.CreateCall(Callee, {LHS, RHS});
18196   }
18197   case WebAssembly::BI__builtin_wasm_abs_i8x16:
18198   case WebAssembly::BI__builtin_wasm_abs_i16x8:
18199   case WebAssembly::BI__builtin_wasm_abs_i32x4:
18200   case WebAssembly::BI__builtin_wasm_abs_i64x2: {
18201     Value *Vec = EmitScalarExpr(E->getArg(0));
18202     Value *Neg = Builder.CreateNeg(Vec, "neg");
18203     Constant *Zero = llvm::Constant::getNullValue(Vec->getType());
18204     Value *ICmp = Builder.CreateICmpSLT(Vec, Zero, "abscond");
18205     return Builder.CreateSelect(ICmp, Neg, Vec, "abs");
18206   }
18207   case WebAssembly::BI__builtin_wasm_min_s_i8x16:
18208   case WebAssembly::BI__builtin_wasm_min_u_i8x16:
18209   case WebAssembly::BI__builtin_wasm_max_s_i8x16:
18210   case WebAssembly::BI__builtin_wasm_max_u_i8x16:
18211   case WebAssembly::BI__builtin_wasm_min_s_i16x8:
18212   case WebAssembly::BI__builtin_wasm_min_u_i16x8:
18213   case WebAssembly::BI__builtin_wasm_max_s_i16x8:
18214   case WebAssembly::BI__builtin_wasm_max_u_i16x8:
18215   case WebAssembly::BI__builtin_wasm_min_s_i32x4:
18216   case WebAssembly::BI__builtin_wasm_min_u_i32x4:
18217   case WebAssembly::BI__builtin_wasm_max_s_i32x4:
18218   case WebAssembly::BI__builtin_wasm_max_u_i32x4: {
18219     Value *LHS = EmitScalarExpr(E->getArg(0));
18220     Value *RHS = EmitScalarExpr(E->getArg(1));
18221     Value *ICmp;
18222     switch (BuiltinID) {
18223     case WebAssembly::BI__builtin_wasm_min_s_i8x16:
18224     case WebAssembly::BI__builtin_wasm_min_s_i16x8:
18225     case WebAssembly::BI__builtin_wasm_min_s_i32x4:
18226       ICmp = Builder.CreateICmpSLT(LHS, RHS);
18227       break;
18228     case WebAssembly::BI__builtin_wasm_min_u_i8x16:
18229     case WebAssembly::BI__builtin_wasm_min_u_i16x8:
18230     case WebAssembly::BI__builtin_wasm_min_u_i32x4:
18231       ICmp = Builder.CreateICmpULT(LHS, RHS);
18232       break;
18233     case WebAssembly::BI__builtin_wasm_max_s_i8x16:
18234     case WebAssembly::BI__builtin_wasm_max_s_i16x8:
18235     case WebAssembly::BI__builtin_wasm_max_s_i32x4:
18236       ICmp = Builder.CreateICmpSGT(LHS, RHS);
18237       break;
18238     case WebAssembly::BI__builtin_wasm_max_u_i8x16:
18239     case WebAssembly::BI__builtin_wasm_max_u_i16x8:
18240     case WebAssembly::BI__builtin_wasm_max_u_i32x4:
18241       ICmp = Builder.CreateICmpUGT(LHS, RHS);
18242       break;
18243     default:
18244       llvm_unreachable("unexpected builtin ID");
18245     }
18246     return Builder.CreateSelect(ICmp, LHS, RHS);
18247   }
18248   case WebAssembly::BI__builtin_wasm_avgr_u_i8x16:
18249   case WebAssembly::BI__builtin_wasm_avgr_u_i16x8: {
18250     Value *LHS = EmitScalarExpr(E->getArg(0));
18251     Value *RHS = EmitScalarExpr(E->getArg(1));
18252     Function *Callee = CGM.getIntrinsic(Intrinsic::wasm_avgr_unsigned,
18253                                         ConvertType(E->getType()));
18254     return Builder.CreateCall(Callee, {LHS, RHS});
18255   }
18256   case WebAssembly::BI__builtin_wasm_q15mulr_sat_s_i16x8: {
18257     Value *LHS = EmitScalarExpr(E->getArg(0));
18258     Value *RHS = EmitScalarExpr(E->getArg(1));
18259     Function *Callee = CGM.getIntrinsic(Intrinsic::wasm_q15mulr_sat_signed);
18260     return Builder.CreateCall(Callee, {LHS, RHS});
18261   }
18262   case WebAssembly::BI__builtin_wasm_extadd_pairwise_i8x16_s_i16x8:
18263   case WebAssembly::BI__builtin_wasm_extadd_pairwise_i8x16_u_i16x8:
18264   case WebAssembly::BI__builtin_wasm_extadd_pairwise_i16x8_s_i32x4:
18265   case WebAssembly::BI__builtin_wasm_extadd_pairwise_i16x8_u_i32x4: {
18266     Value *Vec = EmitScalarExpr(E->getArg(0));
18267     unsigned IntNo;
18268     switch (BuiltinID) {
18269     case WebAssembly::BI__builtin_wasm_extadd_pairwise_i8x16_s_i16x8:
18270     case WebAssembly::BI__builtin_wasm_extadd_pairwise_i16x8_s_i32x4:
18271       IntNo = Intrinsic::wasm_extadd_pairwise_signed;
18272       break;
18273     case WebAssembly::BI__builtin_wasm_extadd_pairwise_i8x16_u_i16x8:
18274     case WebAssembly::BI__builtin_wasm_extadd_pairwise_i16x8_u_i32x4:
18275       IntNo = Intrinsic::wasm_extadd_pairwise_unsigned;
18276       break;
18277     default:
18278       llvm_unreachable("unexptected builtin ID");
18279     }
18280 
18281     Function *Callee = CGM.getIntrinsic(IntNo, ConvertType(E->getType()));
18282     return Builder.CreateCall(Callee, Vec);
18283   }
18284   case WebAssembly::BI__builtin_wasm_bitselect: {
18285     Value *V1 = EmitScalarExpr(E->getArg(0));
18286     Value *V2 = EmitScalarExpr(E->getArg(1));
18287     Value *C = EmitScalarExpr(E->getArg(2));
18288     Function *Callee =
18289         CGM.getIntrinsic(Intrinsic::wasm_bitselect, ConvertType(E->getType()));
18290     return Builder.CreateCall(Callee, {V1, V2, C});
18291   }
18292   case WebAssembly::BI__builtin_wasm_dot_s_i32x4_i16x8: {
18293     Value *LHS = EmitScalarExpr(E->getArg(0));
18294     Value *RHS = EmitScalarExpr(E->getArg(1));
18295     Function *Callee = CGM.getIntrinsic(Intrinsic::wasm_dot);
18296     return Builder.CreateCall(Callee, {LHS, RHS});
18297   }
18298   case WebAssembly::BI__builtin_wasm_popcnt_i8x16: {
18299     Value *Vec = EmitScalarExpr(E->getArg(0));
18300     Function *Callee =
18301         CGM.getIntrinsic(Intrinsic::ctpop, ConvertType(E->getType()));
18302     return Builder.CreateCall(Callee, {Vec});
18303   }
18304   case WebAssembly::BI__builtin_wasm_any_true_v128:
18305   case WebAssembly::BI__builtin_wasm_all_true_i8x16:
18306   case WebAssembly::BI__builtin_wasm_all_true_i16x8:
18307   case WebAssembly::BI__builtin_wasm_all_true_i32x4:
18308   case WebAssembly::BI__builtin_wasm_all_true_i64x2: {
18309     unsigned IntNo;
18310     switch (BuiltinID) {
18311     case WebAssembly::BI__builtin_wasm_any_true_v128:
18312       IntNo = Intrinsic::wasm_anytrue;
18313       break;
18314     case WebAssembly::BI__builtin_wasm_all_true_i8x16:
18315     case WebAssembly::BI__builtin_wasm_all_true_i16x8:
18316     case WebAssembly::BI__builtin_wasm_all_true_i32x4:
18317     case WebAssembly::BI__builtin_wasm_all_true_i64x2:
18318       IntNo = Intrinsic::wasm_alltrue;
18319       break;
18320     default:
18321       llvm_unreachable("unexpected builtin ID");
18322     }
18323     Value *Vec = EmitScalarExpr(E->getArg(0));
18324     Function *Callee = CGM.getIntrinsic(IntNo, Vec->getType());
18325     return Builder.CreateCall(Callee, {Vec});
18326   }
18327   case WebAssembly::BI__builtin_wasm_bitmask_i8x16:
18328   case WebAssembly::BI__builtin_wasm_bitmask_i16x8:
18329   case WebAssembly::BI__builtin_wasm_bitmask_i32x4:
18330   case WebAssembly::BI__builtin_wasm_bitmask_i64x2: {
18331     Value *Vec = EmitScalarExpr(E->getArg(0));
18332     Function *Callee =
18333         CGM.getIntrinsic(Intrinsic::wasm_bitmask, Vec->getType());
18334     return Builder.CreateCall(Callee, {Vec});
18335   }
18336   case WebAssembly::BI__builtin_wasm_abs_f32x4:
18337   case WebAssembly::BI__builtin_wasm_abs_f64x2: {
18338     Value *Vec = EmitScalarExpr(E->getArg(0));
18339     Function *Callee = CGM.getIntrinsic(Intrinsic::fabs, Vec->getType());
18340     return Builder.CreateCall(Callee, {Vec});
18341   }
18342   case WebAssembly::BI__builtin_wasm_sqrt_f32x4:
18343   case WebAssembly::BI__builtin_wasm_sqrt_f64x2: {
18344     Value *Vec = EmitScalarExpr(E->getArg(0));
18345     Function *Callee = CGM.getIntrinsic(Intrinsic::sqrt, Vec->getType());
18346     return Builder.CreateCall(Callee, {Vec});
18347   }
18348   case WebAssembly::BI__builtin_wasm_narrow_s_i8x16_i16x8:
18349   case WebAssembly::BI__builtin_wasm_narrow_u_i8x16_i16x8:
18350   case WebAssembly::BI__builtin_wasm_narrow_s_i16x8_i32x4:
18351   case WebAssembly::BI__builtin_wasm_narrow_u_i16x8_i32x4: {
18352     Value *Low = EmitScalarExpr(E->getArg(0));
18353     Value *High = EmitScalarExpr(E->getArg(1));
18354     unsigned IntNo;
18355     switch (BuiltinID) {
18356     case WebAssembly::BI__builtin_wasm_narrow_s_i8x16_i16x8:
18357     case WebAssembly::BI__builtin_wasm_narrow_s_i16x8_i32x4:
18358       IntNo = Intrinsic::wasm_narrow_signed;
18359       break;
18360     case WebAssembly::BI__builtin_wasm_narrow_u_i8x16_i16x8:
18361     case WebAssembly::BI__builtin_wasm_narrow_u_i16x8_i32x4:
18362       IntNo = Intrinsic::wasm_narrow_unsigned;
18363       break;
18364     default:
18365       llvm_unreachable("unexpected builtin ID");
18366     }
18367     Function *Callee =
18368         CGM.getIntrinsic(IntNo, {ConvertType(E->getType()), Low->getType()});
18369     return Builder.CreateCall(Callee, {Low, High});
18370   }
18371   case WebAssembly::BI__builtin_wasm_trunc_sat_zero_s_f64x2_i32x4:
18372   case WebAssembly::BI__builtin_wasm_trunc_sat_zero_u_f64x2_i32x4: {
18373     Value *Vec = EmitScalarExpr(E->getArg(0));
18374     unsigned IntNo;
18375     switch (BuiltinID) {
18376     case WebAssembly::BI__builtin_wasm_trunc_sat_zero_s_f64x2_i32x4:
18377       IntNo = Intrinsic::fptosi_sat;
18378       break;
18379     case WebAssembly::BI__builtin_wasm_trunc_sat_zero_u_f64x2_i32x4:
18380       IntNo = Intrinsic::fptoui_sat;
18381       break;
18382     default:
18383       llvm_unreachable("unexpected builtin ID");
18384     }
18385     llvm::Type *SrcT = Vec->getType();
18386     llvm::Type *TruncT = SrcT->getWithNewType(Builder.getInt32Ty());
18387     Function *Callee = CGM.getIntrinsic(IntNo, {TruncT, SrcT});
18388     Value *Trunc = Builder.CreateCall(Callee, Vec);
18389     Value *Splat = Constant::getNullValue(TruncT);
18390     return Builder.CreateShuffleVector(Trunc, Splat, ArrayRef<int>{0, 1, 2, 3});
18391   }
18392   case WebAssembly::BI__builtin_wasm_shuffle_i8x16: {
18393     Value *Ops[18];
18394     size_t OpIdx = 0;
18395     Ops[OpIdx++] = EmitScalarExpr(E->getArg(0));
18396     Ops[OpIdx++] = EmitScalarExpr(E->getArg(1));
18397     while (OpIdx < 18) {
18398       Optional<llvm::APSInt> LaneConst =
18399           E->getArg(OpIdx)->getIntegerConstantExpr(getContext());
18400       assert(LaneConst && "Constant arg isn't actually constant?");
18401       Ops[OpIdx++] = llvm::ConstantInt::get(getLLVMContext(), *LaneConst);
18402     }
18403     Function *Callee = CGM.getIntrinsic(Intrinsic::wasm_shuffle);
18404     return Builder.CreateCall(Callee, Ops);
18405   }
18406   case WebAssembly::BI__builtin_wasm_fma_f32x4:
18407   case WebAssembly::BI__builtin_wasm_fms_f32x4:
18408   case WebAssembly::BI__builtin_wasm_fma_f64x2:
18409   case WebAssembly::BI__builtin_wasm_fms_f64x2: {
18410     Value *A = EmitScalarExpr(E->getArg(0));
18411     Value *B = EmitScalarExpr(E->getArg(1));
18412     Value *C = EmitScalarExpr(E->getArg(2));
18413     unsigned IntNo;
18414     switch (BuiltinID) {
18415     case WebAssembly::BI__builtin_wasm_fma_f32x4:
18416     case WebAssembly::BI__builtin_wasm_fma_f64x2:
18417       IntNo = Intrinsic::wasm_fma;
18418       break;
18419     case WebAssembly::BI__builtin_wasm_fms_f32x4:
18420     case WebAssembly::BI__builtin_wasm_fms_f64x2:
18421       IntNo = Intrinsic::wasm_fms;
18422       break;
18423     default:
18424       llvm_unreachable("unexpected builtin ID");
18425     }
18426     Function *Callee = CGM.getIntrinsic(IntNo, A->getType());
18427     return Builder.CreateCall(Callee, {A, B, C});
18428   }
18429   case WebAssembly::BI__builtin_wasm_laneselect_i8x16:
18430   case WebAssembly::BI__builtin_wasm_laneselect_i16x8:
18431   case WebAssembly::BI__builtin_wasm_laneselect_i32x4:
18432   case WebAssembly::BI__builtin_wasm_laneselect_i64x2: {
18433     Value *A = EmitScalarExpr(E->getArg(0));
18434     Value *B = EmitScalarExpr(E->getArg(1));
18435     Value *C = EmitScalarExpr(E->getArg(2));
18436     Function *Callee =
18437         CGM.getIntrinsic(Intrinsic::wasm_laneselect, A->getType());
18438     return Builder.CreateCall(Callee, {A, B, C});
18439   }
18440   case WebAssembly::BI__builtin_wasm_relaxed_swizzle_i8x16: {
18441     Value *Src = EmitScalarExpr(E->getArg(0));
18442     Value *Indices = EmitScalarExpr(E->getArg(1));
18443     Function *Callee = CGM.getIntrinsic(Intrinsic::wasm_relaxed_swizzle);
18444     return Builder.CreateCall(Callee, {Src, Indices});
18445   }
18446   case WebAssembly::BI__builtin_wasm_relaxed_min_f32x4:
18447   case WebAssembly::BI__builtin_wasm_relaxed_max_f32x4:
18448   case WebAssembly::BI__builtin_wasm_relaxed_min_f64x2:
18449   case WebAssembly::BI__builtin_wasm_relaxed_max_f64x2: {
18450     Value *LHS = EmitScalarExpr(E->getArg(0));
18451     Value *RHS = EmitScalarExpr(E->getArg(1));
18452     unsigned IntNo;
18453     switch (BuiltinID) {
18454     case WebAssembly::BI__builtin_wasm_relaxed_min_f32x4:
18455     case WebAssembly::BI__builtin_wasm_relaxed_min_f64x2:
18456       IntNo = Intrinsic::wasm_relaxed_min;
18457       break;
18458     case WebAssembly::BI__builtin_wasm_relaxed_max_f32x4:
18459     case WebAssembly::BI__builtin_wasm_relaxed_max_f64x2:
18460       IntNo = Intrinsic::wasm_relaxed_max;
18461       break;
18462     default:
18463       llvm_unreachable("unexpected builtin ID");
18464     }
18465     Function *Callee = CGM.getIntrinsic(IntNo, LHS->getType());
18466     return Builder.CreateCall(Callee, {LHS, RHS});
18467   }
18468   case WebAssembly::BI__builtin_wasm_relaxed_trunc_s_i32x4_f32x4:
18469   case WebAssembly::BI__builtin_wasm_relaxed_trunc_u_i32x4_f32x4:
18470   case WebAssembly::BI__builtin_wasm_relaxed_trunc_zero_s_i32x4_f64x2:
18471   case WebAssembly::BI__builtin_wasm_relaxed_trunc_zero_u_i32x4_f64x2: {
18472     Value *Vec = EmitScalarExpr(E->getArg(0));
18473     unsigned IntNo;
18474     switch (BuiltinID) {
18475     case WebAssembly::BI__builtin_wasm_relaxed_trunc_s_i32x4_f32x4:
18476       IntNo = Intrinsic::wasm_relaxed_trunc_signed;
18477       break;
18478     case WebAssembly::BI__builtin_wasm_relaxed_trunc_u_i32x4_f32x4:
18479       IntNo = Intrinsic::wasm_relaxed_trunc_unsigned;
18480       break;
18481     case WebAssembly::BI__builtin_wasm_relaxed_trunc_zero_s_i32x4_f64x2:
18482       IntNo = Intrinsic::wasm_relaxed_trunc_zero_signed;
18483       break;
18484     case WebAssembly::BI__builtin_wasm_relaxed_trunc_zero_u_i32x4_f64x2:
18485       IntNo = Intrinsic::wasm_relaxed_trunc_zero_unsigned;
18486       break;
18487     default:
18488       llvm_unreachable("unexpected builtin ID");
18489     }
18490     Function *Callee = CGM.getIntrinsic(IntNo);
18491     return Builder.CreateCall(Callee, {Vec});
18492   }
18493   default:
18494     return nullptr;
18495   }
18496 }
18497 
18498 static std::pair<Intrinsic::ID, unsigned>
18499 getIntrinsicForHexagonNonGCCBuiltin(unsigned BuiltinID) {
18500   struct Info {
18501     unsigned BuiltinID;
18502     Intrinsic::ID IntrinsicID;
18503     unsigned VecLen;
18504   };
18505   Info Infos[] = {
18506 #define CUSTOM_BUILTIN_MAPPING(x,s) \
18507   { Hexagon::BI__builtin_HEXAGON_##x, Intrinsic::hexagon_##x, s },
18508     CUSTOM_BUILTIN_MAPPING(L2_loadrub_pci, 0)
18509     CUSTOM_BUILTIN_MAPPING(L2_loadrb_pci, 0)
18510     CUSTOM_BUILTIN_MAPPING(L2_loadruh_pci, 0)
18511     CUSTOM_BUILTIN_MAPPING(L2_loadrh_pci, 0)
18512     CUSTOM_BUILTIN_MAPPING(L2_loadri_pci, 0)
18513     CUSTOM_BUILTIN_MAPPING(L2_loadrd_pci, 0)
18514     CUSTOM_BUILTIN_MAPPING(L2_loadrub_pcr, 0)
18515     CUSTOM_BUILTIN_MAPPING(L2_loadrb_pcr, 0)
18516     CUSTOM_BUILTIN_MAPPING(L2_loadruh_pcr, 0)
18517     CUSTOM_BUILTIN_MAPPING(L2_loadrh_pcr, 0)
18518     CUSTOM_BUILTIN_MAPPING(L2_loadri_pcr, 0)
18519     CUSTOM_BUILTIN_MAPPING(L2_loadrd_pcr, 0)
18520     CUSTOM_BUILTIN_MAPPING(S2_storerb_pci, 0)
18521     CUSTOM_BUILTIN_MAPPING(S2_storerh_pci, 0)
18522     CUSTOM_BUILTIN_MAPPING(S2_storerf_pci, 0)
18523     CUSTOM_BUILTIN_MAPPING(S2_storeri_pci, 0)
18524     CUSTOM_BUILTIN_MAPPING(S2_storerd_pci, 0)
18525     CUSTOM_BUILTIN_MAPPING(S2_storerb_pcr, 0)
18526     CUSTOM_BUILTIN_MAPPING(S2_storerh_pcr, 0)
18527     CUSTOM_BUILTIN_MAPPING(S2_storerf_pcr, 0)
18528     CUSTOM_BUILTIN_MAPPING(S2_storeri_pcr, 0)
18529     CUSTOM_BUILTIN_MAPPING(S2_storerd_pcr, 0)
18530     // Legacy builtins that take a vector in place of a vector predicate.
18531     CUSTOM_BUILTIN_MAPPING(V6_vmaskedstoreq, 64)
18532     CUSTOM_BUILTIN_MAPPING(V6_vmaskedstorenq, 64)
18533     CUSTOM_BUILTIN_MAPPING(V6_vmaskedstorentq, 64)
18534     CUSTOM_BUILTIN_MAPPING(V6_vmaskedstorentnq, 64)
18535     CUSTOM_BUILTIN_MAPPING(V6_vmaskedstoreq_128B, 128)
18536     CUSTOM_BUILTIN_MAPPING(V6_vmaskedstorenq_128B, 128)
18537     CUSTOM_BUILTIN_MAPPING(V6_vmaskedstorentq_128B, 128)
18538     CUSTOM_BUILTIN_MAPPING(V6_vmaskedstorentnq_128B, 128)
18539 #include "clang/Basic/BuiltinsHexagonMapCustomDep.def"
18540 #undef CUSTOM_BUILTIN_MAPPING
18541   };
18542 
18543   auto CmpInfo = [] (Info A, Info B) { return A.BuiltinID < B.BuiltinID; };
18544   static const bool SortOnce = (llvm::sort(Infos, CmpInfo), true);
18545   (void)SortOnce;
18546 
18547   const Info *F = std::lower_bound(std::begin(Infos), std::end(Infos),
18548                                    Info{BuiltinID, 0, 0}, CmpInfo);
18549   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
18550     return {Intrinsic::not_intrinsic, 0};
18551 
18552   return {F->IntrinsicID, F->VecLen};
18553 }
18554 
18555 Value *CodeGenFunction::EmitHexagonBuiltinExpr(unsigned BuiltinID,
18556                                                const CallExpr *E) {
18557   Intrinsic::ID ID;
18558   unsigned VecLen;
18559   std::tie(ID, VecLen) = getIntrinsicForHexagonNonGCCBuiltin(BuiltinID);
18560 
18561   auto MakeCircOp = [this, E](unsigned IntID, bool IsLoad) {
18562     // The base pointer is passed by address, so it needs to be loaded.
18563     Address A = EmitPointerWithAlignment(E->getArg(0));
18564     Address BP = Address(Builder.CreateBitCast(
18565         A.getPointer(), Int8PtrPtrTy), Int8PtrTy, A.getAlignment());
18566     llvm::Value *Base = Builder.CreateLoad(BP);
18567     // The treatment of both loads and stores is the same: the arguments for
18568     // the builtin are the same as the arguments for the intrinsic.
18569     // Load:
18570     //   builtin(Base, Inc, Mod, Start) -> intr(Base, Inc, Mod, Start)
18571     //   builtin(Base, Mod, Start)      -> intr(Base, Mod, Start)
18572     // Store:
18573     //   builtin(Base, Inc, Mod, Val, Start) -> intr(Base, Inc, Mod, Val, Start)
18574     //   builtin(Base, Mod, Val, Start)      -> intr(Base, Mod, Val, Start)
18575     SmallVector<llvm::Value*,5> Ops = { Base };
18576     for (unsigned i = 1, e = E->getNumArgs(); i != e; ++i)
18577       Ops.push_back(EmitScalarExpr(E->getArg(i)));
18578 
18579     llvm::Value *Result = Builder.CreateCall(CGM.getIntrinsic(IntID), Ops);
18580     // The load intrinsics generate two results (Value, NewBase), stores
18581     // generate one (NewBase). The new base address needs to be stored.
18582     llvm::Value *NewBase = IsLoad ? Builder.CreateExtractValue(Result, 1)
18583                                   : Result;
18584     llvm::Value *LV = Builder.CreateBitCast(
18585         EmitScalarExpr(E->getArg(0)), NewBase->getType()->getPointerTo());
18586     Address Dest = EmitPointerWithAlignment(E->getArg(0));
18587     llvm::Value *RetVal =
18588         Builder.CreateAlignedStore(NewBase, LV, Dest.getAlignment());
18589     if (IsLoad)
18590       RetVal = Builder.CreateExtractValue(Result, 0);
18591     return RetVal;
18592   };
18593 
18594   // Handle the conversion of bit-reverse load intrinsics to bit code.
18595   // The intrinsic call after this function only reads from memory and the
18596   // write to memory is dealt by the store instruction.
18597   auto MakeBrevLd = [this, E](unsigned IntID, llvm::Type *DestTy) {
18598     // The intrinsic generates one result, which is the new value for the base
18599     // pointer. It needs to be returned. The result of the load instruction is
18600     // passed to intrinsic by address, so the value needs to be stored.
18601     llvm::Value *BaseAddress =
18602         Builder.CreateBitCast(EmitScalarExpr(E->getArg(0)), Int8PtrTy);
18603 
18604     // Expressions like &(*pt++) will be incremented per evaluation.
18605     // EmitPointerWithAlignment and EmitScalarExpr evaluates the expression
18606     // per call.
18607     Address DestAddr = EmitPointerWithAlignment(E->getArg(1));
18608     DestAddr = Address(Builder.CreateBitCast(DestAddr.getPointer(), Int8PtrTy),
18609                        Int8Ty, DestAddr.getAlignment());
18610     llvm::Value *DestAddress = DestAddr.getPointer();
18611 
18612     // Operands are Base, Dest, Modifier.
18613     // The intrinsic format in LLVM IR is defined as
18614     // { ValueType, i8* } (i8*, i32).
18615     llvm::Value *Result = Builder.CreateCall(
18616         CGM.getIntrinsic(IntID), {BaseAddress, EmitScalarExpr(E->getArg(2))});
18617 
18618     // The value needs to be stored as the variable is passed by reference.
18619     llvm::Value *DestVal = Builder.CreateExtractValue(Result, 0);
18620 
18621     // The store needs to be truncated to fit the destination type.
18622     // While i32 and i64 are natively supported on Hexagon, i8 and i16 needs
18623     // to be handled with stores of respective destination type.
18624     DestVal = Builder.CreateTrunc(DestVal, DestTy);
18625 
18626     llvm::Value *DestForStore =
18627         Builder.CreateBitCast(DestAddress, DestVal->getType()->getPointerTo());
18628     Builder.CreateAlignedStore(DestVal, DestForStore, DestAddr.getAlignment());
18629     // The updated value of the base pointer is returned.
18630     return Builder.CreateExtractValue(Result, 1);
18631   };
18632 
18633   auto V2Q = [this, VecLen] (llvm::Value *Vec) {
18634     Intrinsic::ID ID = VecLen == 128 ? Intrinsic::hexagon_V6_vandvrt_128B
18635                                      : Intrinsic::hexagon_V6_vandvrt;
18636     return Builder.CreateCall(CGM.getIntrinsic(ID),
18637                               {Vec, Builder.getInt32(-1)});
18638   };
18639   auto Q2V = [this, VecLen] (llvm::Value *Pred) {
18640     Intrinsic::ID ID = VecLen == 128 ? Intrinsic::hexagon_V6_vandqrt_128B
18641                                      : Intrinsic::hexagon_V6_vandqrt;
18642     return Builder.CreateCall(CGM.getIntrinsic(ID),
18643                               {Pred, Builder.getInt32(-1)});
18644   };
18645 
18646   switch (BuiltinID) {
18647   // These intrinsics return a tuple {Vector, VectorPred} in LLVM IR,
18648   // and the corresponding C/C++ builtins use loads/stores to update
18649   // the predicate.
18650   case Hexagon::BI__builtin_HEXAGON_V6_vaddcarry:
18651   case Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B:
18652   case Hexagon::BI__builtin_HEXAGON_V6_vsubcarry:
18653   case Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B: {
18654     // Get the type from the 0-th argument.
18655     llvm::Type *VecType = ConvertType(E->getArg(0)->getType());
18656     Address PredAddr = Builder.CreateElementBitCast(
18657         EmitPointerWithAlignment(E->getArg(2)), VecType);
18658     llvm::Value *PredIn = V2Q(Builder.CreateLoad(PredAddr));
18659     llvm::Value *Result = Builder.CreateCall(CGM.getIntrinsic(ID),
18660         {EmitScalarExpr(E->getArg(0)), EmitScalarExpr(E->getArg(1)), PredIn});
18661 
18662     llvm::Value *PredOut = Builder.CreateExtractValue(Result, 1);
18663     Builder.CreateAlignedStore(Q2V(PredOut), PredAddr.getPointer(),
18664         PredAddr.getAlignment());
18665     return Builder.CreateExtractValue(Result, 0);
18666   }
18667 
18668   case Hexagon::BI__builtin_HEXAGON_V6_vmaskedstoreq:
18669   case Hexagon::BI__builtin_HEXAGON_V6_vmaskedstorenq:
18670   case Hexagon::BI__builtin_HEXAGON_V6_vmaskedstorentq:
18671   case Hexagon::BI__builtin_HEXAGON_V6_vmaskedstorentnq:
18672   case Hexagon::BI__builtin_HEXAGON_V6_vmaskedstoreq_128B:
18673   case Hexagon::BI__builtin_HEXAGON_V6_vmaskedstorenq_128B:
18674   case Hexagon::BI__builtin_HEXAGON_V6_vmaskedstorentq_128B:
18675   case Hexagon::BI__builtin_HEXAGON_V6_vmaskedstorentnq_128B: {
18676     SmallVector<llvm::Value*,4> Ops;
18677     const Expr *PredOp = E->getArg(0);
18678     // There will be an implicit cast to a boolean vector. Strip it.
18679     if (auto *Cast = dyn_cast<ImplicitCastExpr>(PredOp)) {
18680       if (Cast->getCastKind() == CK_BitCast)
18681         PredOp = Cast->getSubExpr();
18682       Ops.push_back(V2Q(EmitScalarExpr(PredOp)));
18683     }
18684     for (int i = 1, e = E->getNumArgs(); i != e; ++i)
18685       Ops.push_back(EmitScalarExpr(E->getArg(i)));
18686     return Builder.CreateCall(CGM.getIntrinsic(ID), Ops);
18687   }
18688 
18689   case Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci:
18690   case Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci:
18691   case Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci:
18692   case Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci:
18693   case Hexagon::BI__builtin_HEXAGON_L2_loadri_pci:
18694   case Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci:
18695   case Hexagon::BI__builtin_HEXAGON_L2_loadrub_pcr:
18696   case Hexagon::BI__builtin_HEXAGON_L2_loadrb_pcr:
18697   case Hexagon::BI__builtin_HEXAGON_L2_loadruh_pcr:
18698   case Hexagon::BI__builtin_HEXAGON_L2_loadrh_pcr:
18699   case Hexagon::BI__builtin_HEXAGON_L2_loadri_pcr:
18700   case Hexagon::BI__builtin_HEXAGON_L2_loadrd_pcr:
18701     return MakeCircOp(ID, /*IsLoad=*/true);
18702   case Hexagon::BI__builtin_HEXAGON_S2_storerb_pci:
18703   case Hexagon::BI__builtin_HEXAGON_S2_storerh_pci:
18704   case Hexagon::BI__builtin_HEXAGON_S2_storerf_pci:
18705   case Hexagon::BI__builtin_HEXAGON_S2_storeri_pci:
18706   case Hexagon::BI__builtin_HEXAGON_S2_storerd_pci:
18707   case Hexagon::BI__builtin_HEXAGON_S2_storerb_pcr:
18708   case Hexagon::BI__builtin_HEXAGON_S2_storerh_pcr:
18709   case Hexagon::BI__builtin_HEXAGON_S2_storerf_pcr:
18710   case Hexagon::BI__builtin_HEXAGON_S2_storeri_pcr:
18711   case Hexagon::BI__builtin_HEXAGON_S2_storerd_pcr:
18712     return MakeCircOp(ID, /*IsLoad=*/false);
18713   case Hexagon::BI__builtin_brev_ldub:
18714     return MakeBrevLd(Intrinsic::hexagon_L2_loadrub_pbr, Int8Ty);
18715   case Hexagon::BI__builtin_brev_ldb:
18716     return MakeBrevLd(Intrinsic::hexagon_L2_loadrb_pbr, Int8Ty);
18717   case Hexagon::BI__builtin_brev_lduh:
18718     return MakeBrevLd(Intrinsic::hexagon_L2_loadruh_pbr, Int16Ty);
18719   case Hexagon::BI__builtin_brev_ldh:
18720     return MakeBrevLd(Intrinsic::hexagon_L2_loadrh_pbr, Int16Ty);
18721   case Hexagon::BI__builtin_brev_ldw:
18722     return MakeBrevLd(Intrinsic::hexagon_L2_loadri_pbr, Int32Ty);
18723   case Hexagon::BI__builtin_brev_ldd:
18724     return MakeBrevLd(Intrinsic::hexagon_L2_loadrd_pbr, Int64Ty);
18725   } // switch
18726 
18727   return nullptr;
18728 }
18729 
18730 Value *CodeGenFunction::EmitRISCVBuiltinExpr(unsigned BuiltinID,
18731                                              const CallExpr *E,
18732                                              ReturnValueSlot ReturnValue) {
18733   SmallVector<Value *, 4> Ops;
18734   llvm::Type *ResultType = ConvertType(E->getType());
18735 
18736   for (unsigned i = 0, e = E->getNumArgs(); i != e; i++)
18737     Ops.push_back(EmitScalarExpr(E->getArg(i)));
18738 
18739   Intrinsic::ID ID = Intrinsic::not_intrinsic;
18740   unsigned NF = 1;
18741   constexpr unsigned TAIL_UNDISTURBED = 0;
18742 
18743   // Required for overloaded intrinsics.
18744   llvm::SmallVector<llvm::Type *, 2> IntrinsicTypes;
18745   switch (BuiltinID) {
18746   default: llvm_unreachable("unexpected builtin ID");
18747   case RISCV::BI__builtin_riscv_orc_b_32:
18748   case RISCV::BI__builtin_riscv_orc_b_64:
18749   case RISCV::BI__builtin_riscv_clmul:
18750   case RISCV::BI__builtin_riscv_clmulh:
18751   case RISCV::BI__builtin_riscv_clmulr:
18752   case RISCV::BI__builtin_riscv_bcompress_32:
18753   case RISCV::BI__builtin_riscv_bcompress_64:
18754   case RISCV::BI__builtin_riscv_bdecompress_32:
18755   case RISCV::BI__builtin_riscv_bdecompress_64:
18756   case RISCV::BI__builtin_riscv_bfp_32:
18757   case RISCV::BI__builtin_riscv_bfp_64:
18758   case RISCV::BI__builtin_riscv_grev_32:
18759   case RISCV::BI__builtin_riscv_grev_64:
18760   case RISCV::BI__builtin_riscv_gorc_32:
18761   case RISCV::BI__builtin_riscv_gorc_64:
18762   case RISCV::BI__builtin_riscv_shfl_32:
18763   case RISCV::BI__builtin_riscv_shfl_64:
18764   case RISCV::BI__builtin_riscv_unshfl_32:
18765   case RISCV::BI__builtin_riscv_unshfl_64:
18766   case RISCV::BI__builtin_riscv_xperm_n:
18767   case RISCV::BI__builtin_riscv_xperm_b:
18768   case RISCV::BI__builtin_riscv_xperm_h:
18769   case RISCV::BI__builtin_riscv_xperm_w:
18770   case RISCV::BI__builtin_riscv_crc32_b:
18771   case RISCV::BI__builtin_riscv_crc32_h:
18772   case RISCV::BI__builtin_riscv_crc32_w:
18773   case RISCV::BI__builtin_riscv_crc32_d:
18774   case RISCV::BI__builtin_riscv_crc32c_b:
18775   case RISCV::BI__builtin_riscv_crc32c_h:
18776   case RISCV::BI__builtin_riscv_crc32c_w:
18777   case RISCV::BI__builtin_riscv_crc32c_d:
18778   case RISCV::BI__builtin_riscv_fsl_32:
18779   case RISCV::BI__builtin_riscv_fsr_32:
18780   case RISCV::BI__builtin_riscv_fsl_64:
18781   case RISCV::BI__builtin_riscv_fsr_64: {
18782     switch (BuiltinID) {
18783     default: llvm_unreachable("unexpected builtin ID");
18784     // Zbb
18785     case RISCV::BI__builtin_riscv_orc_b_32:
18786     case RISCV::BI__builtin_riscv_orc_b_64:
18787       ID = Intrinsic::riscv_orc_b;
18788       break;
18789 
18790     // Zbc
18791     case RISCV::BI__builtin_riscv_clmul:
18792       ID = Intrinsic::riscv_clmul;
18793       break;
18794     case RISCV::BI__builtin_riscv_clmulh:
18795       ID = Intrinsic::riscv_clmulh;
18796       break;
18797     case RISCV::BI__builtin_riscv_clmulr:
18798       ID = Intrinsic::riscv_clmulr;
18799       break;
18800 
18801     // Zbe
18802     case RISCV::BI__builtin_riscv_bcompress_32:
18803     case RISCV::BI__builtin_riscv_bcompress_64:
18804       ID = Intrinsic::riscv_bcompress;
18805       break;
18806     case RISCV::BI__builtin_riscv_bdecompress_32:
18807     case RISCV::BI__builtin_riscv_bdecompress_64:
18808       ID = Intrinsic::riscv_bdecompress;
18809       break;
18810 
18811     // Zbf
18812     case RISCV::BI__builtin_riscv_bfp_32:
18813     case RISCV::BI__builtin_riscv_bfp_64:
18814       ID = Intrinsic::riscv_bfp;
18815       break;
18816 
18817     // Zbp
18818     case RISCV::BI__builtin_riscv_grev_32:
18819     case RISCV::BI__builtin_riscv_grev_64:
18820       ID = Intrinsic::riscv_grev;
18821       break;
18822     case RISCV::BI__builtin_riscv_gorc_32:
18823     case RISCV::BI__builtin_riscv_gorc_64:
18824       ID = Intrinsic::riscv_gorc;
18825       break;
18826     case RISCV::BI__builtin_riscv_shfl_32:
18827     case RISCV::BI__builtin_riscv_shfl_64:
18828       ID = Intrinsic::riscv_shfl;
18829       break;
18830     case RISCV::BI__builtin_riscv_unshfl_32:
18831     case RISCV::BI__builtin_riscv_unshfl_64:
18832       ID = Intrinsic::riscv_unshfl;
18833       break;
18834     case RISCV::BI__builtin_riscv_xperm_n:
18835       ID = Intrinsic::riscv_xperm_n;
18836       break;
18837     case RISCV::BI__builtin_riscv_xperm_b:
18838       ID = Intrinsic::riscv_xperm_b;
18839       break;
18840     case RISCV::BI__builtin_riscv_xperm_h:
18841       ID = Intrinsic::riscv_xperm_h;
18842       break;
18843     case RISCV::BI__builtin_riscv_xperm_w:
18844       ID = Intrinsic::riscv_xperm_w;
18845       break;
18846 
18847     // Zbr
18848     case RISCV::BI__builtin_riscv_crc32_b:
18849       ID = Intrinsic::riscv_crc32_b;
18850       break;
18851     case RISCV::BI__builtin_riscv_crc32_h:
18852       ID = Intrinsic::riscv_crc32_h;
18853       break;
18854     case RISCV::BI__builtin_riscv_crc32_w:
18855       ID = Intrinsic::riscv_crc32_w;
18856       break;
18857     case RISCV::BI__builtin_riscv_crc32_d:
18858       ID = Intrinsic::riscv_crc32_d;
18859       break;
18860     case RISCV::BI__builtin_riscv_crc32c_b:
18861       ID = Intrinsic::riscv_crc32c_b;
18862       break;
18863     case RISCV::BI__builtin_riscv_crc32c_h:
18864       ID = Intrinsic::riscv_crc32c_h;
18865       break;
18866     case RISCV::BI__builtin_riscv_crc32c_w:
18867       ID = Intrinsic::riscv_crc32c_w;
18868       break;
18869     case RISCV::BI__builtin_riscv_crc32c_d:
18870       ID = Intrinsic::riscv_crc32c_d;
18871       break;
18872 
18873     // Zbt
18874     case RISCV::BI__builtin_riscv_fsl_32:
18875     case RISCV::BI__builtin_riscv_fsl_64:
18876       ID = Intrinsic::riscv_fsl;
18877       break;
18878     case RISCV::BI__builtin_riscv_fsr_32:
18879     case RISCV::BI__builtin_riscv_fsr_64:
18880       ID = Intrinsic::riscv_fsr;
18881       break;
18882     }
18883 
18884     IntrinsicTypes = {ResultType};
18885     break;
18886   }
18887   // Vector builtins are handled from here.
18888 #include "clang/Basic/riscv_vector_builtin_cg.inc"
18889   }
18890 
18891   assert(ID != Intrinsic::not_intrinsic);
18892 
18893   llvm::Function *F = CGM.getIntrinsic(ID, IntrinsicTypes);
18894   return Builder.CreateCall(F, Ops, "");
18895 }
18896