clang  16.0.0git
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 "ABIInfo.h"
14 #include "CGCUDARuntime.h"
15 #include "CGCXXABI.h"
16 #include "CGObjCRuntime.h"
17 #include "CGOpenCLRuntime.h"
18 #include "CGRecordLayout.h"
19 #include "CodeGenFunction.h"
20 #include "CodeGenModule.h"
21 #include "ConstantEmitter.h"
22 #include "PatternInit.h"
23 #include "TargetInfo.h"
24 #include "clang/AST/ASTContext.h"
25 #include "clang/AST/Attr.h"
26 #include "clang/AST/Decl.h"
27 #include "clang/AST/OSLog.h"
29 #include "clang/Basic/TargetInfo.h"
31 #include "llvm/ADT/APFloat.h"
32 #include "llvm/ADT/APInt.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/Analysis/ValueTracking.h"
36 #include "llvm/IR/DataLayout.h"
37 #include "llvm/IR/InlineAsm.h"
38 #include "llvm/IR/Intrinsics.h"
39 #include "llvm/IR/IntrinsicsAArch64.h"
40 #include "llvm/IR/IntrinsicsAMDGPU.h"
41 #include "llvm/IR/IntrinsicsARM.h"
42 #include "llvm/IR/IntrinsicsBPF.h"
43 #include "llvm/IR/IntrinsicsHexagon.h"
44 #include "llvm/IR/IntrinsicsLoongArch.h"
45 #include "llvm/IR/IntrinsicsNVPTX.h"
46 #include "llvm/IR/IntrinsicsPowerPC.h"
47 #include "llvm/IR/IntrinsicsR600.h"
48 #include "llvm/IR/IntrinsicsRISCV.h"
49 #include "llvm/IR/IntrinsicsS390.h"
50 #include "llvm/IR/IntrinsicsVE.h"
51 #include "llvm/IR/IntrinsicsWebAssembly.h"
52 #include "llvm/IR/IntrinsicsX86.h"
53 #include "llvm/IR/MDBuilder.h"
54 #include "llvm/IR/MatrixBuilder.h"
55 #include "llvm/Support/ConvertUTF.h"
56 #include "llvm/Support/ScopedPrinter.h"
57 #include "llvm/Support/X86TargetParser.h"
58 #include <sstream>
59 
60 using namespace clang;
61 using namespace CodeGen;
62 using namespace llvm;
63 
64 static void initializeAlloca(CodeGenFunction &CGF, AllocaInst *AI, Value *Size,
65  Align AlignmentInBytes) {
66  ConstantInt *Byte;
67  switch (CGF.getLangOpts().getTrivialAutoVarInit()) {
69  // Nothing to initialize.
70  return;
72  Byte = CGF.Builder.getInt8(0x00);
73  break;
75  llvm::Type *Int8 = llvm::IntegerType::getInt8Ty(CGF.CGM.getLLVMContext());
76  Byte = llvm::dyn_cast<llvm::ConstantInt>(
77  initializationPatternFor(CGF.CGM, Int8));
78  break;
79  }
80  }
81  if (CGF.CGM.stopAutoInit())
82  return;
83  auto *I = CGF.Builder.CreateMemSet(AI, Byte, Size, AlignmentInBytes);
84  I->addAnnotationMetadata("auto-init");
85 }
86 
87 /// getBuiltinLibFunction - Given a builtin id for a function like
88 /// "__builtin_fabsf", return a Function* for "fabsf".
90  unsigned BuiltinID) {
91  assert(Context.BuiltinInfo.isLibFunction(BuiltinID));
92 
93  // Get the name, skip over the __builtin_ prefix (if necessary).
94  StringRef Name;
95  GlobalDecl D(FD);
96 
97  // TODO: This list should be expanded or refactored after all GCC-compatible
98  // std libcall builtins are implemented.
99  static SmallDenseMap<unsigned, StringRef, 8> F128Builtins{
100  {Builtin::BI__builtin_printf, "__printfieee128"},
101  {Builtin::BI__builtin_vsnprintf, "__vsnprintfieee128"},
102  {Builtin::BI__builtin_vsprintf, "__vsprintfieee128"},
103  {Builtin::BI__builtin_sprintf, "__sprintfieee128"},
104  {Builtin::BI__builtin_snprintf, "__snprintfieee128"},
105  {Builtin::BI__builtin_fprintf, "__fprintfieee128"},
106  {Builtin::BI__builtin_nexttowardf128, "__nexttowardieee128"},
107  };
108 
109  // The AIX library functions frexpl, ldexpl, and modfl are for 128-bit
110  // IBM 'long double' (i.e. __ibm128). Map to the 'double' versions
111  // if it is 64-bit 'long double' mode.
112  static SmallDenseMap<unsigned, StringRef, 4> AIXLongDouble64Builtins{
113  {Builtin::BI__builtin_frexpl, "frexp"},
114  {Builtin::BI__builtin_ldexpl, "ldexp"},
115  {Builtin::BI__builtin_modfl, "modf"},
116  };
117 
118  // If the builtin has been declared explicitly with an assembler label,
119  // use the mangled name. This differs from the plain label on platforms
120  // that prefix labels.
121  if (FD->hasAttr<AsmLabelAttr>())
122  Name = getMangledName(D);
123  else {
124  // TODO: This mutation should also be applied to other targets other than
125  // PPC, after backend supports IEEE 128-bit style libcalls.
126  if (getTriple().isPPC64() &&
127  &getTarget().getLongDoubleFormat() == &llvm::APFloat::IEEEquad() &&
128  F128Builtins.find(BuiltinID) != F128Builtins.end())
129  Name = F128Builtins[BuiltinID];
130  else if (getTriple().isOSAIX() &&
131  &getTarget().getLongDoubleFormat() ==
132  &llvm::APFloat::IEEEdouble() &&
133  AIXLongDouble64Builtins.find(BuiltinID) !=
134  AIXLongDouble64Builtins.end())
135  Name = AIXLongDouble64Builtins[BuiltinID];
136  else
137  Name = Context.BuiltinInfo.getName(BuiltinID) + 10;
138  }
139 
140  llvm::FunctionType *Ty =
141  cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
142 
143  return GetOrCreateLLVMFunction(Name, Ty, D, /*ForVTable=*/false);
144 }
145 
146 /// Emit the conversions required to turn the given value into an
147 /// integer of the given size.
148 static Value *EmitToInt(CodeGenFunction &CGF, llvm::Value *V,
149  QualType T, llvm::IntegerType *IntType) {
150  V = CGF.EmitToMemory(V, T);
151 
152  if (V->getType()->isPointerTy())
153  return CGF.Builder.CreatePtrToInt(V, IntType);
154 
155  assert(V->getType() == IntType);
156  return V;
157 }
158 
159 static Value *EmitFromInt(CodeGenFunction &CGF, llvm::Value *V,
160  QualType T, llvm::Type *ResultType) {
161  V = CGF.EmitFromMemory(V, T);
162 
163  if (ResultType->isPointerTy())
164  return CGF.Builder.CreateIntToPtr(V, ResultType);
165 
166  assert(V->getType() == ResultType);
167  return V;
168 }
169 
170 /// Utility to insert an atomic instruction based on Intrinsic::ID
171 /// and the expression node.
173  CodeGenFunction &CGF, llvm::AtomicRMWInst::BinOp Kind, const CallExpr *E,
174  AtomicOrdering Ordering = AtomicOrdering::SequentiallyConsistent) {
175 
176  QualType T = E->getType();
177  assert(E->getArg(0)->getType()->isPointerType());
178  assert(CGF.getContext().hasSameUnqualifiedType(T,
179  E->getArg(0)->getType()->getPointeeType()));
180  assert(CGF.getContext().hasSameUnqualifiedType(T, E->getArg(1)->getType()));
181 
182  llvm::Value *DestPtr = CGF.EmitScalarExpr(E->getArg(0));
183  unsigned AddrSpace = DestPtr->getType()->getPointerAddressSpace();
184 
185  llvm::IntegerType *IntType =
186  llvm::IntegerType::get(CGF.getLLVMContext(),
187  CGF.getContext().getTypeSize(T));
188  llvm::Type *IntPtrType = IntType->getPointerTo(AddrSpace);
189 
190  llvm::Value *Args[2];
191  Args[0] = CGF.Builder.CreateBitCast(DestPtr, IntPtrType);
192  Args[1] = CGF.EmitScalarExpr(E->getArg(1));
193  llvm::Type *ValueType = Args[1]->getType();
194  Args[1] = EmitToInt(CGF, Args[1], T, IntType);
195 
196  llvm::Value *Result = CGF.Builder.CreateAtomicRMW(
197  Kind, Args[0], Args[1], Ordering);
198  return EmitFromInt(CGF, Result, T, ValueType);
199 }
200 
202  Value *Val = CGF.EmitScalarExpr(E->getArg(0));
203  Value *Address = CGF.EmitScalarExpr(E->getArg(1));
204 
205  // Convert the type of the pointer to a pointer to the stored type.
206  Val = CGF.EmitToMemory(Val, E->getArg(0)->getType());
207  unsigned SrcAddrSpace = Address->getType()->getPointerAddressSpace();
208  Value *BC = CGF.Builder.CreateBitCast(
209  Address, llvm::PointerType::get(Val->getType(), SrcAddrSpace), "cast");
210  LValue LV = CGF.MakeNaturalAlignAddrLValue(BC, E->getArg(0)->getType());
211  LV.setNontemporal(true);
212  CGF.EmitStoreOfScalar(Val, LV, false);
213  return nullptr;
214 }
215 
217  Value *Address = CGF.EmitScalarExpr(E->getArg(0));
218 
220  LV.setNontemporal(true);
221  return CGF.EmitLoadOfScalar(LV, E->getExprLoc());
222 }
223 
225  llvm::AtomicRMWInst::BinOp Kind,
226  const CallExpr *E) {
227  return RValue::get(MakeBinaryAtomicValue(CGF, Kind, E));
228 }
229 
230 /// Utility to insert an atomic instruction based Intrinsic::ID and
231 /// the expression node, where the return value is the result of the
232 /// operation.
234  llvm::AtomicRMWInst::BinOp Kind,
235  const CallExpr *E,
236  Instruction::BinaryOps Op,
237  bool Invert = false) {
238  QualType T = E->getType();
239  assert(E->getArg(0)->getType()->isPointerType());
240  assert(CGF.getContext().hasSameUnqualifiedType(T,
241  E->getArg(0)->getType()->getPointeeType()));
242  assert(CGF.getContext().hasSameUnqualifiedType(T, E->getArg(1)->getType()));
243 
244  llvm::Value *DestPtr = CGF.EmitScalarExpr(E->getArg(0));
245  unsigned AddrSpace = DestPtr->getType()->getPointerAddressSpace();
246 
247  llvm::IntegerType *IntType =
248  llvm::IntegerType::get(CGF.getLLVMContext(),
249  CGF.getContext().getTypeSize(T));
250  llvm::Type *IntPtrType = IntType->getPointerTo(AddrSpace);
251 
252  llvm::Value *Args[2];
253  Args[1] = CGF.EmitScalarExpr(E->getArg(1));
254  llvm::Type *ValueType = Args[1]->getType();
255  Args[1] = EmitToInt(CGF, Args[1], T, IntType);
256  Args[0] = CGF.Builder.CreateBitCast(DestPtr, IntPtrType);
257 
258  llvm::Value *Result = CGF.Builder.CreateAtomicRMW(
259  Kind, Args[0], Args[1], llvm::AtomicOrdering::SequentiallyConsistent);
260  Result = CGF.Builder.CreateBinOp(Op, Result, Args[1]);
261  if (Invert)
262  Result =
263  CGF.Builder.CreateBinOp(llvm::Instruction::Xor, Result,
264  llvm::ConstantInt::getAllOnesValue(IntType));
265  Result = EmitFromInt(CGF, Result, T, ValueType);
266  return RValue::get(Result);
267 }
268 
269 /// Utility to insert an atomic cmpxchg instruction.
270 ///
271 /// @param CGF The current codegen function.
272 /// @param E Builtin call expression to convert to cmpxchg.
273 /// arg0 - address to operate on
274 /// arg1 - value to compare with
275 /// arg2 - new value
276 /// @param ReturnBool Specifies whether to return success flag of
277 /// cmpxchg result or the old value.
278 ///
279 /// @returns result of cmpxchg, according to ReturnBool
280 ///
281 /// Note: In order to lower Microsoft's _InterlockedCompareExchange* intrinsics
282 /// invoke the function EmitAtomicCmpXchgForMSIntrin.
284  bool ReturnBool) {
285  QualType T = ReturnBool ? E->getArg(1)->getType() : E->getType();
286  llvm::Value *DestPtr = CGF.EmitScalarExpr(E->getArg(0));
287  unsigned AddrSpace = DestPtr->getType()->getPointerAddressSpace();
288 
289  llvm::IntegerType *IntType = llvm::IntegerType::get(
290  CGF.getLLVMContext(), CGF.getContext().getTypeSize(T));
291  llvm::Type *IntPtrType = IntType->getPointerTo(AddrSpace);
292 
293  Value *Args[3];
294  Args[0] = CGF.Builder.CreateBitCast(DestPtr, IntPtrType);
295  Args[1] = CGF.EmitScalarExpr(E->getArg(1));
296  llvm::Type *ValueType = Args[1]->getType();
297  Args[1] = EmitToInt(CGF, Args[1], T, IntType);
298  Args[2] = EmitToInt(CGF, CGF.EmitScalarExpr(E->getArg(2)), T, IntType);
299 
300  Value *Pair = CGF.Builder.CreateAtomicCmpXchg(
301  Args[0], Args[1], Args[2], llvm::AtomicOrdering::SequentiallyConsistent,
302  llvm::AtomicOrdering::SequentiallyConsistent);
303  if (ReturnBool)
304  // Extract boolean success flag and zext it to int.
305  return CGF.Builder.CreateZExt(CGF.Builder.CreateExtractValue(Pair, 1),
306  CGF.ConvertType(E->getType()));
307  else
308  // Extract old value and emit it using the same type as compare value.
309  return EmitFromInt(CGF, CGF.Builder.CreateExtractValue(Pair, 0), T,
310  ValueType);
311 }
312 
313 /// This function should be invoked to emit atomic cmpxchg for Microsoft's
314 /// _InterlockedCompareExchange* intrinsics which have the following signature:
315 /// T _InterlockedCompareExchange(T volatile *Destination,
316 /// T Exchange,
317 /// T Comparand);
318 ///
319 /// Whereas the llvm 'cmpxchg' instruction has the following syntax:
320 /// cmpxchg *Destination, Comparand, Exchange.
321 /// So we need to swap Comparand and Exchange when invoking
322 /// CreateAtomicCmpXchg. That is the reason we could not use the above utility
323 /// function MakeAtomicCmpXchgValue since it expects the arguments to be
324 /// already swapped.
325 
326 static
328  AtomicOrdering SuccessOrdering = AtomicOrdering::SequentiallyConsistent) {
329  assert(E->getArg(0)->getType()->isPointerType());
330  assert(CGF.getContext().hasSameUnqualifiedType(
331  E->getType(), E->getArg(0)->getType()->getPointeeType()));
332  assert(CGF.getContext().hasSameUnqualifiedType(E->getType(),
333  E->getArg(1)->getType()));
334  assert(CGF.getContext().hasSameUnqualifiedType(E->getType(),
335  E->getArg(2)->getType()));
336 
337  auto *Destination = CGF.EmitScalarExpr(E->getArg(0));
338  auto *Comparand = CGF.EmitScalarExpr(E->getArg(2));
339  auto *Exchange = CGF.EmitScalarExpr(E->getArg(1));
340 
341  // For Release ordering, the failure ordering should be Monotonic.
342  auto FailureOrdering = SuccessOrdering == AtomicOrdering::Release ?
343  AtomicOrdering::Monotonic :
344  SuccessOrdering;
345 
346  // The atomic instruction is marked volatile for consistency with MSVC. This
347  // blocks the few atomics optimizations that LLVM has. If we want to optimize
348  // _Interlocked* operations in the future, we will have to remove the volatile
349  // marker.
350  auto *Result = CGF.Builder.CreateAtomicCmpXchg(
351  Destination, Comparand, Exchange,
352  SuccessOrdering, FailureOrdering);
353  Result->setVolatile(true);
354  return CGF.Builder.CreateExtractValue(Result, 0);
355 }
356 
357 // 64-bit Microsoft platforms support 128 bit cmpxchg operations. They are
358 // prototyped like this:
359 //
360 // unsigned char _InterlockedCompareExchange128...(
361 // __int64 volatile * _Destination,
362 // __int64 _ExchangeHigh,
363 // __int64 _ExchangeLow,
364 // __int64 * _ComparandResult);
366  const CallExpr *E,
367  AtomicOrdering SuccessOrdering) {
368  assert(E->getNumArgs() == 4);
369  llvm::Value *Destination = CGF.EmitScalarExpr(E->getArg(0));
370  llvm::Value *ExchangeHigh = CGF.EmitScalarExpr(E->getArg(1));
371  llvm::Value *ExchangeLow = CGF.EmitScalarExpr(E->getArg(2));
372  llvm::Value *ComparandPtr = CGF.EmitScalarExpr(E->getArg(3));
373 
374  assert(Destination->getType()->isPointerTy());
375  assert(!ExchangeHigh->getType()->isPointerTy());
376  assert(!ExchangeLow->getType()->isPointerTy());
377  assert(ComparandPtr->getType()->isPointerTy());
378 
379  // For Release ordering, the failure ordering should be Monotonic.
380  auto FailureOrdering = SuccessOrdering == AtomicOrdering::Release
381  ? AtomicOrdering::Monotonic
382  : SuccessOrdering;
383 
384  // Convert to i128 pointers and values.
385  llvm::Type *Int128Ty = llvm::IntegerType::get(CGF.getLLVMContext(), 128);
386  llvm::Type *Int128PtrTy = Int128Ty->getPointerTo();
387  Destination = CGF.Builder.CreateBitCast(Destination, Int128PtrTy);
388  Address ComparandResult(CGF.Builder.CreateBitCast(ComparandPtr, Int128PtrTy),
389  Int128Ty, CGF.getContext().toCharUnitsFromBits(128));
390 
391  // (((i128)hi) << 64) | ((i128)lo)
392  ExchangeHigh = CGF.Builder.CreateZExt(ExchangeHigh, Int128Ty);
393  ExchangeLow = CGF.Builder.CreateZExt(ExchangeLow, Int128Ty);
394  ExchangeHigh =
395  CGF.Builder.CreateShl(ExchangeHigh, llvm::ConstantInt::get(Int128Ty, 64));
396  llvm::Value *Exchange = CGF.Builder.CreateOr(ExchangeHigh, ExchangeLow);
397 
398  // Load the comparand for the instruction.
399  llvm::Value *Comparand = CGF.Builder.CreateLoad(ComparandResult);
400 
401  auto *CXI = CGF.Builder.CreateAtomicCmpXchg(Destination, Comparand, Exchange,
402  SuccessOrdering, FailureOrdering);
403 
404  // The atomic instruction is marked volatile for consistency with MSVC. This
405  // blocks the few atomics optimizations that LLVM has. If we want to optimize
406  // _Interlocked* operations in the future, we will have to remove the volatile
407  // marker.
408  CXI->setVolatile(true);
409 
410  // Store the result as an outparameter.
411  CGF.Builder.CreateStore(CGF.Builder.CreateExtractValue(CXI, 0),
412  ComparandResult);
413 
414  // Get the success boolean and zero extend it to i8.
415  Value *Success = CGF.Builder.CreateExtractValue(CXI, 1);
416  return CGF.Builder.CreateZExt(Success, CGF.Int8Ty);
417 }
418 
420  AtomicOrdering Ordering = AtomicOrdering::SequentiallyConsistent) {
421  assert(E->getArg(0)->getType()->isPointerType());
422 
423  auto *IntTy = CGF.ConvertType(E->getType());
424  auto *Result = CGF.Builder.CreateAtomicRMW(
426  CGF.EmitScalarExpr(E->getArg(0)),
427  ConstantInt::get(IntTy, 1),
428  Ordering);
429  return CGF.Builder.CreateAdd(Result, ConstantInt::get(IntTy, 1));
430 }
431 
433  AtomicOrdering Ordering = AtomicOrdering::SequentiallyConsistent) {
434  assert(E->getArg(0)->getType()->isPointerType());
435 
436  auto *IntTy = CGF.ConvertType(E->getType());
437  auto *Result = CGF.Builder.CreateAtomicRMW(
439  CGF.EmitScalarExpr(E->getArg(0)),
440  ConstantInt::get(IntTy, 1),
441  Ordering);
442  return CGF.Builder.CreateSub(Result, ConstantInt::get(IntTy, 1));
443 }
444 
445 // Build a plain volatile load.
447  Value *Ptr = CGF.EmitScalarExpr(E->getArg(0));
448  QualType ElTy = E->getArg(0)->getType()->getPointeeType();
449  CharUnits LoadSize = CGF.getContext().getTypeSizeInChars(ElTy);
450  llvm::Type *ITy =
451  llvm::IntegerType::get(CGF.getLLVMContext(), LoadSize.getQuantity() * 8);
452  Ptr = CGF.Builder.CreateBitCast(Ptr, ITy->getPointerTo());
453  llvm::LoadInst *Load = CGF.Builder.CreateAlignedLoad(ITy, Ptr, LoadSize);
454  Load->setVolatile(true);
455  return Load;
456 }
457 
458 // Build a plain volatile store.
460  Value *Ptr = CGF.EmitScalarExpr(E->getArg(0));
461  Value *Value = CGF.EmitScalarExpr(E->getArg(1));
462  QualType ElTy = E->getArg(0)->getType()->getPointeeType();
463  CharUnits StoreSize = CGF.getContext().getTypeSizeInChars(ElTy);
464  llvm::Type *ITy =
465  llvm::IntegerType::get(CGF.getLLVMContext(), StoreSize.getQuantity() * 8);
466  Ptr = CGF.Builder.CreateBitCast(Ptr, ITy->getPointerTo());
467  llvm::StoreInst *Store =
468  CGF.Builder.CreateAlignedStore(Value, Ptr, StoreSize);
469  Store->setVolatile(true);
470  return Store;
471 }
472 
473 // Emit a simple mangled intrinsic that has 1 argument and a return type
474 // matching the argument type. Depending on mode, this may be a constrained
475 // floating-point intrinsic.
477  const CallExpr *E, unsigned IntrinsicID,
478  unsigned ConstrainedIntrinsicID) {
479  llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
480 
481  if (CGF.Builder.getIsFPConstrained()) {
482  CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
483  Function *F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID, Src0->getType());
484  return CGF.Builder.CreateConstrainedFPCall(F, { Src0 });
485  } else {
486  Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
487  return CGF.Builder.CreateCall(F, Src0);
488  }
489 }
490 
491 // Emit an intrinsic that has 2 operands of the same type as its result.
492 // Depending on mode, this may be a constrained floating-point intrinsic.
494  const CallExpr *E, unsigned IntrinsicID,
495  unsigned ConstrainedIntrinsicID) {
496  llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
497  llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1));
498 
499  if (CGF.Builder.getIsFPConstrained()) {
500  CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
501  Function *F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID, Src0->getType());
502  return CGF.Builder.CreateConstrainedFPCall(F, { Src0, Src1 });
503  } else {
504  Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
505  return CGF.Builder.CreateCall(F, { Src0, Src1 });
506  }
507 }
508 
509 // Emit an intrinsic that has 3 operands of the same type as its result.
510 // Depending on mode, this may be a constrained floating-point intrinsic.
512  const CallExpr *E, unsigned IntrinsicID,
513  unsigned ConstrainedIntrinsicID) {
514  llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
515  llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1));
516  llvm::Value *Src2 = CGF.EmitScalarExpr(E->getArg(2));
517 
518  if (CGF.Builder.getIsFPConstrained()) {
519  CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
520  Function *F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID, Src0->getType());
521  return CGF.Builder.CreateConstrainedFPCall(F, { Src0, Src1, Src2 });
522  } else {
523  Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
524  return CGF.Builder.CreateCall(F, { Src0, Src1, Src2 });
525  }
526 }
527 
528 // Emit an intrinsic where all operands are of the same type as the result.
529 // Depending on mode, this may be a constrained floating-point intrinsic.
531  unsigned IntrinsicID,
532  unsigned ConstrainedIntrinsicID,
533  llvm::Type *Ty,
534  ArrayRef<Value *> Args) {
535  Function *F;
536  if (CGF.Builder.getIsFPConstrained())
537  F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID, Ty);
538  else
539  F = CGF.CGM.getIntrinsic(IntrinsicID, Ty);
540 
541  if (CGF.Builder.getIsFPConstrained())
542  return CGF.Builder.CreateConstrainedFPCall(F, Args);
543  else
544  return CGF.Builder.CreateCall(F, Args);
545 }
546 
547 // Emit a simple mangled intrinsic that has 1 argument and a return type
548 // matching the argument type.
550  unsigned IntrinsicID,
551  llvm::StringRef Name = "") {
552  llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
553 
554  Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
555  return CGF.Builder.CreateCall(F, Src0, Name);
556 }
557 
558 // Emit an intrinsic that has 2 operands of the same type as its result.
560  const CallExpr *E,
561  unsigned IntrinsicID) {
562  llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
563  llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1));
564 
565  Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
566  return CGF.Builder.CreateCall(F, { Src0, Src1 });
567 }
568 
569 // Emit an intrinsic that has 3 operands of the same type as its result.
571  const CallExpr *E,
572  unsigned IntrinsicID) {
573  llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
574  llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1));
575  llvm::Value *Src2 = CGF.EmitScalarExpr(E->getArg(2));
576 
577  Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
578  return CGF.Builder.CreateCall(F, { Src0, Src1, Src2 });
579 }
580 
581 // Emit an intrinsic that has 1 float or double operand, and 1 integer.
583  const CallExpr *E,
584  unsigned IntrinsicID) {
585  llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
586  llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1));
587 
588  Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
589  return CGF.Builder.CreateCall(F, {Src0, Src1});
590 }
591 
592 // Emit an intrinsic that has overloaded integer result and fp operand.
593 static Value *
595  unsigned IntrinsicID,
596  unsigned ConstrainedIntrinsicID) {
597  llvm::Type *ResultType = CGF.ConvertType(E->getType());
598  llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
599 
600  if (CGF.Builder.getIsFPConstrained()) {
601  CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
602  Function *F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID,
603  {ResultType, Src0->getType()});
604  return CGF.Builder.CreateConstrainedFPCall(F, {Src0});
605  } else {
606  Function *F =
607  CGF.CGM.getIntrinsic(IntrinsicID, {ResultType, Src0->getType()});
608  return CGF.Builder.CreateCall(F, Src0);
609  }
610 }
611 
612 /// EmitFAbs - Emit a call to @llvm.fabs().
614  Function *F = CGF.CGM.getIntrinsic(Intrinsic::fabs, V->getType());
615  llvm::CallInst *Call = CGF.Builder.CreateCall(F, V);
616  Call->setDoesNotAccessMemory();
617  return Call;
618 }
619 
620 /// Emit the computation of the sign bit for a floating point value. Returns
621 /// the i1 sign bit value.
623  LLVMContext &C = CGF.CGM.getLLVMContext();
624 
625  llvm::Type *Ty = V->getType();
626  int Width = Ty->getPrimitiveSizeInBits();
627  llvm::Type *IntTy = llvm::IntegerType::get(C, Width);
628  V = CGF.Builder.CreateBitCast(V, IntTy);
629  if (Ty->isPPC_FP128Ty()) {
630  // We want the sign bit of the higher-order double. The bitcast we just
631  // did works as if the double-double was stored to memory and then
632  // read as an i128. The "store" will put the higher-order double in the
633  // lower address in both little- and big-Endian modes, but the "load"
634  // will treat those bits as a different part of the i128: the low bits in
635  // little-Endian, the high bits in big-Endian. Therefore, on big-Endian
636  // we need to shift the high bits down to the low before truncating.
637  Width >>= 1;
638  if (CGF.getTarget().isBigEndian()) {
639  Value *ShiftCst = llvm::ConstantInt::get(IntTy, Width);
640  V = CGF.Builder.CreateLShr(V, ShiftCst);
641  }
642  // We are truncating value in order to extract the higher-order
643  // double, which we will be using to extract the sign from.
644  IntTy = llvm::IntegerType::get(C, Width);
645  V = CGF.Builder.CreateTrunc(V, IntTy);
646  }
647  Value *Zero = llvm::Constant::getNullValue(IntTy);
648  return CGF.Builder.CreateICmpSLT(V, Zero);
649 }
650 
652  const CallExpr *E, llvm::Constant *calleeValue) {
653  CGCallee callee = CGCallee::forDirect(calleeValue, GlobalDecl(FD));
654  return CGF.EmitCall(E->getCallee()->getType(), callee, E, ReturnValueSlot());
655 }
656 
657 /// Emit a call to llvm.{sadd,uadd,ssub,usub,smul,umul}.with.overflow.*
658 /// depending on IntrinsicID.
659 ///
660 /// \arg CGF The current codegen function.
661 /// \arg IntrinsicID The ID for the Intrinsic we wish to generate.
662 /// \arg X The first argument to the llvm.*.with.overflow.*.
663 /// \arg Y The second argument to the llvm.*.with.overflow.*.
664 /// \arg Carry The carry returned by the llvm.*.with.overflow.*.
665 /// \returns The result (i.e. sum/product) returned by the intrinsic.
666 static llvm::Value *EmitOverflowIntrinsic(CodeGenFunction &CGF,
667  const llvm::Intrinsic::ID IntrinsicID,
668  llvm::Value *X, llvm::Value *Y,
669  llvm::Value *&Carry) {
670  // Make sure we have integers of the same width.
671  assert(X->getType() == Y->getType() &&
672  "Arguments must be the same type. (Did you forget to make sure both "
673  "arguments have the same integer width?)");
674 
675  Function *Callee = CGF.CGM.getIntrinsic(IntrinsicID, X->getType());
676  llvm::Value *Tmp = CGF.Builder.CreateCall(Callee, {X, Y});
677  Carry = CGF.Builder.CreateExtractValue(Tmp, 1);
678  return CGF.Builder.CreateExtractValue(Tmp, 0);
679 }
680 
682  unsigned IntrinsicID,
683  int low, int high) {
684  llvm::MDBuilder MDHelper(CGF.getLLVMContext());
685  llvm::MDNode *RNode = MDHelper.createRange(APInt(32, low), APInt(32, high));
686  Function *F = CGF.CGM.getIntrinsic(IntrinsicID, {});
687  llvm::Instruction *Call = CGF.Builder.CreateCall(F);
688  Call->setMetadata(llvm::LLVMContext::MD_range, RNode);
689  return Call;
690 }
691 
692 namespace {
693  struct WidthAndSignedness {
694  unsigned Width;
695  bool Signed;
696  };
697 }
698 
699 static WidthAndSignedness
701  const clang::QualType Type) {
702  assert(Type->isIntegerType() && "Given type is not an integer.");
703  unsigned Width = Type->isBooleanType() ? 1
704  : Type->isBitIntType() ? context.getIntWidth(Type)
705  : context.getTypeInfo(Type).Width;
706  bool Signed = Type->isSignedIntegerType();
707  return {Width, Signed};
708 }
709 
710 // Given one or more integer types, this function produces an integer type that
711 // encompasses them: any value in one of the given types could be expressed in
712 // the encompassing type.
713 static struct WidthAndSignedness
714 EncompassingIntegerType(ArrayRef<struct WidthAndSignedness> Types) {
715  assert(Types.size() > 0 && "Empty list of types.");
716 
717  // If any of the given types is signed, we must return a signed type.
718  bool Signed = false;
719  for (const auto &Type : Types) {
720  Signed |= Type.Signed;
721  }
722 
723  // The encompassing type must have a width greater than or equal to the width
724  // of the specified types. Additionally, if the encompassing type is signed,
725  // its width must be strictly greater than the width of any unsigned types
726  // given.
727  unsigned Width = 0;
728  for (const auto &Type : Types) {
729  unsigned MinWidth = Type.Width + (Signed && !Type.Signed);
730  if (Width < MinWidth) {
731  Width = MinWidth;
732  }
733  }
734 
735  return {Width, Signed};
736 }
737 
738 Value *CodeGenFunction::EmitVAStartEnd(Value *ArgValue, bool IsStart) {
739  llvm::Type *DestType = Int8PtrTy;
740  if (ArgValue->getType() != DestType)
741  ArgValue =
742  Builder.CreateBitCast(ArgValue, DestType, ArgValue->getName().data());
743 
744  Intrinsic::ID inst = IsStart ? Intrinsic::vastart : Intrinsic::vaend;
745  return Builder.CreateCall(CGM.getIntrinsic(inst), ArgValue);
746 }
747 
748 /// Checks if using the result of __builtin_object_size(p, @p From) in place of
749 /// __builtin_object_size(p, @p To) is correct
750 static bool areBOSTypesCompatible(int From, int To) {
751  // Note: Our __builtin_object_size implementation currently treats Type=0 and
752  // Type=2 identically. Encoding this implementation detail here may make
753  // improving __builtin_object_size difficult in the future, so it's omitted.
754  return From == To || (From == 0 && To == 1) || (From == 3 && To == 2);
755 }
756 
757 static llvm::Value *
758 getDefaultBuiltinObjectSizeResult(unsigned Type, llvm::IntegerType *ResType) {
759  return ConstantInt::get(ResType, (Type & 2) ? 0 : -1, /*isSigned=*/true);
760 }
761 
762 llvm::Value *
763 CodeGenFunction::evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type,
764  llvm::IntegerType *ResType,
765  llvm::Value *EmittedE,
766  bool IsDynamic) {
767  uint64_t ObjectSize;
768  if (!E->tryEvaluateObjectSize(ObjectSize, getContext(), Type))
769  return emitBuiltinObjectSize(E, Type, ResType, EmittedE, IsDynamic);
770  return ConstantInt::get(ResType, ObjectSize, /*isSigned=*/true);
771 }
772 
773 /// Returns a Value corresponding to the size of the given expression.
774 /// This Value may be either of the following:
775 /// - A llvm::Argument (if E is a param with the pass_object_size attribute on
776 /// it)
777 /// - A call to the @llvm.objectsize intrinsic
778 ///
779 /// EmittedE is the result of emitting `E` as a scalar expr. If it's non-null
780 /// and we wouldn't otherwise try to reference a pass_object_size parameter,
781 /// we'll call @llvm.objectsize on EmittedE, rather than emitting E.
782 llvm::Value *
783 CodeGenFunction::emitBuiltinObjectSize(const Expr *E, unsigned Type,
784  llvm::IntegerType *ResType,
785  llvm::Value *EmittedE, bool IsDynamic) {
786  // We need to reference an argument if the pointer is a parameter with the
787  // pass_object_size attribute.
788  if (auto *D = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) {
789  auto *Param = dyn_cast<ParmVarDecl>(D->getDecl());
790  auto *PS = D->getDecl()->getAttr<PassObjectSizeAttr>();
791  if (Param != nullptr && PS != nullptr &&
792  areBOSTypesCompatible(PS->getType(), Type)) {
793  auto Iter = SizeArguments.find(Param);
794  assert(Iter != SizeArguments.end());
795 
796  const ImplicitParamDecl *D = Iter->second;
797  auto DIter = LocalDeclMap.find(D);
798  assert(DIter != LocalDeclMap.end());
799 
800  return EmitLoadOfScalar(DIter->second, /*Volatile=*/false,
801  getContext().getSizeType(), E->getBeginLoc());
802  }
803  }
804 
805  // LLVM can't handle Type=3 appropriately, and __builtin_object_size shouldn't
806  // evaluate E for side-effects. In either case, we shouldn't lower to
807  // @llvm.objectsize.
808  if (Type == 3 || (!EmittedE && E->HasSideEffects(getContext())))
809  return getDefaultBuiltinObjectSizeResult(Type, ResType);
810 
811  Value *Ptr = EmittedE ? EmittedE : EmitScalarExpr(E);
812  assert(Ptr->getType()->isPointerTy() &&
813  "Non-pointer passed to __builtin_object_size?");
814 
815  Function *F =
816  CGM.getIntrinsic(Intrinsic::objectsize, {ResType, Ptr->getType()});
817 
818  // LLVM only supports 0 and 2, make sure that we pass along that as a boolean.
819  Value *Min = Builder.getInt1((Type & 2) != 0);
820  // For GCC compatibility, __builtin_object_size treat NULL as unknown size.
821  Value *NullIsUnknown = Builder.getTrue();
822  Value *Dynamic = Builder.getInt1(IsDynamic);
823  return Builder.CreateCall(F, {Ptr, Min, NullIsUnknown, Dynamic});
824 }
825 
826 namespace {
827 /// A struct to generically describe a bit test intrinsic.
828 struct BitTest {
829  enum ActionKind : uint8_t { TestOnly, Complement, Reset, Set };
830  enum InterlockingKind : uint8_t {
831  Unlocked,
832  Sequential,
833  Acquire,
834  Release,
835  NoFence
836  };
837 
838  ActionKind Action;
839  InterlockingKind Interlocking;
840  bool Is64Bit;
841 
842  static BitTest decodeBitTestBuiltin(unsigned BuiltinID);
843 };
844 } // namespace
845 
846 BitTest BitTest::decodeBitTestBuiltin(unsigned BuiltinID) {
847  switch (BuiltinID) {
848  // Main portable variants.
849  case Builtin::BI_bittest:
850  return {TestOnly, Unlocked, false};
851  case Builtin::BI_bittestandcomplement:
852  return {Complement, Unlocked, false};
853  case Builtin::BI_bittestandreset:
854  return {Reset, Unlocked, false};
855  case Builtin::BI_bittestandset:
856  return {Set, Unlocked, false};
857  case Builtin::BI_interlockedbittestandreset:
858  return {Reset, Sequential, false};
859  case Builtin::BI_interlockedbittestandset:
860  return {Set, Sequential, false};
861 
862  // X86-specific 64-bit variants.
863  case Builtin::BI_bittest64:
864  return {TestOnly, Unlocked, true};
865  case Builtin::BI_bittestandcomplement64:
866  return {Complement, Unlocked, true};
867  case Builtin::BI_bittestandreset64:
868  return {Reset, Unlocked, true};
869  case Builtin::BI_bittestandset64:
870  return {Set, Unlocked, true};
871  case Builtin::BI_interlockedbittestandreset64:
872  return {Reset, Sequential, true};
873  case Builtin::BI_interlockedbittestandset64:
874  return {Set, Sequential, true};
875 
876  // ARM/AArch64-specific ordering variants.
877  case Builtin::BI_interlockedbittestandset_acq:
878  return {Set, Acquire, false};
879  case Builtin::BI_interlockedbittestandset_rel:
880  return {Set, Release, false};
881  case Builtin::BI_interlockedbittestandset_nf:
882  return {Set, NoFence, false};
883  case Builtin::BI_interlockedbittestandreset_acq:
884  return {Reset, Acquire, false};
885  case Builtin::BI_interlockedbittestandreset_rel:
886  return {Reset, Release, false};
887  case Builtin::BI_interlockedbittestandreset_nf:
888  return {Reset, NoFence, false};
889  }
890  llvm_unreachable("expected only bittest intrinsics");
891 }
892 
893 static char bitActionToX86BTCode(BitTest::ActionKind A) {
894  switch (A) {
895  case BitTest::TestOnly: return '\0';
896  case BitTest::Complement: return 'c';
897  case BitTest::Reset: return 'r';
898  case BitTest::Set: return 's';
899  }
900  llvm_unreachable("invalid action");
901 }
902 
903 static llvm::Value *EmitX86BitTestIntrinsic(CodeGenFunction &CGF,
904  BitTest BT,
905  const CallExpr *E, Value *BitBase,
906  Value *BitPos) {
907  char Action = bitActionToX86BTCode(BT.Action);
908  char SizeSuffix = BT.Is64Bit ? 'q' : 'l';
909 
910  // Build the assembly.
912  raw_svector_ostream AsmOS(Asm);
913  if (BT.Interlocking != BitTest::Unlocked)
914  AsmOS << "lock ";
915  AsmOS << "bt";
916  if (Action)
917  AsmOS << Action;
918  AsmOS << SizeSuffix << " $2, ($1)";
919 
920  // Build the constraints. FIXME: We should support immediates when possible.
921  std::string Constraints = "={@ccc},r,r,~{cc},~{memory}";
922  std::string MachineClobbers = CGF.getTarget().getClobbers();
923  if (!MachineClobbers.empty()) {
924  Constraints += ',';
925  Constraints += MachineClobbers;
926  }
927  llvm::IntegerType *IntType = llvm::IntegerType::get(
928  CGF.getLLVMContext(),
929  CGF.getContext().getTypeSize(E->getArg(1)->getType()));
930  llvm::Type *IntPtrType = IntType->getPointerTo();
931  llvm::FunctionType *FTy =
932  llvm::FunctionType::get(CGF.Int8Ty, {IntPtrType, IntType}, false);
933 
934  llvm::InlineAsm *IA =
935  llvm::InlineAsm::get(FTy, Asm, Constraints, /*hasSideEffects=*/true);
936  return CGF.Builder.CreateCall(IA, {BitBase, BitPos});
937 }
938 
939 static llvm::AtomicOrdering
940 getBitTestAtomicOrdering(BitTest::InterlockingKind I) {
941  switch (I) {
942  case BitTest::Unlocked: return llvm::AtomicOrdering::NotAtomic;
943  case BitTest::Sequential: return llvm::AtomicOrdering::SequentiallyConsistent;
944  case BitTest::Acquire: return llvm::AtomicOrdering::Acquire;
945  case BitTest::Release: return llvm::AtomicOrdering::Release;
946  case BitTest::NoFence: return llvm::AtomicOrdering::Monotonic;
947  }
948  llvm_unreachable("invalid interlocking");
949 }
950 
951 /// Emit a _bittest* intrinsic. These intrinsics take a pointer to an array of
952 /// bits and a bit position and read and optionally modify the bit at that
953 /// position. The position index can be arbitrarily large, i.e. it can be larger
954 /// than 31 or 63, so we need an indexed load in the general case.
955 static llvm::Value *EmitBitTestIntrinsic(CodeGenFunction &CGF,
956  unsigned BuiltinID,
957  const CallExpr *E) {
958  Value *BitBase = CGF.EmitScalarExpr(E->getArg(0));
959  Value *BitPos = CGF.EmitScalarExpr(E->getArg(1));
960 
961  BitTest BT = BitTest::decodeBitTestBuiltin(BuiltinID);
962 
963  // X86 has special BT, BTC, BTR, and BTS instructions that handle the array
964  // indexing operation internally. Use them if possible.
965  if (CGF.getTarget().getTriple().isX86())
966  return EmitX86BitTestIntrinsic(CGF, BT, E, BitBase, BitPos);
967 
968  // Otherwise, use generic code to load one byte and test the bit. Use all but
969  // the bottom three bits as the array index, and the bottom three bits to form
970  // a mask.
971  // Bit = BitBaseI8[BitPos >> 3] & (1 << (BitPos & 0x7)) != 0;
972  Value *ByteIndex = CGF.Builder.CreateAShr(
973  BitPos, llvm::ConstantInt::get(BitPos->getType(), 3), "bittest.byteidx");
974  Value *BitBaseI8 = CGF.Builder.CreatePointerCast(BitBase, CGF.Int8PtrTy);
975  Address ByteAddr(CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, BitBaseI8,
976  ByteIndex, "bittest.byteaddr"),
977  CGF.Int8Ty, CharUnits::One());
978  Value *PosLow =
979  CGF.Builder.CreateAnd(CGF.Builder.CreateTrunc(BitPos, CGF.Int8Ty),
980  llvm::ConstantInt::get(CGF.Int8Ty, 0x7));
981 
982  // The updating instructions will need a mask.
983  Value *Mask = nullptr;
984  if (BT.Action != BitTest::TestOnly) {
985  Mask = CGF.Builder.CreateShl(llvm::ConstantInt::get(CGF.Int8Ty, 1), PosLow,
986  "bittest.mask");
987  }
988 
989  // Check the action and ordering of the interlocked intrinsics.
990  llvm::AtomicOrdering Ordering = getBitTestAtomicOrdering(BT.Interlocking);
991 
992  Value *OldByte = nullptr;
993  if (Ordering != llvm::AtomicOrdering::NotAtomic) {
994  // Emit a combined atomicrmw load/store operation for the interlocked
995  // intrinsics.
996  llvm::AtomicRMWInst::BinOp RMWOp = llvm::AtomicRMWInst::Or;
997  if (BT.Action == BitTest::Reset) {
998  Mask = CGF.Builder.CreateNot(Mask);
999  RMWOp = llvm::AtomicRMWInst::And;
1000  }
1001  OldByte = CGF.Builder.CreateAtomicRMW(RMWOp, ByteAddr.getPointer(), Mask,
1002  Ordering);
1003  } else {
1004  // Emit a plain load for the non-interlocked intrinsics.
1005  OldByte = CGF.Builder.CreateLoad(ByteAddr, "bittest.byte");
1006  Value *NewByte = nullptr;
1007  switch (BT.Action) {
1008  case BitTest::TestOnly:
1009  // Don't store anything.
1010  break;
1011  case BitTest::Complement:
1012  NewByte = CGF.Builder.CreateXor(OldByte, Mask);
1013  break;
1014  case BitTest::Reset:
1015  NewByte = CGF.Builder.CreateAnd(OldByte, CGF.Builder.CreateNot(Mask));
1016  break;
1017  case BitTest::Set:
1018  NewByte = CGF.Builder.CreateOr(OldByte, Mask);
1019  break;
1020  }
1021  if (NewByte)
1022  CGF.Builder.CreateStore(NewByte, ByteAddr);
1023  }
1024 
1025  // However we loaded the old byte, either by plain load or atomicrmw, shift
1026  // the bit into the low position and mask it to 0 or 1.
1027  Value *ShiftedByte = CGF.Builder.CreateLShr(OldByte, PosLow, "bittest.shr");
1028  return CGF.Builder.CreateAnd(
1029  ShiftedByte, llvm::ConstantInt::get(CGF.Int8Ty, 1), "bittest.res");
1030 }
1031 
1033  unsigned BuiltinID,
1034  const CallExpr *E) {
1035  Value *Addr = CGF.EmitScalarExpr(E->getArg(0));
1036 
1038  raw_svector_ostream AsmOS(Asm);
1039  llvm::IntegerType *RetType = CGF.Int32Ty;
1040 
1041  switch (BuiltinID) {
1042  case clang::PPC::BI__builtin_ppc_ldarx:
1043  AsmOS << "ldarx ";
1044  RetType = CGF.Int64Ty;
1045  break;
1046  case clang::PPC::BI__builtin_ppc_lwarx:
1047  AsmOS << "lwarx ";
1048  RetType = CGF.Int32Ty;
1049  break;
1050  case clang::PPC::BI__builtin_ppc_lharx:
1051  AsmOS << "lharx ";
1052  RetType = CGF.Int16Ty;
1053  break;
1054  case clang::PPC::BI__builtin_ppc_lbarx:
1055  AsmOS << "lbarx ";
1056  RetType = CGF.Int8Ty;
1057  break;
1058  default:
1059  llvm_unreachable("Expected only PowerPC load reserve intrinsics");
1060  }
1061 
1062  AsmOS << "$0, ${1:y}";
1063 
1064  std::string Constraints = "=r,*Z,~{memory}";
1065  std::string MachineClobbers = CGF.getTarget().getClobbers();
1066  if (!MachineClobbers.empty()) {
1067  Constraints += ',';
1068  Constraints += MachineClobbers;
1069  }
1070 
1071  llvm::Type *IntPtrType = RetType->getPointerTo();
1072  llvm::FunctionType *FTy =
1073  llvm::FunctionType::get(RetType, {IntPtrType}, false);
1074 
1075  llvm::InlineAsm *IA =
1076  llvm::InlineAsm::get(FTy, Asm, Constraints, /*hasSideEffects=*/true);
1077  llvm::CallInst *CI = CGF.Builder.CreateCall(IA, {Addr});
1078  CI->addParamAttr(
1079  0, Attribute::get(CGF.getLLVMContext(), Attribute::ElementType, RetType));
1080  return CI;
1081 }
1082 
1083 namespace {
1084 enum class MSVCSetJmpKind {
1085  _setjmpex,
1086  _setjmp3,
1087  _setjmp
1088 };
1089 }
1090 
1091 /// MSVC handles setjmp a bit differently on different platforms. On every
1092 /// architecture except 32-bit x86, the frame address is passed. On x86, extra
1093 /// parameters can be passed as variadic arguments, but we always pass none.
1094 static RValue EmitMSVCRTSetJmp(CodeGenFunction &CGF, MSVCSetJmpKind SJKind,
1095  const CallExpr *E) {
1096  llvm::Value *Arg1 = nullptr;
1097  llvm::Type *Arg1Ty = nullptr;
1098  StringRef Name;
1099  bool IsVarArg = false;
1100  if (SJKind == MSVCSetJmpKind::_setjmp3) {
1101  Name = "_setjmp3";
1102  Arg1Ty = CGF.Int32Ty;
1103  Arg1 = llvm::ConstantInt::get(CGF.IntTy, 0);
1104  IsVarArg = true;
1105  } else {
1106  Name = SJKind == MSVCSetJmpKind::_setjmp ? "_setjmp" : "_setjmpex";
1107  Arg1Ty = CGF.Int8PtrTy;
1108  if (CGF.getTarget().getTriple().getArch() == llvm::Triple::aarch64) {
1109  Arg1 = CGF.Builder.CreateCall(
1110  CGF.CGM.getIntrinsic(Intrinsic::sponentry, CGF.AllocaInt8PtrTy));
1111  } else
1112  Arg1 = CGF.Builder.CreateCall(
1113  CGF.CGM.getIntrinsic(Intrinsic::frameaddress, CGF.AllocaInt8PtrTy),
1114  llvm::ConstantInt::get(CGF.Int32Ty, 0));
1115  }
1116 
1117  // Mark the call site and declaration with ReturnsTwice.
1118  llvm::Type *ArgTypes[2] = {CGF.Int8PtrTy, Arg1Ty};
1119  llvm::AttributeList ReturnsTwiceAttr = llvm::AttributeList::get(
1120  CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex,
1121  llvm::Attribute::ReturnsTwice);
1122  llvm::FunctionCallee SetJmpFn = CGF.CGM.CreateRuntimeFunction(
1123  llvm::FunctionType::get(CGF.IntTy, ArgTypes, IsVarArg), Name,
1124  ReturnsTwiceAttr, /*Local=*/true);
1125 
1126  llvm::Value *Buf = CGF.Builder.CreateBitOrPointerCast(
1127  CGF.EmitScalarExpr(E->getArg(0)), CGF.Int8PtrTy);
1128  llvm::Value *Args[] = {Buf, Arg1};
1129  llvm::CallBase *CB = CGF.EmitRuntimeCallOrInvoke(SetJmpFn, Args);
1130  CB->setAttributes(ReturnsTwiceAttr);
1131  return RValue::get(CB);
1132 }
1133 
1134 // Many of MSVC builtins are on x64, ARM and AArch64; to avoid repeating code,
1135 // we handle them here.
1137  _BitScanForward,
1138  _BitScanReverse,
1139  _InterlockedAnd,
1140  _InterlockedDecrement,
1141  _InterlockedExchange,
1142  _InterlockedExchangeAdd,
1143  _InterlockedExchangeSub,
1144  _InterlockedIncrement,
1145  _InterlockedOr,
1146  _InterlockedXor,
1147  _InterlockedExchangeAdd_acq,
1148  _InterlockedExchangeAdd_rel,
1149  _InterlockedExchangeAdd_nf,
1150  _InterlockedExchange_acq,
1151  _InterlockedExchange_rel,
1152  _InterlockedExchange_nf,
1153  _InterlockedCompareExchange_acq,
1154  _InterlockedCompareExchange_rel,
1155  _InterlockedCompareExchange_nf,
1156  _InterlockedCompareExchange128,
1157  _InterlockedCompareExchange128_acq,
1158  _InterlockedCompareExchange128_rel,
1159  _InterlockedCompareExchange128_nf,
1160  _InterlockedOr_acq,
1161  _InterlockedOr_rel,
1162  _InterlockedOr_nf,
1163  _InterlockedXor_acq,
1164  _InterlockedXor_rel,
1165  _InterlockedXor_nf,
1166  _InterlockedAnd_acq,
1167  _InterlockedAnd_rel,
1168  _InterlockedAnd_nf,
1169  _InterlockedIncrement_acq,
1170  _InterlockedIncrement_rel,
1171  _InterlockedIncrement_nf,
1172  _InterlockedDecrement_acq,
1173  _InterlockedDecrement_rel,
1174  _InterlockedDecrement_nf,
1175  __fastfail,
1176 };
1177 
1179 translateArmToMsvcIntrin(unsigned BuiltinID) {
1181  switch (BuiltinID) {
1182  default:
1183  return std::nullopt;
1184  case clang::ARM::BI_BitScanForward:
1185  case clang::ARM::BI_BitScanForward64:
1186  return MSVCIntrin::_BitScanForward;
1187  case clang::ARM::BI_BitScanReverse:
1188  case clang::ARM::BI_BitScanReverse64:
1189  return MSVCIntrin::_BitScanReverse;
1190  case clang::ARM::BI_InterlockedAnd64:
1191  return MSVCIntrin::_InterlockedAnd;
1192  case clang::ARM::BI_InterlockedExchange64:
1193  return MSVCIntrin::_InterlockedExchange;
1194  case clang::ARM::BI_InterlockedExchangeAdd64:
1195  return MSVCIntrin::_InterlockedExchangeAdd;
1196  case clang::ARM::BI_InterlockedExchangeSub64:
1197  return MSVCIntrin::_InterlockedExchangeSub;
1198  case clang::ARM::BI_InterlockedOr64:
1199  return MSVCIntrin::_InterlockedOr;
1200  case clang::ARM::BI_InterlockedXor64:
1201  return MSVCIntrin::_InterlockedXor;
1202  case clang::ARM::BI_InterlockedDecrement64:
1203  return MSVCIntrin::_InterlockedDecrement;
1204  case clang::ARM::BI_InterlockedIncrement64:
1205  return MSVCIntrin::_InterlockedIncrement;
1206  case clang::ARM::BI_InterlockedExchangeAdd8_acq:
1207  case clang::ARM::BI_InterlockedExchangeAdd16_acq:
1208  case clang::ARM::BI_InterlockedExchangeAdd_acq:
1209  case clang::ARM::BI_InterlockedExchangeAdd64_acq:
1210  return MSVCIntrin::_InterlockedExchangeAdd_acq;
1211  case clang::ARM::BI_InterlockedExchangeAdd8_rel:
1212  case clang::ARM::BI_InterlockedExchangeAdd16_rel:
1213  case clang::ARM::BI_InterlockedExchangeAdd_rel:
1214  case clang::ARM::BI_InterlockedExchangeAdd64_rel:
1215  return MSVCIntrin::_InterlockedExchangeAdd_rel;
1216  case clang::ARM::BI_InterlockedExchangeAdd8_nf:
1217  case clang::ARM::BI_InterlockedExchangeAdd16_nf:
1218  case clang::ARM::BI_InterlockedExchangeAdd_nf:
1219  case clang::ARM::BI_InterlockedExchangeAdd64_nf:
1220  return MSVCIntrin::_InterlockedExchangeAdd_nf;
1221  case clang::ARM::BI_InterlockedExchange8_acq:
1222  case clang::ARM::BI_InterlockedExchange16_acq:
1223  case clang::ARM::BI_InterlockedExchange_acq:
1224  case clang::ARM::BI_InterlockedExchange64_acq:
1225  return MSVCIntrin::_InterlockedExchange_acq;
1226  case clang::ARM::BI_InterlockedExchange8_rel:
1227  case clang::ARM::BI_InterlockedExchange16_rel:
1228  case clang::ARM::BI_InterlockedExchange_rel:
1229  case clang::ARM::BI_InterlockedExchange64_rel:
1230  return MSVCIntrin::_InterlockedExchange_rel;
1231  case clang::ARM::BI_InterlockedExchange8_nf:
1232  case clang::ARM::BI_InterlockedExchange16_nf:
1233  case clang::ARM::BI_InterlockedExchange_nf:
1234  case clang::ARM::BI_InterlockedExchange64_nf:
1235  return MSVCIntrin::_InterlockedExchange_nf;
1236  case clang::ARM::BI_InterlockedCompareExchange8_acq:
1237  case clang::ARM::BI_InterlockedCompareExchange16_acq:
1238  case clang::ARM::BI_InterlockedCompareExchange_acq:
1239  case clang::ARM::BI_InterlockedCompareExchange64_acq:
1240  return MSVCIntrin::_InterlockedCompareExchange_acq;
1241  case clang::ARM::BI_InterlockedCompareExchange8_rel:
1242  case clang::ARM::BI_InterlockedCompareExchange16_rel:
1243  case clang::ARM::BI_InterlockedCompareExchange_rel:
1244  case clang::ARM::BI_InterlockedCompareExchange64_rel:
1245  return MSVCIntrin::_InterlockedCompareExchange_rel;
1246  case clang::ARM::BI_InterlockedCompareExchange8_nf:
1247  case clang::ARM::BI_InterlockedCompareExchange16_nf:
1248  case clang::ARM::BI_InterlockedCompareExchange_nf:
1249  case clang::ARM::BI_InterlockedCompareExchange64_nf:
1250  return MSVCIntrin::_InterlockedCompareExchange_nf;
1251  case clang::ARM::BI_InterlockedOr8_acq:
1252  case clang::ARM::BI_InterlockedOr16_acq:
1253  case clang::ARM::BI_InterlockedOr_acq:
1254  case clang::ARM::BI_InterlockedOr64_acq:
1255  return MSVCIntrin::_InterlockedOr_acq;
1256  case clang::ARM::BI_InterlockedOr8_rel:
1257  case clang::ARM::BI_InterlockedOr16_rel:
1258  case clang::ARM::BI_InterlockedOr_rel:
1259  case clang::ARM::BI_InterlockedOr64_rel:
1260  return MSVCIntrin::_InterlockedOr_rel;
1261  case clang::ARM::BI_InterlockedOr8_nf:
1262  case clang::ARM::BI_InterlockedOr16_nf:
1263  case clang::ARM::BI_InterlockedOr_nf:
1264  case clang::ARM::BI_InterlockedOr64_nf:
1265  return MSVCIntrin::_InterlockedOr_nf;
1266  case clang::ARM::BI_InterlockedXor8_acq:
1267  case clang::ARM::BI_InterlockedXor16_acq:
1268  case clang::ARM::BI_InterlockedXor_acq:
1269  case clang::ARM::BI_InterlockedXor64_acq:
1270  return MSVCIntrin::_InterlockedXor_acq;
1271  case clang::ARM::BI_InterlockedXor8_rel:
1272  case clang::ARM::BI_InterlockedXor16_rel:
1273  case clang::ARM::BI_InterlockedXor_rel:
1274  case clang::ARM::BI_InterlockedXor64_rel:
1275  return MSVCIntrin::_InterlockedXor_rel;
1276  case clang::ARM::BI_InterlockedXor8_nf:
1277  case clang::ARM::BI_InterlockedXor16_nf:
1278  case clang::ARM::BI_InterlockedXor_nf:
1279  case clang::ARM::BI_InterlockedXor64_nf:
1280  return MSVCIntrin::_InterlockedXor_nf;
1281  case clang::ARM::BI_InterlockedAnd8_acq:
1282  case clang::ARM::BI_InterlockedAnd16_acq:
1283  case clang::ARM::BI_InterlockedAnd_acq:
1284  case clang::ARM::BI_InterlockedAnd64_acq:
1285  return MSVCIntrin::_InterlockedAnd_acq;
1286  case clang::ARM::BI_InterlockedAnd8_rel:
1287  case clang::ARM::BI_InterlockedAnd16_rel:
1288  case clang::ARM::BI_InterlockedAnd_rel:
1289  case clang::ARM::BI_InterlockedAnd64_rel:
1290  return MSVCIntrin::_InterlockedAnd_rel;
1291  case clang::ARM::BI_InterlockedAnd8_nf:
1292  case clang::ARM::BI_InterlockedAnd16_nf:
1293  case clang::ARM::BI_InterlockedAnd_nf:
1294  case clang::ARM::BI_InterlockedAnd64_nf:
1295  return MSVCIntrin::_InterlockedAnd_nf;
1296  case clang::ARM::BI_InterlockedIncrement16_acq:
1297  case clang::ARM::BI_InterlockedIncrement_acq:
1298  case clang::ARM::BI_InterlockedIncrement64_acq:
1299  return MSVCIntrin::_InterlockedIncrement_acq;
1300  case clang::ARM::BI_InterlockedIncrement16_rel:
1301  case clang::ARM::BI_InterlockedIncrement_rel:
1302  case clang::ARM::BI_InterlockedIncrement64_rel:
1303  return MSVCIntrin::_InterlockedIncrement_rel;
1304  case clang::ARM::BI_InterlockedIncrement16_nf:
1305  case clang::ARM::BI_InterlockedIncrement_nf:
1306  case clang::ARM::BI_InterlockedIncrement64_nf:
1307  return MSVCIntrin::_InterlockedIncrement_nf;
1308  case clang::ARM::BI_InterlockedDecrement16_acq:
1309  case clang::ARM::BI_InterlockedDecrement_acq:
1310  case clang::ARM::BI_InterlockedDecrement64_acq:
1311  return MSVCIntrin::_InterlockedDecrement_acq;
1312  case clang::ARM::BI_InterlockedDecrement16_rel:
1313  case clang::ARM::BI_InterlockedDecrement_rel:
1314  case clang::ARM::BI_InterlockedDecrement64_rel:
1315  return MSVCIntrin::_InterlockedDecrement_rel;
1316  case clang::ARM::BI_InterlockedDecrement16_nf:
1317  case clang::ARM::BI_InterlockedDecrement_nf:
1318  case clang::ARM::BI_InterlockedDecrement64_nf:
1319  return MSVCIntrin::_InterlockedDecrement_nf;
1320  }
1321  llvm_unreachable("must return from switch");
1322 }
1323 
1325 translateAarch64ToMsvcIntrin(unsigned BuiltinID) {
1327  switch (BuiltinID) {
1328  default:
1329  return std::nullopt;
1330  case clang::AArch64::BI_BitScanForward:
1331  case clang::AArch64::BI_BitScanForward64:
1332  return MSVCIntrin::_BitScanForward;
1333  case clang::AArch64::BI_BitScanReverse:
1334  case clang::AArch64::BI_BitScanReverse64:
1335  return MSVCIntrin::_BitScanReverse;
1336  case clang::AArch64::BI_InterlockedAnd64:
1337  return MSVCIntrin::_InterlockedAnd;
1338  case clang::AArch64::BI_InterlockedExchange64:
1339  return MSVCIntrin::_InterlockedExchange;
1340  case clang::AArch64::BI_InterlockedExchangeAdd64:
1341  return MSVCIntrin::_InterlockedExchangeAdd;
1342  case clang::AArch64::BI_InterlockedExchangeSub64:
1343  return MSVCIntrin::_InterlockedExchangeSub;
1344  case clang::AArch64::BI_InterlockedOr64:
1345  return MSVCIntrin::_InterlockedOr;
1346  case clang::AArch64::BI_InterlockedXor64:
1347  return MSVCIntrin::_InterlockedXor;
1348  case clang::AArch64::BI_InterlockedDecrement64:
1349  return MSVCIntrin::_InterlockedDecrement;
1350  case clang::AArch64::BI_InterlockedIncrement64:
1351  return MSVCIntrin::_InterlockedIncrement;
1352  case clang::AArch64::BI_InterlockedExchangeAdd8_acq:
1353  case clang::AArch64::BI_InterlockedExchangeAdd16_acq:
1354  case clang::AArch64::BI_InterlockedExchangeAdd_acq:
1355  case clang::AArch64::BI_InterlockedExchangeAdd64_acq:
1356  return MSVCIntrin::_InterlockedExchangeAdd_acq;
1357  case clang::AArch64::BI_InterlockedExchangeAdd8_rel:
1358  case clang::AArch64::BI_InterlockedExchangeAdd16_rel:
1359  case clang::AArch64::BI_InterlockedExchangeAdd_rel:
1360  case clang::AArch64::BI_InterlockedExchangeAdd64_rel:
1361  return MSVCIntrin::_InterlockedExchangeAdd_rel;
1362  case clang::AArch64::BI_InterlockedExchangeAdd8_nf:
1363  case clang::AArch64::BI_InterlockedExchangeAdd16_nf:
1364  case clang::AArch64::BI_InterlockedExchangeAdd_nf:
1365  case clang::AArch64::BI_InterlockedExchangeAdd64_nf:
1366  return MSVCIntrin::_InterlockedExchangeAdd_nf;
1367  case clang::AArch64::BI_InterlockedExchange8_acq:
1368  case clang::AArch64::BI_InterlockedExchange16_acq:
1369  case clang::AArch64::BI_InterlockedExchange_acq:
1370  case clang::AArch64::BI_InterlockedExchange64_acq:
1371  return MSVCIntrin::_InterlockedExchange_acq;
1372  case clang::AArch64::BI_InterlockedExchange8_rel:
1373  case clang::AArch64::BI_InterlockedExchange16_rel:
1374  case clang::AArch64::BI_InterlockedExchange_rel:
1375  case clang::AArch64::BI_InterlockedExchange64_rel:
1376  return MSVCIntrin::_InterlockedExchange_rel;
1377  case clang::AArch64::BI_InterlockedExchange8_nf:
1378  case clang::AArch64::BI_InterlockedExchange16_nf:
1379  case clang::AArch64::BI_InterlockedExchange_nf:
1380  case clang::AArch64::BI_InterlockedExchange64_nf:
1381  return MSVCIntrin::_InterlockedExchange_nf;
1382  case clang::AArch64::BI_InterlockedCompareExchange8_acq:
1383  case clang::AArch64::BI_InterlockedCompareExchange16_acq:
1384  case clang::AArch64::BI_InterlockedCompareExchange_acq:
1385  case clang::AArch64::BI_InterlockedCompareExchange64_acq:
1386  return MSVCIntrin::_InterlockedCompareExchange_acq;
1387  case clang::AArch64::BI_InterlockedCompareExchange8_rel:
1388  case clang::AArch64::BI_InterlockedCompareExchange16_rel:
1389  case clang::AArch64::BI_InterlockedCompareExchange_rel:
1390  case clang::AArch64::BI_InterlockedCompareExchange64_rel:
1391  return MSVCIntrin::_InterlockedCompareExchange_rel;
1392  case clang::AArch64::BI_InterlockedCompareExchange8_nf:
1393  case clang::AArch64::BI_InterlockedCompareExchange16_nf:
1394  case clang::AArch64::BI_InterlockedCompareExchange_nf:
1395  case clang::AArch64::BI_InterlockedCompareExchange64_nf:
1396  return MSVCIntrin::_InterlockedCompareExchange_nf;
1397  case clang::AArch64::BI_InterlockedCompareExchange128:
1398  return MSVCIntrin::_InterlockedCompareExchange128;
1399  case clang::AArch64::BI_InterlockedCompareExchange128_acq:
1400  return MSVCIntrin::_InterlockedCompareExchange128_acq;
1401  case clang::AArch64::BI_InterlockedCompareExchange128_nf:
1402  return MSVCIntrin::_InterlockedCompareExchange128_nf;
1403  case clang::AArch64::BI_InterlockedCompareExchange128_rel:
1404  return MSVCIntrin::_InterlockedCompareExchange128_rel;
1405  case clang::AArch64::BI_InterlockedOr8_acq:
1406  case clang::AArch64::BI_InterlockedOr16_acq:
1407  case clang::AArch64::BI_InterlockedOr_acq:
1408  case clang::AArch64::BI_InterlockedOr64_acq:
1409  return MSVCIntrin::_InterlockedOr_acq;
1410  case clang::AArch64::BI_InterlockedOr8_rel:
1411  case clang::AArch64::BI_InterlockedOr16_rel:
1412  case clang::AArch64::BI_InterlockedOr_rel:
1413  case clang::AArch64::BI_InterlockedOr64_rel:
1414  return MSVCIntrin::_InterlockedOr_rel;
1415  case clang::AArch64::BI_InterlockedOr8_nf:
1416  case clang::AArch64::BI_InterlockedOr16_nf:
1417  case clang::AArch64::BI_InterlockedOr_nf:
1418  case clang::AArch64::BI_InterlockedOr64_nf:
1419  return MSVCIntrin::_InterlockedOr_nf;
1420  case clang::AArch64::BI_InterlockedXor8_acq:
1421  case clang::AArch64::BI_InterlockedXor16_acq:
1422  case clang::AArch64::BI_InterlockedXor_acq:
1423  case clang::AArch64::BI_InterlockedXor64_acq:
1424  return MSVCIntrin::_InterlockedXor_acq;
1425  case clang::AArch64::BI_InterlockedXor8_rel:
1426  case clang::AArch64::BI_InterlockedXor16_rel:
1427  case clang::AArch64::BI_InterlockedXor_rel:
1428  case clang::AArch64::BI_InterlockedXor64_rel:
1429  return MSVCIntrin::_InterlockedXor_rel;
1430  case clang::AArch64::BI_InterlockedXor8_nf:
1431  case clang::AArch64::BI_InterlockedXor16_nf:
1432  case clang::AArch64::BI_InterlockedXor_nf:
1433  case clang::AArch64::BI_InterlockedXor64_nf:
1434  return MSVCIntrin::_InterlockedXor_nf;
1435  case clang::AArch64::BI_InterlockedAnd8_acq:
1436  case clang::AArch64::BI_InterlockedAnd16_acq:
1437  case clang::AArch64::BI_InterlockedAnd_acq:
1438  case clang::AArch64::BI_InterlockedAnd64_acq:
1439  return MSVCIntrin::_InterlockedAnd_acq;
1440  case clang::AArch64::BI_InterlockedAnd8_rel:
1441  case clang::AArch64::BI_InterlockedAnd16_rel:
1442  case clang::AArch64::BI_InterlockedAnd_rel:
1443  case clang::AArch64::BI_InterlockedAnd64_rel:
1444  return MSVCIntrin::_InterlockedAnd_rel;
1445  case clang::AArch64::BI_InterlockedAnd8_nf:
1446  case clang::AArch64::BI_InterlockedAnd16_nf:
1447  case clang::AArch64::BI_InterlockedAnd_nf:
1448  case clang::AArch64::BI_InterlockedAnd64_nf:
1449  return MSVCIntrin::_InterlockedAnd_nf;
1450  case clang::AArch64::BI_InterlockedIncrement16_acq:
1451  case clang::AArch64::BI_InterlockedIncrement_acq:
1452  case clang::AArch64::BI_InterlockedIncrement64_acq:
1453  return MSVCIntrin::_InterlockedIncrement_acq;
1454  case clang::AArch64::BI_InterlockedIncrement16_rel:
1455  case clang::AArch64::BI_InterlockedIncrement_rel:
1456  case clang::AArch64::BI_InterlockedIncrement64_rel:
1457  return MSVCIntrin::_InterlockedIncrement_rel;
1458  case clang::AArch64::BI_InterlockedIncrement16_nf:
1459  case clang::AArch64::BI_InterlockedIncrement_nf:
1460  case clang::AArch64::BI_InterlockedIncrement64_nf:
1461  return MSVCIntrin::_InterlockedIncrement_nf;
1462  case clang::AArch64::BI_InterlockedDecrement16_acq:
1463  case clang::AArch64::BI_InterlockedDecrement_acq:
1464  case clang::AArch64::BI_InterlockedDecrement64_acq:
1465  return MSVCIntrin::_InterlockedDecrement_acq;
1466  case clang::AArch64::BI_InterlockedDecrement16_rel:
1467  case clang::AArch64::BI_InterlockedDecrement_rel:
1468  case clang::AArch64::BI_InterlockedDecrement64_rel:
1469  return MSVCIntrin::_InterlockedDecrement_rel;
1470  case clang::AArch64::BI_InterlockedDecrement16_nf:
1471  case clang::AArch64::BI_InterlockedDecrement_nf:
1472  case clang::AArch64::BI_InterlockedDecrement64_nf:
1473  return MSVCIntrin::_InterlockedDecrement_nf;
1474  }
1475  llvm_unreachable("must return from switch");
1476 }
1477 
1479 translateX86ToMsvcIntrin(unsigned BuiltinID) {
1481  switch (BuiltinID) {
1482  default:
1483  return std::nullopt;
1484  case clang::X86::BI_BitScanForward:
1485  case clang::X86::BI_BitScanForward64:
1486  return MSVCIntrin::_BitScanForward;
1487  case clang::X86::BI_BitScanReverse:
1488  case clang::X86::BI_BitScanReverse64:
1489  return MSVCIntrin::_BitScanReverse;
1490  case clang::X86::BI_InterlockedAnd64:
1491  return MSVCIntrin::_InterlockedAnd;
1492  case clang::X86::BI_InterlockedCompareExchange128:
1493  return MSVCIntrin::_InterlockedCompareExchange128;
1494  case clang::X86::BI_InterlockedExchange64:
1495  return MSVCIntrin::_InterlockedExchange;
1496  case clang::X86::BI_InterlockedExchangeAdd64:
1497  return MSVCIntrin::_InterlockedExchangeAdd;
1498  case clang::X86::BI_InterlockedExchangeSub64:
1499  return MSVCIntrin::_InterlockedExchangeSub;
1500  case clang::X86::BI_InterlockedOr64:
1501  return MSVCIntrin::_InterlockedOr;
1502  case clang::X86::BI_InterlockedXor64:
1503  return MSVCIntrin::_InterlockedXor;
1504  case clang::X86::BI_InterlockedDecrement64:
1505  return MSVCIntrin::_InterlockedDecrement;
1506  case clang::X86::BI_InterlockedIncrement64:
1507  return MSVCIntrin::_InterlockedIncrement;
1508  }
1509  llvm_unreachable("must return from switch");
1510 }
1511 
1512 // Emit an MSVC intrinsic. Assumes that arguments have *not* been evaluated.
1514  const CallExpr *E) {
1515  switch (BuiltinID) {
1516  case MSVCIntrin::_BitScanForward:
1517  case MSVCIntrin::_BitScanReverse: {
1518  Address IndexAddress(EmitPointerWithAlignment(E->getArg(0)));
1519  Value *ArgValue = EmitScalarExpr(E->getArg(1));
1520 
1521  llvm::Type *ArgType = ArgValue->getType();
1522  llvm::Type *IndexType = IndexAddress.getElementType();
1523  llvm::Type *ResultType = ConvertType(E->getType());
1524 
1525  Value *ArgZero = llvm::Constant::getNullValue(ArgType);
1526  Value *ResZero = llvm::Constant::getNullValue(ResultType);
1527  Value *ResOne = llvm::ConstantInt::get(ResultType, 1);
1528 
1529  BasicBlock *Begin = Builder.GetInsertBlock();
1530  BasicBlock *End = createBasicBlock("bitscan_end", this->CurFn);
1531  Builder.SetInsertPoint(End);
1532  PHINode *Result = Builder.CreatePHI(ResultType, 2, "bitscan_result");
1533 
1534  Builder.SetInsertPoint(Begin);
1535  Value *IsZero = Builder.CreateICmpEQ(ArgValue, ArgZero);
1536  BasicBlock *NotZero = createBasicBlock("bitscan_not_zero", this->CurFn);
1537  Builder.CreateCondBr(IsZero, End, NotZero);
1538  Result->addIncoming(ResZero, Begin);
1539 
1540  Builder.SetInsertPoint(NotZero);
1541 
1542  if (BuiltinID == MSVCIntrin::_BitScanForward) {
1543  Function *F = CGM.getIntrinsic(Intrinsic::cttz, ArgType);
1544  Value *ZeroCount = Builder.CreateCall(F, {ArgValue, Builder.getTrue()});
1545  ZeroCount = Builder.CreateIntCast(ZeroCount, IndexType, false);
1546  Builder.CreateStore(ZeroCount, IndexAddress, false);
1547  } else {
1548  unsigned ArgWidth = cast<llvm::IntegerType>(ArgType)->getBitWidth();
1549  Value *ArgTypeLastIndex = llvm::ConstantInt::get(IndexType, ArgWidth - 1);
1550 
1551  Function *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
1552  Value *ZeroCount = Builder.CreateCall(F, {ArgValue, Builder.getTrue()});
1553  ZeroCount = Builder.CreateIntCast(ZeroCount, IndexType, false);
1554  Value *Index = Builder.CreateNSWSub(ArgTypeLastIndex, ZeroCount);
1555  Builder.CreateStore(Index, IndexAddress, false);
1556  }
1557  Builder.CreateBr(End);
1558  Result->addIncoming(ResOne, NotZero);
1559 
1560  Builder.SetInsertPoint(End);
1561  return Result;
1562  }
1563  case MSVCIntrin::_InterlockedAnd:
1564  return MakeBinaryAtomicValue(*this, AtomicRMWInst::And, E);
1565  case MSVCIntrin::_InterlockedExchange:
1566  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xchg, E);
1567  case MSVCIntrin::_InterlockedExchangeAdd:
1568  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Add, E);
1569  case MSVCIntrin::_InterlockedExchangeSub:
1570  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Sub, E);
1571  case MSVCIntrin::_InterlockedOr:
1572  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Or, E);
1573  case MSVCIntrin::_InterlockedXor:
1574  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xor, E);
1575  case MSVCIntrin::_InterlockedExchangeAdd_acq:
1576  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Add, E,
1577  AtomicOrdering::Acquire);
1578  case MSVCIntrin::_InterlockedExchangeAdd_rel:
1579  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Add, E,
1580  AtomicOrdering::Release);
1581  case MSVCIntrin::_InterlockedExchangeAdd_nf:
1582  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Add, E,
1583  AtomicOrdering::Monotonic);
1584  case MSVCIntrin::_InterlockedExchange_acq:
1585  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xchg, E,
1586  AtomicOrdering::Acquire);
1587  case MSVCIntrin::_InterlockedExchange_rel:
1588  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xchg, E,
1589  AtomicOrdering::Release);
1590  case MSVCIntrin::_InterlockedExchange_nf:
1591  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xchg, E,
1592  AtomicOrdering::Monotonic);
1593  case MSVCIntrin::_InterlockedCompareExchange_acq:
1594  return EmitAtomicCmpXchgForMSIntrin(*this, E, AtomicOrdering::Acquire);
1595  case MSVCIntrin::_InterlockedCompareExchange_rel:
1596  return EmitAtomicCmpXchgForMSIntrin(*this, E, AtomicOrdering::Release);
1597  case MSVCIntrin::_InterlockedCompareExchange_nf:
1598  return EmitAtomicCmpXchgForMSIntrin(*this, E, AtomicOrdering::Monotonic);
1599  case MSVCIntrin::_InterlockedCompareExchange128:
1601  *this, E, AtomicOrdering::SequentiallyConsistent);
1602  case MSVCIntrin::_InterlockedCompareExchange128_acq:
1603  return EmitAtomicCmpXchg128ForMSIntrin(*this, E, AtomicOrdering::Acquire);
1604  case MSVCIntrin::_InterlockedCompareExchange128_rel:
1605  return EmitAtomicCmpXchg128ForMSIntrin(*this, E, AtomicOrdering::Release);
1606  case MSVCIntrin::_InterlockedCompareExchange128_nf:
1607  return EmitAtomicCmpXchg128ForMSIntrin(*this, E, AtomicOrdering::Monotonic);
1608  case MSVCIntrin::_InterlockedOr_acq:
1609  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Or, E,
1610  AtomicOrdering::Acquire);
1611  case MSVCIntrin::_InterlockedOr_rel:
1612  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Or, E,
1613  AtomicOrdering::Release);
1614  case MSVCIntrin::_InterlockedOr_nf:
1615  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Or, E,
1616  AtomicOrdering::Monotonic);
1617  case MSVCIntrin::_InterlockedXor_acq:
1618  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xor, E,
1619  AtomicOrdering::Acquire);
1620  case MSVCIntrin::_InterlockedXor_rel:
1621  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xor, E,
1622  AtomicOrdering::Release);
1623  case MSVCIntrin::_InterlockedXor_nf:
1624  return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xor, E,
1625  AtomicOrdering::Monotonic);
1626  case MSVCIntrin::_InterlockedAnd_acq:
1627  return MakeBinaryAtomicValue(*this, AtomicRMWInst::And, E,
1628  AtomicOrdering::Acquire);
1629  case MSVCIntrin::_InterlockedAnd_rel:
1630  return MakeBinaryAtomicValue(*this, AtomicRMWInst::And, E,
1631  AtomicOrdering::Release);
1632  case MSVCIntrin::_InterlockedAnd_nf:
1633  return MakeBinaryAtomicValue(*this, AtomicRMWInst::And, E,
1634  AtomicOrdering::Monotonic);
1635  case MSVCIntrin::_InterlockedIncrement_acq:
1636  return EmitAtomicIncrementValue(*this, E, AtomicOrdering::Acquire);
1637  case MSVCIntrin::_InterlockedIncrement_rel:
1638  return EmitAtomicIncrementValue(*this, E, AtomicOrdering::Release);
1639  case MSVCIntrin::_InterlockedIncrement_nf:
1640  return EmitAtomicIncrementValue(*this, E, AtomicOrdering::Monotonic);
1641  case MSVCIntrin::_InterlockedDecrement_acq:
1642  return EmitAtomicDecrementValue(*this, E, AtomicOrdering::Acquire);
1643  case MSVCIntrin::_InterlockedDecrement_rel:
1644  return EmitAtomicDecrementValue(*this, E, AtomicOrdering::Release);
1645  case MSVCIntrin::_InterlockedDecrement_nf:
1646  return EmitAtomicDecrementValue(*this, E, AtomicOrdering::Monotonic);
1647 
1648  case MSVCIntrin::_InterlockedDecrement:
1649  return EmitAtomicDecrementValue(*this, E);
1650  case MSVCIntrin::_InterlockedIncrement:
1651  return EmitAtomicIncrementValue(*this, E);
1652 
1653  case MSVCIntrin::__fastfail: {
1654  // Request immediate process termination from the kernel. The instruction
1655  // sequences to do this are documented on MSDN:
1656  // https://msdn.microsoft.com/en-us/library/dn774154.aspx
1657  llvm::Triple::ArchType ISA = getTarget().getTriple().getArch();
1658  StringRef Asm, Constraints;
1659  switch (ISA) {
1660  default:
1661  ErrorUnsupported(E, "__fastfail call for this architecture");
1662  break;
1663  case llvm::Triple::x86:
1664  case llvm::Triple::x86_64:
1665  Asm = "int $$0x29";
1666  Constraints = "{cx}";
1667  break;
1668  case llvm::Triple::thumb:
1669  Asm = "udf #251";
1670  Constraints = "{r0}";
1671  break;
1672  case llvm::Triple::aarch64:
1673  Asm = "brk #0xF003";
1674  Constraints = "{w0}";
1675  }
1676  llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, {Int32Ty}, false);
1677  llvm::InlineAsm *IA =
1678  llvm::InlineAsm::get(FTy, Asm, Constraints, /*hasSideEffects=*/true);
1679  llvm::AttributeList NoReturnAttr = llvm::AttributeList::get(
1680  getLLVMContext(), llvm::AttributeList::FunctionIndex,
1681  llvm::Attribute::NoReturn);
1682  llvm::CallInst *CI = Builder.CreateCall(IA, EmitScalarExpr(E->getArg(0)));
1683  CI->setAttributes(NoReturnAttr);
1684  return CI;
1685  }
1686  }
1687  llvm_unreachable("Incorrect MSVC intrinsic!");
1688 }
1689 
1690 namespace {
1691 // ARC cleanup for __builtin_os_log_format
1692 struct CallObjCArcUse final : EHScopeStack::Cleanup {
1693  CallObjCArcUse(llvm::Value *object) : object(object) {}
1694  llvm::Value *object;
1695 
1696  void Emit(CodeGenFunction &CGF, Flags flags) override {
1697  CGF.EmitARCIntrinsicUse(object);
1698  }
1699 };
1700 }
1701 
1704  assert((Kind == BCK_CLZPassedZero || Kind == BCK_CTZPassedZero)
1705  && "Unsupported builtin check kind");
1706 
1707  Value *ArgValue = EmitScalarExpr(E);
1708  if (!SanOpts.has(SanitizerKind::Builtin) || !getTarget().isCLZForZeroUndef())
1709  return ArgValue;
1710 
1711  SanitizerScope SanScope(this);
1712  Value *Cond = Builder.CreateICmpNE(
1713  ArgValue, llvm::Constant::getNullValue(ArgValue->getType()));
1714  EmitCheck(std::make_pair(Cond, SanitizerKind::Builtin),
1715  SanitizerHandler::InvalidBuiltin,
1716  {EmitCheckSourceLocation(E->getExprLoc()),
1717  llvm::ConstantInt::get(Builder.getInt8Ty(), Kind)},
1718  std::nullopt);
1719  return ArgValue;
1720 }
1721 
1722 /// Get the argument type for arguments to os_log_helper.
1724  QualType UnsignedTy = C.getIntTypeForBitwidth(Size * 8, /*Signed=*/false);
1725  return C.getCanonicalType(UnsignedTy);
1726 }
1727 
1729  const analyze_os_log::OSLogBufferLayout &Layout,
1730  CharUnits BufferAlignment) {
1731  ASTContext &Ctx = getContext();
1732 
1733  llvm::SmallString<64> Name;
1734  {
1735  raw_svector_ostream OS(Name);
1736  OS << "__os_log_helper";
1737  OS << "_" << BufferAlignment.getQuantity();
1738  OS << "_" << int(Layout.getSummaryByte());
1739  OS << "_" << int(Layout.getNumArgsByte());
1740  for (const auto &Item : Layout.Items)
1741  OS << "_" << int(Item.getSizeByte()) << "_"
1742  << int(Item.getDescriptorByte());
1743  }
1744 
1745  if (llvm::Function *F = CGM.getModule().getFunction(Name))
1746  return F;
1747 
1749  FunctionArgList Args;
1750  Args.push_back(ImplicitParamDecl::Create(
1751  Ctx, nullptr, SourceLocation(), &Ctx.Idents.get("buffer"), Ctx.VoidPtrTy,
1753  ArgTys.emplace_back(Ctx.VoidPtrTy);
1754 
1755  for (unsigned int I = 0, E = Layout.Items.size(); I < E; ++I) {
1756  char Size = Layout.Items[I].getSizeByte();
1757  if (!Size)
1758  continue;
1759 
1760  QualType ArgTy = getOSLogArgType(Ctx, Size);
1761  Args.push_back(ImplicitParamDecl::Create(
1762  Ctx, nullptr, SourceLocation(),
1763  &Ctx.Idents.get(std::string("arg") + llvm::to_string(I)), ArgTy,
1765  ArgTys.emplace_back(ArgTy);
1766  }
1767 
1768  QualType ReturnTy = Ctx.VoidTy;
1769 
1770  // The helper function has linkonce_odr linkage to enable the linker to merge
1771  // identical functions. To ensure the merging always happens, 'noinline' is
1772  // attached to the function when compiling with -Oz.
1773  const CGFunctionInfo &FI =
1774  CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, Args);
1775  llvm::FunctionType *FuncTy = CGM.getTypes().GetFunctionType(FI);
1776  llvm::Function *Fn = llvm::Function::Create(
1777  FuncTy, llvm::GlobalValue::LinkOnceODRLinkage, Name, &CGM.getModule());
1778  Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
1779  CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Fn, /*IsThunk=*/false);
1780  CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Fn);
1781  Fn->setDoesNotThrow();
1782 
1783  // Attach 'noinline' at -Oz.
1784  if (CGM.getCodeGenOpts().OptimizeSize == 2)
1785  Fn->addFnAttr(llvm::Attribute::NoInline);
1786 
1787  auto NL = ApplyDebugLocation::CreateEmpty(*this);
1788  StartFunction(GlobalDecl(), ReturnTy, Fn, FI, Args);
1789 
1790  // Create a scope with an artificial location for the body of this function.
1791  auto AL = ApplyDebugLocation::CreateArtificial(*this);
1792 
1793  CharUnits Offset;
1794  Address BufAddr =
1795  Address(Builder.CreateLoad(GetAddrOfLocalVar(Args[0]), "buf"), Int8Ty,
1796  BufferAlignment);
1797  Builder.CreateStore(Builder.getInt8(Layout.getSummaryByte()),
1798  Builder.CreateConstByteGEP(BufAddr, Offset++, "summary"));
1799  Builder.CreateStore(Builder.getInt8(Layout.getNumArgsByte()),
1800  Builder.CreateConstByteGEP(BufAddr, Offset++, "numArgs"));
1801 
1802  unsigned I = 1;
1803  for (const auto &Item : Layout.Items) {
1804  Builder.CreateStore(
1805  Builder.getInt8(Item.getDescriptorByte()),
1806  Builder.CreateConstByteGEP(BufAddr, Offset++, "argDescriptor"));
1807  Builder.CreateStore(
1808  Builder.getInt8(Item.getSizeByte()),
1809  Builder.CreateConstByteGEP(BufAddr, Offset++, "argSize"));
1810 
1811  CharUnits Size = Item.size();
1812  if (!Size.getQuantity())
1813  continue;
1814 
1815  Address Arg = GetAddrOfLocalVar(Args[I]);
1816  Address Addr = Builder.CreateConstByteGEP(BufAddr, Offset, "argData");
1817  Addr =
1818  Builder.CreateElementBitCast(Addr, Arg.getElementType(), "argDataCast");
1819  Builder.CreateStore(Builder.CreateLoad(Arg), Addr);
1820  Offset += Size;
1821  ++I;
1822  }
1823 
1824  FinishFunction();
1825 
1826  return Fn;
1827 }
1828 
1830  assert(E.getNumArgs() >= 2 &&
1831  "__builtin_os_log_format takes at least 2 arguments");
1832  ASTContext &Ctx = getContext();
1835  Address BufAddr = EmitPointerWithAlignment(E.getArg(0));
1836  llvm::SmallVector<llvm::Value *, 4> RetainableOperands;
1837 
1838  // Ignore argument 1, the format string. It is not currently used.
1839  CallArgList Args;
1840  Args.add(RValue::get(BufAddr.getPointer()), Ctx.VoidPtrTy);
1841 
1842  for (const auto &Item : Layout.Items) {
1843  int Size = Item.getSizeByte();
1844  if (!Size)
1845  continue;
1846 
1847  llvm::Value *ArgVal;
1848 
1849  if (Item.getKind() == analyze_os_log::OSLogBufferItem::MaskKind) {
1850  uint64_t Val = 0;
1851  for (unsigned I = 0, E = Item.getMaskType().size(); I < E; ++I)
1852  Val |= ((uint64_t)Item.getMaskType()[I]) << I * 8;
1853  ArgVal = llvm::Constant::getIntegerValue(Int64Ty, llvm::APInt(64, Val));
1854  } else if (const Expr *TheExpr = Item.getExpr()) {
1855  ArgVal = EmitScalarExpr(TheExpr, /*Ignore*/ false);
1856 
1857  // If a temporary object that requires destruction after the full
1858  // expression is passed, push a lifetime-extended cleanup to extend its
1859  // lifetime to the end of the enclosing block scope.
1860  auto LifetimeExtendObject = [&](const Expr *E) {
1861  E = E->IgnoreParenCasts();
1862  // Extend lifetimes of objects returned by function calls and message
1863  // sends.
1864 
1865  // FIXME: We should do this in other cases in which temporaries are
1866  // created including arguments of non-ARC types (e.g., C++
1867  // temporaries).
1868  if (isa<CallExpr>(E) || isa<ObjCMessageExpr>(E))
1869  return true;
1870  return false;
1871  };
1872 
1873  if (TheExpr->getType()->isObjCRetainableType() &&
1874  getLangOpts().ObjCAutoRefCount && LifetimeExtendObject(TheExpr)) {
1875  assert(getEvaluationKind(TheExpr->getType()) == TEK_Scalar &&
1876  "Only scalar can be a ObjC retainable type");
1877  if (!isa<Constant>(ArgVal)) {
1878  CleanupKind Cleanup = getARCCleanupKind();
1879  QualType Ty = TheExpr->getType();
1880  Address Alloca = Address::invalid();
1881  Address Addr = CreateMemTemp(Ty, "os.log.arg", &Alloca);
1882  ArgVal = EmitARCRetain(Ty, ArgVal);
1883  Builder.CreateStore(ArgVal, Addr);
1884  pushLifetimeExtendedDestroy(Cleanup, Alloca, Ty,
1886  Cleanup & EHCleanup);
1887 
1888  // Push a clang.arc.use call to ensure ARC optimizer knows that the
1889  // argument has to be alive.
1890  if (CGM.getCodeGenOpts().OptimizationLevel != 0)
1891  pushCleanupAfterFullExpr<CallObjCArcUse>(Cleanup, ArgVal);
1892  }
1893  }
1894  } else {
1895  ArgVal = Builder.getInt32(Item.getConstValue().getQuantity());
1896  }
1897 
1898  unsigned ArgValSize =
1899  CGM.getDataLayout().getTypeSizeInBits(ArgVal->getType());
1900  llvm::IntegerType *IntTy = llvm::Type::getIntNTy(getLLVMContext(),
1901  ArgValSize);
1902  ArgVal = Builder.CreateBitOrPointerCast(ArgVal, IntTy);
1903  CanQualType ArgTy = getOSLogArgType(Ctx, Size);
1904  // If ArgVal has type x86_fp80, zero-extend ArgVal.
1905  ArgVal = Builder.CreateZExtOrBitCast(ArgVal, ConvertType(ArgTy));
1906  Args.add(RValue::get(ArgVal), ArgTy);
1907  }
1908 
1909  const CGFunctionInfo &FI =
1910  CGM.getTypes().arrangeBuiltinFunctionCall(Ctx.VoidTy, Args);
1911  llvm::Function *F = CodeGenFunction(CGM).generateBuiltinOSLogHelperFunction(
1912  Layout, BufAddr.getAlignment());
1913  EmitCall(FI, CGCallee::forDirect(F), ReturnValueSlot(), Args);
1914  return RValue::get(BufAddr.getPointer());
1915 }
1916 
1918  unsigned BuiltinID, WidthAndSignedness Op1Info, WidthAndSignedness Op2Info,
1919  WidthAndSignedness ResultInfo) {
1920  return BuiltinID == Builtin::BI__builtin_mul_overflow &&
1921  Op1Info.Width == Op2Info.Width && Op2Info.Width == ResultInfo.Width &&
1922  !Op1Info.Signed && !Op2Info.Signed && ResultInfo.Signed;
1923 }
1924 
1926  CodeGenFunction &CGF, const clang::Expr *Op1, WidthAndSignedness Op1Info,
1927  const clang::Expr *Op2, WidthAndSignedness Op2Info,
1928  const clang::Expr *ResultArg, QualType ResultQTy,
1929  WidthAndSignedness ResultInfo) {
1931  Builtin::BI__builtin_mul_overflow, Op1Info, Op2Info, ResultInfo) &&
1932  "Cannot specialize this multiply");
1933 
1934  llvm::Value *V1 = CGF.EmitScalarExpr(Op1);
1935  llvm::Value *V2 = CGF.EmitScalarExpr(Op2);
1936 
1937  llvm::Value *HasOverflow;
1938  llvm::Value *Result = EmitOverflowIntrinsic(
1939  CGF, llvm::Intrinsic::umul_with_overflow, V1, V2, HasOverflow);
1940 
1941  // The intrinsic call will detect overflow when the value is > UINT_MAX,
1942  // however, since the original builtin had a signed result, we need to report
1943  // an overflow when the result is greater than INT_MAX.
1944  auto IntMax = llvm::APInt::getSignedMaxValue(ResultInfo.Width);
1945  llvm::Value *IntMaxValue = llvm::ConstantInt::get(Result->getType(), IntMax);
1946 
1947  llvm::Value *IntMaxOverflow = CGF.Builder.CreateICmpUGT(Result, IntMaxValue);
1948  HasOverflow = CGF.Builder.CreateOr(HasOverflow, IntMaxOverflow);
1949 
1950  bool isVolatile =
1951  ResultArg->getType()->getPointeeType().isVolatileQualified();
1952  Address ResultPtr = CGF.EmitPointerWithAlignment(ResultArg);
1953  CGF.Builder.CreateStore(CGF.EmitToMemory(Result, ResultQTy), ResultPtr,
1954  isVolatile);
1955  return RValue::get(HasOverflow);
1956 }
1957 
1958 /// Determine if a binop is a checked mixed-sign multiply we can specialize.
1959 static bool isSpecialMixedSignMultiply(unsigned BuiltinID,
1960  WidthAndSignedness Op1Info,
1961  WidthAndSignedness Op2Info,
1962  WidthAndSignedness ResultInfo) {
1963  return BuiltinID == Builtin::BI__builtin_mul_overflow &&
1964  std::max(Op1Info.Width, Op2Info.Width) >= ResultInfo.Width &&
1965  Op1Info.Signed != Op2Info.Signed;
1966 }
1967 
1968 /// Emit a checked mixed-sign multiply. This is a cheaper specialization of
1969 /// the generic checked-binop irgen.
1970 static RValue
1972  WidthAndSignedness Op1Info, const clang::Expr *Op2,
1973  WidthAndSignedness Op2Info,
1974  const clang::Expr *ResultArg, QualType ResultQTy,
1975  WidthAndSignedness ResultInfo) {
1976  assert(isSpecialMixedSignMultiply(Builtin::BI__builtin_mul_overflow, Op1Info,
1977  Op2Info, ResultInfo) &&
1978  "Not a mixed-sign multipliction we can specialize");
1979 
1980  // Emit the signed and unsigned operands.
1981  const clang::Expr *SignedOp = Op1Info.Signed ? Op1 : Op2;
1982  const clang::Expr *UnsignedOp = Op1Info.Signed ? Op2 : Op1;
1983  llvm::Value *Signed = CGF.EmitScalarExpr(SignedOp);
1984  llvm::Value *Unsigned = CGF.EmitScalarExpr(UnsignedOp);
1985  unsigned SignedOpWidth = Op1Info.Signed ? Op1Info.Width : Op2Info.Width;
1986  unsigned UnsignedOpWidth = Op1Info.Signed ? Op2Info.Width : Op1Info.Width;
1987 
1988  // One of the operands may be smaller than the other. If so, [s|z]ext it.
1989  if (SignedOpWidth < UnsignedOpWidth)
1990  Signed = CGF.Builder.CreateSExt(Signed, Unsigned->getType(), "op.sext");
1991  if (UnsignedOpWidth < SignedOpWidth)
1992  Unsigned = CGF.Builder.CreateZExt(Unsigned, Signed->getType(), "op.zext");
1993 
1994  llvm::Type *OpTy = Signed->getType();
1995  llvm::Value *Zero = llvm::Constant::getNullValue(OpTy);
1996  Address ResultPtr = CGF.EmitPointerWithAlignment(ResultArg);
1997  llvm::Type *ResTy = ResultPtr.getElementType();
1998  unsigned OpWidth = std::max(Op1Info.Width, Op2Info.Width);
1999 
2000  // Take the absolute value of the signed operand.
2001  llvm::Value *IsNegative = CGF.Builder.CreateICmpSLT(Signed, Zero);
2002  llvm::Value *AbsOfNegative = CGF.Builder.CreateSub(Zero, Signed);
2003  llvm::Value *AbsSigned =
2004  CGF.Builder.CreateSelect(IsNegative, AbsOfNegative, Signed);
2005 
2006  // Perform a checked unsigned multiplication.
2007  llvm::Value *UnsignedOverflow;
2008  llvm::Value *UnsignedResult =
2009  EmitOverflowIntrinsic(CGF, llvm::Intrinsic::umul_with_overflow, AbsSigned,
2010  Unsigned, UnsignedOverflow);
2011 
2012  llvm::Value *Overflow, *Result;
2013  if (ResultInfo.Signed) {
2014  // Signed overflow occurs if the result is greater than INT_MAX or lesser
2015  // than INT_MIN, i.e when |Result| > (INT_MAX + IsNegative).
2016  auto IntMax =
2017  llvm::APInt::getSignedMaxValue(ResultInfo.Width).zext(OpWidth);
2018  llvm::Value *MaxResult =
2019  CGF.Builder.CreateAdd(llvm::ConstantInt::get(OpTy, IntMax),
2020  CGF.Builder.CreateZExt(IsNegative, OpTy));
2021  llvm::Value *SignedOverflow =
2022  CGF.Builder.CreateICmpUGT(UnsignedResult, MaxResult);
2023  Overflow = CGF.Builder.CreateOr(UnsignedOverflow, SignedOverflow);
2024 
2025  // Prepare the signed result (possibly by negating it).
2026  llvm::Value *NegativeResult = CGF.Builder.CreateNeg(UnsignedResult);
2027  llvm::Value *SignedResult =
2028  CGF.Builder.CreateSelect(IsNegative, NegativeResult, UnsignedResult);
2029  Result = CGF.Builder.CreateTrunc(SignedResult, ResTy);
2030  } else {
2031  // Unsigned overflow occurs if the result is < 0 or greater than UINT_MAX.
2032  llvm::Value *Underflow = CGF.Builder.CreateAnd(
2033  IsNegative, CGF.Builder.CreateIsNotNull(UnsignedResult));
2034  Overflow = CGF.Builder.CreateOr(UnsignedOverflow, Underflow);
2035  if (ResultInfo.Width < OpWidth) {
2036  auto IntMax =
2037  llvm::APInt::getMaxValue(ResultInfo.Width).zext(OpWidth);
2038  llvm::Value *TruncOverflow = CGF.Builder.CreateICmpUGT(
2039  UnsignedResult, llvm::ConstantInt::get(OpTy, IntMax));
2040  Overflow = CGF.Builder.CreateOr(Overflow, TruncOverflow);
2041  }
2042 
2043  // Negate the product if it would be negative in infinite precision.
2044  Result = CGF.Builder.CreateSelect(
2045  IsNegative, CGF.Builder.CreateNeg(UnsignedResult), UnsignedResult);
2046 
2047  Result = CGF.Builder.CreateTrunc(Result, ResTy);
2048  }
2049  assert(Overflow && Result && "Missing overflow or result");
2050 
2051  bool isVolatile =
2052  ResultArg->getType()->getPointeeType().isVolatileQualified();
2053  CGF.Builder.CreateStore(CGF.EmitToMemory(Result, ResultQTy), ResultPtr,
2054  isVolatile);
2055  return RValue::get(Overflow);
2056 }
2057 
2058 static bool
2060  llvm::SmallPtrSetImpl<const Decl *> &Seen) {
2061  if (const auto *Arr = Ctx.getAsArrayType(Ty))
2062  Ty = Ctx.getBaseElementType(Arr);
2063 
2064  const auto *Record = Ty->getAsCXXRecordDecl();
2065  if (!Record)
2066  return false;
2067 
2068  // We've already checked this type, or are in the process of checking it.
2069  if (!Seen.insert(Record).second)
2070  return false;
2071 
2072  assert(Record->hasDefinition() &&
2073  "Incomplete types should already be diagnosed");
2074 
2075  if (Record->isDynamicClass())
2076  return true;
2077 
2078  for (FieldDecl *F : Record->fields()) {
2079  if (TypeRequiresBuiltinLaunderImp(Ctx, F->getType(), Seen))
2080  return true;
2081  }
2082  return false;
2083 }
2084 
2085 /// Determine if the specified type requires laundering by checking if it is a
2086 /// dynamic class type or contains a subobject which is a dynamic class type.
2088  if (!CGM.getCodeGenOpts().StrictVTablePointers)
2089  return false;
2091  return TypeRequiresBuiltinLaunderImp(CGM.getContext(), Ty, Seen);
2092 }
2093 
2094 RValue CodeGenFunction::emitRotate(const CallExpr *E, bool IsRotateRight) {
2095  llvm::Value *Src = EmitScalarExpr(E->getArg(0));
2096  llvm::Value *ShiftAmt = EmitScalarExpr(E->getArg(1));
2097 
2098  // The builtin's shift arg may have a different type than the source arg and
2099  // result, but the LLVM intrinsic uses the same type for all values.
2100  llvm::Type *Ty = Src->getType();
2101  ShiftAmt = Builder.CreateIntCast(ShiftAmt, Ty, false);
2102 
2103  // Rotate is a special case of LLVM funnel shift - 1st 2 args are the same.
2104  unsigned IID = IsRotateRight ? Intrinsic::fshr : Intrinsic::fshl;
2105  Function *F = CGM.getIntrinsic(IID, Ty);
2106  return RValue::get(Builder.CreateCall(F, { Src, Src, ShiftAmt }));
2107 }
2108 
2109 // Map math builtins for long-double to f128 version.
2110 static unsigned mutateLongDoubleBuiltin(unsigned BuiltinID) {
2111  switch (BuiltinID) {
2112 #define MUTATE_LDBL(func) \
2113  case Builtin::BI__builtin_##func##l: \
2114  return Builtin::BI__builtin_##func##f128;
2115  MUTATE_LDBL(sqrt)
2116  MUTATE_LDBL(cbrt)
2117  MUTATE_LDBL(fabs)
2118  MUTATE_LDBL(log)
2119  MUTATE_LDBL(log2)
2122  MUTATE_LDBL(logb)
2123  MUTATE_LDBL(exp)
2124  MUTATE_LDBL(exp2)
2126  MUTATE_LDBL(fdim)
2129  MUTATE_LDBL(pow)
2130  MUTATE_LDBL(fmin)
2131  MUTATE_LDBL(fmax)
2132  MUTATE_LDBL(ceil)
2134  MUTATE_LDBL(rint)
2142  MUTATE_LDBL(fmod)
2143  MUTATE_LDBL(modf)
2144  MUTATE_LDBL(nan)
2145  MUTATE_LDBL(nans)
2146  MUTATE_LDBL(inf)
2147  MUTATE_LDBL(fma)
2148  MUTATE_LDBL(sin)
2149  MUTATE_LDBL(cos)
2150  MUTATE_LDBL(tan)
2151  MUTATE_LDBL(sinh)
2152  MUTATE_LDBL(cosh)
2153  MUTATE_LDBL(tanh)
2154  MUTATE_LDBL(asin)
2155  MUTATE_LDBL(acos)
2156  MUTATE_LDBL(atan)
2161  MUTATE_LDBL(erf)
2162  MUTATE_LDBL(erfc)
2165  MUTATE_LDBL(huge_val)
2175 #undef MUTATE_LDBL
2176  default:
2177  return BuiltinID;
2178  }
2179 }
2180 
2182  const CallExpr *E,
2183  ReturnValueSlot ReturnValue) {
2184  const FunctionDecl *FD = GD.getDecl()->getAsFunction();
2185  // See if we can constant fold this builtin. If so, don't emit it at all.
2186  // TODO: Extend this handling to all builtin calls that we can constant-fold.
2187  Expr::EvalResult Result;
2188  if (E->isPRValue() && E->EvaluateAsRValue(Result, CGM.getContext()) &&
2189  !Result.hasSideEffects()) {
2190  if (Result.Val.isInt())
2191  return RValue::get(llvm::ConstantInt::get(getLLVMContext(),
2192  Result.Val.getInt()));
2193  if (Result.Val.isFloat())
2194  return RValue::get(llvm::ConstantFP::get(getLLVMContext(),
2195  Result.Val.getFloat()));
2196  }
2197 
2198  // If current long-double semantics is IEEE 128-bit, replace math builtins
2199  // of long-double with f128 equivalent.
2200  // TODO: This mutation should also be applied to other targets other than PPC,
2201  // after backend supports IEEE 128-bit style libcalls.
2202  if (getTarget().getTriple().isPPC64() &&
2203  &getTarget().getLongDoubleFormat() == &llvm::APFloat::IEEEquad())
2204  BuiltinID = mutateLongDoubleBuiltin(BuiltinID);
2205 
2206  // If the builtin has been declared explicitly with an assembler label,
2207  // disable the specialized emitting below. Ideally we should communicate the
2208  // rename in IR, or at least avoid generating the intrinsic calls that are
2209  // likely to get lowered to the renamed library functions.
2210  const unsigned BuiltinIDIfNoAsmLabel =
2211  FD->hasAttr<AsmLabelAttr>() ? 0 : BuiltinID;
2212 
2213  // There are LLVM math intrinsics/instructions corresponding to math library
2214  // functions except the LLVM op will never set errno while the math library
2215  // might. Also, math builtins have the same semantics as their math library
2216  // twins. Thus, we can transform math library and builtin calls to their
2217  // LLVM counterparts if the call is marked 'const' (known to never set errno).
2218  // In case FP exceptions are enabled, the experimental versions of the
2219  // intrinsics model those.
2220  bool ConstWithoutErrnoAndExceptions =
2221  getContext().BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
2222  bool ConstWithoutExceptions =
2223  getContext().BuiltinInfo.isConstWithoutExceptions(BuiltinID);
2224  if (FD->hasAttr<ConstAttr>() ||
2225  ((ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
2226  (!ConstWithoutErrnoAndExceptions || (!getLangOpts().MathErrno)))) {
2227  switch (BuiltinIDIfNoAsmLabel) {
2228  case Builtin::BIceil:
2229  case Builtin::BIceilf:
2230  case Builtin::BIceill:
2231  case Builtin::BI__builtin_ceil:
2232  case Builtin::BI__builtin_ceilf:
2233  case Builtin::BI__builtin_ceilf16:
2234  case Builtin::BI__builtin_ceill:
2235  case Builtin::BI__builtin_ceilf128:
2238  Intrinsic::experimental_constrained_ceil));
2239 
2240  case Builtin::BIcopysign:
2241  case Builtin::BIcopysignf:
2242  case Builtin::BIcopysignl:
2243  case Builtin::BI__builtin_copysign:
2244  case Builtin::BI__builtin_copysignf:
2245  case Builtin::BI__builtin_copysignf16:
2246  case Builtin::BI__builtin_copysignl:
2247  case Builtin::BI__builtin_copysignf128:
2249 
2250  case Builtin::BIcos:
2251  case Builtin::BIcosf:
2252  case Builtin::BIcosl:
2253  case Builtin::BI__builtin_cos:
2254  case Builtin::BI__builtin_cosf:
2255  case Builtin::BI__builtin_cosf16:
2256  case Builtin::BI__builtin_cosl:
2257  case Builtin::BI__builtin_cosf128:
2260  Intrinsic::experimental_constrained_cos));
2261 
2262  case Builtin::BIexp:
2263  case Builtin::BIexpf:
2264  case Builtin::BIexpl:
2265  case Builtin::BI__builtin_exp:
2266  case Builtin::BI__builtin_expf:
2267  case Builtin::BI__builtin_expf16:
2268  case Builtin::BI__builtin_expl:
2269  case Builtin::BI__builtin_expf128:
2272  Intrinsic::experimental_constrained_exp));
2273 
2274  case Builtin::BIexp2:
2275  case Builtin::BIexp2f:
2276  case Builtin::BIexp2l:
2277  case Builtin::BI__builtin_exp2:
2278  case Builtin::BI__builtin_exp2f:
2279  case Builtin::BI__builtin_exp2f16:
2280  case Builtin::BI__builtin_exp2l:
2281  case Builtin::BI__builtin_exp2f128:
2284  Intrinsic::experimental_constrained_exp2));
2285 
2286  case Builtin::BIfabs:
2287  case Builtin::BIfabsf:
2288  case Builtin::BIfabsl:
2289  case Builtin::BI__builtin_fabs:
2290  case Builtin::BI__builtin_fabsf:
2291  case Builtin::BI__builtin_fabsf16:
2292  case Builtin::BI__builtin_fabsl:
2293  case Builtin::BI__builtin_fabsf128:
2294  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::fabs));
2295 
2296  case Builtin::BIfloor:
2297  case Builtin::BIfloorf:
2298  case Builtin::BIfloorl:
2299  case Builtin::BI__builtin_floor:
2300  case Builtin::BI__builtin_floorf:
2301  case Builtin::BI__builtin_floorf16:
2302  case Builtin::BI__builtin_floorl:
2303  case Builtin::BI__builtin_floorf128:
2306  Intrinsic::experimental_constrained_floor));
2307 
2308  case Builtin::BIfma:
2309  case Builtin::BIfmaf:
2310  case Builtin::BIfmal:
2311  case Builtin::BI__builtin_fma:
2312  case Builtin::BI__builtin_fmaf:
2313  case Builtin::BI__builtin_fmaf16:
2314  case Builtin::BI__builtin_fmal:
2315  case Builtin::BI__builtin_fmaf128:
2318  Intrinsic::experimental_constrained_fma));
2319 
2320  case Builtin::BIfmax:
2321  case Builtin::BIfmaxf:
2322  case Builtin::BIfmaxl:
2323  case Builtin::BI__builtin_fmax:
2324  case Builtin::BI__builtin_fmaxf:
2325  case Builtin::BI__builtin_fmaxf16:
2326  case Builtin::BI__builtin_fmaxl:
2327  case Builtin::BI__builtin_fmaxf128:
2329  Intrinsic::maxnum,
2330  Intrinsic::experimental_constrained_maxnum));
2331 
2332  case Builtin::BIfmin:
2333  case Builtin::BIfminf:
2334  case Builtin::BIfminl:
2335  case Builtin::BI__builtin_fmin:
2336  case Builtin::BI__builtin_fminf:
2337  case Builtin::BI__builtin_fminf16:
2338  case Builtin::BI__builtin_fminl:
2339  case Builtin::BI__builtin_fminf128:
2341  Intrinsic::minnum,
2342  Intrinsic::experimental_constrained_minnum));
2343 
2344  // fmod() is a special-case. It maps to the frem instruction rather than an
2345  // LLVM intrinsic.
2346  case Builtin::BIfmod:
2347  case Builtin::BIfmodf:
2348  case Builtin::BIfmodl:
2349  case Builtin::BI__builtin_fmod:
2350  case Builtin::BI__builtin_fmodf:
2351  case Builtin::BI__builtin_fmodf16:
2352  case Builtin::BI__builtin_fmodl:
2353  case Builtin::BI__builtin_fmodf128: {
2354  CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
2355  Value *Arg1 = EmitScalarExpr(E->getArg(0));
2356  Value *Arg2 = EmitScalarExpr(E->getArg(1));
2357  return RValue::get(Builder.CreateFRem(Arg1, Arg2, "fmod"));
2358  }
2359 
2360  case Builtin::BIlog:
2361  case Builtin::BIlogf:
2362  case Builtin::BIlogl:
2363  case Builtin::BI__builtin_log:
2364  case Builtin::BI__builtin_logf:
2365  case Builtin::BI__builtin_logf16:
2366  case Builtin::BI__builtin_logl:
2367  case Builtin::BI__builtin_logf128:
2370  Intrinsic::experimental_constrained_log));
2371 
2372  case Builtin::BIlog10:
2373  case Builtin::BIlog10f:
2374  case Builtin::BIlog10l:
2375  case Builtin::BI__builtin_log10:
2376  case Builtin::BI__builtin_log10f:
2377  case Builtin::BI__builtin_log10f16:
2378  case Builtin::BI__builtin_log10l:
2379  case Builtin::BI__builtin_log10f128:
2382  Intrinsic::experimental_constrained_log10));
2383 
2384  case Builtin::BIlog2:
2385  case Builtin::BIlog2f:
2386  case Builtin::BIlog2l:
2387  case Builtin::BI__builtin_log2:
2388  case Builtin::BI__builtin_log2f:
2389  case Builtin::BI__builtin_log2f16:
2390  case Builtin::BI__builtin_log2l:
2391  case Builtin::BI__builtin_log2f128:
2394  Intrinsic::experimental_constrained_log2));
2395 
2396  case Builtin::BInearbyint:
2397  case Builtin::BInearbyintf:
2398  case Builtin::BInearbyintl:
2399  case Builtin::BI__builtin_nearbyint:
2400  case Builtin::BI__builtin_nearbyintf:
2401  case Builtin::BI__builtin_nearbyintl:
2402  case Builtin::BI__builtin_nearbyintf128:
2405  Intrinsic::experimental_constrained_nearbyint));
2406 
2407  case Builtin::BIpow:
2408  case Builtin::BIpowf:
2409  case Builtin::BIpowl:
2410  case Builtin::BI__builtin_pow:
2411  case Builtin::BI__builtin_powf:
2412  case Builtin::BI__builtin_powf16:
2413  case Builtin::BI__builtin_powl:
2414  case Builtin::BI__builtin_powf128:
2417  Intrinsic::experimental_constrained_pow));
2418 
2419  case Builtin::BIrint:
2420  case Builtin::BIrintf:
2421  case Builtin::BIrintl:
2422  case Builtin::BI__builtin_rint:
2423  case Builtin::BI__builtin_rintf:
2424  case Builtin::BI__builtin_rintf16:
2425  case Builtin::BI__builtin_rintl:
2426  case Builtin::BI__builtin_rintf128:
2429  Intrinsic::experimental_constrained_rint));
2430 
2431  case Builtin::BIround:
2432  case Builtin::BIroundf:
2433  case Builtin::BIroundl:
2434  case Builtin::BI__builtin_round:
2435  case Builtin::BI__builtin_roundf:
2436  case Builtin::BI__builtin_roundf16:
2437  case Builtin::BI__builtin_roundl:
2438  case Builtin::BI__builtin_roundf128:
2441  Intrinsic::experimental_constrained_round));
2442 
2443  case Builtin::BIsin:
2444  case Builtin::BIsinf:
2445  case Builtin::BIsinl:
2446  case Builtin::BI__builtin_sin:
2447  case Builtin::BI__builtin_sinf:
2448  case Builtin::BI__builtin_sinf16:
2449  case Builtin::BI__builtin_sinl:
2450  case Builtin::BI__builtin_sinf128:
2453  Intrinsic::experimental_constrained_sin));
2454 
2455  case Builtin::BIsqrt:
2456  case Builtin::BIsqrtf:
2457  case Builtin::BIsqrtl:
2458  case Builtin::BI__builtin_sqrt:
2459  case Builtin::BI__builtin_sqrtf:
2460  case Builtin::BI__builtin_sqrtf16:
2461  case Builtin::BI__builtin_sqrtl:
2462  case Builtin::BI__builtin_sqrtf128:
2465  Intrinsic::experimental_constrained_sqrt));
2466 
2467  case Builtin::BItrunc:
2468  case Builtin::BItruncf:
2469  case Builtin::BItruncl:
2470  case Builtin::BI__builtin_trunc:
2471  case Builtin::BI__builtin_truncf:
2472  case Builtin::BI__builtin_truncf16:
2473  case Builtin::BI__builtin_truncl:
2474  case Builtin::BI__builtin_truncf128:
2477  Intrinsic::experimental_constrained_trunc));
2478 
2479  case Builtin::BIlround:
2480  case Builtin::BIlroundf:
2481  case Builtin::BIlroundl:
2482  case Builtin::BI__builtin_lround:
2483  case Builtin::BI__builtin_lroundf:
2484  case Builtin::BI__builtin_lroundl:
2485  case Builtin::BI__builtin_lroundf128:
2487  *this, E, Intrinsic::lround,
2488  Intrinsic::experimental_constrained_lround));
2489 
2490  case Builtin::BIllround:
2491  case Builtin::BIllroundf:
2492  case Builtin::BIllroundl:
2493  case Builtin::BI__builtin_llround:
2494  case Builtin::BI__builtin_llroundf:
2495  case Builtin::BI__builtin_llroundl:
2496  case Builtin::BI__builtin_llroundf128:
2498  *this, E, Intrinsic::llround,
2499  Intrinsic::experimental_constrained_llround));
2500 
2501  case Builtin::BIlrint:
2502  case Builtin::BIlrintf:
2503  case Builtin::BIlrintl:
2504  case Builtin::BI__builtin_lrint:
2505  case Builtin::BI__builtin_lrintf:
2506  case Builtin::BI__builtin_lrintl:
2507  case Builtin::BI__builtin_lrintf128:
2509  *this, E, Intrinsic::lrint,
2510  Intrinsic::experimental_constrained_lrint));
2511 
2512  case Builtin::BIllrint:
2513  case Builtin::BIllrintf:
2514  case Builtin::BIllrintl:
2515  case Builtin::BI__builtin_llrint:
2516  case Builtin::BI__builtin_llrintf:
2517  case Builtin::BI__builtin_llrintl:
2518  case Builtin::BI__builtin_llrintf128:
2520  *this, E, Intrinsic::llrint,
2521  Intrinsic::experimental_constrained_llrint));
2522 
2523  default:
2524  break;
2525  }
2526  }
2527 
2528  switch (BuiltinIDIfNoAsmLabel) {
2529  default: break;
2530  case Builtin::BI__builtin___CFStringMakeConstantString:
2531  case Builtin::BI__builtin___NSStringMakeConstantString:
2532  return RValue::get(ConstantEmitter(*this).emitAbstract(E, E->getType()));
2533  case Builtin::BI__builtin_stdarg_start:
2534  case Builtin::BI__builtin_va_start:
2535  case Builtin::BI__va_start:
2536  case Builtin::BI__builtin_va_end:
2537  EmitVAStartEnd(BuiltinID == Builtin::BI__va_start
2538  ? EmitScalarExpr(E->getArg(0))
2539  : EmitVAListRef(E->getArg(0)).getPointer(),
2540  BuiltinID != Builtin::BI__builtin_va_end);
2541  return RValue::get(nullptr);
2542  case Builtin::BI__builtin_va_copy: {
2543  Value *DstPtr = EmitVAListRef(E->getArg(0)).getPointer();
2544  Value *SrcPtr = EmitVAListRef(E->getArg(1)).getPointer();
2545 
2546  llvm::Type *Type = Int8PtrTy;
2547 
2548  DstPtr = Builder.CreateBitCast(DstPtr, Type);
2549  SrcPtr = Builder.CreateBitCast(SrcPtr, Type);
2550  Builder.CreateCall(CGM.getIntrinsic(Intrinsic::vacopy), {DstPtr, SrcPtr});
2551  return RValue::get(nullptr);
2552  }
2553  case Builtin::BI__builtin_abs:
2554  case Builtin::BI__builtin_labs:
2555  case Builtin::BI__builtin_llabs: {
2556  // X < 0 ? -X : X
2557  // The negation has 'nsw' because abs of INT_MIN is undefined.
2558  Value *ArgValue = EmitScalarExpr(E->getArg(0));
2559  Value *NegOp = Builder.CreateNSWNeg(ArgValue, "neg");
2560  Constant *Zero = llvm::Constant::getNullValue(ArgValue->getType());
2561  Value *CmpResult = Builder.CreateICmpSLT(ArgValue, Zero, "abscond");
2562  Value *Result = Builder.CreateSelect(CmpResult, NegOp, ArgValue, "abs");
2563  return RValue::get(Result);
2564  }
2565  case Builtin::BI__builtin_complex: {
2566  Value *Real = EmitScalarExpr(E->getArg(0));
2567  Value *Imag = EmitScalarExpr(E->getArg(1));
2568  return RValue::getComplex({Real, Imag});
2569  }
2570  case Builtin::BI__builtin_conj:
2571  case Builtin::BI__builtin_conjf:
2572  case Builtin::BI__builtin_conjl:
2573  case Builtin::BIconj:
2574  case Builtin::BIconjf:
2575  case Builtin::BIconjl: {
2576  ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0));
2577  Value *Real = ComplexVal.first;
2578  Value *Imag = ComplexVal.second;
2579  Imag = Builder.CreateFNeg(Imag, "neg");
2580  return RValue::getComplex(std::make_pair(Real, Imag));
2581  }
2582  case Builtin::BI__builtin_creal:
2583  case Builtin::BI__builtin_crealf:
2584  case Builtin::BI__builtin_creall:
2585  case Builtin::BIcreal:
2586  case Builtin::BIcrealf:
2587  case Builtin::BIcreall: {
2588  ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0));
2589  return RValue::get(ComplexVal.first);
2590  }
2591 
2592  case Builtin::BI__builtin_preserve_access_index: {
2593  // Only enabled preserved access index region when debuginfo
2594  // is available as debuginfo is needed to preserve user-level
2595  // access pattern.
2596  if (!getDebugInfo()) {
2597  CGM.Error(E->getExprLoc(), "using builtin_preserve_access_index() without -g");
2598  return RValue::get(EmitScalarExpr(E->getArg(0)));
2599  }
2600 
2601  // Nested builtin_preserve_access_index() not supported
2602  if (IsInPreservedAIRegion) {
2603  CGM.Error(E->getExprLoc(), "nested builtin_preserve_access_index() not supported");
2604  return RValue::get(EmitScalarExpr(E->getArg(0)));
2605  }
2606 
2607  IsInPreservedAIRegion = true;
2608  Value *Res = EmitScalarExpr(E->getArg(0));
2609  IsInPreservedAIRegion = false;
2610  return RValue::get(Res);
2611  }
2612 
2613  case Builtin::BI__builtin_cimag:
2614  case Builtin::BI__builtin_cimagf:
2615  case Builtin::BI__builtin_cimagl:
2616  case Builtin::BIcimag:
2617  case Builtin::BIcimagf:
2618  case Builtin::BIcimagl: {
2619  ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0));
2620  return RValue::get(ComplexVal.second);
2621  }
2622 
2623  case Builtin::BI__builtin_clrsb:
2624  case Builtin::BI__builtin_clrsbl:
2625  case Builtin::BI__builtin_clrsbll: {
2626  // clrsb(x) -> clz(x < 0 ? ~x : x) - 1 or
2627  Value *ArgValue = EmitScalarExpr(E->getArg(0));
2628 
2629  llvm::Type *ArgType = ArgValue->getType();
2630  Function *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
2631 
2632  llvm::Type *ResultType = ConvertType(E->getType());
2633  Value *Zero = llvm::Constant::getNullValue(ArgType);
2634  Value *IsNeg = Builder.CreateICmpSLT(ArgValue, Zero, "isneg");
2635  Value *Inverse = Builder.CreateNot(ArgValue, "not");
2636  Value *Tmp = Builder.CreateSelect(IsNeg, Inverse, ArgValue);
2637  Value *Ctlz = Builder.CreateCall(F, {Tmp, Builder.getFalse()});
2638  Value *Result = Builder.CreateSub(Ctlz, llvm::ConstantInt::get(ArgType, 1));
2639  Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
2640  "cast");
2641  return RValue::get(Result);
2642  }
2643  case Builtin::BI__builtin_ctzs:
2644  case Builtin::BI__builtin_ctz:
2645  case Builtin::BI__builtin_ctzl:
2646  case Builtin::BI__builtin_ctzll: {
2647  Value *ArgValue = EmitCheckedArgForBuiltin(E->getArg(0), BCK_CTZPassedZero);
2648 
2649  llvm::Type *ArgType = ArgValue->getType();
2650  Function *F = CGM.getIntrinsic(Intrinsic::cttz, ArgType);
2651 
2652  llvm::Type *ResultType = ConvertType(E->getType());
2653  Value *ZeroUndef = Builder.getInt1(getTarget().isCLZForZeroUndef());
2654  Value *Result = Builder.CreateCall(F, {ArgValue, ZeroUndef});
2655  if (Result->getType() != ResultType)
2656  Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
2657  "cast");
2658  return RValue::get(Result);
2659  }
2660  case Builtin::BI__builtin_clzs:
2661  case Builtin::BI__builtin_clz:
2662  case Builtin::BI__builtin_clzl:
2663  case Builtin::BI__builtin_clzll: {
2664  Value *ArgValue = EmitCheckedArgForBuiltin(E->getArg(0), BCK_CLZPassedZero);
2665 
2666  llvm::Type *ArgType = ArgValue->getType();
2667  Function *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
2668 
2669  llvm::Type *ResultType = ConvertType(E->getType());
2670  Value *ZeroUndef = Builder.getInt1(getTarget().isCLZForZeroUndef());
2671  Value *Result = Builder.CreateCall(F, {ArgValue, ZeroUndef});
2672  if (Result->getType() != ResultType)
2673  Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
2674  "cast");
2675  return RValue::get(Result);
2676  }
2677  case Builtin::BI__builtin_ffs:
2678  case Builtin::BI__builtin_ffsl:
2679  case Builtin::BI__builtin_ffsll: {
2680  // ffs(x) -> x ? cttz(x) + 1 : 0
2681  Value *ArgValue = EmitScalarExpr(E->getArg(0));
2682 
2683  llvm::Type *ArgType = ArgValue->getType();
2684  Function *F = CGM.getIntrinsic(Intrinsic::cttz, ArgType);
2685 
2686  llvm::Type *ResultType = ConvertType(E->getType());
2687  Value *Tmp =
2688  Builder.CreateAdd(Builder.CreateCall(F, {ArgValue, Builder.getTrue()}),
2689  llvm::ConstantInt::get(ArgType, 1));
2690  Value *Zero = llvm::Constant::getNullValue(ArgType);
2691  Value *IsZero = Builder.CreateICmpEQ(ArgValue, Zero, "iszero");
2692  Value *Result = Builder.CreateSelect(IsZero, Zero, Tmp, "ffs");
2693  if (Result->getType() != ResultType)
2694  Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
2695  "cast");
2696  return RValue::get(Result);
2697  }
2698  case Builtin::BI__builtin_parity:
2699  case Builtin::BI__builtin_parityl:
2700  case Builtin::BI__builtin_parityll: {
2701  // parity(x) -> ctpop(x) & 1
2702  Value *ArgValue = EmitScalarExpr(E->getArg(0));
2703 
2704  llvm::Type *ArgType = ArgValue->getType();
2705  Function *F = CGM.getIntrinsic(Intrinsic::ctpop, ArgType);
2706 
2707  llvm::Type *ResultType = ConvertType(E->getType());
2708  Value *Tmp = Builder.CreateCall(F, ArgValue);
2709  Value *Result = Builder.CreateAnd(Tmp, llvm::ConstantInt::get(ArgType, 1));
2710  if (Result->getType() != ResultType)
2711  Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
2712  "cast");
2713  return RValue::get(Result);
2714  }
2715  case Builtin::BI__lzcnt16:
2716  case Builtin::BI__lzcnt:
2717  case Builtin::BI__lzcnt64: {
2718  Value *ArgValue = EmitScalarExpr(E->getArg(0));
2719 
2720  llvm::Type *ArgType = ArgValue->getType();
2721  Function *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
2722 
2723  llvm::Type *ResultType = ConvertType(E->getType());
2724  Value *Result = Builder.CreateCall(F, {ArgValue, Builder.getFalse()});
2725  if (Result->getType() != ResultType)
2726  Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
2727  "cast");
2728  return RValue::get(Result);
2729  }
2730  case Builtin::BI__popcnt16:
2731  case Builtin::BI__popcnt:
2732  case Builtin::BI__popcnt64:
2733  case Builtin::BI__builtin_popcount:
2734  case Builtin::BI__builtin_popcountl:
2735  case Builtin::BI__builtin_popcountll: {
2736  Value *ArgValue = EmitScalarExpr(E->getArg(0));
2737 
2738  llvm::Type *ArgType = ArgValue->getType();
2739  Function *F = CGM.getIntrinsic(Intrinsic::ctpop, ArgType);
2740 
2741  llvm::Type *ResultType = ConvertType(E->getType());
2742  Value *Result = Builder.CreateCall(F, ArgValue);
2743  if (Result->getType() != ResultType)
2744  Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
2745  "cast");
2746  return RValue::get(Result);
2747  }
2748  case Builtin::BI__builtin_unpredictable: {
2749  // Always return the argument of __builtin_unpredictable. LLVM does not
2750  // handle this builtin. Metadata for this builtin should be added directly
2751  // to instructions such as branches or switches that use it.
2752  return RValue::get(EmitScalarExpr(E->getArg(0)));
2753  }
2754  case Builtin::BI__builtin_expect: {
2755  Value *ArgValue = EmitScalarExpr(E->getArg(0));
2756  llvm::Type *ArgType = ArgValue->getType();
2757 
2758  Value *ExpectedValue = EmitScalarExpr(E->getArg(1));
2759  // Don't generate llvm.expect on -O0 as the backend won't use it for
2760  // anything.
2761  // Note, we still IRGen ExpectedValue because it could have side-effects.
2762  if (CGM.getCodeGenOpts().OptimizationLevel == 0)
2763  return RValue::get(ArgValue);
2764 
2765  Function *FnExpect = CGM.getIntrinsic(Intrinsic::expect, ArgType);
2766  Value *Result =
2767  Builder.CreateCall(FnExpect, {ArgValue, ExpectedValue}, "expval");
2768  return RValue::get(Result);
2769  }
2770  case Builtin::BI__builtin_expect_with_probability: {
2771  Value *ArgValue = EmitScalarExpr(E->getArg(0));
2772  llvm::Type *ArgType = ArgValue->getType();
2773 
2774  Value *ExpectedValue = EmitScalarExpr(E->getArg(1));
2775  llvm::APFloat Probability(0.0);
2776  const Expr *ProbArg = E->getArg(2);
2777  bool EvalSucceed = ProbArg->EvaluateAsFloat(Probability, CGM.getContext());
2778  assert(EvalSucceed && "probability should be able to evaluate as float");
2779  (void)EvalSucceed;
2780  bool LoseInfo = false;
2781  Probability.convert(llvm::APFloat::IEEEdouble(),
2782  llvm::RoundingMode::Dynamic, &LoseInfo);
2783  llvm::Type *Ty = ConvertType(ProbArg->getType());
2784  Constant *Confidence = ConstantFP::get(Ty, Probability);
2785  // Don't generate llvm.expect.with.probability on -O0 as the backend
2786  // won't use it for anything.
2787  // Note, we still IRGen ExpectedValue because it could have side-effects.
2788  if (CGM.getCodeGenOpts().OptimizationLevel == 0)
2789  return RValue::get(ArgValue);
2790 
2791  Function *FnExpect =
2792  CGM.getIntrinsic(Intrinsic::expect_with_probability, ArgType);
2793  Value *Result = Builder.CreateCall(
2794  FnExpect, {ArgValue, ExpectedValue, Confidence}, "expval");
2795  return RValue::get(Result);
2796  }
2797  case Builtin::BI__builtin_assume_aligned: {
2798  const Expr *Ptr = E->getArg(0);
2799  Value *PtrValue = EmitScalarExpr(Ptr);
2800  if (PtrValue->getType() != VoidPtrTy)
2801  PtrValue = EmitCastToVoidPtr(PtrValue);
2802  Value *OffsetValue =
2803  (E->getNumArgs() > 2) ? EmitScalarExpr(E->getArg(2)) : nullptr;
2804 
2805  Value *AlignmentValue = EmitScalarExpr(E->getArg(1));
2806  ConstantInt *AlignmentCI = cast<ConstantInt>(AlignmentValue);
2807  if (AlignmentCI->getValue().ugt(llvm::Value::MaximumAlignment))
2808  AlignmentCI = ConstantInt::get(AlignmentCI->getType(),
2809  llvm::Value::MaximumAlignment);
2810 
2811  emitAlignmentAssumption(PtrValue, Ptr,
2812  /*The expr loc is sufficient.*/ SourceLocation(),
2813  AlignmentCI, OffsetValue);
2814  return RValue::get(PtrValue);
2815  }
2816  case Builtin::BI__assume:
2817  case Builtin::BI__builtin_assume: {
2818  if (E->getArg(0)->HasSideEffects(getContext()))
2819  return RValue::get(nullptr);
2820 
2821  Value *ArgValue = EmitScalarExpr(E->getArg(0));
2822  Function *FnAssume = CGM.getIntrinsic(Intrinsic::assume);
2823  Builder.CreateCall(FnAssume, ArgValue);
2824  return RValue::get(nullptr);
2825  }
2826  case Builtin::BI__arithmetic_fence: {
2827  // Create the builtin call if FastMath is selected, and the target
2828  // supports the builtin, otherwise just return the argument.
2829  CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
2830  llvm::FastMathFlags FMF = Builder.getFastMathFlags();
2831  bool isArithmeticFenceEnabled =
2832  FMF.allowReassoc() &&
2833  getContext().getTargetInfo().checkArithmeticFenceSupported();
2834  QualType ArgType = E->getArg(0)->getType();
2835  if (ArgType->isComplexType()) {
2836  if (isArithmeticFenceEnabled) {
2837  QualType ElementType = ArgType->castAs<ComplexType>()->getElementType();
2838  ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0));
2839  Value *Real = Builder.CreateArithmeticFence(ComplexVal.first,
2840  ConvertType(ElementType));
2841  Value *Imag = Builder.CreateArithmeticFence(ComplexVal.second,
2842  ConvertType(ElementType));
2843  return RValue::getComplex(std::make_pair(Real, Imag));
2844  }
2845  ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0));
2846  Value *Real = ComplexVal.first;
2847  Value *Imag = ComplexVal.second;
2848  return RValue::getComplex(std::make_pair(Real, Imag));
2849  }
2850  Value *ArgValue = EmitScalarExpr(E->getArg(0));
2851  if (isArithmeticFenceEnabled)
2852  return RValue::get(
2853  Builder.CreateArithmeticFence(ArgValue, ConvertType(ArgType)));
2854  return RValue::get(ArgValue);
2855  }
2856  case Builtin::BI__builtin_bswap16:
2857  case Builtin::BI__builtin_bswap32:
2858  case Builtin::BI__builtin_bswap64:
2859  case Builtin::BI_byteswap_ushort:
2860  case Builtin::BI_byteswap_ulong:
2861  case Builtin::BI_byteswap_uint64: {
2862  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::bswap));
2863  }
2864  case Builtin::BI__builtin_bitreverse8:
2865  case Builtin::BI__builtin_bitreverse16:
2866  case Builtin::BI__builtin_bitreverse32:
2867  case Builtin::BI__builtin_bitreverse64: {
2868  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::bitreverse));
2869  }
2870  case Builtin::BI__builtin_rotateleft8:
2871  case Builtin::BI__builtin_rotateleft16:
2872  case Builtin::BI__builtin_rotateleft32:
2873  case Builtin::BI__builtin_rotateleft64:
2874  case Builtin::BI_rotl8: // Microsoft variants of rotate left
2875  case Builtin::BI_rotl16:
2876  case Builtin::BI_rotl:
2877  case Builtin::BI_lrotl:
2878  case Builtin::BI_rotl64:
2879  return emitRotate(E, false);
2880 
2881  case Builtin::BI__builtin_rotateright8:
2882  case Builtin::BI__builtin_rotateright16:
2883  case Builtin::BI__builtin_rotateright32:
2884  case Builtin::BI__builtin_rotateright64:
2885  case Builtin::BI_rotr8: // Microsoft variants of rotate right
2886  case Builtin::BI_rotr16:
2887  case Builtin::BI_rotr:
2888  case Builtin::BI_lrotr:
2889  case Builtin::BI_rotr64:
2890  return emitRotate(E, true);
2891 
2892  case Builtin::BI__builtin_constant_p: {
2893  llvm::Type *ResultType = ConvertType(E->getType());
2894 
2895  const Expr *Arg = E->getArg(0);
2896  QualType ArgType = Arg->getType();
2897  // FIXME: The allowance for Obj-C pointers and block pointers is historical
2898  // and likely a mistake.
2899  if (!ArgType->isIntegralOrEnumerationType() && !ArgType->isFloatingType() &&
2900  !ArgType->isObjCObjectPointerType() && !ArgType->isBlockPointerType())
2901  // Per the GCC documentation, only numeric constants are recognized after
2902  // inlining.
2903  return RValue::get(ConstantInt::get(ResultType, 0));
2904 
2905  if (Arg->HasSideEffects(getContext()))
2906  // The argument is unevaluated, so be conservative if it might have
2907  // side-effects.
2908  return RValue::get(ConstantInt::get(ResultType, 0));
2909 
2910  Value *ArgValue = EmitScalarExpr(Arg);
2911  if (ArgType->isObjCObjectPointerType()) {
2912  // Convert Objective-C objects to id because we cannot distinguish between
2913  // LLVM types for Obj-C classes as they are opaque.
2914  ArgType = CGM.getContext().getObjCIdType();
2915  ArgValue = Builder.CreateBitCast(ArgValue, ConvertType(ArgType));
2916  }
2917  Function *F =
2918  CGM.getIntrinsic(Intrinsic::is_constant, ConvertType(ArgType));
2919  Value *Result = Builder.CreateCall(F, ArgValue);
2920  if (Result->getType() != ResultType)
2921  Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/false);
2922  return RValue::get(Result);
2923  }
2924  case Builtin::BI__builtin_dynamic_object_size:
2925  case Builtin::BI__builtin_object_size: {
2926  unsigned Type =
2927  E->getArg(1)->EvaluateKnownConstInt(getContext()).getZExtValue();
2928  auto *ResType = cast<llvm::IntegerType>(ConvertType(E->getType()));
2929 
2930  // We pass this builtin onto the optimizer so that it can figure out the
2931  // object size in more complex cases.
2932  bool IsDynamic = BuiltinID == Builtin::BI__builtin_dynamic_object_size;
2933  return RValue::get(emitBuiltinObjectSize(E->getArg(0), Type, ResType,
2934  /*EmittedE=*/nullptr, IsDynamic));
2935  }
2936  case Builtin::BI__builtin_prefetch: {
2937  Value *Locality, *RW, *Address = EmitScalarExpr(E->getArg(0));
2938  // FIXME: Technically these constants should of type 'int', yes?
2939  RW = (E->getNumArgs() > 1) ? EmitScalarExpr(E->getArg(1)) :
2940  llvm::ConstantInt::get(Int32Ty, 0);
2941  Locality = (E->getNumArgs() > 2) ? EmitScalarExpr(E->getArg(2)) :
2942  llvm::ConstantInt::get(Int32Ty, 3);
2943  Value *Data = llvm::ConstantInt::get(Int32Ty, 1);
2944  Function *F = CGM.getIntrinsic(Intrinsic::prefetch, Address->getType());
2945  Builder.CreateCall(F, {Address, RW, Locality, Data});
2946  return RValue::get(nullptr);
2947  }
2948  case Builtin::BI__builtin_readcyclecounter: {
2949  Function *F = CGM.getIntrinsic(Intrinsic::readcyclecounter);
2950  return RValue::get(Builder.CreateCall(F));
2951  }
2952  case Builtin::BI__builtin___clear_cache: {
2953  Value *Begin = EmitScalarExpr(E->getArg(0));
2954  Value *End = EmitScalarExpr(E->getArg(1));
2955  Function *F = CGM.getIntrinsic(Intrinsic::clear_cache);
2956  return RValue::get(Builder.CreateCall(F, {Begin, End}));
2957  }
2958  case Builtin::BI__builtin_trap:
2959  EmitTrapCall(Intrinsic::trap);
2960  return RValue::get(nullptr);
2961  case Builtin::BI__debugbreak:
2962  EmitTrapCall(Intrinsic::debugtrap);
2963  return RValue::get(nullptr);
2964  case Builtin::BI__builtin_unreachable: {
2965  EmitUnreachable(E->getExprLoc());
2966 
2967  // We do need to preserve an insertion point.
2968  EmitBlock(createBasicBlock("unreachable.cont"));
2969 
2970  return RValue::get(nullptr);
2971  }
2972 
2973  case Builtin::BI__builtin_powi:
2974  case Builtin::BI__builtin_powif:
2975  case Builtin::BI__builtin_powil: {
2976  llvm::Value *Src0 = EmitScalarExpr(E->getArg(0));
2977  llvm::Value *Src1 = EmitScalarExpr(E->getArg(1));
2978 
2979  if (Builder.getIsFPConstrained()) {
2980  CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
2981  Function *F = CGM.getIntrinsic(Intrinsic::experimental_constrained_powi,
2982  Src0->getType());
2983  return RValue::get(Builder.CreateConstrainedFPCall(F, { Src0, Src1 }));
2984  }
2985 
2986  Function *F = CGM.getIntrinsic(Intrinsic::powi,
2987  { Src0->getType(), Src1->getType() });
2988  return RValue::get(Builder.CreateCall(F, { Src0, Src1 }));
2989  }
2990  case Builtin::BI__builtin_isgreater:
2991  case Builtin::BI__builtin_isgreaterequal:
2992  case Builtin::BI__builtin_isless:
2993  case Builtin::BI__builtin_islessequal:
2994  case Builtin::BI__builtin_islessgreater:
2995  case Builtin::BI__builtin_isunordered: {
2996  // Ordered comparisons: we know the arguments to these are matching scalar
2997  // floating point values.
2998  CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
2999  Value *LHS = EmitScalarExpr(E->getArg(0));
3000  Value *RHS = EmitScalarExpr(E->getArg(1));
3001 
3002  switch (BuiltinID) {
3003  default: llvm_unreachable("Unknown ordered comparison");
3004  case Builtin::BI__builtin_isgreater:
3005  LHS = Builder.CreateFCmpOGT(LHS, RHS, "cmp");
3006  break;
3007  case Builtin::BI__builtin_isgreaterequal:
3008  LHS = Builder.CreateFCmpOGE(LHS, RHS, "cmp");
3009  break;
3010  case Builtin::BI__builtin_isless:
3011  LHS = Builder.CreateFCmpOLT(LHS, RHS, "cmp");
3012  break;
3013  case Builtin::BI__builtin_islessequal:
3014  LHS = Builder.CreateFCmpOLE(LHS, RHS, "cmp");
3015  break;
3016  case Builtin::BI__builtin_islessgreater:
3017  LHS = Builder.CreateFCmpONE(LHS, RHS, "cmp");
3018  break;
3019  case Builtin::BI__builtin_isunordered:
3020  LHS = Builder.CreateFCmpUNO(LHS, RHS, "cmp");
3021  break;
3022  }
3023  // ZExt bool to int type.
3024  return RValue::get(Builder.CreateZExt(LHS, ConvertType(E->getType())));
3025  }
3026  case Builtin::BI__builtin_isnan: {
3027  CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
3028  Value *V = EmitScalarExpr(E->getArg(0));
3029  llvm::Type *Ty = V->getType();
3030  const llvm::fltSemantics &Semantics = Ty->getFltSemantics();
3031  if (!Builder.getIsFPConstrained() ||
3032  Builder.getDefaultConstrainedExcept() == fp::ebIgnore ||
3033  !Ty->isIEEE()) {
3034  V = Builder.CreateFCmpUNO(V, V, "cmp");
3035  return RValue::get(Builder.CreateZExt(V, ConvertType(E->getType())));
3036  }
3037 
3038  if (Value *Result = getTargetHooks().testFPKind(V, BuiltinID, Builder, CGM))
3039  return RValue::get(Result);
3040 
3041  // NaN has all exp bits set and a non zero significand. Therefore:
3042  // isnan(V) == ((exp mask - (abs(V) & exp mask)) < 0)
3043  unsigned bitsize = Ty->getScalarSizeInBits();
3044  llvm::IntegerType *IntTy = Builder.getIntNTy(bitsize);
3045  Value *IntV = Builder.CreateBitCast(V, IntTy);
3046  APInt AndMask = APInt::getSignedMaxValue(bitsize);
3047  Value *AbsV =
3048  Builder.CreateAnd(IntV, llvm::ConstantInt::get(IntTy, AndMask));
3049  APInt ExpMask = APFloat::getInf(Semantics).bitcastToAPInt();
3050  Value *Sub =
3051  Builder.CreateSub(llvm::ConstantInt::get(IntTy, ExpMask), AbsV);
3052  // V = sign bit (Sub) <=> V = (Sub < 0)
3053  V = Builder.CreateLShr(Sub, llvm::ConstantInt::get(IntTy, bitsize - 1));
3054  if (bitsize > 32)
3055  V = Builder.CreateTrunc(V, ConvertType(E->getType()));
3056  return RValue::get(V);
3057  }
3058 
3059  case Builtin::BI__builtin_elementwise_abs: {
3060  Value *Result;
3061  QualType QT = E->getArg(0)->getType();
3062 
3063  if (auto *VecTy = QT->getAs<VectorType>())
3064  QT = VecTy->getElementType();
3065  if (QT->isIntegerType())
3066  Result = Builder.CreateBinaryIntrinsic(
3067  llvm::Intrinsic::abs, EmitScalarExpr(E->getArg(0)),
3068  Builder.getFalse(), nullptr, "elt.abs");
3069  else
3070  Result = emitUnaryBuiltin(*this, E, llvm::Intrinsic::fabs, "elt.abs");
3071 
3072  return RValue::get(Result);
3073  }
3074 
3075  case Builtin::BI__builtin_elementwise_ceil:
3076  return RValue::get(
3077  emitUnaryBuiltin(*this, E, llvm::Intrinsic::ceil, "elt.ceil"));
3078  case Builtin::BI__builtin_elementwise_cos:
3079  return RValue::get(
3080  emitUnaryBuiltin(*this, E, llvm::Intrinsic::cos, "elt.cos"));
3081  case Builtin::BI__builtin_elementwise_floor:
3082  return RValue::get(
3083  emitUnaryBuiltin(*this, E, llvm::Intrinsic::floor, "elt.floor"));
3084  case Builtin::BI__builtin_elementwise_roundeven:
3085  return RValue::get(emitUnaryBuiltin(*this, E, llvm::Intrinsic::roundeven,
3086  "elt.roundeven"));
3087  case Builtin::BI__builtin_elementwise_sin:
3088  return RValue::get(
3089  emitUnaryBuiltin(*this, E, llvm::Intrinsic::sin, "elt.sin"));
3090 
3091  case Builtin::BI__builtin_elementwise_trunc:
3092  return RValue::get(
3093  emitUnaryBuiltin(*this, E, llvm::Intrinsic::trunc, "elt.trunc"));
3094 
3095  case Builtin::BI__builtin_elementwise_add_sat:
3096  case Builtin::BI__builtin_elementwise_sub_sat: {
3097  Value *Op0 = EmitScalarExpr(E->getArg(0));
3098  Value *Op1 = EmitScalarExpr(E->getArg(1));
3099  Value *Result;
3100  assert(Op0->getType()->isIntOrIntVectorTy() && "integer type expected");
3101  QualType Ty = E->getArg(0)->getType();
3102  if (auto *VecTy = Ty->getAs<VectorType>())
3103  Ty = VecTy->getElementType();
3104  bool IsSigned = Ty->isSignedIntegerType();
3105  unsigned Opc;
3106  if (BuiltinIDIfNoAsmLabel == Builtin::BI__builtin_elementwise_add_sat)
3107  Opc = IsSigned ? llvm::Intrinsic::sadd_sat : llvm::Intrinsic::uadd_sat;
3108  else
3109  Opc = IsSigned ? llvm::Intrinsic::ssub_sat : llvm::Intrinsic::usub_sat;
3110  Result = Builder.CreateBinaryIntrinsic(Opc, Op0, Op1, nullptr, "elt.sat");
3111  return RValue::get(Result);
3112  }
3113 
3114  case Builtin::BI__builtin_elementwise_max: {
3115  Value *Op0 = EmitScalarExpr(E->getArg(0));
3116  Value *Op1 = EmitScalarExpr(E->getArg(1));
3117  Value *Result;
3118  if (Op0->getType()->isIntOrIntVectorTy()) {
3119  QualType Ty = E->getArg(0)->getType();
3120  if (auto *VecTy = Ty->getAs<VectorType>())
3121  Ty = VecTy->getElementType();
3122  Result = Builder.CreateBinaryIntrinsic(Ty->isSignedIntegerType()
3123  ? llvm::Intrinsic::smax
3125  Op0, Op1, nullptr, "elt.max");
3126  } else
3127  Result = Builder.CreateMaxNum(Op0, Op1, "elt.max");
3128  return RValue::get(Result);
3129  }
3130  case Builtin::BI__builtin_elementwise_min: {
3131  Value *Op0 = EmitScalarExpr(E->getArg(0));
3132  Value *Op1 = EmitScalarExpr(E->getArg(1));
3133  Value *Result;
3134  if (Op0->getType()->isIntOrIntVectorTy()) {
3135  QualType Ty = E->getArg(0)->getType();
3136  if (auto *VecTy = Ty->getAs<VectorType>())
3137  Ty = VecTy->getElementType();
3138  Result = Builder.CreateBinaryIntrinsic(Ty->isSignedIntegerType()
3139  ? llvm::Intrinsic::smin
3141  Op0, Op1, nullptr, "elt.min");
3142  } else
3143  Result = Builder.CreateMinNum(Op0, Op1, "elt.min");
3144  return RValue::get(Result);
3145  }
3146 
3147  case Builtin::BI__builtin_reduce_max: {
3148  auto GetIntrinsicID = [](QualType QT) {
3149  if (auto *VecTy = QT->getAs<VectorType>())
3150  QT = VecTy->getElementType();
3151  if (QT->isSignedIntegerType())
3152  return llvm::Intrinsic::vector_reduce_smax;
3153  if (QT->isUnsignedIntegerType())
3154  return llvm::Intrinsic::vector_reduce_umax;
3155  assert(QT->isFloatingType() && "must have a float here");
3156  return llvm::Intrinsic::vector_reduce_fmax;
3157  };
3159  *this, E, GetIntrinsicID(E->getArg(0)->getType()), "rdx.min"));
3160  }
3161 
3162  case Builtin::BI__builtin_reduce_min: {
3163  auto GetIntrinsicID = [](QualType QT) {
3164  if (auto *VecTy = QT->getAs<VectorType>())
3165  QT = VecTy->getElementType();
3166  if (QT->isSignedIntegerType())
3167  return llvm::Intrinsic::vector_reduce_smin;
3168  if (QT->isUnsignedIntegerType())
3169  return llvm::Intrinsic::vector_reduce_umin;
3170  assert(QT->isFloatingType() && "must have a float here");
3171  return llvm::Intrinsic::vector_reduce_fmin;
3172  };
3173 
3175  *this, E, GetIntrinsicID(E->getArg(0)->getType()), "rdx.min"));
3176  }
3177 
3178  case Builtin::BI__builtin_reduce_add:
3180  *this, E, llvm::Intrinsic::vector_reduce_add, "rdx.add"));
3181  case Builtin::BI__builtin_reduce_mul:
3183  *this, E, llvm::Intrinsic::vector_reduce_mul, "rdx.mul"));
3184  case Builtin::BI__builtin_reduce_xor:
3186  *this, E, llvm::Intrinsic::vector_reduce_xor, "rdx.xor"));
3187  case Builtin::BI__builtin_reduce_or:
3189  *this, E, llvm::Intrinsic::vector_reduce_or, "rdx.or"));
3190  case Builtin::BI__builtin_reduce_and:
3192  *this, E, llvm::Intrinsic::vector_reduce_and, "rdx.and"));
3193 
3194  case Builtin::BI__builtin_matrix_transpose: {
3195  auto *MatrixTy = E->getArg(0)->getType()->castAs<ConstantMatrixType>();
3196  Value *MatValue = EmitScalarExpr(E->getArg(0));
3197  MatrixBuilder MB(Builder);
3198  Value *Result = MB.CreateMatrixTranspose(MatValue, MatrixTy->getNumRows(),
3199  MatrixTy->getNumColumns());
3200  return RValue::get(Result);
3201  }
3202 
3203  case Builtin::BI__builtin_matrix_column_major_load: {
3204  MatrixBuilder MB(Builder);
3205  // Emit everything that isn't dependent on the first parameter type
3206  Value *Stride = EmitScalarExpr(E->getArg(3));
3207  const auto *ResultTy = E->getType()->getAs<ConstantMatrixType>();
3208  auto *PtrTy = E->getArg(0)->getType()->getAs<PointerType>();
3209  assert(PtrTy && "arg0 must be of pointer type");
3210  bool IsVolatile = PtrTy->getPointeeType().isVolatileQualified();
3211 
3212  Address Src = EmitPointerWithAlignment(E->getArg(0));
3213  EmitNonNullArgCheck(RValue::get(Src.getPointer()), E->getArg(0)->getType(),
3214  E->getArg(0)->getExprLoc(), FD, 0);
3215  Value *Result = MB.CreateColumnMajorLoad(
3216  Src.getElementType(), Src.getPointer(),
3217  Align(Src.getAlignment().getQuantity()), Stride, IsVolatile,
3218  ResultTy->getNumRows(), ResultTy->getNumColumns(),
3219  "matrix");
3220  return RValue::get(Result);
3221  }
3222 
3223  case Builtin::BI__builtin_matrix_column_major_store: {
3224  MatrixBuilder MB(Builder);
3225  Value *Matrix = EmitScalarExpr(E->getArg(0));
3226  Address Dst = EmitPointerWithAlignment(E->getArg(1));
3227  Value *Stride = EmitScalarExpr(E->getArg(2));
3228 
3229  const auto *MatrixTy = E->getArg(0)->getType()->getAs<ConstantMatrixType>();
3230  auto *PtrTy = E->getArg(1)->getType()->getAs<PointerType>();
3231  assert(PtrTy && "arg1 must be of pointer type");
3232  bool IsVolatile = PtrTy->getPointeeType().isVolatileQualified();
3233 
3234  EmitNonNullArgCheck(RValue::get(Dst.getPointer()), E->getArg(1)->getType(),
3235  E->getArg(1)->getExprLoc(), FD, 0);
3236  Value *Result = MB.CreateColumnMajorStore(
3237  Matrix, Dst.getPointer(), Align(Dst.getAlignment().getQuantity()),
3238  Stride, IsVolatile, MatrixTy->getNumRows(), MatrixTy->getNumColumns());
3239  return RValue::get(Result);
3240  }
3241 
3242  case Builtin::BIfinite:
3243  case Builtin::BI__finite:
3244  case Builtin::BIfinitef:
3245  case Builtin::BI__finitef:
3246  case Builtin::BIfinitel:
3247  case Builtin::BI__finitel:
3248  case Builtin::BI__builtin_isinf:
3249  case Builtin::BI__builtin_isfinite: {
3250  // isinf(x) --> fabs(x) == infinity
3251  // isfinite(x) --> fabs(x) != infinity
3252  // x != NaN via the ordered compare in either case.
3253  CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
3254  Value *V = EmitScalarExpr(E->getArg(0));
3255  llvm::Type *Ty = V->getType();
3256  if (!Builder.getIsFPConstrained() ||
3257  Builder.getDefaultConstrainedExcept() == fp::ebIgnore ||
3258  !Ty->isIEEE()) {
3259  Value *Fabs = EmitFAbs(*this, V);
3260  Constant *Infinity = ConstantFP::getInfinity(V->getType());
3261  CmpInst::Predicate Pred = (BuiltinID == Builtin::BI__builtin_isinf)
3262  ? CmpInst::FCMP_OEQ
3263  : CmpInst::FCMP_ONE;
3264  Value *FCmp = Builder.CreateFCmp(Pred, Fabs, Infinity, "cmpinf");
3265  return RValue::get(Builder.CreateZExt(FCmp, ConvertType(E->getType())));
3266  }
3267 
3268  if (Value *Result = getTargetHooks().testFPKind(V, BuiltinID, Builder, CGM))
3269  return RValue::get(Result);
3270 
3271  // Inf values have all exp bits set and a zero significand. Therefore:
3272  // isinf(V) == ((V << 1) == ((exp mask) << 1))
3273  // isfinite(V) == ((V << 1) < ((exp mask) << 1)) using unsigned comparison
3274  unsigned bitsize = Ty->getScalarSizeInBits();
3275  llvm::IntegerType *IntTy = Builder.getIntNTy(bitsize);
3276  Value *IntV = Builder.CreateBitCast(V, IntTy);
3277  Value *Shl1 = Builder.CreateShl(IntV, 1);
3278  const llvm::fltSemantics &Semantics = Ty->getFltSemantics();
3279  APInt ExpMask = APFloat::getInf(Semantics).bitcastToAPInt();
3280  Value *ExpMaskShl1 = llvm::ConstantInt::get(IntTy, ExpMask.shl(1));
3281  if (BuiltinID == Builtin::BI__builtin_isinf)
3282  V = Builder.CreateICmpEQ(Shl1, ExpMaskShl1);
3283  else
3284  V = Builder.CreateICmpULT(Shl1, ExpMaskShl1);
3285  return RValue::get(Builder.CreateZExt(V, ConvertType(E->getType())));
3286  }
3287 
3288  case Builtin::BI__builtin_isinf_sign: {
3289  // isinf_sign(x) -> fabs(x) == infinity ? (signbit(x) ? -1 : 1) : 0
3290  CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
3291  // FIXME: for strictfp/IEEE-754 we need to not trap on SNaN here.
3292  Value *Arg = EmitScalarExpr(E->getArg(0));
3293  Value *AbsArg = EmitFAbs(*this, Arg);
3294  Value *IsInf = Builder.CreateFCmpOEQ(
3295  AbsArg, ConstantFP::getInfinity(Arg->getType()), "isinf");
3296  Value *IsNeg = EmitSignBit(*this, Arg);
3297 
3298  llvm::Type *IntTy = ConvertType(E->getType());
3299  Value *Zero = Constant::getNullValue(IntTy);
3300  Value *One = ConstantInt::get(IntTy, 1);
3301  Value *NegativeOne = ConstantInt::get(IntTy, -1);
3302  Value *SignResult = Builder.CreateSelect(IsNeg, NegativeOne, One);
3303  Value *Result = Builder.CreateSelect(IsInf, SignResult, Zero);
3304  return RValue::get(Result);
3305  }
3306 
3307  case Builtin::BI__builtin_isnormal: {
3308  // isnormal(x) --> x == x && fabsf(x) < infinity && fabsf(x) >= float_min
3309  CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
3310  // FIXME: for strictfp/IEEE-754 we need to not trap on SNaN here.
3311  Value *V = EmitScalarExpr(E->getArg(0));
3312  Value *Eq = Builder.CreateFCmpOEQ(V, V, "iseq");
3313 
3314  Value *Abs = EmitFAbs(*this, V);
3315  Value *IsLessThanInf =
3316  Builder.CreateFCmpULT(Abs, ConstantFP::getInfinity(V->getType()),"isinf");
3317  APFloat Smallest = APFloat::getSmallestNormalized(
3318  getContext().getFloatTypeSemantics(E->getArg(0)->getType()));
3319  Value *IsNormal =
3320  Builder.CreateFCmpUGE(Abs, ConstantFP::get(V->getContext(), Smallest),
3321  "isnormal");
3322  V = Builder.CreateAnd(Eq, IsLessThanInf, "and");
3323  V = Builder.CreateAnd(V, IsNormal, "and");
3324  return RValue::get(Builder.CreateZExt(V, ConvertType(E->getType())));
3325  }
3326 
3327  case Builtin::BI__builtin_flt_rounds: {
3328  Function *F = CGM.getIntrinsic(Intrinsic::flt_rounds);
3329 
3330  llvm::Type *ResultType = ConvertType(E->getType());
3331  Value *Result = Builder.CreateCall(F);
3332  if (Result->getType() != ResultType)
3333  Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
3334  "cast");
3335  return RValue::get(Result);
3336  }
3337 
3338  case Builtin::BI__builtin_fpclassify: {
3339  CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
3340  // FIXME: for strictfp/IEEE-754 we need to not trap on SNaN here.
3341  Value *V = EmitScalarExpr(E->getArg(5));
3342  llvm::Type *Ty = ConvertType(E->getArg(5)->getType());
3343 
3344  // Create Result
3345  BasicBlock *Begin = Builder.GetInsertBlock();
3346  BasicBlock *End = createBasicBlock("fpclassify_end", this->CurFn);
3347  Builder.SetInsertPoint(End);
3348  PHINode *Result =
3349  Builder.CreatePHI(ConvertType(E->getArg(0)->getType()), 4,
3350  "fpclassify_result");
3351 
3352  // if (V==0) return FP_ZERO
3353  Builder.SetInsertPoint(Begin);
3354  Value *IsZero = Builder.CreateFCmpOEQ(V, Constant::getNullValue(Ty),
3355  "iszero");
3356  Value *ZeroLiteral = EmitScalarExpr(E->getArg(4));
3357  BasicBlock *NotZero = createBasicBlock("fpclassify_not_zero", this->CurFn);
3358  Builder.CreateCondBr(IsZero, End, NotZero);
3359  Result->addIncoming(ZeroLiteral, Begin);
3360 
3361  // if (V != V) return FP_NAN
3362  Builder.SetInsertPoint(NotZero);
3363  Value *IsNan = Builder.CreateFCmpUNO(V, V, "cmp");
3364  Value *NanLiteral = EmitScalarExpr(E->getArg(0));
3365  BasicBlock *NotNan = createBasicBlock("fpclassify_not_nan", this->CurFn);
3366  Builder.CreateCondBr(IsNan, End, NotNan);
3367  Result->addIncoming(NanLiteral, NotZero);
3368 
3369  // if (fabs(V) == infinity) return FP_INFINITY
3370  Builder.SetInsertPoint(NotNan);
3371  Value *VAbs = EmitFAbs(*this, V);
3372  Value *IsInf =
3373  Builder.CreateFCmpOEQ(VAbs, ConstantFP::getInfinity(V->getType()),
3374  "isinf");
3375  Value *InfLiteral = EmitScalarExpr(E->getArg(1));
3376  BasicBlock *NotInf = createBasicBlock("fpclassify_not_inf", this->CurFn);
3377  Builder.CreateCondBr(IsInf, End, NotInf);
3378  Result->addIncoming(InfLiteral, NotNan);
3379 
3380  // if (fabs(V) >= MIN_NORMAL) return FP_NORMAL else FP_SUBNORMAL
3381  Builder.SetInsertPoint(NotInf);
3382  APFloat Smallest = APFloat::getSmallestNormalized(
3383  getContext().getFloatTypeSemantics(E->getArg(5)->getType()));
3384  Value *IsNormal =
3385  Builder.CreateFCmpUGE(VAbs, ConstantFP::get(V->getContext(), Smallest),
3386  "isnormal");
3387  Value *NormalResult =
3388  Builder.CreateSelect(IsNormal, EmitScalarExpr(E->getArg(2)),
3389  EmitScalarExpr(E->getArg(3)));
3390  Builder.CreateBr(End);
3391  Result->addIncoming(NormalResult, NotInf);
3392 
3393  // return Result
3394  Builder.SetInsertPoint(End);
3395  return RValue::get(Result);
3396  }
3397 
3398  case Builtin::BIalloca:
3399  case Builtin::BI_alloca:
3400  case Builtin::BI__builtin_alloca_uninitialized:
3401  case Builtin::BI__builtin_alloca: {
3402  Value *Size = EmitScalarExpr(E->getArg(0));
3403  const TargetInfo &TI = getContext().getTargetInfo();
3404  // The alignment of the alloca should correspond to __BIGGEST_ALIGNMENT__.
3405  const Align SuitableAlignmentInBytes =
3406  CGM.getContext()
3407  .toCharUnitsFromBits(TI.getSuitableAlign())
3408  .getAsAlign();
3409  AllocaInst *AI = Builder.CreateAlloca(Builder.getInt8Ty(), Size);
3410  AI->setAlignment(SuitableAlignmentInBytes);
3411  if (BuiltinID != Builtin::BI__builtin_alloca_uninitialized)
3412  initializeAlloca(*this, AI, Size, SuitableAlignmentInBytes);
3413  return RValue::get(AI);
3414  }
3415 
3416  case Builtin::BI__builtin_alloca_with_align_uninitialized:
3417  case Builtin::BI__builtin_alloca_with_align: {
3418  Value *Size = EmitScalarExpr(E->getArg(0));
3419  Value *AlignmentInBitsValue = EmitScalarExpr(E->getArg(1));
3420  auto *AlignmentInBitsCI = cast<ConstantInt>(AlignmentInBitsValue);
3421  unsigned AlignmentInBits = AlignmentInBitsCI->getZExtValue();
3422  const Align AlignmentInBytes =
3423  CGM.getContext().toCharUnitsFromBits(AlignmentInBits).getAsAlign();
3424  AllocaInst *AI = Builder.CreateAlloca(Builder.getInt8Ty(), Size);
3425  AI->setAlignment(AlignmentInBytes);
3426  if (BuiltinID != Builtin::BI__builtin_alloca_with_align_uninitialized)
3427  initializeAlloca(*this, AI, Size, AlignmentInBytes);
3428  return RValue::get(AI);
3429  }
3430 
3431  case Builtin::BIbzero:
3432  case Builtin::BI__builtin_bzero: {
3433  Address Dest = EmitPointerWithAlignment(E->getArg(0));
3434  Value *SizeVal = EmitScalarExpr(E->getArg(1));
3435  EmitNonNullArgCheck(RValue::get(Dest.getPointer()), E->getArg(0)->getType(),
3436  E->getArg(0)->getExprLoc(), FD, 0);
3437  Builder.CreateMemSet(Dest, Builder.getInt8(0), SizeVal, false);
3438  return RValue::get(nullptr);
3439  }
3440  case Builtin::BImemcpy:
3441  case Builtin::BI__builtin_memcpy:
3442  case Builtin::BImempcpy:
3443  case Builtin::BI__builtin_mempcpy: {
3444  Address Dest = EmitPointerWithAlignment(E->getArg(0));
3445  Address Src = EmitPointerWithAlignment(E->getArg(1));
3446  Value *SizeVal = EmitScalarExpr(E->getArg(2));
3447  EmitNonNullArgCheck(RValue::get(Dest.getPointer()), E->getArg(0)->getType(),
3448  E->getArg(0)->getExprLoc(), FD, 0);
3449  EmitNonNullArgCheck(RValue::get(Src.getPointer()), E->getArg(1)->getType(),
3450  E->getArg(1)->getExprLoc(), FD, 1);
3451  Builder.CreateMemCpy(Dest, Src, SizeVal, false);
3452  if (BuiltinID == Builtin::BImempcpy ||
3453  BuiltinID == Builtin::BI__builtin_mempcpy)
3454  return RValue::get(Builder.CreateInBoundsGEP(Dest.getElementType(),
3455  Dest.getPointer(), SizeVal));
3456  else
3457  return RValue::get(Dest.getPointer());
3458  }
3459 
3460  case Builtin::BI__builtin_memcpy_inline: {
3461  Address Dest = EmitPointerWithAlignment(E->getArg(0));
3462  Address Src = EmitPointerWithAlignment(E->getArg(1));
3463  uint64_t Size =
3464  E->getArg(2)->EvaluateKnownConstInt(getContext()).getZExtValue();
3465  EmitNonNullArgCheck(RValue::get(Dest.getPointer()), E->getArg(0)->getType(),
3466  E->getArg(0)->getExprLoc(), FD, 0);
3467  EmitNonNullArgCheck(RValue::get(Src.getPointer()), E->getArg(1)->getType(),
3468  E->getArg(1)->getExprLoc(), FD, 1);
3469  Builder.CreateMemCpyInline(Dest, Src, Size);
3470  return RValue::get(nullptr);
3471  }
3472 
3473  case Builtin::BI__builtin_char_memchr:
3474  BuiltinID = Builtin::BI__builtin_memchr;
3475  break;
3476 
3477  case Builtin::BI__builtin___memcpy_chk: {
3478  // fold __builtin_memcpy_chk(x, y, cst1, cst2) to memcpy iff cst1<=cst2.
3479  Expr::EvalResult SizeResult, DstSizeResult;
3480  if (!E->getArg(2)->EvaluateAsInt(SizeResult, CGM.getContext()) ||
3481  !E->getArg(3)->EvaluateAsInt(DstSizeResult, CGM.getContext()))
3482  break;
3483  llvm::APSInt Size = SizeResult.Val.getInt();
3484  llvm::APSInt DstSize = DstSizeResult.Val.getInt();
3485  if (Size.ugt(DstSize))
3486  break;
3487  Address Dest = EmitPointerWithAlignment(E->getArg(0));
3488  Address Src = EmitPointerWithAlignment(E->getArg(1));
3489  Value *SizeVal = llvm::ConstantInt::get(Builder.getContext(), Size);
3490  Builder.CreateMemCpy(Dest, Src, SizeVal, false);
3491  return RValue::get(Dest.getPointer());
3492  }
3493 
3494  case Builtin::BI__builtin_objc_memmove_collectable: {
3495  Address DestAddr = EmitPointerWithAlignment(E->getArg(0));
3496  Address SrcAddr = EmitPointerWithAlignment(E->getArg(1));
3497  Value *SizeVal = EmitScalarExpr(E->getArg(2));
3498  CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this,
3499  DestAddr, SrcAddr, SizeVal);
3500  return RValue::get(DestAddr.getPointer());
3501  }
3502 
3503  case Builtin::BI__builtin___memmove_chk: {
3504  // fold __builtin_memmove_chk(x, y, cst1, cst2) to memmove iff cst1<=cst2.
3505  Expr::EvalResult SizeResult, DstSizeResult;
3506  if (!E->getArg(2)->EvaluateAsInt(SizeResult, CGM.getContext()) ||
3507  !E->getArg(3)->EvaluateAsInt(DstSizeResult, CGM.getContext()))
3508  break;
3509  llvm::APSInt Size = SizeResult.Val.getInt();
3510  llvm::APSInt DstSize = DstSizeResult.Val.getInt();
3511  if (Size.ugt(DstSize))
3512  break;
3513  Address Dest = EmitPointerWithAlignment(E->getArg(0));
3514  Address Src = EmitPointerWithAlignment(E->getArg(1));
3515  Value *SizeVal = llvm::ConstantInt::get(Builder.getContext(), Size);
3516  Builder.CreateMemMove(Dest, Src, SizeVal, false);
3517  return RValue::get(Dest.getPointer());
3518  }
3519 
3520  case Builtin::BImemmove:
3521  case Builtin::BI__builtin_memmove: {
3522  Address Dest = EmitPointerWithAlignment(E->getArg(0));
3523  Address Src = EmitPointerWithAlignment(E->getArg(1));
3524  Value *SizeVal = EmitScalarExpr(E->getArg(2));
3525  EmitNonNullArgCheck(RValue::get(Dest.getPointer()), E->getArg(0)->getType(),
3526  E->getArg(0)->getExprLoc(), FD, 0);
3527  EmitNonNullArgCheck(RValue::get(Src.getPointer()), E->getArg(1)->getType(),
3528  E->getArg(1)->getExprLoc(), FD, 1);
3529  Builder.CreateMemMove(Dest, Src, SizeVal, false);
3530  return RValue::get(Dest.getPointer());
3531  }
3532  case Builtin::BImemset:
3533  case Builtin::BI__builtin_memset: {
3534  Address Dest = EmitPointerWithAlignment(E->getArg(0));
3535  Value *ByteVal = Builder.CreateTrunc(EmitScalarExpr(E->getArg(1)),
3536  Builder.getInt8Ty());
3537  Value *SizeVal = EmitScalarExpr(E->getArg(2));
3538  EmitNonNullArgCheck(RValue::get(Dest.getPointer()), E->getArg(0)->getType(),
3539  E->getArg(0)->getExprLoc(), FD, 0);
3540  Builder.CreateMemSet(Dest, ByteVal, SizeVal, false);
3541  return RValue::get(Dest.getPointer());
3542  }
3543  case Builtin::BI__builtin_memset_inline: {
3544  Address Dest = EmitPointerWithAlignment(E->getArg(0));
3545  Value *ByteVal =
3546  Builder.CreateTrunc(EmitScalarExpr(E->getArg(1)), Builder.getInt8Ty());
3547  uint64_t Size =
3548  E->getArg(2)->EvaluateKnownConstInt(getContext()).getZExtValue();
3549  EmitNonNullArgCheck(RValue::get(Dest.getPointer()), E->getArg(0)->getType(),
3550  E->getArg(0)->getExprLoc(), FD, 0);
3551  Builder.CreateMemSetInline(Dest, ByteVal, Size);
3552  return RValue::get(nullptr);
3553  }
3554  case Builtin::BI__builtin___memset_chk: {
3555  // fold __builtin_memset_chk(x, y, cst1, cst2) to memset iff cst1<=cst2.
3556  Expr::EvalResult SizeResult, DstSizeResult;
3557  if (!E->getArg(2)->EvaluateAsInt(SizeResult, CGM.getContext()) ||
3558  !E->getArg(3)->EvaluateAsInt(DstSizeResult, CGM.getContext()))
3559  break;
3560  llvm::APSInt Size = SizeResult.Val.getInt();
3561  llvm::APSInt DstSize = DstSizeResult.Val.getInt();
3562  if (Size.ugt(DstSize))
3563  break;
3564  Address Dest = EmitPointerWithAlignment(E->getArg(0));
3565  Value *ByteVal = Builder.CreateTrunc(EmitScalarExpr(E->getArg(1)),
3566  Builder.getInt8Ty());
3567  Value *SizeVal = llvm::ConstantInt::get(Builder.getContext(), Size);
3568  Builder.CreateMemSet(Dest, ByteVal, SizeVal, false);
3569  return RValue::get(Dest.getPointer());
3570  }
3571  case Builtin::BI__builtin_wmemchr: {
3572  // The MSVC runtime library does not provide a definition of wmemchr, so we
3573  // need an inline implementation.
3574  if (!getTarget().getTriple().isOSMSVCRT())
3575  break;
3576 
3577  llvm::Type *WCharTy = ConvertType(getContext().WCharTy);
3578  Value *Str = EmitScalarExpr(E->getArg(0));
3579  Value *Chr = EmitScalarExpr(E->getArg(1));
3580  Value *Size = EmitScalarExpr(E->getArg(2));
3581 
3582  BasicBlock *Entry = Builder.GetInsertBlock();
3583  BasicBlock *CmpEq = createBasicBlock("wmemchr.eq");
3584  BasicBlock *Next = createBasicBlock("wmemchr.next");
3585  BasicBlock *Exit = createBasicBlock("wmemchr.exit");
3586  Value *SizeEq0 = Builder.CreateICmpEQ(Size, ConstantInt::get(SizeTy, 0));
3587  Builder.CreateCondBr(SizeEq0, Exit, CmpEq);
3588 
3589  EmitBlock(CmpEq);
3590  PHINode *StrPhi = Builder.CreatePHI(Str->getType(), 2);
3591  StrPhi->addIncoming(Str, Entry);
3592  PHINode *SizePhi = Builder.CreatePHI(SizeTy, 2);
3593  SizePhi->addIncoming(Size, Entry);
3594  CharUnits WCharAlign =
3595  getContext().getTypeAlignInChars(getContext().WCharTy);
3596  Value *StrCh = Builder.CreateAlignedLoad(WCharTy, StrPhi, WCharAlign);
3597  Value *FoundChr = Builder.CreateConstInBoundsGEP1_32(WCharTy, StrPhi, 0);
3598  Value *StrEqChr = Builder.CreateICmpEQ(StrCh, Chr);
3599  Builder.CreateCondBr(StrEqChr, Exit, Next);
3600 
3601  EmitBlock(Next);
3602  Value *NextStr = Builder.CreateConstInBoundsGEP1_32(WCharTy, StrPhi, 1);
3603  Value *NextSize = Builder.CreateSub(SizePhi, ConstantInt::get(SizeTy, 1));
3604  Value *NextSizeEq0 =
3605  Builder.CreateICmpEQ(NextSize, ConstantInt::get(SizeTy, 0));
3606  Builder.CreateCondBr(NextSizeEq0, Exit, CmpEq);
3607  StrPhi->addIncoming(NextStr, Next);
3608  SizePhi->addIncoming(NextSize, Next);
3609 
3610  EmitBlock(Exit);
3611  PHINode *Ret = Builder.CreatePHI(Str->getType(), 3);
3612  Ret->addIncoming(llvm::Constant::getNullValue(Str->getType()), Entry);
3613  Ret->addIncoming(llvm::Constant::getNullValue(Str->getType()), Next);
3614  Ret->addIncoming(FoundChr, CmpEq);
3615  return RValue::get(Ret);
3616  }
3617  case Builtin::BI__builtin_wmemcmp: {
3618  // The MSVC runtime library does not provide a definition of wmemcmp, so we
3619  // need an inline implementation.
3620  if (!getTarget().getTriple().isOSMSVCRT())
3621  break;
3622 
3623  llvm::Type *WCharTy = ConvertType(getContext().WCharTy);
3624 
3625  Value *Dst = EmitScalarExpr(E->getArg(0));
3626  Value *Src = EmitScalarExpr(E->getArg(1));
3627  Value *Size = EmitScalarExpr(E->getArg(2));
3628 
3629  BasicBlock *Entry = Builder.GetInsertBlock();
3630  BasicBlock *CmpGT = createBasicBlock("wmemcmp.gt");
3631  BasicBlock *CmpLT = createBasicBlock("wmemcmp.lt");
3632  BasicBlock *Next = createBasicBlock("wmemcmp.next");
3633  BasicBlock *Exit = createBasicBlock("wmemcmp.exit");
3634  Value *SizeEq0 = Builder.CreateICmpEQ(Size, ConstantInt::get(SizeTy, 0));
3635  Builder.CreateCondBr(SizeEq0, Exit, CmpGT);
3636 
3637  EmitBlock(CmpGT);
3638  PHINode *DstPhi = Builder.CreatePHI(Dst->getType(), 2);
3639  DstPhi->addIncoming(Dst, Entry);
3640  PHINode *SrcPhi = Builder.CreatePHI(Src->getType(), 2);
3641  SrcPhi->addIncoming(Src, Entry);
3642  PHINode *SizePhi = Builder.CreatePHI(SizeTy, 2);
3643  SizePhi->addIncoming(Size, Entry);
3644  CharUnits WCharAlign =
3645  getContext().getTypeAlignInChars(getContext().WCharTy);
3646  Value *DstCh = Builder.CreateAlignedLoad(WCharTy, DstPhi, WCharAlign);
3647  Value *SrcCh = Builder.CreateAlignedLoad(WCharTy, SrcPhi, WCharAlign);
3648  Value *DstGtSrc = Builder.CreateICmpUGT(DstCh, SrcCh);
3649  Builder.CreateCondBr(DstGtSrc, Exit, CmpLT);
3650 
3651  EmitBlock(CmpLT);
3652  Value *DstLtSrc = Builder.CreateICmpULT(DstCh, SrcCh);
3653  Builder.CreateCondBr(DstLtSrc, Exit, Next);
3654 
3655  EmitBlock(Next);
3656  Value *NextDst = Builder.CreateConstInBoundsGEP1_32(WCharTy, DstPhi, 1);
3657  Value *NextSrc = Builder.CreateConstInBoundsGEP1_32(WCharTy, SrcPhi, 1);
3658  Value *NextSize = Builder.CreateSub(SizePhi, ConstantInt::get(SizeTy, 1));
3659  Value *NextSizeEq0 =
3660  Builder.CreateICmpEQ(NextSize, ConstantInt::get(SizeTy, 0));
3661  Builder.CreateCondBr(NextSizeEq0, Exit, CmpGT);
3662  DstPhi->addIncoming(NextDst, Next);
3663  SrcPhi->addIncoming(NextSrc, Next);
3664  SizePhi->addIncoming(NextSize, Next);
3665 
3666  EmitBlock(Exit);
3667  PHINode *Ret = Builder.CreatePHI(IntTy, 4);
3668  Ret->addIncoming(ConstantInt::get(IntTy, 0), Entry);
3669  Ret->addIncoming(ConstantInt::get(IntTy, 1), CmpGT);
3670  Ret->addIncoming(ConstantInt::get(IntTy, -1), CmpLT);
3671  Ret->addIncoming(ConstantInt::get(IntTy, 0), Next);
3672  return RValue::get(Ret);
3673  }
3674  case Builtin::BI__builtin_dwarf_cfa: {
3675  // The offset in bytes from the first argument to the CFA.
3676  //
3677  // Why on earth is this in the frontend? Is there any reason at
3678  // all that the backend can't reasonably determine this while
3679  // lowering llvm.eh.dwarf.cfa()?
3680  //
3681  // TODO: If there's a satisfactory reason, add a target hook for
3682  // this instead of hard-coding 0, which is correct for most targets.
3683  int32_t Offset = 0;
3684 
3685  Function *F = CGM.getIntrinsic(Intrinsic::eh_dwarf_cfa);
3686  return RValue::get(Builder.CreateCall(F,
3687  llvm::ConstantInt::get(Int32Ty, Offset)));
3688  }
3689  case Builtin::BI__builtin_return_address: {
3690  Value *Depth = ConstantEmitter(*this).emitAbstract(E->getArg(0),
3691  getContext().UnsignedIntTy);
3692  Function *F = CGM.getIntrinsic(Intrinsic::returnaddress);
3693  return RValue::get(Builder.CreateCall(F, Depth));
3694  }
3695  case Builtin::BI_ReturnAddress: {
3696  Function *F = CGM.getIntrinsic(Intrinsic::returnaddress);
3697  return RValue::get(Builder.CreateCall(F, Builder.getInt32(0)));
3698  }
3699  case Builtin::BI__builtin_frame_address: {
3700  Value *Depth = ConstantEmitter(*this).emitAbstract(E->getArg(0),
3701  getContext().UnsignedIntTy);
3702  Function *F = CGM.getIntrinsic(Intrinsic::frameaddress, AllocaInt8PtrTy);
3703  return RValue::get(Builder.CreateCall(F, Depth));
3704  }
3705  case Builtin::BI__builtin_extract_return_addr: {
3706  Value *Address = EmitScalarExpr(E->getArg(0));
3707  Value *Result = getTargetHooks().decodeReturnAddress(*this, Address);
3708  return RValue::get(Result);
3709  }
3710  case Builtin::BI__builtin_frob_return_addr: {
3711  Value *Address = EmitScalarExpr(E->getArg(0));
3712  Value *Result = getTargetHooks().encodeReturnAddress(*this, Address);
3713  return RValue::get(Result);
3714  }
3715  case Builtin::BI__builtin_dwarf_sp_column: {
3716  llvm::IntegerType *Ty
3717  = cast<llvm::IntegerType>(ConvertType(E->getType()));
3718  int Column = getTargetHooks().getDwarfEHStackPointer(CGM);
3719  if (Column == -1) {
3720  CGM.ErrorUnsupported(E, "__builtin_dwarf_sp_column");
3721  return RValue::get(llvm::UndefValue::get(Ty));
3722  }
3723  return RValue::get(llvm::ConstantInt::get(Ty, Column, true));
3724  }
3725  case Builtin::BI__builtin_init_dwarf_reg_size_table: {
3726  Value *Address = EmitScalarExpr(E->getArg(0));
3727  if (getTargetHooks().initDwarfEHRegSizeTable(*this, Address))
3728  CGM.ErrorUnsupported(E, "__builtin_init_dwarf_reg_size_table");
3729  return RValue::get(llvm::UndefValue::get(ConvertType(E->getType())));
3730  }
3731  case Builtin::BI__builtin_eh_return: {
3732  Value *Int = EmitScalarExpr(E->getArg(0));
3733  Value *Ptr = EmitScalarExpr(E->getArg(1));
3734 
3735  llvm::IntegerType *IntTy = cast<llvm::IntegerType>(Int->getType());
3736  assert((IntTy->getBitWidth() == 32 || IntTy->getBitWidth() == 64) &&
3737  "LLVM's __builtin_eh_return only supports 32- and 64-bit variants");
3738  Function *F =
3739  CGM.getIntrinsic(IntTy->getBitWidth() == 32 ? Intrinsic::eh_return_i32
3740  : Intrinsic::eh_return_i64);
3741  Builder.CreateCall(F, {Int, Ptr});
3742  Builder.CreateUnreachable();
3743 
3744  // We do need to preserve an insertion point.
3745  EmitBlock(createBasicBlock("builtin_eh_return.cont"));
3746 
3747  return RValue::get(nullptr);
3748  }
3749  case Builtin::BI__builtin_unwind_init: {
3750  Function *F = CGM.getIntrinsic(Intrinsic::eh_unwind_init);
3751  Builder.CreateCall(F);
3752  return RValue::get(nullptr);
3753  }
3754  case Builtin::BI__builtin_extend_pointer: {
3755  // Extends a pointer to the size of an _Unwind_Word, which is
3756  // uint64_t on all platforms. Generally this gets poked into a
3757  // register and eventually used as an address, so if the
3758  // addressing registers are wider than pointers and the platform
3759  // doesn't implicitly ignore high-order bits when doing
3760  // addressing, we need to make sure we zext / sext based on
3761  // the platform's expectations.
3762  //
3763  // See: http://gcc.gnu.org/ml/gcc-bugs/2002-02/msg00237.html
3764 
3765  // Cast the pointer to intptr_t.
3766  Value *Ptr = EmitScalarExpr(E->getArg(0));
3767  Value *Result = Builder.CreatePtrToInt(Ptr, IntPtrTy, "extend.cast");
3768 
3769  // If that's 64 bits, we're done.
3770  if (IntPtrTy->getBitWidth() == 64)
3771  return RValue::get(Result);
3772 
3773  // Otherwise, ask the codegen data what to do.
3774  if (getTargetHooks().extendPointerWithSExt())
3775  return RValue::get(Builder.CreateSExt(Result, Int64Ty, "extend.sext"));
3776  else
3777  return RValue::get(Builder.CreateZExt(Result, Int64Ty, "extend.zext"));
3778  }
3779  case Builtin::BI__builtin_setjmp: {
3780  // Buffer is a void**.
3781  Address Buf = EmitPointerWithAlignment(E->getArg(0));
3782 
3783  // Store the frame pointer to the setjmp buffer.
3784  Value *FrameAddr = Builder.CreateCall(
3785  CGM.getIntrinsic(Intrinsic::frameaddress, AllocaInt8PtrTy),
3786  ConstantInt::get(Int32Ty, 0));
3787  Builder.CreateStore(FrameAddr, Buf);
3788 
3789  // Store the stack pointer to the setjmp buffer.
3790  Value *StackAddr =
3791  Builder.CreateCall(CGM.getIntrinsic(Intrinsic::stacksave));
3792  Address StackSaveSlot = Builder.CreateConstInBoundsGEP(Buf, 2);
3793  Builder.CreateStore(StackAddr, StackSaveSlot);
3794 
3795  // Call LLVM's EH setjmp, which is lightweight.
3796  Function *F = CGM.getIntrinsic(Intrinsic::eh_sjlj_setjmp);
3797  Buf = Builder.CreateElementBitCast(Buf, Int8Ty);
3798  return RValue::get(Builder.CreateCall(F, Buf.getPointer()));
3799  }
3800  case Builtin::BI__builtin_longjmp: {
3801  Value *Buf = EmitScalarExpr(E->getArg(0));
3802  Buf = Builder.CreateBitCast(Buf, Int8PtrTy);
3803 
3804  // Call LLVM's EH longjmp, which is lightweight.
3805  Builder.CreateCall(CGM.getIntrinsic(Intrinsic::eh_sjlj_longjmp), Buf);
3806 
3807  // longjmp doesn't return; mark this as unreachable.
3808  Builder.CreateUnreachable();
3809 
3810  // We do need to preserve an insertion point.
3811  EmitBlock(createBasicBlock("longjmp.cont"));
3812 
3813  return RValue::get(nullptr);
3814  }
3815  case Builtin::BI__builtin_launder: {
3816  const Expr *Arg = E->getArg(0);
3817  QualType ArgTy = Arg->getType()->getPointeeType();
3818  Value *Ptr = EmitScalarExpr(Arg);
3819  if (TypeRequiresBuiltinLaunder(CGM, ArgTy))
3820  Ptr = Builder.CreateLaunderInvariantGroup(Ptr);
3821 
3822  return RValue::get(Ptr);
3823  }
3824  case Builtin::BI__sync_fetch_and_add:
3825  case Builtin::BI__sync_fetch_and_sub:
3826  case Builtin::BI__sync_fetch_and_or:
3827  case Builtin::BI__sync_fetch_and_and:
3828  case Builtin::BI__sync_fetch_and_xor:
3829  case Builtin::BI__sync_fetch_and_nand:
3830  case Builtin::BI__sync_add_and_fetch:
3831  case Builtin::BI__sync_sub_and_fetch:
3832  case Builtin::BI__sync_and_and_fetch:
3833  case Builtin::BI__sync_or_and_fetch:
3834  case Builtin::BI__sync_xor_and_fetch:
3835  case Builtin::BI__sync_nand_and_fetch:
3836  case Builtin::BI__sync_val_compare_and_swap:
3837  case Builtin::BI__sync_bool_compare_and_swap:
3838  case Builtin::BI__sync_lock_test_and_set:
3839  case Builtin::BI__sync_lock_release:
3840  case Builtin::BI__sync_swap:
3841  llvm_unreachable("Shouldn't make it through sema");
3842  case Builtin::BI__sync_fetch_and_add_1:
3843  case Builtin::BI__sync_fetch_and_add_2:
3844  case Builtin::BI__sync_fetch_and_add_4:
3845  case Builtin::BI__sync_fetch_and_add_8:
3846  case Builtin::BI__sync_fetch_and_add_16:
3847  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Add, E);
3848  case Builtin::BI__sync_fetch_and_sub_1:
3849  case Builtin::BI__sync_fetch_and_sub_2:
3850  case Builtin::BI__sync_fetch_and_sub_4:
3851  case Builtin::BI__sync_fetch_and_sub_8:
3852  case Builtin::BI__sync_fetch_and_sub_16:
3853  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Sub, E);
3854  case Builtin::BI__sync_fetch_and_or_1:
3855  case Builtin::BI__sync_fetch_and_or_2:
3856  case Builtin::BI__sync_fetch_and_or_4:
3857  case Builtin::BI__sync_fetch_and_or_8:
3858  case Builtin::BI__sync_fetch_and_or_16:
3859  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Or, E);
3860  case Builtin::BI__sync_fetch_and_and_1:
3861  case Builtin::BI__sync_fetch_and_and_2:
3862  case Builtin::BI__sync_fetch_and_and_4:
3863  case Builtin::BI__sync_fetch_and_and_8:
3864  case Builtin::BI__sync_fetch_and_and_16:
3865  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::And, E);
3866  case Builtin::BI__sync_fetch_and_xor_1:
3867  case Builtin::BI__sync_fetch_and_xor_2:
3868  case Builtin::BI__sync_fetch_and_xor_4:
3869  case Builtin::BI__sync_fetch_and_xor_8:
3870  case Builtin::BI__sync_fetch_and_xor_16:
3871  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Xor, E);
3872  case Builtin::BI__sync_fetch_and_nand_1:
3873  case Builtin::BI__sync_fetch_and_nand_2:
3874  case Builtin::BI__sync_fetch_and_nand_4:
3875  case Builtin::BI__sync_fetch_and_nand_8:
3876  case Builtin::BI__sync_fetch_and_nand_16:
3877  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Nand, E);
3878 
3879  // Clang extensions: not overloaded yet.
3880  case Builtin::BI__sync_fetch_and_min:
3881  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Min, E);
3882  case Builtin::BI__sync_fetch_and_max:
3883  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Max, E);
3884  case Builtin::BI__sync_fetch_and_umin:
3885  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::UMin, E);
3886  case Builtin::BI__sync_fetch_and_umax:
3887  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::UMax, E);
3888 
3889  case Builtin::BI__sync_add_and_fetch_1:
3890  case Builtin::BI__sync_add_and_fetch_2:
3891  case Builtin::BI__sync_add_and_fetch_4:
3892  case Builtin::BI__sync_add_and_fetch_8:
3893  case Builtin::BI__sync_add_and_fetch_16:
3896  case Builtin::BI__sync_sub_and_fetch_1:
3897  case Builtin::BI__sync_sub_and_fetch_2:
3898  case Builtin::BI__sync_sub_and_fetch_4:
3899  case Builtin::BI__sync_sub_and_fetch_8:
3900  case Builtin::BI__sync_sub_and_fetch_16:
3903  case Builtin::BI__sync_and_and_fetch_1:
3904  case Builtin::BI__sync_and_and_fetch_2:
3905  case Builtin::BI__sync_and_and_fetch_4:
3906  case Builtin::BI__sync_and_and_fetch_8:
3907  case Builtin::BI__sync_and_and_fetch_16:
3910  case Builtin::BI__sync_or_and_fetch_1:
3911  case Builtin::BI__sync_or_and_fetch_2:
3912  case Builtin::BI__sync_or_and_fetch_4:
3913  case Builtin::BI__sync_or_and_fetch_8:
3914  case Builtin::BI__sync_or_and_fetch_16:
3915  return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Or, E,
3916  llvm::Instruction::Or);
3917  case Builtin::BI__sync_xor_and_fetch_1:
3918  case Builtin::BI__sync_xor_and_fetch_2:
3919  case Builtin::BI__sync_xor_and_fetch_4:
3920  case Builtin::BI__sync_xor_and_fetch_8:
3921  case Builtin::BI__sync_xor_and_fetch_16:
3922  return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Xor, E,
3923  llvm::Instruction::Xor);
3924  case Builtin::BI__sync_nand_and_fetch_1:
3925  case Builtin::BI__sync_nand_and_fetch_2:
3926  case Builtin::BI__sync_nand_and_fetch_4:
3927  case Builtin::BI__sync_nand_and_fetch_8:
3928  case Builtin::BI__sync_nand_and_fetch_16:
3929  return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Nand, E,
3930  llvm::Instruction::And, true);
3931 
3932  case Builtin::BI__sync_val_compare_and_swap_1:
3933  case Builtin::BI__sync_val_compare_and_swap_2:
3934  case Builtin::BI__sync_val_compare_and_swap_4:
3935  case Builtin::BI__sync_val_compare_and_swap_8:
3936  case Builtin::BI__sync_val_compare_and_swap_16:
3937  return RValue::get(MakeAtomicCmpXchgValue(*this, E, false));
3938 
3939  case Builtin::BI__sync_bool_compare_and_swap_1:
3940  case Builtin::BI__sync_bool_compare_and_swap_2:
3941  case Builtin::BI__sync_bool_compare_and_swap_4:
3942  case Builtin::BI__sync_bool_compare_and_swap_8:
3943  case Builtin::BI__sync_bool_compare_and_swap_16:
3944  return RValue::get(MakeAtomicCmpXchgValue(*this, E, true));
3945 
3946  case Builtin::BI__sync_swap_1:
3947  case Builtin::BI__sync_swap_2:
3948  case Builtin::BI__sync_swap_4:
3949  case Builtin::BI__sync_swap_8:
3950  case Builtin::BI__sync_swap_16:
3951  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Xchg, E);
3952 
3953  case Builtin::BI__sync_lock_test_and_set_1:
3954  case Builtin::BI__sync_lock_test_and_set_2:
3955  case Builtin::BI__sync_lock_test_and_set_4:
3956  case Builtin::BI__sync_lock_test_and_set_8:
3957  case Builtin::BI__sync_lock_test_and_set_16:
3958  return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Xchg, E);
3959 
3960  case Builtin::BI__sync_lock_release_1:
3961  case Builtin::BI__sync_lock_release_2:
3962  case Builtin::BI__sync_lock_release_4:
3963  case Builtin::BI__sync_lock_release_8:
3964  case Builtin::BI__sync_lock_release_16: {
3965  Value *Ptr = EmitScalarExpr(E->getArg(0));
3966  QualType ElTy = E->getArg(0)->getType()->getPointeeType();
3967  CharUnits StoreSize = getContext().getTypeSizeInChars(ElTy);
3968  llvm::Type *ITy = llvm::IntegerType::get(getLLVMContext(),
3969  StoreSize.getQuantity() * 8);
3970  Ptr = Builder.CreateBitCast(Ptr, ITy->getPointerTo());
3971  llvm::StoreInst *Store =
3972  Builder.CreateAlignedStore(llvm::Constant::getNullValue(ITy), Ptr,
3973  StoreSize);
3974  Store->setAtomic(llvm::AtomicOrdering::Release);
3975  return RValue::get(nullptr);
3976  }
3977 
3978  case Builtin::BI__sync_synchronize: {
3979  // We assume this is supposed to correspond to a C++0x-style
3980  // sequentially-consistent fence (i.e. this is only usable for
3981  // synchronization, not device I/O or anything like that). This intrinsic
3982  // is really badly designed in the sense that in theory, there isn't
3983  // any way to safely use it... but in practice, it mostly works
3984  // to use it with non-atomic loads and stores to get acquire/release
3985  // semantics.
3986  Builder.CreateFence(llvm::AtomicOrdering::SequentiallyConsistent);
3987  return RValue::get(nullptr);
3988  }
3989 
3990  case Builtin::BI__builtin_nontemporal_load:
3991  return RValue::get(EmitNontemporalLoad(*this, E));
3992  case Builtin::BI__builtin_nontemporal_store:
3993  return RValue::get(EmitNontemporalStore(*this, E));
3994  case Builtin::BI__c11_atomic_is_lock_free:
3995  case Builtin::BI__atomic_is_lock_free: {
3996  // Call "bool __atomic_is_lock_free(size_t size, void *ptr)". For the
3997  // __c11 builtin, ptr is 0 (indicating a properly-aligned object), since
3998  // _Atomic(T) is always properly-aligned.
3999  const char *LibCallName = "__atomic_is_lock_free";
4000  CallArgList Args;
4001  Args.add(RValue::get(EmitScalarExpr(E->getArg(0))),
4002  getContext().getSizeType());
4003  if (BuiltinID == Builtin::BI__atomic_is_lock_free)
4004  Args.add(RValue::get(EmitScalarExpr(E->getArg(1))),
4005  getContext().VoidPtrTy);
4006  else
4007  Args.add(RValue::get(llvm::Constant::getNullValue(VoidPtrTy)),
4008  getContext().VoidPtrTy);
4009  const CGFunctionInfo &FuncInfo =
4010  CGM.getTypes().arrangeBuiltinFunctionCall(E->getType(), Args);
4011  llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FuncInfo);
4012  llvm::FunctionCallee Func = CGM.CreateRuntimeFunction(FTy, LibCallName);
4013  return EmitCall(FuncInfo, CGCallee::forDirect(Func),
4014  ReturnValueSlot(), Args);
4015  }
4016 
4017  case Builtin::BI__atomic_test_and_set: {
4018  // Look at the argument type to determine whether this is a volatile
4019  // operation. The parameter type is always volatile.
4020  QualType PtrTy = E->getArg(0)->IgnoreImpCasts()->getType();
4021  bool Volatile =
4022  PtrTy->castAs<PointerType>()->getPointeeType().isVolatileQualified();
4023 
4024  Value *Ptr = EmitScalarExpr(E->getArg(0));
4025  unsigned AddrSpace = Ptr->getType()->getPointerAddressSpace();
4026  Ptr = Builder.CreateBitCast(Ptr, Int8Ty->getPointerTo(AddrSpace));
4027  Value *NewVal = Builder.getInt8(1);
4028  Value *Order = EmitScalarExpr(E->getArg(1));
4029  if (isa<llvm::ConstantInt>(Order)) {
4030  int ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
4031  AtomicRMWInst *Result = nullptr;
4032  switch (ord) {
4033  case 0: // memory_order_relaxed
4034  default: // invalid order
4035  Result = Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg, Ptr, NewVal,
4036  llvm::AtomicOrdering::Monotonic);
4037  break;
4038  case 1: // memory_order_consume
4039  case 2: // memory_order_acquire
4040  Result = Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg, Ptr, NewVal,
4041  llvm::AtomicOrdering::Acquire);
4042  break;
4043  case 3: // memory_order_release
4044  Result = Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg, Ptr, NewVal,
4045  llvm::AtomicOrdering::Release);
4046  break;
4047  case 4: // memory_order_acq_rel
4048 
4049  Result = Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg, Ptr, NewVal,
4050  llvm::AtomicOrdering::AcquireRelease);
4051  break;
4052  case 5: // memory_order_seq_cst
4053  Result = Builder.CreateAtomicRMW(
4054  llvm::AtomicRMWInst::Xchg, Ptr, NewVal,
4055  llvm::AtomicOrdering::SequentiallyConsistent);
4056  break;
4057  }
4058  Result->setVolatile(Volatile);
4059  return RValue::get(Builder.CreateIsNotNull(Result, "tobool"));
4060  }
4061 
4062  llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
4063 
4064  llvm::BasicBlock *BBs[5] = {
4065  createBasicBlock("monotonic", CurFn),
4066  createBasicBlock("acquire", CurFn),
4067  createBasicBlock("release", CurFn),
4068  createBasicBlock("acqrel", CurFn),
4069  createBasicBlock("seqcst", CurFn)
4070  };
4071  llvm::AtomicOrdering Orders[5] = {
4072  llvm::AtomicOrdering::Monotonic, llvm::AtomicOrdering::Acquire,
4073  llvm::AtomicOrdering::Release, llvm::AtomicOrdering::AcquireRelease,
4074  llvm::AtomicOrdering::SequentiallyConsistent};
4075 
4076  Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
4077  llvm::SwitchInst *SI = Builder.CreateSwitch(Order, BBs[0]);
4078 
4079  Builder.SetInsertPoint(ContBB);
4080  PHINode *Result = Builder.CreatePHI(Int8Ty, 5, "was_set");
4081 
4082  for (unsigned i = 0; i < 5; ++i) {
4083  Builder.SetInsertPoint(BBs[i]);
4084  AtomicRMWInst *RMW = Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg,
4085  Ptr, NewVal, Orders[i]);
4086  RMW->setVolatile(Volatile);
4087  Result->addIncoming(RMW, BBs[i]);
4088  Builder.CreateBr(ContBB);
4089  }
4090 
4091  SI->addCase(Builder.getInt32(0), BBs[0]);
4092  SI->addCase(Builder.getInt32(1), BBs[1]);
4093  SI->addCase(Builder.getInt32(2), BBs[1]);
4094  SI->addCase(Builder.getInt32(3), BBs[2]);
4095  SI->addCase(Builder.getInt32(4), BBs[3]);
4096  SI->addCase(Builder.getInt32(5), BBs[4]);
4097 
4098  Builder.SetInsertPoint(ContBB);
4099  return RValue::get(Builder.CreateIsNotNull(Result, "tobool"));
4100  }
4101 
4102  case Builtin::BI__atomic_clear: {
4103  QualType PtrTy = E->getArg(0)->IgnoreImpCasts()->getType();
4104  bool Volatile =
4105  PtrTy->castAs<PointerType>()->getPointeeType().isVolatileQualified();
4106 
4107  Address Ptr = EmitPointerWithAlignment(E->getArg(0));
4108  Ptr = Builder.CreateElementBitCast(Ptr, Int8Ty);
4109  Value *NewVal = Builder.getInt8(0);
4110  Value *Order = EmitScalarExpr(E->getArg(1));
4111  if (isa<llvm::ConstantInt>(Order)) {
4112  int ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
4113  StoreInst *Store = Builder.CreateStore(NewVal, Ptr, Volatile);
4114  switch (ord) {
4115  case 0: // memory_order_relaxed
4116  default: // invalid order
4117  Store->setOrdering(llvm::AtomicOrdering::Monotonic);
4118  break;
4119  case 3: // memory_order_release
4120  Store->setOrdering(llvm::AtomicOrdering::Release);
4121  break;
4122  case 5: // memory_order_seq_cst
4123  Store->setOrdering(llvm::AtomicOrdering::SequentiallyConsistent);
4124  break;
4125  }
4126  return RValue::get(nullptr);
4127  }
4128 
4129  llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
4130 
4131  llvm::BasicBlock *BBs[3] = {
4132  createBasicBlock("monotonic", CurFn),
4133  createBasicBlock("release", CurFn),
4134  createBasicBlock("seqcst", CurFn)
4135  };
4136  llvm::AtomicOrdering Orders[3] = {
4137  llvm::AtomicOrdering::Monotonic, llvm::AtomicOrdering::Release,
4138  llvm::AtomicOrdering::SequentiallyConsistent};
4139 
4140  Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
4141  llvm::SwitchInst *SI = Builder.CreateSwitch(Order, BBs[0]);
4142 
4143  for (unsigned i = 0; i < 3; ++i) {
4144  Builder.SetInsertPoint(BBs[i]);
4145  StoreInst *Store = Builder.CreateStore(NewVal, Ptr, Volatile);
4146  Store->setOrdering(Orders[i]);
4147  Builder.CreateBr(ContBB);
4148  }
4149 
4150  SI->addCase(Builder.getInt32(0), BBs[0]);
4151  SI->addCase(Builder.getInt32(3), BBs[1]);
4152  SI->addCase(Builder.getInt32(5), BBs[2]);
4153 
4154  Builder.SetInsertPoint(ContBB);
4155  return RValue::get(nullptr);
4156  }
4157 
4158  case Builtin::BI__atomic_thread_fence:
4159  case Builtin::BI__atomic_signal_fence:
4160  case Builtin::BI__c11_atomic_thread_fence:
4161  case Builtin::BI__c11_atomic_signal_fence: {
4162  llvm::SyncScope::ID SSID;
4163  if (BuiltinID == Builtin::BI__atomic_signal_fence ||
4164  BuiltinID == Builtin::BI__c11_atomic_signal_fence)
4165  SSID = llvm::SyncScope::SingleThread;
4166  else
4167  SSID = llvm::SyncScope::System;
4168  Value *Order = EmitScalarExpr(E->getArg(0));
4169  if (isa<llvm::ConstantInt>(Order)) {
4170  int ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
4171  switch (ord) {
4172  case 0: // memory_order_relaxed
4173  default: // invalid order
4174  break;
4175  case 1: // memory_order_consume
4176  case 2: // memory_order_acquire
4177  Builder.CreateFence(llvm::AtomicOrdering::Acquire, SSID);
4178  break;
4179  case 3: // memory_order_release
4180  Builder.CreateFence(llvm::AtomicOrdering::Release, SSID);
4181  break;
4182  case 4: // memory_order_acq_rel
4183  Builder.CreateFence(llvm::AtomicOrdering::AcquireRelease, SSID);
4184  break;
4185  case 5: // memory_order_seq_cst
4186  Builder.CreateFence(llvm::AtomicOrdering::SequentiallyConsistent, SSID);
4187  break;
4188  }
4189  return RValue::get(nullptr);
4190  }
4191 
4192  llvm::BasicBlock *AcquireBB, *ReleaseBB, *AcqRelBB, *SeqCstBB;
4193  AcquireBB = createBasicBlock("acquire", CurFn);
4194  ReleaseBB = createBasicBlock("release", CurFn);
4195  AcqRelBB = createBasicBlock("acqrel", CurFn);
4196  SeqCstBB = createBasicBlock("seqcst", CurFn);
4197  llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
4198 
4199  Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
4200  llvm::SwitchInst *SI = Builder.CreateSwitch(Order, ContBB);
4201 
4202  Builder.SetInsertPoint(AcquireBB);
4203  Builder.CreateFence(llvm::AtomicOrdering::Acquire, SSID);
4204  Builder.CreateBr(ContBB);
4205  SI->addCase(Builder.getInt32(1), AcquireBB);
4206  SI->addCase(Builder.getInt32(2), AcquireBB);
4207 
4208  Builder.SetInsertPoint(ReleaseBB);
4209  Builder.CreateFence(llvm::AtomicOrdering::Release, SSID);
4210  Builder.CreateBr(ContBB);
4211  SI->addCase(Builder.getInt32(3), ReleaseBB);
4212 
4213  Builder.SetInsertPoint(AcqRelBB);
4214  Builder.CreateFence(llvm::AtomicOrdering::AcquireRelease, SSID);
4215  Builder.CreateBr(ContBB);
4216  SI->addCase(Builder.getInt32(4), AcqRelBB);
4217 
4218  Builder.SetInsertPoint(SeqCstBB);
4219  Builder.CreateFence(llvm::AtomicOrdering::SequentiallyConsistent, SSID);
4220  Builder.CreateBr(ContBB);
4221  SI->addCase(Builder.getInt32(5), SeqCstBB);
4222 
4223  Builder.SetInsertPoint(ContBB);
4224  return RValue::get(nullptr);
4225  }
4226 
4227  case Builtin::BI__builtin_signbit:
4228  case Builtin::BI__builtin_signbitf:
4229  case Builtin::BI__builtin_signbitl: {
4230  return RValue::get(
4231  Builder.CreateZExt(EmitSignBit(*this, EmitScalarExpr(E->getArg(0))),
4232  ConvertType(E->getType())));
4233  }
4234  case Builtin::BI__warn_memset_zero_len:
4235  return RValue::getIgnored();
4236  case Builtin::BI__annotation: {
4237  // Re-encode each wide string to UTF8 and make an MDString.
4239  for (const Expr *Arg : E->arguments()) {
4240  const auto *Str = cast<StringLiteral>(Arg->IgnoreParenCasts());
4241  assert(Str->getCharByteWidth() == 2);
4242  StringRef WideBytes = Str->getBytes();
4243  std::string StrUtf8;
4244  if (!convertUTF16ToUTF8String(
4245  makeArrayRef(WideBytes.data(), WideBytes.size()), StrUtf8)) {
4246  CGM.ErrorUnsupported(E, "non-UTF16 __annotation argument");
4247  continue;
4248  }
4249  Strings.push_back(llvm::MDString::get(getLLVMContext(), StrUtf8));
4250  }
4251 
4252  // Build and MDTuple of MDStrings and emit the intrinsic call.
4253  llvm::Function *F =
4254  CGM.getIntrinsic(llvm::Intrinsic::codeview_annotation, {});
4255  MDTuple *StrTuple = MDTuple::get(getLLVMContext(), Strings);
4256  Builder.CreateCall(F, MetadataAsValue::get(getLLVMContext(), StrTuple));
4257  return RValue::getIgnored();
4258  }
4259  case Builtin::BI__builtin_annotation: {
4260  llvm::Value *AnnVal = EmitScalarExpr(E->getArg(0));
4261  llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::annotation,
4262  AnnVal->getType());
4263 
4264  // Get the annotation string, go through casts. Sema requires this to be a
4265  // non-wide string literal, potentially casted, so the cast<> is safe.
4266  const Expr *AnnotationStrExpr = E->getArg(1)->IgnoreParenCasts();
4267  StringRef Str = cast<StringLiteral>(AnnotationStrExpr)->getString();
4268  return RValue::get(
4269  EmitAnnotationCall(F, AnnVal, Str, E->getExprLoc(), nullptr));
4270  }
4271  case Builtin::BI__builtin_addcb:
4272  case Builtin::BI__builtin_addcs:
4273  case Builtin::BI__builtin_addc:
4274  case Builtin::BI__builtin_addcl:
4275  case Builtin::BI__builtin_addcll:
4276  case Builtin::BI__builtin_subcb:
4277  case Builtin::BI__builtin_subcs:
4278  case Builtin::BI__builtin_subc:
4279  case Builtin::BI__builtin_subcl:
4280  case Builtin::BI__builtin_subcll: {
4281 
4282  // We translate all of these builtins from expressions of the form:
4283  // int x = ..., y = ..., carryin = ..., carryout, result;
4284  // result = __builtin_addc(x, y, carryin, &carryout);
4285  //
4286  // to LLVM IR of the form:
4287  //
4288  // %tmp1 = call {i32, i1} @llvm.uadd.with.overflow.i32(i32 %x, i32 %y)
4289  // %tmpsum1 = extractvalue {i32, i1} %tmp1, 0
4290  // %carry1 = extractvalue {i32, i1} %tmp1, 1
4291  // %tmp2 = call {i32, i1} @llvm.uadd.with.overflow.i32(i32 %tmpsum1,
4292  // i32 %carryin)
4293  // %result = extractvalue {i32, i1} %tmp2, 0
4294  // %carry2 = extractvalue {i32, i1} %tmp2, 1
4295  // %tmp3 = or i1 %carry1, %carry2
4296  // %tmp4 = zext i1 %tmp3 to i32
4297  // store i32 %tmp4, i32* %carryout
4298 
4299  // Scalarize our inputs.
4300  llvm::Value *X = EmitScalarExpr(E->getArg(0));
4301  llvm::Value *Y = EmitScalarExpr(E->getArg(1));
4302  llvm::Value *Carryin = EmitScalarExpr(E->getArg(2));
4303  Address CarryOutPtr = EmitPointerWithAlignment(E->getArg(3));
4304 
4305  // Decide if we are lowering to a uadd.with.overflow or usub.with.overflow.
4306  llvm::Intrinsic::ID IntrinsicId;
4307  switch (BuiltinID) {
4308  default: llvm_unreachable("Unknown multiprecision builtin id.");
4309  case Builtin::BI__builtin_addcb:
4310  case Builtin::BI__builtin_addcs:
4311  case Builtin::BI__builtin_addc:
4312  case Builtin::BI__builtin_addcl:
4313  case Builtin::BI__builtin_addcll:
4314  IntrinsicId = llvm::Intrinsic::uadd_with_overflow;
4315  break;
4316  case Builtin::BI__builtin_subcb:
4317  case Builtin::BI__builtin_subcs:
4318  case Builtin::BI__builtin_subc:
4319  case Builtin::BI__builtin_subcl:
4320  case Builtin::BI__builtin_subcll:
4321  IntrinsicId = llvm::Intrinsic::usub_with_overflow;
4322  break;
4323  }
4324 
4325  // Construct our resulting LLVM IR expression.
4326  llvm::Value *Carry1;
4327  llvm::Value *Sum1 = EmitOverflowIntrinsic(*this, IntrinsicId,
4328  X, Y, Carry1);
4329  llvm::Value *Carry2;
4330  llvm::Value *Sum2 = EmitOverflowIntrinsic(*this, IntrinsicId,
4331  Sum1, Carryin, Carry2);
4332  llvm::Value *CarryOut = Builder.CreateZExt(Builder.CreateOr(Carry1, Carry2),
4333  X->getType());
4334  Builder.CreateStore(CarryOut, CarryOutPtr);
4335  return RValue::get(Sum2);
4336  }
4337 
4338  case Builtin::BI__builtin_add_overflow:
4339  case Builtin::BI__builtin_sub_overflow:
4340  case Builtin::BI__builtin_mul_overflow: {
4341  const clang::Expr *LeftArg = E->getArg(0);
4342  const clang::Expr *RightArg = E->getArg(1);
4343  const clang::Expr *ResultArg = E->getArg(2);
4344 
4345  clang::QualType ResultQTy =
4346  ResultArg->getType()->castAs<PointerType>()->getPointeeType();
4347 
4348  WidthAndSignedness LeftInfo =
4349  getIntegerWidthAndSignedness(CGM.getContext(), LeftArg->getType());
4350  WidthAndSignedness RightInfo =
4351  getIntegerWidthAndSignedness(CGM.getContext(), RightArg->getType());
4352  WidthAndSignedness ResultInfo =
4353  getIntegerWidthAndSignedness(CGM.getContext(), ResultQTy);
4354 
4355  // Handle mixed-sign multiplication as a special case, because adding
4356  // runtime or backend support for our generic irgen would be too expensive.
4357  if (isSpecialMixedSignMultiply(BuiltinID, LeftInfo, RightInfo, ResultInfo))
4358  return EmitCheckedMixedSignMultiply(*this, LeftArg, LeftInfo, RightArg,
4359  RightInfo, ResultArg, ResultQTy,
4360  ResultInfo);
4361 
4362  if (isSpecialUnsignedMultiplySignedResult(BuiltinID, LeftInfo, RightInfo,
4363  ResultInfo))
4365  *this, LeftArg, LeftInfo, RightArg, RightInfo, ResultArg, ResultQTy,
4366  ResultInfo);
4367 
4368  WidthAndSignedness EncompassingInfo =
4369  EncompassingIntegerType({LeftInfo, RightInfo, ResultInfo});
4370 
4371  llvm::Type *EncompassingLLVMTy =
4372  llvm::IntegerType::get(CGM.getLLVMContext(), EncompassingInfo.Width);
4373 
4374  llvm::Type *ResultLLVMTy = CGM.getTypes().ConvertType(ResultQTy);
4375 
4376  llvm::Intrinsic::ID IntrinsicId;
4377  switch (BuiltinID) {
4378  default:
4379  llvm_unreachable("Unknown overflow builtin id.");
4380  case Builtin::BI__builtin_add_overflow:
4381  IntrinsicId = EncompassingInfo.Signed
4382  ? llvm::Intrinsic::sadd_with_overflow
4383  : llvm::Intrinsic::uadd_with_overflow;
4384  break;
4385  case Builtin::BI__builtin_sub_overflow:
4386  IntrinsicId = EncompassingInfo.Signed
4387  ? llvm::Intrinsic::ssub_with_overflow
4388  : llvm::Intrinsic::usub_with_overflow;
4389  break;
4390  case Builtin::BI__builtin_mul_overflow:
4391  IntrinsicId = EncompassingInfo.Signed
4392  ? llvm::Intrinsic::smul_with_overflow
4393  : llvm::Intrinsic::umul_with_overflow;
4394  break;
4395  }
4396 
4397  llvm::Value *Left = EmitScalarExpr(LeftArg);
4398  llvm::Value *Right = EmitScalarExpr(RightArg);
4399  Address ResultPtr = EmitPointerWithAlignment(ResultArg);
4400 
4401  // Extend each operand to the encompassing type.
4402  Left = Builder.CreateIntCast(Left, EncompassingLLVMTy, LeftInfo.Signed);
4403  Right = Builder.CreateIntCast(Right, EncompassingLLVMTy, RightInfo.Signed);
4404 
4405  // Perform the operation on the extended values.
4406  llvm::Value *Overflow, *Result;
4407  Result = EmitOverflowIntrinsic(*this, IntrinsicId, Left, Right, Overflow);
4408 
4409  if (EncompassingInfo.Width > ResultInfo.Width) {
4410  // The encompassing type is wider than the result type, so we need to
4411  // truncate it.
4412  llvm::Value *ResultTrunc = Builder.CreateTrunc(Result, ResultLLVMTy);
4413 
4414  // To see if the truncation caused an overflow, we will extend
4415  // the result and then compare it to the original result.
4416  llvm::Value *ResultTruncExt = Builder.CreateIntCast(
4417  ResultTrunc, EncompassingLLVMTy, ResultInfo.Signed);
4418  llvm::Value *TruncationOverflow =
4419  Builder.CreateICmpNE(Result, ResultTruncExt);
4420 
4421  Overflow = Builder.CreateOr(Overflow, TruncationOverflow);
4422  Result = ResultTrunc;
4423  }
4424 
4425  // Finally, store the result using the pointer.
4426  bool isVolatile =
4427  ResultArg->getType()->getPointeeType().isVolatileQualified();
4428  Builder.CreateStore(EmitToMemory(Result, ResultQTy), ResultPtr, isVolatile);
4429 
4430  return RValue::get(Overflow);
4431  }
4432 
4433  case Builtin::BI__builtin_uadd_overflow:
4434  case Builtin::BI__builtin_uaddl_overflow:
4435  case Builtin::BI__builtin_uaddll_overflow:
4436  case Builtin::BI__builtin_usub_overflow:
4437  case Builtin::BI__builtin_usubl_overflow:
4438  case Builtin::BI__builtin_usubll_overflow:
4439  case Builtin::BI__builtin_umul_overflow:
4440  case Builtin::BI__builtin_umull_overflow:
4441  case Builtin::BI__builtin_umulll_overflow:
4442  case Builtin::BI__builtin_sadd_overflow:
4443  case Builtin::BI__builtin_saddl_overflow:
4444  case Builtin::BI__builtin_saddll_overflow:
4445  case Builtin::BI__builtin_ssub_overflow:
4446  case Builtin::BI__builtin_ssubl_overflow:
4447  case Builtin::BI__builtin_ssubll_overflow:
4448  case Builtin::BI__builtin_smul_overflow:
4449  case Builtin::BI__builtin_smull_overflow:
4450  case Builtin::BI__builtin_smulll_overflow: {
4451 
4452  // We translate all of these builtins directly to the relevant llvm IR node.
4453 
4454  // Scalarize our inputs.
4455  llvm::Value *X = EmitScalarExpr(E->getArg(0));
4456  llvm::Value *Y = EmitScalarExpr(E->getArg(1));
4457  Address SumOutPtr = EmitPointerWithAlignment(E->getArg(2));
4458 
4459  // Decide which of the overflow intrinsics we are lowering to:
4460  llvm::Intrinsic::ID IntrinsicId;
4461  switch (BuiltinID) {
4462  default: llvm_unreachable("Unknown overflow builtin id.");
4463  case Builtin::BI__builtin_uadd_overflow:
4464  case Builtin::BI__builtin_uaddl_overflow:
4465  case Builtin::BI__builtin_uaddll_overflow:
4466  IntrinsicId = llvm::Intrinsic::uadd_with_overflow;
4467  break;
4468  case Builtin::BI__builtin_usub_overflow:
4469  case Builtin::BI__builtin_usubl_overflow:
4470  case Builtin::BI__builtin_usubll_overflow:
4471  IntrinsicId = llvm::Intrinsic::usub_with_overflow;
4472  break;
4473  case Builtin::BI__builtin_umul_overflow:
4474  case Builtin::BI__builtin_umull_overflow:
4475  case Builtin::BI__builtin_umulll_overflow:
4476  IntrinsicId = llvm::Intrinsic::umul_with_overflow;
4477  break;
4478  case Builtin::BI__builtin_sadd_overflow:
4479  case Builtin::BI__builtin_saddl_overflow:
4480  case Builtin::BI__builtin_saddll_overflow:
4481  IntrinsicId = llvm::Intrinsic::sadd_with_overflow;
4482  break;
4483  case Builtin::BI__builtin_ssub_overflow:
4484  case Builtin::BI__builtin_ssubl_overflow:
4485  case Builtin::BI__builtin_ssubll_overflow:
4486  IntrinsicId = llvm::Intrinsic::ssub_with_overflow;
4487  break;
4488  case Builtin::BI__builtin_smul_overflow:
4489  case Builtin::BI__builtin_smull_overflow:
4490  case Builtin::BI__builtin_smulll_overflow:
4491  IntrinsicId = llvm::Intrinsic::smul_with_overflow;
4492  break;
4493  }
4494 
4495 
4496  llvm::Value *Carry;
4497  llvm::Value *Sum = EmitOverflowIntrinsic(*this, IntrinsicId, X, Y, Carry);
4498  Builder.CreateStore(Sum, SumOutPtr);
4499 
4500  return RValue::get(Carry);
4501  }
4502  case Builtin::BIaddressof:
4503  case Builtin::BI__addressof:
4504  case Builtin::BI__builtin_addressof:
4505  return RValue::get(EmitLValue(E->getArg(0)).getPointer(*this));
4506  case Builtin::BI__builtin_function_start:
4507  return RValue::get(CGM.GetFunctionStart(
4508  E->getArg(0)->getAsBuiltinConstantDeclRef(CGM.getContext())));
4509  case Builtin::BI__builtin_operator_new:
4510  return EmitBuiltinNewDeleteCall(
4511  E->getCallee()->getType()->castAs<FunctionProtoType>(), E, false);
4512  case Builtin::BI__builtin_operator_delete:
4513  EmitBuiltinNewDeleteCall(
4514  E->getCallee()->getType()->castAs<FunctionProtoType>(), E, true);
4515  return RValue::get(nullptr);
4516 
4517  case Builtin::BI__builtin_is_aligned:
4518  return EmitBuiltinIsAligned(E);
4519  case Builtin::BI__builtin_align_up:
4520  return EmitBuiltinAlignTo(E, true);
4521  case Builtin::BI__builtin_align_down:
4522  return EmitBuiltinAlignTo(E, false);
4523 
4524  case Builtin::BI__noop:
4525  // __noop always evaluates to an integer literal zero.
4526  return RValue::get(ConstantInt::get(IntTy, 0));
4527  case Builtin::BI__builtin_call_with_static_chain: {
4528  const CallExpr *Call = cast<CallExpr>(E->getArg(0));
4529  const Expr *Chain = E->getArg(1);
4530  return EmitCall(Call->getCallee()->getType(),
4531  EmitCallee(Call->getCallee()), Call, ReturnValue,
4532  EmitScalarExpr(Chain));
4533  }
4534  case Builtin::BI_InterlockedExchange8:
4535  case Builtin::BI_InterlockedExchange16:
4536  case Builtin::BI_InterlockedExchange:
4537  case Builtin::BI_InterlockedExchangePointer:
4538  return RValue::get(
4539  EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedExchange, E));
4540  case Builtin::BI_InterlockedCompareExchangePointer:
4541  case Builtin::BI_InterlockedCompareExchangePointer_nf: {
4542  llvm::Type *RTy;
4543  llvm::IntegerType *IntType =
4544  IntegerType::get(getLLVMContext(),
4545  getContext().getTypeSize(E->getType()));
4546  llvm::Type *IntPtrType = IntType->getPointerTo();
4547 
4548  llvm::Value *Destination =
4549  Builder.CreateBitCast(EmitScalarExpr(E->getArg(0)), IntPtrType);
4550 
4551  llvm::Value *Exchange = EmitScalarExpr(E->getArg(1));
4552  RTy = Exchange->getType();
4553  Exchange = Builder.CreatePtrToInt(Exchange, IntType);
4554 
4555  llvm::Value *Comparand =
4556  Builder.CreatePtrToInt(EmitScalarExpr(E->getArg(2)), IntType);
4557 
4558  auto Ordering =
4559  BuiltinID == Builtin::BI_InterlockedCompareExchangePointer_nf ?
4560  AtomicOrdering::Monotonic : AtomicOrdering::SequentiallyConsistent;
4561 
4562  auto Result = Builder.CreateAtomicCmpXchg(Destination, Comparand, Exchange,
4563  Ordering, Ordering);
4564  Result->setVolatile(true);
4565 
4566  return RValue::get(Builder.CreateIntToPtr(Builder.CreateExtractValue(Result,
4567  0),
4568  RTy));
4569  }
4570  case Builtin::BI_InterlockedCompareExchange8:
4571  case Builtin::BI_InterlockedCompareExchange16:
4572  case Builtin::BI_InterlockedCompareExchange:
4573  case Builtin::BI_InterlockedCompareExchange64:
4574  return RValue::get(EmitAtomicCmpXchgForMSIntrin(*this, E));
4575  case Builtin::BI_InterlockedIncrement16:
4576  case Builtin::BI_InterlockedIncrement:
4577  return RValue::get(
4578  EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedIncrement, E));
4579  case Builtin::BI_InterlockedDecrement16:
4580  case Builtin::BI_InterlockedDecrement:
4581  return RValue::get(
4582  EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedDecrement, E));
4583  case Builtin::BI_InterlockedAnd8:
4584  case Builtin::BI_InterlockedAnd16:
4585  case Builtin::BI_InterlockedAnd:
4586  return RValue::get(EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedAnd, E));
4587  case Builtin::BI_InterlockedExchangeAdd8:
4588  case Builtin::BI_InterlockedExchangeAdd16:
4589  case Builtin::BI_InterlockedExchangeAdd:
4590  return RValue::get(
4591  EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedExchangeAdd, E));
4592  case Builtin::BI_InterlockedExchangeSub8:
4593  case Builtin::BI_InterlockedExchangeSub16:
4594  case Builtin::BI_InterlockedExchangeSub:
4595  return RValue::get(
4596  EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedExchangeSub, E));
4597  case Builtin::BI_InterlockedOr8:
4598  case Builtin::BI_InterlockedOr16:
4599  case Builtin::BI_InterlockedOr:
4600  return RValue::get(EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedOr, E));
4601  case Builtin::BI_InterlockedXor8:
4602  case Builtin::BI_InterlockedXor16:
4603  case Builtin::BI_InterlockedXor:
4604  return RValue::get(EmitMSVCBuiltinExpr(MSVCIntrin::_InterlockedXor, E));
4605 
4606  case Builtin::BI_bittest64:
4607  case Builtin::BI_bittest:
4608  case Builtin::BI_bittestandcomplement64:
4609  case Builtin::BI_bittestandcomplement:
4610  case Builtin::BI_bittestandreset64:
4611  case Builtin::BI_bittestandreset:
4612  case Builtin::BI_bittestandset64:
4613  case Builtin::BI_bittestandset:
4614  case Builtin::BI_interlockedbittestandreset:
4615  case Builtin::BI_interlockedbittestandreset64:
4616  case Builtin::BI_interlockedbittestandset64:
4617  case Builtin::BI_interlockedbittestandset:
4618  case Builtin::BI_interlockedbittestandset_acq:
4619  case Builtin::BI_interlockedbittestandset_rel:
4620  case Builtin::BI_interlockedbittestandset_nf:
4621  case Builtin::BI_interlockedbittestandreset_acq:
4622  case Builtin::BI_interlockedbittestandreset_rel:
4623  case Builtin::BI_interlockedbittestandreset_nf:
4624  return RValue::get(EmitBitTestIntrinsic(*this, BuiltinID, E));
4625 
4626  // These builtins exist to emit regular volatile loads and stores not
4627  // affected by the -fms-volatile setting.
4628  case Builtin::BI__iso_volatile_load8:
4629  case Builtin::BI__iso_volatile_load16:
4630  case Builtin::BI__iso_volatile_load32:
4631  case Builtin::BI__iso_volatile_load64:
4632  return RValue::get(EmitISOVolatileLoad(*this, E));
4633  case Builtin::BI__iso_volatile_store8:
4634  case Builtin::BI__iso_volatile_store16:
4635  case Builtin::BI__iso_volatile_store32:
4636  case Builtin::BI__iso_volatile_store64:
4637  return RValue::get(EmitISOVolatileStore(*this, E));
4638 
4639  case Builtin::BI__exception_code:
4640  case Builtin::BI_exception_code:
4641  return RValue::get(EmitSEHExceptionCode());
4642  case Builtin::BI__exception_info:
4643  case Builtin::BI_exception_info:
4644  return RValue::get(EmitSEHExceptionInfo());
4645  case Builtin::BI__abnormal_termination:
4646  case Builtin::BI_abnormal_termination:
4647  return RValue::get(EmitSEHAbnormalTermination());
4648  case Builtin::BI_setjmpex:
4649  if (getTarget().getTriple().isOSMSVCRT() && E->getNumArgs() == 1 &&
4650  E->getArg(0)->getType()->isPointerType())
4651  return EmitMSVCRTSetJmp(*this, MSVCSetJmpKind::_setjmpex, E);
4652  break;
4653  case Builtin::BI_setjmp:
4654  if (getTarget().getTriple().isOSMSVCRT() && E->getNumArgs() == 1 &&
4655  E->getArg(0)->getType()->isPointerType()) {
4656  if (getTarget().getTriple().getArch() == llvm::Triple::x86)
4657  return EmitMSVCRTSetJmp(*this, MSVCSetJmpKind::_setjmp3, E);
4658  else if (getTarget().getTriple().getArch() == llvm::Triple::aarch64)
4659  return EmitMSVCRTSetJmp(*this, MSVCSetJmpKind::_setjmpex, E);
4660  return EmitMSVCRTSetJmp(*this, MSVCSetJmpKind::_setjmp, E);
4661  }
4662  break;
4663 
4664  // C++ std:: builtins.
4665  case Builtin::BImove:
4666  case Builtin::BImove_if_noexcept:
4667  case Builtin::BIforward:
4668  case Builtin::BIas_const:
4669  return RValue::get(EmitLValue(E->getArg(0)).getPointer(*this));
4670  case Builtin::BI__GetExceptionInfo: {
4671  if (llvm::GlobalVariable *GV =
4672  CGM.getCXXABI().getThrowInfo(FD->getParamDecl(0)->getType()))
4673  return RValue::get(llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy));
4674  break;
4675  }
4676 
4677  case Builtin::BI__fastfail:
4678  return RValue::get(EmitMSVCBuiltinExpr(MSVCIntrin::__fastfail, E));
4679 
4680  case Builtin::BI__builtin_coro_id:
4681  return EmitCoroutineIntrinsic(E, Intrinsic::coro_id);
4682  case Builtin::BI__builtin_coro_promise:
4683  return EmitCoroutineIntrinsic(E, Intrinsic::coro_promise);
4684  case Builtin::BI__builtin_coro_resume:
4685  EmitCoroutineIntrinsic(E, Intrinsic::coro_resume);
4686  return RValue::get(nullptr);
4687  case Builtin::BI__builtin_coro_frame:
4688  return EmitCoroutineIntrinsic(E, Intrinsic::coro_frame);
4689  case Builtin::BI__builtin_coro_noop:
4690  return EmitCoroutineIntrinsic(E, Intrinsic::coro_noop);
4691  case Builtin::BI__builtin_coro_free:
4692  return EmitCoroutineIntrinsic(E, Intrinsic::coro_free);
4693  case Builtin::BI__builtin_coro_destroy:
4694  EmitCoroutineIntrinsic(E, Intrinsic::coro_destroy);
4695  return RValue::get(nullptr);
4696  case Builtin::BI__builtin_coro_done:
4697  return EmitCoroutineIntrinsic(E, Intrinsic::coro_done);
4698  case Builtin::BI__builtin_coro_alloc:
4699  return EmitCoroutineIntrinsic(E, Intrinsic::coro_alloc);
4700  case Builtin::BI__builtin_coro_begin:
4701  return EmitCoroutineIntrinsic(E, Intrinsic::coro_begin);
4702  case Builtin::BI__builtin_coro_end:
4703  return EmitCoroutineIntrinsic(E, Intrinsic::coro_end);
4704  case Builtin::BI__builtin_coro_suspend:
4705  return EmitCoroutineIntrinsic(E, Intrinsic::coro_suspend);
4706  case Builtin::BI__builtin_coro_size:
4707  return EmitCoroutineIntrinsic(E, Intrinsic::coro_size);
4708  case Builtin::BI__builtin_coro_align:
4709  return EmitCoroutineIntrinsic(E, Intrinsic::coro_align);
4710 
4711  // OpenCL v2.0 s6.13.16.2, Built-in pipe read and write functions
4712  case Builtin::BIread_pipe:
4713  case Builtin::BIwrite_pipe: {
4714  Value *Arg0 = EmitScalarExpr(E->getArg(0)),
4715  *Arg1 = EmitScalarExpr(E->getArg(1));
4716  CGOpenCLRuntime OpenCLRT(CGM);
4717  Value *PacketSize = OpenCLRT.getPipeElemSize(E->getArg(0));
4718  Value *PacketAlign = OpenCLRT.getPipeElemAlign(E->getArg(0));
4719 
4720  // Type of the generic packet parameter.
4721  unsigned GenericAS =
4722  getContext().getTargetAddressSpace(LangAS::opencl_generic);
4723  llvm::Type *I8PTy = llvm::PointerType::get(
4724  llvm::Type::getInt8Ty(getLLVMContext()), GenericAS);
4725 
4726  // Testing which overloaded version we should generate the call for.
4727  if (2U == E->getNumArgs()) {
4728  const char *Name = (BuiltinID == Builtin::BIread_pipe) ? "__read_pipe_2"
4729  : "__write_pipe_2";
4730  // Creating a generic function type to be able to call with any builtin or
4731  // user defined type.
4732  llvm::Type *ArgTys[] = {Arg0->getType(), I8PTy, Int32Ty, Int32Ty};
4733  llvm::FunctionType *FTy = llvm::FunctionType::get(
4734  Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
4735  Value *BCast = Builder.CreatePointerCast(Arg1, I8PTy);
4736  return RValue::get(
4737  EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
4738  {Arg0, BCast, PacketSize, PacketAlign}));
4739  } else {
4740  assert(4 == E->getNumArgs() &&
4741  "Illegal number of parameters to pipe function");
4742  const char *Name = (BuiltinID == Builtin::BIread_pipe) ? "__read_pipe_4"
4743  : "__write_pipe_4";
4744 
4745  llvm::Type *ArgTys[] = {Arg0->getType(), Arg1->getType(), Int32Ty, I8PTy,
4746  Int32Ty, Int32Ty};
4747  Value *Arg2 = EmitScalarExpr(E->getArg(2)),
4748  *Arg3 = EmitScalarExpr(E->getArg(3));
4749  llvm::FunctionType *FTy = llvm::FunctionType::get(
4750  Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
4751  Value *BCast = Builder.CreatePointerCast(Arg3, I8PTy);
4752  // We know the third argument is an integer type, but we may need to cast
4753  // it to i32.
4754  if (Arg2->getType() != Int32Ty)
4755  Arg2 = Builder.CreateZExtOrTrunc(Arg2, Int32Ty);
4756  return RValue::get(
4757  EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
4758  {Arg0, Arg1, Arg2, BCast, PacketSize, PacketAlign}));
4759  }
4760  }
4761  // OpenCL v2.0 s6.13.16 ,s9.17.3.5 - Built-in pipe reserve read and write
4762  // functions
4763  case Builtin::BIreserve_read_pipe:
4764  case Builtin::BIreserve_write_pipe:
4765  case Builtin::BIwork_group_reserve_read_pipe:
4766  case Builtin::BIwork_group_reserve_write_pipe:
4767  case Builtin::BIsub_group_reserve_read_pipe:
4768  case Builtin::BIsub_group_reserve_write_pipe: {
4769  // Composing the mangled name for the function.
4770  const char *Name;
4771  if (BuiltinID == Builtin::BIreserve_read_pipe)
4772  Name = "__reserve_read_pipe";
4773  else if (BuiltinID == Builtin::BIreserve_write_pipe)
4774  Name = "__reserve_write_pipe";
4775  else if (BuiltinID == Builtin::BIwork_group_reserve_read_pipe)
4776  Name = "__work_group_reserve_read_pipe";
4777  else if (BuiltinID == Builtin::BIwork_group_reserve_write_pipe)
4778  Name = "__work_group_reserve_write_pipe";
4779  else if (BuiltinID == Builtin::BIsub_group_reserve_read_pipe)
4780  Name = "__sub_group_reserve_read_pipe";
4781  else
4782  Name = "__sub_group_reserve_write_pipe";
4783 
4784  Value *Arg0 = EmitScalarExpr(E->getArg(0)),
4785  *Arg1 = EmitScalarExpr(E->getArg(1));
4786  llvm::Type *ReservedIDTy = ConvertType(getContext().OCLReserveIDTy);
4787  CGOpenCLRuntime OpenCLRT(CGM);
4788  Value *PacketSize = OpenCLRT.getPipeElemSize(E->getArg(0));
4789  Value *PacketAlign = OpenCLRT.getPipeElemAlign(E->getArg(0));
4790 
4791  // Building the generic function prototype.
4792  llvm::Type *ArgTys[] = {Arg0->getType(), Int32Ty, Int32Ty, Int32Ty};
4793  llvm::FunctionType *FTy = llvm::FunctionType::get(
4794  ReservedIDTy, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
4795  // We know the second argument is an integer type, but we may need to cast
4796  // it to i32.
4797  if (Arg1->getType() != Int32Ty)
4798  Arg1 = Builder.CreateZExtOrTrunc(Arg1, Int32Ty);
4799  return RValue::get(EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
4800  {Arg0, Arg1, PacketSize, PacketAlign}));
4801  }
4802  // OpenCL v2.0 s6.13.16, s9.17.3.5 - Built-in pipe commit read and write
4803  // functions
4804  case Builtin::BIcommit_read_pipe:
4805  case Builtin::BIcommit_write_pipe:
4806  case Builtin::BIwork_group_commit_read_pipe:
4807  case Builtin::BIwork_group_commit_write_pipe:
4808  case Builtin::BIsub_group_commit_read_pipe:
4809  case Builtin::BIsub_group_commit_write_pipe: {
4810  const char *Name;
4811  if (BuiltinID == Builtin::BIcommit_read_pipe)
4812  Name = "__commit_read_pipe";
4813  else if (BuiltinID == Builtin::BIcommit_write_pipe)
4814  Name = "__commit_write_pipe";
4815  else if (BuiltinID == Builtin::BIwork_group_commit_read_pipe)
4816  Name = "__work_group_commit_read_pipe";
4817  else if (BuiltinID == Builtin::BIwork_group_commit_write_pipe)
4818  Name = "__work_group_commit_write_pipe";
4819  else if (BuiltinID == Builtin::BIsub_group_commit_read_pipe)
4820  Name = "__sub_group_commit_read_pipe";
4821  else
4822  Name = "__sub_group_commit_write_pipe";
4823 
4824  Value *Arg0 = EmitScalarExpr(E->getArg(0)),
4825  *Arg1 = EmitScalarExpr(E->getArg(1));
4826  CGOpenCLRuntime OpenCLRT(CGM);
4827  Value *PacketSize = OpenCLRT.getPipeElemSize(E->getArg(0));
4828  Value *PacketAlign = OpenCLRT.getPipeElemAlign(E->getArg(0));
4829 
4830  // Building the generic function prototype.
4831  llvm::Type *ArgTys[] = {Arg0->getType(), Arg1->getType(), Int32Ty, Int32Ty};
4832  llvm::FunctionType *FTy =
4833  llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
4834  llvm::ArrayRef<llvm::Type *>(ArgTys), false);
4835 
4836  return RValue::get(EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
4837  {Arg0, Arg1, PacketSize, PacketAlign}));
4838  }
4839  // OpenCL v2.0 s6.13.16.4 Built-in pipe query functions
4840  case Builtin::BIget_pipe_num_packets:
4841  case Builtin::BIget_pipe_max_packets: {
4842  const char *BaseName;
4843  const auto *PipeTy = E->getArg(0)->getType()->castAs<PipeType>();
4844  if (BuiltinID == Builtin::BIget_pipe_num_packets)
4845  BaseName = "__get_pipe_num_packets";
4846  else
4847  BaseName = "__get_pipe_max_packets";
4848  std::string Name = std::string(BaseName) +
4849  std::string(PipeTy->isReadOnly() ? "_ro" : "_wo");
4850 
4851  // Building the generic function prototype.
4852  Value *Arg0 = EmitScalarExpr(E->getArg(0));
4853  CGOpenCLRuntime OpenCLRT(CGM);
4854  Value *PacketSize = OpenCLRT.getPipeElemSize(E->getArg(0));
4855  Value *PacketAlign = OpenCLRT.getPipeElemAlign(E->getArg(0));
4856  llvm::Type *ArgTys[] = {Arg0->getType(), Int32Ty, Int32Ty};
4857  llvm::FunctionType *FTy = llvm::FunctionType::get(
4858  Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
4859 
4860  return RValue::get(EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
4861  {Arg0, PacketSize, PacketAlign}));
4862  }
4863 
4864  // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
4865  case Builtin::BIto_global:
4866  case Builtin::BIto_local:
4867  case Builtin::BIto_private: {
4868  auto Arg0 = EmitScalarExpr(E->getArg(0));
4869  auto NewArgT = llvm::PointerType::get(Int8Ty,
4870  CGM.getContext().getTargetAddressSpace(LangAS::opencl_generic));
4871  auto NewRetT = llvm::PointerType::get(Int8Ty,
4872  CGM.getContext().getTargetAddressSpace(
4874  auto FTy = llvm::FunctionType::get(NewRetT, {NewArgT}, false);
4875  llvm::Value *NewArg;
4876  if (Arg0->getType()->getPointerAddressSpace() !=
4877  NewArgT->getPointerAddressSpace())
4878  NewArg = Builder.CreateAddrSpaceCast(Arg0, NewArgT);
4879  else
4880  NewArg = Builder.CreateBitOrPointerCast(Arg0, NewArgT);
4881  auto NewName = std::string("__") + E->getDirectCallee()->getName().str();
4882  auto NewCall =
4883  EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, NewName), {NewArg});
4884  return RValue::get(Builder.CreateBitOrPointerCast(NewCall,
4885  ConvertType(E->getType())));
4886  }
4887 
4888  // OpenCL v2.0, s6.13.17 - Enqueue kernel function.
4889  // It contains four different overload formats specified in Table 6.13.17.1.
4890  case Builtin::BIenqueue_kernel: {
4891  StringRef Name; // Generated function call name
4892  unsigned NumArgs = E->getNumArgs();
4893 
4894  llvm::Type *QueueTy = ConvertType(getContext().OCLQueueTy);
4895  llvm::Type *GenericVoidPtrTy = Builder.getInt8PtrTy(
4896  getContext().getTargetAddressSpace(LangAS::opencl_generic));
4897 
4898  llvm::Value *Queue = EmitScalarExpr(E->getArg(0));
4899  llvm::Value *Flags = EmitScalarExpr(E->getArg(1));
4900  LValue NDRangeL = EmitAggExprToLValue(E->getArg(2));
4901  llvm::Value *Range = NDRangeL.getAddress(*this).getPointer();
4902  llvm::Type *RangeTy = NDRangeL.getAddress(*this).getType();
4903 
4904  if (NumArgs == 4) {
4905  // The most basic form of the call with parameters:
4906  // queue_t, kernel_enqueue_flags_t, ndrange_t, block(void)
4907  Name = "__enqueue_kernel_basic";
4908  llvm::Type *ArgTys[] = {QueueTy, Int32Ty, RangeTy, GenericVoidPtrTy,
4909  GenericVoidPtrTy};
4910  llvm::FunctionType *FTy = llvm::FunctionType::get(
4911  Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
4912 
4913  auto Info =
4914  CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(3));
4915  llvm::Value *Kernel =
4916  Builder.CreatePointerCast(Info.Kernel, GenericVoidPtrTy);
4917  llvm::Value *Block =
4918  Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
4919 
4920  AttrBuilder B(Builder.getContext());
4921  B.addByValAttr(NDRangeL.getAddress(*this).getElementType());
4922  llvm::AttributeList ByValAttrSet =
4923  llvm::AttributeList::get(CGM.getModule().getContext(), 3U, B);
4924 
4925  auto RTCall =
4926  EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name, ByValAttrSet),
4927  {Queue, Flags, Range, Kernel, Block});
4928  RTCall->setAttributes(ByValAttrSet);
4929  return RValue::get(RTCall);
4930  }
4931  assert(NumArgs >= 5 && "Invalid enqueue_kernel signature");
4932 
4933  // Create a temporary array to hold the sizes of local pointer arguments
4934  // for the block. \p First is the position of the first size argument.
4935  auto CreateArrayForSizeVar = [=](unsigned First)
4936  -> std::tuple<llvm::Value *, llvm::Value *, llvm::Value *> {
4937  llvm::APInt ArraySize(32, NumArgs - First);
4938  QualType SizeArrayTy = getContext().getConstantArrayType(
4939  getContext().getSizeType(), ArraySize, nullptr, ArrayType::Normal,
4940  /*IndexTypeQuals=*/0);
4941  auto Tmp = CreateMemTemp(SizeArrayTy, "block_sizes");
4942  llvm::Value *TmpPtr = Tmp.getPointer();
4943  llvm::Value *TmpSize = EmitLifetimeStart(
4944  CGM.getDataLayout().getTypeAllocSize(Tmp.getElementType()), TmpPtr);
4945  llvm::Value *ElemPtr;
4946  // Each of the following arguments specifies the size of the corresponding
4947  // argument passed to the enqueued block.
4948  auto *Zero = llvm::ConstantInt::get(IntTy, 0);
4949  for (unsigned I = First; I < NumArgs; ++I) {
4950  auto *Index = llvm::ConstantInt::get(IntTy, I - First);
4951  auto *GEP = Builder.CreateGEP(Tmp.getElementType(), TmpPtr,
4952  {Zero, Index});
4953  if (I == First)
4954  ElemPtr = GEP;
4955  auto *V =
4956  Builder.CreateZExtOrTrunc(EmitScalarExpr(E->getArg(I)), SizeTy);
4957  Builder.CreateAlignedStore(
4958  V, GEP, CGM.getDataLayout().getPrefTypeAlign(SizeTy));
4959  }
4960  return std::tie(ElemPtr, TmpSize, TmpPtr);
4961  };
4962 
4963  // Could have events and/or varargs.
4964  if (E->getArg(3)->getType()->isBlockPointerType()) {
4965  // No events passed, but has variadic arguments.
4966  Name = "__enqueue_kernel_varargs";
4967  auto Info =
4968  CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(3));
4969  llvm::Value *Kernel =
4970  Builder.CreatePointerCast(Info.Kernel, GenericVoidPtrTy);
4971  auto *Block = Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
4972  llvm::Value *ElemPtr, *TmpSize, *TmpPtr;
4973  std::tie(ElemPtr, TmpSize, TmpPtr) = CreateArrayForSizeVar(4);
4974 
4975  // Create a vector of the arguments, as well as a constant value to
4976  // express to the runtime the number of variadic arguments.
4977  llvm::Value *const Args[] = {Queue, Flags,
4978  Range, Kernel,
4979  Block, ConstantInt::get(IntTy, NumArgs - 4),
4980  ElemPtr};
4981  llvm::Type *const ArgTys[] = {
4982  QueueTy, IntTy, RangeTy, GenericVoidPtrTy,
4983  GenericVoidPtrTy, IntTy, ElemPtr->getType()};
4984 
4985  llvm::FunctionType *FTy = llvm::FunctionType::get(Int32Ty, ArgTys, false);
4986  auto Call = RValue::get(
4987  EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name), Args));
4988  if (TmpSize)
4989  EmitLifetimeEnd(TmpSize, TmpPtr);
4990  return Call;
4991  }
4992  // Any calls now have event arguments passed.
4993  if (NumArgs >= 7) {
4994  llvm::Type *EventTy = ConvertType(getContext().OCLClkEventTy);
4995  llvm::PointerType *EventPtrTy = EventTy->getPointerTo(
4996  CGM.getContext().getTargetAddressSpace(LangAS::opencl_generic));
4997 
4998  llvm::Value *NumEvents =
4999  Builder.CreateZExtOrTrunc(EmitScalarExpr(E->getArg(3)), Int32Ty);
5000 
5001  // Since SemaOpenCLBuiltinEnqueueKernel allows fifth and sixth arguments
5002  // to be a null pointer constant (including `0` literal), we can take it
5003  // into account and emit null pointer directly.
5004  llvm::Value *EventWaitList = nullptr;
5005  if (E->getArg(4)->isNullPointerConstant(
5006  getContext(), Expr::NPC_ValueDependentIsNotNull)) {
5007  EventWaitList = llvm::ConstantPointerNull::get(EventPtrTy);
5008  } else {
5009  EventWaitList = E->getArg(4)->getType()->isArrayType()
5010  ? EmitArrayToPointerDecay(E->getArg(4)).getPointer()
5011  : EmitScalarExpr(E->getArg(4));
5012  // Convert to generic address space.
5013  EventWaitList = Builder.CreatePointerCast(EventWaitList, EventPtrTy);
5014  }
5015  llvm::Value *EventRet = nullptr;
5016  if (E->getArg(5)->isNullPointerConstant(
5017  getContext(), Expr::NPC_ValueDependentIsNotNull)) {
5018  EventRet = llvm::ConstantPointerNull::get(EventPtrTy);
5019  } else {
5020  EventRet =
5021  Builder.CreatePointerCast(EmitScalarExpr(E->getArg(5)), EventPtrTy);
5022  }
5023 
5024  auto Info =
5025  CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(6));
5026  llvm::Value *Kernel =
5027  Builder.CreatePointerCast(Info.Kernel, GenericVoidPtrTy);
5028  llvm::Value *Block =
5029  Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
5030 
5031  std::vector<llvm::Type *> ArgTys = {
5032  QueueTy, Int32Ty, RangeTy, Int32Ty,
5033  EventPtrTy, EventPtrTy, GenericVoidPtrTy, GenericVoidPtrTy};
5034 
5035  std::vector<llvm::Value *> Args = {Queue, Flags, Range,
5036  NumEvents, EventWaitList, EventRet,
5037  Kernel, Block};
5038 
5039  if (NumArgs == 7) {
5040  // Has events but no variadics.
5041  Name = "__enqueue_kernel_basic_events";
5042  llvm::FunctionType *FTy = llvm::FunctionType::get(
5043  Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
5044  return RValue::get(
5045  EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
5047  }
5048  // Has event info and variadics
5049  // Pass the number of variadics to the runtime function too.
5050  Args.push_back(ConstantInt::get(Int32Ty, NumArgs - 7));
5051  ArgTys.push_back(Int32Ty);
5052  Name = "__enqueue_kernel_events_varargs";
5053 
5054  llvm::Value *ElemPtr, *TmpSize, *TmpPtr;
5055  std::tie(ElemPtr, TmpSize, TmpPtr) = CreateArrayForSizeVar(7);
5056  Args.push_back(ElemPtr);
5057  ArgTys.push_back(ElemPtr->getType());
5058 
5059  llvm::FunctionType *FTy = llvm::FunctionType::get(
5060  Int32Ty, llvm::ArrayRef<llvm::Type *>(ArgTys), false);
5061  auto Call =
5062  RValue::get(EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
5064  if (TmpSize)
5065  EmitLifetimeEnd(TmpSize, TmpPtr);
5066  return Call;
5067  }
5068  [[fallthrough]];
5069  }
5070  // OpenCL v2.0 s6.13.17.6 - Kernel query functions need bitcast of block
5071  // parameter.
5072  case Builtin::BIget_kernel_work_group_size: {
5073  llvm::Type *GenericVoidPtrTy = Builder.getInt8PtrTy(
5074  getContext().getTargetAddressSpace(LangAS::opencl_generic));
5075  auto Info =
5076  CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(0));
5077  Value *Kernel = Builder.CreatePointerCast(Info.Kernel, GenericVoidPtrTy);
5078  Value *Arg = Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
5079  return RValue::get(EmitRuntimeCall(
5080  CGM.CreateRuntimeFunction(
5081  llvm::FunctionType::get(IntTy, {GenericVoidPtrTy, GenericVoidPtrTy},
5082  false),
5083  "__get_kernel_work_group_size_impl"),
5084  {Kernel, Arg}));
5085  }
5086  case Builtin::BIget_kernel_preferred_work_group_size_multiple: {
5087  llvm::Type *GenericVoidPtrTy = Builder.getInt8PtrTy(
5088  getContext().getTargetAddressSpace(LangAS::opencl_generic));
5089  auto Info =
5090  CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(0));
5091  Value *Kernel = Builder.CreatePointerCast(Info.Kernel, GenericVoidPtrTy);
5092  Value *Arg = Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
5093  return RValue::get(EmitRuntimeCall(
5094  CGM.CreateRuntimeFunction(
5095  llvm::FunctionType::get(IntTy, {GenericVoidPtrTy, GenericVoidPtrTy},
5096  false),
5097  "__get_kernel_preferred_work_group_size_multiple_impl"),
5098  {Kernel, Arg}));
5099  }
5100  case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
5101  case Builtin::BIget_kernel_sub_group_count_for_ndrange: {
5102  llvm::Type *GenericVoidPtrTy = Builder.getInt8PtrTy(
5103  getContext().getTargetAddressSpace(LangAS::opencl_generic));
5104  LValue NDRangeL = EmitAggExprToLValue(E->getArg(0));
5105  llvm::Value *NDRange = NDRangeL.getAddress(*this).getPointer();
5106  auto Info =
5107  CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(1));
5108  Value *Kernel = Builder.CreatePointerCast(Info.Kernel, GenericVoidPtrTy);
5109  Value *Block = Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
5110  const char *Name =
5111  BuiltinID == Builtin::BIget_kernel_max_sub_group_size_for_ndrange
5112  ? "__get_kernel_max_sub_group_size_for_ndrange_impl"
5113  : "__get_kernel_sub_group_count_for_ndrange_impl";
5114  return RValue::get(EmitRuntimeCall(
5115  CGM.CreateRuntimeFunction(
5116  llvm::FunctionType::get(
5117  IntTy, {NDRange->getType(), GenericVoidPtrTy, GenericVoidPtrTy},
5118  false),
5119  Name),
5120  {NDRange, Kernel, Block}));
5121  }
5122 
5123  case Builtin::BI__builtin_store_half:
5124  case Builtin::BI__builtin_store_halff: {
5125  Value *Val = EmitScalarExpr(E->getArg(0));
5126  Address Address = EmitPointerWithAlignment(E->getArg(1));
5127  Value *HalfVal = Builder.CreateFPTrunc(Val, Builder.getHalfTy());
5128  Builder.CreateStore(HalfVal, Address);
5129  return RValue::get(nullptr);
5130  }
5131  case Builtin::BI__builtin_load_half: {
5132  Address Address = EmitPointerWithAlignment(E->getArg(0));
5133  Value *HalfVal = Builder.CreateLoad(Address);
5134  return RValue::get(Builder.CreateFPExt(HalfVal, Builder.getDoubleTy()));
5135  }
5136  case Builtin::BI__builtin_load_halff: {
5137  Address Address = EmitPointerWithAlignment(E->getArg(0));
5138  Value *HalfVal = Builder.CreateLoad(Address);
5139  return RValue::get(Builder.CreateFPExt(HalfVal, Builder.getFloatTy()));
5140  }
5141  case Builtin::BIprintf:
5142  if (getTarget().getTriple().isNVPTX() ||
5143  getTarget().getTriple().isAMDGCN()) {
5144  if (getLangOpts().OpenMPIsDevice)
5145  return EmitOpenMPDevicePrintfCallExpr(E);
5146  if (getTarget().getTriple().isNVPTX())
5147  return EmitNVPTXDevicePrintfCallExpr(E);
5148  if (getTarget().getTriple().isAMDGCN() && getLangOpts().HIP)
5149  return EmitAMDGPUDevicePrintfCallExpr(E);
5150  }
5151 
5152  break;
5153  case Builtin::BI__builtin_canonicalize:
5154  case Builtin::BI__builtin_canonicalizef:
5155  case Builtin::BI__builtin_canonicalizef16:
5156  case Builtin::BI__builtin_canonicalizel:
5157  return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::canonicalize));
5158 
5159  case Builtin::BI__builtin_thread_pointer: {
5160  if (!getContext().getTargetInfo().isTLSSupported())
5161  CGM.ErrorUnsupported(E, "__builtin_thread_pointer");
5162  // Fall through - it's already mapped to the intrinsic by ClangBuiltin.
5163  break;
5164  }
5165  case Builtin::BI__builtin_os_log_format:
5166  return emitBuiltinOSLogFormat(*E);
5167 
5168  case Builtin::BI__xray_customevent: {
5169  if (!ShouldXRayInstrumentFunction())
5170  return RValue::getIgnored();
5171 
5172  if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
5174  return RValue::getIgnored();
5175 
5176  if (const auto *XRayAttr = CurFuncDecl->getAttr<XRayInstrumentAttr>())
5177  if (XRayAttr->neverXRayInstrument() && !AlwaysEmitXRayCustomEvents())
5178  return RValue::getIgnored();
5179 
5180  Function *F = CGM.getIntrinsic(Intrinsic::xray_customevent);
5181  auto FTy = F->getFunctionType();
5182  auto Arg0 = E->getArg(0);
5183  auto Arg0Val = EmitScalarExpr(Arg0);
5184  auto Arg0Ty = Arg0->getType();
5185  auto PTy0 = FTy->getParamType(0);
5186  if (PTy0 != Arg0Val->getType()) {
5187  if (Arg0Ty->isArrayType())
5188  Arg0Val = EmitArrayToPointerDecay(Arg0).getPointer();
5189  else
5190  Arg0Val = Builder.CreatePointerCast(Arg0Val, PTy0);
5191  }
5192  auto Arg1 = EmitScalarExpr(E->getArg(1));
5193  auto PTy1 = FTy->getParamType(1);
5194  if (PTy1 != Arg1->getType())
5195  Arg1 = Builder.CreateTruncOrBitCast(Arg1, PTy1);
5196  return RValue::get(Builder.CreateCall(F, {Arg0Val, Arg1}));
5197  }
5198 
5199  case Builtin::BI__xray_typedevent: {
5200  // TODO: There should be a way to always emit events even if the current
5201  // function is not instrumented. Losing events in a stream can cripple
5202  // a trace.
5203  if (!ShouldXRayInstrumentFunction())
5204  return RValue::getIgnored();
5205 
5206  if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
5208  return RValue::getIgnored();
5209 
5210  if (const auto *XRayAttr = CurFuncDecl->getAttr<XRayInstrumentAttr>())
5211  if (XRayAttr->neverXRayInstrument() && !AlwaysEmitXRayTypedEvents())
5212  return RValue::getIgnored();
5213 
5214  Function *F = CGM.getIntrinsic(Intrinsic::xray_typedevent);
5215  auto FTy = F->getFunctionType();
5216  auto Arg0 = EmitScalarExpr(E->getArg(0));
5217  auto PTy0 = FTy->getParamType(0);
5218  if (PTy0 != Arg0->getType())
5219  Arg0 = Builder.CreateTruncOrBitCast(Arg0, PTy0);
5220  auto Arg1 = E->getArg(1);
5221  auto Arg1Val = EmitScalarExpr(Arg1);
5222  auto Arg1Ty = Arg1->getType();
5223  auto PTy1 = FTy->getParamType(1);
5224  if (PTy1 != Arg1Val->getType()) {
5225  if (Arg1Ty->isArrayType())
5226  Arg1Val = EmitArrayToPointerDecay(Arg1).getPointer();
5227  else
5228  Arg1Val = Builder.CreatePointerCast(Arg1Val, PTy1);
5229  }
5230  auto Arg2 = EmitScalarExpr(E->getArg(2));
5231  auto PTy2 = FTy->getParamType(2);
5232  if (PTy2 != Arg2->getType())
5233  Arg2 = Builder.CreateTruncOrBitCast(Arg2, PTy2);
5234  return RValue::get(Builder.CreateCall(F, {Arg0, Arg1Val, Arg2}));
5235  }
5236 
5237  case Builtin::BI__builtin_ms_va_start:
5238  case Builtin::BI__builtin_ms_va_end:
5239  return RValue::get(
5240  EmitVAStartEnd(EmitMSVAListRef(E->getArg(0)).getPointer(),
5241  BuiltinID == Builtin::BI__builtin_ms_va_start));
5242 
5243  case Builtin::BI__builtin_ms_va_copy: {
5244  // Lower this manually. We can't reliably determine whether or not any
5245  // given va_copy() is for a Win64 va_list from the calling convention
5246  // alone, because it's legal to do this from a System V ABI function.
5247  // With opaque pointer types, we won't have enough information in LLVM
5248  // IR to determine this from the argument types, either. Best to do it
5249  // now, while we have enough information.
5250  Address DestAddr = EmitMSVAListRef(E->getArg(0));
5251  Address SrcAddr = EmitMSVAListRef(E->getArg(1));
5252 
5253  llvm::Type *BPP = Int8PtrPtrTy;
5254 
5255  DestAddr = Address(Builder.CreateBitCast(DestAddr.getPointer(), BPP, "cp"),
5256  Int8PtrTy, DestAddr.getAlignment());
5257  SrcAddr = Address(Builder.CreateBitCast(SrcAddr.getPointer(), BPP, "ap"),
5258  Int8PtrTy, SrcAddr.getAlignment());
5259 
5260  Value *ArgPtr = Builder.CreateLoad(SrcAddr, "ap.val");
5261  return RValue::get(Builder.CreateStore(ArgPtr, DestAddr));
5262  }
5263 
5264  case Builtin::BI__builtin_get_device_side_mangled_name: {
5265  auto Name = CGM.getCUDARuntime().getDeviceSideName(
5266  cast<DeclRefExpr>(E->getArg(0)->IgnoreImpCasts())->getDecl());
5267  auto Str = CGM.GetAddrOfConstantCString(Name, "");
5268  llvm::Constant *Zeros[] = {llvm::ConstantInt::get(SizeTy, 0),
5269  llvm::ConstantInt::get(SizeTy, 0)};
5270  auto *Ptr = llvm::ConstantExpr::getGetElementPtr(Str.getElementType(),
5271  Str.getPointer(), Zeros);
5272  return RValue::get(Ptr);
5273  }
5274  }
5275 
5276  // If this is an alias for a lib function (e.g. __builtin_sin), emit
5277  // the call using the normal call path, but using the unmangled
5278  // version of the function name.
5279  if (getContext().BuiltinInfo.isLibFunction(BuiltinID))
5280  return emitLibraryCall(*this, FD, E,
5281  CGM.getBuiltinLibFunction(FD, BuiltinID));
5282 
5283  // If this is a predefined lib function (e.g. malloc), emit the call
5284  // using exactly the normal call path.
5285  if (getContext().BuiltinInfo.isPredefinedLibFunction(BuiltinID))
5286  return emitLibraryCall(*this, FD, E,
5287  cast<llvm::Constant>(EmitScalarExpr(E->getCallee())));
5288 
5289  // Check that a call to a target specific builtin has the correct target
5290  // features.
5291  // This is down here to avoid non-target specific builtins, however, if
5292  // generic builtins start to require generic target features then we
5293  // can move this up to the beginning of the function.
5294  checkTargetFeatures(E, FD);
5295 
5296  if (unsigned VectorWidth = getContext().BuiltinInfo.getRequiredVectorWidth(BuiltinID))
5297  LargestVectorWidth = std::max(LargestVectorWidth, VectorWidth);
5298 
5299  // See if we have a target specific intrinsic.
5300  const char *Name = getContext().BuiltinInfo.getName(BuiltinID);
5301  Intrinsic::ID IntrinsicID = Intrinsic::not_intrinsic;
5302  StringRef Prefix =
5303  llvm::Triple::getArchTypePrefix(getTarget().getTriple().getArch());
5304  if (!Prefix.empty()) {
5305  IntrinsicID = Intrinsic::getIntrinsicForClangBuiltin(Prefix.data(), Name);
5306  // NOTE we don't need to perform a compatibility flag check here since the
5307  // intrinsics are declared in Builtins*.def via LANGBUILTIN which filter the
5308  // MS builtins via ALL_MS_LANGUAGES and are filtered earlier.
5309  if (IntrinsicID == Intrinsic::not_intrinsic)
5310  IntrinsicID = Intrinsic::getIntrinsicForMSBuiltin(Prefix.data(), Name);
5311  }
5312 
5313  if (IntrinsicID != Intrinsic::not_intrinsic) {
5315 
5316  // Find out if any arguments are required to be integer constant
5317  // expressions.
5318  unsigned ICEArguments = 0;
5320  getContext().GetBuiltinType(BuiltinID, Error, &ICEArguments);
5321  assert(Error == ASTContext::GE_None && "Should not codegen an error");
5322 
5323  Function *F = CGM.getIntrinsic(IntrinsicID);
5324  llvm::FunctionType *FTy = F->getFunctionType();
5325 
5326  for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
5327  Value *ArgValue;
5328  // If this is a normal argument, just emit it as a scalar.
5329  if ((ICEArguments & (1 << i)) == 0) {
5330  ArgValue = EmitScalarExpr(E->getArg(i));
5331  } else {
5332  // If this is required to be a constant, constant fold it so that we
5333  // know that the generated intrinsic gets a ConstantInt.
5334  ArgValue = llvm::ConstantInt::get(
5335  getLLVMContext(),
5336  *E->getArg(i)->getIntegerConstantExpr(getContext()));
5337  }
5338 
5339  // If the intrinsic arg type is different from the builtin arg type
5340  // we need to do a bit cast.
5341  llvm::Type *PTy = FTy->getParamType(i);
5342  if (PTy != ArgValue->getType()) {
5343  // XXX - vector of pointers?
5344  if (auto *PtrTy = dyn_cast<llvm::PointerType>(PTy)) {
5345  if (PtrTy->getAddressSpace() !=
5346  ArgValue->getType()->getPointerAddressSpace()) {
5347  ArgValue = Builder.CreateAddrSpaceCast(
5348  ArgValue,
5349  ArgValue->getType()->getPointerTo(PtrTy->getAddressSpace()));
5350  }
5351  }
5352 
5353  assert(PTy->canLosslesslyBitCastTo(FTy->getParamType(i)) &&
5354  "Must be able to losslessly bit cast to param");
5355  // Cast vector type (e.g., v256i32) to x86_amx, this only happen
5356  // in amx intrinsics.
5357  if (PTy->isX86_AMXTy())
5358  ArgValue = Builder.CreateIntrinsic(Intrinsic::x86_cast_vector_to_tile,
5359  {ArgValue->getType()}, {ArgValue});
5360  else
5361  ArgValue = Builder.CreateBitCast(ArgValue, PTy);
5362  }
5363 
5364  Args.push_back(ArgValue);
5365  }
5366 
5367  Value *V = Builder.CreateCall(F, Args);
5368  QualType BuiltinRetType = E->getType();
5369 
5370  llvm::Type *RetTy = VoidTy;
5371  if (!BuiltinRetType->isVoidType())
5372  RetTy = ConvertType(BuiltinRetType);
5373 
5374  if (RetTy != V->getType()) {
5375  // XXX - vector of pointers?
5376  if (auto *PtrTy = dyn_cast<llvm::PointerType>(RetTy)) {
5377  if (PtrTy->getAddressSpace() != V->getType()->getPointerAddressSpace()) {
5378  V = Builder.CreateAddrSpaceCast(
5379  V, V->getType()->getPointerTo(PtrTy->getAddressSpace()));
5380  }
5381  }
5382 
5383  assert(V->getType()->canLosslesslyBitCastTo(RetTy) &&
5384  "Must be able to losslessly bit cast result type");
5385  // Cast x86_amx to vector type (e.g., v256i32), this only happen
5386  // in amx intrinsics.
5387  if (V->getType()->isX86_AMXTy())
5388  V = Builder.CreateIntrinsic(Intrinsic::x86_cast_tile_to_vector, {RetTy},
5389  {V});
5390  else
5391  V = Builder.CreateBitCast(V, RetTy);
5392  }
5393 
5394  if (RetTy->isVoidTy())
5395  return RValue::get(nullptr);
5396 
5397  return RValue::get(V);
5398  }
5399 
5400  // Some target-specific builtins can have aggregate return values, e.g.
5401  // __builtin_arm_mve_vld2q_u32. So if the result is an aggregate, force
5402  // ReturnValue to be non-null, so that the target-specific emission code can
5403  // always just emit into it.
5404  TypeEvaluationKind EvalKind = getEvaluationKind(E->getType());
5405  if (EvalKind == TEK_Aggregate && ReturnValue.isNull()) {
5406  Address DestPtr = CreateMemTemp(E->getType(), "agg.tmp");
5407  ReturnValue = ReturnValueSlot(DestPtr, false);
5408  }
5409 
5410  // Now see if we can emit a target-specific builtin.
5411  if (Value *V = EmitTargetBuiltinExpr(BuiltinID, E, ReturnValue)) {
5412  switch (EvalKind) {
5413  case TEK_Scalar:
5414  if (V->getType()->isVoidTy())
5415  return RValue::get(nullptr);
5416  return RValue::get(V);
5417  case TEK_Aggregate:
5418  return RValue::getAggregate(ReturnValue.getValue(),
5419  ReturnValue.isVolatile());
5420  case TEK_Complex:
5421  llvm_unreachable("No current target builtin returns complex");
5422  }
5423  llvm_unreachable("Bad evaluation kind in EmitBuiltinExpr");
5424  }
5425 
5426  ErrorUnsupported(E, "builtin function");
5427 
5428  // Unknown builtin, for now just dump it out and return undef.
5429  return GetUndefRValue(E->getType());
5430 }
5431 
5433  unsigned BuiltinID, const CallExpr *E,
5434  ReturnValueSlot ReturnValue,
5435  llvm::Triple::ArchType Arch) {
5436  switch (Arch) {
5437  case llvm::Triple::arm:
5438  case llvm::Triple::armeb:
5439  case llvm::Triple::thumb:
5440  case llvm::Triple::thumbeb:
5441  return CGF->EmitARMBuiltinExpr(BuiltinID, E, ReturnValue, Arch);
5442  case llvm::Triple::aarch64:
5443  case llvm::Triple::aarch64_32:
5444  case llvm::Triple::aarch64_be:
5445  return CGF->EmitAArch64BuiltinExpr(BuiltinID, E, Arch);
5446  case llvm::Triple::bpfeb:
5447  case llvm::Triple::bpfel:
5448  return CGF->EmitBPFBuiltinExpr(BuiltinID, E);
5449  case llvm::Triple::x86:
5450  case llvm::Triple::x86_64:
5451  return CGF->EmitX86BuiltinExpr(BuiltinID, E);
5452  case llvm::Triple::ppc:
5453  case llvm::Triple::ppcle:
5454  case llvm::Triple::ppc64:
5455  case llvm::Triple::ppc64le:
5456  return CGF->EmitPPCBuiltinExpr(BuiltinID, E);
5457  case llvm::Triple::r600:
5458  case llvm::Triple::amdgcn:
5459  return CGF->EmitAMDGPUBuiltinExpr(BuiltinID, E);
5460  case llvm::Triple::systemz:
5461  return CGF->EmitSystemZBuiltinExpr(BuiltinID, E);
5462  case llvm::Triple::nvptx:
5463  case llvm::Triple::nvptx64:
5464  return CGF->EmitNVPTXBuiltinExpr(BuiltinID, E);
5465  case llvm::Triple::wasm32:
5466  case llvm::Triple::wasm64:
5467  return CGF->EmitWebAssemblyBuiltinExpr(BuiltinID, E);
5468  case llvm::Triple::hexagon:
5469  return CGF->EmitHexagonBuiltinExpr(BuiltinID, E);
5470  case llvm::Triple::riscv32:
5471  case llvm::Triple::riscv64:
5472  return CGF->EmitRISCVBuiltinExpr(BuiltinID, E, ReturnValue);
5473  case llvm::Triple::loongarch32:
5474  case llvm::Triple::loongarch64:
5475  return CGF->EmitLoongArchBuiltinExpr(BuiltinID, E);
5476  default:
5477  return nullptr;
5478  }
5479 }
5480 
5482  const CallExpr *E,
5483  ReturnValueSlot ReturnValue) {
5484  if (getContext().BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
5485  assert(getContext().getAuxTargetInfo() && "Missing aux target info");
5487  this, getContext().BuiltinInfo.getAuxBuiltinID(BuiltinID), E,
5488  ReturnValue, getContext().getAuxTargetInfo()->getTriple().getArch());
5489  }
5490 
5491  return EmitTargetArchBuiltinExpr(this, BuiltinID, E, ReturnValue,
5492  getTarget().getTriple().getArch());
5493 }
5494 
5495 static llvm::FixedVectorType *GetNeonType(CodeGenFunction *CGF,
5496  NeonTypeFlags TypeFlags,
5497  bool HasLegalHalfType = true,
5498  bool V1Ty = false,
5499  bool AllowBFloatArgsAndRet = true) {
5500  int IsQuad = TypeFlags.isQuad();
5501  switch (TypeFlags.getEltType()) {
5502  case NeonTypeFlags::Int8:
5503  case NeonTypeFlags::Poly8: