Coverage Report

Created: 2021-08-24 07:12

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