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