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