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