clang  8.0.0svn
CGBuiltin.cpp
Go to the documentation of this file.
1 //===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This contains code to emit Builtin calls as LLVM code.
11 //
12 //===----------------------------------------------------------------------===//
13 
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 "TargetInfo.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/Decl.h"
24 #include "clang/AST/OSLog.h"
26 #include "clang/Basic/TargetInfo.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/IR/CallSite.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/InlineAsm.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/IR/MDBuilder.h"
34 #include "llvm/Support/ConvertUTF.h"
35 #include "llvm/Support/ScopedPrinter.h"
36 #include "llvm/Support/TargetParser.h"
37 #include <sstream>
38 
39 using namespace clang;
40 using namespace CodeGen;
41 using namespace llvm;
42 
43 static
44 int64_t clamp(int64_t Value, int64_t Low, int64_t High) {
45  return std::min(High, std::max(Low, Value));
46 }
47 
48 /// getBuiltinLibFunction - Given a builtin id for a function like
49 /// "__builtin_fabsf", return a Function* for "fabsf".
51  unsigned BuiltinID) {
52  assert(Context.BuiltinInfo.isLibFunction(BuiltinID));
53 
54  // Get the name, skip over the __builtin_ prefix (if necessary).
55  StringRef Name;
56  GlobalDecl D(FD);
57 
58  // If the builtin has been declared explicitly with an assembler label,
59  // use the mangled name. This differs from the plain label on platforms
60  // that prefix labels.
61  if (FD->hasAttr<AsmLabelAttr>())
62  Name = getMangledName(D);
63  else
64  Name = Context.BuiltinInfo.getName(BuiltinID) + 10;
65 
66  llvm::FunctionType *Ty =
67  cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
68 
69  return GetOrCreateLLVMFunction(Name, Ty, D, /*ForVTable=*/false);
70 }
71 
72 /// Emit the conversions required to turn the given value into an
73 /// integer of the given size.
75  QualType T, llvm::IntegerType *IntType) {
76  V = CGF.EmitToMemory(V, T);
77 
78  if (V->getType()->isPointerTy())
79  return CGF.Builder.CreatePtrToInt(V, IntType);
80 
81  assert(V->getType() == IntType);
82  return V;
83 }
84 
86  QualType T, llvm::Type *ResultType) {
87  V = CGF.EmitFromMemory(V, T);
88 
89  if (ResultType->isPointerTy())
90  return CGF.Builder.CreateIntToPtr(V, ResultType);
91 
92  assert(V->getType() == ResultType);
93  return V;
94 }
95 
96 /// Utility to insert an atomic instruction based on Instrinsic::ID
97 /// and the expression node.
99  CodeGenFunction &CGF, llvm::AtomicRMWInst::BinOp Kind, const CallExpr *E,
100  AtomicOrdering Ordering = AtomicOrdering::SequentiallyConsistent) {
101  QualType T = E->getType();
102  assert(E->getArg(0)->getType()->isPointerType());
103  assert(CGF.getContext().hasSameUnqualifiedType(T,
104  E->getArg(0)->getType()->getPointeeType()));
105  assert(CGF.getContext().hasSameUnqualifiedType(T, E->getArg(1)->getType()));
106 
107  llvm::Value *DestPtr = CGF.EmitScalarExpr(E->getArg(0));
108  unsigned AddrSpace = DestPtr->getType()->getPointerAddressSpace();
109 
110  llvm::IntegerType *IntType =
111  llvm::IntegerType::get(CGF.getLLVMContext(),
112  CGF.getContext().getTypeSize(T));
113  llvm::Type *IntPtrType = IntType->getPointerTo(AddrSpace);
114 
115  llvm::Value *Args[2];
116  Args[0] = CGF.Builder.CreateBitCast(DestPtr, IntPtrType);
117  Args[1] = CGF.EmitScalarExpr(E->getArg(1));
118  llvm::Type *ValueType = Args[1]->getType();
119  Args[1] = EmitToInt(CGF, Args[1], T, IntType);
120 
121  llvm::Value *Result = CGF.Builder.CreateAtomicRMW(
122  Kind, Args[0], Args[1], Ordering);
123  return EmitFromInt(CGF, Result, T, ValueType);
124 }
125 
127  Value *Val = CGF.EmitScalarExpr(E->getArg(0));
128  Value *Address = CGF.EmitScalarExpr(E->getArg(1));
129 
130  // Convert the type of the pointer to a pointer to the stored type.
131  Val = CGF.EmitToMemory(Val, E->getArg(0)->getType());
132  Value *BC = CGF.Builder.CreateBitCast(
133  Address, llvm::PointerType::getUnqual(Val->getType()), "cast");
134  LValue LV = CGF.MakeNaturalAlignAddrLValue(BC, E->getArg(0)->getType());
135  LV.setNontemporal(true);
136  CGF.EmitStoreOfScalar(Val, LV, false);
137  return nullptr;
138 }
139 
141  Value *Address = CGF.EmitScalarExpr(E->getArg(0));
142 
143  LValue LV = CGF.MakeNaturalAlignAddrLValue(Address, E->getType());
144  LV.setNontemporal(true);
145  return CGF.EmitLoadOfScalar(LV, E->getExprLoc());
146 }
147 
149  llvm::AtomicRMWInst::BinOp Kind,
150  const CallExpr *E) {
151  return RValue::get(MakeBinaryAtomicValue(CGF, Kind, E));
152 }
153 
154 /// Utility to insert an atomic instruction based Instrinsic::ID and
155 /// the expression node, where the return value is the result of the
156 /// operation.
158  llvm::AtomicRMWInst::BinOp Kind,
159  const CallExpr *E,
160  Instruction::BinaryOps Op,
161  bool Invert = false) {
162  QualType T = E->getType();
163  assert(E->getArg(0)->getType()->isPointerType());
164  assert(CGF.getContext().hasSameUnqualifiedType(T,
165  E->getArg(0)->getType()->getPointeeType()));
166  assert(CGF.getContext().hasSameUnqualifiedType(T, E->getArg(1)->getType()));
167 
168  llvm::Value *DestPtr = CGF.EmitScalarExpr(E->getArg(0));
169  unsigned AddrSpace = DestPtr->getType()->getPointerAddressSpace();
170 
171  llvm::IntegerType *IntType =
172  llvm::IntegerType::get(CGF.getLLVMContext(),
173  CGF.getContext().getTypeSize(T));
174  llvm::Type *IntPtrType = IntType->getPointerTo(AddrSpace);
175 
176  llvm::Value *Args[2];
177  Args[1] = CGF.EmitScalarExpr(E->getArg(1));
178  llvm::Type *ValueType = Args[1]->getType();
179  Args[1] = EmitToInt(CGF, Args[1], T, IntType);
180  Args[0] = CGF.Builder.CreateBitCast(DestPtr, IntPtrType);
181 
182  llvm::Value *Result = CGF.Builder.CreateAtomicRMW(
183  Kind, Args[0], Args[1], llvm::AtomicOrdering::SequentiallyConsistent);
184  Result = CGF.Builder.CreateBinOp(Op, Result, Args[1]);
185  if (Invert)
186  Result = CGF.Builder.CreateBinOp(llvm::Instruction::Xor, Result,
187  llvm::ConstantInt::get(IntType, -1));
188  Result = EmitFromInt(CGF, Result, T, ValueType);
189  return RValue::get(Result);
190 }
191 
192 /// Utility to insert an atomic cmpxchg instruction.
193 ///
194 /// @param CGF The current codegen function.
195 /// @param E Builtin call expression to convert to cmpxchg.
196 /// arg0 - address to operate on
197 /// arg1 - value to compare with
198 /// arg2 - new value
199 /// @param ReturnBool Specifies whether to return success flag of
200 /// cmpxchg result or the old value.
201 ///
202 /// @returns result of cmpxchg, according to ReturnBool
203 ///
204 /// Note: In order to lower Microsoft's _InterlockedCompareExchange* intrinsics
205 /// invoke the function EmitAtomicCmpXchgForMSIntrin.
207  bool ReturnBool) {
208  QualType T = ReturnBool ? E->getArg(1)->getType() : E->getType();
209  llvm::Value *DestPtr = CGF.EmitScalarExpr(E->getArg(0));
210  unsigned AddrSpace = DestPtr->getType()->getPointerAddressSpace();
211 
212  llvm::IntegerType *IntType = llvm::IntegerType::get(
213  CGF.getLLVMContext(), CGF.getContext().getTypeSize(T));
214  llvm::Type *IntPtrType = IntType->getPointerTo(AddrSpace);
215 
216  Value *Args[3];
217  Args[0] = CGF.Builder.CreateBitCast(DestPtr, IntPtrType);
218  Args[1] = CGF.EmitScalarExpr(E->getArg(1));
219  llvm::Type *ValueType = Args[1]->getType();
220  Args[1] = EmitToInt(CGF, Args[1], T, IntType);
221  Args[2] = EmitToInt(CGF, CGF.EmitScalarExpr(E->getArg(2)), T, IntType);
222 
223  Value *Pair = CGF.Builder.CreateAtomicCmpXchg(
224  Args[0], Args[1], Args[2], llvm::AtomicOrdering::SequentiallyConsistent,
225  llvm::AtomicOrdering::SequentiallyConsistent);
226  if (ReturnBool)
227  // Extract boolean success flag and zext it to int.
228  return CGF.Builder.CreateZExt(CGF.Builder.CreateExtractValue(Pair, 1),
229  CGF.ConvertType(E->getType()));
230  else
231  // Extract old value and emit it using the same type as compare value.
232  return EmitFromInt(CGF, CGF.Builder.CreateExtractValue(Pair, 0), T,
233  ValueType);
234 }
235 
236 /// This function should be invoked to emit atomic cmpxchg for Microsoft's
237 /// _InterlockedCompareExchange* intrinsics which have the following signature:
238 /// T _InterlockedCompareExchange(T volatile *Destination,
239 /// T Exchange,
240 /// T Comparand);
241 ///
242 /// Whereas the llvm 'cmpxchg' instruction has the following syntax:
243 /// cmpxchg *Destination, Comparand, Exchange.
244 /// So we need to swap Comparand and Exchange when invoking
245 /// CreateAtomicCmpXchg. That is the reason we could not use the above utility
246 /// function MakeAtomicCmpXchgValue since it expects the arguments to be
247 /// already swapped.
248 
249 static
251  AtomicOrdering SuccessOrdering = AtomicOrdering::SequentiallyConsistent) {
252  assert(E->getArg(0)->getType()->isPointerType());
253  assert(CGF.getContext().hasSameUnqualifiedType(
254  E->getType(), E->getArg(0)->getType()->getPointeeType()));
255  assert(CGF.getContext().hasSameUnqualifiedType(E->getType(),
256  E->getArg(1)->getType()));
257  assert(CGF.getContext().hasSameUnqualifiedType(E->getType(),
258  E->getArg(2)->getType()));
259 
260  auto *Destination = CGF.EmitScalarExpr(E->getArg(0));
261  auto *Comparand = CGF.EmitScalarExpr(E->getArg(2));
262  auto *Exchange = CGF.EmitScalarExpr(E->getArg(1));
263 
264  // For Release ordering, the failure ordering should be Monotonic.
265  auto FailureOrdering = SuccessOrdering == AtomicOrdering::Release ?
266  AtomicOrdering::Monotonic :
267  SuccessOrdering;
268 
269  auto *Result = CGF.Builder.CreateAtomicCmpXchg(
270  Destination, Comparand, Exchange,
271  SuccessOrdering, FailureOrdering);
272  Result->setVolatile(true);
273  return CGF.Builder.CreateExtractValue(Result, 0);
274 }
275 
277  AtomicOrdering Ordering = AtomicOrdering::SequentiallyConsistent) {
278  assert(E->getArg(0)->getType()->isPointerType());
279 
280  auto *IntTy = CGF.ConvertType(E->getType());
281  auto *Result = CGF.Builder.CreateAtomicRMW(
282  AtomicRMWInst::Add,
283  CGF.EmitScalarExpr(E->getArg(0)),
284  ConstantInt::get(IntTy, 1),
285  Ordering);
286  return CGF.Builder.CreateAdd(Result, ConstantInt::get(IntTy, 1));
287 }
288 
290  AtomicOrdering Ordering = AtomicOrdering::SequentiallyConsistent) {
291  assert(E->getArg(0)->getType()->isPointerType());
292 
293  auto *IntTy = CGF.ConvertType(E->getType());
294  auto *Result = CGF.Builder.CreateAtomicRMW(
295  AtomicRMWInst::Sub,
296  CGF.EmitScalarExpr(E->getArg(0)),
297  ConstantInt::get(IntTy, 1),
298  Ordering);
299  return CGF.Builder.CreateSub(Result, ConstantInt::get(IntTy, 1));
300 }
301 
302 // Emit a simple mangled intrinsic that has 1 argument and a return type
303 // matching the argument type.
305  const CallExpr *E,
306  unsigned IntrinsicID) {
307  llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
308 
309  Value *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
310  return CGF.Builder.CreateCall(F, Src0);
311 }
312 
313 // Emit an intrinsic that has 2 operands of the same type as its result.
315  const CallExpr *E,
316  unsigned IntrinsicID) {
317  llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
318  llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1));
319 
320  Value *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
321  return CGF.Builder.CreateCall(F, { Src0, Src1 });
322 }
323 
324 // Emit an intrinsic that has 3 operands of the same type as its result.
326  const CallExpr *E,
327  unsigned IntrinsicID) {
328  llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
329  llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1));
330  llvm::Value *Src2 = CGF.EmitScalarExpr(E->getArg(2));
331 
332  Value *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
333  return CGF.Builder.CreateCall(F, { Src0, Src1, Src2 });
334 }
335 
336 // Emit an intrinsic that has 1 float or double operand, and 1 integer.
338  const CallExpr *E,
339  unsigned IntrinsicID) {
340  llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
341  llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1));
342 
343  Value *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
344  return CGF.Builder.CreateCall(F, {Src0, Src1});
345 }
346 
347 /// EmitFAbs - Emit a call to @llvm.fabs().
348 static Value *EmitFAbs(CodeGenFunction &CGF, Value *V) {
349  Value *F = CGF.CGM.getIntrinsic(Intrinsic::fabs, V->getType());
350  llvm::CallInst *Call = CGF.Builder.CreateCall(F, V);
351  Call->setDoesNotAccessMemory();
352  return Call;
353 }
354 
355 /// Emit the computation of the sign bit for a floating point value. Returns
356 /// the i1 sign bit value.
358  LLVMContext &C = CGF.CGM.getLLVMContext();
359 
360  llvm::Type *Ty = V->getType();
361  int Width = Ty->getPrimitiveSizeInBits();
362  llvm::Type *IntTy = llvm::IntegerType::get(C, Width);
363  V = CGF.Builder.CreateBitCast(V, IntTy);
364  if (Ty->isPPC_FP128Ty()) {
365  // We want the sign bit of the higher-order double. The bitcast we just
366  // did works as if the double-double was stored to memory and then
367  // read as an i128. The "store" will put the higher-order double in the
368  // lower address in both little- and big-Endian modes, but the "load"
369  // will treat those bits as a different part of the i128: the low bits in
370  // little-Endian, the high bits in big-Endian. Therefore, on big-Endian
371  // we need to shift the high bits down to the low before truncating.
372  Width >>= 1;
373  if (CGF.getTarget().isBigEndian()) {
374  Value *ShiftCst = llvm::ConstantInt::get(IntTy, Width);
375  V = CGF.Builder.CreateLShr(V, ShiftCst);
376  }
377  // We are truncating value in order to extract the higher-order
378  // double, which we will be using to extract the sign from.
379  IntTy = llvm::IntegerType::get(C, Width);
380  V = CGF.Builder.CreateTrunc(V, IntTy);
381  }
382  Value *Zero = llvm::Constant::getNullValue(IntTy);
383  return CGF.Builder.CreateICmpSLT(V, Zero);
384 }
385 
387  const CallExpr *E, llvm::Constant *calleeValue) {
388  CGCallee callee = CGCallee::forDirect(calleeValue, GlobalDecl(FD));
389  return CGF.EmitCall(E->getCallee()->getType(), callee, E, ReturnValueSlot());
390 }
391 
392 /// Emit a call to llvm.{sadd,uadd,ssub,usub,smul,umul}.with.overflow.*
393 /// depending on IntrinsicID.
394 ///
395 /// \arg CGF The current codegen function.
396 /// \arg IntrinsicID The ID for the Intrinsic we wish to generate.
397 /// \arg X The first argument to the llvm.*.with.overflow.*.
398 /// \arg Y The second argument to the llvm.*.with.overflow.*.
399 /// \arg Carry The carry returned by the llvm.*.with.overflow.*.
400 /// \returns The result (i.e. sum/product) returned by the intrinsic.
402  const llvm::Intrinsic::ID IntrinsicID,
404  llvm::Value *&Carry) {
405  // Make sure we have integers of the same width.
406  assert(X->getType() == Y->getType() &&
407  "Arguments must be the same type. (Did you forget to make sure both "
408  "arguments have the same integer width?)");
409 
410  llvm::Value *Callee = CGF.CGM.getIntrinsic(IntrinsicID, X->getType());
411  llvm::Value *Tmp = CGF.Builder.CreateCall(Callee, {X, Y});
412  Carry = CGF.Builder.CreateExtractValue(Tmp, 1);
413  return CGF.Builder.CreateExtractValue(Tmp, 0);
414 }
415 
417  unsigned IntrinsicID,
418  int low, int high) {
419  llvm::MDBuilder MDHelper(CGF.getLLVMContext());
420  llvm::MDNode *RNode = MDHelper.createRange(APInt(32, low), APInt(32, high));
421  Value *F = CGF.CGM.getIntrinsic(IntrinsicID, {});
422  llvm::Instruction *Call = CGF.Builder.CreateCall(F);
423  Call->setMetadata(llvm::LLVMContext::MD_range, RNode);
424  return Call;
425 }
426 
427 namespace {
428  struct WidthAndSignedness {
429  unsigned Width;
430  bool Signed;
431  };
432 }
433 
434 static WidthAndSignedness
436  const clang::QualType Type) {
437  assert(Type->isIntegerType() && "Given type is not an integer.");
438  unsigned Width = Type->isBooleanType() ? 1 : context.getTypeInfo(Type).Width;
439  bool Signed = Type->isSignedIntegerType();
440  return {Width, Signed};
441 }
442 
443 // Given one or more integer types, this function produces an integer type that
444 // encompasses them: any value in one of the given types could be expressed in
445 // the encompassing type.
446 static struct WidthAndSignedness
447 EncompassingIntegerType(ArrayRef<struct WidthAndSignedness> Types) {
448  assert(Types.size() > 0 && "Empty list of types.");
449 
450  // If any of the given types is signed, we must return a signed type.
451  bool Signed = false;
452  for (const auto &Type : Types) {
453  Signed |= Type.Signed;
454  }
455 
456  // The encompassing type must have a width greater than or equal to the width
457  // of the specified types. Additionally, if the encompassing type is signed,
458  // its width must be strictly greater than the width of any unsigned types
459  // given.
460  unsigned Width = 0;
461  for (const auto &Type : Types) {
462  unsigned MinWidth = Type.Width + (Signed && !Type.Signed);
463  if (Width < MinWidth) {
464  Width = MinWidth;
465  }
466  }
467 
468  return {Width, Signed};
469 }
470 
471 Value *CodeGenFunction::EmitVAStartEnd(Value *ArgValue, bool IsStart) {
472  llvm::Type *DestType = Int8PtrTy;
473  if (ArgValue->getType() != DestType)
474  ArgValue =
475  Builder.CreateBitCast(ArgValue, DestType, ArgValue->getName().data());
476 
477  Intrinsic::ID inst = IsStart ? Intrinsic::vastart : Intrinsic::vaend;
478  return Builder.CreateCall(CGM.getIntrinsic(inst), ArgValue);
479 }
480 
481 /// Checks if using the result of __builtin_object_size(p, @p From) in place of
482 /// __builtin_object_size(p, @p To) is correct
483 static bool areBOSTypesCompatible(int From, int To) {
484  // Note: Our __builtin_object_size implementation currently treats Type=0 and
485  // Type=2 identically. Encoding this implementation detail here may make
486  // improving __builtin_object_size difficult in the future, so it's omitted.
487  return From == To || (From == 0 && To == 1) || (From == 3 && To == 2);
488 }
489 
490 static llvm::Value *
491 getDefaultBuiltinObjectSizeResult(unsigned Type, llvm::IntegerType *ResType) {
492  return ConstantInt::get(ResType, (Type & 2) ? 0 : -1, /*isSigned=*/true);
493 }
494 
495 llvm::Value *
496 CodeGenFunction::evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type,
497  llvm::IntegerType *ResType,
498  llvm::Value *EmittedE) {
499  uint64_t ObjectSize;
500  if (!E->tryEvaluateObjectSize(ObjectSize, getContext(), Type))
501  return emitBuiltinObjectSize(E, Type, ResType, EmittedE);
502  return ConstantInt::get(ResType, ObjectSize, /*isSigned=*/true);
503 }
504 
505 /// Returns a Value corresponding to the size of the given expression.
506 /// This Value may be either of the following:
507 /// - A llvm::Argument (if E is a param with the pass_object_size attribute on
508 /// it)
509 /// - A call to the @llvm.objectsize intrinsic
510 ///
511 /// EmittedE is the result of emitting `E` as a scalar expr. If it's non-null
512 /// and we wouldn't otherwise try to reference a pass_object_size parameter,
513 /// we'll call @llvm.objectsize on EmittedE, rather than emitting E.
514 llvm::Value *
515 CodeGenFunction::emitBuiltinObjectSize(const Expr *E, unsigned Type,
516  llvm::IntegerType *ResType,
517  llvm::Value *EmittedE) {
518  // We need to reference an argument if the pointer is a parameter with the
519  // pass_object_size attribute.
520  if (auto *D = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) {
521  auto *Param = dyn_cast<ParmVarDecl>(D->getDecl());
522  auto *PS = D->getDecl()->getAttr<PassObjectSizeAttr>();
523  if (Param != nullptr && PS != nullptr &&
524  areBOSTypesCompatible(PS->getType(), Type)) {
525  auto Iter = SizeArguments.find(Param);
526  assert(Iter != SizeArguments.end());
527 
528  const ImplicitParamDecl *D = Iter->second;
529  auto DIter = LocalDeclMap.find(D);
530  assert(DIter != LocalDeclMap.end());
531 
532  return EmitLoadOfScalar(DIter->second, /*volatile=*/false,
533  getContext().getSizeType(), E->getBeginLoc());
534  }
535  }
536 
537  // LLVM can't handle Type=3 appropriately, and __builtin_object_size shouldn't
538  // evaluate E for side-effects. In either case, we shouldn't lower to
539  // @llvm.objectsize.
540  if (Type == 3 || (!EmittedE && E->HasSideEffects(getContext())))
541  return getDefaultBuiltinObjectSizeResult(Type, ResType);
542 
543  Value *Ptr = EmittedE ? EmittedE : EmitScalarExpr(E);
544  assert(Ptr->getType()->isPointerTy() &&
545  "Non-pointer passed to __builtin_object_size?");
546 
547  Value *F = CGM.getIntrinsic(Intrinsic::objectsize, {ResType, Ptr->getType()});
548 
549  // LLVM only supports 0 and 2, make sure that we pass along that as a boolean.
550  Value *Min = Builder.getInt1((Type & 2) != 0);
551  // For GCC compatibility, __builtin_object_size treat NULL as unknown size.
552  Value *NullIsUnknown = Builder.getTrue();
553  return Builder.CreateCall(F, {Ptr, Min, NullIsUnknown});
554 }
555 
556 namespace {
557 /// A struct to generically desribe a bit test intrinsic.
558 struct BitTest {
559  enum ActionKind : uint8_t { TestOnly, Complement, Reset, Set };
560  enum InterlockingKind : uint8_t {
561  Unlocked,
562  Sequential,
563  Acquire,
564  Release,
565  NoFence
566  };
567 
568  ActionKind Action;
569  InterlockingKind Interlocking;
570  bool Is64Bit;
571 
572  static BitTest decodeBitTestBuiltin(unsigned BuiltinID);
573 };
574 } // namespace
575 
576 BitTest BitTest::decodeBitTestBuiltin(unsigned BuiltinID) {
577  switch (BuiltinID) {
578  // Main portable variants.
579  case Builtin::BI_bittest:
580  return {TestOnly, Unlocked, false};
581  case Builtin::BI_bittestandcomplement:
582  return {Complement, Unlocked, false};
583  case Builtin::BI_bittestandreset:
584  return {Reset, Unlocked, false};
585  case Builtin::BI_bittestandset:
586  return {Set, Unlocked, false};
587  case Builtin::BI_interlockedbittestandreset:
588  return {Reset, Sequential, false};
589  case Builtin::BI_interlockedbittestandset:
590  return {Set, Sequential, false};
591 
592  // X86-specific 64-bit variants.
593  case Builtin::BI_bittest64:
594  return {TestOnly, Unlocked, true};
595  case Builtin::BI_bittestandcomplement64:
596  return {Complement, Unlocked, true};
597  case Builtin::BI_bittestandreset64:
598  return {Reset, Unlocked, true};
599  case Builtin::BI_bittestandset64:
600  return {Set, Unlocked, true};
601  case Builtin::BI_interlockedbittestandreset64:
602  return {Reset, Sequential, true};
603  case Builtin::BI_interlockedbittestandset64:
604  return {Set, Sequential, true};
605 
606  // ARM/AArch64-specific ordering variants.
607  case Builtin::BI_interlockedbittestandset_acq:
608  return {Set, Acquire, false};
609  case Builtin::BI_interlockedbittestandset_rel:
610  return {Set, Release, false};
611  case Builtin::BI_interlockedbittestandset_nf:
612  return {Set, NoFence, false};
613  case Builtin::BI_interlockedbittestandreset_acq:
614  return {Reset, Acquire, false};
615  case Builtin::BI_interlockedbittestandreset_rel:
616  return {Reset, Release, false};
617  case Builtin::BI_interlockedbittestandreset_nf:
618  return {Reset, NoFence, false};
619  }
620  llvm_unreachable("expected only bittest intrinsics");
621 }
622 
623 static char bitActionToX86BTCode(BitTest::ActionKind A) {
624  switch (A) {
625  case BitTest::TestOnly: return '\0';
626  case BitTest::Complement: return 'c';
627  case BitTest::Reset: return 'r';
628  case BitTest::Set: return 's';
629  }
630  llvm_unreachable("invalid action");
631 }
632 
634  BitTest BT,
635  const CallExpr *E, Value *BitBase,
636  Value *BitPos) {
637  char Action = bitActionToX86BTCode(BT.Action);
638  char SizeSuffix = BT.Is64Bit ? 'q' : 'l';
639 
640  // Build the assembly.
641  SmallString<64> Asm;
642  raw_svector_ostream AsmOS(Asm);
643  if (BT.Interlocking != BitTest::Unlocked)
644  AsmOS << "lock ";
645  AsmOS << "bt";
646  if (Action)
647  AsmOS << Action;
648  AsmOS << SizeSuffix << " $2, ($1)\n\tsetc ${0:b}";
649 
650  // Build the constraints. FIXME: We should support immediates when possible.
651  std::string Constraints = "=r,r,r,~{cc},~{flags},~{fpsr}";
652  llvm::IntegerType *IntType = llvm::IntegerType::get(
653  CGF.getLLVMContext(),
654  CGF.getContext().getTypeSize(E->getArg(1)->getType()));
655  llvm::Type *IntPtrType = IntType->getPointerTo();
656  llvm::FunctionType *FTy =
657  llvm::FunctionType::get(CGF.Int8Ty, {IntPtrType, IntType}, false);
658 
659  llvm::InlineAsm *IA =
660  llvm::InlineAsm::get(FTy, Asm, Constraints, /*SideEffects=*/true);
661  return CGF.Builder.CreateCall(IA, {BitBase, BitPos});
662 }
663 
664 static llvm::AtomicOrdering
665 getBitTestAtomicOrdering(BitTest::InterlockingKind I) {
666  switch (I) {
667  case BitTest::Unlocked: return llvm::AtomicOrdering::NotAtomic;
668  case BitTest::Sequential: return llvm::AtomicOrdering::SequentiallyConsistent;
669  case BitTest::Acquire: return llvm::AtomicOrdering::Acquire;
670  case BitTest::Release: return llvm::AtomicOrdering::Release;
671  case BitTest::NoFence: return llvm::AtomicOrdering::Monotonic;
672  }
673  llvm_unreachable("invalid interlocking");
674 }
675 
676 /// Emit a _bittest* intrinsic. These intrinsics take a pointer to an array of
677 /// bits and a bit position and read and optionally modify the bit at that
678 /// position. The position index can be arbitrarily large, i.e. it can be larger
679 /// than 31 or 63, so we need an indexed load in the general case.
681  unsigned BuiltinID,
682  const CallExpr *E) {
683  Value *BitBase = CGF.EmitScalarExpr(E->getArg(0));
684  Value *BitPos = CGF.EmitScalarExpr(E->getArg(1));
685 
686  BitTest BT = BitTest::decodeBitTestBuiltin(BuiltinID);
687 
688  // X86 has special BT, BTC, BTR, and BTS instructions that handle the array
689  // indexing operation internally. Use them if possible.
690  llvm::Triple::ArchType Arch = CGF.getTarget().getTriple().getArch();
691  if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64)
692  return EmitX86BitTestIntrinsic(CGF, BT, E, BitBase, BitPos);
693 
694  // Otherwise, use generic code to load one byte and test the bit. Use all but
695  // the bottom three bits as the array index, and the bottom three bits to form
696  // a mask.
697  // Bit = BitBaseI8[BitPos >> 3] & (1 << (BitPos & 0x7)) != 0;
698  Value *ByteIndex = CGF.Builder.CreateAShr(
699  BitPos, llvm::ConstantInt::get(BitPos->getType(), 3), "bittest.byteidx");
700  Value *BitBaseI8 = CGF.Builder.CreatePointerCast(BitBase, CGF.Int8PtrTy);
701  Address ByteAddr(CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, BitBaseI8,
702  ByteIndex, "bittest.byteaddr"),
703  CharUnits::One());
704  Value *PosLow =
705  CGF.Builder.CreateAnd(CGF.Builder.CreateTrunc(BitPos, CGF.Int8Ty),
706  llvm::ConstantInt::get(CGF.Int8Ty, 0x7));
707 
708  // The updating instructions will need a mask.
709  Value *Mask = nullptr;
710  if (BT.Action != BitTest::TestOnly) {
711  Mask = CGF.Builder.CreateShl(llvm::ConstantInt::get(CGF.Int8Ty, 1), PosLow,
712  "bittest.mask");
713  }
714 
715  // Check the action and ordering of the interlocked intrinsics.
716  llvm::AtomicOrdering Ordering = getBitTestAtomicOrdering(BT.Interlocking);
717 
718  Value *OldByte = nullptr;
719  if (Ordering != llvm::AtomicOrdering::NotAtomic) {
720  // Emit a combined atomicrmw load/store operation for the interlocked
721  // intrinsics.
722  llvm::AtomicRMWInst::BinOp RMWOp = llvm::AtomicRMWInst::Or;
723  if (BT.Action == BitTest::Reset) {
724  Mask = CGF.Builder.CreateNot(Mask);
725  RMWOp = llvm::AtomicRMWInst::And;
726  }
727  OldByte = CGF.Builder.CreateAtomicRMW(RMWOp, ByteAddr.getPointer(), Mask,
728  Ordering);
729  } else {
730  // Emit a plain load for the non-interlocked intrinsics.
731  OldByte = CGF.Builder.CreateLoad(ByteAddr, "bittest.byte");
732  Value *NewByte = nullptr;
733  switch (BT.Action) {
734  case BitTest::TestOnly:
735  // Don't store anything.
736  break;
737  case BitTest::Complement:
738  NewByte = CGF.Builder.CreateXor(OldByte, Mask);
739  break;
740  case BitTest::Reset:
741  NewByte = CGF.Builder.CreateAnd(OldByte, CGF.Builder.CreateNot(Mask));
742  break;
743  case BitTest::Set:
744  NewByte = CGF.Builder.CreateOr(OldByte, Mask);
745  break;
746  }
747  if (NewByte)
748  CGF.Builder.CreateStore(NewByte, ByteAddr);
749  }
750 
751  // However we loaded the old byte, either by plain load or atomicrmw, shift
752  // the bit into the low position and mask it to 0 or 1.
753  Value *ShiftedByte = CGF.Builder.CreateLShr(OldByte, PosLow, "bittest.shr");
754  return CGF.Builder.CreateAnd(
755  ShiftedByte, llvm::ConstantInt::get(CGF.Int8Ty, 1), "bittest.res");
756 }
757 
758 namespace {
759 enum class MSVCSetJmpKind {
760  _setjmpex,
761  _setjmp3,
762  _setjmp
763 };
764 }
765 
766 /// MSVC handles setjmp a bit differently on different platforms. On every
767 /// architecture except 32-bit x86, the frame address is passed. On x86, extra
768 /// parameters can be passed as variadic arguments, but we always pass none.
770  const CallExpr *E) {
771  llvm::Value *Arg1 = nullptr;
772  llvm::Type *Arg1Ty = nullptr;
773  StringRef Name;
774  bool IsVarArg = false;
775  if (SJKind == MSVCSetJmpKind::_setjmp3) {
776  Name = "_setjmp3";
777  Arg1Ty = CGF.Int32Ty;
778  Arg1 = llvm::ConstantInt::get(CGF.IntTy, 0);
779  IsVarArg = true;
780  } else {
781  Name = SJKind == MSVCSetJmpKind::_setjmp ? "_setjmp" : "_setjmpex";
782  Arg1Ty = CGF.Int8PtrTy;
783  if (CGF.getTarget().getTriple().getArch() == llvm::Triple::aarch64) {
784  Arg1 = CGF.Builder.CreateCall(CGF.CGM.getIntrinsic(Intrinsic::sponentry));
785  } else
786  Arg1 = CGF.Builder.CreateCall(CGF.CGM.getIntrinsic(Intrinsic::frameaddress),
787  llvm::ConstantInt::get(CGF.Int32Ty, 0));
788  }
789 
790  // Mark the call site and declaration with ReturnsTwice.
791  llvm::Type *ArgTypes[2] = {CGF.Int8PtrTy, Arg1Ty};
792  llvm::AttributeList ReturnsTwiceAttr = llvm::AttributeList::get(
793  CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex,
794  llvm::Attribute::ReturnsTwice);
795  llvm::Constant *SetJmpFn = CGF.CGM.CreateRuntimeFunction(
796  llvm::FunctionType::get(CGF.IntTy, ArgTypes, IsVarArg), Name,
797  ReturnsTwiceAttr, /*Local=*/true);
798 
799  llvm::Value *Buf = CGF.Builder.CreateBitOrPointerCast(
800  CGF.EmitScalarExpr(E->getArg(0)), CGF.Int8PtrTy);
801  llvm::Value *Args[] = {Buf, Arg1};
802  llvm::CallSite CS = CGF.EmitRuntimeCallOrInvoke(SetJmpFn, Args);
803  CS.setAttributes(ReturnsTwiceAttr);
804  return RValue::get(CS.getInstruction());
805 }
806 
807 // Many of MSVC builtins are on x64, ARM and AArch64; to avoid repeating code,
808 // we handle them here.
810  _BitScanForward,
811  _BitScanReverse,
812  _InterlockedAnd,
813  _InterlockedDecrement,
814  _InterlockedExchange,
815  _InterlockedExchangeAdd,
816  _InterlockedExchangeSub,
817  _InterlockedIncrement,
818  _InterlockedOr,
819  _InterlockedXor,
820  _InterlockedExchangeAdd_acq,
821  _InterlockedExchangeAdd_rel,
822  _InterlockedExchangeAdd_nf,
823  _InterlockedExchange_acq,
824  _InterlockedExchange_rel,
825  _InterlockedExchange_nf,
826  _InterlockedCompareExchange_acq,
827  _InterlockedCompareExchange_rel,
828  _InterlockedCompareExchange_nf,
829  _InterlockedOr_acq,
830  _InterlockedOr_rel,
831  _InterlockedOr_nf,
832  _InterlockedXor_acq,
833  _InterlockedXor_rel,
834  _InterlockedXor_nf,
835  _InterlockedAnd_acq,
836  _InterlockedAnd_rel,
837  _InterlockedAnd_nf,
838  _InterlockedIncrement_acq,
839  _InterlockedIncrement_rel,
840  _InterlockedIncrement_nf,
841  _InterlockedDecrement_acq,
842  _InterlockedDecrement_rel,
843  _InterlockedDecrement_nf,
844  __fastfail,
845 };
846 
848  const CallExpr *E) {
849  switch (BuiltinID) {
850  case MSVCIntrin::_BitScanForward:
851  case MSVCIntrin::_BitScanReverse: {
852  Value *ArgValue = EmitScalarExpr(E->getArg(1));
853 
854  llvm::Type *ArgType = ArgValue->getType();
855  llvm::Type *IndexType =
856  EmitScalarExpr(E->getArg(0))->getType()->getPointerElementType();
857  llvm::Type *ResultType = ConvertType(E->getType());
858 
859  Value *ArgZero = llvm::Constant::getNullValue(ArgType);
860  Value *ResZero = llvm::Constant::getNullValue(ResultType);
861  Value *ResOne = llvm::ConstantInt::get(ResultType, 1);
862 
863  BasicBlock *Begin = Builder.GetInsertBlock();
864  BasicBlock *End = createBasicBlock("bitscan_end", this->CurFn);
865  Builder.SetInsertPoint(End);
866  PHINode *Result = Builder.CreatePHI(ResultType, 2, "bitscan_result");
867 
868  Builder.SetInsertPoint(Begin);
869  Value *IsZero = Builder.CreateICmpEQ(ArgValue, ArgZero);
870  BasicBlock *NotZero = createBasicBlock("bitscan_not_zero", this->CurFn);
871  Builder.CreateCondBr(IsZero, End, NotZero);
872  Result->addIncoming(ResZero, Begin);
873 
874  Builder.SetInsertPoint(NotZero);
875  Address IndexAddress = EmitPointerWithAlignment(E->getArg(0));
876 
877  if (BuiltinID == MSVCIntrin::_BitScanForward) {
878  Value *F = CGM.getIntrinsic(Intrinsic::cttz, ArgType);
879  Value *ZeroCount = Builder.CreateCall(F, {ArgValue, Builder.getTrue()});
880  ZeroCount = Builder.CreateIntCast(ZeroCount, IndexType, false);
881  Builder.CreateStore(ZeroCount, IndexAddress, false);
882  } else {
883  unsigned ArgWidth = cast<llvm::IntegerType>(ArgType)->getBitWidth();
884  Value *ArgTypeLastIndex = llvm::ConstantInt::get(IndexType, ArgWidth - 1);
885 
886  Value *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
887  Value *ZeroCount = Builder.CreateCall(F, {ArgValue, Builder.getTrue()});
888  ZeroCount = Builder.CreateIntCast(ZeroCount, IndexType, false);
889  Value *Index = Builder.CreateNSWSub(ArgTypeLastIndex, ZeroCount);
890  Builder.CreateStore(Index, IndexAddress, false);
891  }
892  Builder.CreateBr(End);
893  Result->addIncoming(ResOne, NotZero);
894 
895  Builder.SetInsertPoint(End);
896  return Result;
897  }
898  case MSVCIntrin::_InterlockedAnd:
899  return MakeBinaryAtomicValue(*this, AtomicRMWInst::And, E);
900  case MSVCIntrin::_InterlockedExchange:
901  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xchg, E);
902  case MSVCIntrin::_InterlockedExchangeAdd:
903  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Add, E);
904  case MSVCIntrin::_InterlockedExchangeSub:
905  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Sub, E);
906  case MSVCIntrin::_InterlockedOr:
907  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Or, E);
908  case MSVCIntrin::_InterlockedXor:
909  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xor, E);
910  case MSVCIntrin::_InterlockedExchangeAdd_acq:
911  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Add, E,
912  AtomicOrdering::Acquire);
913  case MSVCIntrin::_InterlockedExchangeAdd_rel:
914  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Add, E,
915  AtomicOrdering::Release);
916  case MSVCIntrin::_InterlockedExchangeAdd_nf:
917  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Add, E,
918  AtomicOrdering::Monotonic);
919  case MSVCIntrin::_InterlockedExchange_acq:
920  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xchg, E,
921  AtomicOrdering::Acquire);
922  case MSVCIntrin::_InterlockedExchange_rel:
923  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xchg, E,
924  AtomicOrdering::Release);
925  case MSVCIntrin::_InterlockedExchange_nf:
926  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xchg, E,
927  AtomicOrdering::Monotonic);
928  case MSVCIntrin::_InterlockedCompareExchange_acq:
929  return EmitAtomicCmpXchgForMSIntrin(*this, E, AtomicOrdering::Acquire);
930  case MSVCIntrin::_InterlockedCompareExchange_rel:
931  return EmitAtomicCmpXchgForMSIntrin(*this, E, AtomicOrdering::Release);
932  case MSVCIntrin::_InterlockedCompareExchange_nf:
933  return EmitAtomicCmpXchgForMSIntrin(*this, E, AtomicOrdering::Monotonic);
934  case MSVCIntrin::_InterlockedOr_acq:
935  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Or, E,
936  AtomicOrdering::Acquire);
937  case MSVCIntrin::_InterlockedOr_rel:
938  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Or, E,
939  AtomicOrdering::Release);
940  case MSVCIntrin::_InterlockedOr_nf:
941  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Or, E,
942  AtomicOrdering::Monotonic);
943  case MSVCIntrin::_InterlockedXor_acq:
944  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xor, E,
945  AtomicOrdering::Acquire);
946  case MSVCIntrin::_InterlockedXor_rel:
947  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xor, E,
948  AtomicOrdering::Release);
949  case MSVCIntrin::_InterlockedXor_nf:
950  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xor, E,
951  AtomicOrdering::Monotonic);
952  case MSVCIntrin::_InterlockedAnd_acq:
953  return MakeBinaryAtomicValue(*this, AtomicRMWInst::And, E,
954  AtomicOrdering::Acquire);
955  case MSVCIntrin::_InterlockedAnd_rel:
956  return MakeBinaryAtomicValue(*this, AtomicRMWInst::And, E,
957  AtomicOrdering::Release);
958  case MSVCIntrin::_InterlockedAnd_nf:
959  return MakeBinaryAtomicValue(*this, AtomicRMWInst::And, E,
960  AtomicOrdering::Monotonic);
961  case MSVCIntrin::_InterlockedIncrement_acq:
962  return EmitAtomicIncrementValue(*this, E, AtomicOrdering::Acquire);
963  case MSVCIntrin::_InterlockedIncrement_rel:
964  return EmitAtomicIncrementValue(*this, E, AtomicOrdering::Release);
965  case MSVCIntrin::_InterlockedIncrement_nf:
966  return EmitAtomicIncrementValue(*this, E, AtomicOrdering::Monotonic);
967  case MSVCIntrin::_InterlockedDecrement_acq:
968  return EmitAtomicDecrementValue(*this, E, AtomicOrdering::Acquire);
969  case MSVCIntrin::_InterlockedDecrement_rel:
970  return EmitAtomicDecrementValue(*this, E, AtomicOrdering::Release);
971  case MSVCIntrin::_InterlockedDecrement_nf:
972  return EmitAtomicDecrementValue(*this, E, AtomicOrdering::Monotonic);
973 
974  case MSVCIntrin::_InterlockedDecrement:
975  return EmitAtomicDecrementValue(*this, E);
976  case MSVCIntrin::_InterlockedIncrement:
977  return EmitAtomicIncrementValue(*this, E);
978 
979  case MSVCIntrin::__fastfail: {
980  // Request immediate process termination from the kernel. The instruction
981  // sequences to do this are documented on MSDN:
982  // https://msdn.microsoft.com/en-us/library/dn774154.aspx
983  llvm::Triple::ArchType ISA = getTarget().getTriple().getArch();
984  StringRef Asm, Constraints;
985  switch (ISA) {
986  default:
987  ErrorUnsupported(E, "__fastfail call for this architecture");
988  break;
989  case llvm::Triple::x86:
990  case llvm::Triple::x86_64:
991  Asm = "int $$0x29";
992  Constraints = "{cx}";
993  break;
994  case llvm::Triple::thumb:
995  Asm = "udf #251";
996  Constraints = "{r0}";
997  break;
998  }
999  llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, {Int32Ty}, false);
1000  llvm::InlineAsm *IA =
1001  llvm::InlineAsm::get(FTy, Asm, Constraints, /*SideEffects=*/true);
1002  llvm::AttributeList NoReturnAttr = llvm::AttributeList::get(
1003  getLLVMContext(), llvm::AttributeList::FunctionIndex,
1004  llvm::Attribute::NoReturn);
1005  CallSite CS = Builder.CreateCall(IA, EmitScalarExpr(E->getArg(0)));
1006  CS.setAttributes(NoReturnAttr);
1007  return CS.getInstruction();
1008  }
1009  }
1010  llvm_unreachable("Incorrect MSVC intrinsic!");
1011 }
1012 
1013 namespace {
1014 // ARC cleanup for __builtin_os_log_format
1015 struct CallObjCArcUse final : EHScopeStack::Cleanup {
1016  CallObjCArcUse(llvm::Value *object) : object(object) {}
1017  llvm::Value *object;
1018 
1019  void Emit(CodeGenFunction &CGF, Flags flags) override {
1020  CGF.EmitARCIntrinsicUse(object);
1021  }
1022 };
1023 }
1024 
1027  assert((Kind == BCK_CLZPassedZero || Kind == BCK_CTZPassedZero)
1028  && "Unsupported builtin check kind");
1029 
1030  Value *ArgValue = EmitScalarExpr(E);
1031  if (!SanOpts.has(SanitizerKind::Builtin) || !getTarget().isCLZForZeroUndef())
1032  return ArgValue;
1033 
1034  SanitizerScope SanScope(this);
1035  Value *Cond = Builder.CreateICmpNE(
1036  ArgValue, llvm::Constant::getNullValue(ArgValue->getType()));
1037  EmitCheck(std::make_pair(Cond, SanitizerKind::Builtin),
1038  SanitizerHandler::InvalidBuiltin,
1039  {EmitCheckSourceLocation(E->getExprLoc()),
1040  llvm::ConstantInt::get(Builder.getInt8Ty(), Kind)},
1041  None);
1042  return ArgValue;
1043 }
1044 
1045 /// Get the argument type for arguments to os_log_helper.
1047  QualType UnsignedTy = C.getIntTypeForBitwidth(Size * 8, /*Signed=*/false);
1048  return C.getCanonicalType(UnsignedTy);
1049 }
1050 
1052  const analyze_os_log::OSLogBufferLayout &Layout,
1053  CharUnits BufferAlignment) {
1054  ASTContext &Ctx = getContext();
1055 
1056  llvm::SmallString<64> Name;
1057  {
1058  raw_svector_ostream OS(Name);
1059  OS << "__os_log_helper";
1060  OS << "_" << BufferAlignment.getQuantity();
1061  OS << "_" << int(Layout.getSummaryByte());
1062  OS << "_" << int(Layout.getNumArgsByte());
1063  for (const auto &Item : Layout.Items)
1064  OS << "_" << int(Item.getSizeByte()) << "_"
1065  << int(Item.getDescriptorByte());
1066  }
1067 
1068  if (llvm::Function *F = CGM.getModule().getFunction(Name))
1069  return F;
1070 
1073  Params.emplace_back(Ctx, nullptr, SourceLocation(), &Ctx.Idents.get("buffer"),
1075  ArgTys.emplace_back(Ctx.VoidPtrTy);
1076 
1077  for (unsigned int I = 0, E = Layout.Items.size(); I < E; ++I) {
1078  char Size = Layout.Items[I].getSizeByte();
1079  if (!Size)
1080  continue;
1081 
1082  QualType ArgTy = getOSLogArgType(Ctx, Size);
1083  Params.emplace_back(
1084  Ctx, nullptr, SourceLocation(),
1085  &Ctx.Idents.get(std::string("arg") + llvm::to_string(I)), ArgTy,
1087  ArgTys.emplace_back(ArgTy);
1088  }
1089 
1090  FunctionArgList Args;
1091  for (auto &P : Params)
1092  Args.push_back(&P);
1093 
1094  QualType ReturnTy = Ctx.VoidTy;
1095  QualType FuncionTy = Ctx.getFunctionType(ReturnTy, ArgTys, {});
1096 
1097  // The helper function has linkonce_odr linkage to enable the linker to merge
1098  // identical functions. To ensure the merging always happens, 'noinline' is
1099  // attached to the function when compiling with -Oz.
1100  const CGFunctionInfo &FI =
1101  CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, Args);
1102  llvm::FunctionType *FuncTy = CGM.getTypes().GetFunctionType(FI);
1103  llvm::Function *Fn = llvm::Function::Create(
1104  FuncTy, llvm::GlobalValue::LinkOnceODRLinkage, Name, &CGM.getModule());
1105  Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
1106  CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Fn);
1107  CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Fn);
1108 
1109  // Attach 'noinline' at -Oz.
1110  if (CGM.getCodeGenOpts().OptimizeSize == 2)
1111  Fn->addFnAttr(llvm::Attribute::NoInline);
1112 
1113  auto NL = ApplyDebugLocation::CreateEmpty(*this);
1114  IdentifierInfo *II = &Ctx.Idents.get(Name);
1117  FuncionTy, nullptr, SC_PrivateExtern, false, false);
1118 
1119  StartFunction(FD, ReturnTy, Fn, FI, Args);
1120 
1121  // Create a scope with an artificial location for the body of this function.
1122  auto AL = ApplyDebugLocation::CreateArtificial(*this);
1123 
1124  CharUnits Offset;
1125  Address BufAddr(Builder.CreateLoad(GetAddrOfLocalVar(&Params[0]), "buf"),
1126  BufferAlignment);
1127  Builder.CreateStore(Builder.getInt8(Layout.getSummaryByte()),
1128  Builder.CreateConstByteGEP(BufAddr, Offset++, "summary"));
1129  Builder.CreateStore(Builder.getInt8(Layout.getNumArgsByte()),
1130  Builder.CreateConstByteGEP(BufAddr, Offset++, "numArgs"));
1131 
1132  unsigned I = 1;
1133  for (const auto &Item : Layout.Items) {
1134  Builder.CreateStore(
1135  Builder.getInt8(Item.getDescriptorByte()),
1136  Builder.CreateConstByteGEP(BufAddr, Offset++, "argDescriptor"));
1137  Builder.CreateStore(
1138  Builder.getInt8(Item.getSizeByte()),
1139  Builder.CreateConstByteGEP(BufAddr, Offset++, "argSize"));
1140 
1141  CharUnits Size = Item.size();
1142  if (!Size.getQuantity())
1143  continue;
1144 
1145  Address Arg = GetAddrOfLocalVar(&Params[I]);
1146  Address Addr = Builder.CreateConstByteGEP(BufAddr, Offset, "argData");
1147  Addr = Builder.CreateBitCast(Addr, Arg.getPointer()->getType(),
1148  "argDataCast");
1149  Builder.CreateStore(Builder.CreateLoad(Arg), Addr);
1150  Offset += Size;
1151  ++I;
1152  }
1153 
1154  FinishFunction();
1155 
1156  return Fn;
1157 }
1158 
1160  assert(E.getNumArgs() >= 2 &&
1161  "__builtin_os_log_format takes at least 2 arguments");
1162  ASTContext &Ctx = getContext();
1165  Address BufAddr = EmitPointerWithAlignment(E.getArg(0));
1166  llvm::SmallVector<llvm::Value *, 4> RetainableOperands;
1167 
1168  // Ignore argument 1, the format string. It is not currently used.
1169  CallArgList Args;
1170  Args.add(RValue::get(BufAddr.getPointer()), Ctx.VoidPtrTy);
1171 
1172  for (const auto &Item : Layout.Items) {
1173  int Size = Item.getSizeByte();
1174  if (!Size)
1175  continue;
1176 
1177  llvm::Value *ArgVal;
1178 
1179  if (Item.getKind() == analyze_os_log::OSLogBufferItem::MaskKind) {
1180  uint64_t Val = 0;
1181  for (unsigned I = 0, E = Item.getMaskType().size(); I < E; ++I)
1182  Val |= ((uint64_t)Item.getMaskType()[I]) << I * 8;
1183  ArgVal = llvm::Constant::getIntegerValue(Int64Ty, llvm::APInt(64, Val));
1184  } else if (const Expr *TheExpr = Item.getExpr()) {
1185  ArgVal = EmitScalarExpr(TheExpr, /*Ignore*/ false);
1186 
1187  // Check if this is a retainable type.
1188  if (TheExpr->getType()->isObjCRetainableType()) {
1189  assert(getEvaluationKind(TheExpr->getType()) == TEK_Scalar &&
1190  "Only scalar can be a ObjC retainable type");
1191  // Check if the object is constant, if not, save it in
1192  // RetainableOperands.
1193  if (!isa<Constant>(ArgVal))
1194  RetainableOperands.push_back(ArgVal);
1195  }
1196  } else {
1197  ArgVal = Builder.getInt32(Item.getConstValue().getQuantity());
1198  }
1199 
1200  unsigned ArgValSize =
1201  CGM.getDataLayout().getTypeSizeInBits(ArgVal->getType());
1202  llvm::IntegerType *IntTy = llvm::Type::getIntNTy(getLLVMContext(),
1203  ArgValSize);
1204  ArgVal = Builder.CreateBitOrPointerCast(ArgVal, IntTy);
1205  CanQualType ArgTy = getOSLogArgType(Ctx, Size);
1206  // If ArgVal has type x86_fp80, zero-extend ArgVal.
1207  ArgVal = Builder.CreateZExtOrBitCast(ArgVal, ConvertType(ArgTy));
1208  Args.add(RValue::get(ArgVal), ArgTy);
1209  }
1210 
1211  const CGFunctionInfo &FI =
1212  CGM.getTypes().arrangeBuiltinFunctionCall(Ctx.VoidTy, Args);
1213  llvm::Function *F = CodeGenFunction(CGM).generateBuiltinOSLogHelperFunction(
1214  Layout, BufAddr.getAlignment());
1215  EmitCall(FI, CGCallee::forDirect(F), ReturnValueSlot(), Args);
1216 
1217  // Push a clang.arc.use cleanup for each object in RetainableOperands. The
1218  // cleanup will cause the use to appear after the final log call, keeping
1219  // the object valid while it’s held in the log buffer. Note that if there’s
1220  // a release cleanup on the object, it will already be active; since
1221  // cleanups are emitted in reverse order, the use will occur before the
1222  // object is released.
1223  if (!RetainableOperands.empty() && getLangOpts().ObjCAutoRefCount &&
1224  CGM.getCodeGenOpts().OptimizationLevel != 0)
1225  for (llvm::Value *Object : RetainableOperands)
1226  pushFullExprCleanup<CallObjCArcUse>(getARCCleanupKind(), Object);
1227 
1228  return RValue::get(BufAddr.getPointer());
1229 }
1230 
1231 /// Determine if a binop is a checked mixed-sign multiply we can specialize.
1232 static bool isSpecialMixedSignMultiply(unsigned BuiltinID,
1233  WidthAndSignedness Op1Info,
1234  WidthAndSignedness Op2Info,
1235  WidthAndSignedness ResultInfo) {
1236  return BuiltinID == Builtin::BI__builtin_mul_overflow &&
1237  Op1Info.Width == Op2Info.Width && Op1Info.Width >= ResultInfo.Width &&
1238  Op1Info.Signed != Op2Info.Signed;
1239 }
1240 
1241 /// Emit a checked mixed-sign multiply. This is a cheaper specialization of
1242 /// the generic checked-binop irgen.
1243 static RValue
1245  WidthAndSignedness Op1Info, const clang::Expr *Op2,
1246  WidthAndSignedness Op2Info,
1247  const clang::Expr *ResultArg, QualType ResultQTy,
1248  WidthAndSignedness ResultInfo) {
1249  assert(isSpecialMixedSignMultiply(Builtin::BI__builtin_mul_overflow, Op1Info,
1250  Op2Info, ResultInfo) &&
1251  "Not a mixed-sign multipliction we can specialize");
1252 
1253  // Emit the signed and unsigned operands.
1254  const clang::Expr *SignedOp = Op1Info.Signed ? Op1 : Op2;
1255  const clang::Expr *UnsignedOp = Op1Info.Signed ? Op2 : Op1;
1256  llvm::Value *Signed = CGF.EmitScalarExpr(SignedOp);
1257  llvm::Value *Unsigned = CGF.EmitScalarExpr(UnsignedOp);
1258 
1259  llvm::Type *OpTy = Signed->getType();
1260  llvm::Value *Zero = llvm::Constant::getNullValue(OpTy);
1261  Address ResultPtr = CGF.EmitPointerWithAlignment(ResultArg);
1262  llvm::Type *ResTy = ResultPtr.getElementType();
1263 
1264  // Take the absolute value of the signed operand.
1265  llvm::Value *IsNegative = CGF.Builder.CreateICmpSLT(Signed, Zero);
1266  llvm::Value *AbsOfNegative = CGF.Builder.CreateSub(Zero, Signed);
1267  llvm::Value *AbsSigned =
1268  CGF.Builder.CreateSelect(IsNegative, AbsOfNegative, Signed);
1269 
1270  // Perform a checked unsigned multiplication.
1271  llvm::Value *UnsignedOverflow;
1272  llvm::Value *UnsignedResult =
1273  EmitOverflowIntrinsic(CGF, llvm::Intrinsic::umul_with_overflow, AbsSigned,
1274  Unsigned, UnsignedOverflow);
1275 
1276  llvm::Value *Overflow, *Result;
1277  if (ResultInfo.Signed) {
1278  // Signed overflow occurs if the result is greater than INT_MAX or lesser
1279  // than INT_MIN, i.e when |Result| > (INT_MAX + IsNegative).
1280  auto IntMax = llvm::APInt::getSignedMaxValue(ResultInfo.Width)
1281  .zextOrSelf(Op1Info.Width);
1282  llvm::Value *MaxResult =
1283  CGF.Builder.CreateAdd(llvm::ConstantInt::get(OpTy, IntMax),
1284  CGF.Builder.CreateZExt(IsNegative, OpTy));
1285  llvm::Value *SignedOverflow =
1286  CGF.Builder.CreateICmpUGT(UnsignedResult, MaxResult);
1287  Overflow = CGF.Builder.CreateOr(UnsignedOverflow, SignedOverflow);
1288 
1289  // Prepare the signed result (possibly by negating it).
1290  llvm::Value *NegativeResult = CGF.Builder.CreateNeg(UnsignedResult);
1291  llvm::Value *SignedResult =
1292  CGF.Builder.CreateSelect(IsNegative, NegativeResult, UnsignedResult);
1293  Result = CGF.Builder.CreateTrunc(SignedResult, ResTy);
1294  } else {
1295  // Unsigned overflow occurs if the result is < 0 or greater than UINT_MAX.
1296  llvm::Value *Underflow = CGF.Builder.CreateAnd(
1297  IsNegative, CGF.Builder.CreateIsNotNull(UnsignedResult));
1298  Overflow = CGF.Builder.CreateOr(UnsignedOverflow, Underflow);
1299  if (ResultInfo.Width < Op1Info.Width) {
1300  auto IntMax =
1301  llvm::APInt::getMaxValue(ResultInfo.Width).zext(Op1Info.Width);
1302  llvm::Value *TruncOverflow = CGF.Builder.CreateICmpUGT(
1303  UnsignedResult, llvm::ConstantInt::get(OpTy, IntMax));
1304  Overflow = CGF.Builder.CreateOr(Overflow, TruncOverflow);
1305  }
1306 
1307  // Negate the product if it would be negative in infinite precision.
1308  Result = CGF.Builder.CreateSelect(
1309  IsNegative, CGF.Builder.CreateNeg(UnsignedResult), UnsignedResult);
1310 
1311  Result = CGF.Builder.CreateTrunc(Result, ResTy);
1312  }
1313  assert(Overflow && Result && "Missing overflow or result");
1314 
1315  bool isVolatile =
1316  ResultArg->getType()->getPointeeType().isVolatileQualified();
1317  CGF.Builder.CreateStore(CGF.EmitToMemory(Result, ResultQTy), ResultPtr,
1318  isVolatile);
1319  return RValue::get(Overflow);
1320 }
1321 
1323  Value *&RecordPtr, CharUnits Align, Value *Func,
1324  int Lvl) {
1325  const auto *RT = RType->getAs<RecordType>();
1326  ASTContext &Context = CGF.getContext();
1327  RecordDecl *RD = RT->getDecl()->getDefinition();
1328  ASTContext &Ctx = RD->getASTContext();
1329  const ASTRecordLayout &RL = Ctx.getASTRecordLayout(RD);
1330  std::string Pad = std::string(Lvl * 4, ' ');
1331 
1332  Value *GString =
1333  CGF.Builder.CreateGlobalStringPtr(RType.getAsString() + " {\n");
1334  Value *Res = CGF.Builder.CreateCall(Func, {GString});
1335 
1336  static llvm::DenseMap<QualType, const char *> Types;
1337  if (Types.empty()) {
1338  Types[Context.CharTy] = "%c";
1339  Types[Context.BoolTy] = "%d";
1340  Types[Context.SignedCharTy] = "%hhd";
1341  Types[Context.UnsignedCharTy] = "%hhu";
1342  Types[Context.IntTy] = "%d";
1343  Types[Context.UnsignedIntTy] = "%u";
1344  Types[Context.LongTy] = "%ld";
1345  Types[Context.UnsignedLongTy] = "%lu";
1346  Types[Context.LongLongTy] = "%lld";
1347  Types[Context.UnsignedLongLongTy] = "%llu";
1348  Types[Context.ShortTy] = "%hd";
1349  Types[Context.UnsignedShortTy] = "%hu";
1350  Types[Context.VoidPtrTy] = "%p";
1351  Types[Context.FloatTy] = "%f";
1352  Types[Context.DoubleTy] = "%f";
1353  Types[Context.LongDoubleTy] = "%Lf";
1354  Types[Context.getPointerType(Context.CharTy)] = "%s";
1355  Types[Context.getPointerType(Context.getConstType(Context.CharTy))] = "%s";
1356  }
1357 
1358  for (const auto *FD : RD->fields()) {
1359  uint64_t Off = RL.getFieldOffset(FD->getFieldIndex());
1360  Off = Ctx.toCharUnitsFromBits(Off).getQuantity();
1361 
1362  Value *FieldPtr = RecordPtr;
1363  if (RD->isUnion())
1364  FieldPtr = CGF.Builder.CreatePointerCast(
1365  FieldPtr, CGF.ConvertType(Context.getPointerType(FD->getType())));
1366  else
1367  FieldPtr = CGF.Builder.CreateStructGEP(CGF.ConvertType(RType), FieldPtr,
1368  FD->getFieldIndex());
1369 
1370  GString = CGF.Builder.CreateGlobalStringPtr(
1371  llvm::Twine(Pad)
1372  .concat(FD->getType().getAsString())
1373  .concat(llvm::Twine(' '))
1374  .concat(FD->getNameAsString())
1375  .concat(" : ")
1376  .str());
1377  Value *TmpRes = CGF.Builder.CreateCall(Func, {GString});
1378  Res = CGF.Builder.CreateAdd(Res, TmpRes);
1379 
1380  QualType CanonicalType =
1381  FD->getType().getUnqualifiedType().getCanonicalType();
1382 
1383  // We check whether we are in a recursive type
1384  if (CanonicalType->isRecordType()) {
1385  Value *TmpRes =
1386  dumpRecord(CGF, CanonicalType, FieldPtr, Align, Func, Lvl + 1);
1387  Res = CGF.Builder.CreateAdd(TmpRes, Res);
1388  continue;
1389  }
1390 
1391  // We try to determine the best format to print the current field
1392  llvm::Twine Format = Types.find(CanonicalType) == Types.end()
1393  ? Types[Context.VoidPtrTy]
1394  : Types[CanonicalType];
1395 
1396  Address FieldAddress = Address(FieldPtr, Align);
1397  FieldPtr = CGF.Builder.CreateLoad(FieldAddress);
1398 
1399  // FIXME Need to handle bitfield here
1400  GString = CGF.Builder.CreateGlobalStringPtr(
1401  Format.concat(llvm::Twine('\n')).str());
1402  TmpRes = CGF.Builder.CreateCall(Func, {GString, FieldPtr});
1403  Res = CGF.Builder.CreateAdd(Res, TmpRes);
1404  }
1405 
1406  GString = CGF.Builder.CreateGlobalStringPtr(Pad + "}\n");
1407  Value *TmpRes = CGF.Builder.CreateCall(Func, {GString});
1408  Res = CGF.Builder.CreateAdd(Res, TmpRes);
1409  return Res;
1410 }
1411 
1412 RValue CodeGenFunction::emitRotate(const CallExpr *E, bool IsRotateRight) {
1413  llvm::Value *Src = EmitScalarExpr(E->getArg(0));
1414  llvm::Value *ShiftAmt = EmitScalarExpr(E->getArg(1));
1415 
1416  // The builtin's shift arg may have a different type than the source arg and
1417  // result, but the LLVM intrinsic uses the same type for all values.
1418  llvm::Type *Ty = Src->getType();
1419  ShiftAmt = Builder.CreateIntCast(ShiftAmt, Ty, false);
1420 
1421  // Rotate is a special case of LLVM funnel shift - 1st 2 args are the same.
1422  unsigned IID = IsRotateRight ? Intrinsic::fshr : Intrinsic::fshl;
1423  Value *F = CGM.getIntrinsic(IID, Ty);
1424  return RValue::get(Builder.CreateCall(F, { Src, Src, ShiftAmt }));
1425 }
1426 
1428  const CallExpr *E,
1429  ReturnValueSlot ReturnValue) {
1430  const FunctionDecl *FD = GD.getDecl()->getAsFunction();
1431  // See if we can constant fold this builtin. If so, don't emit it at all.
1432  Expr::EvalResult Result;
1433  if (E->EvaluateAsRValue(Result, CGM.getContext()) &&
1434  !Result.hasSideEffects()) {
1435  if (Result.Val.isInt())
1436  return RValue::get(llvm::ConstantInt::get(getLLVMContext(),
1437  Result.Val.getInt()));
1438  if (Result.Val.isFloat())
1439  return RValue::get(llvm::ConstantFP::get(getLLVMContext(),
1440  Result.Val.getFloat()));
1441  }
1442 
1443  // There are LLVM math intrinsics/instructions corresponding to math library
1444  // functions except the LLVM op will never set errno while the math library
1445  // might. Also, math builtins have the same semantics as their math library
1446  // twins. Thus, we can transform math library and builtin calls to their
1447  // LLVM counterparts if the call is marked 'const' (known to never set errno).
1448  if (FD->hasAttr<ConstAttr>()) {
1449  switch (BuiltinID) {
1450  case Builtin::BIceil:
1451  case Builtin::BIceilf:
1452  case Builtin::BIceill:
1453  case Builtin::BI__builtin_ceil:
1454  case Builtin::BI__builtin_ceilf:
1455  case Builtin::BI__builtin_ceill:
1456  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::ceil));
1457 
1458  case Builtin::BIcopysign:
1459  case Builtin::BIcopysignf:
1460  case Builtin::BIcopysignl:
1461  case Builtin::BI__builtin_copysign:
1462  case Builtin::BI__builtin_copysignf:
1463  case Builtin::BI__builtin_copysignl:
1464  case Builtin::BI__builtin_copysignf128:
1466 
1467  case Builtin::BIcos:
1468  case Builtin::BIcosf:
1469  case Builtin::BIcosl:
1470  case Builtin::BI__builtin_cos:
1471  case Builtin::BI__builtin_cosf:
1472  case Builtin::BI__builtin_cosl:
1473  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::cos));
1474 
1475  case Builtin::BIexp:
1476  case Builtin::BIexpf:
1477  case Builtin::BIexpl:
1478  case Builtin::BI__builtin_exp:
1479  case Builtin::BI__builtin_expf:
1480  case Builtin::BI__builtin_expl:
1481  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::exp));
1482 
1483  case Builtin::BIexp2:
1484  case Builtin::BIexp2f:
1485  case Builtin::BIexp2l:
1486  case Builtin::BI__builtin_exp2:
1487  case Builtin::BI__builtin_exp2f:
1488  case Builtin::BI__builtin_exp2l:
1489  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::exp2));
1490 
1491  case Builtin::BIfabs:
1492  case Builtin::BIfabsf:
1493  case Builtin::BIfabsl:
1494  case Builtin::BI__builtin_fabs:
1495  case Builtin::BI__builtin_fabsf:
1496  case Builtin::BI__builtin_fabsl:
1497  case Builtin::BI__builtin_fabsf128:
1498  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::fabs));
1499 
1500  case Builtin::BIfloor:
1501  case Builtin::BIfloorf:
1502  case Builtin::BIfloorl:
1503  case Builtin::BI__builtin_floor:
1504  case Builtin::BI__builtin_floorf:
1505  case Builtin::BI__builtin_floorl:
1506  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::floor));
1507 
1508  case Builtin::BIfma:
1509  case Builtin::BIfmaf:
1510  case Builtin::BIfmal:
1511  case Builtin::BI__builtin_fma:
1512  case Builtin::BI__builtin_fmaf:
1513  case Builtin::BI__builtin_fmal:
1514  return RValue::get(emitTernaryBuiltin(*this, E, Intrinsic::fma));
1515 
1516  case Builtin::BIfmax:
1517  case Builtin::BIfmaxf:
1518  case Builtin::BIfmaxl:
1519  case Builtin::BI__builtin_fmax:
1520  case Builtin::BI__builtin_fmaxf:
1521  case Builtin::BI__builtin_fmaxl:
1522  return RValue::get(emitBinaryBuiltin(*this, E, Intrinsic::maxnum));
1523 
1524  case Builtin::BIfmin:
1525  case Builtin::BIfminf:
1526  case Builtin::BIfminl:
1527  case Builtin::BI__builtin_fmin:
1528  case Builtin::BI__builtin_fminf:
1529  case Builtin::BI__builtin_fminl:
1530  return RValue::get(emitBinaryBuiltin(*this, E, Intrinsic::minnum));
1531 
1532  // fmod() is a special-case. It maps to the frem instruction rather than an
1533  // LLVM intrinsic.
1534  case Builtin::BIfmod:
1535  case Builtin::BIfmodf:
1536  case Builtin::BIfmodl:
1537  case Builtin::BI__builtin_fmod:
1538  case Builtin::BI__builtin_fmodf:
1539  case Builtin::BI__builtin_fmodl: {
1540  Value *Arg1 = EmitScalarExpr(E->getArg(0));
1541  Value *Arg2 = EmitScalarExpr(E->getArg(1));
1542  return RValue::get(Builder.CreateFRem(Arg1, Arg2, "fmod"));
1543  }
1544 
1545  case Builtin::BIlog:
1546  case Builtin::BIlogf:
1547  case Builtin::BIlogl:
1548  case Builtin::BI__builtin_log:
1549  case Builtin::BI__builtin_logf:
1550  case Builtin::BI__builtin_logl:
1551  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::log));
1552 
1553  case Builtin::BIlog10:
1554  case Builtin::BIlog10f:
1555  case Builtin::BIlog10l:
1556  case Builtin::BI__builtin_log10:
1557  case Builtin::BI__builtin_log10f:
1558  case Builtin::BI__builtin_log10l:
1559  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::log10));
1560 
1561  case Builtin::BIlog2:
1562  case Builtin::BIlog2f:
1563  case Builtin::BIlog2l:
1564  case Builtin::BI__builtin_log2:
1565  case Builtin::BI__builtin_log2f:
1566  case Builtin::BI__builtin_log2l:
1567  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::log2));
1568 
1569  case Builtin::BInearbyint:
1570  case Builtin::BInearbyintf:
1571  case Builtin::BInearbyintl:
1572  case Builtin::BI__builtin_nearbyint:
1573  case Builtin::BI__builtin_nearbyintf:
1574  case Builtin::BI__builtin_nearbyintl:
1576 
1577  case Builtin::BIpow:
1578  case Builtin::BIpowf:
1579  case Builtin::BIpowl:
1580  case Builtin::BI__builtin_pow:
1581  case Builtin::BI__builtin_powf:
1582  case Builtin::BI__builtin_powl:
1583  return RValue::get(emitBinaryBuiltin(*this, E, Intrinsic::pow));
1584 
1585  case Builtin::BIrint:
1586  case Builtin::BIrintf:
1587  case Builtin::BIrintl:
1588  case Builtin::BI__builtin_rint:
1589  case Builtin::BI__builtin_rintf:
1590  case Builtin::BI__builtin_rintl:
1591  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::rint));
1592 
1593  case Builtin::BIround:
1594  case Builtin::BIroundf:
1595  case Builtin::BIroundl:
1596  case Builtin::BI__builtin_round:
1597  case Builtin::BI__builtin_roundf:
1598  case Builtin::BI__builtin_roundl:
1599  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::round));
1600 
1601  case Builtin::BIsin:
1602  case Builtin::BIsinf:
1603  case Builtin::BIsinl:
1604  case Builtin::BI__builtin_sin:
1605  case Builtin::BI__builtin_sinf:
1606  case Builtin::BI__builtin_sinl:
1607  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::sin));
1608 
1609  case Builtin::BIsqrt:
1610  case Builtin::BIsqrtf:
1611  case Builtin::BIsqrtl:
1612  case Builtin::BI__builtin_sqrt:
1613  case Builtin::BI__builtin_sqrtf:
1614  case Builtin::BI__builtin_sqrtl:
1615  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::sqrt));
1616 
1617  case Builtin::BItrunc:
1618  case Builtin::BItruncf:
1619  case Builtin::BItruncl:
1620  case Builtin::BI__builtin_trunc:
1621  case Builtin::BI__builtin_truncf:
1622  case Builtin::BI__builtin_truncl:
1623  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::trunc));
1624 
1625  default:
1626  break;
1627  }
1628  }
1629 
1630  switch (BuiltinID) {
1631  default: break;
1632  case Builtin::BI__builtin___CFStringMakeConstantString:
1633  case Builtin::BI__builtin___NSStringMakeConstantString:
1634  return RValue::get(ConstantEmitter(*this).emitAbstract(E, E->getType()));
1635  case Builtin::BI__builtin_stdarg_start:
1636  case Builtin::BI__builtin_va_start:
1637  case Builtin::BI__va_start:
1638  case Builtin::BI__builtin_va_end:
1639  return RValue::get(
1640  EmitVAStartEnd(BuiltinID == Builtin::BI__va_start
1641  ? EmitScalarExpr(E->getArg(0))
1642  : EmitVAListRef(E->getArg(0)).getPointer(),
1643  BuiltinID != Builtin::BI__builtin_va_end));
1644  case Builtin::BI__builtin_va_copy: {
1645  Value *DstPtr = EmitVAListRef(E->getArg(0)).getPointer();
1646  Value *SrcPtr = EmitVAListRef(E->getArg(1)).getPointer();
1647 
1648  llvm::Type *Type = Int8PtrTy;
1649 
1650  DstPtr = Builder.CreateBitCast(DstPtr, Type);
1651  SrcPtr = Builder.CreateBitCast(SrcPtr, Type);
1652  return RValue::get(Builder.CreateCall(CGM.getIntrinsic(Intrinsic::vacopy),
1653  {DstPtr, SrcPtr}));
1654  }
1655  case Builtin::BI__builtin_abs:
1656  case Builtin::BI__builtin_labs:
1657  case Builtin::BI__builtin_llabs: {
1658  // X < 0 ? -X : X
1659  // The negation has 'nsw' because abs of INT_MIN is undefined.
1660  Value *ArgValue = EmitScalarExpr(E->getArg(0));
1661  Value *NegOp = Builder.CreateNSWNeg(ArgValue, "neg");
1662  Constant *Zero = llvm::Constant::getNullValue(ArgValue->getType());
1663  Value *CmpResult = Builder.CreateICmpSLT(ArgValue, Zero, "abscond");
1664  Value *Result = Builder.CreateSelect(CmpResult, NegOp, ArgValue, "abs");
1665  return RValue::get(Result);
1666  }
1667  case Builtin::BI__builtin_conj:
1668  case Builtin::BI__builtin_conjf:
1669  case Builtin::BI__builtin_conjl: {
1670  ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0));
1671  Value *Real = ComplexVal.first;
1672  Value *Imag = ComplexVal.second;
1673  Value *Zero =
1674  Imag->getType()->isFPOrFPVectorTy()
1675  ? llvm::ConstantFP::getZeroValueForNegation(Imag->getType())
1676  : llvm::Constant::getNullValue(Imag->getType());
1677 
1678  Imag = Builder.CreateFSub(Zero, Imag, "sub");
1679  return RValue::getComplex(std::make_pair(Real, Imag));
1680  }
1681  case Builtin::BI__builtin_creal:
1682  case Builtin::BI__builtin_crealf:
1683  case Builtin::BI__builtin_creall:
1684  case Builtin::BIcreal:
1685  case Builtin::BIcrealf:
1686  case Builtin::BIcreall: {
1687  ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0));
1688  return RValue::get(ComplexVal.first);
1689  }
1690 
1691  case Builtin::BI__builtin_dump_struct: {
1692  Value *Func = EmitScalarExpr(E->getArg(1)->IgnoreImpCasts());
1693  CharUnits Arg0Align = EmitPointerWithAlignment(E->getArg(0)).getAlignment();
1694 
1695  const Expr *Arg0 = E->getArg(0)->IgnoreImpCasts();
1696  QualType Arg0Type = Arg0->getType()->getPointeeType();
1697 
1698  Value *RecordPtr = EmitScalarExpr(Arg0);
1699  Value *Res = dumpRecord(*this, Arg0Type, RecordPtr, Arg0Align, Func, 0);
1700  return RValue::get(Res);
1701  }
1702 
1703  case Builtin::BI__builtin_cimag:
1704  case Builtin::BI__builtin_cimagf:
1705  case Builtin::BI__builtin_cimagl:
1706  case Builtin::BIcimag:
1707  case Builtin::BIcimagf:
1708  case Builtin::BIcimagl: {
1709  ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0));
1710  return RValue::get(ComplexVal.second);
1711  }
1712 
1713  case Builtin::BI__builtin_clrsb:
1714  case Builtin::BI__builtin_clrsbl:
1715  case Builtin::BI__builtin_clrsbll: {
1716  // clrsb(x) -> clz(x < 0 ? ~x : x) - 1 or
1717  Value *ArgValue = EmitScalarExpr(E->getArg(0));
1718 
1719  llvm::Type *ArgType = ArgValue->getType();
1720  Value *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
1721 
1722  llvm::Type *ResultType = ConvertType(E->getType());
1723  Value *Zero = llvm::Constant::getNullValue(ArgType);
1724  Value *IsNeg = Builder.CreateICmpSLT(ArgValue, Zero, "isneg");
1725  Value *Inverse = Builder.CreateNot(ArgValue, "not");
1726  Value *Tmp = Builder.CreateSelect(IsNeg, Inverse, ArgValue);
1727  Value *Ctlz = Builder.CreateCall(F, {Tmp, Builder.getFalse()});
1728  Value *Result = Builder.CreateSub(Ctlz, llvm::ConstantInt::get(ArgType, 1));
1729  Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
1730  "cast");
1731  return RValue::get(Result);
1732  }
1733  case Builtin::BI__builtin_ctzs:
1734  case Builtin::BI__builtin_ctz:
1735  case Builtin::BI__builtin_ctzl:
1736  case Builtin::BI__builtin_ctzll: {
1737  Value *ArgValue = EmitCheckedArgForBuiltin(E->getArg(0), BCK_CTZPassedZero);
1738 
1739  llvm::Type *ArgType = ArgValue->getType();
1740  Value *F = CGM.getIntrinsic(Intrinsic::cttz, ArgType);
1741 
1742  llvm::Type *ResultType = ConvertType(E->getType());
1743  Value *ZeroUndef = Builder.getInt1(getTarget().isCLZForZeroUndef());
1744  Value *Result = Builder.CreateCall(F, {ArgValue, ZeroUndef});
1745  if (Result->getType() != ResultType)
1746  Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
1747  "cast");
1748  return RValue::get(Result);
1749  }
1750  case Builtin::BI__builtin_clzs:
1751  case Builtin::BI__builtin_clz:
1752  case Builtin::BI__builtin_clzl:
1753  case Builtin::BI__builtin_clzll: {
1754  Value *ArgValue = EmitCheckedArgForBuiltin(E->getArg(0), BCK_CLZPassedZero);
1755 
1756  llvm::Type *ArgType = ArgValue->getType();
1757  Value *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
1758 
1759  llvm::Type *ResultType = ConvertType(E->getType());
1760  Value *ZeroUndef = Builder.getInt1(getTarget().isCLZForZeroUndef());
1761  Value *Result = Builder.CreateCall(F, {ArgValue, ZeroUndef});
1762  if (Result->getType() != ResultType)
1763  Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
1764  "cast");
1765  return RValue::get(Result);
1766  }
1767  case Builtin::BI__builtin_ffs:
1768  case Builtin::BI__builtin_ffsl:
1769  case Builtin::BI__builtin_ffsll: {
1770  // ffs(x) -> x ? cttz(x) + 1 : 0
1771  Value *ArgValue = EmitScalarExpr(E->getArg(0));
1772 
1773  llvm::Type *ArgType = ArgValue->getType();
1774  Value *F = CGM.getIntrinsic(Intrinsic::cttz, ArgType);
1775 
1776  llvm::Type *ResultType = ConvertType(E->getType());
1777  Value *Tmp =
1778  Builder.CreateAdd(Builder.CreateCall(F, {ArgValue, Builder.getTrue()}),
1779  llvm::ConstantInt::get(ArgType, 1));
1780  Value *Zero = llvm::Constant::getNullValue(ArgType);
1781  Value *IsZero = Builder.CreateICmpEQ(ArgValue, Zero, "iszero");
1782  Value *Result = Builder.CreateSelect(IsZero, Zero, Tmp, "ffs");
1783  if (Result->getType() != ResultType)
1784  Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
1785  "cast");
1786  return RValue::get(Result);
1787  }
1788  case Builtin::BI__builtin_parity:
1789  case Builtin::BI__builtin_parityl:
1790  case Builtin::BI__builtin_parityll: {
1791  // parity(x) -> ctpop(x) & 1
1792  Value *ArgValue = EmitScalarExpr(E->getArg(0));
1793 
1794  llvm::Type *ArgType = ArgValue->getType();
1795  Value *F = CGM.getIntrinsic(Intrinsic::ctpop, ArgType);
1796 
1797  llvm::Type *ResultType = ConvertType(E->getType());
1798  Value *Tmp = Builder.CreateCall(F, ArgValue);
1799  Value *Result = Builder.CreateAnd(Tmp, llvm::ConstantInt::get(ArgType, 1));
1800  if (Result->getType() != ResultType)
1801  Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
1802  "cast");
1803  return RValue::get(Result);
1804  }
1805  case Builtin::BI__popcnt16:
1806  case Builtin::BI__popcnt:
1807  case Builtin::BI__popcnt64:
1808  case Builtin::BI__builtin_popcount:
1809  case Builtin::BI__builtin_popcountl:
1810  case Builtin::BI__builtin_popcountll: {
1811  Value *ArgValue = EmitScalarExpr(E->getArg(0));
1812 
1813  llvm::Type *ArgType = ArgValue->getType();
1814  Value *F = CGM.getIntrinsic(Intrinsic::ctpop, ArgType);
1815 
1816  llvm::Type *ResultType = ConvertType(E->getType());
1817  Value *Result = Builder.CreateCall(F, ArgValue);
1818  if (Result->getType() != ResultType)
1819  Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
1820  "cast");
1821  return RValue::get(Result);
1822  }
1823  case Builtin::BI_rotr8:
1824  case Builtin::BI_rotr16:
1825  case Builtin::BI_rotr:
1826  case Builtin::BI_lrotr:
1827  case Builtin::BI_rotr64: {
1828  Value *Val = EmitScalarExpr(E->getArg(0));
1829  Value *Shift = EmitScalarExpr(E->getArg(1));
1830 
1831  llvm::Type *ArgType = Val->getType();
1832  Shift = Builder.CreateIntCast(Shift, ArgType, false);
1833  unsigned ArgWidth = ArgType->getIntegerBitWidth();
1834  Value *Mask = llvm::ConstantInt::get(ArgType, ArgWidth - 1);
1835 
1836  Value *RightShiftAmt = Builder.CreateAnd(Shift, Mask);
1837  Value *RightShifted = Builder.CreateLShr(Val, RightShiftAmt);
1838  Value *LeftShiftAmt = Builder.CreateAnd(Builder.CreateNeg(Shift), Mask);
1839  Value *LeftShifted = Builder.CreateShl(Val, LeftShiftAmt);
1840  Value *Result = Builder.CreateOr(LeftShifted, RightShifted);
1841  return RValue::get(Result);
1842  }
1843  case Builtin::BI_rotl8:
1844  case Builtin::BI_rotl16:
1845  case Builtin::BI_rotl:
1846  case Builtin::BI_lrotl:
1847  case Builtin::BI_rotl64: {
1848  Value *Val = EmitScalarExpr(E->getArg(0));
1849  Value *Shift = EmitScalarExpr(E->getArg(1));
1850 
1851  llvm::Type *ArgType = Val->getType();
1852  Shift = Builder.CreateIntCast(Shift, ArgType, false);
1853  unsigned ArgWidth = ArgType->getIntegerBitWidth();
1854  Value *Mask = llvm::ConstantInt::get(ArgType, ArgWidth - 1);
1855 
1856  Value *LeftShiftAmt = Builder.CreateAnd(Shift, Mask);
1857  Value *LeftShifted = Builder.CreateShl(Val, LeftShiftAmt);
1858  Value *RightShiftAmt = Builder.CreateAnd(Builder.CreateNeg(Shift), Mask);
1859  Value *RightShifted = Builder.CreateLShr(Val, RightShiftAmt);
1860  Value *Result = Builder.CreateOr(LeftShifted, RightShifted);
1861  return RValue::get(Result);
1862  }
1863  case Builtin::BI__builtin_unpredictable: {
1864  // Always return the argument of __builtin_unpredictable. LLVM does not
1865  // handle this builtin. Metadata for this builtin should be added directly
1866  // to instructions such as branches or switches that use it.
1867  return RValue::get(EmitScalarExpr(E->getArg(0)));
1868  }
1869  case Builtin::BI__builtin_expect: {
1870  Value *ArgValue = EmitScalarExpr(E->getArg(0));
1871  llvm::Type *ArgType = ArgValue->getType();
1872 
1873  Value *ExpectedValue = EmitScalarExpr(E->getArg(1));
1874  // Don't generate llvm.expect on -O0 as the backend won't use it for
1875  // anything.
1876  // Note, we still IRGen ExpectedValue because it could have side-effects.
1877  if (CGM.getCodeGenOpts().OptimizationLevel == 0)
1878  return RValue::get(ArgValue);
1879 
1880  Value *FnExpect = CGM.getIntrinsic(Intrinsic::expect, ArgType);
1881  Value *Result =
1882  Builder.CreateCall(FnExpect, {ArgValue, ExpectedValue}, "expval");
1883  return RValue::get(Result);
1884  }
1885  case Builtin::BI__builtin_assume_aligned: {
1886  Value *PtrValue = EmitScalarExpr(E->getArg(0));
1887  Value *OffsetValue =
1888  (E->getNumArgs() > 2) ? EmitScalarExpr(E->getArg(2)) : nullptr;
1889 
1890  Value *AlignmentValue = EmitScalarExpr(E->getArg(1));
1891  ConstantInt *AlignmentCI = cast<ConstantInt>(AlignmentValue);
1892  unsigned Alignment = (unsigned) AlignmentCI->getZExtValue();
1893 
1894  EmitAlignmentAssumption(PtrValue, Alignment, OffsetValue);
1895  return RValue::get(PtrValue);
1896  }
1897  case Builtin::BI__assume:
1898  case Builtin::BI__builtin_assume: {
1899  if (E->getArg(0)->HasSideEffects(getContext()))
1900  return RValue::get(nullptr);
1901 
1902  Value *ArgValue = EmitScalarExpr(E->getArg(0));
1903  Value *FnAssume = CGM.getIntrinsic(Intrinsic::assume);
1904  return RValue::get(Builder.CreateCall(FnAssume, ArgValue));
1905  }
1906  case Builtin::BI__builtin_bswap16:
1907  case Builtin::BI__builtin_bswap32:
1908  case Builtin::BI__builtin_bswap64: {
1909  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::bswap));
1910  }
1911  case Builtin::BI__builtin_bitreverse8:
1912  case Builtin::BI__builtin_bitreverse16:
1913  case Builtin::BI__builtin_bitreverse32:
1914  case Builtin::BI__builtin_bitreverse64: {
1915  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::bitreverse));
1916  }
1917  case Builtin::BI__builtin_rotateleft8:
1918  case Builtin::BI__builtin_rotateleft16:
1919  case Builtin::BI__builtin_rotateleft32:
1920  case Builtin::BI__builtin_rotateleft64:
1921  return emitRotate(E, false);
1922 
1923  case Builtin::BI__builtin_rotateright8:
1924  case Builtin::BI__builtin_rotateright16:
1925  case Builtin::BI__builtin_rotateright32:
1926  case Builtin::BI__builtin_rotateright64:
1927  return emitRotate(E, true);
1928 
1929  case Builtin::BI__builtin_constant_p: {
1930  llvm::Type *ResultType = ConvertType(E->getType());
1931  if (CGM.getCodeGenOpts().OptimizationLevel == 0)
1932  // At -O0, we don't perform inlining, so we don't need to delay the
1933  // processing.
1934  return RValue::get(ConstantInt::get(ResultType, 0));
1935  if (auto *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)->IgnoreImplicit())) {
1936  auto DREType = DRE->getType();
1937  if (DREType->isAggregateType() || DREType->isFunctionType())
1938  return RValue::get(ConstantInt::get(ResultType, 0));
1939  }
1940  Value *ArgValue = EmitScalarExpr(E->getArg(0));
1941  llvm::Type *ArgType = ArgValue->getType();
1942 
1943  Value *F = CGM.getIntrinsic(Intrinsic::is_constant, ArgType);
1944  Value *Result = Builder.CreateCall(F, ArgValue);
1945  if (Result->getType() != ResultType)
1946  Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true);
1947  return RValue::get(Result);
1948  }
1949  case Builtin::BI__builtin_object_size: {
1950  unsigned Type =
1951  E->getArg(1)->EvaluateKnownConstInt(getContext()).getZExtValue();
1952  auto *ResType = cast<llvm::IntegerType>(ConvertType(E->getType()));
1953 
1954  // We pass this builtin onto the optimizer so that it can figure out the
1955  // object size in more complex cases.
1956  return RValue::get(emitBuiltinObjectSize(E->getArg(0), Type, ResType,
1957  /*EmittedE=*/nullptr));
1958  }
1959  case Builtin::BI__builtin_prefetch: {
1960  Value *Locality, *RW, *Address = EmitScalarExpr(E->getArg(0));
1961  // FIXME: Technically these constants should of type 'int', yes?
1962  RW = (E->getNumArgs() > 1) ? EmitScalarExpr(E->getArg(1)) :
1963  llvm::ConstantInt::get(Int32Ty, 0);
1964  Locality = (E->getNumArgs() > 2) ? EmitScalarExpr(E->getArg(2)) :
1965  llvm::ConstantInt::get(Int32Ty, 3);
1966  Value *Data = llvm::ConstantInt::get(Int32Ty, 1);
1967  Value *F = CGM.getIntrinsic(Intrinsic::prefetch);
1968  return RValue::get(Builder.CreateCall(F, {Address, RW, Locality, Data}));
1969  }
1970  case Builtin::BI__builtin_readcyclecounter: {
1971  Value *F = CGM.getIntrinsic(Intrinsic::readcyclecounter);
1972  return RValue::get(Builder.CreateCall(F));
1973  }
1974  case Builtin::BI__builtin___clear_cache: {
1975  Value *Begin = EmitScalarExpr(E->getArg(0));
1976  Value *End = EmitScalarExpr(E->getArg(1));
1977  Value *F = CGM.getIntrinsic(Intrinsic::clear_cache);
1978  return RValue::get(Builder.CreateCall(F, {Begin, End}));
1979  }
1980  case Builtin::BI__builtin_trap:
1981  return RValue::get(EmitTrapCall(Intrinsic::trap));
1982  case Builtin::BI__debugbreak:
1983  return RValue::get(EmitTrapCall(Intrinsic::debugtrap));
1984  case Builtin::BI__builtin_unreachable: {
1985  EmitUnreachable(E->getExprLoc());
1986 
1987  // We do need to preserve an insertion point.
1988  EmitBlock(createBasicBlock("unreachable.cont"));
1989 
1990  return RValue::get(nullptr);
1991  }
1992 
1993  case Builtin::BI__builtin_powi:
1994  case Builtin::BI__builtin_powif:
1995  case Builtin::BI__builtin_powil: {
1996  Value *Base = EmitScalarExpr(E->getArg(0));
1997  Value *Exponent = EmitScalarExpr(E->getArg(1));
1998  llvm::Type *ArgType = Base->getType();
1999  Value *F = CGM.getIntrinsic(Intrinsic::powi, ArgType);
2000  return RValue::get(Builder.CreateCall(F, {Base, Exponent}));
2001  }
2002 
2003  case Builtin::BI__builtin_isgreater:
2004  case Builtin::BI__builtin_isgreaterequal:
2005  case Builtin::BI__builtin_isless:
2006  case Builtin::BI__builtin_islessequal:
2007  case Builtin::BI__builtin_islessgreater:
2008  case Builtin::BI__builtin_isunordered: {
2009  // Ordered comparisons: we know the arguments to these are matching scalar
2010  // floating point values.
2011  Value *LHS = EmitScalarExpr(E->getArg(0));
2012  Value *RHS = EmitScalarExpr(E->getArg(1));
2013 
2014  switch (BuiltinID) {
2015  default: llvm_unreachable("Unknown ordered comparison");
2016  case Builtin::BI__builtin_isgreater:
2017  LHS = Builder.CreateFCmpOGT(LHS, RHS, "cmp");
2018  break;
2019  case Builtin::BI__builtin_isgreaterequal:
2020  LHS = Builder.CreateFCmpOGE(LHS, RHS, "cmp");
2021  break;
2022  case Builtin::BI__builtin_isless:
2023  LHS = Builder.CreateFCmpOLT(LHS, RHS, "cmp");
2024  break;
2025  case Builtin::BI__builtin_islessequal:
2026  LHS = Builder.CreateFCmpOLE(LHS, RHS, "cmp");
2027  break;
2028  case Builtin::BI__builtin_islessgreater:
2029  LHS = Builder.CreateFCmpONE(LHS, RHS, "cmp");
2030  break;
2031  case Builtin::BI__builtin_isunordered:
2032  LHS = Builder.CreateFCmpUNO(LHS, RHS, "cmp");
2033  break;
2034  }
2035  // ZExt bool to int type.
2036  return RValue::get(Builder.CreateZExt(LHS, ConvertType(E->getType())));
2037  }
2038  case Builtin::BI__builtin_isnan: {
2039  Value *V = EmitScalarExpr(E->getArg(0));
2040  V = Builder.CreateFCmpUNO(V, V, "cmp");
2041  return RValue::get(Builder.CreateZExt(V, ConvertType(E->getType())));
2042  }
2043 
2044  case Builtin::BIfinite:
2045  case Builtin::BI__finite:
2046  case Builtin::BIfinitef:
2047  case Builtin::BI__finitef:
2048  case Builtin::BIfinitel:
2049  case Builtin::BI__finitel:
2050  case Builtin::BI__builtin_isinf:
2051  case Builtin::BI__builtin_isfinite: {
2052  // isinf(x) --> fabs(x) == infinity
2053  // isfinite(x) --> fabs(x) != infinity
2054  // x != NaN via the ordered compare in either case.
2055  Value *V = EmitScalarExpr(E->getArg(0));
2056  Value *Fabs = EmitFAbs(*this, V);
2057  Constant *Infinity = ConstantFP::getInfinity(V->getType());
2058  CmpInst::Predicate Pred = (BuiltinID == Builtin::BI__builtin_isinf)
2059  ? CmpInst::FCMP_OEQ
2060  : CmpInst::FCMP_ONE;
2061  Value *FCmp = Builder.CreateFCmp(Pred, Fabs, Infinity, "cmpinf");
2062  return RValue::get(Builder.CreateZExt(FCmp, ConvertType(E->getType())));
2063  }
2064 
2065  case Builtin::BI__builtin_isinf_sign: {
2066  // isinf_sign(x) -> fabs(x) == infinity ? (signbit(x) ? -1 : 1) : 0
2067  Value *Arg = EmitScalarExpr(E->getArg(0));
2068  Value *AbsArg = EmitFAbs(*this, Arg);
2069  Value *IsInf = Builder.CreateFCmpOEQ(
2070  AbsArg, ConstantFP::getInfinity(Arg->getType()), "isinf");
2071  Value *IsNeg = EmitSignBit(*this, Arg);
2072 
2073  llvm::Type *IntTy = ConvertType(E->getType());
2074  Value *Zero = Constant::getNullValue(IntTy);
2075  Value *One = ConstantInt::get(IntTy, 1);
2076  Value *NegativeOne = ConstantInt::get(IntTy, -1);
2077  Value *SignResult = Builder.CreateSelect(IsNeg, NegativeOne, One);
2078  Value *Result = Builder.CreateSelect(IsInf, SignResult, Zero);
2079  return RValue::get(Result);
2080  }
2081 
2082  case Builtin::BI__builtin_isnormal: {
2083  // isnormal(x) --> x == x && fabsf(x) < infinity && fabsf(x) >= float_min
2084  Value *V = EmitScalarExpr(E->getArg(0));
2085  Value *Eq = Builder.CreateFCmpOEQ(V, V, "iseq");
2086 
2087  Value *Abs = EmitFAbs(*this, V);
2088  Value *IsLessThanInf =
2089  Builder.CreateFCmpULT(Abs, ConstantFP::getInfinity(V->getType()),"isinf");
2090  APFloat Smallest = APFloat::getSmallestNormalized(
2091  getContext().getFloatTypeSemantics(E->getArg(0)->getType()));
2092  Value *IsNormal =
2093  Builder.CreateFCmpUGE(Abs, ConstantFP::get(V->getContext(), Smallest),
2094  "isnormal");
2095  V = Builder.CreateAnd(Eq, IsLessThanInf, "and");
2096  V = Builder.CreateAnd(V, IsNormal, "and");
2097  return RValue::get(Builder.CreateZExt(V, ConvertType(E->getType())));
2098  }
2099 
2100  case Builtin::BI__builtin_fpclassify: {
2101  Value *V = EmitScalarExpr(E->getArg(5));
2102  llvm::Type *Ty = ConvertType(E->getArg(5)->getType());
2103 
2104  // Create Result
2105  BasicBlock *Begin = Builder.GetInsertBlock();
2106  BasicBlock *End = createBasicBlock("fpclassify_end", this->CurFn);
2107  Builder.SetInsertPoint(End);
2108  PHINode *Result =
2109  Builder.CreatePHI(ConvertType(E->getArg(0)->getType()), 4,
2110  "fpclassify_result");
2111 
2112  // if (V==0) return FP_ZERO
2113  Builder.SetInsertPoint(Begin);
2114  Value *IsZero = Builder.CreateFCmpOEQ(V, Constant::getNullValue(Ty),
2115  "iszero");
2116  Value *ZeroLiteral = EmitScalarExpr(E->getArg(4));
2117  BasicBlock *NotZero = createBasicBlock("fpclassify_not_zero", this->CurFn);
2118  Builder.CreateCondBr(IsZero, End, NotZero);
2119  Result->addIncoming(ZeroLiteral, Begin);
2120 
2121  // if (V != V) return FP_NAN
2122  Builder.SetInsertPoint(NotZero);
2123  Value *IsNan = Builder.CreateFCmpUNO(V, V, "cmp");
2124  Value *NanLiteral = EmitScalarExpr(E->getArg(0));
2125  BasicBlock *NotNan = createBasicBlock("fpclassify_not_nan", this->CurFn);
2126  Builder.CreateCondBr(IsNan, End, NotNan);
2127  Result->addIncoming(NanLiteral, NotZero);
2128 
2129  // if (fabs(V) == infinity) return FP_INFINITY
2130  Builder.SetInsertPoint(NotNan);
2131  Value *VAbs = EmitFAbs(*this, V);
2132  Value *IsInf =
2133  Builder.CreateFCmpOEQ(VAbs, ConstantFP::getInfinity(V->getType()),
2134  "isinf");
2135  Value *InfLiteral = EmitScalarExpr(E->getArg(1));
2136  BasicBlock *NotInf = createBasicBlock("fpclassify_not_inf", this->CurFn);
2137  Builder.CreateCondBr(IsInf, End, NotInf);
2138  Result->addIncoming(InfLiteral, NotNan);
2139 
2140  // if (fabs(V) >= MIN_NORMAL) return FP_NORMAL else FP_SUBNORMAL
2141  Builder.SetInsertPoint(NotInf);
2142  APFloat Smallest = APFloat::getSmallestNormalized(
2143  getContext().getFloatTypeSemantics(E->getArg(5)->getType()));
2144  Value *IsNormal =
2145  Builder.CreateFCmpUGE(VAbs, ConstantFP::get(V->getContext(), Smallest),
2146  "isnormal");
2147  Value *NormalResult =
2148  Builder.CreateSelect(IsNormal, EmitScalarExpr(E->getArg(2)),
2149  EmitScalarExpr(E->getArg(3)));
2150  Builder.CreateBr(End);
2151  Result->addIncoming(NormalResult, NotInf);
2152 
2153  // return Result
2154  Builder.SetInsertPoint(End);
2155  return RValue::get(Result);
2156  }
2157 
2158  case Builtin::BIalloca:
2159  case Builtin::BI_alloca:
2160  case Builtin::BI__builtin_alloca: {
2161  Value *Size = EmitScalarExpr(E->getArg(0));
2162  const TargetInfo &TI = getContext().getTargetInfo();
2163  // The alignment of the alloca should correspond to __BIGGEST_ALIGNMENT__.
2164  unsigned SuitableAlignmentInBytes =
2165  CGM.getContext()
2166  .toCharUnitsFromBits(TI.getSuitableAlign())
2167  .getQuantity();
2168  AllocaInst *AI = Builder.CreateAlloca(Builder.getInt8Ty(), Size);
2169  AI->setAlignment(SuitableAlignmentInBytes);
2170  return RValue::get(AI);
2171  }
2172 
2173  case Builtin::BI__builtin_alloca_with_align: {
2174  Value *Size = EmitScalarExpr(E->getArg(0));
2175  Value *AlignmentInBitsValue = EmitScalarExpr(E->getArg(1));
2176  auto *AlignmentInBitsCI = cast<ConstantInt>(AlignmentInBitsValue);
2177  unsigned AlignmentInBits = AlignmentInBitsCI->getZExtValue();
2178  unsigned AlignmentInBytes =
2179  CGM.getContext().toCharUnitsFromBits(AlignmentInBits).getQuantity();
2180  AllocaInst *AI = Builder.CreateAlloca(Builder.getInt8Ty(), Size);
2181  AI->setAlignment(AlignmentInBytes);
2182  return RValue::get(AI);
2183  }
2184 
2185  case Builtin::BIbzero:
2186  case Builtin::BI__builtin_bzero: {
2187  Address Dest = EmitPointerWithAlignment(E->getArg(0));
2188  Value *SizeVal = EmitScalarExpr(E->getArg(1));
2189  EmitNonNullArgCheck(RValue::get(Dest.getPointer()), E->getArg(0)->getType(),
2190  E->getArg(0)->getExprLoc(), FD, 0);
2191  Builder.CreateMemSet(Dest, Builder.getInt8(0), SizeVal, false);
2192  return RValue::get(nullptr);
2193  }
2194  case Builtin::BImemcpy:
2195  case Builtin::BI__builtin_memcpy: {
2196  Address Dest = EmitPointerWithAlignment(E->getArg(0));
2197  Address Src = EmitPointerWithAlignment(E->getArg(1));
2198  Value *SizeVal = EmitScalarExpr(E->getArg(2));
2199  EmitNonNullArgCheck(RValue::get(Dest.getPointer()), E->getArg(0)->getType(),
2200  E->getArg(0)->getExprLoc(), FD, 0);
2201  EmitNonNullArgCheck(RValue::get(Src.getPointer()), E->getArg(1)->getType(),
2202  E->getArg(1)->getExprLoc(), FD, 1);
2203  Builder.CreateMemCpy(Dest, Src, SizeVal, false);
2204  return RValue::get(Dest.getPointer());
2205  }
2206 
2207  case Builtin::BI__builtin_char_memchr:
2208  BuiltinID = Builtin::BI__builtin_memchr;
2209  break;
2210 
2211  case Builtin::BI__builtin___memcpy_chk: {
2212  // fold __builtin_memcpy_chk(x, y, cst1, cst2) to memcpy iff cst1<=cst2.
2213  Expr::EvalResult SizeResult, DstSizeResult;
2214  if (!E->getArg(2)->EvaluateAsInt(SizeResult, CGM.getContext()) ||
2215  !E->getArg(3)->EvaluateAsInt(DstSizeResult, CGM.getContext()))
2216  break;
2217  llvm::APSInt Size = SizeResult.Val.getInt();
2218  llvm::APSInt DstSize = DstSizeResult.Val.getInt();
2219  if (Size.ugt(DstSize))
2220  break;
2221  Address Dest = EmitPointerWithAlignment(E->getArg(0));
2222  Address Src = EmitPointerWithAlignment(E->getArg(1));
2223  Value *SizeVal = llvm::ConstantInt::get(Builder.getContext(), Size);
2224  Builder.CreateMemCpy(Dest, Src, SizeVal, false);
2225  return RValue::get(Dest.getPointer());
2226  }
2227 
2228  case Builtin::BI__builtin_objc_memmove_collectable: {
2229  Address DestAddr = EmitPointerWithAlignment(E->getArg(0));
2230  Address SrcAddr = EmitPointerWithAlignment(E->getArg(1));
2231  Value *SizeVal = EmitScalarExpr(E->getArg(2));
2232  CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this,
2233  DestAddr, SrcAddr, SizeVal);
2234  return RValue::get(DestAddr.getPointer());
2235  }
2236 
2237  case Builtin::BI__builtin___memmove_chk: {
2238  // fold __builtin_memmove_chk(x, y, cst1, cst2) to memmove iff cst1<=cst2.
2239  Expr::EvalResult SizeResult, DstSizeResult;
2240  if (!E->getArg(2)->EvaluateAsInt(SizeResult, CGM.getContext()) ||
2241  !E->getArg(3)->EvaluateAsInt(DstSizeResult, CGM.getContext()))
2242  break;
2243  llvm::APSInt Size = SizeResult.Val.getInt();
2244  llvm::APSInt DstSize = DstSizeResult.Val.getInt();
2245  if (Size.ugt(DstSize))
2246  break;
2247  Address Dest = EmitPointerWithAlignment(E->getArg(0));
2248  Address Src = EmitPointerWithAlignment(E->getArg(1));
2249  Value *SizeVal = llvm::ConstantInt::get(Builder.getContext(), Size);
2250  Builder.CreateMemMove(Dest, Src, SizeVal, false);
2251  return RValue::get(Dest.getPointer());
2252  }
2253 
2254  case Builtin::BImemmove:
2255  case Builtin::BI__builtin_memmove: {
2256  Address Dest = EmitPointerWithAlignment(E->getArg(0));
2257  Address Src = EmitPointerWithAlignment(E->getArg(1));
2258  Value *SizeVal = EmitScalarExpr(E->getArg(2));
2259  EmitNonNullArgCheck(RValue::get(Dest.getPointer()), E->getArg(0)->getType(),
2260  E->getArg(0)->getExprLoc(), FD, 0);
2261  EmitNonNullArgCheck(RValue::get(Src.getPointer()), E->getArg(1)->getType(),
2262  E->getArg(1)->getExprLoc(), FD, 1);
2263  Builder.CreateMemMove(Dest, Src, SizeVal, false);
2264  return RValue::get(Dest.getPointer());
2265  }
2266  case Builtin::BImemset:
2267  case Builtin::BI__builtin_memset: {
2268  Address Dest = EmitPointerWithAlignment(E->getArg(0));
2269  Value *ByteVal = Builder.CreateTrunc(EmitScalarExpr(E->getArg(1)),
2270  Builder.getInt8Ty());
2271  Value *SizeVal = EmitScalarExpr(E->getArg(2));
2272  EmitNonNullArgCheck(RValue::get(Dest.getPointer()), E->getArg(0)->getType(),
2273  E->getArg(0)->getExprLoc(), FD, 0);
2274  Builder.CreateMemSet(Dest, ByteVal, SizeVal, false);
2275  return RValue::get(Dest.getPointer());
2276  }
2277  case Builtin::BI__builtin___memset_chk: {
2278  // fold __builtin_memset_chk(x, y, cst1, cst2) to memset iff cst1<=cst2.
2279  Expr::EvalResult SizeResult, DstSizeResult;
2280  if (!E->getArg(2)->EvaluateAsInt(SizeResult, CGM.getContext()) ||
2281  !E->getArg(3)->EvaluateAsInt(DstSizeResult, CGM.getContext()))
2282  break;
2283  llvm::APSInt Size = SizeResult.Val.getInt();
2284  llvm::APSInt DstSize = DstSizeResult.Val.getInt();
2285  if (Size.ugt(DstSize))
2286  break;
2287  Address Dest = EmitPointerWithAlignment(E->getArg(0));
2288  Value *ByteVal = Builder.CreateTrunc(EmitScalarExpr(E->getArg(1)),
2289  Builder.getInt8Ty());
2290  Value *SizeVal = llvm::ConstantInt::get(Builder.getContext(), Size);
2291  Builder.CreateMemSet(Dest, ByteVal, SizeVal, false);
2292  return RValue::get(Dest.getPointer());
2293  }
2294  case Builtin::BI__builtin_wmemcmp: {
2295  // The MSVC runtime library does not provide a definition of wmemcmp, so we
2296  // need an inline implementation.
2297  if (!getTarget().getTriple().isOSMSVCRT())
2298  break;
2299 
2300  llvm::Type *WCharTy = ConvertType(getContext().WCharTy);
2301 
2302  Value *Dst = EmitScalarExpr(E->getArg(0));
2303  Value *Src = EmitScalarExpr(E->getArg(1));
2304  Value *Size = EmitScalarExpr(E->getArg(2));
2305 
2306  BasicBlock *Entry = Builder.GetInsertBlock();
2307  BasicBlock *CmpGT = createBasicBlock("wmemcmp.gt");
2308  BasicBlock *CmpLT = createBasicBlock("wmemcmp.lt");
2309  BasicBlock *Next = createBasicBlock("wmemcmp.next");
2310  BasicBlock *Exit = createBasicBlock("wmemcmp.exit");
2311  Value *SizeEq0 = Builder.CreateICmpEQ(Size, ConstantInt::get(SizeTy, 0));
2312  Builder.CreateCondBr(SizeEq0, Exit, CmpGT);
2313 
2314  EmitBlock(CmpGT);
2315  PHINode *DstPhi = Builder.CreatePHI(Dst->getType(), 2);
2316  DstPhi->addIncoming(Dst, Entry);
2317  PHINode *SrcPhi = Builder.CreatePHI(Src->getType(), 2);
2318  SrcPhi->addIncoming(Src, Entry);
2319  PHINode *SizePhi = Builder.CreatePHI(SizeTy, 2);
2320  SizePhi->addIncoming(Size, Entry);
2321  CharUnits WCharAlign =
2322  getContext().getTypeAlignInChars(getContext().WCharTy);
2323  Value *DstCh = Builder.CreateAlignedLoad(WCharTy, DstPhi, WCharAlign);
2324  Value *SrcCh = Builder.CreateAlignedLoad(WCharTy, SrcPhi, WCharAlign);
2325  Value *DstGtSrc = Builder.CreateICmpUGT(DstCh, SrcCh);
2326  Builder.CreateCondBr(DstGtSrc, Exit, CmpLT);
2327 
2328  EmitBlock(CmpLT);
2329  Value *DstLtSrc = Builder.CreateICmpULT(DstCh, SrcCh);
2330  Builder.CreateCondBr(DstLtSrc, Exit, Next);
2331 
2332  EmitBlock(Next);
2333  Value *NextDst = Builder.CreateConstInBoundsGEP1_32(WCharTy, DstPhi, 1);
2334  Value *NextSrc = Builder.CreateConstInBoundsGEP1_32(WCharTy, SrcPhi, 1);
2335  Value *NextSize = Builder.CreateSub(SizePhi, ConstantInt::get(SizeTy, 1));
2336  Value *NextSizeEq0 =
2337  Builder.CreateICmpEQ(NextSize, ConstantInt::get(SizeTy, 0));
2338  Builder.CreateCondBr(NextSizeEq0, Exit, CmpGT);
2339  DstPhi->addIncoming(NextDst, Next);
2340  SrcPhi->addIncoming(NextSrc, Next);
2341  SizePhi->addIncoming(NextSize, Next);
2342 
2343  EmitBlock(Exit);
2344  PHINode *Ret = Builder.CreatePHI(IntTy, 4);
2345  Ret->addIncoming(ConstantInt::get(IntTy, 0), Entry);
2346  Ret->addIncoming(ConstantInt::get(IntTy, 1), CmpGT);
2347  Ret->addIncoming(ConstantInt::get(IntTy, -1), CmpLT);
2348  Ret->addIncoming(ConstantInt::get(IntTy, 0), Next);
2349  return RValue::get(Ret);
2350  }
2351  case Builtin::BI__builtin_dwarf_cfa: {
2352  // The offset in bytes from the first argument to the CFA.
2353  //
2354  // Why on earth is this in the frontend? Is there any reason at
2355  // all that the backend can't reasonably determine this while
2356  // lowering llvm.eh.dwarf.cfa()?
2357  //
2358  // TODO: If there's a satisfactory reason, add a target hook for
2359  // this instead of hard-coding 0, which is correct for most targets.
2360  int32_t Offset = 0;
2361 
2362  Value *F = CGM.getIntrinsic(Intrinsic::eh_dwarf_cfa);
2363  return RValue::get(Builder.CreateCall(F,
2364  llvm::ConstantInt::get(Int32Ty, Offset)));
2365  }
2366  case Builtin::BI__builtin_return_address: {
2367  Value *Depth = ConstantEmitter(*this).emitAbstract(E->getArg(0),
2368  getContext().UnsignedIntTy);
2369  Value *F = CGM.getIntrinsic(Intrinsic::returnaddress);
2370  return RValue::get(Builder.CreateCall(F, Depth));
2371  }
2372  case Builtin::BI_ReturnAddress: {
2373  Value *F = CGM.getIntrinsic(Intrinsic::returnaddress);
2374  return RValue::get(Builder.CreateCall(F, Builder.getInt32(0)));
2375  }
2376  case Builtin::BI__builtin_frame_address: {
2377  Value *Depth = ConstantEmitter(*this).emitAbstract(E->getArg(0),
2378  getContext().UnsignedIntTy);
2379  Value *F = CGM.getIntrinsic(Intrinsic::frameaddress);
2380  return RValue::get(Builder.CreateCall(F, Depth));
2381  }
2382  case Builtin::BI__builtin_extract_return_addr: {
2383  Value *Address = EmitScalarExpr(E->getArg(0));
2384  Value *Result = getTargetHooks().decodeReturnAddress(*this, Address);
2385  return RValue::get(Result);
2386  }
2387  case Builtin::BI__builtin_frob_return_addr: {
2388  Value *Address = EmitScalarExpr(E->getArg(0));
2389  Value *Result = getTargetHooks().encodeReturnAddress(*this, Address);
2390  return RValue::get(Result);
2391  }
2392  case Builtin::BI__builtin_dwarf_sp_column: {
2393  llvm::IntegerType *Ty
2394  = cast<llvm::IntegerType>(ConvertType(E->getType()));
2395  int Column = getTargetHooks().getDwarfEHStackPointer(CGM);
2396  if (Column == -1) {
2397  CGM.ErrorUnsupported(E, "__builtin_dwarf_sp_column");
2398  return RValue::get(llvm::UndefValue::get(Ty));
2399  }
2400  return RValue::get(llvm::ConstantInt::get(Ty, Column, true));
2401  }
2402  case Builtin::BI__builtin_init_dwarf_reg_size_table: {
2403  Value *Address = EmitScalarExpr(E->getArg(0));
2404  if (getTargetHooks().initDwarfEHRegSizeTable(*this, Address))
2405  CGM.ErrorUnsupported(E, "__builtin_init_dwarf_reg_size_table");
2406  return RValue::get(llvm::UndefValue::get(ConvertType(E->getType())));
2407  }
2408  case Builtin::BI__builtin_eh_return: {
2409  Value *Int = EmitScalarExpr(E->getArg(0));
2410  Value *Ptr = EmitScalarExpr(E->getArg(1));
2411 
2412  llvm::IntegerType *IntTy = cast<llvm::IntegerType>(Int->getType());
2413  assert((IntTy->getBitWidth() == 32 || IntTy->getBitWidth() == 64) &&
2414  "LLVM's __builtin_eh_return only supports 32- and 64-bit variants");
2415  Value *F = CGM.getIntrinsic(IntTy->getBitWidth() == 32
2416  ? Intrinsic::eh_return_i32
2417  : Intrinsic::eh_return_i64);
2418  Builder.CreateCall(F, {Int, Ptr});
2419  Builder.CreateUnreachable();
2420 
2421  // We do need to preserve an insertion point.
2422  EmitBlock(createBasicBlock("builtin_eh_return.cont"));
2423 
2424  return RValue::get(nullptr);
2425  }
2426  case Builtin::BI__builtin_unwind_init: {
2427  Value *F = CGM.getIntrinsic(Intrinsic::eh_unwind_init);
2428  return RValue::get(Builder.CreateCall(F));
2429  }
2430  case Builtin::BI__builtin_extend_pointer: {
2431  // Extends a pointer to the size of an _Unwind_Word, which is
2432  // uint64_t on all platforms. Generally this gets poked into a
2433  // register and eventually used as an address, so if the
2434  // addressing registers are wider than pointers and the platform
2435  // doesn't implicitly ignore high-order bits when doing
2436  // addressing, we need to make sure we zext / sext based on
2437  // the platform's expectations.
2438  //
2439  // See: http://gcc.gnu.org/ml/gcc-bugs/2002-02/msg00237.html
2440 
2441  // Cast the pointer to intptr_t.
2442  Value *Ptr = EmitScalarExpr(E->getArg(0));
2443  Value *Result = Builder.CreatePtrToInt(Ptr, IntPtrTy, "extend.cast");
2444 
2445  // If that's 64 bits, we're done.
2446  if (IntPtrTy->getBitWidth() == 64)
2447  return RValue::get(Result);
2448 
2449  // Otherwise, ask the codegen data what to do.
2450  if (getTargetHooks().extendPointerWithSExt())
2451  return RValue::get(Builder.CreateSExt(Result, Int64Ty, "extend.sext"));
2452  else
2453  return RValue::get(Builder.CreateZExt(Result, Int64Ty, "extend.zext"));
2454  }
2455  case Builtin::BI__builtin_setjmp: {
2456  // Buffer is a void**.
2457  Address Buf = EmitPointerWithAlignment(E->getArg(0));
2458 
2459  // Store the frame pointer to the setjmp buffer.
2460  Value *FrameAddr =
2461  Builder.CreateCall(CGM.getIntrinsic(Intrinsic::frameaddress),
2462  ConstantInt::get(Int32Ty, 0));
2463  Builder.CreateStore(FrameAddr, Buf);
2464 
2465  // Store the stack pointer to the setjmp buffer.
2466  Value *StackAddr =
2467  Builder.CreateCall(CGM.getIntrinsic(Intrinsic::stacksave));
2468  Address StackSaveSlot =
2469  Builder.CreateConstInBoundsGEP(Buf, 2, getPointerSize());
2470  Builder.CreateStore(StackAddr, StackSaveSlot);
2471 
2472  // Call LLVM's EH setjmp, which is lightweight.
2473  Value *F = CGM.getIntrinsic(Intrinsic::eh_sjlj_setjmp);
2474  Buf = Builder.CreateBitCast(Buf, Int8PtrTy);
2475  return RValue::get(Builder.CreateCall(F, Buf.getPointer()));
2476  }
2477  case Builtin::BI__builtin_longjmp: {
2478  Value *Buf = EmitScalarExpr(E->getArg(0));
2479  Buf = Builder.CreateBitCast(Buf, Int8PtrTy);
2480 
2481  // Call LLVM's EH longjmp, which is lightweight.
2482  Builder.CreateCall(CGM.getIntrinsic(Intrinsic::eh_sjlj_longjmp), Buf);
2483 
2484  // longjmp doesn't return; mark this as unreachable.
2485  Builder.CreateUnreachable();
2486 
2487  // We do need to preserve an insertion point.
2488  EmitBlock(createBasicBlock("longjmp.cont"));
2489 
2490  return RValue::get(nullptr);
2491  }
2492  case Builtin::BI__sync_fetch_and_add:
2493  case Builtin::BI__sync_fetch_and_sub:
2494  case Builtin::BI__sync_fetch_and_or:
2495  case Builtin::BI__sync_fetch_and_and:
2496  case Builtin::BI__sync_fetch_and_xor:
2497  case Builtin::BI__sync_fetch_and_nand:
2498  case Builtin::BI__sync_add_and_fetch:
2499  case Builtin::BI__sync_sub_and_fetch:
2500  case Builtin::BI__sync_and_and_fetch:
2501  case Builtin::BI__sync_or_and_fetch:
2502  case Builtin::BI__sync_xor_and_fetch:
2503  case Builtin::BI__sync_nand_and_fetch:
2504  case Builtin::BI__sync_val_compare_and_swap:
2505  case Builtin::BI__sync_bool_compare_and_swap:
2506  case Builtin::BI__sync_lock_test_and_set:
2507  case Builtin::BI__sync_lock_release:
2508  case Builtin::BI__sync_swap:
2509  llvm_unreachable("Shouldn't make it through sema");
2510  case Builtin::BI__sync_fetch_and_add_1:
2511  case Builtin::BI__sync_fetch_and_add_2:
2512  case Builtin::BI__sync_fetch_and_add_4:
2513  case Builtin::BI__sync_fetch_and_add_8:
2514  case Builtin::BI__sync_fetch_and_add_16:
2515  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Add, E);
2516  case Builtin::BI__sync_fetch_and_sub_1:
2517  case Builtin::BI__sync_fetch_and_sub_2:
2518  case Builtin::BI__sync_fetch_and_sub_4:
2519  case Builtin::BI__sync_fetch_and_sub_8:
2520  case Builtin::BI__sync_fetch_and_sub_16:
2521  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Sub, E);
2522  case Builtin::BI__sync_fetch_and_or_1:
2523  case Builtin::BI__sync_fetch_and_or_2:
2524  case Builtin::BI__sync_fetch_and_or_4:
2525  case Builtin::BI__sync_fetch_and_or_8:
2526  case Builtin::BI__sync_fetch_and_or_16:
2527  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Or, E);
2528  case Builtin::BI__sync_fetch_and_and_1:
2529  case Builtin::BI__sync_fetch_and_and_2:
2530  case Builtin::BI__sync_fetch_and_and_4:
2531  case Builtin::BI__sync_fetch_and_and_8:
2532  case Builtin::BI__sync_fetch_and_and_16:
2533  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::And, E);
2534  case Builtin::BI__sync_fetch_and_xor_1:
2535  case Builtin::BI__sync_fetch_and_xor_2:
2536  case Builtin::BI__sync_fetch_and_xor_4:
2537  case Builtin::BI__sync_fetch_and_xor_8:
2538  case Builtin::BI__sync_fetch_and_xor_16:
2539  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Xor, E);
2540  case Builtin::BI__sync_fetch_and_nand_1:
2541  case Builtin::BI__sync_fetch_and_nand_2:
2542  case Builtin::BI__sync_fetch_and_nand_4:
2543  case Builtin::BI__sync_fetch_and_nand_8:
2544  case Builtin::BI__sync_fetch_and_nand_16:
2545  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Nand, E);
2546 
2547  // Clang extensions: not overloaded yet.
2548  case Builtin::BI__sync_fetch_and_min:
2549  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Min, E);
2550  case Builtin::BI__sync_fetch_and_max:
2551  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Max, E);
2552  case Builtin::BI__sync_fetch_and_umin:
2553  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::UMin, E);
2554  case Builtin::BI__sync_fetch_and_umax:
2555  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::UMax, E);
2556 
2557  case Builtin::BI__sync_add_and_fetch_1:
2558  case Builtin::BI__sync_add_and_fetch_2:
2559  case Builtin::BI__sync_add_and_fetch_4:
2560  case Builtin::BI__sync_add_and_fetch_8:
2561  case Builtin::BI__sync_add_and_fetch_16:
2562  return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Add, E,
2563  llvm::Instruction::Add);
2564  case Builtin::BI__sync_sub_and_fetch_1:
2565  case Builtin::BI__sync_sub_and_fetch_2:
2566  case Builtin::BI__sync_sub_and_fetch_4:
2567  case Builtin::BI__sync_sub_and_fetch_8:
2568  case Builtin::BI__sync_sub_and_fetch_16:
2569  return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Sub, E,
2570  llvm::Instruction::Sub);
2571  case Builtin::BI__sync_and_and_fetch_1:
2572  case Builtin::BI__sync_and_and_fetch_2:
2573  case Builtin::BI__sync_and_and_fetch_4:
2574  case Builtin::BI__sync_and_and_fetch_8:
2575  case Builtin::BI__sync_and_and_fetch_16:
2578  case Builtin::BI__sync_or_and_fetch_1:
2579  case Builtin::BI__sync_or_and_fetch_2:
2580  case Builtin::BI__sync_or_and_fetch_4:
2581  case Builtin::BI__sync_or_and_fetch_8:
2582  case Builtin::BI__sync_or_and_fetch_16:
2583  return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Or, E,
2584  llvm::Instruction::Or);
2585  case Builtin::BI__sync_xor_and_fetch_1:
2586  case Builtin::BI__sync_xor_and_fetch_2:
2587  case Builtin::BI__sync_xor_and_fetch_4:
2588  case Builtin::BI__sync_xor_and_fetch_8:
2589  case Builtin::BI__sync_xor_and_fetch_16:
2590  return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Xor, E,
2591  llvm::Instruction::Xor);
2592  case Builtin::BI__sync_nand_and_fetch_1:
2593  case Builtin::BI__sync_nand_and_fetch_2:
2594  case Builtin::BI__sync_nand_and_fetch_4:
2595  case Builtin::BI__sync_nand_and_fetch_8:
2596  case Builtin::BI__sync_nand_and_fetch_16:
2597  return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Nand, E,
2598  llvm::Instruction::And, true);
2599 
2600  case Builtin::BI__sync_val_compare_and_swap_1:
2601  case Builtin::BI__sync_val_compare_and_swap_2:
2602  case Builtin::BI__sync_val_compare_and_swap_4:
2603  case Builtin::BI__sync_val_compare_and_swap_8:
2604  case Builtin::BI__sync_val_compare_and_swap_16:
2605  return RValue::get(MakeAtomicCmpXchgValue(*this, E, false));
2606 
2607  case Builtin::BI__sync_bool_compare_and_swap_1:
2608  case Builtin::BI__sync_bool_compare_and_swap_2:
2609  case Builtin::BI__sync_bool_compare_and_swap_4:
2610  case Builtin::BI__sync_bool_compare_and_swap_8:
2611  case Builtin::BI__sync_bool_compare_and_swap_16:
2612  return RValue::get(MakeAtomicCmpXchgValue(*this, E, true));
2613 
2614  case Builtin::BI__sync_swap_1:
2615  case Builtin::BI__sync_swap_2:
2616  case Builtin::BI__sync_swap_4:
2617  case Builtin::BI__sync_swap_8:
2618  case Builtin::BI__sync_swap_16:
2619  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Xchg, E);
2620 
2621  case Builtin::BI__sync_lock_test_and_set_1:
2622  case Builtin::BI__sync_lock_test_and_set_2:
2623  case Builtin::BI__sync_lock_test_and_set_4:
2624  case Builtin::BI__sync_lock_test_and_set_8:
2625  case Builtin::BI__sync_lock_test_and_set_16:
2626  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Xchg, E);
2627 
2628  case Builtin::BI__sync_lock_release_1:
2629  case Builtin::BI__sync_lock_release_2:
2630  case Builtin::BI__sync_lock_release_4:
2631  case Builtin::BI__sync_lock_release_8:
2632  case Builtin::BI__sync_lock_release_16: {
2633  Value *Ptr = EmitScalarExpr(E->getArg(0));
2634  QualType ElTy = E->getArg(0)->getType()->getPointeeType();
2635  CharUnits StoreSize = getContext().getTypeSizeInChars(ElTy);
2636  llvm::Type *ITy = llvm::IntegerType::get(getLLVMContext(),
2637  StoreSize.getQuantity() * 8);
2638  Ptr = Builder.CreateBitCast(Ptr, ITy->getPointerTo());
2639  llvm::StoreInst *Store =
2640  Builder.CreateAlignedStore(llvm::Constant::getNullValue(ITy), Ptr,
2641  StoreSize);
2642  Store->setAtomic(llvm::AtomicOrdering::Release);
2643  return RValue::get(nullptr);
2644  }
2645 
2646  case Builtin::BI__sync_synchronize: {
2647  // We assume this is supposed to correspond to a C++0x-style
2648  // sequentially-consistent fence (i.e. this is only usable for
2649  // synchronization, not device I/O or anything like that). This intrinsic
2650  // is really badly designed in the sense that in theory, there isn't
2651  // any way to safely use it... but in practice, it mostly works
2652  // to use it with non-atomic loads and stores to get acquire/release
2653  // semantics.
2654  Builder.CreateFence(llvm::AtomicOrdering::SequentiallyConsistent);
2655  return RValue::get(nullptr);
2656  }
2657 
2658  case Builtin::BI__builtin_nontemporal_load:
2659  return RValue::get(EmitNontemporalLoad(*this, E));
2660  case Builtin::BI__builtin_nontemporal_store:
2661  return RValue::get(EmitNontemporalStore(*this, E));
2662  case Builtin::BI__c11_atomic_is_lock_free:
2663  case Builtin::BI__atomic_is_lock_free: {
2664  // Call "bool __atomic_is_lock_free(size_t size, void *ptr)". For the
2665  // __c11 builtin, ptr is 0 (indicating a properly-aligned object), since
2666  // _Atomic(T) is always properly-aligned.
2667  const char *LibCallName = "__atomic_is_lock_free";
2668  CallArgList Args;
2669  Args.add(RValue::get(EmitScalarExpr(E->getArg(0))),
2670  getContext().getSizeType());
2671  if (BuiltinID == Builtin::BI__atomic_is_lock_free)
2672  Args.add(RValue::get(EmitScalarExpr(E->getArg(1))),
2673  getContext().VoidPtrTy);
2674  else
2675  Args.add(RValue::get(llvm::Constant::getNullValue(VoidPtrTy)),
2676  getContext().VoidPtrTy);
2677  const CGFunctionInfo &FuncInfo =
2678  CGM.getTypes().arrangeBuiltinFunctionCall(E->getType(), Args);
2679  llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FuncInfo);
2680  llvm::Constant *Func = CGM.CreateRuntimeFunction(FTy, LibCallName);
2681  return EmitCall(FuncInfo, CGCallee::forDirect(Func),
2682  ReturnValueSlot(), Args);
2683  }
2684 
2685  case Builtin::BI__atomic_test_and_set: {
2686  // Look at the argument type to determine whether this is a volatile
2687  // operation. The parameter type is always volatile.
2688  QualType PtrTy = E->getArg(0)->IgnoreImpCasts()->getType();
2689  bool Volatile =
2690  PtrTy->castAs<PointerType>()->getPointeeType().isVolatileQualified();
2691 
2692  Value *Ptr = EmitScalarExpr(E->getArg(0));
2693  unsigned AddrSpace = Ptr->getType()->getPointerAddressSpace();
2694  Ptr = Builder.CreateBitCast(Ptr, Int8Ty->getPointerTo(AddrSpace));
2695  Value *NewVal = Builder.getInt8(1);
2696  Value *Order = EmitScalarExpr(E->getArg(1));
2697  if (isa<llvm::ConstantInt>(Order)) {
2698  int ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
2699  AtomicRMWInst *Result = nullptr;
2700  switch (ord) {
2701  case 0: // memory_order_relaxed
2702  default: // invalid order
2703  Result = Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg, Ptr, NewVal,
2704  llvm::AtomicOrdering::Monotonic);
2705  break;
2706  case 1: // memory_order_consume
2707  case 2: // memory_order_acquire
2708  Result = Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg, Ptr, NewVal,
2709  llvm::AtomicOrdering::Acquire);
2710  break;
2711  case 3: // memory_order_release
2712  Result = Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg, Ptr, NewVal,
2713  llvm::AtomicOrdering::Release);
2714  break;
2715  case 4: // memory_order_acq_rel
2716 
2717  Result = Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg, Ptr, NewVal,
2718  llvm::AtomicOrdering::AcquireRelease);
2719  break;
2720  case 5: // memory_order_seq_cst
2721  Result = Builder.CreateAtomicRMW(
2722  llvm::AtomicRMWInst::Xchg, Ptr, NewVal,
2723  llvm::AtomicOrdering::SequentiallyConsistent);
2724  break;
2725  }
2726  Result->setVolatile(Volatile);
2727  return RValue::get(Builder.CreateIsNotNull(Result, "tobool"));
2728  }
2729 
2730  llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
2731 
2732  llvm::BasicBlock *BBs[5] = {
2733  createBasicBlock("monotonic", CurFn),
2734  createBasicBlock("acquire", CurFn),
2735  createBasicBlock("release", CurFn),
2736  createBasicBlock("acqrel", CurFn),
2737  createBasicBlock("seqcst", CurFn)
2738  };
2739  llvm::AtomicOrdering Orders[5] = {
2740  llvm::AtomicOrdering::Monotonic, llvm::AtomicOrdering::Acquire,
2741  llvm::AtomicOrdering::Release, llvm::AtomicOrdering::AcquireRelease,
2742  llvm::AtomicOrdering::SequentiallyConsistent};
2743 
2744  Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
2745  llvm::SwitchInst *SI = Builder.CreateSwitch(Order, BBs[0]);
2746 
2747  Builder.SetInsertPoint(ContBB);
2748  PHINode *Result = Builder.CreatePHI(Int8Ty, 5, "was_set");
2749 
2750  for (unsigned i = 0; i < 5; ++i) {
2751  Builder.SetInsertPoint(BBs[i]);
2752  AtomicRMWInst *RMW = Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg,
2753  Ptr, NewVal, Orders[i]);
2754  RMW->setVolatile(Volatile);
2755  Result->addIncoming(RMW, BBs[i]);
2756  Builder.CreateBr(ContBB);
2757  }
2758 
2759  SI->addCase(Builder.getInt32(0), BBs[0]);
2760  SI->addCase(Builder.getInt32(1), BBs[1]);
2761  SI->addCase(Builder.getInt32(2), BBs[1]);
2762  SI->addCase(Builder.getInt32(3), BBs[2]);
2763  SI->addCase(Builder.getInt32(4), BBs[3]);
2764  SI->addCase(Builder.getInt32(5), BBs[4]);
2765 
2766  Builder.SetInsertPoint(ContBB);
2767  return RValue::get(Builder.CreateIsNotNull(Result, "tobool"));
2768  }
2769 
2770  case Builtin::BI__atomic_clear: {
2771  QualType PtrTy = E->getArg(0)->IgnoreImpCasts()->getType();
2772  bool Volatile =
2773  PtrTy->castAs<PointerType>()->getPointeeType().isVolatileQualified();
2774 
2775  Address Ptr = EmitPointerWithAlignment(E->getArg(0));
2776  unsigned AddrSpace = Ptr.getPointer()->getType()->getPointerAddressSpace();
2777  Ptr = Builder.CreateBitCast(Ptr, Int8Ty->getPointerTo(AddrSpace));
2778  Value *NewVal = Builder.getInt8(0);
2779  Value *Order = EmitScalarExpr(E->getArg(1));
2780  if (isa<llvm::ConstantInt>(Order)) {
2781  int ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
2782  StoreInst *Store = Builder.CreateStore(NewVal, Ptr, Volatile);
2783  switch (ord) {
2784  case 0: // memory_order_relaxed
2785  default: // invalid order
2786  Store->setOrdering(llvm::AtomicOrdering::Monotonic);
2787  break;
2788  case 3: // memory_order_release
2789  Store->setOrdering(llvm::AtomicOrdering::Release);
2790  break;
2791  case 5: // memory_order_seq_cst
2792  Store->setOrdering(llvm::AtomicOrdering::SequentiallyConsistent);
2793  break;
2794  }
2795  return RValue::get(nullptr);
2796  }
2797 
2798  llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
2799 
2800  llvm::BasicBlock *BBs[3] = {
2801  createBasicBlock("monotonic", CurFn),
2802  createBasicBlock("release", CurFn),
2803  createBasicBlock("seqcst", CurFn)
2804  };
2805  llvm::AtomicOrdering Orders[3] = {
2806  llvm::AtomicOrdering::Monotonic, llvm::AtomicOrdering::Release,
2807  llvm::AtomicOrdering::SequentiallyConsistent};
2808 
2809  Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
2810  llvm::SwitchInst *SI = Builder.CreateSwitch(Order, BBs[0]);
2811 
2812  for (unsigned i = 0; i < 3; ++i) {
2813  Builder.SetInsertPoint(BBs[i]);
2814  StoreInst *Store = Builder.CreateStore(NewVal, Ptr, Volatile);
2815  Store->setOrdering(Orders[i]);
2816  Builder.CreateBr(ContBB);
2817  }
2818 
2819  SI->addCase(Builder.getInt32(0), BBs[0]);
2820  SI->addCase(Builder.getInt32(3), BBs[1]);
2821  SI->addCase(Builder.getInt32(5), BBs[2]);
2822 
2823  Builder.SetInsertPoint(ContBB);
2824  return RValue::get(nullptr);
2825  }
2826 
2827  case Builtin::BI__atomic_thread_fence:
2828  case Builtin::BI__atomic_signal_fence:
2829  case Builtin::BI__c11_atomic_thread_fence:
2830  case Builtin::BI__c11_atomic_signal_fence: {
2831  llvm::SyncScope::ID SSID;
2832  if (BuiltinID == Builtin::BI__atomic_signal_fence ||
2833  BuiltinID == Builtin::BI__c11_atomic_signal_fence)
2834  SSID = llvm::SyncScope::SingleThread;
2835  else
2836  SSID = llvm::SyncScope::System;
2837  Value *Order = EmitScalarExpr(E->getArg(0));
2838  if (isa<llvm::ConstantInt>(Order)) {
2839  int ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
2840  switch (ord) {
2841  case 0: // memory_order_relaxed
2842  default: // invalid order
2843  break;
2844  case 1: // memory_order_consume
2845  case 2: // memory_order_acquire
2846  Builder.CreateFence(llvm::AtomicOrdering::Acquire, SSID);
2847  break;
2848  case 3: // memory_order_release
2849  Builder.CreateFence(llvm::AtomicOrdering::Release, SSID);
2850  break;
2851  case 4: // memory_order_acq_rel
2852  Builder.CreateFence(llvm::AtomicOrdering::AcquireRelease, SSID);
2853  break;
2854  case 5: // memory_order_seq_cst
2855  Builder.CreateFence(llvm::AtomicOrdering::SequentiallyConsistent, SSID);
2856  break;
2857  }
2858  return RValue::get(nullptr);
2859  }
2860 
2861  llvm::BasicBlock *AcquireBB, *ReleaseBB, *AcqRelBB, *SeqCstBB;
2862  AcquireBB = createBasicBlock("acquire", CurFn);
2863  ReleaseBB = createBasicBlock("release", CurFn);
2864  AcqRelBB = createBasicBlock("acqrel", CurFn);
2865  SeqCstBB = createBasicBlock("seqcst", CurFn);
2866  llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
2867 
2868  Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
2869  llvm::SwitchInst *SI = Builder.CreateSwitch(Order, ContBB);
2870 
2871  Builder.SetInsertPoint(AcquireBB);
2872  Builder.CreateFence(llvm::AtomicOrdering::Acquire, SSID);
2873  Builder.CreateBr(ContBB);
2874  SI->addCase(Builder.getInt32(1), AcquireBB);
2875  SI->addCase(Builder.getInt32(2), AcquireBB);
2876 
2877  Builder.SetInsertPoint(ReleaseBB);
2878  Builder.CreateFence(llvm::AtomicOrdering::Release, SSID);
2879  Builder.CreateBr(ContBB);
2880  SI->addCase(Builder.getInt32(3), ReleaseBB);
2881 
2882  Builder.SetInsertPoint(AcqRelBB);
2883  Builder.CreateFence(llvm::AtomicOrdering::AcquireRelease, SSID);
2884  Builder.CreateBr(ContBB);
2885  SI->addCase(Builder.getInt32(4), AcqRelBB);
2886 
2887  Builder.SetInsertPoint(SeqCstBB);
2888  Builder.CreateFence(llvm::AtomicOrdering::SequentiallyConsistent, SSID);
2889  Builder.CreateBr(ContBB);
2890  SI->addCase(Builder.getInt32(5), SeqCstBB);
2891 
2892  Builder.SetInsertPoint(ContBB);
2893  return RValue::get(nullptr);
2894  }
2895 
2896  case Builtin::BI__builtin_signbit:
2897  case Builtin::BI__builtin_signbitf:
2898  case Builtin::BI__builtin_signbitl: {
2899  return RValue::get(
2900  Builder.CreateZExt(EmitSignBit(*this, EmitScalarExpr(E->getArg(0))),
2901  ConvertType(E->getType())));
2902  }
2903  case Builtin::BI__annotation: {
2904  // Re-encode each wide string to UTF8 and make an MDString.
2906  for (const Expr *Arg : E->arguments()) {
2907  const auto *Str = cast<StringLiteral>(Arg->IgnoreParenCasts());
2908  assert(Str->getCharByteWidth() == 2);
2909  StringRef WideBytes = Str->getBytes();
2910  std::string StrUtf8;
2911  if (!convertUTF16ToUTF8String(
2912  makeArrayRef(WideBytes.data(), WideBytes.size()), StrUtf8)) {
2913  CGM.ErrorUnsupported(E, "non-UTF16 __annotation argument");
2914  continue;
2915  }
2916  Strings.push_back(llvm::MDString::get(getLLVMContext(), StrUtf8));
2917  }
2918 
2919  // Build and MDTuple of MDStrings and emit the intrinsic call.
2920  llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::codeview_annotation, {});
2921  MDTuple *StrTuple = MDTuple::get(getLLVMContext(), Strings);
2922  Builder.CreateCall(F, MetadataAsValue::get(getLLVMContext(), StrTuple));
2923  return RValue::getIgnored();
2924  }
2925  case Builtin::BI__builtin_annotation: {
2926  llvm::Value *AnnVal = EmitScalarExpr(E->getArg(0));
2927  llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::annotation,
2928  AnnVal->getType());
2929 
2930  // Get the annotation string, go through casts. Sema requires this to be a
2931  // non-wide string literal, potentially casted, so the cast<> is safe.
2932  const Expr *AnnotationStrExpr = E->getArg(1)->IgnoreParenCasts();
2933  StringRef Str = cast<StringLiteral>(AnnotationStrExpr)->getString();
2934  return RValue::get(EmitAnnotationCall(F, AnnVal, Str, E->getExprLoc()));
2935  }
2936  case Builtin::BI__builtin_addcb:
2937  case Builtin::BI__builtin_addcs:
2938  case Builtin::BI__builtin_addc:
2939  case Builtin::BI__builtin_addcl:
2940  case Builtin::BI__builtin_addcll:
2941  case Builtin::BI__builtin_subcb:
2942  case Builtin::BI__builtin_subcs:
2943  case Builtin::BI__builtin_subc:
2944  case Builtin::BI__builtin_subcl:
2945  case Builtin::BI__builtin_subcll: {
2946 
2947  // We translate all of these builtins from expressions of the form:
2948  // int x = ..., y = ..., carryin = ..., carryout, result;
2949  // result = __builtin_addc(x, y, carryin, &carryout);
2950  //
2951  // to LLVM IR of the form:
2952  //
2953  // %tmp1 = call {i32, i1} @llvm.uadd.with.overflow.i32(i32 %x, i32 %y)
2954  // %tmpsum1 = extractvalue {i32, i1} %tmp1, 0
2955  // %carry1 = extractvalue {i32, i1} %tmp1, 1
2956  // %tmp2 = call {i32, i1} @llvm.uadd.with.overflow.i32(i32 %tmpsum1,
2957  // i32 %carryin)
2958  // %result = extractvalue {i32, i1} %tmp2, 0
2959  // %carry2 = extractvalue {i32, i1} %tmp2, 1
2960  // %tmp3 = or i1 %carry1, %carry2
2961  // %tmp4 = zext i1 %tmp3 to i32
2962  // store i32 %tmp4, i32* %carryout
2963 
2964  // Scalarize our inputs.
2965  llvm::Value *X = EmitScalarExpr(E->getArg(0));
2966  llvm::Value *Y = EmitScalarExpr(E->getArg(1));
2967  llvm::Value *Carryin = EmitScalarExpr(E->getArg(2));
2968  Address CarryOutPtr = EmitPointerWithAlignment(E->getArg(3));
2969 
2970  // Decide if we are lowering to a uadd.with.overflow or usub.with.overflow.
2971  llvm::Intrinsic::ID IntrinsicId;
2972  switch (BuiltinID) {
2973  default: llvm_unreachable("Unknown multiprecision builtin id.");
2974  case Builtin::BI__builtin_addcb:
2975  case Builtin::BI__builtin_addcs:
2976  case Builtin::BI__builtin_addc:
2977  case Builtin::BI__builtin_addcl:
2978  case Builtin::BI__builtin_addcll:
2979  IntrinsicId = llvm::Intrinsic::uadd_with_overflow;
2980  break;
2981  case Builtin::BI__builtin_subcb:
2982  case Builtin::BI__builtin_subcs:
2983  case Builtin::BI__builtin_subc:
2984  case Builtin::BI__builtin_subcl:
2985  case Builtin::BI__builtin_subcll:
2986  IntrinsicId = llvm::Intrinsic::usub_with_overflow;
2987  break;
2988  }
2989 
2990  // Construct our resulting LLVM IR expression.
2991  llvm::Value *Carry1;
2992  llvm::Value *Sum1 = EmitOverflowIntrinsic(*this, IntrinsicId,
2993  X, Y, Carry1);
2994  llvm::Value *Carry2;
2995  llvm::Value *Sum2 = EmitOverflowIntrinsic(*this, IntrinsicId,
2996  Sum1, Carryin, Carry2);
2997  llvm::Value *CarryOut = Builder.CreateZExt(Builder.CreateOr(Carry1, Carry2),
2998  X->getType());
2999  Builder.CreateStore(CarryOut, CarryOutPtr);
3000  return RValue::get(Sum2);
3001  }
3002 
3003  case Builtin::BI__builtin_add_overflow:
3004  case Builtin::BI__builtin_sub_overflow:
3005  case Builtin::BI__builtin_mul_overflow: {
3006  const clang::Expr *LeftArg = E->getArg(0);
3007  const clang::Expr *RightArg = E->getArg(1);
3008  const clang::Expr *ResultArg = E->getArg(2);
3009 
3010  clang::QualType ResultQTy =
3011  ResultArg->getType()->castAs<PointerType>()->getPointeeType();
3012 
3013  WidthAndSignedness LeftInfo =
3014  getIntegerWidthAndSignedness(CGM.getContext(), LeftArg->getType());
3015  WidthAndSignedness RightInfo =
3016  getIntegerWidthAndSignedness(CGM.getContext(), RightArg->getType());
3017  WidthAndSignedness ResultInfo =
3018  getIntegerWidthAndSignedness(CGM.getContext(), ResultQTy);
3019 
3020  // Handle mixed-sign multiplication as a special case, because adding
3021  // runtime or backend support for our generic irgen would be too expensive.
3022  if (isSpecialMixedSignMultiply(BuiltinID, LeftInfo, RightInfo, ResultInfo))
3023  return EmitCheckedMixedSignMultiply(*this, LeftArg, LeftInfo, RightArg,
3024  RightInfo, ResultArg, ResultQTy,
3025  ResultInfo);
3026 
3027  WidthAndSignedness EncompassingInfo =
3028  EncompassingIntegerType({LeftInfo, RightInfo, ResultInfo});
3029 
3030  llvm::Type *EncompassingLLVMTy =
3031  llvm::IntegerType::get(CGM.getLLVMContext(), EncompassingInfo.Width);
3032 
3033  llvm::Type *ResultLLVMTy = CGM.getTypes().ConvertType(ResultQTy);
3034 
3035  llvm::Intrinsic::ID IntrinsicId;
3036  switch (BuiltinID) {
3037  default:
3038  llvm_unreachable("Unknown overflow builtin id.");
3039  case Builtin::BI__builtin_add_overflow:
3040  IntrinsicId = EncompassingInfo.Signed
3041  ? llvm::Intrinsic::sadd_with_overflow
3042  : llvm::Intrinsic::uadd_with_overflow;
3043  break;
3044  case Builtin::BI__builtin_sub_overflow:
3045  IntrinsicId = EncompassingInfo.Signed
3046  ? llvm::Intrinsic::ssub_with_overflow
3047  : llvm::Intrinsic::usub_with_overflow;
3048  break;
3049  case Builtin::BI__builtin_mul_overflow:
3050  IntrinsicId = EncompassingInfo.Signed
3051  ? llvm::Intrinsic::smul_with_overflow
3052  : llvm::Intrinsic::umul_with_overflow;
3053  break;
3054  }
3055 
3056  llvm::Value *Left = EmitScalarExpr(LeftArg);
3057  llvm::Value *Right = EmitScalarExpr(RightArg);
3058  Address ResultPtr = EmitPointerWithAlignment(ResultArg);
3059 
3060  // Extend each operand to the encompassing type.
3061  Left = Builder.CreateIntCast(Left, EncompassingLLVMTy, LeftInfo.Signed);
3062  Right = Builder.CreateIntCast(Right, EncompassingLLVMTy, RightInfo.Signed);
3063 
3064  // Perform the operation on the extended values.
3065  llvm::Value *Overflow, *Result;
3066  Result = EmitOverflowIntrinsic(*this, IntrinsicId, Left, Right, Overflow);
3067 
3068  if (EncompassingInfo.Width > ResultInfo.Width) {
3069  // The encompassing type is wider than the result type, so we need to
3070  // truncate it.
3071  llvm::Value *ResultTrunc = Builder.CreateTrunc(Result, ResultLLVMTy);
3072 
3073  // To see if the truncation caused an overflow, we will extend
3074  // the result and then compare it to the original result.
3075  llvm::Value *ResultTruncExt = Builder.CreateIntCast(
3076  ResultTrunc, EncompassingLLVMTy, ResultInfo.Signed);
3077  llvm::Value *TruncationOverflow =
3078  Builder.CreateICmpNE(Result, ResultTruncExt);
3079 
3080  Overflow = Builder.CreateOr(Overflow, TruncationOverflow);
3081  Result = ResultTrunc;
3082  }
3083 
3084  // Finally, store the result using the pointer.
3085  bool isVolatile =
3086  ResultArg->getType()->getPointeeType().isVolatileQualified();
3087  Builder.CreateStore(EmitToMemory(Result, ResultQTy), ResultPtr, isVolatile);
3088 
3089  return RValue::get(Overflow);
3090  }
3091 
3092  case Builtin::BI__builtin_uadd_overflow:
3093  case Builtin::BI__builtin_uaddl_overflow:
3094  case Builtin::BI__builtin_uaddll_overflow:
3095  case Builtin::BI__builtin_usub_overflow:
3096  case Builtin::BI__builtin_usubl_overflow:
3097  case Builtin::BI__builtin_usubll_overflow:
3098  case Builtin::BI__builtin_umul_overflow:
3099  case Builtin::BI__builtin_umull_overflow:
3100  case Builtin::BI__builtin_umulll_overflow:
3101  case Builtin::BI__builtin_sadd_overflow:
3102  case Builtin::BI__builtin_saddl_overflow:
3103  case Builtin::BI__builtin_saddll_overflow:
3104  case Builtin::BI__builtin_ssub_overflow:
3105  case Builtin::BI__builtin_ssubl_overflow:
3106  case Builtin::BI__builtin_ssubll_overflow:
3107  case Builtin::BI__builtin_smul_overflow:
3108  case Builtin::BI__builtin_smull_overflow:
3109  case Builtin::BI__builtin_smulll_overflow: {
3110 
3111  // We translate all of these builtins directly to the relevant llvm IR node.
3112 
3113  // Scalarize our inputs.
3114  llvm::Value *X = EmitScalarExpr(E->getArg(0));
3115  llvm::Value *Y = EmitScalarExpr(E->getArg(1));
3116  Address SumOutPtr = EmitPointerWithAlignment(E->getArg(2));
3117 
3118  // Decide which of the overflow intrinsics we are lowering to:
3119  llvm::Intrinsic::ID IntrinsicId;
3120  switch (BuiltinID) {
3121  default: llvm_unreachable("Unknown overflow builtin id.");
3122  case Builtin::BI__builtin_uadd_overflow:
3123  case Builtin::BI__builtin_uaddl_overflow:
3124  case Builtin::BI__builtin_uaddll_overflow:
3125  IntrinsicId = llvm::Intrinsic::uadd_with_overflow;
3126  break;
3127  case Builtin::BI__builtin_usub_overflow:
3128  case Builtin::BI__builtin_usubl_overflow:
3129  case Builtin::BI__builtin_usubll_overflow:
3130  IntrinsicId = llvm::Intrinsic::usub_with_overflow;
3131  break;
3132  case Builtin::BI__builtin_umul_overflow:
3133  case Builtin::BI__builtin_umull_overflow:
3134  case Builtin::BI__builtin_umulll_overflow:
3135  IntrinsicId = llvm::Intrinsic::umul_with_overflow;
3136  break;
3137  case Builtin::BI__builtin_sadd_overflow:
3138  case Builtin::BI__builtin_saddl_overflow:
3139  case Builtin::BI__builtin_saddll_overflow:
3140  IntrinsicId = llvm::Intrinsic::sadd_with_overflow;
3141  break;
3142  case Builtin::BI__builtin_ssub_overflow:
3143  case Builtin::BI__builtin_ssubl_overflow:
3144  case Builtin::BI__builtin_ssubll_overflow:
3145  IntrinsicId = llvm::Intrinsic::ssub_with_overflow;
3146  break;
3147  case Builtin::BI__builtin_smul_overflow:
3148  case Builtin::BI__builtin_smull_overflow:
3149  case Builtin::BI__builtin_smulll_overflow:
3150  IntrinsicId = llvm::Intrinsic::smul_with_overflow;
3151  break;
3152  }
3153 
3154 
3155  llvm::Value *Carry;
3156  llvm::Value *Sum = EmitOverflowIntrinsic(*this, IntrinsicId, X, Y, Carry);
3157  Builder.CreateStore(Sum, SumOutPtr);
3158 
3159  return RValue::get(Carry);
3160  }
3161  case Builtin::BI__builtin_addressof:
3162  return RValue::get(EmitLValue(E->getArg(0)).getPointer());
3163  case Builtin::BI__builtin_operator_new:
3164  return EmitBuiltinNewDeleteCall(
3165  E->getCallee()->getType()->castAs<FunctionProtoType>(), E, false);
3166  case Builtin::BI__builtin_operator_delete:
3167  return EmitBuiltinNewDeleteCall(
3168  E->getCallee()->getType()->castAs<FunctionProtoType>(), E, true);
3169 
3170  case Builtin::BI__noop:
3171  // __noop always evaluates to an integer literal zero.
3172  return RValue::get(ConstantInt::get(IntTy, 0));
3173  case Builtin::BI__builtin_call_with_static_chain: {
3174  const CallExpr *Call = cast<CallExpr>(E->getArg(0));
3175  const Expr *Chain = E->getArg(1);
3176  return EmitCall(Call->getCallee()->getType(),
3177  EmitCallee(Call->getCallee()), Call, ReturnValue,
3178  EmitScalarExpr(Chain));
3179  }
3180  case Builtin::BI_InterlockedExchange8:
3181  case Builtin::BI_InterlockedExchange16:
3182  case Builtin::BI_InterlockedExchange:
3183  case Builtin::BI_InterlockedExchangePointer:
3184  return RValue::get(
3185  EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedExchange, E));
3186  case Builtin::BI_InterlockedCompareExchangePointer:
3187  case Builtin::BI_InterlockedCompareExchangePointer_nf: {
3188  llvm::Type *RTy;
3189  llvm::IntegerType *IntType =
3190  IntegerType::get(getLLVMContext(),
3191  getContext().getTypeSize(E->getType()));
3192  llvm::Type *IntPtrType = IntType->getPointerTo();
3193 
3194  llvm::Value *Destination =
3195  Builder.CreateBitCast(EmitScalarExpr(E->getArg(0)), IntPtrType);
3196 
3197  llvm::Value *Exchange = EmitScalarExpr(E->getArg(1));
3198  RTy = Exchange->getType();
3199  Exchange = Builder.CreatePtrToInt(Exchange, IntType);
3200 
3201  llvm::Value *Comparand =
3202  Builder.CreatePtrToInt(EmitScalarExpr(E->getArg(2)), IntType);
3203 
3204  auto Ordering =
3205  BuiltinID == Builtin::BI_InterlockedCompareExchangePointer_nf ?
3206  AtomicOrdering::Monotonic : AtomicOrdering::SequentiallyConsistent;
3207 
3208  auto Result = Builder.CreateAtomicCmpXchg(Destination, Comparand, Exchange,
3209  Ordering, Ordering);
3210  Result->setVolatile(true);
3211 
3212  return RValue::get(Builder.CreateIntToPtr(Builder.CreateExtractValue(Result,
3213  0),
3214  RTy));
3215  }
3216  case Builtin::BI_InterlockedCompareExchange8:
3217  case Builtin::BI_InterlockedCompareExchange16:
3218  case Builtin::BI_InterlockedCompareExchange:
3219  case Builtin::BI_InterlockedCompareExchange64:
3220  return RValue::get(EmitAtomicCmpXchgForMSIntrin(*this, E));
3221  case Builtin::BI_InterlockedIncrement16:
3222  case Builtin::BI_InterlockedIncrement:
3223  return RValue::get(
3224  EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedIncrement, E));
3225  case Builtin::BI_InterlockedDecrement16:
3226  case Builtin::BI_InterlockedDecrement:
3227  return RValue::get(
3228  EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedDecrement, E));
3229  case Builtin::BI_InterlockedAnd8:
3230  case Builtin::BI_InterlockedAnd16:
3231  case Builtin::BI_InterlockedAnd:
3232  return RValue::get(EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedAnd, E));
3233  case Builtin::BI_InterlockedExchangeAdd8:
3234  case Builtin::BI_InterlockedExchangeAdd16:
3235  case Builtin::BI_InterlockedExchangeAdd:
3236  return RValue::get(
3237  EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedExchangeAdd, E));
3238  case Builtin::BI_InterlockedExchangeSub8:
3239  case Builtin::BI_InterlockedExchangeSub16:
3240  case Builtin::BI_InterlockedExchangeSub:
3241  return RValue::get(
3242  EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedExchangeSub, E));
3243  case Builtin::BI_InterlockedOr8:
3244  case Builtin::BI_InterlockedOr16:
3245  case Builtin::BI_InterlockedOr:
3246  return RValue::get(EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedOr, E));
3247  case Builtin::BI_InterlockedXor8:
3248  case Builtin::BI_InterlockedXor16:
3249  case Builtin::BI_InterlockedXor:
3250  return RValue::get(EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedXor, E));
3251 
3252  case Builtin::BI_bittest64:
3253  case Builtin::BI_bittest:
3254  case Builtin::BI_bittestandcomplement64:
3255  case Builtin::BI_bittestandcomplement:
3256  case Builtin::BI_bittestandreset64:
3257  case Builtin::BI_bittestandreset:
3258  case Builtin::BI_bittestandset64:
3259  case Builtin::BI_bittestandset:
3260  case Builtin::BI_interlockedbittestandreset:
3261  case Builtin::BI_interlockedbittestandreset64:
3262  case Builtin::BI_interlockedbittestandset64:
3263  case Builtin::BI_interlockedbittestandset:
3264  case Builtin::BI_interlockedbittestandset_acq:
3265  case Builtin::BI_interlockedbittestandset_rel:
3266  case Builtin::BI_interlockedbittestandset_nf:
3267  case Builtin::BI_interlockedbittestandreset_acq:
3268  case Builtin::BI_interlockedbittestandreset_rel:
3269  case Builtin::BI_interlockedbittestandreset_nf:
3270  return RValue::get(EmitBitTestIntrinsic(*this, BuiltinID, E));
3271 
3272  case Builtin::BI__exception_code:
3273  case Builtin::BI_exception_code:
3274  return RValue::get(EmitSEHExceptionCode());
3275  case Builtin::BI__exception_info:
3276  case Builtin::BI_exception_info:
3277  return RValue::get(EmitSEHExceptionInfo());
3278  case Builtin::BI__abnormal_termination:
3279  case Builtin::BI_abnormal_termination:
3280  return RValue::get(EmitSEHAbnormalTermination());
3281  case Builtin::BI_setjmpex:
3282  if (getTarget().getTriple().isOSMSVCRT())
3283  return EmitMSVCRTSetJmp(*this, MSVCSetJmpKind::_setjmpex, E);
3284  break;
3285  case Builtin::BI_setjmp:
3286  if (getTarget().getTriple().isOSMSVCRT()) {
3287  if (getTarget().getTriple().getArch() == llvm::Triple::x86)
3288  return EmitMSVCRTSetJmp(*this, MSVCSetJmpKind::_setjmp3, E);
3289  else if (getTarget().getTriple().getArch() == llvm::Triple::aarch64)
3290  return EmitMSVCRTSetJmp(*this, MSVCSetJmpKind::_setjmpex, E);
3291  return EmitMSVCRTSetJmp(*this, MSVCSetJmpKind::_setjmp, E);
3292  }
3293  break;
3294 
3295  case Builtin::BI__GetExceptionInfo: {
3296  if (llvm::GlobalVariable *GV =
3297  CGM.getCXXABI().getThrowInfo(FD->getParamDecl(0)->getType()))
3298  return RValue::get(llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy));
3299  break;
3300  }
3301 
3302  case Builtin::BI__fastfail:
3303  return RValue::get(EmitMSVCBuiltinExpr(MSVCIntrin::__fastfail, E));
3304 
3305  case Builtin::BI__builtin_coro_size: {
3306  auto & Context = getContext();
3307  auto SizeTy = Context.getSizeType();
3308  auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
3309  Value *F = CGM.getIntrinsic(Intrinsic::coro_size, T);
3310  return RValue::get(Builder.CreateCall(F));
3311  }
3312 
3313  case Builtin::BI__builtin_coro_id:
3314  return EmitCoroutineIntrinsic(E, Intrinsic::coro_id);
3315  case Builtin::BI__builtin_coro_promise:
3316  return EmitCoroutineIntrinsic(E, Intrinsic::coro_promise);
3317  case Builtin::BI__builtin_coro_resume:
3318  return EmitCoroutineIntrinsic(E, Intrinsic::coro_resume);
3319  case Builtin::BI__builtin_coro_frame:
3320  return EmitCoroutineIntrinsic(E, Intrinsic::coro_frame);
3321  case Builtin::BI__builtin_coro_noop:
3322  return EmitCoroutineIntrinsic(E, Intrinsic::coro_noop);
3323  case Builtin::BI__builtin_coro_free:
3324  return EmitCoroutineIntrinsic(E, Intrinsic::coro_free);
3325  case Builtin::BI__builtin_coro_destroy:
3326  return EmitCoroutineIntrinsic(E, Intrinsic::coro_destroy);
3327  case Builtin::BI__builtin_coro_done:
3328  return EmitCoroutineIntrinsic(E, Intrinsic::coro_done);
3329  case Builtin::BI__builtin_coro_alloc:
3330  return EmitCoroutineIntrinsic(E, Intrinsic::coro_alloc);
3331  case Builtin::BI__builtin_coro_begin:
3332  return EmitCoroutineIntrinsic(E, Intrinsic::coro_begin);
3333  case Builtin::BI__builtin_coro_end:
3334  return EmitCoroutineIntrinsic(E, Intrinsic::coro_end);
3335  case Builtin::BI__builtin_coro_suspend:
3336  return EmitCoroutineIntrinsic(E, Intrinsic::coro_suspend);
3337  case Builtin::BI__builtin_coro_param:
3338  return EmitCoroutineIntrinsic(E, Intrinsic::coro_param);
3339 
3340  // OpenCL v2.0 s6.13.16.2, Built-in pipe read and write functions
3341  case Builtin::BIread_pipe:
3342  case Builtin::BIwrite_pipe: {
3343  Value *Arg0 = EmitScalarExpr(E->getArg(0)),
3344  *Arg1 = EmitScalarExpr(E->getArg(1));
3345  CGOpenCLRuntime OpenCLRT(CGM);
3346  Value *PacketSize = OpenCLRT.getPipeElemSize(E->getArg(0));
3347  Value *PacketAlign = OpenCLRT.getPipeElemAlign(E->getArg(0));
3348 
3349  // Type of the generic packet parameter.
3350  unsigned GenericAS =
3351  getContext().getTargetAddressSpace(LangAS::opencl_generic);
3352  llvm::Type *I8PTy = llvm::PointerType::get(
3353  llvm::Type::getInt8Ty(getLLVMContext()), GenericAS);
3354 
3355  // Testing which overloaded version we should generate the call for.
3356  if (2U == E->getNumArgs()) {
3357  const char *Name = (BuiltinID == Builtin::BIread_pipe) ? "__read_pipe_2"
3358  : "__write_pipe_2";
3359  // Creating a generic function type to be able to call with any builtin or
3360  // user defined type.
3361  llvm::Type *ArgTys[] = {Arg0->getType(), I8PTy, Int32Ty, Int32Ty};
3362  llvm::FunctionType *FTy = llvm::FunctionType::get(
3363  Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
3364  Value *BCast = Builder.CreatePointerCast(Arg1, I8PTy);
3365  return RValue::get(
3366  Builder.CreateCall(CGM.CreateRuntimeFunction(FTy, Name),
3367  {Arg0, BCast, PacketSize, PacketAlign}));
3368  } else {
3369  assert(4 == E->getNumArgs() &&
3370  "Illegal number of parameters to pipe function");
3371  const char *Name = (BuiltinID == Builtin::BIread_pipe) ? "__read_pipe_4"
3372  : "__write_pipe_4";
3373 
3374  llvm::Type *ArgTys[] = {Arg0->getType(), Arg1->getType(), Int32Ty, I8PTy,
3375  Int32Ty, Int32Ty};
3376  Value *Arg2 = EmitScalarExpr(E->getArg(2)),
3377  *Arg3 = EmitScalarExpr(E->getArg(3));
3378  llvm::FunctionType *FTy = llvm::FunctionType::get(
3379  Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
3380  Value *BCast = Builder.CreatePointerCast(Arg3, I8PTy);
3381  // We know the third argument is an integer type, but we may need to cast
3382  // it to i32.
3383  if (Arg2->getType() != Int32Ty)
3384  Arg2 = Builder.CreateZExtOrTrunc(Arg2, Int32Ty);
3385  return RValue::get(Builder.CreateCall(
3386  CGM.CreateRuntimeFunction(FTy, Name),
3387  {Arg0, Arg1, Arg2, BCast, PacketSize, PacketAlign}));
3388  }
3389  }
3390  // OpenCL v2.0 s6.13.16 ,s9.17.3.5 - Built-in pipe reserve read and write
3391  // functions
3392  case Builtin::BIreserve_read_pipe:
3393  case Builtin::BIreserve_write_pipe:
3394  case Builtin::BIwork_group_reserve_read_pipe:
3395  case Builtin::BIwork_group_reserve_write_pipe:
3396  case Builtin::BIsub_group_reserve_read_pipe:
3397  case Builtin::BIsub_group_reserve_write_pipe: {
3398  // Composing the mangled name for the function.
3399  const char *Name;
3400  if (BuiltinID == Builtin::BIreserve_read_pipe)
3401  Name = "__reserve_read_pipe";
3402  else if (BuiltinID == Builtin::BIreserve_write_pipe)
3403  Name = "__reserve_write_pipe";
3404  else if (BuiltinID == Builtin::BIwork_group_reserve_read_pipe)
3405  Name = "__work_group_reserve_read_pipe";
3406  else if (BuiltinID == Builtin::BIwork_group_reserve_write_pipe)
3407  Name = "__work_group_reserve_write_pipe";
3408  else if (BuiltinID == Builtin::BIsub_group_reserve_read_pipe)
3409  Name = "__sub_group_reserve_read_pipe";
3410  else
3411  Name = "__sub_group_reserve_write_pipe";
3412 
3413  Value *Arg0 = EmitScalarExpr(E->getArg(0)),
3414  *Arg1 = EmitScalarExpr(E->getArg(1));
3415  llvm::Type *ReservedIDTy = ConvertType(getContext().OCLReserveIDTy);
3416  CGOpenCLRuntime OpenCLRT(CGM);
3417  Value *PacketSize = OpenCLRT.getPipeElemSize(E->getArg(0));
3418  Value *PacketAlign = OpenCLRT.getPipeElemAlign(E->getArg(0));
3419 
3420  // Building the generic function prototype.
3421  llvm::Type *ArgTys[] = {Arg0->getType(), Int32Ty, Int32Ty, Int32Ty};
3422  llvm::FunctionType *FTy = llvm::FunctionType::get(
3423  ReservedIDTy, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
3424  // We know the second argument is an integer type, but we may need to cast
3425  // it to i32.
3426  if (Arg1->getType() != Int32Ty)
3427  Arg1 = Builder.CreateZExtOrTrunc(Arg1, Int32Ty);
3428  return RValue::get(
3429  Builder.CreateCall(CGM.CreateRuntimeFunction(FTy, Name),
3430  {Arg0, Arg1, PacketSize, PacketAlign}));
3431  }
3432  // OpenCL v2.0 s6.13.16, s9.17.3.5 - Built-in pipe commit read and write
3433  // functions
3434  case Builtin::BIcommit_read_pipe:
3435  case Builtin::BIcommit_write_pipe:
3436  case Builtin::BIwork_group_commit_read_pipe:
3437  case Builtin::BIwork_group_commit_write_pipe:
3438  case Builtin::BIsub_group_commit_read_pipe:
3439  case Builtin::BIsub_group_commit_write_pipe: {
3440  const char *Name;
3441  if (BuiltinID == Builtin::BIcommit_read_pipe)
3442  Name = "__commit_read_pipe";
3443  else if (BuiltinID == Builtin::BIcommit_write_pipe)
3444  Name = "__commit_write_pipe";
3445  else if (BuiltinID == Builtin::BIwork_group_commit_read_pipe)
3446  Name = "__work_group_commit_read_pipe";
3447  else if (BuiltinID == Builtin::BIwork_group_commit_write_pipe)
3448  Name = "__work_group_commit_write_pipe";
3449  else if (BuiltinID == Builtin::BIsub_group_commit_read_pipe)
3450  Name = "__sub_group_commit_read_pipe";
3451  else
3452  Name = "__sub_group_commit_write_pipe";
3453 
3454  Value *Arg0 = EmitScalarExpr(E->getArg(0)),
3455  *Arg1 = EmitScalarExpr(E->getArg(1));
3456  CGOpenCLRuntime OpenCLRT(CGM);
3457  Value *PacketSize = OpenCLRT.getPipeElemSize(E->getArg(0));
3458  Value *PacketAlign = OpenCLRT.getPipeElemAlign(E->getArg(0));
3459 
3460  // Building the generic function prototype.
3461  llvm::Type *ArgTys[] = {Arg0->getType(), Arg1->getType(), Int32Ty, Int32Ty};
3462  llvm::FunctionType *FTy =
3463  llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
3464  llvm::ArrayRef<llvm::Type *>(ArgTys), false);
3465 
3466  return RValue::get(
3467  Builder.CreateCall(CGM.CreateRuntimeFunction(FTy, Name),
3468  {Arg0, Arg1, PacketSize, PacketAlign}));
3469  }
3470  // OpenCL v2.0 s6.13.16.4 Built-in pipe query functions
3471  case Builtin::BIget_pipe_num_packets:
3472  case Builtin::BIget_pipe_max_packets: {
3473  const char *BaseName;
3474  const PipeType *PipeTy = E->getArg(0)->getType()->getAs<PipeType>();
3475  if (BuiltinID == Builtin::BIget_pipe_num_packets)
3476  BaseName = "__get_pipe_num_packets";
3477  else
3478  BaseName = "__get_pipe_max_packets";
3479  auto Name = std::string(BaseName) +
3480  std::string(PipeTy->isReadOnly() ? "_ro" : "_wo");
3481 
3482  // Building the generic function prototype.
3483  Value *Arg0 = EmitScalarExpr(E->getArg(0));
3484  CGOpenCLRuntime OpenCLRT(CGM);
3485  Value *PacketSize = OpenCLRT.getPipeElemSize(E->getArg(0));
3486  Value *PacketAlign = OpenCLRT.getPipeElemAlign(E->getArg(0));
3487  llvm::Type *ArgTys[] = {Arg0->getType(), Int32Ty, Int32Ty};
3488  llvm::FunctionType *FTy = llvm::FunctionType::get(
3489  Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
3490 
3491  return RValue::get(Builder.CreateCall(CGM.CreateRuntimeFunction(FTy, Name),
3492  {Arg0, PacketSize, PacketAlign}));
3493  }
3494 
3495  // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
3496  case Builtin::BIto_global:
3497  case Builtin::BIto_local:
3498  case Builtin::BIto_private: {
3499  auto Arg0 = EmitScalarExpr(E->getArg(0));
3500  auto NewArgT = llvm::PointerType::get(Int8Ty,
3501  CGM.getContext().getTargetAddressSpace(LangAS::opencl_generic));
3502  auto NewRetT = llvm::PointerType::get(Int8Ty,
3503  CGM.getContext().getTargetAddressSpace(
3505  auto FTy = llvm::FunctionType::get(NewRetT, {NewArgT}, false);
3506  llvm::Value *NewArg;
3507  if (Arg0->getType()->getPointerAddressSpace() !=
3508  NewArgT->getPointerAddressSpace())
3509  NewArg = Builder.CreateAddrSpaceCast(Arg0, NewArgT);
3510  else
3511  NewArg = Builder.CreateBitOrPointerCast(Arg0, NewArgT);
3512  auto NewName = std::string("__") + E->getDirectCallee()->getName().str();
3513  auto NewCall =
3514  Builder.CreateCall(CGM.CreateRuntimeFunction(FTy, NewName), {NewArg});
3515  return RValue::get(Builder.CreateBitOrPointerCast(NewCall,
3516  ConvertType(E->getType())));
3517  }
3518 
3519  // OpenCL v2.0, s6.13.17 - Enqueue kernel function.
3520  // It contains four different overload formats specified in Table 6.13.17.1.
3521  case Builtin::BIenqueue_kernel: {
3522  StringRef Name; // Generated function call name
3523  unsigned NumArgs = E->getNumArgs();
3524 
3525  llvm::Type *QueueTy = ConvertType(getContext().OCLQueueTy);
3526  llvm::Type *GenericVoidPtrTy = Builder.getInt8PtrTy(
3527  getContext().getTargetAddressSpace(LangAS::opencl_generic));
3528 
3529  llvm::Value *Queue = EmitScalarExpr(E->getArg(0));
3530  llvm::Value *Flags = EmitScalarExpr(E->getArg(1));
3531  LValue NDRangeL = EmitAggExprToLValue(E->getArg(2));
3532  llvm::Value *Range = NDRangeL.getAddress().getPointer();
3533  llvm::Type *RangeTy = NDRangeL.getAddress().getType();
3534 
3535  if (NumArgs == 4) {
3536  // The most basic form of the call with parameters:
3537  // queue_t, kernel_enqueue_flags_t, ndrange_t, block(void)
3538  Name = "__enqueue_kernel_basic";
3539  llvm::Type *ArgTys[] = {QueueTy, Int32Ty, RangeTy, GenericVoidPtrTy,
3540  GenericVoidPtrTy};
3541  llvm::FunctionType *FTy = llvm::FunctionType::get(
3542  Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
3543 
3544  auto Info =
3545  CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(3));
3546  llvm::Value *Kernel =
3547  Builder.CreatePointerCast(Info.Kernel, GenericVoidPtrTy);
3548  llvm::Value *Block =
3549  Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
3550 
3551  AttrBuilder B;
3552  B.addAttribute(Attribute::ByVal);
3553  llvm::AttributeList ByValAttrSet =
3554  llvm::AttributeList::get(CGM.getModule().getContext(), 3U, B);
3555 
3556  auto RTCall =
3557  Builder.CreateCall(CGM.CreateRuntimeFunction(FTy, Name, ByValAttrSet),
3558  {Queue, Flags, Range, Kernel, Block});
3559  RTCall->setAttributes(ByValAttrSet);
3560  return RValue::get(RTCall);
3561  }
3562  assert(NumArgs >= 5 && "Invalid enqueue_kernel signature");
3563 
3564  // Create a temporary array to hold the sizes of local pointer arguments
3565  // for the block. \p First is the position of the first size argument.
3566  auto CreateArrayForSizeVar = [=](unsigned First)
3567  -> std::tuple<llvm::Value *, llvm::Value *, llvm::Value *> {
3568  llvm::APInt ArraySize(32, NumArgs - First);
3569  QualType SizeArrayTy = getContext().getConstantArrayType(
3570  getContext().getSizeType(), ArraySize, ArrayType::Normal,
3571  /*IndexTypeQuals=*/0);
3572  auto Tmp = CreateMemTemp(SizeArrayTy, "block_sizes");
3573  llvm::Value *TmpPtr = Tmp.getPointer();
3574  llvm::Value *TmpSize = EmitLifetimeStart(
3575  CGM.getDataLayout().getTypeAllocSize(Tmp.getElementType()), TmpPtr);
3576  llvm::Value *ElemPtr;
3577  // Each of the following arguments specifies the size of the corresponding
3578  // argument passed to the enqueued block.
3579  auto *Zero = llvm::ConstantInt::get(IntTy, 0);
3580  for (unsigned I = First; I < NumArgs; ++I) {
3581  auto *Index = llvm::ConstantInt::get(IntTy, I - First);
3582  auto *GEP = Builder.CreateGEP(TmpPtr, {Zero, Index});
3583  if (I == First)
3584  ElemPtr = GEP;
3585  auto *V =
3586  Builder.CreateZExtOrTrunc(EmitScalarExpr(E->getArg(I)), SizeTy);
3587  Builder.CreateAlignedStore(
3588  V, GEP, CGM.getDataLayout().getPrefTypeAlignment(SizeTy));
3589  }
3590  return std::tie(ElemPtr, TmpSize, TmpPtr);
3591  };
3592 
3593  // Could have events and/or varargs.
3594  if (E->getArg(3)->getType()->isBlockPointerType()) {
3595  // No events passed, but has variadic arguments.
3596  Name = "__enqueue_kernel_varargs";
3597  auto Info =
3598  CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(3));
3599  llvm::Value *Kernel =
3600  Builder.CreatePointerCast(Info.Kernel, GenericVoidPtrTy);
3601  auto *Block = Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
3602  llvm::Value *ElemPtr, *TmpSize, *TmpPtr;
3603  std::tie(ElemPtr, TmpSize, TmpPtr) = CreateArrayForSizeVar(4);
3604 
3605  // Create a vector of the arguments, as well as a constant value to
3606  // express to the runtime the number of variadic arguments.
3607  std::vector<llvm::Value *> Args = {
3608  Queue, Flags, Range,
3609  Kernel, Block, ConstantInt::get(IntTy, NumArgs - 4),
3610  ElemPtr};
3611  std::vector<llvm::Type *> ArgTys = {
3612  QueueTy, IntTy, RangeTy, GenericVoidPtrTy,
3613  GenericVoidPtrTy, IntTy, ElemPtr->getType()};
3614 
3615  llvm::FunctionType *FTy = llvm::FunctionType::get(
3616  Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
3617  auto Call =
3618  RValue::get(Builder.CreateCall(CGM.CreateRuntimeFunction(FTy, Name),
3620  if (TmpSize)
3621  EmitLifetimeEnd(TmpSize, TmpPtr);
3622  return Call;
3623  }
3624  // Any calls now have event arguments passed.
3625  if (NumArgs >= 7) {
3626  llvm::Type *EventTy = ConvertType(getContext().OCLClkEventTy);
3627  llvm::Type *EventPtrTy = EventTy->getPointerTo(
3628  CGM.getContext().getTargetAddressSpace(LangAS::opencl_generic));
3629 
3630  llvm::Value *NumEvents =
3631  Builder.CreateZExtOrTrunc(EmitScalarExpr(E->getArg(3)), Int32Ty);
3632  llvm::Value *EventList =
3633  E->getArg(4)->getType()->isArrayType()
3634  ? EmitArrayToPointerDecay(E->getArg(4)).getPointer()
3635  : EmitScalarExpr(E->getArg(4));
3636  llvm::Value *ClkEvent = EmitScalarExpr(E->getArg(5));
3637  // Convert to generic address space.
3638  EventList = Builder.CreatePointerCast(EventList, EventPtrTy);
3639  ClkEvent = ClkEvent->getType()->isIntegerTy()
3640  ? Builder.CreateBitOrPointerCast(ClkEvent, EventPtrTy)
3641  : Builder.CreatePointerCast(ClkEvent, EventPtrTy);
3642  auto Info =
3643  CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(6));
3644  llvm::Value *Kernel =
3645  Builder.CreatePointerCast(Info.Kernel, GenericVoidPtrTy);
3646  llvm::Value *Block =
3647  Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
3648 
3649  std::vector<llvm::Type *> ArgTys = {
3650  QueueTy, Int32Ty, RangeTy, Int32Ty,
3651  EventPtrTy, EventPtrTy, GenericVoidPtrTy, GenericVoidPtrTy};
3652 
3653  std::vector<llvm::Value *> Args = {Queue, Flags, Range, NumEvents,
3654  EventList, ClkEvent, Kernel, Block};
3655 
3656  if (NumArgs == 7) {
3657  // Has events but no variadics.
3658  Name = "__enqueue_kernel_basic_events";
3659  llvm::FunctionType *FTy = llvm::FunctionType::get(
3660  Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
3661  return RValue::get(
3662  Builder.CreateCall(CGM.CreateRuntimeFunction(FTy, Name),
3664  }
3665  // Has event info and variadics
3666  // Pass the number of variadics to the runtime function too.
3667  Args.push_back(ConstantInt::get(Int32Ty, NumArgs - 7));
3668  ArgTys.push_back(Int32Ty);
3669  Name = "__enqueue_kernel_events_varargs";
3670 
3671  llvm::Value *ElemPtr, *TmpSize, *TmpPtr;
3672  std::tie(ElemPtr, TmpSize, TmpPtr) = CreateArrayForSizeVar(7);
3673  Args.push_back(ElemPtr);
3674  ArgTys.push_back(ElemPtr->getType());
3675 
3676  llvm::FunctionType *FTy = llvm::FunctionType::get(
3677  Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
3678  auto Call =
3679  RValue::get(Builder.CreateCall(CGM.CreateRuntimeFunction(FTy, Name),
3681  if (TmpSize)
3682  EmitLifetimeEnd(TmpSize, TmpPtr);
3683  return Call;
3684  }
3685  LLVM_FALLTHROUGH;
3686  }
3687  // OpenCL v2.0 s6.13.17.6 - Kernel query functions need bitcast of block
3688  // parameter.
3689  case Builtin::BIget_kernel_work_group_size: {
3690  llvm::Type *GenericVoidPtrTy = Builder.getInt8PtrTy(
3691  getContext().getTargetAddressSpace(LangAS::opencl_generic));
3692  auto Info =
3693  CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(0));
3694  Value *Kernel = Builder.CreatePointerCast(Info.Kernel, GenericVoidPtrTy);
3695  Value *Arg = Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
3696  return RValue::get(Builder.CreateCall(
3697  CGM.CreateRuntimeFunction(
3698  llvm::FunctionType::get(IntTy, {GenericVoidPtrTy, GenericVoidPtrTy},
3699  false),
3700  "__get_kernel_work_group_size_impl"),
3701  {Kernel, Arg}));
3702  }
3703  case Builtin::BIget_kernel_preferred_work_group_size_multiple: {
3704  llvm::Type *GenericVoidPtrTy = Builder.getInt8PtrTy(
3705  getContext().getTargetAddressSpace(LangAS::opencl_generic));
3706  auto Info =
3707  CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(0));
3708  Value *Kernel = Builder.CreatePointerCast(Info.Kernel, GenericVoidPtrTy);
3709  Value *Arg = Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
3710  return RValue::get(Builder.CreateCall(
3711  CGM.CreateRuntimeFunction(
3712  llvm::FunctionType::get(IntTy, {GenericVoidPtrTy, GenericVoidPtrTy},
3713  false),
3714  "__get_kernel_preferred_work_group_size_multiple_impl"),
3715  {Kernel, Arg}));
3716  }
3717  case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3718  case Builtin::BIget_kernel_sub_group_count_for_ndrange: {
3719  llvm::Type *GenericVoidPtrTy = Builder.getInt8PtrTy(
3720  getContext().getTargetAddressSpace(LangAS::opencl_generic));
3721  LValue NDRangeL = EmitAggExprToLValue(E->getArg(0));
3722  llvm::Value *NDRange = NDRangeL.getAddress().getPointer();
3723  auto Info =
3724  CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(1));
3725  Value *Kernel = Builder.CreatePointerCast(Info.Kernel, GenericVoidPtrTy);
3726  Value *Block = Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
3727  const char *Name =
3728  BuiltinID == Builtin::BIget_kernel_max_sub_group_size_for_ndrange
3729  ? "__get_kernel_max_sub_group_size_for_ndrange_impl"
3730  : "__get_kernel_sub_group_count_for_ndrange_impl";
3731  return RValue::get(Builder.CreateCall(
3732  CGM.CreateRuntimeFunction(
3733  llvm::FunctionType::get(
3734  IntTy, {NDRange->getType(), GenericVoidPtrTy, GenericVoidPtrTy},
3735  false),
3736  Name),
3737  {NDRange, Kernel, Block}));
3738  }
3739 
3740  case Builtin::BI__builtin_store_half:
3741  case Builtin::BI__builtin_store_halff: {
3742  Value *Val = EmitScalarExpr(E->getArg(0));
3743  Address Address = EmitPointerWithAlignment(E->getArg(1));
3744  Value *HalfVal = Builder.CreateFPTrunc(Val, Builder.getHalfTy());
3745  return RValue::get(Builder.CreateStore(HalfVal, Address));
3746  }
3747  case Builtin::BI__builtin_load_half: {
3748  Address Address = EmitPointerWithAlignment(E->getArg(0));
3749  Value *HalfVal = Builder.CreateLoad(Address);
3750  return RValue::get(Builder.CreateFPExt(HalfVal, Builder.getDoubleTy()));
3751  }
3752  case Builtin::BI__builtin_load_halff: {
3753  Address Address = EmitPointerWithAlignment(E->getArg(0));
3754  Value *HalfVal = Builder.CreateLoad(Address);
3755  return RValue::get(Builder.CreateFPExt(HalfVal, Builder.getFloatTy()));
3756  }
3757  case Builtin::BIprintf:
3758  if (getTarget().getTriple().isNVPTX())
3759  return EmitNVPTXDevicePrintfCallExpr(E, ReturnValue);
3760  break;
3761  case Builtin::BI__builtin_canonicalize:
3762  case Builtin::BI__builtin_canonicalizef:
3763  case Builtin::BI__builtin_canonicalizel:
3764  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::canonicalize));
3765 
3766  case Builtin::BI__builtin_thread_pointer: {
3767  if (!getContext().getTargetInfo().isTLSSupported())
3768  CGM.ErrorUnsupported(E, "__builtin_thread_pointer");
3769  // Fall through - it's already mapped to the intrinsic by GCCBuiltin.
3770  break;
3771  }
3772  case Builtin::BI__builtin_os_log_format:
3773  return emitBuiltinOSLogFormat(*E);
3774 
3775  case Builtin::BI__xray_customevent: {
3776  if (!ShouldXRayInstrumentFunction())
3777  return RValue::getIgnored();
3778 
3779  if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
3781  return RValue::getIgnored();
3782 
3783  if (const auto *XRayAttr = CurFuncDecl->getAttr<XRayInstrumentAttr>())
3784  if (XRayAttr->neverXRayInstrument() && !AlwaysEmitXRayCustomEvents())
3785  return RValue::getIgnored();
3786 
3787  Function *F = CGM.getIntrinsic(Intrinsic::xray_customevent);
3788  auto FTy = F->getFunctionType();
3789  auto Arg0 = E->getArg(0);
3790  auto Arg0Val = EmitScalarExpr(Arg0);
3791  auto Arg0Ty = Arg0->getType();
3792  auto PTy0 = FTy->getParamType(0);
3793  if (PTy0 != Arg0Val->getType()) {
3794  if (Arg0Ty->isArrayType())
3795  Arg0Val = EmitArrayToPointerDecay(Arg0).getPointer();
3796  else
3797  Arg0Val = Builder.CreatePointerCast(Arg0Val, PTy0);
3798  }
3799  auto Arg1 = EmitScalarExpr(E->getArg(1));
3800  auto PTy1 = FTy->getParamType(1);
3801  if (PTy1 != Arg1->getType())
3802  Arg1 = Builder.CreateTruncOrBitCast(Arg1, PTy1);
3803  return RValue::get(Builder.CreateCall(F, {Arg0Val, Arg1}));
3804  }
3805 
3806  case Builtin::BI__xray_typedevent: {
3807  // TODO: There should be a way to always emit events even if the current
3808  // function is not instrumented. Losing events in a stream can cripple
3809  // a trace.
3810  if (!ShouldXRayInstrumentFunction())
3811  return RValue::getIgnored();
3812 
3813  if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
3815  return RValue::getIgnored();
3816 
3817  if (const auto *XRayAttr = CurFuncDecl->getAttr<XRayInstrumentAttr>())
3818  if (XRayAttr->neverXRayInstrument() && !AlwaysEmitXRayTypedEvents())
3819  return RValue::getIgnored();
3820 
3821  Function *F = CGM.getIntrinsic(Intrinsic::xray_typedevent);
3822  auto FTy = F->getFunctionType();
3823  auto Arg0 = EmitScalarExpr(E->getArg(0));
3824  auto PTy0 = FTy->getParamType(0);
3825  if (PTy0 != Arg0->getType())
3826  Arg0 = Builder.CreateTruncOrBitCast(Arg0, PTy0);
3827  auto Arg1 = E->getArg(1);
3828  auto Arg1Val = EmitScalarExpr(Arg1);
3829  auto Arg1Ty = Arg1->getType();
3830  auto PTy1 = FTy->getParamType(1);
3831  if (PTy1 != Arg1Val->getType()) {
3832  if (Arg1Ty->isArrayType())
3833  Arg1Val = EmitArrayToPointerDecay(Arg1).getPointer();
3834  else
3835  Arg1Val = Builder.CreatePointerCast(Arg1Val, PTy1);
3836  }
3837  auto Arg2 = EmitScalarExpr(E->getArg(2));
3838  auto PTy2 = FTy->getParamType(2);
3839  if (PTy2 != Arg2->getType())
3840  Arg2 = Builder.CreateTruncOrBitCast(Arg2, PTy2);
3841  return RValue::get(Builder.CreateCall(F, {Arg0, Arg1Val, Arg2}));
3842  }
3843 
3844  case Builtin::BI__builtin_ms_va_start:
3845  case Builtin::BI__builtin_ms_va_end:
3846  return RValue::get(
3847  EmitVAStartEnd(EmitMSVAListRef(E->getArg(0)).getPointer(),
3848  BuiltinID == Builtin::BI__builtin_ms_va_start));
3849 
3850  case Builtin::BI__builtin_ms_va_copy: {
3851  // Lower this manually. We can't reliably determine whether or not any
3852  // given va_copy() is for a Win64 va_list from the calling convention
3853  // alone, because it's legal to do this from a System V ABI function.
3854  // With opaque pointer types, we won't have enough information in LLVM
3855  // IR to determine this from the argument types, either. Best to do it
3856  // now, while we have enough information.
3857  Address DestAddr = EmitMSVAListRef(E->getArg(0));
3858  Address SrcAddr = EmitMSVAListRef(E->getArg(1));
3859 
3860  llvm::Type *BPP = Int8PtrPtrTy;
3861 
3862  DestAddr = Address(Builder.CreateBitCast(DestAddr.getPointer(), BPP, "cp"),
3863  DestAddr.getAlignment());
3864  SrcAddr = Address(Builder.CreateBitCast(SrcAddr.getPointer(), BPP, "ap"),
3865  SrcAddr.getAlignment());
3866 
3867  Value *ArgPtr = Builder.CreateLoad(SrcAddr, "ap.val");
3868  return RValue::get(Builder.CreateStore(ArgPtr, DestAddr));
3869  }
3870  }
3871 
3872  // If this is an alias for a lib function (e.g. __builtin_sin), emit
3873  // the call using the normal call path, but using the unmangled
3874  // version of the function name.
3875  if (getContext().BuiltinInfo.isLibFunction(BuiltinID))
3876  return emitLibraryCall(*this, FD, E,
3877  CGM.getBuiltinLibFunction(FD, BuiltinID));
3878 
3879  // If this is a predefined lib function (e.g. malloc), emit the call
3880  // using exactly the normal call path.
3881  if (getContext().BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3882  return emitLibraryCall(*this, FD, E,
3883  cast<llvm::Constant>(EmitScalarExpr(E->getCallee())));
3884 
3885  // Check that a call to a target specific builtin has the correct target
3886  // features.
3887  // This is down here to avoid non-target specific builtins, however, if
3888  // generic builtins start to require generic target features then we
3889  // can move this up to the beginning of the function.
3890  checkTargetFeatures(E, FD);
3891 
3892  if (unsigned VectorWidth = getContext().BuiltinInfo.getRequiredVectorWidth(BuiltinID))
3893  LargestVectorWidth = std::max(LargestVectorWidth, VectorWidth);
3894 
3895  // See if we have a target specific intrinsic.
3896  const char *Name = getContext().BuiltinInfo.getName(BuiltinID);
3897  Intrinsic::ID IntrinsicID = Intrinsic::not_intrinsic;
3898  StringRef Prefix =
3899  llvm::Triple::getArchTypePrefix(getTarget().getTriple().getArch());
3900  if (!Prefix.empty()) {
3901  IntrinsicID = Intrinsic::getIntrinsicForGCCBuiltin(Prefix.data(), Name);
3902  // NOTE we don't need to perform a compatibility flag check here since the
3903  // intrinsics are declared in Builtins*.def via LANGBUILTIN which filter the
3904  // MS builtins via ALL_MS_LANGUAGES and are filtered earlier.
3905  if (IntrinsicID == Intrinsic::not_intrinsic)
3906  IntrinsicID = Intrinsic::getIntrinsicForMSBuiltin(Prefix.data(), Name);
3907  }
3908 
3909  if (IntrinsicID != Intrinsic::not_intrinsic) {
3911 
3912  // Find out if any arguments are required to be integer constant
3913  // expressions.
3914  unsigned ICEArguments = 0;
3916  getContext().GetBuiltinType(BuiltinID, Error, &ICEArguments);
3917  assert(Error == ASTContext::GE_None && "Should not codegen an error");
3918 
3919  Function *F = CGM.getIntrinsic(IntrinsicID);
3920  llvm::FunctionType *FTy = F->getFunctionType();
3921 
3922  for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
3923  Value *ArgValue;
3924  // If this is a normal argument, just emit it as a scalar.
3925  if ((ICEArguments & (1 << i)) == 0) {
3926  ArgValue = EmitScalarExpr(E->getArg(i));
3927  } else {
3928  // If this is required to be a constant, constant fold it so that we
3929  // know that the generated intrinsic gets a ConstantInt.
3930  llvm::APSInt Result;
3931  bool IsConst = E->getArg(i)->isIntegerConstantExpr(Result,getContext());
3932  assert(IsConst && "Constant arg isn't actually constant?");
3933  (void)IsConst;
3934  ArgValue = llvm::ConstantInt::get(getLLVMContext(), Result);
3935  }
3936 
3937  // If the intrinsic arg type is different from the builtin arg type
3938  // we need to do a bit cast.
3939  llvm::Type *PTy = FTy->getParamType(i);
3940  if (PTy != ArgValue->getType()) {
3941  // XXX - vector of pointers?
3942  if (auto *PtrTy = dyn_cast<llvm::PointerType>(PTy)) {
3943  if (PtrTy->getAddressSpace() !=
3944  ArgValue->getType()->getPointerAddressSpace()) {
3945  ArgValue = Builder.CreateAddrSpaceCast(
3946  ArgValue,
3947  ArgValue->getType()->getPointerTo(PtrTy->getAddressSpace()));
3948  }
3949  }
3950 
3951  assert(PTy->canLosslesslyBitCastTo(FTy->getParamType(i)) &&
3952  "Must be able to losslessly bit cast to param");
3953  ArgValue = Builder.CreateBitCast(ArgValue, PTy);
3954  }
3955 
3956  Args.push_back(ArgValue);
3957  }
3958 
3959  Value *V = Builder.CreateCall(F, Args);
3960  QualType BuiltinRetType = E->getType();
3961 
3962  llvm::Type *RetTy = VoidTy;
3963  if (!BuiltinRetType->isVoidType())
3964  RetTy = ConvertType(BuiltinRetType);
3965 
3966  if (RetTy != V->getType()) {
3967  // XXX - vector of pointers?
3968  if (auto *PtrTy = dyn_cast<llvm::PointerType>(RetTy)) {
3969  if (PtrTy->getAddressSpace() != V->getType()->getPointerAddressSpace()) {
3970  V = Builder.CreateAddrSpaceCast(
3971  V, V->getType()->getPointerTo(PtrTy->getAddressSpace()));
3972  }
3973  }
3974 
3975  assert(V->getType()->canLosslesslyBitCastTo(RetTy) &&
3976  "Must be able to losslessly bit cast result type");
3977  V = Builder.CreateBitCast(V, RetTy);
3978  }
3979 
3980  return RValue::get(V);
3981  }
3982 
3983  // See if we have a target specific builtin that needs to be lowered.
3984  if (Value *V = EmitTargetBuiltinExpr(BuiltinID, E))
3985  return RValue::get(V);
3986 
3987  ErrorUnsupported(E, "builtin function");
3988 
3989  // Unknown builtin, for now just dump it out and return undef.
3990  return GetUndefRValue(E->getType());
3991 }
3992 
3994  unsigned BuiltinID, const CallExpr *E,
3995  llvm::Triple::ArchType Arch) {
3996  switch (Arch) {
3997  case llvm::Triple::arm:
3998  case llvm::Triple::armeb:
3999  case llvm::Triple::thumb:
4000  case llvm::Triple::thumbeb:
4001  return CGF->EmitARMBuiltinExpr(BuiltinID, E, Arch);
4002  case llvm::Triple::aarch64:
4003  case llvm::Triple::aarch64_be:
4004  return CGF->EmitAArch64BuiltinExpr(BuiltinID, E, Arch);
4005  case llvm::Triple::x86:
4006  case llvm::Triple::x86_64:
4007  return CGF->EmitX86BuiltinExpr(BuiltinID, E);
4008  case llvm::Triple::ppc:
4009  case llvm::Triple::ppc64:
4010  case llvm::Triple::ppc64le:
4011  return CGF->EmitPPCBuiltinExpr(BuiltinID, E);
4012  case llvm::Triple::r600:
4013  case llvm::Triple::amdgcn:
4014  return CGF->EmitAMDGPUBuiltinExpr(BuiltinID, E);
4015  case llvm::Triple::systemz:
4016  return CGF->EmitSystemZBuiltinExpr(BuiltinID, E);
4017  case llvm::Triple::nvptx:
4018  case llvm::Triple::nvptx64:
4019  return CGF->EmitNVPTXBuiltinExpr(BuiltinID, E);
4020  case llvm::Triple::wasm32:
4021  case llvm::Triple::wasm64:
4022  return CGF->EmitWebAssemblyBuiltinExpr(BuiltinID, E);
4023  case llvm::Triple::hexagon:
4024  return CGF->EmitHexagonBuiltinExpr(BuiltinID, E);
4025  default:
4026  return nullptr;
4027  }
4028 }
4029 
4031  const CallExpr *E) {
4032  if (getContext().BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
4033  assert(getContext().getAuxTargetInfo() && "Missing aux target info");
4035  this, getContext().BuiltinInfo.getAuxBuiltinID(BuiltinID), E,
4036  getContext().getAuxTargetInfo()->getTriple().getArch());
4037  }
4038 
4039  return EmitTargetArchBuiltinExpr(this, BuiltinID, E,
4040  getTarget().getTriple().getArch());
4041 }
4042 
4043 static llvm::VectorType *GetNeonType(CodeGenFunction *CGF,
4044  NeonTypeFlags TypeFlags,
4045  bool HasLegalHalfType=true,
4046  bool V1Ty=false) {
4047  int IsQuad = TypeFlags.isQuad();
4048  switch (TypeFlags.getEltType()) {
4049  case NeonTypeFlags::Int8:
4050  case NeonTypeFlags::Poly8:
4051  return llvm::VectorType::get(CGF->Int8Ty, V1Ty ? 1 : (8 << IsQuad));
4052  case NeonTypeFlags::Int16:
4053  case NeonTypeFlags::Poly16:
4054  return llvm::VectorType::get(CGF->Int16Ty, V1Ty ? 1 : (4 << IsQuad));
4056  if (HasLegalHalfType)
4057  return llvm::VectorType::get(CGF->HalfTy, V1Ty ? 1 : (4 << IsQuad));
4058  else
4059  return llvm::VectorType::get(CGF->Int16Ty, V1Ty ? 1 : (4 << IsQuad));
4060  case NeonTypeFlags::Int32:
4061  return llvm::VectorType::get(CGF->Int32Ty, V1Ty ? 1 : (2 << IsQuad));
4062  case NeonTypeFlags::Int64:
4063  case NeonTypeFlags::Poly64:
4064  return llvm::VectorType::get(CGF->Int64Ty, V1Ty ? 1 : (1 << IsQuad));
4066  // FIXME: i128 and f128 doesn't get fully support in Clang and llvm.
4067  // There is a lot of i128 and f128 API missing.
4068  // so we use v16i8 to represent poly128 and get pattern matched.
4069  return llvm::VectorType::get(CGF->Int8Ty, 16);
4071  return llvm::VectorType::get(CGF->FloatTy, V1Ty ? 1 : (2 << IsQuad));
4073  return llvm::VectorType::get(CGF->DoubleTy, V1Ty ? 1 : (1 << IsQuad));
4074  }
4075  llvm_unreachable("Unknown vector element type!");
4076 }
4077 
4078 static llvm::VectorType *GetFloatNeonType(CodeGenFunction *CGF,
4079  NeonTypeFlags IntTypeFlags) {
4080  int IsQuad = IntTypeFlags.isQuad();
4081  switch (IntTypeFlags.getEltType()) {
4082  case NeonTypeFlags::Int16:
4083  return llvm::VectorType::get(CGF->HalfTy, (4 << IsQuad));
4084  case NeonTypeFlags::Int32:
4085  return llvm::VectorType::get(CGF->FloatTy, (2 << IsQuad));
4086  case NeonTypeFlags::Int64:
4087  return llvm::VectorType::get(CGF->DoubleTy, (1 << IsQuad));
4088  default:
4089  llvm_unreachable("Type can't be converted to floating-point!");
4090  }
4091 }
4092 
4094  unsigned nElts = V->getType()->getVectorNumElements();
4095  Value* SV = llvm::ConstantVector::getSplat(nElts, C);
4096  return Builder.CreateShuffleVector(V, V, SV, "lane");
4097 }
4098 
4100  const char *name,
4101  unsigned shift, bool rightshift) {
4102  unsigned j = 0;
4103  for (Function::const_arg_iterator ai = F->arg_begin(), ae = F->arg_end();
4104  ai != ae; ++ai, ++j)
4105  if (shift > 0 && shift == j)
4106  Ops[j] = EmitNeonShiftVector(Ops[j], ai->getType(), rightshift);
4107  else
4108  Ops[j] = Builder.CreateBitCast(Ops[j], ai->getType(), name);
4109 
4110  return Builder.CreateCall(F, Ops, name);
4111 }
4112 
4114  bool neg) {
4115  int SV = cast<ConstantInt>(V)->getSExtValue();
4116  return ConstantInt::get(Ty, neg ? -SV : SV);
4117 }
4118 
4119 // Right-shift a vector by a constant.
4121  llvm::Type *Ty, bool usgn,
4122  const char *name) {
4123  llvm::VectorType *VTy = cast<llvm::VectorType>(Ty);
4124 
4125  int ShiftAmt = cast<ConstantInt>(Shift)->getSExtValue();
4126  int EltSize = VTy->getScalarSizeInBits();
4127 
4128  Vec = Builder.CreateBitCast(Vec, Ty);
4129 
4130  // lshr/ashr are undefined when the shift amount is equal to the vector
4131  // element size.
4132  if (ShiftAmt == EltSize) {
4133  if (usgn) {
4134  // Right-shifting an unsigned value by its size yields 0.
4135  return llvm::ConstantAggregateZero::get(VTy);
4136  } else {
4137  // Right-shifting a signed value by its size is equivalent
4138  // to a shift of size-1.
4139  --ShiftAmt;
4140  Shift = ConstantInt::get(VTy->getElementType(), ShiftAmt);
4141  }
4142  }
4143 
4144  Shift = EmitNeonShiftVector(Shift, Ty, false);
4145  if (usgn)
4146  return Builder.CreateLShr(Vec, Shift, name);
4147  else
4148  return Builder.CreateAShr(Vec, Shift, name);
4149 }
4150 
4151 enum {
4152  AddRetType = (1 << 0),
4153  Add1ArgType = (1 << 1),
4154  Add2ArgTypes = (1 << 2),
4155 
4156  VectorizeRetType = (1 << 3),
4157  VectorizeArgTypes = (1 << 4),
4158 
4159  InventFloatType = (1 << 5),
4160  UnsignedAlts = (1 << 6),
4161 
4162  Use64BitVectors = (1 << 7),
4163  Use128BitVectors = (1 << 8),
4164 
4171 };
4172 
4173 namespace {
4174 struct NeonIntrinsicInfo {
4175  const char *NameHint;
4176  unsigned BuiltinID;
4177  unsigned LLVMIntrinsic;
4178  unsigned AltLLVMIntrinsic;
4179  unsigned TypeModifier;
4180 
4181  bool operator<(unsigned RHSBuiltinID) const {
4182  return BuiltinID < RHSBuiltinID;
4183  }
4184  bool operator<(const NeonIntrinsicInfo &TE) const {
4185  return BuiltinID < TE.BuiltinID;
4186  }
4187 };
4188 } // end anonymous namespace
4189 
4190 #define NEONMAP0(NameBase) \
4191  { #NameBase, NEON::BI__builtin_neon_ ## NameBase, 0, 0, 0 }
4192 
4193 #define NEONMAP1(NameBase, LLVMIntrinsic, TypeModifier) \
4194  { #NameBase, NEON:: BI__builtin_neon_ ## NameBase, \
4195  Intrinsic::LLVMIntrinsic, 0, TypeModifier }
4196 
4197 #define NEONMAP2(NameBase, LLVMIntrinsic, AltLLVMIntrinsic, TypeModifier) \
4198  { #NameBase, NEON:: BI__builtin_neon_ ## NameBase, \
4199  Intrinsic::LLVMIntrinsic, Intrinsic::AltLLVMIntrinsic, \
4200  TypeModifier }
4201 
4202 static const NeonIntrinsicInfo ARMSIMDIntrinsicMap [] = {
4203  NEONMAP2(vabd_v, arm_neon_vabdu, arm_neon_vabds, Add1ArgType | UnsignedAlts),
4204  NEONMAP2(vabdq_v, arm_neon_vabdu, arm_neon_vabds, Add1ArgType | UnsignedAlts),
4205  NEONMAP1(vabs_v, arm_neon_vabs, 0),
4206  NEONMAP1(vabsq_v, arm_neon_vabs, 0),
4207  NEONMAP0(vaddhn_v),
4208  NEONMAP1(vaesdq_v, arm_neon_aesd, 0),
4209  NEONMAP1(vaeseq_v, arm_neon_aese, 0),
4210  NEONMAP1(vaesimcq_v, arm_neon_aesimc, 0),
4211  NEONMAP1(vaesmcq_v, arm_neon_aesmc, 0),
4212  NEONMAP1(vbsl_v, arm_neon_vbsl, AddRetType),
4213  NEONMAP1(vbslq_v, arm_neon_vbsl, AddRetType),
4214  NEONMAP1(vcage_v, arm_neon_vacge, 0),
4215  NEONMAP1(vcageq_v, arm_neon_vacge, 0),
4216  NEONMAP1(vcagt_v, arm_neon_vacgt, 0),
4217  NEONMAP1(vcagtq_v, arm_neon_vacgt, 0),
4218  NEONMAP1(vcale_v, arm_neon_vacge, 0),
4219  NEONMAP1(vcaleq_v, arm_neon_vacge, 0),
4220  NEONMAP1(vcalt_v, arm_neon_vacgt, 0),
4221  NEONMAP1(vcaltq_v, arm_neon_vacgt, 0),
4222  NEONMAP0(vceqz_v),
4223  NEONMAP0(vceqzq_v),
4224  NEONMAP0(vcgez_v),
4225  NEONMAP0(vcgezq_v),
4226  NEONMAP0(vcgtz_v),
4227  NEONMAP0(vcgtzq_v),
4228  NEONMAP0(vclez_v),
4229  NEONMAP0(vclezq_v),
4230  NEONMAP1(vcls_v, arm_neon_vcls, Add1ArgType),
4231  NEONMAP1(vclsq_v, arm_neon_vcls, Add1ArgType),
4232  NEONMAP0(vcltz_v),
4233  NEONMAP0(vcltzq_v),
4234  NEONMAP1(vclz_v, ctlz, Add1ArgType),
4235  NEONMAP1(vclzq_v, ctlz, Add1ArgType),
4236  NEONMAP1(vcnt_v, ctpop, Add1ArgType),
4237  NEONMAP1(vcntq_v, ctpop, Add1ArgType),
4238  NEONMAP1(vcvt_f16_f32, arm_neon_vcvtfp2hf, 0),
4239  NEONMAP0(vcvt_f16_v),
4240  NEONMAP1(vcvt_f32_f16, arm_neon_vcvthf2fp, 0),
4241  NEONMAP0(vcvt_f32_v),
4242  NEONMAP2(vcvt_n_f16_v, arm_neon_vcvtfxu2fp, arm_neon_vcvtfxs2fp, 0),
4243  NEONMAP2(vcvt_n_f32_v, arm_neon_vcvtfxu2fp, arm_neon_vcvtfxs2fp, 0),
4244  NEONMAP1(vcvt_n_s16_v, arm_neon_vcvtfp2fxs, 0),
4245  NEONMAP1(vcvt_n_s32_v, arm_neon_vcvtfp2fxs, 0),
4246  NEONMAP1(vcvt_n_s64_v, arm_neon_vcvtfp2fxs, 0),
4247  NEONMAP1(vcvt_n_u16_v, arm_neon_vcvtfp2fxu, 0),
4248  NEONMAP1(vcvt_n_u32_v, arm_neon_vcvtfp2fxu, 0),
4249  NEONMAP1(vcvt_n_u64_v, arm_neon_vcvtfp2fxu, 0),
4250  NEONMAP0(vcvt_s16_v),
4251  NEONMAP0(vcvt_s32_v),
4252  NEONMAP0(vcvt_s64_v),
4253  NEONMAP0(vcvt_u16_v),
4254  NEONMAP0(vcvt_u32_v),
4255  NEONMAP0(vcvt_u64_v),
4256  NEONMAP1(vcvta_s16_v, arm_neon_vcvtas, 0),
4257  NEONMAP1(vcvta_s32_v, arm_neon_vcvtas, 0),
4258  NEONMAP1(vcvta_s64_v, arm_neon_vcvtas, 0),
4259  NEONMAP1(vcvta_u16_v, arm_neon_vcvtau, 0),
4260  NEONMAP1(vcvta_u32_v, arm_neon_vcvtau, 0),
4261  NEONMAP1(vcvta_u64_v, arm_neon_vcvtau, 0),
4262  NEONMAP1(vcvtaq_s16_v, arm_neon_vcvtas, 0),
4263  NEONMAP1(vcvtaq_s32_v, arm_neon_vcvtas, 0),
4264  NEONMAP1(vcvtaq_s64_v, arm_neon_vcvtas, 0),
4265  NEONMAP1(vcvtaq_u16_v, arm_neon_vcvtau, 0),
4266  NEONMAP1(vcvtaq_u32_v, arm_neon_vcvtau, 0),
4267  NEONMAP1(vcvtaq_u64_v, arm_neon_vcvtau, 0),
4268  NEONMAP1(vcvtm_s16_v, arm_neon_vcvtms, 0),
4269  NEONMAP1(vcvtm_s32_v, arm_neon_vcvtms, 0),
4270  NEONMAP1(vcvtm_s64_v, arm_neon_vcvtms, 0),
4271  NEONMAP1(vcvtm_u16_v, arm_neon_vcvtmu, 0),
4272  NEONMAP1(vcvtm_u32_v, arm_neon_vcvtmu, 0),
4273  NEONMAP1(vcvtm_u64_v, arm_neon_vcvtmu, 0),
4274  NEONMAP1(vcvtmq_s16_v, arm_neon_vcvtms, 0),
4275  NEONMAP1(vcvtmq_s32_v, arm_neon_vcvtms, 0),
4276  NEONMAP1(vcvtmq_s64_v, arm_neon_vcvtms, 0),
4277  NEONMAP1(vcvtmq_u16_v, arm_neon_vcvtmu, 0),
4278  NEONMAP1(vcvtmq_u32_v, arm_neon_vcvtmu, 0),
4279  NEONMAP1(vcvtmq_u64_v, arm_neon_vcvtmu, 0),
4280  NEONMAP1(vcvtn_s16_v, arm_neon_vcvtns, 0),
4281  NEONMAP1(vcvtn_s32_v, arm_neon_vcvtns, 0),
4282  NEONMAP1(vcvtn_s64_v, arm_neon_vcvtns, 0),
4283  NEONMAP1(vcvtn_u16_v, arm_neon_vcvtnu, 0),
4284  NEONMAP1(vcvtn_u32_v, arm_neon_vcvtnu, 0),
4285  NEONMAP1(vcvtn_u64_v, arm_neon_vcvtnu, 0),
4286  NEONMAP1(vcvtnq_s16_v, arm_neon_vcvtns, 0),
4287  NEONMAP1(vcvtnq_s32_v, arm_neon_vcvtns, 0),
4288  NEONMAP1(vcvtnq_s64_v, arm_neon_vcvtns, 0),
4289  NEONMAP1(vcvtnq_u16_v, arm_neon_vcvtnu, 0),
4290  NEONMAP1(vcvtnq_u32_v, arm_neon_vcvtnu, 0),
4291  NEONMAP1(vcvtnq_u64_v, arm_neon_vcvtnu, 0),
4292  NEONMAP1(vcvtp_s16_v, arm_neon_vcvtps, 0),
4293  NEONMAP1(vcvtp_s32_v, arm_neon_vcvtps, 0),
4294  NEONMAP1(vcvtp_s64_v, arm_neon_vcvtps, 0),
4295  NEONMAP1(vcvtp_u16_v, arm_neon_vcvtpu, 0),
4296  NEONMAP1(vcvtp_u32_v, arm_neon_vcvtpu, 0),
4297  NEONMAP1(vcvtp_u64_v, arm_neon_vcvtpu, 0),
4298  NEONMAP1(vcvtpq_s16_v, arm_neon_vcvtps, 0),
4299  NEONMAP1(vcvtpq_s32_v, arm_neon_vcvtps, 0),
4300  NEONMAP1(vcvtpq_s64_v, arm_neon_vcvtps, 0),
4301  NEONMAP1(vcvtpq_u16_v, arm_neon_vcvtpu, 0),
4302  NEONMAP1(vcvtpq_u32_v, arm_neon_vcvtpu, 0),
4303  NEONMAP1(vcvtpq_u64_v, arm_neon_vcvtpu, 0),
4304  NEONMAP0(vcvtq_f16_v),
4305  NEONMAP0(vcvtq_f32_v),
4306  NEONMAP2(vcvtq_n_f16_v, arm_neon_vcvtfxu2fp, arm_neon_vcvtfxs2fp, 0),
4307  NEONMAP2(vcvtq_n_f32_v, arm_neon_vcvtfxu2fp, arm_neon_vcvtfxs2fp, 0),
4308  NEONMAP1(vcvtq_n_s16_v, arm_neon_vcvtfp2fxs, 0),
4309  NEONMAP1(vcvtq_n_s32_v, arm_neon_vcvtfp2fxs, 0),
4310  NEONMAP1(vcvtq_n_s64_v, arm_neon_vcvtfp2fxs, 0),
4311  NEONMAP1(vcvtq_n_u16_v, arm_neon_vcvtfp2fxu, 0),
4312  NEONMAP1(vcvtq_n_u32_v, arm_neon_vcvtfp2fxu, 0),
4313  NEONMAP1(vcvtq_n_u64_v, arm_neon_vcvtfp2fxu, 0),
4314  NEONMAP0(vcvtq_s16_v),
4315  NEONMAP0(vcvtq_s32_v),
4316  NEONMAP0(vcvtq_s64_v),
4317  NEONMAP0(vcvtq_u16_v),
4318  NEONMAP0(vcvtq_u32_v),
4319  NEONMAP0(vcvtq_u64_v),
4320  NEONMAP2(vdot_v, arm_neon_udot, arm_neon_sdot, 0),
4321  NEONMAP2(vdotq_v, arm_neon_udot, arm_neon_sdot, 0),
4322  NEONMAP0(vext_v),
4323  NEONMAP0(vextq_v),
4324  NEONMAP0(vfma_v),
4325  NEONMAP0(vfmaq_v),
4326  NEONMAP2(vhadd_v, arm_neon_vhaddu, arm_neon_vhadds, Add1ArgType | UnsignedAlts),
4327  NEONMAP2(vhaddq_v, arm_neon_vhaddu, arm_neon_vhadds, Add1ArgType | UnsignedAlts),
4328  NEONMAP2(vhsub_v, arm_neon_vhsubu, arm_neon_vhsubs, Add1ArgType | UnsignedAlts),
4329  NEONMAP2(vhsubq_v, arm_neon_vhsubu, arm_neon_vhsubs, Add1ArgType | UnsignedAlts),
4330  NEONMAP0(vld1_dup_v),
4331  NEONMAP1(vld1_v, arm_neon_vld1, 0),
4332  NEONMAP1(vld1_x2_v, arm_neon_vld1x2, 0),
4333  NEONMAP1(vld1_x3_v, arm_neon_vld1x3, 0),
4334  NEONMAP1(vld1_x4_v, arm_neon_vld1x4, 0),
4335  NEONMAP0(vld1q_dup_v),
4336  NEONMAP1(vld1q_v, arm_neon_vld1, 0),
4337  NEONMAP1(vld1q_x2_v, arm_neon_vld1x2, 0),
4338  NEONMAP1(vld1q_x3_v, arm_neon_vld1x3, 0),
4339  NEONMAP1(vld1q_x4_v, arm_neon_vld1x4, 0),
4340  NEONMAP1(vld2_dup_v, arm_neon_vld2dup, 0),
4341  NEONMAP1(vld2_lane_v, arm_neon_vld2lane, 0),
4342  NEONMAP1(vld2_v, arm_neon_vld2, 0),
4343  NEONMAP1(vld2q_dup_v, arm_neon_vld2dup, 0),
4344  NEONMAP1(vld2q_lane_v, arm_neon_vld2lane, 0),
4345  NEONMAP1(vld2q_v, arm_neon_vld2, 0),
4346  NEONMAP1(vld3_dup_v, arm_neon_vld3dup, 0),
4347  NEONMAP1(vld3_lane_v, arm_neon_vld3lane, 0),
4348  NEONMAP1(vld3_v, arm_neon_vld3, 0),
4349  NEONMAP1(vld3q_dup_v, arm_neon_vld3dup, 0),
4350  NEONMAP1(vld3q_lane_v, arm_neon_vld3lane, 0),
4351  NEONMAP1(vld3q_v, arm_neon_vld3, 0),
4352  NEONMAP1(vld4_dup_v, arm_neon_vld4dup, 0),
4353  NEONMAP1(vld4_lane_v, arm_neon_vld4lane, 0),
4354  NEONMAP1(vld4_v, arm_neon_vld4, 0),
4355  NEONMAP1(vld4q_dup_v, arm_neon_vld4dup, 0),
4356  NEONMAP1(vld4q_lane_v, arm_neon_vld4lane, 0),
4357  NEONMAP1(vld4q_v, arm_neon_vld4, 0),
4358  NEONMAP2(vmax_v, arm_neon_vmaxu, arm_neon_vmaxs, Add1ArgType | UnsignedAlts),
4359  NEONMAP1(vmaxnm_v, arm_neon_vmaxnm, Add1ArgType),
4360  NEONMAP1(vmaxnmq_v, arm_neon_vmaxnm, Add1ArgType),
4361  NEONMAP2(vmaxq_v, arm_neon_vmaxu, arm_neon_vmaxs, Add1ArgType | UnsignedAlts),
4362  NEONMAP2(vmin_v, arm_neon_vminu, arm_neon_vmins, Add1ArgType | UnsignedAlts),
4363  NEONMAP1(vminnm_v, arm_neon_vminnm, Add1ArgType),
4364  NEONMAP1(vminnmq_v, arm_neon_vminnm, Add1ArgType),
4365  NEONMAP2(vminq_v, arm_neon_vminu, arm_neon_vmins, Add1ArgType | UnsignedAlts),
4366  NEONMAP0(vmovl_v),
4367  NEONMAP0(vmovn_v),
4368  NEONMAP1(vmul_v, arm_neon_vmulp, Add1ArgType),
4369  NEONMAP0(vmull_v),
4370  NEONMAP1(vmulq_v, arm_neon_vmulp, Add1ArgType),
4371  NEONMAP2(vpadal_v, arm_neon_vpadalu, arm_neon_vpadals, UnsignedAlts),
4372  NEONMAP2(vpadalq_v, arm_neon_vpadalu, arm_neon_vpadals, UnsignedAlts),
4373  NEONMAP1(vpadd_v, arm_neon_vpadd, Add1ArgType),
4374  NEONMAP2(vpaddl_v, arm_neon_vpaddlu, arm_neon_vpaddls, UnsignedAlts),
4375  NEONMAP2(vpaddlq_v, arm_neon_vpaddlu, arm_neon_vpaddls, UnsignedAlts),
4376  NEONMAP1(vpaddq_v, arm_neon_vpadd, Add1ArgType),
4377  NEONMAP2(vpmax_v, arm_neon_vpmaxu, arm_neon_vpmaxs, Add1ArgType | UnsignedAlts),
4378  NEONMAP2(vpmin_v, arm_neon_vpminu, arm_neon_vpmins, Add1ArgType | UnsignedAlts),
4379  NEONMAP1(vqabs_v, arm_neon_vqabs, Add1ArgType),
4380  NEONMAP1(vqabsq_v, arm_neon_vqabs, Add1ArgType),
4381  NEONMAP2(vqadd_v, arm_neon_vqaddu, arm_neon_vqadds, Add1ArgType | UnsignedAlts),
4382  NEONMAP2(vqaddq_v, arm_neon_vqaddu, arm_neon_vqadds, Add1ArgType | UnsignedAlts),
4383  NEONMAP2(vqdmlal_v, arm_neon_vqdmull, arm_neon_vqadds, 0),
4384  NEONMAP2(vqdmlsl_v, arm_neon_vqdmull, arm_neon_vqsubs, 0),
4385  NEONMAP1(vqdmulh_v, arm_neon_vqdmulh, Add1ArgType),
4386  NEONMAP1(vqdmulhq_v, arm_neon_vqdmulh, Add1ArgType),
4387  NEONMAP1(vqdmull_v, arm_neon_vqdmull, Add1ArgType),
4388  NEONMAP2(vqmovn_v, arm_neon_vqmovnu, arm_neon_vqmovns, Add1ArgType | UnsignedAlts),
4389  NEONMAP1(vqmovun_v, arm_neon_vqmovnsu, Add1ArgType),
4390  NEONMAP1(vqneg_v, arm_neon_vqneg, Add1ArgType),
4391  NEONMAP1(vqnegq_v, arm_neon_vqneg, Add1ArgType),
4392  NEONMAP1(vqrdmulh_v, arm_neon_vqrdmulh, Add1ArgType),
4393  NEONMAP1(vqrdmulhq_v, arm_neon_vqrdmulh, Add1ArgType),
4394  NEONMAP2(vqrshl_v, arm_neon_vqrshiftu, arm_neon_vqrshifts, Add1ArgType | UnsignedAlts),
4395  NEONMAP2(vqrshlq_v, arm_neon_vqrshiftu, arm_neon_vqrshifts, Add1ArgType | UnsignedAlts),
4396  NEONMAP2(vqshl_n_v, arm_neon_vqshiftu, arm_neon_vqshifts, UnsignedAlts),
4397  NEONMAP2(vqshl_v, arm_neon_vqshiftu, arm_neon_vqshifts, Add1ArgType | UnsignedAlts),
4398  NEONMAP2(vqshlq_n_v, arm_neon_vqshiftu, arm_neon_vqshifts, UnsignedAlts),
4399  NEONMAP2(vqshlq_v, arm_neon_vqshiftu, arm_neon_vqshifts, Add1ArgType | UnsignedAlts),
4400  NEONMAP1(vqshlu_n_v, arm_neon_vqshiftsu, 0),
4401  NEONMAP1(vqshluq_n_v, arm_neon_vqshiftsu, 0),
4402  NEONMAP2(vqsub_v, arm_neon_vqsubu, arm_neon_vqsubs, Add1ArgType | UnsignedAlts),
4403  NEONMAP2(vqsubq_v, arm_neon_vqsubu, arm_neon_vqsubs, Add1ArgType | UnsignedAlts),
4404  NEONMAP1(vraddhn_v, arm_neon_vraddhn, Add1ArgType),
4405  NEONMAP2(vrecpe_v, arm_neon_vrecpe, arm_neon_vrecpe, 0),
4406  NEONMAP2(vrecpeq_v, arm_neon_vrecpe, arm_neon_vrecpe, 0),
4407  NEONMAP1(vrecps_v, arm_neon_vrecps, Add1ArgType),
4408  NEONMAP1(vrecpsq_v, arm_neon_vrecps, Add1ArgType),
4409  NEONMAP2(vrhadd_v, arm_neon_vrhaddu, arm_neon_vrhadds, Add1ArgType | UnsignedAlts),
4410  NEONMAP2(vrhaddq_v, arm_neon_vrhaddu, arm_neon_vrhadds, Add1ArgType | UnsignedAlts),
4411  NEONMAP1(vrnd_v, arm_neon_vrintz, Add1ArgType),
4412  NEONMAP1(vrnda_v, arm_neon_vrinta, Add1ArgType),
4413  NEONMAP1(vrndaq_v, arm_neon_vrinta, Add1ArgType),
4414  NEONMAP0(vrndi_v),
4415  NEONMAP0(vrndiq_v),
4416  NEONMAP1(vrndm_v, arm_neon_vrintm, Add1ArgType),
4417  NEONMAP1(vrndmq_v, arm_neon_vrintm, Add1ArgType),
4418  NEONMAP1(vrndn_v, arm_neon_vrintn, Add1ArgType),
4419  NEONMAP1(vrndnq_v, arm_neon_vrintn, Add1ArgType),
4420  NEONMAP1(vrndp_v, arm_neon_vrintp, Add1ArgType),
4421  NEONMAP1(vrndpq_v, arm_neon_vrintp, Add1ArgType),
4422  NEONMAP1(vrndq_v, arm_neon_vrintz, Add1ArgType),
4423  NEONMAP1(vrndx_v, arm_neon_vrintx, Add1ArgType),
4424  NEONMAP1(vrndxq_v, arm_neon_vrintx, Add1ArgType),
4425  NEONMAP2(vrshl_v, arm_neon_vrshiftu, arm_neon_vrshifts, Add1ArgType | UnsignedAlts),
4426  NEONMAP2(vrshlq_v, arm_neon_vrshiftu, arm_neon_vrshifts, Add1ArgType | UnsignedAlts),
4427  NEONMAP2(vrshr_n_v, arm_neon_vrshiftu, arm_neon_vrshifts, UnsignedAlts),
4428  NEONMAP2(vrshrq_n_v, arm_neon_vrshiftu, arm_neon_vrshifts, UnsignedAlts),
4429  NEONMAP2(vrsqrte_v, arm_neon_vrsqrte, arm_neon_vrsqrte, 0),
4430  NEONMAP2(vrsqrteq_v, arm_neon_vrsqrte, arm_neon_vrsqrte, 0),
4431  NEONMAP1(vrsqrts_v, arm_neon_vrsqrts, Add1ArgType),
4432  NEONMAP1(vrsqrtsq_v, arm_neon_vrsqrts, Add1ArgType),
4433  NEONMAP1(vrsubhn_v, arm_neon_vrsubhn, Add1ArgType),
4434  NEONMAP1(vsha1su0q_v, arm_neon_sha1su0, 0),
4435  NEONMAP1(vsha1su1q_v, arm_neon_sha1su1, 0),
4436  NEONMAP1(vsha256h2q_v, arm_neon_sha256h2, 0),
4437  NEONMAP1(vsha256hq_v, arm_neon_sha256h, 0),
4438  NEONMAP1(vsha256su0q_v, arm_neon_sha256su0, 0),
4439  NEONMAP1(vsha256su1q_v, arm_neon_sha256su1, 0),
4440  NEONMAP0(vshl_n_v),
4441  NEONMAP2(vshl_v, arm_neon_vshiftu, arm_neon_vshifts, Add1ArgType | UnsignedAlts),
4442  NEONMAP0(vshll_n_v),
4443  NEONMAP0(vshlq_n_v),
4444  NEONMAP2(vshlq_v, arm_neon_vshiftu, arm_neon_vshifts, Add1ArgType | UnsignedAlts),
4445  NEONMAP0(vshr_n_v),
4446  NEONMAP0(vshrn_n_v),
4447  NEONMAP0(vshrq_n_v),
4448  NEONMAP1(vst1_v, arm_neon_vst1, 0),
4449  NEONMAP1(vst1_x2_v, arm_neon_vst1x2, 0),
4450  NEONMAP1(vst1_x3_v, arm_neon_vst1x3, 0),
4451  NEONMAP1(vst1_x4_v, arm_neon_vst1x4, 0),
4452  NEONMAP1(vst1q_v, arm_neon_vst1, 0),
4453  NEONMAP1(vst1q_x2_v, arm_neon_vst1x2, 0),
4454  NEONMAP1(vst1q_x3_v, arm_neon_vst1x3, 0),
4455  NEONMAP1(vst1q_x4_v, arm_neon_vst1x4, 0),
4456  NEONMAP1(vst2_lane_v, arm_neon_vst2lane, 0),
4457  NEONMAP1(vst2_v, arm_neon_vst2, 0),
4458  NEONMAP1(vst2q_lane_v, arm_neon_vst2lane, 0),
4459  NEONMAP1(vst2q_v, arm_neon_vst2, 0),
4460  NEONMAP1(vst3_lane_v, arm_neon_vst3lane, 0),
4461  NEONMAP1(vst3_v, arm_neon_vst3, 0),
4462  NEONMAP1(vst3q_lane_v, arm_neon_vst3lane, 0),
4463  NEONMAP1(vst3q_v, arm_neon_vst3, 0),
4464  NEONMAP1(vst4_lane_v, arm_neon_vst4lane, 0),
4465  NEONMAP1(vst4_v, arm_neon_vst4, 0),
4466  NEONMAP1(vst4q_lane_v, arm_neon_vst4lane, 0),
4467  NEONMAP1(vst4q_v, arm_neon_vst4, 0),
4468  NEONMAP0(vsubhn_v),
4469  NEONMAP0(vtrn_v),
4470  NEONMAP0(vtrnq_v),
4471  NEONMAP0(vtst_v),
4472  NEONMAP0(vtstq_v),
4473  NEONMAP0(vuzp_v),
4474  NEONMAP0(vuzpq_v),
4475  NEONMAP0(vzip_v),
4476  NEONMAP0(vzipq_v)
4477 };
4478 
4479 static const NeonIntrinsicInfo AArch64SIMDIntrinsicMap[] = {
4480  NEONMAP1(vabs_v, aarch64_neon_abs, 0),
4481  NEONMAP1(vabsq_v, aarch64_neon_abs, 0),
4482  NEONMAP0(vaddhn_v),
4483  NEONMAP1(vaesdq_v, aarch64_crypto_aesd, 0),
4484  NEONMAP1(vaeseq_v, aarch64_crypto_aese, 0),
4485  NEONMAP1(vaesimcq_v, aarch64_crypto_aesimc, 0),
4486  NEONMAP1(vaesmcq_v, aarch64_crypto_aesmc, 0),
4487  NEONMAP1(vcage_v, aarch64_neon_facge, 0),
4488  NEONMAP1(vcageq_v, aarch64_neon_facge, 0),
4489  NEONMAP1(vcagt_v, aarch64_neon_facgt, 0),
4490  NEONMAP1(vcagtq_v, aarch64_neon_facgt, 0),
4491  NEONMAP1(vcale_v, aarch64_neon_facge, 0),
4492  NEONMAP1(vcaleq_v, aarch64_neon_facge, 0),
4493  NEONMAP1(vcalt_v, aarch64_neon_facgt, 0),
4494  NEONMAP1(vcaltq_v, aarch64_neon_facgt, 0),
4495  NEONMAP0(vceqz_v),
4496  NEONMAP0(vceqzq_v),
4497  NEONMAP0(vcgez_v),
4498  NEONMAP0(vcgezq_v),
4499  NEONMAP0(vcgtz_v),
4500  NEONMAP0(vcgtzq_v),
4501  NEONMAP0(vclez_v),
4502  NEONMAP0(vclezq_v),
4503  NEONMAP1(vcls_v, aarch64_neon_cls, Add1ArgType),
4504  NEONMAP1(vclsq_v, aarch64_neon_cls, Add1ArgType),
4505  NEONMAP0(vcltz_v),
4506  NEONMAP0(vcltzq_v),
4507  NEONMAP1(vclz_v, ctlz, Add1ArgType),
4508  NEONMAP1(vclzq_v, ctlz, Add1ArgType),
4509  NEONMAP1(vcnt_v, ctpop, Add1ArgType),
4510  NEONMAP1(vcntq_v, ctpop, Add1ArgType),
4511  NEONMAP1(vcvt_f16_f32, aarch64_neon_vcvtfp2hf, 0),
4512  NEONMAP0(vcvt_f16_v),
4513  NEONMAP1(vcvt_f32_f16, aarch64_neon_vcvthf2fp, 0),
4514  NEONMAP0(vcvt_f32_v),
4515  NEONMAP2(vcvt_n_f16_v, aarch64_neon_vcvtfxu2fp, aarch64_neon_vcvtfxs2fp, 0),
4516  NEONMAP2(vcvt_n_f32_v, aarch64_neon_vcvtfxu2fp, aarch64_neon_vcvtfxs2fp, 0),
4517  NEONMAP2(vcvt_n_f64_v, aarch64_neon_vcvtfxu2fp, aarch64_neon_vcvtfxs2fp, 0),
4518  NEONMAP1(vcvt_n_s16_v, aarch64_neon_vcvtfp2fxs, 0),
4519  NEONMAP1(vcvt_n_s32_v, aarch64_neon_vcvtfp2fxs, 0),
4520  NEONMAP1(vcvt_n_s64_v, aarch64_neon_vcvtfp2fxs, 0),
4521  NEONMAP1(vcvt_n_u16_v, aarch64_neon_vcvtfp2fxu, 0),
4522  NEONMAP1(vcvt_n_u32_v, aarch64_neon_vcvtfp2fxu, 0),
4523  NEONMAP1(vcvt_n_u64_v, aarch64_neon_vcvtfp2fxu, 0),
4524  NEONMAP0(vcvtq_f16_v),
4525  NEONMAP0(vcvtq_f32_v),
4526  NEONMAP2(vcvtq_n_f16_v, aarch64_neon_vcvtfxu2fp, aarch64_neon_vcvtfxs2fp, 0),
4527  NEONMAP2(vcvtq_n_f32_v, aarch64_neon_vcvtfxu2fp, aarch64_neon_vcvtfxs2fp, 0),
4528  NEONMAP2(vcvtq_n_f64_v, aarch64_neon_vcvtfxu2fp, aarch64_neon_vcvtfxs2fp, 0),
4529  NEONMAP1(vcvtq_n_s16_v, aarch64_neon_vcvtfp2fxs, 0),
4530  NEONMAP1(vcvtq_n_s32_v, aarch64_neon_vcvtfp2fxs, 0),
4531  NEONMAP1(vcvtq_n_s64_v, aarch64_neon_vcvtfp2fxs, 0),
4532  NEONMAP1(vcvtq_n_u16_v, aarch64_neon_vcvtfp2fxu, 0),
4533  NEONMAP1(vcvtq_n_u32_v, aarch64_neon_vcvtfp2fxu, 0),
4534  NEONMAP1(vcvtq_n_u64_v, aarch64_neon_vcvtfp2fxu, 0),
4535  NEONMAP1(vcvtx_f32_v, aarch64_neon_fcvtxn, AddRetType | Add1ArgType),
4536  NEONMAP2(vdot_v, aarch64_neon_udot, aarch64_neon_sdot, 0),
4537  NEONMAP2(vdotq_v, aarch64_neon_udot, aarch64_neon_sdot, 0),
4538  NEONMAP0(vext_v),
4539  NEONMAP0(vextq_v),
4540  NEONMAP0(vfma_v),
4541  NEONMAP0(vfmaq_v),
4542  NEONMAP1(vfmlal_high_v, aarch64_neon_fmlal2, 0),
4543  NEONMAP1(vfmlal_low_v, aarch64_neon_fmlal, 0),
4544  NEONMAP1(vfmlalq_high_v, aarch64_neon_fmlal2, 0),
4545  NEONMAP1(vfmlalq_low_v, aarch64_neon_fmlal, 0),
4546  NEONMAP1(vfmlsl_high_v, aarch64_neon_fmlsl2, 0),
4547  NEONMAP1(vfmlsl_low_v, aarch64_neon_fmlsl, 0),
4548  NEONMAP1(vfmlslq_high_v, aarch64_neon_fmlsl2, 0),
4549  NEONMAP1(vfmlslq_low_v, aarch64_neon_fmlsl, 0),
4550  NEONMAP2(vhadd_v, aarch64_neon_uhadd, aarch64_neon_shadd, Add1ArgType | UnsignedAlts),
4551  NEONMAP2(vhaddq_v, aarch64_neon_uhadd, aarch64_neon_shadd, Add1ArgType | UnsignedAlts),
4552  NEONMAP2(vhsub_v, aarch64_neon_uhsub, aarch64_neon_shsub, Add1ArgType | UnsignedAlts),
4553  NEONMAP2(vhsubq_v, aarch64_neon_uhsub, aarch64_neon_shsub, Add1ArgType | UnsignedAlts),
4554  NEONMAP1(vld1_x2_v, aarch64_neon_ld1x2, 0),
4555  NEONMAP1(vld1_x3_v, aarch64_neon_ld1x3, 0),
4556  NEONMAP1(vld1_x4_v, aarch64_neon_ld1x4, 0),
4557  NEONMAP1(vld1q_x2_v, aarch64_neon_ld1x2, 0),
4558  NEONMAP1(vld1q_x3_v, aarch64_neon_ld1x3, 0),
4559  NEONMAP1(vld1q_x4_v, aarch64_neon_ld1x4, 0),
4560  NEONMAP0(vmovl_v),
4561  NEONMAP0(vmovn_v),
4562  NEONMAP1(vmul_v, aarch64_neon_pmul, Add1ArgType),
4563  NEONMAP1(vmulq_v, aarch64_neon_pmul, Add1ArgType),
4564  NEONMAP1(vpadd_v, aarch64_neon_addp, Add1ArgType),
4565  NEONMAP2(vpaddl_v, aarch64_neon_uaddlp, aarch64_neon_saddlp, UnsignedAlts),
4566  NEONMAP2(vpaddlq_v, aarch64_neon_uaddlp, aarch64_neon_saddlp, UnsignedAlts),
4567  NEONMAP1(vpaddq_v, aarch64_neon_addp, Add1ArgType),
4568  NEONMAP1(vqabs_v, aarch64_neon_sqabs, Add1ArgType),
4569  NEONMAP1(vqabsq_v, aarch64_neon_sqabs, Add1ArgType),
4570  NEONMAP2(vqadd_v, aarch64_neon_uqadd, aarch64_neon_sqadd, Add1ArgType | UnsignedAlts),
4571  NEONMAP2(vqaddq_v, aarch64_neon_uqadd, aarch64_neon_sqadd, Add1ArgType | UnsignedAlts),
4572  NEONMAP2(vqdmlal_v, aarch64_neon_sqdmull, aarch64_neon_sqadd, 0),
4573  NEONMAP2(vqdmlsl_v, aarch64_neon_sqdmull, aarch64_neon_sqsub, 0),
4574  NEONMAP1(vqdmulh_v, aarch64_neon_sqdmulh, Add1ArgType),
4575  NEONMAP1(vqdmulhq_v, aarch64_neon_sqdmulh, Add1ArgType),
4576  NEONMAP1(vqdmull_v, aarch64_neon_sqdmull, Add1ArgType),
4577  NEONMAP2(vqmovn_v, aarch64_neon_uqxtn, aarch64_neon_sqxtn, Add1ArgType | UnsignedAlts),
4578  NEONMAP1(vqmovun_v, aarch64_neon_sqxtun, Add1ArgType),
4579  NEONMAP1(vqneg_v, aarch64_neon_sqneg, Add1ArgType),
4580  NEONMAP1(vqnegq_v, aarch64_neon_sqneg, Add1ArgType),
4581  NEONMAP1(vqrdmulh_v, aarch64_neon_sqrdmulh, Add1ArgType),
4582  NEONMAP1(vqrdmulhq_v, aarch64_neon_sqrdmulh, Add1ArgType),
4583  NEONMAP2(vqrshl_v, aarch64_neon_uqrshl, aarch64_neon_sqrshl, Add1ArgType | UnsignedAlts),
4584  NEONMAP2(vqrshlq_v, aarch64_neon_uqrshl, aarch64_neon_sqrshl, Add1ArgType | UnsignedAlts),
4585  NEONMAP2(vqshl_n_v, aarch64_neon_uqshl, aarch64_neon_sqshl, UnsignedAlts),
4586  NEONMAP2(vqshl_v, aarch64_neon_uqshl, aarch64_neon_sqshl, Add1ArgType | UnsignedAlts),
4587  NEONMAP2(vqshlq_n_v, aarch64_neon_uqshl, aarch64_neon_sqshl,UnsignedAlts),
4588  NEONMAP2(vqshlq_v, aarch64_neon_uqshl, aarch64_neon_sqshl, Add1ArgType | UnsignedAlts),
4589  NEONMAP1(vqshlu_n_v, aarch64_neon_sqshlu, 0),
4590  NEONMAP1(vqshluq_n_v, aarch64_neon_sqshlu, 0),
4591  NEONMAP2(vqsub_v, aarch64_neon_uqsub, aarch64_neon_sqsub, Add1ArgType | UnsignedAlts),
4592  NEONMAP2(vqsubq_v, aarch64_neon_uqsub, aarch64_neon_sqsub, Add1ArgType | UnsignedAlts),
4593  NEONMAP1(vraddhn_v, aarch64_neon_raddhn, Add1ArgType),
4594  NEONMAP2(vrecpe_v, aarch64_neon_frecpe, aarch64_neon_urecpe, 0),
4595  NEONMAP2(vrecpeq_v, aarch64_neon_frecpe, aarch64_neon_urecpe, 0),
4596  NEONMAP1(vrecps_v, aarch64_neon_frecps, Add1ArgType),
4597  NEONMAP1(vrecpsq_v, aarch64_neon_frecps, Add1ArgType),
4598  NEONMAP2(vrhadd_v, aarch64_neon_urhadd, aarch64_neon_srhadd, Add1ArgType | UnsignedAlts),
4599  NEONMAP2(vrhaddq_v, aarch64_neon_urhadd, aarch64_neon_srhadd, Add1ArgType | UnsignedAlts),
4600  NEONMAP0(vrndi_v),
4601  NEONMAP0(vrndiq_v),
4602  NEONMAP2(vrshl_v, aarch64_neon_urshl, aarch64_neon_srshl, Add1ArgType | UnsignedAlts),
4603  NEONMAP2(vrshlq_v, aarch64_neon_urshl, aarch64_neon_srshl, Add1ArgType | UnsignedAlts),
4604  NEONMAP2(vrshr_n_v, aarch64_neon_urshl, aarch64_neon_srshl, UnsignedAlts),
4605  NEONMAP2(vrshrq_n_v, aarch64_neon_urshl, aarch64_neon_srshl, UnsignedAlts),
4606  NEONMAP2(vrsqrte_v, aarch64_neon_frsqrte, aarch64_neon_ursqrte, 0),
4607  NEONMAP2(vrsqrteq_v, aarch64_neon_frsqrte, aarch64_neon_ursqrte, 0),
4608  NEONMAP1(vrsqrts_v, aarch64_neon_frsqrts, Add1ArgType),
4609  NEONMAP1(vrsqrtsq_v, aarch64_neon_frsqrts, Add1ArgType),
4610  NEONMAP1(vrsubhn_v, aarch64_neon_rsubhn, Add1ArgType),
4611  NEONMAP1(vsha1su0q_v, aarch64_crypto_sha1su0, 0),
4612  NEONMAP1(vsha1su1q_v, aarch64_crypto_sha1su1, 0),
4613  NEONMAP1(vsha256h2q_v, aarch64_crypto_sha256h2, 0),
4614  NEONMAP1(vsha256hq_v, aarch64_crypto_sha256h, 0),
4615  NEONMAP1(vsha256su0q_v, aarch64_crypto_sha256su0, 0),
4616  NEONMAP1(vsha256su1q_v, aarch64_crypto_sha256su1, 0),
4617  NEONMAP0(vshl_n_v),
4618  NEONMAP2(vshl_v, aarch64_neon_ushl, aarch64_neon_sshl, Add1ArgType | UnsignedAlts),
4619  NEONMAP0(vshll_n_v),
4620  NEONMAP0(vshlq_n_v),
4621  NEONMAP2(vshlq_v, aarch64_neon_ushl, aarch64_neon_sshl, Add1ArgType | UnsignedAlts),
4622  NEONMAP0(vshr_n_v),
4623  NEONMAP0(vshrn_n_v),
4624  NEONMAP0(vshrq_n_v),
4625  NEONMAP1(vst1_x2_v, aarch64_neon_st1x2, 0),
4626  NEONMAP1(vst1_x3_v, aarch64_neon_st1x3, 0),
4627  NEONMAP1(vst1_x4_v, aarch64_neon_st1x4, 0),
4628  NEONMAP1(vst1q_x2_v, aarch64_neon_st1x2, 0),
4629  NEONMAP1(vst1q_x3_v, aarch64_neon_st1x3, 0),
4630  NEONMAP1(vst1q_x4_v, aarch64_neon_st1x4, 0),
4631  NEONMAP0(vsubhn_v),
4632  NEONMAP0(vtst_v),
4633  NEONMAP0(vtstq_v),
4634 };
4635 
4636 static const NeonIntrinsicInfo AArch64SISDIntrinsicMap[] = {
4637  NEONMAP1(vabdd_f64, aarch64_sisd_fabd, Add1ArgType),
4638  NEONMAP1(vabds_f32, aarch64_sisd_fabd, Add1ArgType),
4639  NEONMAP1(vabsd_s64, aarch64_neon_abs, Add1ArgType),
4640  NEONMAP1(vaddlv_s32, aarch64_neon_saddlv, AddRetType | Add1ArgType),
4641  NEONMAP1(vaddlv_u32, aarch64_neon_uaddlv, AddRetType | Add1ArgType),
4642  NEONMAP1(vaddlvq_s32, aarch64_neon_saddlv, AddRetType | Add1ArgType),
4643  NEONMAP1(vaddlvq_u32, aarch64_neon_uaddlv, AddRetType | Add1ArgType),
4644  NEONMAP1(vaddv_f32, aarch64_neon_faddv, AddRetType | Add1ArgType),
4645  NEONMAP1(vaddv_s32, aarch64_neon_saddv, AddRetType | Add1ArgType),
4646  NEONMAP1(vaddv_u32, aarch64_neon_uaddv, AddRetType | Add1ArgType),
4647  NEONMAP1(vaddvq_f32, aarch64_neon_faddv, AddRetType | Add1ArgType),
4648  NEONMAP1(vaddvq_f64, aarch64_neon_faddv, AddRetType | Add1ArgType),
4649  NEONMAP1(vaddvq_s32, aarch64_neon_saddv, AddRetType | Add1ArgType),
4650  NEONMAP1(vaddvq_s64, aarch64_neon_saddv, AddRetType | Add1ArgType),
4651  NEONMAP1(vaddvq_u32, aarch64_neon_uaddv, AddRetType | Add1ArgType),
4652  NEONMAP1(vaddvq_u64, aarch64_neon_uaddv, AddRetType | Add1ArgType),
4653  NEONMAP1(vcaged_f64, aarch64_neon_facge, AddRetType | Add1ArgType),
4654  NEONMAP1(vcages_f32, aarch64_neon_facge, AddRetType | Add1ArgType),
4655  NEONMAP1(vcagtd_f64, aarch64_neon_facgt, AddRetType | Add1ArgType),
4656  NEONMAP1(vcagts_f32, aarch64_neon_facgt, AddRetType | Add1ArgType),
4657  NEONMAP1(vcaled_f64, aarch64_neon_facge, AddRetType | Add1ArgType),
4658  NEONMAP1(vcales_f32, aarch64_neon_facge, AddRetType | Add1ArgType),
4659  NEONMAP1(vcaltd_f64, aarch64_neon_facgt, AddRetType | Add1ArgType),
4660  NEONMAP1(vcalts_f32, aarch64_neon_facgt, AddRetType | Add1ArgType),
4661  NEONMAP1(vcvtad_s64_f64, aarch64_neon_fcvtas, AddRetType | Add1ArgType),
4662  NEONMAP1(vcvtad_u64_f64, aarch64_neon_fcvtau, AddRetType | Add1ArgType),
4663  NEONMAP1(vcvtas_s32_f32, aarch64_neon_fcvtas, AddRetType | Add1ArgType),
4664  NEONMAP1(vcvtas_u32_f32, aarch64_neon_fcvtau, AddRetType | Add1ArgType),
4665  NEONMAP1(vcvtd_n_f64_s64, aarch64_neon_vcvtfxs2fp, AddRetType | Add1ArgType),
4666  NEONMAP1(vcvtd_n_f64_u64, aarch64_neon_vcvtfxu2fp, AddRetType | Add1ArgType),
4667  NEONMAP1(vcvtd_n_s64_f64, aarch64_neon_vcvtfp2fxs, AddRetType | Add1ArgType),
4668  NEONMAP1(vcvtd_n_u64_f64, aarch64_neon_vcvtfp2fxu, AddRetType | Add1ArgType),
4669  NEONMAP1(vcvtmd_s64_f64, aarch64_neon_fcvtms, AddRetType | Add1ArgType),
4670  NEONMAP1(vcvtmd_u64_f64, aarch64_neon_fcvtmu, AddRetType | Add1ArgType),
4671  NEONMAP1(vcvtms_s32_f32, aarch64_neon_fcvtms, AddRetType | Add1ArgType),
4672  NEONMAP1(vcvtms_u32_f32, aarch64_neon_fcvtmu, AddRetType | Add1ArgType),
4673  NEONMAP1(vcvtnd_s64_f64, aarch64_neon_fcvtns, AddRetType | Add1ArgType),
4674  NEONMAP1(vcvtnd_u64_f64, aarch64_neon_fcvtnu, AddRetType | Add1ArgType),
4675  NEONMAP1(vcvtns_s32_f32, aarch64_neon_fcvtns, AddRetType | Add1ArgType),
4676  NEONMAP1(vcvtns_u32_f32, aarch64_neon_fcvtnu, AddRetType | Add1ArgType),
4677  NEONMAP1(vcvtpd_s64_f64, aarch64_neon_fcvtps, AddRetType | Add1ArgType),
4678  NEONMAP1(vcvtpd_u64_f64, aarch64_neon_fcvtpu, AddRetType | Add1ArgType),
4679  NEONMAP1(vcvtps_s32_f32, aarch64_neon_fcvtps, AddRetType | Add1ArgType),
4680  NEONMAP1(vcvtps_u32_f32, aarch64_neon_fcvtpu, AddRetType | Add1ArgType),
4681  NEONMAP1(vcvts_n_f32_s32, aarch64_neon_vcvtfxs2fp, AddRetType | Add1ArgType),
4682  NEONMAP1(vcvts_n_f32_u32, aarch64_neon_vcvtfxu2fp, AddRetType | Add1ArgType),
4683  NEONMAP1(vcvts_n_s32_f32, aarch64_neon_vcvtfp2fxs, AddRetType | Add1ArgType),
4684  NEONMAP1(vcvts_n_u32_f32, aarch64_neon_vcvtfp2fxu, AddRetType | Add1ArgType),
4685  NEONMAP1(vcvtxd_f32_f64, aarch64_sisd_fcvtxn, 0),
4686  NEONMAP1(vmaxnmv_f32, aarch64_neon_fmaxnmv, AddRetType | Add1ArgType),
4687  NEONMAP1(vmaxnmvq_f32, aarch64_neon_fmaxnmv, AddRetType | Add1ArgType),
4688  NEONMAP1(vmaxnmvq_f64, aarch64_neon_fmaxnmv, AddRetType | Add1ArgType),
4689  NEONMAP1(vmaxv_f32, aarch64_neon_fmaxv, AddRetType | Add1ArgType),
4690  NEONMAP1(vmaxv_s32, aarch64_neon_smaxv, AddRetType | Add1ArgType),
4691  NEONMAP1(vmaxv_u32, aarch64_neon_umaxv, AddRetType | Add1ArgType),
4692  NEONMAP1(vmaxvq_f32, aarch64_neon_fmaxv, AddRetType | Add1ArgType),
4693  NEONMAP1(vmaxvq_f64, aarch64_neon_fmaxv, AddRetType | Add1ArgType),
4694  NEONMAP1(vmaxvq_s32, aarch64_neon_smaxv, AddRetType | Add1ArgType),
4695  NEONMAP1(vmaxvq_u32, aarch64_neon_umaxv, AddRetType | Add1ArgType),
4696  NEONMAP1(vminnmv_f32, aarch64_neon_fminnmv, AddRetType | Add1ArgType),
4697  NEONMAP1(vminnmvq_f32, aarch64_neon_fminnmv, AddRetType | Add1ArgType),
4698  NEONMAP1(vminnmvq_f64, aarch64_neon_fminnmv, AddRetType | Add1ArgType),
4699  NEONMAP1(vminv_f32, aarch64_neon_fminv, AddRetType | Add1ArgType),
4700  NEONMAP1(vminv_s32, aarch64_neon_sminv, AddRetType | Add1ArgType),
4701  NEONMAP1(vminv_u32, aarch64_neon_uminv, AddRetType | Add1ArgType),
4702  NEONMAP1(vminvq_f32, aarch64_neon_fminv, AddRetType | Add1ArgType),
4703  NEONMAP1(vminvq_f64, aarch64_neon_fminv, AddRetType | Add1ArgType),
4704  NEONMAP1(vminvq_s32, aarch64_neon_sminv, AddRetType | Add1ArgType),
4705  NEONMAP1(vminvq_u32, aarch64_neon_uminv, AddRetType | Add1ArgType),
4706  NEONMAP1(vmull_p64, aarch64_neon_pmull64, 0),
4707  NEONMAP1(vmulxd_f64, aarch64_neon_fmulx, Add1ArgType),
4708  NEONMAP1(vmulxs_f32, aarch64_neon_fmulx, Add1ArgType),
4709  NEONMAP1(vpaddd_s64, aarch64_neon_uaddv, AddRetType | Add1ArgType),
4710  NEONMAP1(vpaddd_u64, aarch64_neon_uaddv, AddRetType | Add1ArgType),
4711  NEONMAP1(vpmaxnmqd_f64, aarch64_neon_fmaxnmv, AddRetType | Add1ArgType),
4712  NEONMAP1(vpmaxnms_f32, aarch64_neon_fmaxnmv, AddRetType | Add1ArgType),
4713  NEONMAP1(vpmaxqd_f64, aarch64_neon_fmaxv, AddRetType | Add1ArgType),
4714  NEONMAP1(vpmaxs_f32, aarch64_neon_fmaxv, AddRetType | Add1ArgType),
4715  NEONMAP1(vpminnmqd_f64, aarch64_neon_fminnmv, AddRetType | Add1ArgType),
4716  NEONMAP1(vpminnms_f32, aarch64_neon_fminnmv, AddRetType | Add1ArgType),
4717  NEONMAP1(vpminqd_f64, aarch64_neon_fminv, AddRetType | Add1ArgType),
4718  NEONMAP1(vpmins_f32, aarch64_neon_fminv, AddRetType | Add1ArgType),
4719  NEONMAP1(vqabsb_s8, aarch64_neon_sqabs, Vectorize1ArgType | Use64BitVectors),
4720  NEONMAP1(vqabsd_s64, aarch64_neon_sqabs, Add1ArgType),
4721  NEONMAP1(vqabsh_s16, aarch64_neon_sqabs, Vectorize1ArgType | Use64BitVectors),
4722  NEONMAP1(vqabss_s32, aarch64_neon_sqabs, Add1ArgType),
4723  NEONMAP1(vqaddb_s8, aarch64_neon_sqadd, Vectorize1ArgType | Use64BitVectors),
4724  NEONMAP1(vqaddb_u8, aarch64_neon_uqadd, Vectorize1ArgType | Use64BitVectors),
4725  NEONMAP1(vqaddd_s64, aarch64_neon_sqadd, Add1ArgType),
4726  NEONMAP1(vqaddd_u64, aarch64_neon_uqadd, Add1ArgType),
4727  NEONMAP1(vqaddh_s16, aarch64_neon_sqadd, Vectorize1ArgType | Use64BitVectors),
4728  NEONMAP1(vqaddh_u16, aarch64_neon_uqadd, Vectorize1ArgType | Use64BitVectors),
4729  NEONMAP1(vqadds_s32, aarch64_neon_sqadd, Add1ArgType),
4730  NEONMAP1(vqadds_u32, aarch64_neon_uqadd, Add1ArgType),
4731  NEONMAP1(vqdmulhh_s16, aarch64_neon_sqdmulh, Vectorize1ArgType | Use64BitVectors),
4732  NEONMAP1(vqdmulhs_s32, aarch64_neon_sqdmulh, Add1ArgType),
4733  NEONMAP1(vqdmullh_s16, aarch64_neon_sqdmull, VectorRet | Use128BitVectors),
4734  NEONMAP1(vqdmulls_s32, aarch64_neon_sqdmulls_scalar, 0),
4735  NEONMAP1(vqmovnd_s64, aarch64_neon_scalar_sqxtn, AddRetType | Add1ArgType),
4736  NEONMAP1(vqmovnd_u64, aarch64_neon_scalar_uqxtn, AddRetType | Add1ArgType),
4737  NEONMAP1(vqmovnh_s16, aarch64_neon_sqxtn, VectorRet | Use64BitVectors),
4738  NEONMAP1(vqmovnh_u16, aarch64_neon_uqxtn, VectorRet | Use64BitVectors),
4739  NEONMAP1(vqmovns_s32, aarch64_neon_sqxtn, VectorRet | Use64BitVectors),
4740  NEONMAP1(vqmovns_u32, aarch64_neon_uqxtn, VectorRet | Use64BitVectors),
4741  NEONMAP1(vqmovund_s64, aarch64_neon_scalar_sqxtun, AddRetType | Add1ArgType),
4742  NEONMAP1(vqmovunh_s16, aarch64_neon_sqxtun, VectorRet | Use64BitVectors),
4743  NEONMAP1(vqmovuns_s32, aarch64_neon_sqxtun, VectorRet | Use64BitVectors),
4744  NEONMAP1(vqnegb_s8, aarch64_neon_sqneg, Vectorize1ArgType | Use64BitVectors),
4745  NEONMAP1(vqnegd_s64, aarch64_neon_sqneg, Add1ArgType),
4746  NEONMAP1(vqnegh_s16, aarch64_neon_sqneg, Vectorize1ArgType | Use64BitVectors),
4747  NEONMAP1(vqnegs_s32, aarch64_neon_sqneg, Add1ArgType),
4748  NEONMAP1(vqrdmulhh_s16, aarch64_neon_sqrdmulh, Vectorize1ArgType | Use64BitVectors),
4749  NEONMAP1(vqrdmulhs_s32, aarch64_neon_sqrdmulh, Add1ArgType),
4750  NEONMAP1(vqrshlb_s8, aarch64_neon_sqrshl, Vectorize1ArgType | Use64BitVectors),
4751  NEONMAP1(vqrshlb_u8, aarch64_neon_uqrshl, Vectorize1ArgType | Use64BitVectors),
4752  NEONMAP1(vqrshld_s64, aarch64_neon_sqrshl, Add1ArgType),
4753  NEONMAP1(vqrshld_u64, aarch64_neon_uqrshl, Add1ArgType),
4754  NEONMAP1(vqrshlh_s16, aarch64_neon_sqrshl, Vectorize1ArgType | Use64BitVectors),
4755  NEONMAP1(vqrshlh_u16, aarch64_neon_uqrshl, Vectorize1ArgType | Use64BitVectors),
4756  NEONMAP1(vqrshls_s32, aarch64_neon_sqrshl, Add1ArgType),
4757  NEONMAP1(vqrshls_u32, aarch64_neon_uqrshl, Add1ArgType),
4758  NEONMAP1(vqrshrnd_n_s64, aarch64_neon_sqrshrn, AddRetType),
4759  NEONMAP1(vqrshrnd_n_u64, aarch64_neon_uqrshrn, AddRetType),
4760  NEONMAP1(vqrshrnh_n_s16, aarch64_neon_sqrshrn, VectorRet | Use64BitVectors),
4761  NEONMAP1(vqrshrnh_n_u16, aarch64_neon_uqrshrn, VectorRet | Use64BitVectors),
4762  NEONMAP1(vqrshrns_n_s32, aarch64_neon_sqrshrn, VectorRet | Use64BitVectors),
4763  NEONMAP1(vqrshrns_n_u32, aarch64_neon_uqrshrn, VectorRet | Use64BitVectors),
4764  NEONMAP1(vqrshrund_n_s64, aarch64_neon_sqrshrun, AddRetType),
4765  NEONMAP1(vqrshrunh_n_s16, aarch64_neon_sqrshrun, VectorRet | Use64BitVectors),
4766  NEONMAP1(vqrshruns_n_s32, aarch64_neon_sqrshrun, VectorRet | Use64BitVectors),
4767  NEONMAP1(vqshlb_n_s8, aarch64_neon_sqshl, Vectorize1ArgType | Use64BitVectors),
4768  NEONMAP1(vqshlb_n_u8, aarch64_neon_uqshl, Vectorize1ArgType | Use64BitVectors),
4769  NEONMAP1(vqshlb_s8, aarch64_neon_sqshl, Vectorize1ArgType | Use64BitVectors),
4770  NEONMAP1(vqshlb_u8, aarch64_neon_uqshl, Vectorize1ArgType | Use64BitVectors),
4771  NEONMAP1(vqshld_s64, aarch64_neon_sqshl, Add1ArgType),
4772  NEONMAP1(vqshld_u64, aarch64_neon_uqshl, Add1ArgType),
4773  NEONMAP1(vqshlh_n_s16, aarch64_neon_sqshl, Vectorize1ArgType | Use64BitVectors),
4774  NEONMAP1(vqshlh_n_u16, aarch64_neon_uqshl, Vectorize1ArgType | Use64BitVectors),
4775  NEONMAP1(vqshlh_s16, aarch64_neon_sqshl, Vectorize1ArgType | Use64BitVectors),
4776  NEONMAP1(vqshlh_u16, aarch64_neon_uqshl, Vectorize1ArgType | Use64BitVectors),
4777  NEONMAP1(vqshls_n_s32, aarch64_neon_sqshl, Add1ArgType),
4778  NEONMAP1(vqshls_n_u32, aarch64_neon_uqshl, Add1ArgType),
4779  NEONMAP1(vqshls_s32, aarch64_neon_sqshl, Add1ArgType),
4780  NEONMAP1(vqshls_u32, aarch64_neon_uqshl, Add1ArgType),
4781  NEONMAP1(vqshlub_n_s8, aarch64_neon_sqshlu, Vectorize1ArgType | Use64BitVectors),
4782  NEONMAP1(vqshluh_n_s16, aarch64_neon_sqshlu, Vectorize1ArgType | Use64BitVectors),
4783  NEONMAP1(vqshlus_n_s32, aarch64_neon_sqshlu, Add1ArgType),
4784  NEONMAP1(vqshrnd_n_s64, aarch64_neon_sqshrn, AddRetType),
4785  NEONMAP1(vqshrnd_n_u64, aarch64_neon_uqshrn, AddRetType),
4786  NEONMAP1(vqshrnh_n_s16, aarch64_neon_sqshrn, VectorRet | Use64BitVectors),
4787  NEONMAP1(vqshrnh_n_u16, aarch64_neon_uqshrn, VectorRet | Use64BitVectors),
4788  NEONMAP1(vqshrns_n_s32, aarch64_neon_sqshrn, VectorRet | Use64BitVectors),
4789  NEONMAP1(vqshrns_n_u32, aarch64_neon_uqshrn, VectorRet | Use64BitVectors),
4790  NEONMAP1(vqshrund_n_s64, aarch64_neon_sqshrun, AddRetType),
4791  NEONMAP1(vqshrunh_n_s16, aarch64_neon_sqshrun, VectorRet | Use64BitVectors),
4792  NEONMAP1(vqshruns_n_s32, aarch64_neon_sqshrun, VectorRet | Use64BitVectors),
4793  NEONMAP1(vqsubb_s8, aarch64_neon_sqsub, Vectorize1ArgType | Use64BitVectors),
4794  NEONMAP1(vqsubb_u8, aarch64_neon_uqsub, Vectorize1ArgType | Use64BitVectors),
4795  NEONMAP1(vqsubd_s64, aarch64_neon_sqsub, Add1ArgType),
4796  NEONMAP1(vqsubd_u64, aarch64_neon_uqsub, Add1ArgType),
4797  NEONMAP1(vqsubh_s16, aarch64_neon_sqsub, Vectorize1ArgType | Use64BitVectors),
4798  NEONMAP1(vqsubh_u16, aarch64_neon_uqsub, Vectorize1ArgType | Use64BitVectors),
4799  NEONMAP1(vqsubs_s32, aarch64_neon_sqsub, Add1ArgType),
4800  NEONMAP1(vqsubs_u32, aarch64_neon_uqsub, Add1ArgType),
4801  NEONMAP1(vrecped_f64, aarch64_neon_frecpe, Add1ArgType),
4802  NEONMAP1(vrecpes_f32, aarch64_neon_frecpe, Add1ArgType),
4803  NEONMAP1(vrecpxd_f64, aarch64_neon_frecpx, Add1ArgType),
4804  NEONMAP1(vrecpxs_f32, aarch64_neon_frecpx, Add1ArgType),
4805  NEONMAP1(vrshld_s64, aarch64_neon_srshl, Add1ArgType),
4806  NEONMAP1(vrshld_u64, aarch64_neon_urshl, Add1ArgType),
4807  NEONMAP1(vrsqrted_f64, aarch64_neon_frsqrte, Add1ArgType),
4808  NEONMAP1(vrsqrtes_f32, aarch64_neon_frsqrte, Add1ArgType),
4809  NEONMAP1(vrsqrtsd_f64, aarch64_neon_frsqrts, Add1ArgType),
4810  NEONMAP1(vrsqrtss_f32, aarch64_neon_frsqrts, Add1ArgType),
4811  NEONMAP1(vsha1cq_u32, aarch64_crypto_sha1c, 0),
4812  NEONMAP1(vsha1h_u32, aarch64_crypto_sha1h, 0),
4813  NEONMAP1(vsha1mq_u32, aarch64_crypto_sha1m, 0),
4814  NEONMAP1(vsha1pq_u32, aarch64_crypto_sha1p, 0),
4815  NEONMAP1(vshld_s64, aarch64_neon_sshl, Add1ArgType),
4816  NEONMAP1(vshld_u64, aarch64_neon_ushl, Add1ArgType),
4817  NEONMAP1(vslid_n_s64, aarch64_neon_vsli, Vectorize1ArgType),
4818  NEONMAP1(vslid_n_u64, aarch64_neon_vsli, Vectorize1ArgType),
4819  NEONMAP1(vsqaddb_u8, aarch64_neon_usqadd, Vectorize1ArgType | Use64BitVectors),
4820  NEONMAP1(vsqaddd_u64, aarch64_neon_usqadd, Add1ArgType),
4821  NEONMAP1(vsqaddh_u16, aarch64_neon_usqadd, Vectorize1ArgType | Use64BitVectors),
4822  NEONMAP1(vsqadds_u32, aarch64_neon_usqadd, Add1ArgType),
4823  NEONMAP1(vsrid_n_s64, aarch64_neon_vsri, Vectorize1ArgType),
4824  NEONMAP1(vsrid_n_u64, aarch64_neon_vsri, Vectorize1ArgType),
4825  NEONMAP1(vuqaddb_s8, aarch64_neon_suqadd, Vectorize1ArgType | Use64BitVectors),
4826  NEONMAP1(vuqaddd_s64, aarch64_neon_suqadd, Add1ArgType),
4827  NEONMAP1(vuqaddh_s16, aarch64_neon_suqadd, Vectorize1ArgType | Use64BitVectors),
4828  NEONMAP1(vuqadds_s32, aarch64_neon_suqadd, Add1ArgType),
4829  // FP16 scalar intrinisics go here.
4830  NEONMAP1(vabdh_f16, aarch64_sisd_fabd, Add1ArgType),
4831  NEONMAP1(vcvtah_s32_f16, aarch64_neon_fcvtas, AddRetType | Add1ArgType),
4832  NEONMAP1(vcvtah_s64_f16, aarch64_neon_fcvtas, AddRetType | Add1ArgType),
4833  NEONMAP1(vcvtah_u32_f16, aarch64_neon_fcvtau, AddRetType | Add1ArgType),
4834  NEONMAP1(vcvtah_u64_f16, aarch64_neon_fcvtau, AddRetType | Add1ArgType),
4835  NEONMAP1(vcvth_n_f16_s32, aarch64_neon_vcvtfxs2fp, AddRetType | Add1ArgType),
4836  NEONMAP1(vcvth_n_f16_s64, aarch64_neon_vcvtfxs2fp, AddRetType | Add1ArgType),
4837  NEONMAP1(vcvth_n_f16_u32, aarch64_neon_vcvtfxu2fp, AddRetType | Add1ArgType),
4838  NEONMAP1(vcvth_n_f16_u64, aarch64_neon_vcvtfxu2fp, AddRetType | Add1ArgType),
4839  NEONMAP1(vcvth_n_s32_f16, aarch64_neon_vcvtfp2fxs, AddRetType | Add1ArgType),
4840  NEONMAP1(vcvth_n_s64_f16, aarch64_neon_vcvtfp2fxs, AddRetType | Add1ArgType),
4841  NEONMAP1(vcvth_n_u32_f16, aarch64_neon_vcvtfp2fxu, AddRetType | Add1ArgType),
4842  NEONMAP1(vcvth_n_u64_f16, aarch64_neon_vcvtfp2fxu, AddRetType | Add1ArgType),
4843  NEONMAP1(vcvtmh_s32_f16, aarch64_neon_fcvtms, AddRetType | Add1ArgType),
4844  NEONMAP1(vcvtmh_s64_f16, aarch64_neon_fcvtms, AddRetType | Add1ArgType),
4845  NEONMAP1(vcvtmh_u32_f16, aarch64_neon_fcvtmu, AddRetType | Add1ArgType),
4846  NEONMAP1(vcvtmh_u64_f16, aarch64_neon_fcvtmu, AddRetType | Add1ArgType),
4847  NEONMAP1(vcvtnh_s32_f16, aarch64_neon_fcvtns, AddRetType | Add1ArgType),
4848  NEONMAP1(vcvtnh_s64_f16, aarch64_neon_fcvtns, AddRetType | Add1ArgType),
4849  NEONMAP1(vcvtnh_u32_f16, aarch64_neon_fcvtnu, AddRetType | Add1ArgType),
4850  NEONMAP1(vcvtnh_u64_f16, aarch64_neon_fcvtnu, AddRetType | Add1ArgType),
4851  NEONMAP1(vcvtph_s32_f16, aarch64_neon_fcvtps, AddRetType | Add1ArgType),
4852  NEONMAP1(vcvtph_s64_f16, aarch64_neon_fcvtps, AddRetType | Add1ArgType),
4853  NEONMAP1(vcvtph_u32_f16, aarch64_neon_fcvtpu, AddRetType | Add1ArgType),
4854  NEONMAP1(vcvtph_u64_f16, aarch64_neon_fcvtpu, AddRetType | Add1ArgType),
4855  NEONMAP1(vmulxh_f16, aarch64_neon_fmulx, Add1ArgType),
4856  NEONMAP1(vrecpeh_f16, aarch64_neon_frecpe, Add1ArgType),
4857  NEONMAP1(vrecpxh_f16, aarch64_neon_frecpx, Add1ArgType),
4858  NEONMAP1(vrsqrteh_f16, aarch64_neon_frsqrte, Add1ArgType),
4859  NEONMAP1(vrsqrtsh_f16, aarch64_neon_frsqrts, Add1ArgType),
4860 };
4861 
4862 #undef NEONMAP0
4863 #undef NEONMAP1
4864 #undef NEONMAP2
4865 
4867 
4870 
4871 
4872 static const NeonIntrinsicInfo *
4874  unsigned BuiltinID, bool &MapProvenSorted) {
4875 
4876 #ifndef NDEBUG
4877  if (!MapProvenSorted) {
4878  assert(std::is_sorted(std::begin(IntrinsicMap), std::end(IntrinsicMap)));
4879  MapProvenSorted = true;
4880  }
4881 #endif
4882 
4883  const NeonIntrinsicInfo *Builtin =
4884  std::lower_bound(IntrinsicMap.begin(), IntrinsicMap.end(), BuiltinID);
4885 
4886  if (Builtin != IntrinsicMap.end() && Builtin->BuiltinID == BuiltinID)
4887  return Builtin;
4888 
4889  return nullptr;
4890 }
4891 
4892 Function *CodeGenFunction::LookupNeonLLVMIntrinsic(unsigned IntrinsicID,
4893  unsigned Modifier,
4894  llvm::Type *ArgType,
4895  const CallExpr *E) {
4896  int VectorSize = 0;
4897  if (Modifier & Use64BitVectors)
4898  VectorSize = 64;
4899  else if (Modifier & Use128BitVectors)
4900  VectorSize = 128;
4901 
4902  // Return type.
4904  if (Modifier & AddRetType) {
4905  llvm::Type *Ty = ConvertType(E->getCallReturnType(getContext()));
4906  if (Modifier & VectorizeRetType)
4907  Ty = llvm::VectorType::get(
4908  Ty, VectorSize ? VectorSize / Ty->getPrimitiveSizeInBits() : 1);
4909 
4910  Tys.push_back(Ty);
4911  }
4912 
4913  // Arguments.
4914  if (Modifier & VectorizeArgTypes) {
4915  int Elts = VectorSize ? VectorSize / ArgType->getPrimitiveSizeInBits() : 1;
4916  ArgType = llvm::VectorType::get(ArgType, Elts);
4917  }
4918 
4919  if (Modifier & (Add1ArgType | Add2ArgTypes))
4920  Tys.push_back(ArgType);
4921 
4922  if (Modifier & Add2ArgTypes)
4923  Tys.push_back(ArgType);
4924 
4925  if (Modifier & InventFloatType)
4926  Tys.push_back(FloatTy);
4927 
4928  return CGM.getIntrinsic(IntrinsicID, Tys);
4929 }
4930 
4932  const NeonIntrinsicInfo &SISDInfo,
4934  const CallExpr *E) {
4935  unsigned BuiltinID = SISDInfo.BuiltinID;
4936  unsigned int Int = SISDInfo.LLVMIntrinsic;
4937  unsigned Modifier = SISDInfo.TypeModifier;
4938  const char *s = SISDInfo.NameHint;
4939 
4940  switch (BuiltinID) {
4941  case NEON::BI__builtin_neon_vcled_s64:
4942  case NEON::BI__builtin_neon_vcled_u64:
4943  case NEON::BI__builtin_neon_vcles_f32:
4944  case NEON::BI__builtin_neon_vcled_f64:
4945  case NEON::BI__builtin_neon_vcltd_s64:
4946  case NEON::BI__builtin_neon_vcltd_u64:
4947  case NEON::BI__builtin_neon_vclts_f32:
4948  case NEON::BI__builtin_neon_vcltd_f64:
4949  case NEON::BI__builtin_neon_vcales_f32:
4950  case NEON::BI__builtin_neon_vcaled_f64:
4951  case NEON::BI__builtin_neon_vcalts_f32:
4952  case NEON::BI__builtin_neon_vcaltd_f64:
4953  // Only one direction of comparisons actually exist, cmle is actually a cmge
4954  // with swapped operands. The table gives us the right intrinsic but we
4955  // still need to do the swap.
4956  std::swap(Ops[0], Ops[1]);
4957  break;
4958  }
4959 
4960  assert(Int && "Generic code assumes a valid intrinsic");
4961 
4962  // Determine the type(s) of this overloaded AArch64 intrinsic.
4963  const Expr *Arg = E->getArg(0);
4964  llvm::Type *ArgTy = CGF.ConvertType(Arg->getType());
4965  Function *F = CGF.LookupNeonLLVMIntrinsic(Int, Modifier, ArgTy, E);
4966 
4967  int j = 0;
4968  ConstantInt *C0 = ConstantInt::get(CGF.SizeTy, 0);
4969  for (Function::const_arg_iterator ai = F->arg_begin(), ae = F->arg_end();
4970  ai != ae; ++ai, ++j) {
4971  llvm::Type *ArgTy = ai->getType();
4972  if (Ops[j]->getType()->getPrimitiveSizeInBits() ==
4973  ArgTy->getPrimitiveSizeInBits())
4974  continue;
4975 
4976  assert(ArgTy->isVectorTy() && !Ops[j]->getType()->isVectorTy());
4977  // The constant argument to an _n_ intrinsic always has Int32Ty, so truncate
4978  // it before inserting.
4979  Ops[j] =
4980  CGF.Builder.CreateTruncOrBitCast(Ops[j], ArgTy->getVectorElementType());
4981  Ops[j] =
4982  CGF.Builder.CreateInsertElement(UndefValue::get(ArgTy), Ops[j], C0);
4983  }
4984 
4985  Value *Result = CGF.EmitNeonCall(F, Ops, s);
4986  llvm::Type *ResultType = CGF.ConvertType(E->getType());
4987  if (ResultType->getPrimitiveSizeInBits() <
4988  Result->getType()->getPrimitiveSizeInBits())
4989  return CGF.Builder.CreateExtractElement(Result, C0);
4990 
4991  return CGF.Builder.CreateBitCast(Result, ResultType, s);
4992 }
4993 
4995  unsigned BuiltinID, unsigned LLVMIntrinsic, unsigned AltLLVMIntrinsic,
4996  const char *NameHint, unsigned Modifier, const CallExpr *E,
4997  SmallVectorImpl<llvm::Value *> &Ops, Address PtrOp0, Address PtrOp1,
4998  llvm::Triple::ArchType Arch) {
4999  // Get the last argument, which specifies the vector type.
5000  llvm::APSInt NeonTypeConst;
5001  const Expr *Arg = E->getArg(E->getNumArgs() - 1);
5002  if (!Arg->isIntegerConstantExpr(NeonTypeConst, getContext()))
5003  return nullptr;
5004 
5005  // Determine the type of this overloaded NEON intrinsic.
5006  NeonTypeFlags Type(NeonTypeConst.getZExtValue());
5007  bool Usgn = Type.isUnsigned();
5008  bool Quad = Type.isQuad();
5009  const bool HasLegalHalfType = getTarget().hasLegalHalfType();
5010 
5011  llvm::VectorType *VTy = GetNeonType(this, Type, HasLegalHalfType);
5012  llvm::Type *Ty = VTy;
5013  if (!Ty)
5014  return nullptr;
5015 
5016  auto getAlignmentValue32 = [&](Address addr) -> Value* {
5017  return Builder.getInt32(addr.getAlignment().getQuantity());
5018  };
5019 
5020  unsigned Int = LLVMIntrinsic;
5021  if ((Modifier & UnsignedAlts) && !Usgn)
5022  Int = AltLLVMIntrinsic;
5023 
5024  switch (BuiltinID) {
5025  default: break;
5026  case NEON::BI__builtin_neon_vabs_v:
5027  case NEON::BI__builtin_neon_vabsq_v:
5028  if (VTy->getElementType()->isFloatingPointTy())
5029  return EmitNeonCall(CGM.getIntrinsic(Intrinsic::fabs, Ty), Ops, "vabs");
5030  return EmitNeonCall(CGM.getIntrinsic(LLVMIntrinsic, Ty), Ops, "vabs");
5031  case NEON::BI__builtin_neon_vaddhn_v: {
5032  llvm::VectorType *SrcTy =
5033  llvm::VectorType::getExtendedElementVectorType(VTy);
5034 
5035  // %sum = add <4 x i32> %lhs, %rhs
5036  Ops[0] = Builder.CreateBitCast(Ops[0], SrcTy);
5037  Ops[1] = Builder.CreateBitCast(Ops[1], SrcTy);
5038  Ops[0] = Builder.CreateAdd(Ops[0], Ops[1], "vaddhn");
5039 
5040  // %high = lshr <4 x i32> %sum, <i32 16, i32 16, i32 16, i32 16>
5041  Constant *ShiftAmt =
5042  ConstantInt::get(SrcTy, SrcTy->getScalarSizeInBits() / 2);
5043  Ops[0] = Builder.CreateLShr(Ops[0], ShiftAmt, "vaddhn");
5044 
5045  // %res = trunc <4 x i32> %high to <4 x i16>
5046  return Builder.CreateTrunc(Ops[0], VTy, "vaddhn");
5047  }
5048  case NEON::BI__builtin_neon_vcale_v:
5049  case NEON::BI__builtin_neon_vcaleq_v:
5050  case NEON::BI__builtin_neon_vcalt_v:
5051  case NEON::BI__builtin_neon_vcaltq_v:
5052  std::swap(Ops[0], Ops[1]);
5053  LLVM_FALLTHROUGH;
5054  case NEON::BI__builtin_neon_vcage_v:
5055  case NEON::BI__builtin_neon_vcageq_v:
5056  case NEON::BI__builtin_neon_vcagt_v:
5057  case NEON::BI__builtin_neon_vcagtq_v: {
5058  llvm::Type *Ty;
5059  switch (VTy->getScalarSizeInBits()) {
5060  default: llvm_unreachable("unexpected type");
5061  case 32:
5062  Ty = FloatTy;
5063  break;
5064  case 64:
5065  Ty = DoubleTy;
5066  break;
5067  case 16:
5068  Ty = HalfTy;
5069  break;
5070  }
5071  llvm::Type *VecFlt = llvm::VectorType::get(Ty, VTy->getNumElements());
5072  llvm::Type *Tys[] = { VTy, VecFlt };
5073  Function *F = CGM.getIntrinsic(LLVMIntrinsic, Tys);
5074  return EmitNeonCall(F, Ops, NameHint);
5075  }
5076  case NEON::BI__builtin_neon_vceqz_v:
5077  case NEON::BI__builtin_neon_vceqzq_v:
5078  return EmitAArch64CompareBuiltinExpr(Ops[0], Ty, ICmpInst::FCMP_OEQ,
5079  ICmpInst::ICMP_EQ, "vceqz");
5080  case NEON::BI__builtin_neon_vcgez_v:
5081  case NEON::BI__builtin_neon_vcgezq_v:
5082  return EmitAArch64CompareBuiltinExpr(Ops[0], Ty, ICmpInst::FCMP_OGE,
5083  ICmpInst::ICMP_SGE, "vcgez");
5084  case NEON::BI__builtin_neon_vclez_v:
5085  case NEON::BI__builtin_neon_vclezq_v:
5086  return EmitAArch64CompareBuiltinExpr(Ops[0], Ty, ICmpInst::FCMP_OLE,
5087  ICmpInst::ICMP_SLE, "vclez");
5088  case NEON::BI__builtin_neon_vcgtz_v:
5089  case NEON::BI__builtin_neon_vcgtzq_v:
5090  return EmitAArch64CompareBuiltinExpr(Ops[0], Ty, ICmpInst::FCMP_OGT,
5091  ICmpInst::ICMP_SGT, "vcgtz");
5092  case NEON::BI__builtin_neon_vcltz_v:
5093  case NEON::BI__builtin_neon_vcltzq_v:
5094  return EmitAArch64CompareBuiltinExpr(Ops[0], Ty, ICmpInst::FCMP_OLT,
5095  ICmpInst::ICMP_SLT, "vcltz");
5096  case NEON::BI__builtin_neon_vclz_v:
5097  case NEON::BI__builtin_neon_vclzq_v:
5098  // We generate target-independent intrinsic, which needs a second argument
5099  // for whether or not clz of zero is undefined; on ARM it isn't.
5100  Ops.push_back(Builder.getInt1(getTarget().isCLZForZeroUndef()));
5101  break;
5102  case NEON::BI__builtin_neon_vcvt_f32_v:
5103  case NEON::BI__builtin_neon_vcvtq_f32_v:
5104  Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
5105  Ty = GetNeonType(this, NeonTypeFlags(NeonTypeFlags::Float32, false, Quad),
5106  HasLegalHalfType);
5107  return Usgn ? Builder.CreateUIToFP(Ops[0], Ty, "vcvt")
5108  : Builder.CreateSIToFP(Ops[0], Ty, "vcvt");
5109  case NEON::BI__builtin_neon_vcvt_f16_v:
5110  case NEON::BI__builtin_neon_vcvtq_f16_v:
5111  Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
5112  Ty = GetNeonType(this, NeonTypeFlags(NeonTypeFlags::Float16, false, Quad),
5113  HasLegalHalfType);
5114  return Usgn ? Builder.CreateUIToFP(Ops[0], Ty, "vcvt")
5115  : Builder.CreateSIToFP(Ops[0], Ty, "vcvt");
5116  case NEON::BI__builtin_neon_vcvt_n_f16_v:
5117  case NEON::BI__builtin_neon_vcvt_n_f32_v:
5118  case NEON::BI__builtin_neon_vcvt_n_f64_v:
5119  case NEON::BI__builtin_neon_vcvtq_n_f16_v:
5120  case NEON::BI__builtin_neon_vcvtq_n_f32_v:
5121  case NEON::BI__builtin_neon_vcvtq_n_f64_v: {
5122  llvm::Type *Tys[2] = { GetFloatNeonType(this, Type), Ty };
5123  Int = Usgn ? LLVMIntrinsic : AltLLVMIntrinsic;
5124  Function *F = CGM.getIntrinsic(Int, Tys);
5125  return EmitNeonCall(F, Ops, "vcvt_n");
5126  }
5127  case NEON::BI__builtin_neon_vcvt_n_s16_v:
5128  case NEON::BI__builtin_neon_vcvt_n_s32_v:
5129  cas