clang 24.0.0git
CGBuiltin.cpp
Go to the documentation of this file.
1//===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This contains code to emit Builtin calls as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGBuiltin.h"
14#include "ABIInfo.h"
15#include "CGCUDARuntime.h"
16#include "CGCXXABI.h"
17#include "CGDebugInfo.h"
18#include "CGObjCRuntime.h"
19#include "CGOpenCLRuntime.h"
20#include "CGRecordLayout.h"
21#include "CGValue.h"
22#include "CodeGenFunction.h"
23#include "CodeGenModule.h"
24#include "ConstantEmitter.h"
25#include "PatternInit.h"
26#include "TargetInfo.h"
27#include "clang/AST/OSLog.h"
31#include "llvm/ADT/APFloat.h"
32#include "llvm/IR/InlineAsm.h"
33#include "llvm/IR/Instruction.h"
34#include "llvm/IR/Intrinsics.h"
35#include "llvm/IR/IntrinsicsX86.h"
36#include "llvm/IR/MatrixBuilder.h"
37#include "llvm/Support/ConvertUTF.h"
38#include "llvm/Support/ScopedPrinter.h"
39#include <algorithm>
40#include <optional>
41#include <utility>
42
43using namespace clang;
44using namespace CodeGen;
45using namespace llvm;
46
47/// Some builtins do not have library implementation on some targets and
48/// are instead emitted as LLVM IRs by some target builtin emitters.
49/// FIXME: Remove this when library support is added
50static bool shouldEmitBuiltinAsIR(unsigned BuiltinID,
51 const Builtin::Context &BI,
52 const CodeGenFunction &CGF) {
53 if (!CGF.CGM.getLangOpts().MathErrno &&
57 switch (BuiltinID) {
58 default:
59 return false;
60 case Builtin::BIlogbf:
61 case Builtin::BI__builtin_logbf:
62 case Builtin::BIlogb:
63 case Builtin::BI__builtin_logb:
64 case Builtin::BIscalbnf:
65 case Builtin::BI__builtin_scalbnf:
66 case Builtin::BIscalbn:
67 case Builtin::BI__builtin_scalbn:
68 return true;
69 }
70 }
71 return false;
72}
73
75 unsigned BuiltinID, const CallExpr *E,
76 ReturnValueSlot ReturnValue,
77 llvm::Triple::ArchType Arch) {
78 // When compiling in HipStdPar mode we have to be conservative in rejecting
79 // target specific features in the FE, and defer the possible error to the
80 // AcceleratorCodeSelection pass, wherein iff an unsupported target builtin is
81 // referenced by an accelerator executable function, we emit an error.
82 // Returning nullptr here leads to the builtin being handled in
83 // EmitStdParUnsupportedBuiltin.
84 if (CGF->getLangOpts().HIPStdPar && CGF->getLangOpts().CUDAIsDevice &&
85 Arch != CGF->getTarget().getTriple().getArch())
86 return nullptr;
87
88 switch (Arch) {
89 case llvm::Triple::arm:
90 case llvm::Triple::armeb:
91 case llvm::Triple::thumb:
92 case llvm::Triple::thumbeb:
93 return CGF->EmitARMBuiltinExpr(BuiltinID, E, ReturnValue, Arch);
94 case llvm::Triple::aarch64:
95 case llvm::Triple::aarch64_32:
96 case llvm::Triple::aarch64_be:
97 return CGF->EmitAArch64BuiltinExpr(BuiltinID, E, Arch);
98 case llvm::Triple::bpfeb:
99 case llvm::Triple::bpfel:
100 return CGF->EmitBPFBuiltinExpr(BuiltinID, E);
101 case llvm::Triple::dxil:
102 return CGF->EmitDirectXBuiltinExpr(BuiltinID, E);
103 case llvm::Triple::x86:
104 case llvm::Triple::x86_64:
105 return CGF->EmitX86BuiltinExpr(BuiltinID, E);
106 case llvm::Triple::ppc:
107 case llvm::Triple::ppcle:
108 case llvm::Triple::ppc64:
109 case llvm::Triple::ppc64le:
110 return CGF->EmitPPCBuiltinExpr(BuiltinID, E);
111 case llvm::Triple::amdgpu:
112 case llvm::Triple::r600:
113 return CGF->EmitAMDGPUBuiltinExpr(BuiltinID, E);
114 case llvm::Triple::systemz:
115 return CGF->EmitSystemZBuiltinExpr(BuiltinID, E);
116 case llvm::Triple::nvptx:
117 case llvm::Triple::nvptx64:
118 return CGF->EmitNVPTXBuiltinExpr(BuiltinID, E);
119 case llvm::Triple::wasm32:
120 case llvm::Triple::wasm64:
121 return CGF->EmitWebAssemblyBuiltinExpr(BuiltinID, E);
122 case llvm::Triple::hexagon:
123 return CGF->EmitHexagonBuiltinExpr(BuiltinID, E);
124 case llvm::Triple::riscv32:
125 case llvm::Triple::riscv64:
126 case llvm::Triple::riscv32be:
127 case llvm::Triple::riscv64be:
128 return CGF->EmitRISCVBuiltinExpr(BuiltinID, E, ReturnValue);
129 case llvm::Triple::spirv32:
130 case llvm::Triple::spirv64:
131 if (CGF->getTarget().getTriple().getOS() == llvm::Triple::OSType::AMDHSA)
132 return CGF->EmitAMDGPUBuiltinExpr(BuiltinID, E);
133 [[fallthrough]];
134 case llvm::Triple::spirv:
135 return CGF->EmitSPIRVBuiltinExpr(BuiltinID, E);
136 case llvm::Triple::avr:
137 return CGF->EmitAVRBuiltinExpr(BuiltinID, E);
138 default:
139 return nullptr;
140 }
141}
142
144 const CallExpr *E,
146 if (getContext().BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
147 assert(getContext().getAuxTargetInfo() && "Missing aux target info");
149 this, getContext().BuiltinInfo.getAuxBuiltinID(BuiltinID), E,
150 ReturnValue, getContext().getAuxTargetInfo()->getTriple().getArch());
151 }
152
153 return EmitTargetArchBuiltinExpr(this, BuiltinID, E, ReturnValue,
154 getTarget().getTriple().getArch());
155}
156
157static void initializeAlloca(CodeGenFunction &CGF, AllocaInst *AI, Value *Size,
158 Align AlignmentInBytes) {
159 ConstantInt *Byte;
160 switch (CGF.getLangOpts().getTrivialAutoVarInit()) {
162 // Nothing to initialize.
163 return;
165 Byte = CGF.Builder.getInt8(0x00);
166 break;
168 llvm::Type *Int8 = llvm::IntegerType::getInt8Ty(CGF.CGM.getLLVMContext());
169 Byte = llvm::dyn_cast<llvm::ConstantInt>(
170 initializationPatternFor(CGF.CGM, Int8));
171 break;
172 }
173 }
174 if (CGF.CGM.stopAutoInit())
175 return;
176 auto *I = CGF.Builder.CreateMemSet(AI, Byte, Size, AlignmentInBytes);
177 I->addAnnotationMetadata("auto-init");
178}
179
180/// getBuiltinLibFunction - Given a builtin id for a function like
181/// "__builtin_fabsf", return a Function* for "fabsf".
183 unsigned BuiltinID) {
184 assert(Context.BuiltinInfo.isLibFunction(BuiltinID));
185
186 // Get the name, skip over the __builtin_ prefix (if necessary). We may have
187 // to build this up so provide a small stack buffer to handle the vast
188 // majority of names.
190 GlobalDecl D(FD);
191
192 // TODO: This list should be expanded or refactored after all GCC-compatible
193 // std libcall builtins are implemented.
194 static const SmallDenseMap<unsigned, StringRef, 64> F128Builtins{
195 {Builtin::BI__builtin___fprintf_chk, "__fprintf_chkieee128"},
196 {Builtin::BI__builtin___printf_chk, "__printf_chkieee128"},
197 {Builtin::BI__builtin___snprintf_chk, "__snprintf_chkieee128"},
198 {Builtin::BI__builtin___sprintf_chk, "__sprintf_chkieee128"},
199 {Builtin::BI__builtin___vfprintf_chk, "__vfprintf_chkieee128"},
200 {Builtin::BI__builtin___vprintf_chk, "__vprintf_chkieee128"},
201 {Builtin::BI__builtin___vsnprintf_chk, "__vsnprintf_chkieee128"},
202 {Builtin::BI__builtin___vsprintf_chk, "__vsprintf_chkieee128"},
203 {Builtin::BI__builtin_fprintf, "__fprintfieee128"},
204 {Builtin::BI__builtin_printf, "__printfieee128"},
205 {Builtin::BI__builtin_snprintf, "__snprintfieee128"},
206 {Builtin::BI__builtin_sprintf, "__sprintfieee128"},
207 {Builtin::BI__builtin_vfprintf, "__vfprintfieee128"},
208 {Builtin::BI__builtin_vprintf, "__vprintfieee128"},
209 {Builtin::BI__builtin_vsnprintf, "__vsnprintfieee128"},
210 {Builtin::BI__builtin_vsprintf, "__vsprintfieee128"},
211 {Builtin::BI__builtin_fscanf, "__fscanfieee128"},
212 {Builtin::BI__builtin_scanf, "__scanfieee128"},
213 {Builtin::BI__builtin_sscanf, "__sscanfieee128"},
214 {Builtin::BI__builtin_vfscanf, "__vfscanfieee128"},
215 {Builtin::BI__builtin_vscanf, "__vscanfieee128"},
216 {Builtin::BI__builtin_vsscanf, "__vsscanfieee128"},
217 {Builtin::BI__builtin_nexttowardf128, "__nexttowardieee128"},
218 };
219
220 // The AIX library functions frexpl, ldexpl, and modfl are for 128-bit
221 // IBM 'long double' (i.e. __ibm128). Map to the 'double' versions
222 // if it is 64-bit 'long double' mode.
223 static const SmallDenseMap<unsigned, StringRef, 4> AIXLongDouble64Builtins{
224 {Builtin::BI__builtin_frexpl, "frexp"},
225 {Builtin::BI__builtin_ldexpl, "ldexp"},
226 {Builtin::BI__builtin_modfl, "modf"},
227 };
228
229 // If the builtin has been declared explicitly with an assembler label,
230 // use the mangled name. This differs from the plain label on platforms
231 // that prefix labels.
232 if (FD->hasAttr<AsmLabelAttr>())
233 Name = getMangledName(D);
234 else {
235 // TODO: This mutation should also be applied to other targets other than
236 // PPC, after backend supports IEEE 128-bit style libcalls.
237 if (getTriple().isPPC64() &&
238 &getTarget().getLongDoubleFormat() == &llvm::APFloat::IEEEquad() &&
239 F128Builtins.contains(BuiltinID))
240 Name = F128Builtins.lookup(BuiltinID);
241 else if (getTriple().isOSAIX() &&
242 &getTarget().getLongDoubleFormat() ==
243 &llvm::APFloat::IEEEdouble() &&
244 AIXLongDouble64Builtins.contains(BuiltinID))
245 Name = AIXLongDouble64Builtins.lookup(BuiltinID);
246 else
247 Name = Context.BuiltinInfo.getName(BuiltinID).substr(10);
248 }
249
250 llvm::FunctionType *Ty =
251 cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
252
253 return GetOrCreateLLVMFunction(Name, Ty, D, /*ForVTable=*/false);
254}
255
257 llvm::Function *F) {
258 llvm::FunctionType *FTy = F->getFunctionType();
259 unsigned NumParams = FTy->getNumParams();
260 if (Args.size() >= NumParams)
261 return;
262
263 auto [FirstDefault, Defaults] =
264 Intrinsic::getAllDefaultArgValues(F->getIntrinsicID());
265 assert(Args.size() >= FirstDefault &&
266 "builtin passes fewer arguments than the intrinsic requires");
267
268 for (unsigned I = Args.size(); I != NumParams; ++I) {
269 llvm::Type *ParamTy = FTy->getParamType(I);
270 unsigned DefaultIdx = I - FirstDefault;
271 assert(ParamTy->isIntegerTy() &&
272 "intrinsic default arguments must be integer-typed");
273 Args.push_back(llvm::ConstantInt::get(ParamTy, Defaults[DefaultIdx]));
274 }
275}
276
277/// Emit the conversions required to turn the given value into an
278/// integer of the given size.
279Value *EmitToInt(CodeGenFunction &CGF, llvm::Value *V,
280 QualType T, llvm::IntegerType *IntType) {
281 V = CGF.EmitToMemory(V, T);
282
283 if (V->getType()->isPointerTy())
284 return CGF.Builder.CreatePtrToInt(V, IntType);
285
286 assert(V->getType() == IntType);
287 return V;
288}
289
290Value *EmitFromInt(CodeGenFunction &CGF, llvm::Value *V,
291 QualType T, llvm::Type *ResultType) {
292 V = CGF.EmitFromMemory(V, T);
293
294 if (ResultType->isPointerTy())
295 return CGF.Builder.CreateIntToPtr(V, ResultType);
296
297 assert(V->getType() == ResultType);
298 return V;
299}
300
302 ASTContext &Ctx = CGF.getContext();
303 Address Ptr = CGF.EmitPointerWithAlignment(E->getArg(0));
304 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
305 unsigned Bytes = Ptr.getElementType()->isPointerTy()
307 : DL.getTypeStoreSize(Ptr.getElementType());
308 unsigned Align = Ptr.getAlignment().getQuantity();
309 if (Align % Bytes != 0) {
310 DiagnosticsEngine &Diags = CGF.CGM.getDiags();
311 Diags.Report(E->getBeginLoc(), diag::warn_sync_op_misaligned);
312 // Force address to be at least naturally-aligned.
313 return Ptr.withAlignment(CharUnits::fromQuantity(Bytes));
314 }
315 return Ptr;
316}
317
318/// Utility to insert an atomic instruction based on Intrinsic::ID
319/// and the expression node.
321 CodeGenFunction &CGF, llvm::AtomicRMWInst::BinOp Kind, const CallExpr *E,
322 AtomicOrdering Ordering) {
323
324 QualType T = E->getType();
325 assert(E->getArg(0)->getType()->isPointerType());
327 E->getArg(0)->getType()->getPointeeType()));
328 assert(CGF.getContext().hasSameUnqualifiedType(T, E->getArg(1)->getType()));
329
330 Address DestAddr = CheckAtomicAlignment(CGF, E);
331
332 llvm::IntegerType *IntType = llvm::IntegerType::get(
333 CGF.getLLVMContext(), CGF.getContext().getTypeSize(T));
334
335 llvm::Value *Val = CGF.EmitScalarExpr(E->getArg(1));
336 llvm::Type *ValueType = Val->getType();
337 Val = EmitToInt(CGF, Val, T, IntType);
338
339 llvm::Value *Result =
340 CGF.Builder.CreateAtomicRMW(Kind, DestAddr, Val, Ordering);
341 // Consider atomics to be volatile in MS kernel mode.
342 if (CGF.CGM.getLangOpts().Kernel)
343 cast<llvm::AtomicRMWInst>(Result)->setVolatile(true);
344 return EmitFromInt(CGF, Result, T, ValueType);
345}
346
348 Value *Val = CGF.EmitScalarExpr(E->getArg(0));
350
351 Val = CGF.EmitToMemory(Val, E->getArg(0)->getType());
352 LValue LV = CGF.MakeAddrLValue(Addr, E->getArg(0)->getType());
353 LV.setNontemporal(true);
354 CGF.EmitStoreOfScalar(Val, LV, false);
355 return nullptr;
356}
357
360
361 LValue LV = CGF.MakeAddrLValue(Addr, E->getType());
362 LV.setNontemporal(true);
363 return CGF.EmitLoadOfScalar(LV, E->getExprLoc());
364}
365
367 llvm::AtomicRMWInst::BinOp Kind,
368 const CallExpr *E) {
369 return RValue::get(MakeBinaryAtomicValue(CGF, Kind, E));
370}
371
372/// Utility to insert an atomic instruction based Intrinsic::ID and
373/// the expression node, where the return value is the result of the
374/// operation.
376 llvm::AtomicRMWInst::BinOp Kind,
377 const CallExpr *E,
378 Instruction::BinaryOps Op,
379 bool Invert = false) {
380 QualType T = E->getType();
381 assert(E->getArg(0)->getType()->isPointerType());
383 E->getArg(0)->getType()->getPointeeType()));
384 assert(CGF.getContext().hasSameUnqualifiedType(T, E->getArg(1)->getType()));
385
386 Address DestAddr = CheckAtomicAlignment(CGF, E);
387
388 llvm::IntegerType *IntType = llvm::IntegerType::get(
389 CGF.getLLVMContext(), CGF.getContext().getTypeSize(T));
390
391 llvm::Value *Val = CGF.EmitScalarExpr(E->getArg(1));
392 llvm::Type *ValueType = Val->getType();
393 Val = EmitToInt(CGF, Val, T, IntType);
394
395 llvm::Value *Result = CGF.Builder.CreateAtomicRMW(
396 Kind, DestAddr, Val, llvm::AtomicOrdering::SequentiallyConsistent);
397 Result = CGF.Builder.CreateBinOp(Op, Result, Val);
398 if (Invert)
399 Result =
400 CGF.Builder.CreateBinOp(llvm::Instruction::Xor, Result,
401 llvm::ConstantInt::getAllOnesValue(IntType));
402 Result = EmitFromInt(CGF, Result, T, ValueType);
403 return RValue::get(Result);
404}
405
406/// Utility to insert an atomic cmpxchg instruction.
407///
408/// @param CGF The current codegen function.
409/// @param E Builtin call expression to convert to cmpxchg.
410/// arg0 - address to operate on
411/// arg1 - value to compare with
412/// arg2 - new value
413/// @param ReturnBool Specifies whether to return success flag of
414/// cmpxchg result or the old value.
415///
416/// @returns result of cmpxchg, according to ReturnBool
417///
418/// Note: In order to lower Microsoft's _InterlockedCompareExchange* intrinsics
419/// invoke the function EmitAtomicCmpXchgForMSIntrin.
421 bool ReturnBool,
422 llvm::AtomicOrdering SuccessOrdering,
423 llvm::AtomicOrdering FailureOrdering) {
424 QualType T = ReturnBool ? E->getArg(1)->getType() : E->getType();
425 Address DestAddr = CheckAtomicAlignment(CGF, E);
426
427 llvm::IntegerType *IntType = llvm::IntegerType::get(
428 CGF.getLLVMContext(), CGF.getContext().getTypeSize(T));
429
430 Value *Cmp = CGF.EmitScalarExpr(E->getArg(1));
431 llvm::Type *ValueType = Cmp->getType();
432 Cmp = EmitToInt(CGF, Cmp, T, IntType);
433 Value *New = EmitToInt(CGF, CGF.EmitScalarExpr(E->getArg(2)), T, IntType);
434
436 DestAddr, Cmp, New, SuccessOrdering, FailureOrdering);
437 if (ReturnBool)
438 // Extract boolean success flag and zext it to int.
439 return CGF.Builder.CreateZExt(CGF.Builder.CreateExtractValue(Pair, 1),
440 CGF.ConvertType(E->getType()));
441 else
442 // Extract old value and emit it using the same type as compare value.
443 return EmitFromInt(CGF, CGF.Builder.CreateExtractValue(Pair, 0), T,
444 ValueType);
445}
446
447/// This function should be invoked to emit atomic cmpxchg for Microsoft's
448/// _InterlockedCompareExchange* intrinsics which have the following signature:
449/// T _InterlockedCompareExchange(T volatile *Destination,
450/// T Exchange,
451/// T Comparand);
452///
453/// Whereas the llvm 'cmpxchg' instruction has the following syntax:
454/// cmpxchg *Destination, Comparand, Exchange.
455/// So we need to swap Comparand and Exchange when invoking
456/// CreateAtomicCmpXchg. That is the reason we could not use the above utility
457/// function MakeAtomicCmpXchgValue since it expects the arguments to be
458/// already swapped.
459
460static
462 AtomicOrdering SuccessOrdering = AtomicOrdering::SequentiallyConsistent) {
463 assert(E->getArg(0)->getType()->isPointerType());
465 E->getType(), E->getArg(0)->getType()->getPointeeType()));
466 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(),
467 E->getArg(1)->getType()));
468 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(),
469 E->getArg(2)->getType()));
470
471 Address DestAddr = CheckAtomicAlignment(CGF, E);
472
473 auto *Exchange = CGF.EmitScalarExpr(E->getArg(1));
474 auto *RTy = Exchange->getType();
475
476 auto *Comparand = CGF.EmitScalarExpr(E->getArg(2));
477
478 if (RTy->isPointerTy()) {
479 Exchange = CGF.Builder.CreatePtrToInt(Exchange, CGF.IntPtrTy);
480 Comparand = CGF.Builder.CreatePtrToInt(Comparand, CGF.IntPtrTy);
481 }
482
483 // For Release ordering, the failure ordering should be Monotonic.
484 auto FailureOrdering = SuccessOrdering == AtomicOrdering::Release ?
485 AtomicOrdering::Monotonic :
486 SuccessOrdering;
487
488 // The atomic instruction is marked volatile for consistency with MSVC. This
489 // blocks the few atomics optimizations that LLVM has. If we want to optimize
490 // _Interlocked* operations in the future, we will have to remove the volatile
491 // marker.
492 auto *CmpXchg = CGF.Builder.CreateAtomicCmpXchg(
493 DestAddr, Comparand, Exchange, SuccessOrdering, FailureOrdering);
494 CmpXchg->setVolatile(true);
495
496 auto *Result = CGF.Builder.CreateExtractValue(CmpXchg, 0);
497 if (RTy->isPointerTy()) {
498 Result = CGF.Builder.CreateIntToPtr(Result, RTy);
499 }
500
501 return Result;
502}
503
504// 64-bit Microsoft platforms support 128 bit cmpxchg operations. They are
505// prototyped like this:
506//
507// unsigned char _InterlockedCompareExchange128...(
508// __int64 volatile * _Destination,
509// __int64 _ExchangeHigh,
510// __int64 _ExchangeLow,
511// __int64 * _ComparandResult);
512//
513// Note that Destination is assumed to be at least 16-byte aligned, despite
514// being typed int64.
515
517 const CallExpr *E,
518 AtomicOrdering SuccessOrdering) {
519 assert(E->getNumArgs() == 4);
520 llvm::Value *DestPtr = CGF.EmitScalarExpr(E->getArg(0));
521 llvm::Value *ExchangeHigh = CGF.EmitScalarExpr(E->getArg(1));
522 llvm::Value *ExchangeLow = CGF.EmitScalarExpr(E->getArg(2));
523 Address ComparandAddr = CGF.EmitPointerWithAlignment(E->getArg(3));
524
525 assert(DestPtr->getType()->isPointerTy());
526 assert(!ExchangeHigh->getType()->isPointerTy());
527 assert(!ExchangeLow->getType()->isPointerTy());
528
529 // For Release ordering, the failure ordering should be Monotonic.
530 auto FailureOrdering = SuccessOrdering == AtomicOrdering::Release
531 ? AtomicOrdering::Monotonic
532 : SuccessOrdering;
533
534 // Convert to i128 pointers and values. Alignment is also overridden for
535 // destination pointer.
536 llvm::Type *Int128Ty = llvm::IntegerType::get(CGF.getLLVMContext(), 128);
537 Address DestAddr(DestPtr, Int128Ty,
539 ComparandAddr = ComparandAddr.withElementType(Int128Ty);
540
541 // (((i128)hi) << 64) | ((i128)lo)
542 ExchangeHigh = CGF.Builder.CreateZExt(ExchangeHigh, Int128Ty);
543 ExchangeLow = CGF.Builder.CreateZExt(ExchangeLow, Int128Ty);
544 ExchangeHigh =
545 CGF.Builder.CreateShl(ExchangeHigh, llvm::ConstantInt::get(Int128Ty, 64));
546 llvm::Value *Exchange = CGF.Builder.CreateOr(ExchangeHigh, ExchangeLow);
547
548 // Load the comparand for the instruction.
549 llvm::Value *Comparand = CGF.Builder.CreateLoad(ComparandAddr);
550
551 auto *CXI = CGF.Builder.CreateAtomicCmpXchg(DestAddr, Comparand, Exchange,
552 SuccessOrdering, FailureOrdering);
553
554 // The atomic instruction is marked volatile for consistency with MSVC. This
555 // blocks the few atomics optimizations that LLVM has. If we want to optimize
556 // _Interlocked* operations in the future, we will have to remove the volatile
557 // marker.
558 CXI->setVolatile(true);
559
560 // Store the result as an outparameter.
561 CGF.Builder.CreateStore(CGF.Builder.CreateExtractValue(CXI, 0),
562 ComparandAddr);
563
564 // Get the success boolean and zero extend it to i8.
565 Value *Success = CGF.Builder.CreateExtractValue(CXI, 1);
566 return CGF.Builder.CreateZExt(Success, CGF.Int8Ty);
567}
568
570 AtomicOrdering Ordering = AtomicOrdering::SequentiallyConsistent) {
571 assert(E->getArg(0)->getType()->isPointerType());
572
573 auto *IntTy = CGF.ConvertType(E->getType());
574 Address DestAddr = CheckAtomicAlignment(CGF, E);
575 auto *Result = CGF.Builder.CreateAtomicRMW(
576 AtomicRMWInst::Add, DestAddr, ConstantInt::get(IntTy, 1), Ordering);
577 return CGF.Builder.CreateAdd(Result, ConstantInt::get(IntTy, 1));
578}
579
581 CodeGenFunction &CGF, const CallExpr *E,
582 AtomicOrdering Ordering = AtomicOrdering::SequentiallyConsistent) {
583 assert(E->getArg(0)->getType()->isPointerType());
584
585 auto *IntTy = CGF.ConvertType(E->getType());
586 Address DestAddr = CheckAtomicAlignment(CGF, E);
587 auto *Result = CGF.Builder.CreateAtomicRMW(
588 AtomicRMWInst::Sub, DestAddr, ConstantInt::get(IntTy, 1), Ordering);
589 return CGF.Builder.CreateSub(Result, ConstantInt::get(IntTy, 1));
590}
591
592// Build a plain volatile load.
594 Value *Ptr = CGF.EmitScalarExpr(E->getArg(0));
595 QualType ElTy = E->getArg(0)->getType()->getPointeeType();
596 CharUnits LoadSize = CGF.getContext().getTypeSizeInChars(ElTy);
597 llvm::Type *ITy =
598 llvm::IntegerType::get(CGF.getLLVMContext(), LoadSize.getQuantity() * 8);
599 llvm::LoadInst *Load = CGF.Builder.CreateAlignedLoad(ITy, Ptr, LoadSize);
600 Load->setAtomic(llvm::AtomicOrdering::Monotonic);
601 Load->setVolatile(true);
602 return Load;
603}
604
605// Build a plain volatile store.
607 Value *Ptr = CGF.EmitScalarExpr(E->getArg(0));
608 Value *Value = CGF.EmitScalarExpr(E->getArg(1));
609 QualType ElTy = E->getArg(0)->getType()->getPointeeType();
610 CharUnits StoreSize = CGF.getContext().getTypeSizeInChars(ElTy);
611 llvm::StoreInst *Store =
612 CGF.Builder.CreateAlignedStore(Value, Ptr, StoreSize);
613 Store->setAtomic(llvm::AtomicOrdering::Monotonic);
614 Store->setVolatile(true);
615 return Store;
616}
617
618// Emit a simple mangled intrinsic that has 1 argument and a return type
619// matching the argument type. Depending on mode, this may be a constrained
620// floating-point intrinsic.
622 const CallExpr *E, unsigned IntrinsicID,
623 unsigned ConstrainedIntrinsicID) {
624 llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
625
626 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
627 if (CGF.Builder.getIsFPConstrained()) {
628 Function *F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID, Src0->getType());
629 return CGF.Builder.CreateConstrainedFPCall(F, { Src0 });
630 } else {
631 Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
632 return CGF.Builder.CreateCall(F, Src0);
633 }
634}
635
636// Emit an intrinsic that has 2 operands of the same type as its result.
637// Depending on mode, this may be a constrained floating-point intrinsic.
639 const CallExpr *E, unsigned IntrinsicID,
640 unsigned ConstrainedIntrinsicID) {
641 llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
642 llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1));
643
644 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
645 if (CGF.Builder.getIsFPConstrained()) {
646 Function *F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID, Src0->getType());
647 return CGF.Builder.CreateConstrainedFPCall(F, { Src0, Src1 });
648 } else {
649 Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
650 return CGF.Builder.CreateCall(F, { Src0, Src1 });
651 }
652}
653
654// Has second type mangled argument.
655static Value *
657 Intrinsic::ID IntrinsicID,
658 Intrinsic::ID ConstrainedIntrinsicID) {
659 llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
660 llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1));
661
662 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
663 if (CGF.Builder.getIsFPConstrained()) {
664 Function *F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID,
665 {Src0->getType(), Src1->getType()});
666 return CGF.Builder.CreateConstrainedFPCall(F, {Src0, Src1});
667 }
668
669 Function *F =
670 CGF.CGM.getIntrinsic(IntrinsicID, {Src0->getType(), Src1->getType()});
671 return CGF.Builder.CreateCall(F, {Src0, Src1});
672}
673
674// Emit an intrinsic that has 3 operands of the same type as its result.
675// Depending on mode, this may be a constrained floating-point intrinsic.
677 const CallExpr *E, unsigned IntrinsicID,
678 unsigned ConstrainedIntrinsicID) {
679 llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
680 llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1));
681 llvm::Value *Src2 = CGF.EmitScalarExpr(E->getArg(2));
682
683 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
684 if (CGF.Builder.getIsFPConstrained()) {
685 Function *F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID, Src0->getType());
686 return CGF.Builder.CreateConstrainedFPCall(F, { Src0, Src1, Src2 });
687 } else {
688 Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType());
689 return CGF.Builder.CreateCall(F, { Src0, Src1, Src2 });
690 }
691}
692
693// Emit an intrinsic that has overloaded integer result and fp operand.
694static Value *
696 unsigned IntrinsicID,
697 unsigned ConstrainedIntrinsicID) {
698 llvm::Type *ResultType = CGF.ConvertType(E->getType());
699 llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
700
701 if (CGF.Builder.getIsFPConstrained()) {
702 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
703 Function *F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID,
704 {ResultType, Src0->getType()});
705 return CGF.Builder.CreateConstrainedFPCall(F, {Src0});
706 } else {
707 Function *F =
708 CGF.CGM.getIntrinsic(IntrinsicID, {ResultType, Src0->getType()});
709 return CGF.Builder.CreateCall(F, Src0);
710 }
711}
712
714 Intrinsic::ID IntrinsicID) {
715 llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0));
716 llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1));
717
718 QualType IntPtrTy = E->getArg(1)->getType()->getPointeeType();
719 llvm::Type *IntTy = CGF.ConvertType(IntPtrTy);
720 llvm::Function *F =
721 CGF.CGM.getIntrinsic(IntrinsicID, {Src0->getType(), IntTy});
722 llvm::Value *Call = CGF.Builder.CreateCall(F, Src0);
723
724 llvm::Value *Exp = CGF.Builder.CreateExtractValue(Call, 1);
725 LValue LV = CGF.MakeNaturalAlignAddrLValue(Src1, IntPtrTy);
726 CGF.EmitStoreOfScalar(Exp, LV);
727
728 return CGF.Builder.CreateExtractValue(Call, 0);
729}
730
731static void emitSincosBuiltin(CodeGenFunction &CGF, const CallExpr *E,
732 Intrinsic::ID IntrinsicID) {
733 llvm::Value *Val = CGF.EmitScalarExpr(E->getArg(0));
734 llvm::Value *Dest0 = CGF.EmitScalarExpr(E->getArg(1));
735 llvm::Value *Dest1 = CGF.EmitScalarExpr(E->getArg(2));
736
737 llvm::Function *F = CGF.CGM.getIntrinsic(IntrinsicID, {Val->getType()});
738 llvm::Value *Call = CGF.Builder.CreateCall(F, Val);
739
740 llvm::Value *SinResult = CGF.Builder.CreateExtractValue(Call, 0);
741 llvm::Value *CosResult = CGF.Builder.CreateExtractValue(Call, 1);
742
743 QualType DestPtrType = E->getArg(1)->getType()->getPointeeType();
744 LValue SinLV = CGF.MakeNaturalAlignAddrLValue(Dest0, DestPtrType);
745 LValue CosLV = CGF.MakeNaturalAlignAddrLValue(Dest1, DestPtrType);
746
747 llvm::StoreInst *StoreSin =
748 CGF.Builder.CreateStore(SinResult, SinLV.getAddress());
749 llvm::StoreInst *StoreCos =
750 CGF.Builder.CreateStore(CosResult, CosLV.getAddress());
751
752 // Mark the two stores as non-aliasing with each other. The order of stores
753 // emitted by this builtin is arbitrary, enforcing a particular order will
754 // prevent optimizations later on.
755 llvm::MDBuilder MDHelper(CGF.getLLVMContext());
756 MDNode *Domain = MDHelper.createAnonymousAliasScopeDomain();
757 MDNode *AliasScope = MDHelper.createAnonymousAliasScope(Domain);
758 MDNode *AliasScopeList = MDNode::get(Call->getContext(), AliasScope);
759 StoreSin->setMetadata(LLVMContext::MD_alias_scope, AliasScopeList);
760 StoreCos->setMetadata(LLVMContext::MD_noalias, AliasScopeList);
761}
762
763static llvm::Value *emitModfBuiltin(CodeGenFunction &CGF, const CallExpr *E,
764 Intrinsic::ID IntrinsicID) {
765 llvm::Value *Val = CGF.EmitScalarExpr(E->getArg(0));
766 llvm::Value *IntPartDest = CGF.EmitScalarExpr(E->getArg(1));
767
768 llvm::Value *Call =
769 CGF.Builder.CreateIntrinsic(IntrinsicID, {Val->getType()}, Val);
770
771 llvm::Value *FractionalResult = CGF.Builder.CreateExtractValue(Call, 0);
772 llvm::Value *IntegralResult = CGF.Builder.CreateExtractValue(Call, 1);
773
774 QualType DestPtrType = E->getArg(1)->getType()->getPointeeType();
775 LValue IntegralLV = CGF.MakeNaturalAlignAddrLValue(IntPartDest, DestPtrType);
776 CGF.EmitStoreOfScalar(IntegralResult, IntegralLV);
777
778 return FractionalResult;
779}
780
781/// EmitFAbs - Emit a call to @llvm.fabs().
783 llvm::Value *Call = CGF.Builder.CreateFAbs(V);
784 if (auto *CallI = dyn_cast<llvm::CallInst>(Call))
785 CallI->setDoesNotAccessMemory();
786 return Call;
787}
788
789/// Emit the computation of the sign bit for a floating point value. Returns
790/// the i1 sign bit value.
792 LLVMContext &C = CGF.CGM.getLLVMContext();
793
794 llvm::Type *Ty = V->getType();
795 int Width = Ty->getPrimitiveSizeInBits();
796 llvm::Type *IntTy = llvm::IntegerType::get(C, Width);
797 V = CGF.Builder.CreateBitCast(V, IntTy);
798 if (Ty->isPPC_FP128Ty()) {
799 // We want the sign bit of the higher-order double. The bitcast we just
800 // did works as if the double-double was stored to memory and then
801 // read as an i128. The "store" will put the higher-order double in the
802 // lower address in both little- and big-Endian modes, but the "load"
803 // will treat those bits as a different part of the i128: the low bits in
804 // little-Endian, the high bits in big-Endian. Therefore, on big-Endian
805 // we need to shift the high bits down to the low before truncating.
806 Width >>= 1;
807 if (CGF.getTarget().isBigEndian()) {
808 Value *ShiftCst = llvm::ConstantInt::get(IntTy, Width);
809 V = CGF.Builder.CreateLShr(V, ShiftCst);
810 }
811 // We are truncating value in order to extract the higher-order
812 // double, which we will be using to extract the sign from.
813 IntTy = llvm::IntegerType::get(C, Width);
814 V = CGF.Builder.CreateTrunc(V, IntTy);
815 }
816 Value *Zero = llvm::Constant::getNullValue(IntTy);
817 return CGF.Builder.CreateICmpSLT(V, Zero);
818}
819
821 const CallExpr *E, llvm::Constant *calleeValue) {
822 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
823 CGCallee callee = CGCallee::forDirect(calleeValue, GlobalDecl(FD));
824 llvm::CallBase *callOrInvoke = nullptr;
825 CGFunctionInfo const *FnInfo = nullptr;
826 return CGF.EmitCall(E->getCallee()->getType(), callee, E, ReturnValueSlot(),
827 /*Chain=*/nullptr, &callOrInvoke, &FnInfo);
828}
829
830/// Emit a call to llvm.{sadd,uadd,ssub,usub,smul,umul}.with.overflow.*
831/// depending on IntrinsicID.
832///
833/// \arg CGF The current codegen function.
834/// \arg IntrinsicID The ID for the Intrinsic we wish to generate.
835/// \arg X The first argument to the llvm.*.with.overflow.*.
836/// \arg Y The second argument to the llvm.*.with.overflow.*.
837/// \arg Carry The carry returned by the llvm.*.with.overflow.*.
838/// \returns The result (i.e. sum/product) returned by the intrinsic.
840 const Intrinsic::ID IntrinsicID,
841 llvm::Value *X, llvm::Value *Y,
842 llvm::Value *&Carry) {
843 // Make sure we have integers of the same width.
844 assert(X->getType() == Y->getType() &&
845 "Arguments must be the same type. (Did you forget to make sure both "
846 "arguments have the same integer width?)");
847
848 Function *Callee = CGF.CGM.getIntrinsic(IntrinsicID, X->getType());
849 llvm::Value *Tmp = CGF.Builder.CreateCall(Callee, {X, Y});
850 Carry = CGF.Builder.CreateExtractValue(Tmp, 1);
851 return CGF.Builder.CreateExtractValue(Tmp, 0);
852}
853
854namespace {
855 struct WidthAndSignedness {
856 unsigned Width;
857 bool Signed;
858 };
859}
860
861static WidthAndSignedness
863 const clang::QualType Type) {
864 assert(Type->isIntegerType() && "Given type is not an integer.");
865 unsigned Width = context.getIntWidth(Type);
867 return {Width, Signed};
868}
869
870// Given one or more integer types, this function produces an integer type that
871// encompasses them: any value in one of the given types could be expressed in
872// the encompassing type.
873static struct WidthAndSignedness
874EncompassingIntegerType(ArrayRef<struct WidthAndSignedness> Types) {
875 assert(Types.size() > 0 && "Empty list of types.");
876
877 // If any of the given types is signed, we must return a signed type.
878 bool Signed = false;
879 for (const auto &Type : Types) {
880 Signed |= Type.Signed;
881 }
882
883 // The encompassing type must have a width greater than or equal to the width
884 // of the specified types. Additionally, if the encompassing type is signed,
885 // its width must be strictly greater than the width of any unsigned types
886 // given.
887 unsigned Width = 0;
888 for (const auto &Type : Types) {
889 unsigned MinWidth = Type.Width + (Signed && !Type.Signed);
890 if (Width < MinWidth) {
891 Width = MinWidth;
892 }
893 }
894
895 return {Width, Signed};
896}
897
898Value *CodeGenFunction::EmitVAStartEnd(Value *ArgValue, bool IsStart) {
899 Intrinsic::ID inst = IsStart ? Intrinsic::vastart : Intrinsic::vaend;
900 return Builder.CreateCall(CGM.getIntrinsic(inst, {ArgValue->getType()}),
901 ArgValue);
902}
903
904/// Checks if using the result of __builtin_object_size(p, @p From) in place of
905/// __builtin_object_size(p, @p To) is correct
906static bool areBOSTypesCompatible(int From, int To) {
907 // Note: Our __builtin_object_size implementation currently treats Type=0 and
908 // Type=2 identically. Encoding this implementation detail here may make
909 // improving __builtin_object_size difficult in the future, so it's omitted.
910 return From == To || (From == 0 && To == 1) || (From == 3 && To == 2);
911}
912
913static llvm::Value *
914getDefaultBuiltinObjectSizeResult(unsigned Type, llvm::IntegerType *ResType) {
915 return ConstantInt::get(ResType, (Type & 2) ? 0 : -1, /*isSigned=*/true);
916}
917
918llvm::Value *
919CodeGenFunction::evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type,
920 llvm::IntegerType *ResType,
921 llvm::Value *EmittedE,
922 bool IsDynamic) {
923 if (std::optional<uint64_t> ObjectSize =
925 return ConstantInt::get(ResType, *ObjectSize, /*isSigned=*/true);
926 return emitBuiltinObjectSize(E, Type, ResType, EmittedE, IsDynamic);
927}
928
929/// Find a struct's flexible array member. It may be embedded inside multiple
930/// sub-structs, but must still be the last field.
932 ASTContext &Ctx,
933 const RecordDecl *RD) {
934 const LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
935 CGF.getLangOpts().getStrictFlexArraysLevel();
936
937 if (RD->isImplicit())
938 return nullptr;
939
940 for (const FieldDecl *FD : RD->fields()) {
942 Ctx, FD, FD->getType(), StrictFlexArraysLevel,
943 /*IgnoreTemplateOrMacroSubstitution=*/true))
944 return FD;
945
946 if (const auto *RD = FD->getType()->getAsRecordDecl())
947 if (const FieldDecl *FD = FindFlexibleArrayMemberField(CGF, Ctx, RD))
948 return FD;
949 }
950
951 return nullptr;
952}
953
954/// Calculate the offset of a struct field. It may be embedded inside multiple
955/// sub-structs.
956static bool GetFieldOffset(ASTContext &Ctx, const RecordDecl *RD,
957 const FieldDecl *FD, int64_t &Offset) {
958 if (RD->isImplicit())
959 return false;
960
961 // Keep track of the field number ourselves, because the other methods
962 // (CGRecordLayout::getLLVMFieldNo) aren't always equivalent to how the AST
963 // is laid out.
964 uint32_t FieldNo = 0;
965 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(RD);
966
967 for (const FieldDecl *Field : RD->fields()) {
968 if (Field == FD) {
969 Offset += Layout.getFieldOffset(FieldNo);
970 return true;
971 }
972
973 if (const auto *RD = Field->getType()->getAsRecordDecl()) {
974 if (GetFieldOffset(Ctx, RD, FD, Offset)) {
975 Offset += Layout.getFieldOffset(FieldNo);
976 return true;
977 }
978 }
979
980 if (!RD->isUnion())
981 ++FieldNo;
982 }
983
984 return false;
985}
986
987static std::optional<int64_t>
988GetFieldOffset(ASTContext &Ctx, const RecordDecl *RD, const FieldDecl *FD) {
989 int64_t Offset = 0;
990
991 if (GetFieldOffset(Ctx, RD, FD, Offset))
992 return std::optional<int64_t>(Offset);
993
994 return std::nullopt;
995}
996
997llvm::Value *CodeGenFunction::emitCountedBySize(const Expr *E,
998 llvm::Value *EmittedE,
999 unsigned Type,
1000 llvm::IntegerType *ResType) {
1001 // Note: If the whole struct is specificed in the __bdos (i.e. Visitor
1002 // returns a DeclRefExpr). The calculation of the whole size of the structure
1003 // with a flexible array member can be done in two ways:
1004 //
1005 // 1) sizeof(struct S) + count * sizeof(typeof(fam))
1006 // 2) offsetof(struct S, fam) + count * sizeof(typeof(fam))
1007 //
1008 // The first will add additional padding after the end of the array
1009 // allocation while the second method is more precise, but not quite expected
1010 // from programmers. See
1011 // https://lore.kernel.org/lkml/ZvV6X5FPBBW7CO1f@archlinux/ for a discussion
1012 // of the topic.
1013 //
1014 // GCC isn't (currently) able to calculate __bdos on a pointer to the whole
1015 // structure. Therefore, because of the above issue, we choose to match what
1016 // GCC does for consistency's sake.
1017
1018 const Expr *Idx = nullptr;
1019 // FIXME: `ArrayElementTy` is misleadingly named. `findStructFieldAccess()`
1020 // sets it to the type of the array-subscript base, i.e. the (possibly cast)
1021 // *pointer* being indexed (not an element type) or a null QualType when there
1022 // is no subscript.
1023 QualType ArrayElementTy;
1024 E = findStructFieldAccess(E, &Idx, &ArrayElementTy);
1025 if (!E)
1026 return nullptr;
1027
1028 if (Idx) {
1029 if (Idx->HasSideEffects(getContext()))
1030 // We can't have side-effects.
1031 return getDefaultBuiltinObjectSizeResult(Type, ResType);
1032
1033 if (const auto *IL = dyn_cast<IntegerLiteral>(Idx)) {
1034 int64_t Val = IL->getValue().getSExtValue();
1035 if (Val < 0)
1036 return getDefaultBuiltinObjectSizeResult(Type, ResType);
1037
1038 // The index is 0, so we don't need to take it into account.
1039 if (Val == 0)
1040 Idx = nullptr;
1041 }
1042 }
1043
1044 // __counted_by on either a flexible array member or a pointer into a struct
1045 // with a flexible array member.
1046 if (const auto *ME = dyn_cast<MemberExpr>(E))
1047 return emitCountedByMemberSize(ME, Idx, EmittedE, ArrayElementTy, Type,
1048 ResType);
1049
1050 // __counted_by on a pointer in a struct.
1051 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
1052 ICE && ICE->getCastKind() == CK_LValueToRValue)
1053 return emitCountedByPointerSize(ICE, Idx, EmittedE, ArrayElementTy, Type,
1054 ResType);
1055
1056 return nullptr;
1057}
1058
1060 llvm::Value *Res,
1061 llvm::Value *Index,
1062 llvm::IntegerType *ResType,
1063 bool IsSigned) {
1064 // cmp = (array_size >= 0)
1065 Value *Cmp = CGF.Builder.CreateIsNotNeg(Res);
1066 if (Index)
1067 // cmp = (cmp && index >= 0)
1068 Cmp = CGF.Builder.CreateAnd(CGF.Builder.CreateIsNotNeg(Index), Cmp);
1069
1070 // return cmp ? result : 0
1071 return CGF.Builder.CreateSelect(Cmp, Res,
1072 ConstantInt::get(ResType, 0, IsSigned));
1073}
1074
1075static std::pair<llvm::Value *, llvm::Value *>
1077 const FieldDecl *ArrayFD, const FieldDecl *CountFD,
1078 const Expr *Idx, llvm::IntegerType *ResType,
1079 bool IsSigned) {
1080 // count = ptr->count;
1081 Value *Count = CGF.EmitLoadOfCountedByField(ME, ArrayFD, CountFD);
1082 if (!Count)
1083 return std::make_pair<Value *>(nullptr, nullptr);
1084 Count = CGF.Builder.CreateIntCast(Count, ResType, IsSigned, "count");
1085
1086 // index = idx;
1087 Value *Index = nullptr;
1088 if (Idx) {
1089 bool IdxSigned = Idx->getType()->isSignedIntegerType();
1090 Index = CGF.EmitScalarExpr(Idx);
1091 Index = CGF.Builder.CreateIntCast(Index, ResType, IdxSigned, "index");
1092 }
1093
1094 return std::make_pair(Count, Index);
1095}
1096
1097llvm::Value *CodeGenFunction::emitCountedByPointerSize(
1098 const ImplicitCastExpr *E, const Expr *Idx, llvm::Value *EmittedE,
1099 QualType CastedArrayElementTy, unsigned Type, llvm::IntegerType *ResType) {
1100 assert(E->getCastKind() == CK_LValueToRValue &&
1101 "must be an LValue to RValue cast");
1102 assert(EmittedE && "emitted must not be null");
1103
1104 const MemberExpr *ME =
1105 dyn_cast<MemberExpr>(E->getSubExpr()->IgnoreParenNoopCasts(getContext()));
1106 if (!ME)
1107 return nullptr;
1108
1109 const auto *ArrayBaseFD = dyn_cast<FieldDecl>(ME->getMemberDecl());
1110 if (!ArrayBaseFD || !ArrayBaseFD->getType()->isPointerType() ||
1111 !ArrayBaseFD->getType()->isCountAttributedType())
1112 return nullptr;
1113
1114 // Get the 'count' FieldDecl.
1115 const FieldDecl *CountFD = ArrayBaseFD->findCountedByField();
1116 if (!CountFD)
1117 // Can't find the field referenced by the "counted_by" attribute.
1118 return nullptr;
1119
1120 // Calculate the array's object size using these formulae. (Note: if the
1121 // calculation is negative, we return 0.):
1122 //
1123 // struct p;
1124 // struct s {
1125 // /* ... */
1126 // struct p **array __attribute__((ATTR(count)));
1127 // int count;
1128 // };
1129 //
1130 // 1) 'ptr->array':
1131 //
1132 // #if ATTR is counted_by_or_null || ATTR is sized_by_or_null
1133 // count = ptr->array ? ptr->count : 0;
1134 // #else
1135 // count = ptr->count;
1136 // #endif
1137 //
1138 // #if ATTR is counted_by || ATTR is counted_by_or_null
1139 // array_element_size = sizeof (*ptr->array);
1140 // array_size = count * array_element_size;
1141 // #else
1142 // array_size = count;
1143 // #endif
1144 //
1145 // result = array_size;
1146 //
1147 // cmp = (result >= 0)
1148 // return cmp ? result : 0;
1149 //
1150 // 2) '&((cast) ptr->array)[idx]':
1151 //
1152 // #if ATTR is counted_by_or_null || ATTR is sized_by_or_null
1153 // count = ptr->array ? ptr->count : 0;
1154 // #else
1155 // count = ptr->count;
1156 // #endif
1157 // index = idx;
1158 //
1159 // #if ATTR is counted_by || ATTR is counted_by_or_null
1160 // array_element_size = sizeof (*ptr->array);
1161 // array_size = count * array_element_size;
1162 // #else
1163 // array_size = count;
1164 // #endif
1165 //
1166 // casted_array_element_size = sizeof (*((cast) ptr->array));
1167 //
1168 // index_size = index * casted_array_element_size;
1169 // result = array_size - index_size;
1170 //
1171 // cmp = (result >= 0)
1172 // if (index)
1173 // cmp = (cmp && index > 0)
1174 // return cmp ? result : 0;
1175
1176 auto GetPointeeSize = [&](QualType PtrTy) -> CharUnits {
1177 assert(!PtrTy.isNull());
1178 QualType PointeeTy = PtrTy->getPointeeType();
1179 assert(!PointeeTy.isNull() &&
1180 (PointeeTy->isVoidType() || !PointeeTy->isIncompleteType()) &&
1181 "pointee type must have a computable size");
1182
1183 CharUnits PointeeSize = getContext().getTypeSizeInChars(PointeeTy);
1184 if (PointeeSize.isZero()) {
1185 // Support GNU extension of treating `void` having size 1.
1186 PointeeSize = CharUnits::One();
1187 }
1188
1189 return PointeeSize;
1190 };
1191
1192 bool IsSigned = CountFD->getType()->isSignedIntegerType();
1193 const auto *CountAttributedTy =
1194 ArrayBaseFD->getType()->getAs<CountAttributedType>();
1195 assert(CountAttributedTy && "the field's type is not a CountAttributedType");
1196
1197 // count = ptr->count;
1198 // index = idx;
1199 Value *Count, *Index;
1200 std::tie(Count, Index) = GetCountFieldAndIndex(
1201 *this, ME, ArrayBaseFD, CountFD, Idx, ResType, IsSigned);
1202 if (!Count)
1203 return nullptr;
1204
1205 // For the _or_null variants, a null pointer describes no accessible memory:
1206 // count = ptr->array ? count : 0;
1207 if (CountAttributedTy->isOrNull()) {
1208 Value *Ptr = nullptr;
1209 if (!Idx) {
1210 // 1) 'ptr->array'
1211 // Reuse the already-emitted pointer value rather than re-loading `ME`.
1212 // Re-loading would produce a second, observable access for a volatile
1213 // pointer field
1214 Ptr = EmittedE;
1215 } else {
1216 // 2) '&((cast) ptr->array)[idx]'
1217 // FIXME: `EmittedE` is the element address, not `ptr->array`, so we fall
1218 // back to re-emitting `ME` and the pointer field is loaded twice. This is
1219 // normally harmless except when the pointer is `volatile`. Avoiding that
1220 // would require restructuring how the base pointer is emitted (it is
1221 // handled elsewhere in the callstack), so it is left as-is for now.
1222 Ptr = EmitScalarExpr(ME);
1223 }
1224 Value *IsNull = Builder.CreateIsNull(Ptr);
1225 Count = Builder.CreateSelect(IsNull, ConstantInt::get(ResType, 0, IsSigned),
1226 Count, "count.or.null");
1227 }
1228
1229 // #if ATTR is counted_by || ATTR is counted_by_or_null
1230 // array_element_size = sizeof (*ptr->array);
1231 // array_size = count * array_element_size;
1232 // #else
1233 // array_size = count;
1234 // #endif
1235 Value *ArraySize;
1236 if (!CountAttributedTy->isCountInBytes()) {
1237 // `__counted_by`/`__counted_by_or_null` require a complete pointee at use
1238 // sites (enforced by Sema) so the element size is computable.
1239 CharUnits ArrayElementBaseSize = GetPointeeSize(ArrayBaseFD->getType());
1240
1241 // array_element_size = sizeof (*ptr->array)
1242 auto *ArrayElementSize = llvm::ConstantInt::get(
1243 ResType, ArrayElementBaseSize.getQuantity(), IsSigned);
1244
1245 // array_size = count * array_element_size;
1246 ArraySize = Builder.CreateMul(Count, ArrayElementSize, "array_size",
1247 !IsSigned, IsSigned);
1248 } else {
1249 // array_size = count;
1250 ArraySize = Count;
1251 }
1252
1253 // Option (1) 'ptr->array'
1254 // result = array_size
1255 Value *Result = ArraySize;
1256
1257 if (Idx) { // Option (2) '&((cast) ptr->array)[idx]'
1258 // FIXME: CastedArrayElementTy is confusingly named. It's actually the base
1259 // expression of the ArraySubscriptExpr, not the element (pointee) type.
1260 CharUnits CastedArrayElementSizeInChars =
1261 GetPointeeSize(CastedArrayElementTy);
1262
1263 // casted_array_element_size = sizeof (*((cast) ptr->array));
1264 auto *CastedArrayElementSize = llvm::ConstantInt::get(
1265 ResType, CastedArrayElementSizeInChars.getQuantity(), IsSigned);
1266
1267 // index_size = index * casted_array_element_size;
1268 Value *IndexSize = Builder.CreateMul(Index, CastedArrayElementSize,
1269 "index_size", !IsSigned, IsSigned);
1270
1271 // result = result - index_size;
1272 Result =
1273 Builder.CreateSub(Result, IndexSize, "result", !IsSigned, IsSigned);
1274 }
1275
1276 return EmitPositiveResultOrZero(*this, Result, Index, ResType, IsSigned);
1277}
1278
1279llvm::Value *CodeGenFunction::emitCountedByMemberSize(
1280 const MemberExpr *ME, const Expr *Idx, llvm::Value *EmittedE,
1281 QualType CastedArrayElementTy, unsigned Type, llvm::IntegerType *ResType) {
1282 const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
1283 if (!FD)
1284 return nullptr;
1285
1286 // Find the flexible array member and check that it has the __counted_by
1287 // attribute.
1288 ASTContext &Ctx = getContext();
1289 const RecordDecl *RD = FD->getDeclContext()->getOuterLexicalRecordContext();
1290 const FieldDecl *FlexibleArrayMemberFD = nullptr;
1291
1293 Ctx, FD, FD->getType(), getLangOpts().getStrictFlexArraysLevel(),
1294 /*IgnoreTemplateOrMacroSubstitution=*/true))
1295 FlexibleArrayMemberFD = FD;
1296 else
1297 FlexibleArrayMemberFD = FindFlexibleArrayMemberField(*this, Ctx, RD);
1298
1299 if (!FlexibleArrayMemberFD ||
1300 !FlexibleArrayMemberFD->getType()->isCountAttributedType())
1301 return nullptr;
1302
1303 // Get the 'count' FieldDecl.
1304 const FieldDecl *CountFD = FlexibleArrayMemberFD->findCountedByField();
1305 if (!CountFD)
1306 // Can't find the field referenced by the "counted_by" attribute.
1307 return nullptr;
1308
1309 // Calculate the flexible array member's object size using these formulae.
1310 // (Note: if the calculation is negative, we return 0.):
1311 //
1312 // struct p;
1313 // struct s {
1314 // /* ... */
1315 // int count;
1316 // struct p *array[] __attribute__((counted_by(count)));
1317 // };
1318 //
1319 // 1) 'ptr->array':
1320 //
1321 // count = ptr->count;
1322 //
1323 // flexible_array_member_element_size = sizeof (*ptr->array);
1324 // flexible_array_member_size =
1325 // count * flexible_array_member_element_size;
1326 //
1327 // result = flexible_array_member_size;
1328 //
1329 // cmp = (result >= 0)
1330 // return cmp ? result : 0;
1331 //
1332 // 2) '&((cast) ptr->array)[idx]':
1333 //
1334 // count = ptr->count;
1335 // index = idx;
1336 //
1337 // flexible_array_member_element_size = sizeof (*ptr->array);
1338 // flexible_array_member_size =
1339 // count * flexible_array_member_element_size;
1340 //
1341 // casted_flexible_array_member_element_size =
1342 // sizeof (*((cast) ptr->array));
1343 // index_size = index * casted_flexible_array_member_element_size;
1344 //
1345 // result = flexible_array_member_size - index_size;
1346 //
1347 // cmp = (result >= 0)
1348 // if (index != 0)
1349 // cmp = (cmp && index >= 0)
1350 // return cmp ? result : 0;
1351 //
1352 // 3) '&ptr->field':
1353 //
1354 // count = ptr->count;
1355 // sizeof_struct = sizeof (struct s);
1356 //
1357 // flexible_array_member_element_size = sizeof (*ptr->array);
1358 // flexible_array_member_size =
1359 // count * flexible_array_member_element_size;
1360 //
1361 // field_offset = offsetof (struct s, field);
1362 // offset_diff = sizeof_struct - field_offset;
1363 //
1364 // result = offset_diff + flexible_array_member_size;
1365 //
1366 // cmp = (result >= 0)
1367 // return cmp ? result : 0;
1368 //
1369 // 4) '&((cast) ptr->field_array)[idx]':
1370 //
1371 // count = ptr->count;
1372 // index = idx;
1373 // sizeof_struct = sizeof (struct s);
1374 //
1375 // flexible_array_member_element_size = sizeof (*ptr->array);
1376 // flexible_array_member_size =
1377 // count * flexible_array_member_element_size;
1378 //
1379 // casted_field_element_size = sizeof (*((cast) ptr->field_array));
1380 // field_offset = offsetof (struct s, field)
1381 // field_offset += index * casted_field_element_size;
1382 //
1383 // offset_diff = sizeof_struct - field_offset;
1384 //
1385 // result = offset_diff + flexible_array_member_size;
1386 //
1387 // cmp = (result >= 0)
1388 // if (index != 0)
1389 // cmp = (cmp && index >= 0)
1390 // return cmp ? result : 0;
1391
1392 bool IsSigned = CountFD->getType()->isSignedIntegerType();
1393
1394 QualType FlexibleArrayMemberTy = FlexibleArrayMemberFD->getType();
1395
1396 // Explicit cast because otherwise the CharWidth will promote an i32's into
1397 // u64's leading to overflows.
1398 int64_t CharWidth = static_cast<int64_t>(CGM.getContext().getCharWidth());
1399
1400 // field_offset = offsetof (struct s, field);
1401 Value *FieldOffset = nullptr;
1402 if (FlexibleArrayMemberFD != FD) {
1403 std::optional<int64_t> Offset = GetFieldOffset(Ctx, RD, FD);
1404 if (!Offset)
1405 return nullptr;
1406 FieldOffset =
1407 llvm::ConstantInt::get(ResType, *Offset / CharWidth, IsSigned);
1408 }
1409
1410 // count = ptr->count;
1411 // index = ptr->index;
1412 Value *Count, *Index;
1413 std::tie(Count, Index) = GetCountFieldAndIndex(
1414 *this, ME, FlexibleArrayMemberFD, CountFD, Idx, ResType, IsSigned);
1415 if (!Count)
1416 return nullptr;
1417
1418 // flexible_array_member_element_size = sizeof (*ptr->array);
1419 const ArrayType *ArrayTy = Ctx.getAsArrayType(FlexibleArrayMemberTy);
1420 CharUnits BaseSize = Ctx.getTypeSizeInChars(ArrayTy->getElementType());
1421 auto *FlexibleArrayMemberElementSize =
1422 llvm::ConstantInt::get(ResType, BaseSize.getQuantity(), IsSigned);
1423
1424 // flexible_array_member_size = count * flexible_array_member_element_size;
1425 Value *FlexibleArrayMemberSize =
1426 Builder.CreateMul(Count, FlexibleArrayMemberElementSize,
1427 "flexible_array_member_size", !IsSigned, IsSigned);
1428
1429 Value *Result = nullptr;
1430 if (FlexibleArrayMemberFD == FD) {
1431 if (Idx) { // Option (2) '&((cast) ptr->array)[idx]'
1432 // casted_flexible_array_member_element_size =
1433 // sizeof (*((cast) ptr->array));
1434 llvm::ConstantInt *CastedFlexibleArrayMemberElementSize =
1435 FlexibleArrayMemberElementSize;
1436 if (!CastedArrayElementTy.isNull() &&
1437 CastedArrayElementTy->isPointerType()) {
1438 CharUnits BaseSize =
1439 Ctx.getTypeSizeInChars(CastedArrayElementTy->getPointeeType());
1440 CastedFlexibleArrayMemberElementSize =
1441 llvm::ConstantInt::get(ResType, BaseSize.getQuantity(), IsSigned);
1442 }
1443
1444 // index_size = index * casted_flexible_array_member_element_size;
1445 Value *IndexSize =
1446 Builder.CreateMul(Index, CastedFlexibleArrayMemberElementSize,
1447 "index_size", !IsSigned, IsSigned);
1448
1449 // result = flexible_array_member_size - index_size;
1450 Result = Builder.CreateSub(FlexibleArrayMemberSize, IndexSize, "result",
1451 !IsSigned, IsSigned);
1452 } else { // Option (1) 'ptr->array'
1453 // result = flexible_array_member_size;
1454 Result = FlexibleArrayMemberSize;
1455 }
1456 } else {
1457 // sizeof_struct = sizeof (struct s);
1458 llvm::StructType *StructTy = getTypes().getCGRecordLayout(RD).getLLVMType();
1459 const llvm::DataLayout &Layout = CGM.getDataLayout();
1460 TypeSize Size = Layout.getTypeSizeInBits(StructTy);
1461 Value *SizeofStruct =
1462 llvm::ConstantInt::get(ResType, Size.getKnownMinValue() / CharWidth);
1463
1464 if (Idx) { // Option (4) '&((cast) ptr->field_array)[idx]'
1465 // casted_field_element_size = sizeof (*((cast) ptr->field_array));
1466 CharUnits BaseSize;
1467 if (!CastedArrayElementTy.isNull() &&
1468 CastedArrayElementTy->isPointerType()) {
1469 BaseSize =
1470 Ctx.getTypeSizeInChars(CastedArrayElementTy->getPointeeType());
1471 } else {
1472 const ArrayType *ArrayTy = Ctx.getAsArrayType(FD->getType());
1473 BaseSize = Ctx.getTypeSizeInChars(ArrayTy->getElementType());
1474 }
1475
1476 llvm::ConstantInt *CastedFieldElementSize =
1477 llvm::ConstantInt::get(ResType, BaseSize.getQuantity(), IsSigned);
1478
1479 // field_offset += index * casted_field_element_size;
1480 Value *Mul = Builder.CreateMul(Index, CastedFieldElementSize,
1481 "field_offset", !IsSigned, IsSigned);
1482 FieldOffset = Builder.CreateAdd(FieldOffset, Mul);
1483 }
1484 // Option (3) '&ptr->field', and Option (4) continuation.
1485 // offset_diff = flexible_array_member_offset - field_offset;
1486 Value *OffsetDiff = Builder.CreateSub(SizeofStruct, FieldOffset,
1487 "offset_diff", !IsSigned, IsSigned);
1488
1489 // result = offset_diff + flexible_array_member_size;
1490 Result = Builder.CreateAdd(FlexibleArrayMemberSize, OffsetDiff, "result");
1491 }
1492
1493 return EmitPositiveResultOrZero(*this, Result, Index, ResType, IsSigned);
1494}
1495
1496/// Returns a Value corresponding to the size of the given expression.
1497/// This Value may be either of the following:
1498/// - A llvm::Argument (if E is a param with the pass_object_size attribute on
1499/// it)
1500/// - A call to the @llvm.objectsize intrinsic
1501///
1502/// EmittedE is the result of emitting `E` as a scalar expr. If it's non-null
1503/// and we wouldn't otherwise try to reference a pass_object_size parameter,
1504/// we'll call @llvm.objectsize on EmittedE, rather than emitting E.
1505llvm::Value *
1506CodeGenFunction::emitBuiltinObjectSize(const Expr *E, unsigned Type,
1507 llvm::IntegerType *ResType,
1508 llvm::Value *EmittedE, bool IsDynamic) {
1509 // We need to reference an argument if the pointer is a parameter with the
1510 // pass_object_size attribute.
1511 if (auto *D = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) {
1512 auto *Param = dyn_cast<ParmVarDecl>(D->getDecl());
1513 auto *PS = D->getDecl()->getAttr<PassObjectSizeAttr>();
1514 if (Param != nullptr && PS != nullptr &&
1515 areBOSTypesCompatible(PS->getType(), Type)) {
1516 auto Iter = SizeArguments.find(Param);
1517 assert(Iter != SizeArguments.end());
1518
1519 const ImplicitParamDecl *D = Iter->second;
1520 auto DIter = LocalDeclMap.find(D);
1521 assert(DIter != LocalDeclMap.end());
1522
1523 return EmitLoadOfScalar(DIter->second, /*Volatile=*/false,
1524 getContext().getSizeType(), E->getBeginLoc());
1525 }
1526 }
1527
1528 // LLVM can't handle Type=3 appropriately, and __builtin_object_size shouldn't
1529 // evaluate E for side-effects. In either case, we shouldn't lower to
1530 // @llvm.objectsize.
1531 if (Type == 3 || (!EmittedE && E->HasSideEffects(getContext())))
1532 return getDefaultBuiltinObjectSizeResult(Type, ResType);
1533
1534 Value *Ptr = EmittedE ? EmittedE : EmitScalarExpr(E);
1535 assert(Ptr->getType()->isPointerTy() &&
1536 "Non-pointer passed to __builtin_object_size?");
1537
1538 if (IsDynamic)
1539 // Emit special code for a flexible array member with the "counted_by"
1540 // attribute.
1541 if (Value *V = emitCountedBySize(E, Ptr, Type, ResType))
1542 return V;
1543
1544 Function *F =
1545 CGM.getIntrinsic(Intrinsic::objectsize, {ResType, Ptr->getType()});
1546
1547 // LLVM only supports 0 and 2, make sure that we pass along that as a boolean.
1548 Value *Min = Builder.getInt1((Type & 2) != 0);
1549 // For GCC compatibility, __builtin_object_size treat NULL as unknown size.
1550 Value *NullIsUnknown = Builder.getTrue();
1551 Value *Dynamic = Builder.getInt1(IsDynamic);
1552 return Builder.CreateCall(F, {Ptr, Min, NullIsUnknown, Dynamic});
1553}
1554
1555namespace {
1556/// A struct to generically describe a bit test intrinsic.
1557struct BitTest {
1558 enum ActionKind : uint8_t { TestOnly, Complement, Reset, Set };
1559 enum InterlockingKind : uint8_t {
1560 Unlocked,
1561 Sequential,
1562 Acquire,
1563 Release,
1564 NoFence
1565 };
1566
1567 ActionKind Action;
1568 InterlockingKind Interlocking;
1569 bool Is64Bit;
1570
1571 static BitTest decodeBitTestBuiltin(unsigned BuiltinID);
1572};
1573
1574} // namespace
1575
1576BitTest BitTest::decodeBitTestBuiltin(unsigned BuiltinID) {
1577 switch (BuiltinID) {
1578 // Main portable variants.
1579 case Builtin::BI_bittest:
1580 return {TestOnly, Unlocked, false};
1581 case Builtin::BI_bittestandcomplement:
1582 return {Complement, Unlocked, false};
1583 case Builtin::BI_bittestandreset:
1584 return {Reset, Unlocked, false};
1585 case Builtin::BI_bittestandset:
1586 return {Set, Unlocked, false};
1587 case Builtin::BI_interlockedbittestandreset:
1588 return {Reset, Sequential, false};
1589 case Builtin::BI_interlockedbittestandset:
1590 return {Set, Sequential, false};
1591
1592 // 64-bit variants.
1593 case Builtin::BI_bittest64:
1594 return {TestOnly, Unlocked, true};
1595 case Builtin::BI_bittestandcomplement64:
1596 return {Complement, Unlocked, true};
1597 case Builtin::BI_bittestandreset64:
1598 return {Reset, Unlocked, true};
1599 case Builtin::BI_bittestandset64:
1600 return {Set, Unlocked, true};
1601 case Builtin::BI_interlockedbittestandreset64:
1602 return {Reset, Sequential, true};
1603 case Builtin::BI_interlockedbittestandset64:
1604 return {Set, Sequential, true};
1605
1606 // ARM/AArch64-specific ordering variants.
1607 case Builtin::BI_interlockedbittestandset_acq:
1608 return {Set, Acquire, false};
1609 case Builtin::BI_interlockedbittestandset_rel:
1610 return {Set, Release, false};
1611 case Builtin::BI_interlockedbittestandset_nf:
1612 return {Set, NoFence, false};
1613 case Builtin::BI_interlockedbittestandreset_acq:
1614 return {Reset, Acquire, false};
1615 case Builtin::BI_interlockedbittestandreset_rel:
1616 return {Reset, Release, false};
1617 case Builtin::BI_interlockedbittestandreset_nf:
1618 return {Reset, NoFence, false};
1619 case Builtin::BI_interlockedbittestandreset64_acq:
1620 return {Reset, Acquire, false};
1621 case Builtin::BI_interlockedbittestandreset64_rel:
1622 return {Reset, Release, false};
1623 case Builtin::BI_interlockedbittestandreset64_nf:
1624 return {Reset, NoFence, false};
1625 case Builtin::BI_interlockedbittestandset64_acq:
1626 return {Set, Acquire, false};
1627 case Builtin::BI_interlockedbittestandset64_rel:
1628 return {Set, Release, false};
1629 case Builtin::BI_interlockedbittestandset64_nf:
1630 return {Set, NoFence, false};
1631 }
1632 llvm_unreachable("expected only bittest intrinsics");
1633}
1634
1635static char bitActionToX86BTCode(BitTest::ActionKind A) {
1636 switch (A) {
1637 case BitTest::TestOnly: return '\0';
1638 case BitTest::Complement: return 'c';
1639 case BitTest::Reset: return 'r';
1640 case BitTest::Set: return 's';
1641 }
1642 llvm_unreachable("invalid action");
1643}
1644
1646 BitTest BT,
1647 const CallExpr *E, Value *BitBase,
1648 Value *BitPos) {
1649 char Action = bitActionToX86BTCode(BT.Action);
1650 char SizeSuffix = BT.Is64Bit ? 'q' : 'l';
1651
1652 // Build the assembly.
1654 raw_svector_ostream AsmOS(Asm);
1655 if (BT.Interlocking != BitTest::Unlocked)
1656 AsmOS << "lock ";
1657 AsmOS << "bt";
1658 if (Action)
1659 AsmOS << Action;
1660 AsmOS << SizeSuffix << " $2, ($1)";
1661
1662 // Build the constraints. FIXME: We should support immediates when possible.
1663 std::string Constraints = "={@ccc},r,r,~{cc},~{memory}";
1664 std::string_view MachineClobbers = CGF.getTarget().getClobbers();
1665 if (!MachineClobbers.empty()) {
1666 Constraints += ',';
1667 Constraints += MachineClobbers;
1668 }
1669 llvm::IntegerType *IntType = llvm::IntegerType::get(
1670 CGF.getLLVMContext(),
1671 CGF.getContext().getTypeSize(E->getArg(1)->getType()));
1672 llvm::FunctionType *FTy =
1673 llvm::FunctionType::get(CGF.Int8Ty, {CGF.DefaultPtrTy, IntType}, false);
1674
1675 llvm::InlineAsm *IA =
1676 llvm::InlineAsm::get(FTy, Asm, Constraints, /*hasSideEffects=*/true);
1677 return CGF.Builder.CreateCall(IA, {BitBase, BitPos});
1678}
1679
1680static llvm::AtomicOrdering
1681getBitTestAtomicOrdering(BitTest::InterlockingKind I) {
1682 switch (I) {
1683 case BitTest::Unlocked: return llvm::AtomicOrdering::NotAtomic;
1684 case BitTest::Sequential: return llvm::AtomicOrdering::SequentiallyConsistent;
1685 case BitTest::Acquire: return llvm::AtomicOrdering::Acquire;
1686 case BitTest::Release: return llvm::AtomicOrdering::Release;
1687 case BitTest::NoFence: return llvm::AtomicOrdering::Monotonic;
1688 }
1689 llvm_unreachable("invalid interlocking");
1690}
1691
1692static llvm::Value *EmitBitCountExpr(CodeGenFunction &CGF, const Expr *E) {
1693 llvm::Value *ArgValue = CGF.EmitScalarExpr(E);
1694 llvm::Type *ArgType = ArgValue->getType();
1695
1696 // Boolean vectors can be casted directly to its bitfield representation. We
1697 // intentionally do not round up to the next power of two size and let LLVM
1698 // handle the trailing bits.
1699 //
1700 // In big endian mode, the bitfield representation has a reversed bit order,
1701 // hence the need to add an operation to reverse it back to the expected
1702 // order.
1703 if (auto *VT = dyn_cast<llvm::FixedVectorType>(ArgType);
1704 VT && VT->getElementType()->isIntegerTy(1)) {
1705 llvm::Type *StorageType =
1706 llvm::Type::getIntNTy(CGF.getLLVMContext(), VT->getNumElements());
1707 ArgValue = CGF.Builder.CreateBitCast(ArgValue, StorageType);
1708
1709 if (CGF.getTarget().isBigEndian())
1710 ArgValue = CGF.Builder.CreateIntrinsic(Intrinsic::bitreverse,
1711 {StorageType}, ArgValue);
1712 }
1713
1714 return ArgValue;
1715}
1716
1717/// Emit a _bittest* intrinsic. These intrinsics take a pointer to an array of
1718/// bits and a bit position and read and optionally modify the bit at that
1719/// position. The position index can be arbitrarily large, i.e. it can be larger
1720/// than 31 or 63, so we need an indexed load in the general case.
1721static llvm::Value *EmitBitTestIntrinsic(CodeGenFunction &CGF,
1722 unsigned BuiltinID,
1723 const CallExpr *E) {
1724 Value *BitBase = CGF.EmitScalarExpr(E->getArg(0));
1725 Value *BitPos = CGF.EmitScalarExpr(E->getArg(1));
1726
1727 BitTest BT = BitTest::decodeBitTestBuiltin(BuiltinID);
1728
1729 // X86 has special BT, BTC, BTR, and BTS instructions that handle the array
1730 // indexing operation internally. Use them if possible.
1731 if (CGF.getTarget().getTriple().isX86())
1732 return EmitX86BitTestIntrinsic(CGF, BT, E, BitBase, BitPos);
1733
1734 // Otherwise, use generic code to load one byte and test the bit. Use all but
1735 // the bottom three bits as the array index, and the bottom three bits to form
1736 // a mask.
1737 // Bit = BitBaseI8[BitPos >> 3] & (1 << (BitPos & 0x7)) != 0;
1738 Value *ByteIndex = CGF.Builder.CreateAShr(
1739 BitPos, llvm::ConstantInt::get(BitPos->getType(), 3), "bittest.byteidx");
1740 Address ByteAddr(CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, BitBase, ByteIndex,
1741 "bittest.byteaddr"),
1742 CGF.Int8Ty, CharUnits::One());
1743 Value *PosLow =
1744 CGF.Builder.CreateAnd(CGF.Builder.CreateTrunc(BitPos, CGF.Int8Ty),
1745 llvm::ConstantInt::get(CGF.Int8Ty, 0x7));
1746
1747 // The updating instructions will need a mask.
1748 Value *Mask = nullptr;
1749 if (BT.Action != BitTest::TestOnly) {
1750 Mask = CGF.Builder.CreateShl(llvm::ConstantInt::get(CGF.Int8Ty, 1), PosLow,
1751 "bittest.mask");
1752 }
1753
1754 // Check the action and ordering of the interlocked intrinsics.
1755 llvm::AtomicOrdering Ordering = getBitTestAtomicOrdering(BT.Interlocking);
1756
1757 Value *OldByte = nullptr;
1758 if (Ordering != llvm::AtomicOrdering::NotAtomic) {
1759 // Emit a combined atomicrmw load/store operation for the interlocked
1760 // intrinsics.
1761 llvm::AtomicRMWInst::BinOp RMWOp = llvm::AtomicRMWInst::Or;
1762 if (BT.Action == BitTest::Reset) {
1763 Mask = CGF.Builder.CreateNot(Mask);
1764 RMWOp = llvm::AtomicRMWInst::And;
1765 }
1766 OldByte = CGF.Builder.CreateAtomicRMW(RMWOp, ByteAddr, Mask, Ordering);
1767 } else {
1768 // Emit a plain load for the non-interlocked intrinsics.
1769 OldByte = CGF.Builder.CreateLoad(ByteAddr, "bittest.byte");
1770 Value *NewByte = nullptr;
1771 switch (BT.Action) {
1772 case BitTest::TestOnly:
1773 // Don't store anything.
1774 break;
1775 case BitTest::Complement:
1776 NewByte = CGF.Builder.CreateXor(OldByte, Mask);
1777 break;
1778 case BitTest::Reset:
1779 NewByte = CGF.Builder.CreateAnd(OldByte, CGF.Builder.CreateNot(Mask));
1780 break;
1781 case BitTest::Set:
1782 NewByte = CGF.Builder.CreateOr(OldByte, Mask);
1783 break;
1784 }
1785 if (NewByte)
1786 CGF.Builder.CreateStore(NewByte, ByteAddr);
1787 }
1788
1789 // However we loaded the old byte, either by plain load or atomicrmw, shift
1790 // the bit into the low position and mask it to 0 or 1.
1791 Value *ShiftedByte = CGF.Builder.CreateLShr(OldByte, PosLow, "bittest.shr");
1792 return CGF.Builder.CreateAnd(
1793 ShiftedByte, llvm::ConstantInt::get(CGF.Int8Ty, 1), "bittest.res");
1794}
1795
1796namespace {
1797enum class MSVCSetJmpKind {
1798 _setjmpex,
1799 _setjmp3,
1800 _setjmp
1801};
1802}
1803
1804/// MSVC handles setjmp a bit differently on different platforms. On 32-bit x86
1805/// extra parameters can be passed as variadic arguments, but we always pass
1806/// none. Everywhere else a frame value is passed: the stack pointer as it was
1807/// on entry to the function for AArch64 and 32-bit Arm, and the frame address
1808/// for the rest.
1809static RValue EmitMSVCRTSetJmp(CodeGenFunction &CGF, MSVCSetJmpKind SJKind,
1810 const CallExpr *E) {
1811 llvm::Value *Arg1 = nullptr;
1812 llvm::Type *Arg1Ty = nullptr;
1813 StringRef Name;
1814 bool IsVarArg = false;
1815 if (SJKind == MSVCSetJmpKind::_setjmp3) {
1816 Name = "_setjmp3";
1817 Arg1Ty = CGF.Int32Ty;
1818 Arg1 = llvm::ConstantInt::get(CGF.IntTy, 0);
1819 IsVarArg = true;
1820 } else {
1821 Name = SJKind == MSVCSetJmpKind::_setjmp ? "_setjmp" : "_setjmpex";
1822 Arg1Ty = CGF.Int8PtrTy;
1823 const llvm::Triple &T = CGF.getTarget().getTriple();
1824 if (T.getArch() == llvm::Triple::aarch64 || T.isARM() || T.isThumb()) {
1825 Arg1 = CGF.Builder.CreateCall(
1826 CGF.CGM.getIntrinsic(Intrinsic::sponentry, CGF.AllocaInt8PtrTy));
1827 } else
1828 Arg1 = CGF.Builder.CreateCall(
1829 CGF.CGM.getIntrinsic(Intrinsic::frameaddress, CGF.AllocaInt8PtrTy),
1830 llvm::ConstantInt::get(CGF.Int32Ty, 0));
1831 }
1832
1833 // Mark the call site and declaration with ReturnsTwice.
1834 llvm::Type *ArgTypes[2] = {CGF.Int8PtrTy, Arg1Ty};
1835 llvm::AttributeList ReturnsTwiceAttr = llvm::AttributeList::get(
1836 CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex,
1837 llvm::Attribute::ReturnsTwice);
1838 llvm::FunctionCallee SetJmpFn = CGF.CGM.CreateRuntimeFunction(
1839 llvm::FunctionType::get(CGF.IntTy, ArgTypes, IsVarArg), Name,
1840 ReturnsTwiceAttr, /*Local=*/true);
1841
1842 llvm::Value *Buf = CGF.Builder.CreateBitOrPointerCast(
1843 CGF.EmitScalarExpr(E->getArg(0)), CGF.Int8PtrTy);
1844 llvm::Value *Args[] = {Buf, Arg1};
1845 llvm::CallBase *CB = CGF.EmitRuntimeCallOrInvoke(SetJmpFn, Args);
1846 CB->setAttributes(ReturnsTwiceAttr);
1847 return RValue::get(CB);
1848}
1849
1850// Emit an MSVC intrinsic. Assumes that arguments have *not* been evaluated.
1852 const CallExpr *E) {
1853 switch (BuiltinID) {
1856 Address IndexAddress(EmitPointerWithAlignment(E->getArg(0)));
1857 Value *ArgValue = EmitScalarExpr(E->getArg(1));
1858
1859 llvm::Type *ArgType = ArgValue->getType();
1860 llvm::Type *IndexType = IndexAddress.getElementType();
1861 llvm::Type *ResultType = ConvertType(E->getType());
1862
1863 Value *ArgZero = llvm::Constant::getNullValue(ArgType);
1864 Value *ResZero = llvm::Constant::getNullValue(ResultType);
1865 Value *ResOne = llvm::ConstantInt::get(ResultType, 1);
1866
1867 BasicBlock *Begin = Builder.GetInsertBlock();
1868 BasicBlock *End = createBasicBlock("bitscan_end", this->CurFn);
1869 Builder.SetInsertPoint(End);
1870 PHINode *Result = Builder.CreatePHI(ResultType, 2, "bitscan_result");
1871
1872 Builder.SetInsertPoint(Begin);
1873 Value *IsZero = Builder.CreateICmpEQ(ArgValue, ArgZero);
1874 BasicBlock *NotZero = createBasicBlock("bitscan_not_zero", this->CurFn);
1875 Builder.CreateCondBr(IsZero, End, NotZero);
1876 Result->addIncoming(ResZero, Begin);
1877
1878 Builder.SetInsertPoint(NotZero);
1879
1880 if (BuiltinID == MSVCIntrin::_BitScanForward) {
1881 Function *F = CGM.getIntrinsic(Intrinsic::cttz, ArgType);
1882 Value *ZeroCount = Builder.CreateCall(F, {ArgValue, Builder.getTrue()});
1883 ZeroCount = Builder.CreateIntCast(ZeroCount, IndexType, false);
1884 Builder.CreateStore(ZeroCount, IndexAddress, false);
1885 } else {
1886 unsigned ArgWidth = cast<llvm::IntegerType>(ArgType)->getBitWidth();
1887 Value *ArgTypeLastIndex = llvm::ConstantInt::get(IndexType, ArgWidth - 1);
1888
1889 Function *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
1890 Value *ZeroCount = Builder.CreateCall(F, {ArgValue, Builder.getTrue()});
1891 ZeroCount = Builder.CreateIntCast(ZeroCount, IndexType, false);
1892 Value *Index = Builder.CreateNSWSub(ArgTypeLastIndex, ZeroCount);
1893 Builder.CreateStore(Index, IndexAddress, false);
1894 }
1895 Builder.CreateBr(End);
1896 Result->addIncoming(ResOne, NotZero);
1897
1898 Builder.SetInsertPoint(End);
1899 return Result;
1900 }
1902 return MakeBinaryAtomicValue(*this, AtomicRMWInst::And, E);
1904 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xchg, E);
1906 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Add, E);
1908 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Sub, E);
1910 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Or, E);
1912 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xor, E);
1914 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Add, E,
1915 AtomicOrdering::Acquire);
1917 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Add, E,
1918 AtomicOrdering::Release);
1920 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Add, E,
1921 AtomicOrdering::Monotonic);
1923 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xchg, E,
1924 AtomicOrdering::Acquire);
1926 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xchg, E,
1927 AtomicOrdering::Release);
1929 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xchg, E,
1930 AtomicOrdering::Monotonic);
1932 return EmitAtomicCmpXchgForMSIntrin(*this, E);
1934 return EmitAtomicCmpXchgForMSIntrin(*this, E, AtomicOrdering::Acquire);
1936 return EmitAtomicCmpXchgForMSIntrin(*this, E, AtomicOrdering::Release);
1938 return EmitAtomicCmpXchgForMSIntrin(*this, E, AtomicOrdering::Monotonic);
1941 *this, E, AtomicOrdering::SequentiallyConsistent);
1943 return EmitAtomicCmpXchg128ForMSIntrin(*this, E, AtomicOrdering::Acquire);
1945 return EmitAtomicCmpXchg128ForMSIntrin(*this, E, AtomicOrdering::Release);
1947 return EmitAtomicCmpXchg128ForMSIntrin(*this, E, AtomicOrdering::Monotonic);
1949 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Or, E,
1950 AtomicOrdering::Acquire);
1952 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Or, E,
1953 AtomicOrdering::Release);
1955 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Or, E,
1956 AtomicOrdering::Monotonic);
1958 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xor, E,
1959 AtomicOrdering::Acquire);
1961 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xor, E,
1962 AtomicOrdering::Release);
1964 return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xor, E,
1965 AtomicOrdering::Monotonic);
1967 return MakeBinaryAtomicValue(*this, AtomicRMWInst::And, E,
1968 AtomicOrdering::Acquire);
1970 return MakeBinaryAtomicValue(*this, AtomicRMWInst::And, E,
1971 AtomicOrdering::Release);
1973 return MakeBinaryAtomicValue(*this, AtomicRMWInst::And, E,
1974 AtomicOrdering::Monotonic);
1976 return EmitAtomicIncrementValue(*this, E, AtomicOrdering::Acquire);
1978 return EmitAtomicIncrementValue(*this, E, AtomicOrdering::Release);
1980 return EmitAtomicIncrementValue(*this, E, AtomicOrdering::Monotonic);
1982 return EmitAtomicDecrementValue(*this, E, AtomicOrdering::Acquire);
1984 return EmitAtomicDecrementValue(*this, E, AtomicOrdering::Release);
1986 return EmitAtomicDecrementValue(*this, E, AtomicOrdering::Monotonic);
1987
1989 return EmitAtomicDecrementValue(*this, E);
1991 return EmitAtomicIncrementValue(*this, E);
1992
1994 // Request immediate process termination from the kernel. The instruction
1995 // sequences to do this are documented on MSDN:
1996 // https://msdn.microsoft.com/en-us/library/dn774154.aspx
1997 llvm::Triple::ArchType ISA = getTarget().getTriple().getArch();
1998 StringRef Asm, Constraints;
1999 switch (ISA) {
2000 default:
2001 ErrorUnsupported(E, "__fastfail call for this architecture");
2002 break;
2003 case llvm::Triple::x86:
2004 case llvm::Triple::x86_64:
2005 Asm = "int $$0x29";
2006 Constraints = "{cx}";
2007 break;
2008 case llvm::Triple::thumb:
2009 Asm = "udf #251";
2010 Constraints = "{r0}";
2011 break;
2012 case llvm::Triple::aarch64:
2013 Asm = "brk #0xF003";
2014 Constraints = "{w0}";
2015 }
2016 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, {Int32Ty}, false);
2017 llvm::InlineAsm *IA =
2018 llvm::InlineAsm::get(FTy, Asm, Constraints, /*hasSideEffects=*/true);
2019 llvm::AttributeList NoReturnAttr = llvm::AttributeList::get(
2020 getLLVMContext(), llvm::AttributeList::FunctionIndex,
2021 llvm::Attribute::NoReturn);
2022 llvm::CallInst *CI = Builder.CreateCall(IA, EmitScalarExpr(E->getArg(0)));
2023 CI->setAttributes(NoReturnAttr);
2024 return CI;
2025 }
2026 }
2027 llvm_unreachable("Incorrect MSVC intrinsic!");
2028}
2029
2030namespace {
2031// ARC cleanup for __builtin_os_log_format
2032struct CallObjCArcUse final : EHScopeStack::Cleanup {
2033 CallObjCArcUse(llvm::Value *object) : object(object) {}
2034 llvm::Value *object;
2035
2036 void Emit(CodeGenFunction &CGF, Flags flags) override {
2037 CGF.EmitARCIntrinsicUse(object);
2038 }
2039};
2040}
2041
2043 BuiltinCheckKind Kind) {
2044 assert((Kind == BCK_CLZPassedZero || Kind == BCK_CTZPassedZero) &&
2045 "Unsupported builtin check kind");
2046
2047 Value *ArgValue = EmitBitCountExpr(*this, E);
2048 if (!SanOpts.has(SanitizerKind::Builtin))
2049 return ArgValue;
2050
2051 auto CheckOrdinal = SanitizerKind::SO_Builtin;
2052 auto CheckHandler = SanitizerHandler::InvalidBuiltin;
2053 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
2054 Value *Cond = Builder.CreateICmpNE(
2055 ArgValue, llvm::Constant::getNullValue(ArgValue->getType()));
2056 EmitCheck(std::make_pair(Cond, CheckOrdinal), CheckHandler,
2058 llvm::ConstantInt::get(Builder.getInt8Ty(), Kind)},
2059 {});
2060 return ArgValue;
2061}
2062
2064 Value *ArgValue = EvaluateExprAsBool(E);
2065 if (!SanOpts.has(SanitizerKind::Builtin))
2066 return ArgValue;
2067
2068 auto CheckOrdinal = SanitizerKind::SO_Builtin;
2069 auto CheckHandler = SanitizerHandler::InvalidBuiltin;
2070 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
2071 EmitCheck(
2072 std::make_pair(ArgValue, CheckOrdinal), CheckHandler,
2074 llvm::ConstantInt::get(Builder.getInt8Ty(), BCK_AssumePassedFalse)},
2075 {});
2076 return ArgValue;
2077}
2078
2079static Value *EmitAbs(CodeGenFunction &CGF, Value *ArgValue, bool HasNSW) {
2080 return CGF.Builder.CreateBinaryIntrinsic(
2081 Intrinsic::abs, ArgValue,
2082 ConstantInt::get(CGF.Builder.getInt1Ty(), HasNSW));
2083}
2084
2086 bool SanitizeOverflow) {
2087 Value *ArgValue = CGF.EmitScalarExpr(E->getArg(0));
2088
2089 // Try to eliminate overflow check.
2090 if (const auto *VCI = dyn_cast<llvm::ConstantInt>(ArgValue)) {
2091 if (!VCI->isMinSignedValue())
2092 return EmitAbs(CGF, ArgValue, true);
2093 }
2094
2096 SanitizerHandler CheckHandler;
2097 if (SanitizeOverflow) {
2098 Ordinals.push_back(SanitizerKind::SO_SignedIntegerOverflow);
2099 CheckHandler = SanitizerHandler::NegateOverflow;
2100 } else
2101 CheckHandler = SanitizerHandler::SubOverflow;
2102
2103 SanitizerDebugLocation SanScope(&CGF, Ordinals, CheckHandler);
2104
2105 Constant *Zero = Constant::getNullValue(ArgValue->getType());
2106 Value *ResultAndOverflow = CGF.Builder.CreateBinaryIntrinsic(
2107 Intrinsic::ssub_with_overflow, Zero, ArgValue);
2108 Value *Result = CGF.Builder.CreateExtractValue(ResultAndOverflow, 0);
2109 Value *NotOverflow = CGF.Builder.CreateNot(
2110 CGF.Builder.CreateExtractValue(ResultAndOverflow, 1));
2111
2112 // TODO: support -ftrapv-handler.
2113 if (SanitizeOverflow) {
2114 CGF.EmitCheck({{NotOverflow, SanitizerKind::SO_SignedIntegerOverflow}},
2115 CheckHandler,
2118 {ArgValue});
2119 } else
2120 CGF.EmitTrapCheck(NotOverflow, CheckHandler);
2121
2122 Value *CmpResult = CGF.Builder.CreateICmpSLT(ArgValue, Zero, "abscond");
2123 return CGF.Builder.CreateSelect(CmpResult, Result, ArgValue, "abs");
2124}
2125
2126/// Get the argument type for arguments to os_log_helper.
2128 QualType UnsignedTy = C.getIntTypeForBitwidth(Size * 8, /*Signed=*/false);
2129 return C.getCanonicalType(UnsignedTy);
2130}
2131
2134 CharUnits BufferAlignment) {
2135 ASTContext &Ctx = getContext();
2136
2138 {
2139 raw_svector_ostream OS(Name);
2140 OS << "__os_log_helper";
2141 OS << "_" << BufferAlignment.getQuantity();
2142 OS << "_" << int(Layout.getSummaryByte());
2143 OS << "_" << int(Layout.getNumArgsByte());
2144 for (const auto &Item : Layout.Items)
2145 OS << "_" << int(Item.getSizeByte()) << "_"
2146 << int(Item.getDescriptorByte());
2147 }
2148
2149 if (llvm::Function *F = CGM.getModule().getFunction(Name))
2150 return F;
2151
2153 FunctionArgList Args;
2154 Args.push_back(ImplicitParamDecl::Create(
2155 Ctx, nullptr, SourceLocation(), &Ctx.Idents.get("buffer"), Ctx.VoidPtrTy,
2157 ArgTys.emplace_back(Ctx.VoidPtrTy);
2158
2159 for (unsigned int I = 0, E = Layout.Items.size(); I < E; ++I) {
2160 char Size = Layout.Items[I].getSizeByte();
2161 if (!Size)
2162 continue;
2163
2164 QualType ArgTy = getOSLogArgType(Ctx, Size);
2165 Args.push_back(ImplicitParamDecl::Create(
2166 Ctx, nullptr, SourceLocation(),
2167 &Ctx.Idents.get(std::string("arg") + llvm::to_string(I)), ArgTy,
2169 ArgTys.emplace_back(ArgTy);
2170 }
2171
2172 QualType ReturnTy = Ctx.VoidTy;
2173
2174 // The helper function has linkonce_odr linkage to enable the linker to merge
2175 // identical functions. To ensure the merging always happens, 'noinline' is
2176 // attached to the function when compiling with -Oz.
2177 const CGFunctionInfo &FI =
2178 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, Args);
2179 llvm::FunctionType *FuncTy = CGM.getTypes().GetFunctionType(FI);
2180 llvm::Function *Fn = llvm::Function::Create(
2181 FuncTy, llvm::GlobalValue::LinkOnceODRLinkage, Name, &CGM.getModule());
2182 Fn->setVisibility(llvm::GlobalValue::HiddenVisibility);
2183 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Fn, /*IsThunk=*/false);
2184 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, Fn);
2185 Fn->setDoesNotThrow();
2186
2187 // Attach 'noinline' at -Oz.
2188 if (CGM.getCodeGenOpts().OptimizeSize == 2)
2189 Fn->addFnAttr(llvm::Attribute::NoInline);
2190
2191 auto NL = ApplyDebugLocation::CreateEmpty(*this);
2192 StartFunction(GlobalDecl(), ReturnTy, Fn, FI, Args);
2193
2194 // Create a scope with an artificial location for the body of this function.
2195 auto AL = ApplyDebugLocation::CreateArtificial(*this);
2196
2197 CharUnits Offset;
2199 Builder.CreateLoad(GetAddrOfLocalVar(Args[0]), "buf"), Ctx.VoidTy,
2200 BufferAlignment);
2201 Builder.CreateStore(Builder.getInt8(Layout.getSummaryByte()),
2202 Builder.CreateConstByteGEP(BufAddr, Offset++, "summary"));
2203 Builder.CreateStore(Builder.getInt8(Layout.getNumArgsByte()),
2204 Builder.CreateConstByteGEP(BufAddr, Offset++, "numArgs"));
2205
2206 unsigned I = 1;
2207 for (const auto &Item : Layout.Items) {
2208 Builder.CreateStore(
2209 Builder.getInt8(Item.getDescriptorByte()),
2210 Builder.CreateConstByteGEP(BufAddr, Offset++, "argDescriptor"));
2211 Builder.CreateStore(
2212 Builder.getInt8(Item.getSizeByte()),
2213 Builder.CreateConstByteGEP(BufAddr, Offset++, "argSize"));
2214
2215 CharUnits Size = Item.size();
2216 if (!Size.getQuantity())
2217 continue;
2218
2219 Address Arg = GetAddrOfLocalVar(Args[I]);
2220 Address Addr = Builder.CreateConstByteGEP(BufAddr, Offset, "argData");
2221 Addr = Addr.withElementType(Arg.getElementType());
2222 Builder.CreateStore(Builder.CreateLoad(Arg), Addr);
2223 Offset += Size;
2224 ++I;
2225 }
2226
2228
2229 return Fn;
2230}
2231
2233 assert(E.getNumArgs() >= 2 &&
2234 "__builtin_os_log_format takes at least 2 arguments");
2235 ASTContext &Ctx = getContext();
2238 Address BufAddr = EmitPointerWithAlignment(E.getArg(0));
2239
2240 // Ignore argument 1, the format string. It is not currently used.
2241 CallArgList Args;
2242 Args.add(RValue::get(BufAddr.emitRawPointer(*this)), Ctx.VoidPtrTy);
2243
2244 for (const auto &Item : Layout.Items) {
2245 int Size = Item.getSizeByte();
2246 if (!Size)
2247 continue;
2248
2249 llvm::Value *ArgVal;
2250
2251 if (Item.getKind() == analyze_os_log::OSLogBufferItem::MaskKind) {
2252 uint64_t Val = 0;
2253 for (unsigned I = 0, E = Item.getMaskType().size(); I < E; ++I)
2254 Val |= ((uint64_t)Item.getMaskType()[I]) << I * 8;
2255 ArgVal = llvm::Constant::getIntegerValue(Int64Ty, llvm::APInt(64, Val));
2256 } else if (const Expr *TheExpr = Item.getExpr()) {
2257 ArgVal = EmitScalarExpr(TheExpr, /*Ignore*/ false);
2258
2259 // If a temporary object that requires destruction after the full
2260 // expression is passed, push a lifetime-extended cleanup to extend its
2261 // lifetime to the end of the enclosing block scope.
2262 auto LifetimeExtendObject = [&](const Expr *E) {
2263 E = E->IgnoreParenCasts();
2264 // Extend lifetimes of objects returned by function calls and message
2265 // sends.
2266
2267 // FIXME: We should do this in other cases in which temporaries are
2268 // created including arguments of non-ARC types (e.g., C++
2269 // temporaries).
2271 return true;
2272 return false;
2273 };
2274
2275 if (TheExpr->getType()->isObjCRetainableType() &&
2276 getLangOpts().ObjCAutoRefCount && LifetimeExtendObject(TheExpr)) {
2277 assert(getEvaluationKind(TheExpr->getType()) == TEK_Scalar &&
2278 "Only scalar can be a ObjC retainable type");
2279 if (!isa<Constant>(ArgVal)) {
2280 CleanupKind Cleanup = getARCCleanupKind();
2281 QualType Ty = TheExpr->getType();
2282 RawAddress Alloca = CreateMemTempWithoutCast(Ty, "os.log.arg");
2283 ArgVal = EmitARCRetain(Ty, ArgVal);
2284 Builder.CreateStore(ArgVal, Alloca);
2285 pushLifetimeExtendedDestroy(Cleanup, Alloca, Ty,
2287 Cleanup & EHCleanup);
2288
2289 // Push a clang.arc.use call to ensure ARC optimizer knows that the
2290 // argument has to be alive.
2291 if (CGM.getCodeGenOpts().OptimizationLevel != 0)
2293 }
2294 }
2295 } else {
2296 ArgVal = Builder.getInt32(Item.getConstValue().getQuantity());
2297 }
2298
2299 unsigned ArgValSize =
2300 CGM.getDataLayout().getTypeSizeInBits(ArgVal->getType());
2301 llvm::IntegerType *IntTy = llvm::Type::getIntNTy(getLLVMContext(),
2302 ArgValSize);
2303 ArgVal = Builder.CreateBitOrPointerCast(ArgVal, IntTy);
2304 CanQualType ArgTy = getOSLogArgType(Ctx, Size);
2305 // If ArgVal has type x86_fp80, zero-extend ArgVal.
2306 ArgVal = Builder.CreateZExtOrBitCast(ArgVal, ConvertType(ArgTy));
2307 Args.add(RValue::get(ArgVal), ArgTy);
2308 }
2309
2310 const CGFunctionInfo &FI =
2311 CGM.getTypes().arrangeBuiltinFunctionCall(Ctx.VoidTy, Args);
2312 llvm::Function *F = CodeGenFunction(CGM).generateBuiltinOSLogHelperFunction(
2313 Layout, BufAddr.getAlignment());
2315 return RValue::get(BufAddr, *this);
2316}
2317
2319 unsigned BuiltinID, WidthAndSignedness Op1Info, WidthAndSignedness Op2Info,
2320 WidthAndSignedness ResultInfo) {
2321 return BuiltinID == Builtin::BI__builtin_mul_overflow &&
2322 Op1Info.Width == Op2Info.Width && Op2Info.Width == ResultInfo.Width &&
2323 !Op1Info.Signed && !Op2Info.Signed && ResultInfo.Signed;
2324}
2325
2327 CodeGenFunction &CGF, const clang::Expr *Op1, WidthAndSignedness Op1Info,
2328 const clang::Expr *Op2, WidthAndSignedness Op2Info,
2329 const clang::Expr *ResultArg, QualType ResultQTy,
2330 WidthAndSignedness ResultInfo) {
2332 Builtin::BI__builtin_mul_overflow, Op1Info, Op2Info, ResultInfo) &&
2333 "Cannot specialize this multiply");
2334
2335 llvm::Value *V1 = CGF.EmitScalarExpr(Op1);
2336 llvm::Value *V2 = CGF.EmitScalarExpr(Op2);
2337
2338 llvm::Value *HasOverflow;
2339 llvm::Value *Result = EmitOverflowIntrinsic(
2340 CGF, Intrinsic::umul_with_overflow, V1, V2, HasOverflow);
2341
2342 // The intrinsic call will detect overflow when the value is > UINT_MAX,
2343 // however, since the original builtin had a signed result, we need to report
2344 // an overflow when the result is greater than INT_MAX.
2345 auto IntMax = llvm::APInt::getSignedMaxValue(ResultInfo.Width);
2346 llvm::Value *IntMaxValue = llvm::ConstantInt::get(Result->getType(), IntMax);
2347
2348 llvm::Value *IntMaxOverflow = CGF.Builder.CreateICmpUGT(Result, IntMaxValue);
2349 HasOverflow = CGF.Builder.CreateOr(HasOverflow, IntMaxOverflow);
2350
2351 bool isVolatile =
2352 ResultArg->getType()->getPointeeType().isVolatileQualified();
2353 Address ResultPtr = CGF.EmitPointerWithAlignment(ResultArg);
2354 CGF.Builder.CreateStore(CGF.EmitToMemory(Result, ResultQTy), ResultPtr,
2355 isVolatile);
2356 return RValue::get(HasOverflow);
2357}
2358
2359/// Determine if a binop is a checked mixed-sign multiply we can specialize.
2360static bool isSpecialMixedSignMultiply(unsigned BuiltinID,
2361 WidthAndSignedness Op1Info,
2362 WidthAndSignedness Op2Info,
2363 WidthAndSignedness ResultInfo) {
2364 return BuiltinID == Builtin::BI__builtin_mul_overflow &&
2365 std::max(Op1Info.Width, Op2Info.Width) >= ResultInfo.Width &&
2366 Op1Info.Signed != Op2Info.Signed;
2367}
2368
2369/// Emit a checked mixed-sign multiply. This is a cheaper specialization of
2370/// the generic checked-binop irgen.
2371static RValue
2373 WidthAndSignedness Op1Info, const clang::Expr *Op2,
2374 WidthAndSignedness Op2Info,
2375 const clang::Expr *ResultArg, QualType ResultQTy,
2376 WidthAndSignedness ResultInfo) {
2377 assert(isSpecialMixedSignMultiply(Builtin::BI__builtin_mul_overflow, Op1Info,
2378 Op2Info, ResultInfo) &&
2379 "Not a mixed-sign multipliction we can specialize");
2380
2381 // Emit the signed and unsigned operands.
2382 const clang::Expr *SignedOp = Op1Info.Signed ? Op1 : Op2;
2383 const clang::Expr *UnsignedOp = Op1Info.Signed ? Op2 : Op1;
2384 llvm::Value *Signed = CGF.EmitScalarExpr(SignedOp);
2385 llvm::Value *Unsigned = CGF.EmitScalarExpr(UnsignedOp);
2386 unsigned SignedOpWidth = Op1Info.Signed ? Op1Info.Width : Op2Info.Width;
2387 unsigned UnsignedOpWidth = Op1Info.Signed ? Op2Info.Width : Op1Info.Width;
2388
2389 // One of the operands may be smaller than the other. If so, [s|z]ext it.
2390 if (SignedOpWidth < UnsignedOpWidth)
2391 Signed = CGF.Builder.CreateSExt(Signed, Unsigned->getType(), "op.sext");
2392 if (UnsignedOpWidth < SignedOpWidth)
2393 Unsigned = CGF.Builder.CreateZExt(Unsigned, Signed->getType(), "op.zext");
2394
2395 llvm::Type *OpTy = Signed->getType();
2396 llvm::Value *Zero = llvm::Constant::getNullValue(OpTy);
2397 Address ResultPtr = CGF.EmitPointerWithAlignment(ResultArg);
2398 llvm::Type *ResTy = CGF.getTypes().ConvertType(ResultQTy);
2399 unsigned OpWidth = std::max(Op1Info.Width, Op2Info.Width);
2400
2401 // Take the absolute value of the signed operand.
2402 llvm::Value *IsNegative = CGF.Builder.CreateICmpSLT(Signed, Zero);
2403 llvm::Value *AbsOfNegative = CGF.Builder.CreateSub(Zero, Signed);
2404 llvm::Value *AbsSigned =
2405 CGF.Builder.CreateSelect(IsNegative, AbsOfNegative, Signed);
2406
2407 // Perform a checked unsigned multiplication.
2408 llvm::Value *UnsignedOverflow;
2409 llvm::Value *UnsignedResult =
2410 EmitOverflowIntrinsic(CGF, Intrinsic::umul_with_overflow, AbsSigned,
2411 Unsigned, UnsignedOverflow);
2412
2413 llvm::Value *Overflow, *Result;
2414 if (ResultInfo.Signed) {
2415 // Signed overflow occurs if the result is greater than INT_MAX or lesser
2416 // than INT_MIN, i.e when |Result| > (INT_MAX + IsNegative).
2417 auto IntMax =
2418 llvm::APInt::getSignedMaxValue(ResultInfo.Width).zext(OpWidth);
2419 llvm::Value *MaxResult =
2420 CGF.Builder.CreateAdd(llvm::ConstantInt::get(OpTy, IntMax),
2421 CGF.Builder.CreateZExt(IsNegative, OpTy));
2422 llvm::Value *SignedOverflow =
2423 CGF.Builder.CreateICmpUGT(UnsignedResult, MaxResult);
2424 Overflow = CGF.Builder.CreateOr(UnsignedOverflow, SignedOverflow);
2425
2426 // Prepare the signed result (possibly by negating it).
2427 llvm::Value *NegativeResult = CGF.Builder.CreateNeg(UnsignedResult);
2428 llvm::Value *SignedResult =
2429 CGF.Builder.CreateSelect(IsNegative, NegativeResult, UnsignedResult);
2430 Result = CGF.Builder.CreateTrunc(SignedResult, ResTy);
2431 } else {
2432 // Unsigned overflow occurs if the result is < 0 or greater than UINT_MAX.
2433 llvm::Value *Underflow = CGF.Builder.CreateAnd(
2434 IsNegative, CGF.Builder.CreateIsNotNull(UnsignedResult));
2435 Overflow = CGF.Builder.CreateOr(UnsignedOverflow, Underflow);
2436 if (ResultInfo.Width < OpWidth) {
2437 auto IntMax =
2438 llvm::APInt::getMaxValue(ResultInfo.Width).zext(OpWidth);
2439 llvm::Value *TruncOverflow = CGF.Builder.CreateICmpUGT(
2440 UnsignedResult, llvm::ConstantInt::get(OpTy, IntMax));
2441 Overflow = CGF.Builder.CreateOr(Overflow, TruncOverflow);
2442 }
2443
2444 // Negate the product if it would be negative in infinite precision.
2445 Result = CGF.Builder.CreateSelect(
2446 IsNegative, CGF.Builder.CreateNeg(UnsignedResult), UnsignedResult);
2447
2448 Result = CGF.Builder.CreateTrunc(Result, ResTy);
2449 }
2450 assert(Overflow && Result && "Missing overflow or result");
2451
2452 bool isVolatile =
2453 ResultArg->getType()->getPointeeType().isVolatileQualified();
2454 CGF.Builder.CreateStore(CGF.EmitToMemory(Result, ResultQTy), ResultPtr,
2455 isVolatile);
2456 return RValue::get(Overflow);
2457}
2458
2459/// Determine if the specified type requires laundering by checking if it is a
2460/// dynamic class type or contains a subobject which is a dynamic class type.
2462 if (!CGM.getCodeGenOpts().StrictVTablePointers)
2463 return false;
2464 return Ty.requiresBuiltinLaunder(CGM.getContext());
2465}
2466
2467RValue CodeGenFunction::emitRotate(const CallExpr *E, bool IsRotateRight) {
2468 llvm::Value *Src = EmitScalarExpr(E->getArg(0));
2469 llvm::Value *ShiftAmt = EmitScalarExpr(E->getArg(1));
2470
2471 // The builtin's shift arg may have a different type than the source arg and
2472 // result, but the LLVM intrinsic uses the same type for all values.
2473 llvm::Type *Ty = Src->getType();
2474 llvm::Type *ShiftTy = ShiftAmt->getType();
2475
2476 unsigned BitWidth = Ty->getIntegerBitWidth();
2477
2478 // Normalize shift amount to [0, BitWidth) range to match runtime behavior.
2479 // This matches the algorithm in ExprConstant.cpp for constant evaluation.
2480 if (BitWidth == 1) {
2481 // Rotating a 1-bit value is always a no-op
2482 ShiftAmt = ConstantInt::get(ShiftTy, 0);
2483 } else if (BitWidth == 2) {
2484 // For 2-bit values: rotation amount is 0 or 1 based on
2485 // whether the amount is even or odd. We can't use srem here because
2486 // the divisor (2) would be misinterpreted as -2 in 2-bit signed arithmetic.
2487 llvm::Value *One = ConstantInt::get(ShiftTy, 1);
2488 ShiftAmt = Builder.CreateAnd(ShiftAmt, One);
2489 } else {
2490 unsigned ShiftAmtBitWidth = ShiftTy->getIntegerBitWidth();
2491 bool ShiftAmtIsSigned = E->getArg(1)->getType()->isSignedIntegerType();
2492
2493 // Choose the wider type for the divisor to avoid truncation
2494 llvm::Type *DivisorTy = ShiftAmtBitWidth > BitWidth ? ShiftTy : Ty;
2495 llvm::Value *Divisor = ConstantInt::get(DivisorTy, BitWidth);
2496
2497 // Extend ShiftAmt to match Divisor width if needed
2498 if (ShiftAmtBitWidth < DivisorTy->getIntegerBitWidth()) {
2499 ShiftAmt = Builder.CreateIntCast(ShiftAmt, DivisorTy, ShiftAmtIsSigned);
2500 }
2501
2502 // Normalize to [0, BitWidth)
2503 llvm::Value *RemResult;
2504 if (ShiftAmtIsSigned) {
2505 RemResult = Builder.CreateSRem(ShiftAmt, Divisor);
2506 // Signed remainder can be negative, convert to positive equivalent
2507 llvm::Value *Zero = ConstantInt::get(DivisorTy, 0);
2508 llvm::Value *IsNegative = Builder.CreateICmpSLT(RemResult, Zero);
2509 llvm::Value *PositiveShift = Builder.CreateAdd(RemResult, Divisor);
2510 ShiftAmt = Builder.CreateSelect(IsNegative, PositiveShift, RemResult);
2511 } else {
2512 ShiftAmt = Builder.CreateURem(ShiftAmt, Divisor);
2513 }
2514 }
2515
2516 // Convert to the source type if needed
2517 if (ShiftAmt->getType() != Ty) {
2518 ShiftAmt = Builder.CreateIntCast(ShiftAmt, Ty, false);
2519 }
2520
2521 // Rotate is a special case of LLVM funnel shift - 1st 2 args are the same.
2522 unsigned IID = IsRotateRight ? Intrinsic::fshr : Intrinsic::fshl;
2523 Function *F = CGM.getIntrinsic(IID, Ty);
2524 return RValue::get(Builder.CreateCall(F, {Src, Src, ShiftAmt}));
2525}
2526
2527// Map math builtins for long-double to f128 version.
2528static unsigned mutateLongDoubleBuiltin(unsigned BuiltinID) {
2529 switch (BuiltinID) {
2530#define MUTATE_LDBL(func) \
2531 case Builtin::BI__builtin_##func##l: \
2532 return Builtin::BI__builtin_##func##f128;
2563 MUTATE_LDBL(nans)
2564 MUTATE_LDBL(inf)
2583 MUTATE_LDBL(huge_val)
2593#undef MUTATE_LDBL
2594 default:
2595 return BuiltinID;
2596 }
2597}
2598
2599static Value *tryUseTestFPKind(CodeGenFunction &CGF, unsigned BuiltinID,
2600 Value *V) {
2601 if (CGF.Builder.getIsFPConstrained() &&
2602 CGF.Builder.getDefaultConstrainedExcept() != fp::ebIgnore) {
2603 if (Value *Result =
2604 CGF.getTargetHooks().testFPKind(V, BuiltinID, CGF.Builder, CGF.CGM))
2605 return Result;
2606 }
2607 return nullptr;
2608}
2609
2611 const FunctionDecl *FD) {
2612 auto Name = FD->getNameAsString() + "__hipstdpar_unsupported";
2613 auto FnTy = CGF->CGM.getTypes().GetFunctionType(FD);
2614 auto UBF = CGF->CGM.getModule().getOrInsertFunction(Name, FnTy);
2615
2617 for (auto &&FormalTy : FnTy->params())
2618 Args.push_back(llvm::PoisonValue::get(FormalTy));
2619
2620 return RValue::get(CGF->Builder.CreateCall(UBF, Args));
2621}
2622
2623// stdc_{leading,trailing}_{zeros,ones} and stdc_count_ones: counts bits using
2624// ctlz, cttz, or ctpop (IsPop). InvertArg flips the input to count the
2625// opposite bit value.
2627 Intrinsic::ID IntID,
2628 bool InvertArg, bool IsPop) {
2629 Value *ArgValue = EmitScalarExpr(E->getArg(0));
2630 llvm::Type *ArgType = ArgValue->getType();
2631 llvm::Type *ResultType = ConvertType(E->getType());
2632 Value *ActualArg = InvertArg ? Builder.CreateNot(ArgValue) : ArgValue;
2633 Function *F = CGM.getIntrinsic(IntID, ArgType);
2634 Value *Result = IsPop
2635 ? Builder.CreateCall(F, ActualArg)
2636 : Builder.CreateCall(F, {ActualArg, Builder.getFalse()});
2637 if (Result->getType() != ResultType)
2638 Result = Builder.CreateIntCast(Result, ResultType, false);
2639 return RValue::get(Result);
2640}
2641
2642// stdc_count_zeros (BitWidth - ctpop) and stdc_bit_width (BitWidth - ctlz).
2643// IsPop selects ctpop; otherwise ctlz is used.
2645 Intrinsic::ID IntID, bool IsPop) {
2646 Value *ArgValue = EmitScalarExpr(E->getArg(0));
2647 llvm::Type *ArgType = ArgValue->getType();
2648 llvm::Type *ResultType = ConvertType(E->getType());
2649 unsigned BitWidth = ArgType->getIntegerBitWidth();
2650 Function *F = CGM.getIntrinsic(IntID, ArgType);
2651 Value *Cnt = IsPop ? Builder.CreateCall(F, ArgValue)
2652 : Builder.CreateCall(F, {ArgValue, Builder.getFalse()});
2653 Value *Result = Builder.CreateSub(ConstantInt::get(ArgType, BitWidth), Cnt);
2654 if (Result->getType() != ResultType)
2655 Result = Builder.CreateIntCast(Result, ResultType, false);
2656 return RValue::get(Result);
2657}
2658
2659// stdc_first_{leading,trailing}_{zero,one}: returns the 1-based position of
2660// the first matching bit, or 0 if no such bit exists. InvertArg flips the
2661// input to search for zeros instead of ones.
2663 bool InvertArg) {
2664 Value *ArgValue = EmitScalarExpr(E->getArg(0));
2665 llvm::Type *ArgType = ArgValue->getType();
2666 llvm::Type *ResultType = ConvertType(E->getType());
2667 Value *Zero = ConstantInt::get(ArgType, 0);
2668 Value *One = ConstantInt::get(ArgType, 1);
2669 Value *ActualArg = InvertArg ? Builder.CreateNot(ArgValue) : ArgValue;
2670 Function *F = CGM.getIntrinsic(IntID, ArgType);
2671 Value *Cnt = Builder.CreateCall(F, {ActualArg, Builder.getFalse()});
2672 Value *Tmp = Builder.CreateAdd(Cnt, One);
2673 Value *IsZero = Builder.CreateICmpEQ(ActualArg, Zero);
2674 Value *Result = Builder.CreateSelect(IsZero, Zero, Tmp);
2675 if (Result->getType() != ResultType)
2676 Result = Builder.CreateIntCast(Result, ResultType, false);
2677 return RValue::get(Result);
2678}
2679
2681 const ASTContext::BitInterval &PaddingInterval) {
2682 uint64_t CharWidth = CGF.getContext().getCharWidth();
2683
2684 auto *I8Ptr = CGF.Builder.CreateBitCast(Src.getBasePointer(), CGF.Int8PtrTy);
2685 auto *Zero = ConstantInt::get(CGF.Int8Ty, 0);
2686
2687 // Calculate byte indices and bit positions
2688 auto StartByte = PaddingInterval.First / CharWidth;
2689 auto StartBit = PaddingInterval.First % CharWidth;
2690 auto EndByte = PaddingInterval.Last / CharWidth;
2691 auto EndBit = PaddingInterval.Last % CharWidth;
2692
2693 if (StartByte == EndByte) {
2694 // Interval is within a single byte
2695 auto *Index = ConstantInt::get(CGF.IntTy, StartByte);
2696 auto *Element = CGF.Builder.CreateGEP(CGF.Int8Ty, I8Ptr, Index);
2697 Address ElementAddr(Element, CGF.Int8Ty,
2699 CharUnits::fromQuantity(StartByte)));
2700
2701 auto *Value = CGF.Builder.CreateLoad(ElementAddr);
2702
2703 // Create mask to clear bits within the byte
2704 // We want to clear bits from StartBit to EndBit-1
2705 uint8_t bitsToClear = ((1 << EndBit) - 1) & ~((1 << StartBit) - 1);
2706 uint8_t bitsToKeep = ~bitsToClear;
2707 auto *MaskValue = ConstantInt::get(CGF.Int8Ty, bitsToKeep);
2708 auto *NewValue = CGF.Builder.CreateAnd(Value, MaskValue);
2709
2710 CGF.Builder.CreateStore(NewValue, ElementAddr);
2711 } else {
2712 // Handle the start byte
2713 if (StartBit != 0) {
2714 auto *Index = ConstantInt::get(CGF.IntTy, StartByte);
2715 auto *Element = CGF.Builder.CreateGEP(CGF.Int8Ty, I8Ptr, Index);
2716 Address ElementAddr(Element, CGF.Int8Ty,
2718 CharUnits::fromQuantity(StartByte)));
2719
2720 auto *Value = CGF.Builder.CreateLoad(ElementAddr);
2721
2722 uint8_t bitsToClear = ((1 << (CharWidth - StartBit)) - 1) << StartBit;
2723 uint8_t bitsToKeep = ~bitsToClear;
2724 auto *MaskValue = ConstantInt::get(CGF.Int8Ty, bitsToKeep);
2725 auto *NewValue = CGF.Builder.CreateAnd(Value, MaskValue);
2726
2727 CGF.Builder.CreateStore(NewValue, ElementAddr);
2728 ++StartByte;
2729 }
2730
2731 // Handle full bytes in the middle
2732 for (auto Offset = StartByte; Offset < EndByte; ++Offset) {
2733 auto *Index = ConstantInt::get(CGF.IntTy, Offset);
2734 auto *Element = CGF.Builder.CreateGEP(CGF.Int8Ty, I8Ptr, Index);
2735 Address ElementAddr(Element, CGF.Int8Ty,
2737 CharUnits::fromQuantity(Offset)));
2738
2739 CGF.Builder.CreateStore(Zero, ElementAddr);
2740 }
2741
2742 // Handle the end byte
2743 if (EndBit != 0) {
2744 auto *Index = ConstantInt::get(CGF.IntTy, EndByte);
2745 auto *Element = CGF.Builder.CreateGEP(CGF.Int8Ty, I8Ptr, Index);
2746 Address ElementAddr(Element, CGF.Int8Ty,
2748 CharUnits::fromQuantity(EndByte)));
2749
2750 auto *Value = CGF.Builder.CreateLoad(ElementAddr);
2751
2752 uint8_t bitsToClear = (1 << EndBit) - 1;
2753 uint8_t bitsToKeep = ~bitsToClear;
2754 auto *MaskValue = ConstantInt::get(CGF.Int8Ty, bitsToKeep);
2755 auto *NewValue = CGF.Builder.CreateAnd(Value, MaskValue);
2756
2757 CGF.Builder.CreateStore(NewValue, ElementAddr);
2758 }
2759 }
2760}
2761
2763 const CallExpr *E,
2765 assert(!getContext().BuiltinInfo.isImmediate(BuiltinID) &&
2766 "Should not codegen for consteval builtins");
2767
2768 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
2769 // See if we can constant fold this builtin. If so, don't emit it at all.
2770 // TODO: Extend this handling to all builtin calls that we can constant-fold.
2772 if (E->isPRValue() && E->EvaluateAsRValue(Result, CGM.getContext()) &&
2773 !Result.hasSideEffects()) {
2774 if (Result.Val.isInt())
2775 return RValue::get(llvm::ConstantInt::get(getLLVMContext(),
2776 Result.Val.getInt()));
2777 if (Result.Val.isFloat())
2778 return RValue::get(llvm::ConstantFP::get(getLLVMContext(),
2779 Result.Val.getFloat()));
2780 }
2781
2782 // If current long-double semantics is IEEE 128-bit, replace math builtins
2783 // of long-double with f128 equivalent.
2784 // TODO: This mutation should also be applied to other targets other than PPC,
2785 // after backend supports IEEE 128-bit style libcalls.
2786 if (getTarget().getTriple().isPPC64() &&
2787 &getTarget().getLongDoubleFormat() == &llvm::APFloat::IEEEquad())
2788 BuiltinID = mutateLongDoubleBuiltin(BuiltinID);
2789
2790 // If the builtin has been declared explicitly with an assembler label,
2791 // disable the specialized emitting below. Ideally we should communicate the
2792 // rename in IR, or at least avoid generating the intrinsic calls that are
2793 // likely to get lowered to the renamed library functions.
2794 const unsigned BuiltinIDIfNoAsmLabel =
2795 FD->hasAttr<AsmLabelAttr>() ? 0 : BuiltinID;
2796
2797 std::optional<bool> ErrnoOverriden;
2798 // ErrnoOverriden is true if math-errno is overriden via the
2799 // '#pragma float_control(precise, on)'. This pragma disables fast-math,
2800 // which implies math-errno.
2801 if (E->hasStoredFPFeatures()) {
2803 if (OP.hasMathErrnoOverride())
2804 ErrnoOverriden = OP.getMathErrnoOverride();
2805 }
2806 // True if 'attribute__((optnone))' is used. This attribute overrides
2807 // fast-math which implies math-errno.
2808 bool OptNone = CurFuncDecl && CurFuncDecl->hasAttr<OptimizeNoneAttr>();
2809
2810 bool IsOptimizationEnabled = CGM.getCodeGenOpts().OptimizationLevel != 0;
2811
2812 bool GenerateFPMathIntrinsics =
2814 BuiltinID, CGM.getTriple(), ErrnoOverriden, getLangOpts().MathErrno,
2815 OptNone, IsOptimizationEnabled);
2816
2817 if (GenerateFPMathIntrinsics) {
2818 switch (BuiltinIDIfNoAsmLabel) {
2819 case Builtin::BIacos:
2820 case Builtin::BIacosf:
2821 case Builtin::BIacosl:
2822 case Builtin::BI__builtin_acos:
2823 case Builtin::BI__builtin_acosf:
2824 case Builtin::BI__builtin_acosf16:
2825 case Builtin::BI__builtin_acosl:
2826 case Builtin::BI__builtin_acosf128:
2827 case Builtin::BI__builtin_elementwise_acos:
2829 *this, E, Intrinsic::acos, Intrinsic::experimental_constrained_acos));
2830
2831 case Builtin::BIasin:
2832 case Builtin::BIasinf:
2833 case Builtin::BIasinl:
2834 case Builtin::BI__builtin_asin:
2835 case Builtin::BI__builtin_asinf:
2836 case Builtin::BI__builtin_asinf16:
2837 case Builtin::BI__builtin_asinl:
2838 case Builtin::BI__builtin_asinf128:
2839 case Builtin::BI__builtin_elementwise_asin:
2841 *this, E, Intrinsic::asin, Intrinsic::experimental_constrained_asin));
2842
2843 case Builtin::BIatan:
2844 case Builtin::BIatanf:
2845 case Builtin::BIatanl:
2846 case Builtin::BI__builtin_atan:
2847 case Builtin::BI__builtin_atanf:
2848 case Builtin::BI__builtin_atanf16:
2849 case Builtin::BI__builtin_atanl:
2850 case Builtin::BI__builtin_atanf128:
2851 case Builtin::BI__builtin_elementwise_atan:
2853 *this, E, Intrinsic::atan, Intrinsic::experimental_constrained_atan));
2854
2855 case Builtin::BIatan2:
2856 case Builtin::BIatan2f:
2857 case Builtin::BIatan2l:
2858 case Builtin::BI__builtin_atan2:
2859 case Builtin::BI__builtin_atan2f:
2860 case Builtin::BI__builtin_atan2f16:
2861 case Builtin::BI__builtin_atan2l:
2862 case Builtin::BI__builtin_atan2f128:
2863 case Builtin::BI__builtin_elementwise_atan2:
2865 *this, E, Intrinsic::atan2,
2866 Intrinsic::experimental_constrained_atan2));
2867
2868 case Builtin::BIceil:
2869 case Builtin::BIceilf:
2870 case Builtin::BIceill:
2871 case Builtin::BI__builtin_ceil:
2872 case Builtin::BI__builtin_ceilf:
2873 case Builtin::BI__builtin_ceilf16:
2874 case Builtin::BI__builtin_ceill:
2875 case Builtin::BI__builtin_ceilf128:
2876 case Builtin::BI__builtin_elementwise_ceil:
2878 Intrinsic::ceil,
2879 Intrinsic::experimental_constrained_ceil));
2880
2881 case Builtin::BIcopysign:
2882 case Builtin::BIcopysignf:
2883 case Builtin::BIcopysignl:
2884 case Builtin::BI__builtin_copysign:
2885 case Builtin::BI__builtin_copysignf:
2886 case Builtin::BI__builtin_copysignf16:
2887 case Builtin::BI__builtin_copysignl:
2888 case Builtin::BI__builtin_copysignf128:
2889 return RValue::get(
2890 emitBuiltinWithOneOverloadedType<2>(*this, E, Intrinsic::copysign));
2891
2892 case Builtin::BIcos:
2893 case Builtin::BIcosf:
2894 case Builtin::BIcosl:
2895 case Builtin::BI__builtin_cos:
2896 case Builtin::BI__builtin_cosf:
2897 case Builtin::BI__builtin_cosf16:
2898 case Builtin::BI__builtin_cosl:
2899 case Builtin::BI__builtin_cosf128:
2900 case Builtin::BI__builtin_elementwise_cos:
2902 Intrinsic::cos,
2903 Intrinsic::experimental_constrained_cos));
2904
2905 case Builtin::BIcosh:
2906 case Builtin::BIcoshf:
2907 case Builtin::BIcoshl:
2908 case Builtin::BI__builtin_cosh:
2909 case Builtin::BI__builtin_coshf:
2910 case Builtin::BI__builtin_coshf16:
2911 case Builtin::BI__builtin_coshl:
2912 case Builtin::BI__builtin_coshf128:
2913 case Builtin::BI__builtin_elementwise_cosh:
2915 *this, E, Intrinsic::cosh, Intrinsic::experimental_constrained_cosh));
2916
2917 case Builtin::BIexp:
2918 case Builtin::BIexpf:
2919 case Builtin::BIexpl:
2920 case Builtin::BI__builtin_exp:
2921 case Builtin::BI__builtin_expf:
2922 case Builtin::BI__builtin_expf16:
2923 case Builtin::BI__builtin_expl:
2924 case Builtin::BI__builtin_expf128:
2925 case Builtin::BI__builtin_elementwise_exp:
2927 Intrinsic::exp,
2928 Intrinsic::experimental_constrained_exp));
2929
2930 case Builtin::BIexp2:
2931 case Builtin::BIexp2f:
2932 case Builtin::BIexp2l:
2933 case Builtin::BI__builtin_exp2:
2934 case Builtin::BI__builtin_exp2f:
2935 case Builtin::BI__builtin_exp2f16:
2936 case Builtin::BI__builtin_exp2l:
2937 case Builtin::BI__builtin_exp2f128:
2938 case Builtin::BI__builtin_elementwise_exp2:
2940 Intrinsic::exp2,
2941 Intrinsic::experimental_constrained_exp2));
2942 case Builtin::BI__builtin_exp10:
2943 case Builtin::BI__builtin_exp10f:
2944 case Builtin::BI__builtin_exp10f16:
2945 case Builtin::BI__builtin_exp10l:
2946 case Builtin::BI__builtin_exp10f128:
2947 case Builtin::BI__builtin_elementwise_exp10: {
2948 // TODO: strictfp support
2949 if (Builder.getIsFPConstrained())
2950 break;
2951 return RValue::get(
2952 emitBuiltinWithOneOverloadedType<1>(*this, E, Intrinsic::exp10));
2953 }
2954 case Builtin::BIfabs:
2955 case Builtin::BIfabsf:
2956 case Builtin::BIfabsl:
2957 case Builtin::BI__builtin_fabs:
2958 case Builtin::BI__builtin_fabsf:
2959 case Builtin::BI__builtin_fabsf16:
2960 case Builtin::BI__builtin_fabsl:
2961 case Builtin::BI__builtin_fabsf128:
2962 return RValue::get(
2963 emitBuiltinWithOneOverloadedType<1>(*this, E, Intrinsic::fabs));
2964
2965 case Builtin::BIfloor:
2966 case Builtin::BIfloorf:
2967 case Builtin::BIfloorl:
2968 case Builtin::BI__builtin_floor:
2969 case Builtin::BI__builtin_floorf:
2970 case Builtin::BI__builtin_floorf16:
2971 case Builtin::BI__builtin_floorl:
2972 case Builtin::BI__builtin_floorf128:
2973 case Builtin::BI__builtin_elementwise_floor:
2975 Intrinsic::floor,
2976 Intrinsic::experimental_constrained_floor));
2977
2978 case Builtin::BIfma:
2979 case Builtin::BIfmaf:
2980 case Builtin::BIfmal:
2981 case Builtin::BI__builtin_fma:
2982 case Builtin::BI__builtin_fmaf:
2983 case Builtin::BI__builtin_fmaf16:
2984 case Builtin::BI__builtin_fmal:
2985 case Builtin::BI__builtin_fmaf128:
2986 case Builtin::BI__builtin_elementwise_fma:
2988 Intrinsic::fma,
2989 Intrinsic::experimental_constrained_fma));
2990
2991 case Builtin::BIfmax:
2992 case Builtin::BIfmaxf:
2993 case Builtin::BIfmaxl:
2994 case Builtin::BI__builtin_fmax:
2995 case Builtin::BI__builtin_fmaxf:
2996 case Builtin::BI__builtin_fmaxf16:
2997 case Builtin::BI__builtin_fmaxl:
2998 case Builtin::BI__builtin_fmaxf128: {
2999 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
3000 Builder.getFastMathFlags().setNoSignedZeros();
3002 *this, E, Intrinsic::maxnum,
3003 Intrinsic::experimental_constrained_maxnum));
3004 }
3005
3006 case Builtin::BIfmin:
3007 case Builtin::BIfminf:
3008 case Builtin::BIfminl:
3009 case Builtin::BI__builtin_fmin:
3010 case Builtin::BI__builtin_fminf:
3011 case Builtin::BI__builtin_fminf16:
3012 case Builtin::BI__builtin_fminl:
3013 case Builtin::BI__builtin_fminf128: {
3014 IRBuilder<>::FastMathFlagGuard FMFGuard(Builder);
3015 Builder.getFastMathFlags().setNoSignedZeros();
3017 *this, E, Intrinsic::minnum,
3018 Intrinsic::experimental_constrained_minnum));
3019 }
3020
3021 case Builtin::BIfmaximum_num:
3022 case Builtin::BIfmaximum_numf:
3023 case Builtin::BIfmaximum_numl:
3024 case Builtin::BI__builtin_fmaximum_num:
3025 case Builtin::BI__builtin_fmaximum_numf:
3026 case Builtin::BI__builtin_fmaximum_numf16:
3027 case Builtin::BI__builtin_fmaximum_numl:
3028 case Builtin::BI__builtin_fmaximum_numf128:
3029 return RValue::get(
3030 emitBuiltinWithOneOverloadedType<2>(*this, E, Intrinsic::maximumnum));
3031
3032 case Builtin::BIfminimum_num:
3033 case Builtin::BIfminimum_numf:
3034 case Builtin::BIfminimum_numl:
3035 case Builtin::BI__builtin_fminimum_num:
3036 case Builtin::BI__builtin_fminimum_numf:
3037 case Builtin::BI__builtin_fminimum_numf16:
3038 case Builtin::BI__builtin_fminimum_numl:
3039 case Builtin::BI__builtin_fminimum_numf128:
3040 return RValue::get(
3041 emitBuiltinWithOneOverloadedType<2>(*this, E, Intrinsic::minimumnum));
3042
3043 // fmod() is a special-case. It maps to the frem instruction rather than an
3044 // LLVM intrinsic.
3045 case Builtin::BIfmod:
3046 case Builtin::BIfmodf:
3047 case Builtin::BIfmodl:
3048 case Builtin::BI__builtin_fmod:
3049 case Builtin::BI__builtin_fmodf:
3050 case Builtin::BI__builtin_fmodf16:
3051 case Builtin::BI__builtin_fmodl:
3052 case Builtin::BI__builtin_fmodf128:
3053 case Builtin::BI__builtin_elementwise_fmod: {
3054 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
3055 Value *Arg1 = EmitScalarExpr(E->getArg(0));
3056 Value *Arg2 = EmitScalarExpr(E->getArg(1));
3057 if (Builder.getIsFPConstrained()) {
3058 Function *F = CGM.getIntrinsic(Intrinsic::experimental_constrained_frem,
3059 Arg1->getType());
3060 return RValue::get(Builder.CreateConstrainedFPCall(F, {Arg1, Arg2}));
3061 } else {
3062 return RValue::get(Builder.CreateFRem(Arg1, Arg2, "fmod"));
3063 }
3064 }
3065
3066 case Builtin::BIlog:
3067 case Builtin::BIlogf:
3068 case Builtin::BIlogl:
3069 case Builtin::BI__builtin_log:
3070 case Builtin::BI__builtin_logf:
3071 case Builtin::BI__builtin_logf16:
3072 case Builtin::BI__builtin_logl:
3073 case Builtin::BI__builtin_logf128:
3074 case Builtin::BI__builtin_elementwise_log:
3076 Intrinsic::log,
3077 Intrinsic::experimental_constrained_log));
3078
3079 case Builtin::BIlog10:
3080 case Builtin::BIlog10f:
3081 case Builtin::BIlog10l:
3082 case Builtin::BI__builtin_log10:
3083 case Builtin::BI__builtin_log10f:
3084 case Builtin::BI__builtin_log10f16:
3085 case Builtin::BI__builtin_log10l:
3086 case Builtin::BI__builtin_log10f128:
3087 case Builtin::BI__builtin_elementwise_log10:
3089 Intrinsic::log10,
3090 Intrinsic::experimental_constrained_log10));
3091
3092 case Builtin::BIlog2:
3093 case Builtin::BIlog2f:
3094 case Builtin::BIlog2l:
3095 case Builtin::BI__builtin_log2:
3096 case Builtin::BI__builtin_log2f:
3097 case Builtin::BI__builtin_log2f16:
3098 case Builtin::BI__builtin_log2l:
3099 case Builtin::BI__builtin_log2f128:
3100 case Builtin::BI__builtin_elementwise_log2:
3102 Intrinsic::log2,
3103 Intrinsic::experimental_constrained_log2));
3104
3105 case Builtin::BInearbyint:
3106 case Builtin::BInearbyintf:
3107 case Builtin::BInearbyintl:
3108 case Builtin::BI__builtin_nearbyint:
3109 case Builtin::BI__builtin_nearbyintf:
3110 case Builtin::BI__builtin_nearbyintl:
3111 case Builtin::BI__builtin_nearbyintf128:
3112 case Builtin::BI__builtin_elementwise_nearbyint:
3114 Intrinsic::nearbyint,
3115 Intrinsic::experimental_constrained_nearbyint));
3116
3117 case Builtin::BIpow:
3118 case Builtin::BIpowf:
3119 case Builtin::BIpowl:
3120 case Builtin::BI__builtin_pow:
3121 case Builtin::BI__builtin_powf:
3122 case Builtin::BI__builtin_powf16:
3123 case Builtin::BI__builtin_powl:
3124 case Builtin::BI__builtin_powf128:
3125 case Builtin::BI__builtin_elementwise_pow:
3127 Intrinsic::pow,
3128 Intrinsic::experimental_constrained_pow));
3129
3130 case Builtin::BIrint:
3131 case Builtin::BIrintf:
3132 case Builtin::BIrintl:
3133 case Builtin::BI__builtin_rint:
3134 case Builtin::BI__builtin_rintf:
3135 case Builtin::BI__builtin_rintf16:
3136 case Builtin::BI__builtin_rintl:
3137 case Builtin::BI__builtin_rintf128:
3138 case Builtin::BI__builtin_elementwise_rint:
3140 Intrinsic::rint,
3141 Intrinsic::experimental_constrained_rint));
3142
3143 case Builtin::BIround:
3144 case Builtin::BIroundf:
3145 case Builtin::BIroundl:
3146 case Builtin::BI__builtin_round:
3147 case Builtin::BI__builtin_roundf:
3148 case Builtin::BI__builtin_roundf16:
3149 case Builtin::BI__builtin_roundl:
3150 case Builtin::BI__builtin_roundf128:
3151 case Builtin::BI__builtin_elementwise_round:
3153 Intrinsic::round,
3154 Intrinsic::experimental_constrained_round));
3155
3156 case Builtin::BIroundeven:
3157 case Builtin::BIroundevenf:
3158 case Builtin::BIroundevenl:
3159 case Builtin::BI__builtin_roundeven:
3160 case Builtin::BI__builtin_roundevenf:
3161 case Builtin::BI__builtin_roundevenf16:
3162 case Builtin::BI__builtin_roundevenl:
3163 case Builtin::BI__builtin_roundevenf128:
3164 case Builtin::BI__builtin_elementwise_roundeven:
3166 Intrinsic::roundeven,
3167 Intrinsic::experimental_constrained_roundeven));
3168
3169 case Builtin::BIsin:
3170 case Builtin::BIsinf:
3171 case Builtin::BIsinl:
3172 case Builtin::BI__builtin_sin:
3173 case Builtin::BI__builtin_sinf:
3174 case Builtin::BI__builtin_sinf16:
3175 case Builtin::BI__builtin_sinl:
3176 case Builtin::BI__builtin_sinf128:
3177 case Builtin::BI__builtin_elementwise_sin:
3179 Intrinsic::sin,
3180 Intrinsic::experimental_constrained_sin));
3181
3182 case Builtin::BIsinh:
3183 case Builtin::BIsinhf:
3184 case Builtin::BIsinhl:
3185 case Builtin::BI__builtin_sinh:
3186 case Builtin::BI__builtin_sinhf:
3187 case Builtin::BI__builtin_sinhf16:
3188 case Builtin::BI__builtin_sinhl:
3189 case Builtin::BI__builtin_sinhf128:
3190 case Builtin::BI__builtin_elementwise_sinh:
3192 *this, E, Intrinsic::sinh, Intrinsic::experimental_constrained_sinh));
3193
3194 case Builtin::BI__builtin_sincospi:
3195 case Builtin::BI__builtin_sincospif:
3196 case Builtin::BI__builtin_sincospil:
3197 if (Builder.getIsFPConstrained())
3198 break; // TODO: Emit constrained sincospi intrinsic once one exists.
3199 emitSincosBuiltin(*this, E, Intrinsic::sincospi);
3200 return RValue::get(nullptr);
3201
3202 case Builtin::BIsincos:
3203 case Builtin::BIsincosf:
3204 case Builtin::BIsincosl:
3205 case Builtin::BI__builtin_sincos:
3206 case Builtin::BI__builtin_sincosf:
3207 case Builtin::BI__builtin_sincosf16:
3208 case Builtin::BI__builtin_sincosl:
3209 case Builtin::BI__builtin_sincosf128:
3210 if (Builder.getIsFPConstrained())
3211 break; // TODO: Emit constrained sincos intrinsic once one exists.
3212 emitSincosBuiltin(*this, E, Intrinsic::sincos);
3213 return RValue::get(nullptr);
3214
3215 case Builtin::BIsqrt:
3216 case Builtin::BIsqrtf:
3217 case Builtin::BIsqrtl:
3218 case Builtin::BI__builtin_sqrt:
3219 case Builtin::BI__builtin_sqrtf:
3220 case Builtin::BI__builtin_sqrtf16:
3221 case Builtin::BI__builtin_sqrtl:
3222 case Builtin::BI__builtin_sqrtf128:
3223 case Builtin::BI__builtin_elementwise_sqrt: {
3225 *this, E, Intrinsic::sqrt, Intrinsic::experimental_constrained_sqrt);
3227 return RValue::get(Call);
3228 }
3229
3230 case Builtin::BItan:
3231 case Builtin::BItanf:
3232 case Builtin::BItanl:
3233 case Builtin::BI__builtin_tan:
3234 case Builtin::BI__builtin_tanf:
3235 case Builtin::BI__builtin_tanf16:
3236 case Builtin::BI__builtin_tanl:
3237 case Builtin::BI__builtin_tanf128:
3238 case Builtin::BI__builtin_elementwise_tan:
3240 *this, E, Intrinsic::tan, Intrinsic::experimental_constrained_tan));
3241
3242 case Builtin::BItanh:
3243 case Builtin::BItanhf:
3244 case Builtin::BItanhl:
3245 case Builtin::BI__builtin_tanh:
3246 case Builtin::BI__builtin_tanhf:
3247 case Builtin::BI__builtin_tanhf16:
3248 case Builtin::BI__builtin_tanhl:
3249 case Builtin::BI__builtin_tanhf128:
3250 case Builtin::BI__builtin_elementwise_tanh:
3252 *this, E, Intrinsic::tanh, Intrinsic::experimental_constrained_tanh));
3253
3254 case Builtin::BItrunc:
3255 case Builtin::BItruncf:
3256 case Builtin::BItruncl:
3257 case Builtin::BI__builtin_trunc:
3258 case Builtin::BI__builtin_truncf:
3259 case Builtin::BI__builtin_truncf16:
3260 case Builtin::BI__builtin_truncl:
3261 case Builtin::BI__builtin_truncf128:
3262 case Builtin::BI__builtin_elementwise_trunc:
3264 Intrinsic::trunc,
3265 Intrinsic::experimental_constrained_trunc));
3266
3267 case Builtin::BIlround:
3268 case Builtin::BIlroundf:
3269 case Builtin::BIlroundl:
3270 case Builtin::BI__builtin_lround:
3271 case Builtin::BI__builtin_lroundf:
3272 case Builtin::BI__builtin_lroundl:
3273 case Builtin::BI__builtin_lroundf128:
3275 *this, E, Intrinsic::lround,
3276 Intrinsic::experimental_constrained_lround));
3277
3278 case Builtin::BIllround:
3279 case Builtin::BIllroundf:
3280 case Builtin::BIllroundl:
3281 case Builtin::BI__builtin_llround:
3282 case Builtin::BI__builtin_llroundf:
3283 case Builtin::BI__builtin_llroundl:
3284 case Builtin::BI__builtin_llroundf128:
3286 *this, E, Intrinsic::llround,
3287 Intrinsic::experimental_constrained_llround));
3288
3289 case Builtin::BIlrint:
3290 case Builtin::BIlrintf:
3291 case Builtin::BIlrintl:
3292 case Builtin::BI__builtin_lrint:
3293 case Builtin::BI__builtin_lrintf:
3294 case Builtin::BI__builtin_lrintl:
3295 case Builtin::BI__builtin_lrintf128:
3297 *this, E, Intrinsic::lrint,
3298 Intrinsic::experimental_constrained_lrint));
3299
3300 case Builtin::BIllrint:
3301 case Builtin::BIllrintf:
3302 case Builtin::BIllrintl:
3303 case Builtin::BI__builtin_llrint:
3304 case Builtin::BI__builtin_llrintf:
3305 case Builtin::BI__builtin_llrintl:
3306 case Builtin::BI__builtin_llrintf128:
3308 *this, E, Intrinsic::llrint,
3309 Intrinsic::experimental_constrained_llrint));
3310 case Builtin::BI__builtin_ldexp:
3311 case Builtin::BI__builtin_ldexpf:
3312 case Builtin::BI__builtin_ldexpl:
3313 case Builtin::BI__builtin_ldexpf16:
3314 case Builtin::BI__builtin_ldexpf128:
3315 case Builtin::BI__builtin_elementwise_ldexp:
3317 *this, E, Intrinsic::ldexp,
3318 Intrinsic::experimental_constrained_ldexp));
3319 default:
3320 break;
3321 }
3322 }
3323
3324 // Check NonnullAttribute/NullabilityArg and Alignment.
3325 auto EmitArgCheck = [&](TypeCheckKind Kind, Address A, const Expr *Arg,
3326 unsigned ParmNum) {
3327 Value *Val = A.emitRawPointer(*this);
3328 EmitNonNullArgCheck(RValue::get(Val), Arg->getType(), Arg->getExprLoc(), FD,
3329 ParmNum);
3330
3331 if (SanOpts.has(SanitizerKind::Alignment)) {
3332 SanitizerSet SkippedChecks;
3333 SkippedChecks.set(SanitizerKind::All);
3334 SkippedChecks.clear(SanitizerKind::Alignment);
3335 SourceLocation Loc = Arg->getExprLoc();
3336 // Strip an implicit cast.
3337 if (auto *CE = dyn_cast<ImplicitCastExpr>(Arg))
3338 if (CE->getCastKind() == CK_BitCast)
3339 Arg = CE->getSubExpr();
3340 EmitTypeCheck(Kind, Loc, Val, Arg->getType(), A.getAlignment(),
3341 SkippedChecks);
3342 }
3343 };
3344
3345 switch (BuiltinIDIfNoAsmLabel) {
3346 default: break;
3347 case Builtin::BI__builtin___CFStringMakeConstantString:
3348 case Builtin::BI__builtin___NSStringMakeConstantString:
3349 return RValue::get(ConstantEmitter(*this).emitAbstract(E, E->getType()));
3350 case Builtin::BI__builtin_stdarg_start:
3351 case Builtin::BI__builtin_va_start:
3352 case Builtin::BI__va_start:
3353 case Builtin::BI__builtin_c23_va_start:
3354 case Builtin::BI__builtin_va_end:
3355 EmitVAStartEnd(BuiltinID == Builtin::BI__va_start
3356 ? EmitScalarExpr(E->getArg(0))
3357 : EmitVAListRef(E->getArg(0)).emitRawPointer(*this),
3358 BuiltinID != Builtin::BI__builtin_va_end);
3359 return RValue::get(nullptr);
3360 case Builtin::BI__builtin_va_copy: {
3361 Value *DstPtr = EmitVAListRef(E->getArg(0)).emitRawPointer(*this);
3362 Value *SrcPtr = EmitVAListRef(E->getArg(1)).emitRawPointer(*this);
3363 Builder.CreateCall(CGM.getIntrinsic(Intrinsic::vacopy, {DstPtr->getType()}),
3364 {DstPtr, SrcPtr});
3365 return RValue::get(nullptr);
3366 }
3367 case Builtin::BIabs:
3368 case Builtin::BIlabs:
3369 case Builtin::BIllabs:
3370 case Builtin::BI__builtin_abs:
3371 case Builtin::BI__builtin_labs:
3372 case Builtin::BI__builtin_llabs: {
3373 bool SanitizeOverflow = SanOpts.has(SanitizerKind::SignedIntegerOverflow);
3374
3375 Value *Result;
3376 switch (getLangOpts().getSignedOverflowBehavior()) {
3378 Result = EmitAbs(*this, EmitScalarExpr(E->getArg(0)), false);
3379 break;
3381 if (!SanitizeOverflow) {
3382 Result = EmitAbs(*this, EmitScalarExpr(E->getArg(0)), true);
3383 break;
3384 }
3385 [[fallthrough]];
3387 // TODO: Somehow handle the corner case when the address of abs is taken.
3388 Result = EmitOverflowCheckedAbs(*this, E, SanitizeOverflow);
3389 break;
3390 }
3391 return RValue::get(Result);
3392 }
3393 case Builtin::BI__builtin_complex: {
3394 Value *Real = EmitScalarExpr(E->getArg(0));
3395 Value *Imag = EmitScalarExpr(E->getArg(1));
3396 return RValue::getComplex({Real, Imag});
3397 }
3398 case Builtin::BI__builtin_conj:
3399 case Builtin::BI__builtin_conjf:
3400 case Builtin::BI__builtin_conjl:
3401 case Builtin::BIconj:
3402 case Builtin::BIconjf:
3403 case Builtin::BIconjl: {
3404 ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0));
3405 Value *Real = ComplexVal.first;
3406 Value *Imag = ComplexVal.second;
3407 Imag = Builder.CreateFNeg(Imag, "neg");
3408 return RValue::getComplex(std::make_pair(Real, Imag));
3409 }
3410 case Builtin::BI__builtin_creal:
3411 case Builtin::BI__builtin_crealf:
3412 case Builtin::BI__builtin_creall:
3413 case Builtin::BIcreal:
3414 case Builtin::BIcrealf:
3415 case Builtin::BIcreall: {
3416 ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0));
3417 return RValue::get(ComplexVal.first);
3418 }
3419
3420 case Builtin::BI__builtin_preserve_access_index: {
3421 // Only enabled preserved access index region when debuginfo
3422 // is available as debuginfo is needed to preserve user-level
3423 // access pattern.
3424 if (!getDebugInfo()) {
3425 CGM.Error(E->getExprLoc(), "using builtin_preserve_access_index() without -g");
3426 return RValue::get(EmitScalarExpr(E->getArg(0)));
3427 }
3428
3429 // Nested builtin_preserve_access_index() not supported
3431 CGM.Error(E->getExprLoc(), "nested builtin_preserve_access_index() not supported");
3432 return RValue::get(EmitScalarExpr(E->getArg(0)));
3433 }
3434
3435 IsInPreservedAIRegion = true;
3436 Value *Res = EmitScalarExpr(E->getArg(0));
3437 IsInPreservedAIRegion = false;
3438 return RValue::get(Res);
3439 }
3440
3441 case Builtin::BI__builtin_cimag:
3442 case Builtin::BI__builtin_cimagf:
3443 case Builtin::BI__builtin_cimagl:
3444 case Builtin::BIcimag:
3445 case Builtin::BIcimagf:
3446 case Builtin::BIcimagl: {
3447 ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0));
3448 return RValue::get(ComplexVal.second);
3449 }
3450
3451 case Builtin::BI__builtin_clrsb:
3452 case Builtin::BI__builtin_clrsbl:
3453 case Builtin::BI__builtin_clrsbll: {
3454 // clrsb(x) -> clz(x < 0 ? ~x : x) - 1 or
3455 Value *ArgValue = EmitScalarExpr(E->getArg(0));
3456
3457 llvm::Type *ArgType = ArgValue->getType();
3458 Function *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
3459
3460 llvm::Type *ResultType = ConvertType(E->getType());
3461 Value *Zero = llvm::Constant::getNullValue(ArgType);
3462 Value *IsNeg = Builder.CreateICmpSLT(ArgValue, Zero, "isneg");
3463 Value *Inverse = Builder.CreateNot(ArgValue, "not");
3464 Value *Tmp = Builder.CreateSelect(IsNeg, Inverse, ArgValue);
3465 Value *Ctlz = Builder.CreateCall(F, {Tmp, Builder.getFalse()});
3466 Value *Result =
3467 Builder.CreateNUWSub(Ctlz, llvm::ConstantInt::get(ArgType, 1));
3468 Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
3469 "cast");
3470 return RValue::get(Result);
3471 }
3472 case Builtin::BI__builtin_ctzs:
3473 case Builtin::BI__builtin_ctz:
3474 case Builtin::BI__builtin_ctzl:
3475 case Builtin::BI__builtin_ctzll:
3476 case Builtin::BI__builtin_ctzg:
3477 case Builtin::BI__builtin_elementwise_ctzg: {
3478 bool HasFallback =
3479 (BuiltinIDIfNoAsmLabel == Builtin::BI__builtin_ctzg ||
3480 BuiltinIDIfNoAsmLabel == Builtin::BI__builtin_elementwise_ctzg) &&
3481 E->getNumArgs() > 1;
3482
3483 Value *ArgValue =
3484 HasFallback ? EmitBitCountExpr(*this, E->getArg(0))
3486
3487 llvm::Type *ArgType = ArgValue->getType();
3488 Function *F = CGM.getIntrinsic(Intrinsic::cttz, ArgType);
3489
3490 llvm::Type *ResultType = ConvertType(E->getType());
3491 // The elementwise builtins always exhibit zero-is-undef behaviour
3492 Value *ZeroUndef = Builder.getInt1(
3493 HasFallback || getTarget().isCLZForZeroUndef() ||
3494 BuiltinIDIfNoAsmLabel == Builtin::BI__builtin_elementwise_ctzg);
3495 Value *Result = Builder.CreateCall(F, {ArgValue, ZeroUndef});
3496 if (Result->getType() != ResultType)
3497 Result =
3498 Builder.CreateIntCast(Result, ResultType, /*isSigned*/ false, "cast");
3499 if (!HasFallback)
3500 return RValue::get(Result);
3501
3502 Value *Zero = Constant::getNullValue(ArgType);
3503 Value *IsZero = Builder.CreateICmpEQ(ArgValue, Zero, "iszero");
3504 Value *FallbackValue = EmitScalarExpr(E->getArg(1));
3505 Value *ResultOrFallback =
3506 Builder.CreateSelect(IsZero, FallbackValue, Result, "ctzg");
3507 return RValue::get(ResultOrFallback);
3508 }
3509 case Builtin::BI__builtin_clzs:
3510 case Builtin::BI__builtin_clz:
3511 case Builtin::BI__builtin_clzl:
3512 case Builtin::BI__builtin_clzll:
3513 case Builtin::BI__builtin_clzg:
3514 case Builtin::BI__builtin_elementwise_clzg: {
3515 bool HasFallback =
3516 (BuiltinIDIfNoAsmLabel == Builtin::BI__builtin_clzg ||
3517 BuiltinIDIfNoAsmLabel == Builtin::BI__builtin_elementwise_clzg) &&
3518 E->getNumArgs() > 1;
3519
3520 Value *ArgValue =
3521 HasFallback ? EmitBitCountExpr(*this, E->getArg(0))
3523
3524 llvm::Type *ArgType = ArgValue->getType();
3525 Function *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
3526
3527 llvm::Type *ResultType = ConvertType(E->getType());
3528 // The elementwise builtins always exhibit zero-is-undef behaviour
3529 Value *ZeroUndef = Builder.getInt1(
3530 HasFallback || getTarget().isCLZForZeroUndef() ||
3531 BuiltinIDIfNoAsmLabel == Builtin::BI__builtin_elementwise_clzg);
3532 Value *Result = Builder.CreateCall(F, {ArgValue, ZeroUndef});
3533 if (Result->getType() != ResultType)
3534 Result =
3535 Builder.CreateIntCast(Result, ResultType, /*isSigned*/ false, "cast");
3536 if (!HasFallback)
3537 return RValue::get(Result);
3538
3539 Value *Zero = Constant::getNullValue(ArgType);
3540 Value *IsZero = Builder.CreateICmpEQ(ArgValue, Zero, "iszero");
3541 Value *FallbackValue = EmitScalarExpr(E->getArg(1));
3542 Value *ResultOrFallback =
3543 Builder.CreateSelect(IsZero, FallbackValue, Result, "clzg");
3544 return RValue::get(ResultOrFallback);
3545 }
3546 case Builtin::BI__builtin_ffs:
3547 case Builtin::BI__builtin_ffsl:
3548 case Builtin::BI__builtin_ffsll: {
3549 // ffs(x) -> x ? cttz(x) + 1 : 0
3550 Value *ArgValue = EmitScalarExpr(E->getArg(0));
3551
3552 llvm::Type *ArgType = ArgValue->getType();
3553 Function *F = CGM.getIntrinsic(Intrinsic::cttz, ArgType);
3554
3555 llvm::Type *ResultType = ConvertType(E->getType());
3556 Value *Tmp =
3557 Builder.CreateAdd(Builder.CreateCall(F, {ArgValue, Builder.getTrue()}),
3558 llvm::ConstantInt::get(ArgType, 1));
3559 Value *Zero = llvm::Constant::getNullValue(ArgType);
3560 Value *IsZero = Builder.CreateICmpEQ(ArgValue, Zero, "iszero");
3561 Value *Result = Builder.CreateSelect(IsZero, Zero, Tmp, "ffs");
3562 if (Result->getType() != ResultType)
3563 Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
3564 "cast");
3565 return RValue::get(Result);
3566 }
3567 case Builtin::BI__builtin_parity:
3568 case Builtin::BI__builtin_parityl:
3569 case Builtin::BI__builtin_parityll: {
3570 // parity(x) -> ctpop(x) & 1
3571 Value *ArgValue = EmitScalarExpr(E->getArg(0));
3572
3573 llvm::Type *ArgType = ArgValue->getType();
3574 Function *F = CGM.getIntrinsic(Intrinsic::ctpop, ArgType);
3575
3576 llvm::Type *ResultType = ConvertType(E->getType());
3577 Value *Tmp = Builder.CreateCall(F, ArgValue);
3578 Value *Result = Builder.CreateAnd(Tmp, llvm::ConstantInt::get(ArgType, 1));
3579 if (Result->getType() != ResultType)
3580 Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
3581 "cast");
3582 return RValue::get(Result);
3583 }
3584 case Builtin::BI__lzcnt16:
3585 case Builtin::BI__lzcnt:
3586 case Builtin::BI__lzcnt64: {
3587 Value *ArgValue = EmitScalarExpr(E->getArg(0));
3588
3589 llvm::Type *ArgType = ArgValue->getType();
3590 Function *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
3591
3592 llvm::Type *ResultType = ConvertType(E->getType());
3593 Value *Result = Builder.CreateCall(F, {ArgValue, Builder.getFalse()});
3594 if (Result->getType() != ResultType)
3595 Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
3596 "cast");
3597 return RValue::get(Result);
3598 }
3599 case Builtin::BI__popcnt16:
3600 case Builtin::BI__popcnt:
3601 case Builtin::BI__popcnt64:
3602 case Builtin::BI__builtin_popcount:
3603 case Builtin::BI__builtin_popcountl:
3604 case Builtin::BI__builtin_popcountll:
3605 case Builtin::BI__builtin_popcountg: {
3606 Value *ArgValue = EmitBitCountExpr(*this, E->getArg(0));
3607
3608 llvm::Type *ArgType = ArgValue->getType();
3609 Function *F = CGM.getIntrinsic(Intrinsic::ctpop, ArgType);
3610
3611 llvm::Type *ResultType = ConvertType(E->getType());
3612 Value *Result = Builder.CreateCall(F, ArgValue);
3613 if (Result->getType() != ResultType)
3614 Result =
3615 Builder.CreateIntCast(Result, ResultType, /*isSigned*/ false, "cast");
3616 return RValue::get(Result);
3617 }
3618 case Builtin::BI__builtin_unpredictable: {
3619 // Always return the argument of __builtin_unpredictable. LLVM does not
3620 // handle this builtin. Metadata for this builtin should be added directly
3621 // to instructions such as branches or switches that use it.
3622 return RValue::get(EmitScalarExpr(E->getArg(0)));
3623 }
3624 case Builtin::BI__builtin_expect: {
3625 Value *ArgValue = EmitScalarExpr(E->getArg(0));
3626 llvm::Type *ArgType = ArgValue->getType();
3627
3628 Value *ExpectedValue = EmitScalarExpr(E->getArg(1));
3629 // Don't generate llvm.expect on -O0 as the backend won't use it for
3630 // anything.
3631 // Note, we still IRGen ExpectedValue because it could have side-effects.
3632 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
3633 return RValue::get(ArgValue);
3634
3635 Function *FnExpect = CGM.getIntrinsic(Intrinsic::expect, ArgType);
3636 Value *Result =
3637 Builder.CreateCall(FnExpect, {ArgValue, ExpectedValue}, "expval");
3638 return RValue::get(Result);
3639 }
3640 case Builtin::BI__builtin_expect_with_probability: {
3641 Value *ArgValue = EmitScalarExpr(E->getArg(0));
3642 llvm::Type *ArgType = ArgValue->getType();
3643
3644 Value *ExpectedValue = EmitScalarExpr(E->getArg(1));
3645 llvm::APFloat Probability(0.0);
3646 const Expr *ProbArg = E->getArg(2);
3647 bool EvalSucceed = ProbArg->EvaluateAsFloat(Probability, CGM.getContext());
3648 assert(EvalSucceed && "probability should be able to evaluate as float");
3649 (void)EvalSucceed;
3650 bool LoseInfo = false;
3651 Probability.convert(llvm::APFloat::IEEEdouble(),
3652 llvm::RoundingMode::Dynamic, &LoseInfo);
3653 llvm::Type *Ty = ConvertType(ProbArg->getType());
3654 Constant *Confidence = ConstantFP::get(Ty, Probability);
3655 // Don't generate llvm.expect.with.probability on -O0 as the backend
3656 // won't use it for anything.
3657 // Note, we still IRGen ExpectedValue because it could have side-effects.
3658 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
3659 return RValue::get(ArgValue);
3660
3661 Function *FnExpect =
3662 CGM.getIntrinsic(Intrinsic::expect_with_probability, ArgType);
3663 Value *Result = Builder.CreateCall(
3664 FnExpect, {ArgValue, ExpectedValue, Confidence}, "expval");
3665 return RValue::get(Result);
3666 }
3667 case Builtin::BI__builtin_assume_aligned: {
3668 const Expr *Ptr = E->getArg(0);
3669 Value *PtrValue = EmitScalarExpr(Ptr);
3670 Value *OffsetValue =
3671 (E->getNumArgs() > 2) ? EmitScalarExpr(E->getArg(2)) : nullptr;
3672
3673 Value *AlignmentValue = EmitScalarExpr(E->getArg(1));
3674 ConstantInt *AlignmentCI = cast<ConstantInt>(AlignmentValue);
3675 if (AlignmentCI->getValue().ugt(llvm::Value::MaximumAlignment))
3676 AlignmentCI = ConstantInt::get(AlignmentCI->getIntegerType(),
3677 llvm::Value::MaximumAlignment);
3678
3679 emitAlignmentAssumption(PtrValue, Ptr,
3680 /*The expr loc is sufficient.*/ SourceLocation(),
3681 AlignmentCI, OffsetValue);
3682 return RValue::get(PtrValue);
3683 }
3684 case Builtin::BI__builtin_assume_dereferenceable: {
3685 const Expr *Ptr = E->getArg(0);
3686 const Expr *Size = E->getArg(1);
3687 Value *PtrValue = EmitScalarExpr(Ptr);
3688 Value *SizeValue = EmitScalarExpr(Size);
3689 if (SizeValue->getType() != IntPtrTy)
3690 SizeValue =
3691 Builder.CreateIntCast(SizeValue, IntPtrTy, false, "casted.size");
3692 Builder.CreateDereferenceableAssumption(PtrValue, SizeValue);
3693 return RValue::get(nullptr);
3694 }
3695 case Builtin::BI__assume:
3696 case Builtin::BI__builtin_assume: {
3697 if (E->getArg(0)->HasSideEffects(getContext()))
3698 return RValue::get(nullptr);
3699
3700 Value *ArgValue = EmitCheckedArgForAssume(E->getArg(0));
3701 Function *FnAssume = CGM.getIntrinsic(Intrinsic::assume);
3702 Builder.CreateCall(FnAssume, ArgValue);
3703 return RValue::get(nullptr);
3704 }
3705 case Builtin::BI__builtin_assume_separate_storage: {
3706 const Expr *Arg0 = E->getArg(0);
3707 const Expr *Arg1 = E->getArg(1);
3708
3709 Value *Value0 = EmitScalarExpr(Arg0);
3710 Value *Value1 = EmitScalarExpr(Arg1);
3711
3712 Value *Values[] = {Value0, Value1};
3713 OperandBundleDefT<Value *> OBD("separate_storage", Values);
3714 Builder.CreateAssumption({OBD});
3715 return RValue::get(nullptr);
3716 }
3717 case Builtin::BI__builtin_allow_runtime_check: {
3718 StringRef Kind =
3719 cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())->getString();
3720 LLVMContext &Ctx = CGM.getLLVMContext();
3721 llvm::Value *Allow = Builder.CreateCall(
3722 CGM.getIntrinsic(Intrinsic::allow_runtime_check),
3723 llvm::MetadataAsValue::get(Ctx, llvm::MDString::get(Ctx, Kind)));
3724 return RValue::get(Allow);
3725 }
3726 case Builtin::BI__builtin_allow_sanitize_check: {
3727 Intrinsic::ID IntrID = Intrinsic::not_intrinsic;
3728 StringRef Name =
3729 cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())->getString();
3730
3731 // We deliberately allow the use of kernel- and non-kernel names
3732 // interchangably, even when one or the other is enabled. This is consistent
3733 // with the no_sanitize-attribute, which allows either kernel- or non-kernel
3734 // name to disable instrumentation (see CodeGenFunction::StartFunction).
3735 if (getLangOpts().Sanitize.hasOneOf(SanitizerKind::Address |
3736 SanitizerKind::KernelAddress) &&
3737 (Name == "address" || Name == "kernel-address")) {
3738 IntrID = Intrinsic::allow_sanitize_address;
3739 } else if (getLangOpts().Sanitize.has(SanitizerKind::Thread) &&
3740 Name == "thread") {
3741 IntrID = Intrinsic::allow_sanitize_thread;
3742 } else if (getLangOpts().Sanitize.hasOneOf(SanitizerKind::Memory |
3743 SanitizerKind::KernelMemory) &&
3744 (Name == "memory" || Name == "kernel-memory")) {
3745 IntrID = Intrinsic::allow_sanitize_memory;
3746 } else if (getLangOpts().Sanitize.hasOneOf(
3747 SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress) &&
3748 (Name == "hwaddress" || Name == "kernel-hwaddress")) {
3749 IntrID = Intrinsic::allow_sanitize_hwaddress;
3750 }
3751
3752 if (IntrID != Intrinsic::not_intrinsic) {
3753 llvm::Value *Allow = Builder.CreateCall(CGM.getIntrinsic(IntrID));
3754 return RValue::get(Allow);
3755 }
3756 // If the checked sanitizer is not enabled, we can safely lower to false
3757 // right away. This is also more efficient, since the LowerAllowCheckPass
3758 // must not always be enabled if none of the above sanitizers are enabled.
3759 return RValue::get(Builder.getFalse());
3760 }
3761 case Builtin::BI__arithmetic_fence: {
3762 // Create the builtin call if FastMath is selected, and the target
3763 // supports the builtin, otherwise just return the argument.
3764 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
3765 llvm::FastMathFlags FMF = Builder.getFastMathFlags();
3766 bool isArithmeticFenceEnabled =
3767 FMF.allowReassoc() &&
3769 QualType ArgType = E->getArg(0)->getType();
3770 if (ArgType->isComplexType()) {
3771 if (isArithmeticFenceEnabled) {
3772 QualType ElementType = ArgType->castAs<ComplexType>()->getElementType();
3773 ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0));
3774 Value *Real = Builder.CreateArithmeticFence(ComplexVal.first,
3775 ConvertType(ElementType));
3776 Value *Imag = Builder.CreateArithmeticFence(ComplexVal.second,
3777 ConvertType(ElementType));
3778 return RValue::getComplex(std::make_pair(Real, Imag));
3779 }
3780 ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0));
3781 Value *Real = ComplexVal.first;
3782 Value *Imag = ComplexVal.second;
3783 return RValue::getComplex(std::make_pair(Real, Imag));
3784 }
3785 Value *ArgValue = EmitScalarExpr(E->getArg(0));
3786 if (isArithmeticFenceEnabled)
3787 return RValue::get(
3788 Builder.CreateArithmeticFence(ArgValue, ConvertType(ArgType)));
3789 return RValue::get(ArgValue);
3790 }
3791 case Builtin::BI__builtin_bswapg: {
3792 Value *ArgValue = EmitScalarExpr(E->getArg(0));
3793 llvm::IntegerType *IntTy = cast<llvm::IntegerType>(ArgValue->getType());
3794 assert(IntTy && "LLVM's __builtin_bswapg only supports integer variants");
3795 if (IntTy->getBitWidth() == 1 || IntTy->getBitWidth() == 8)
3796 return RValue::get(ArgValue);
3797 assert(((IntTy->getBitWidth() % 16 == 0 && IntTy->getBitWidth() != 0)) &&
3798 "LLVM's __builtin_bswapg only supports integer variants that has a "
3799 "multiple of 16 bits as well as a single byte");
3800 return RValue::get(
3801 emitBuiltinWithOneOverloadedType<1>(*this, E, Intrinsic::bswap));
3802 }
3803 case Builtin::BI__builtin_bswap16:
3804 case Builtin::BI__builtin_bswap32:
3805 case Builtin::BI__builtin_bswap64:
3806 case Builtin::BI_byteswap_ushort:
3807 case Builtin::BI_byteswap_ulong:
3808 case Builtin::BI_byteswap_uint64: {
3809 return RValue::get(
3810 emitBuiltinWithOneOverloadedType<1>(*this, E, Intrinsic::bswap));
3811 }
3812 case Builtin::BI__builtin_bitreverseg: {
3813 Value *ArgValue = EmitScalarExpr(E->getArg(0));
3814 llvm::IntegerType *IntTy = cast<llvm::IntegerType>(ArgValue->getType());
3815 assert(IntTy &&
3816 "LLVM's __builtin_bitreverseg only support integer variants");
3817 if (IntTy->getBitWidth() == 1)
3818 return RValue::get(ArgValue);
3819 return RValue::get(
3820 emitBuiltinWithOneOverloadedType<1>(*this, E, Intrinsic::bitreverse));
3821 }
3822 case Builtin::BI__builtin_bitreverse8:
3823 case Builtin::BI__builtin_bitreverse16:
3824 case Builtin::BI__builtin_bitreverse32:
3825 case Builtin::BI__builtin_bitreverse64: {
3826 return RValue::get(
3827 emitBuiltinWithOneOverloadedType<1>(*this, E, Intrinsic::bitreverse));
3828 }
3829 case Builtin::BI__builtin_rotateleft8:
3830 case Builtin::BI__builtin_rotateleft16:
3831 case Builtin::BI__builtin_rotateleft32:
3832 case Builtin::BI__builtin_rotateleft64:
3833 case Builtin::BI__builtin_stdc_rotate_left:
3834 case Builtin::BIstdc_rotate_left_uc:
3835 case Builtin::BIstdc_rotate_left_us:
3836 case Builtin::BIstdc_rotate_left_ui:
3837 case Builtin::BIstdc_rotate_left_ul:
3838 case Builtin::BIstdc_rotate_left_ull:
3839 case Builtin::BI_rotl8: // Microsoft variants of rotate left
3840 case Builtin::BI_rotl16:
3841 case Builtin::BI_rotl:
3842 case Builtin::BI_lrotl:
3843 case Builtin::BI_rotl64:
3844 return emitRotate(E, false);
3845
3846 case Builtin::BI__builtin_rotateright8:
3847 case Builtin::BI__builtin_rotateright16:
3848 case Builtin::BI__builtin_rotateright32:
3849 case Builtin::BI__builtin_rotateright64:
3850 case Builtin::BI__builtin_stdc_rotate_right:
3851 case Builtin::BIstdc_rotate_right_uc:
3852 case Builtin::BIstdc_rotate_right_us:
3853 case Builtin::BIstdc_rotate_right_ui:
3854 case Builtin::BIstdc_rotate_right_ul:
3855 case Builtin::BIstdc_rotate_right_ull:
3856 case Builtin::BI_rotr8: // Microsoft variants of rotate right
3857 case Builtin::BI_rotr16:
3858 case Builtin::BI_rotr:
3859 case Builtin::BI_lrotr:
3860 case Builtin::BI_rotr64:
3861 return emitRotate(E, true);
3862
3863 case Builtin::BIstdc_leading_zeros_uc:
3864 case Builtin::BIstdc_leading_zeros_us:
3865 case Builtin::BIstdc_leading_zeros_ui:
3866 case Builtin::BIstdc_leading_zeros_ul:
3867 case Builtin::BIstdc_leading_zeros_ull:
3868 case Builtin::BI__builtin_stdc_leading_zeros:
3869 return emitStdcCountIntrinsic(E, Intrinsic::ctlz, /*InvertArg=*/false);
3870 case Builtin::BIstdc_leading_ones_uc:
3871 case Builtin::BIstdc_leading_ones_us:
3872 case Builtin::BIstdc_leading_ones_ui:
3873 case Builtin::BIstdc_leading_ones_ul:
3874 case Builtin::BIstdc_leading_ones_ull:
3875 case Builtin::BI__builtin_stdc_leading_ones:
3876 return emitStdcCountIntrinsic(E, Intrinsic::ctlz, /*InvertArg=*/true);
3877 case Builtin::BIstdc_trailing_zeros_uc:
3878 case Builtin::BIstdc_trailing_zeros_us:
3879 case Builtin::BIstdc_trailing_zeros_ui:
3880 case Builtin::BIstdc_trailing_zeros_ul:
3881 case Builtin::BIstdc_trailing_zeros_ull:
3882 case Builtin::BI__builtin_stdc_trailing_zeros:
3883 return emitStdcCountIntrinsic(E, Intrinsic::cttz, /*InvertArg=*/false);
3884 case Builtin::BIstdc_trailing_ones_uc:
3885 case Builtin::BIstdc_trailing_ones_us:
3886 case Builtin::BIstdc_trailing_ones_ui:
3887 case Builtin::BIstdc_trailing_ones_ul:
3888 case Builtin::BIstdc_trailing_ones_ull:
3889 case Builtin::BI__builtin_stdc_trailing_ones:
3890 return emitStdcCountIntrinsic(E, Intrinsic::cttz, /*InvertArg=*/true);
3891 case Builtin::BIstdc_first_leading_zero_uc:
3892 case Builtin::BIstdc_first_leading_zero_us:
3893 case Builtin::BIstdc_first_leading_zero_ui:
3894 case Builtin::BIstdc_first_leading_zero_ul:
3895 case Builtin::BIstdc_first_leading_zero_ull:
3896 case Builtin::BI__builtin_stdc_first_leading_zero:
3897 return emitStdcFirstBit(E, Intrinsic::ctlz, /*InvertArg=*/true);
3898 case Builtin::BIstdc_first_leading_one_uc:
3899 case Builtin::BIstdc_first_leading_one_us:
3900 case Builtin::BIstdc_first_leading_one_ui:
3901 case Builtin::BIstdc_first_leading_one_ul:
3902 case Builtin::BIstdc_first_leading_one_ull:
3903 case Builtin::BI__builtin_stdc_first_leading_one:
3904 return emitStdcFirstBit(E, Intrinsic::ctlz, /*InvertArg=*/false);
3905 case Builtin::BIstdc_first_trailing_zero_uc:
3906 case Builtin::BIstdc_first_trailing_zero_us:
3907 case Builtin::BIstdc_first_trailing_zero_ui:
3908 case Builtin::BIstdc_first_trailing_zero_ul:
3909 case Builtin::BIstdc_first_trailing_zero_ull:
3910 case Builtin::BI__builtin_stdc_first_trailing_zero:
3911 return emitStdcFirstBit(E, Intrinsic::cttz, /*InvertArg=*/true);
3912 case Builtin::BIstdc_first_trailing_one_uc:
3913 case Builtin::BIstdc_first_trailing_one_us:
3914 case Builtin::BIstdc_first_trailing_one_ui:
3915 case Builtin::BIstdc_first_trailing_one_ul:
3916 case Builtin::BIstdc_first_trailing_one_ull:
3917 case Builtin::BI__builtin_stdc_first_trailing_one:
3918 return emitStdcFirstBit(E, Intrinsic::cttz, /*InvertArg=*/false);
3919 case Builtin::BIstdc_count_zeros_uc:
3920 case Builtin::BIstdc_count_zeros_us:
3921 case Builtin::BIstdc_count_zeros_ui:
3922 case Builtin::BIstdc_count_zeros_ul:
3923 case Builtin::BIstdc_count_zeros_ull:
3924 case Builtin::BI__builtin_stdc_count_zeros:
3925 return emitStdcBitWidthMinus(E, Intrinsic::ctpop, /*IsPop=*/true);
3926 case Builtin::BIstdc_count_ones_uc:
3927 case Builtin::BIstdc_count_ones_us:
3928 case Builtin::BIstdc_count_ones_ui:
3929 case Builtin::BIstdc_count_ones_ul:
3930 case Builtin::BIstdc_count_ones_ull:
3931 case Builtin::BI__builtin_stdc_count_ones:
3932 return emitStdcCountIntrinsic(E, Intrinsic::ctpop, /*InvertArg=*/false,
3933 /*IsPop=*/true);
3934 case Builtin::BIstdc_has_single_bit_uc:
3935 case Builtin::BIstdc_has_single_bit_us:
3936 case Builtin::BIstdc_has_single_bit_ui:
3937 case Builtin::BIstdc_has_single_bit_ul:
3938 case Builtin::BIstdc_has_single_bit_ull:
3939 case Builtin::BI__builtin_stdc_has_single_bit: {
3940 Value *ArgValue = EmitScalarExpr(E->getArg(0));
3941 llvm::Type *ArgType = ArgValue->getType();
3942 Value *One = ConstantInt::get(ArgType, 1);
3943 Function *F = CGM.getIntrinsic(Intrinsic::ctpop, ArgType);
3944 Value *PopCnt = Builder.CreateCall(F, ArgValue);
3945 return RValue::get(Builder.CreateICmpEQ(PopCnt, One));
3946 }
3947 case Builtin::BIstdc_bit_width_uc:
3948 case Builtin::BIstdc_bit_width_us:
3949 case Builtin::BIstdc_bit_width_ui:
3950 case Builtin::BIstdc_bit_width_ul:
3951 case Builtin::BIstdc_bit_width_ull:
3952 case Builtin::BI__builtin_stdc_bit_width:
3953 return emitStdcBitWidthMinus(E, Intrinsic::ctlz, /*IsPop=*/false);
3954 case Builtin::BIstdc_bit_floor_uc:
3955 case Builtin::BIstdc_bit_floor_us:
3956 case Builtin::BIstdc_bit_floor_ui:
3957 case Builtin::BIstdc_bit_floor_ul:
3958 case Builtin::BIstdc_bit_floor_ull:
3959 case Builtin::BI__builtin_stdc_bit_floor: {
3960 Value *ArgValue = EmitScalarExpr(E->getArg(0));
3961 llvm::Type *ArgType = ArgValue->getType();
3962 unsigned BitWidth = ArgType->getIntegerBitWidth();
3963 Value *Zero = ConstantInt::get(ArgType, 0);
3964 Value *One = ConstantInt::get(ArgType, 1);
3965 Function *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
3966 Value *LZ = Builder.CreateCall(F, {ArgValue, Builder.getTrue()});
3967 Value *ShiftAmt =
3968 Builder.CreateSub(ConstantInt::get(ArgType, BitWidth - 1), LZ);
3969 Value *Shifted = Builder.CreateShl(One, ShiftAmt);
3970 Value *IsZero = Builder.CreateICmpEQ(ArgValue, Zero);
3971 Value *Result = Builder.CreateSelect(IsZero, Zero, Shifted);
3972 return RValue::get(Result);
3973 }
3974 case Builtin::BIstdc_bit_ceil_uc:
3975 case Builtin::BIstdc_bit_ceil_us:
3976 case Builtin::BIstdc_bit_ceil_ui:
3977 case Builtin::BIstdc_bit_ceil_ul:
3978 case Builtin::BIstdc_bit_ceil_ull:
3979 case Builtin::BI__builtin_stdc_bit_ceil: {
3980 Value *ArgValue = EmitScalarExpr(E->getArg(0));
3981 llvm::Type *ArgType = ArgValue->getType();
3982 Value *One = ConstantInt::get(ArgType, 1);
3983 Value *IsLEOne = Builder.CreateICmpULE(ArgValue, One, "isleone");
3984
3985 BasicBlock *EntryBB = Builder.GetInsertBlock();
3986 BasicBlock *CalcBB = createBasicBlock("bitceil.calc", CurFn);
3987 BasicBlock *MergeBB = createBasicBlock("bitceil.merge", CurFn);
3988
3989 Builder.CreateCondBr(IsLEOne, MergeBB, CalcBB);
3990
3991 Builder.SetInsertPoint(CalcBB);
3992 Function *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
3993 Value *ArgMinusOne = Builder.CreateSub(ArgValue, One);
3994 Value *LZ = Builder.CreateCall(F, {ArgMinusOne, Builder.getFalse()});
3995 // 2<<(BitWidth-1-LZ) to get the next power of two. The shift
3996 // amount is always in [0, BitWidth-1], so when LZ==0 (argument has its MSB
3997 // set), the result wraps to 0
3998 unsigned BitWidth = ArgType->getIntegerBitWidth();
3999 Value *ShiftAmt =
4000 Builder.CreateSub(ConstantInt::get(ArgType, BitWidth - 1), LZ);
4001 Value *Two = Builder.CreateShl(One, One);
4002 Value *Tmp = Builder.CreateShl(Two, ShiftAmt);
4003 Builder.CreateBr(MergeBB);
4004
4005 Builder.SetInsertPoint(MergeBB);
4006 PHINode *Phi = Builder.CreatePHI(ArgType, 2);
4007 Phi->addIncoming(One, EntryBB);
4008 Phi->addIncoming(Tmp, CalcBB);
4009 return RValue::get(Phi);
4010 }
4011
4012 // stdc_memreverse8u8 is a no-op (single byte, nothing to swap).
4013 case Builtin::BIstdc_memreverse8u8:
4014 return RValue::get(EmitScalarExpr(E->getArg(0)));
4015
4016 case Builtin::BIstdc_memreverse8u16:
4017 case Builtin::BIstdc_memreverse8u32:
4018 case Builtin::BIstdc_memreverse8u64:
4019 return RValue::get(
4020 emitBuiltinWithOneOverloadedType<1>(*this, E, Intrinsic::bswap));
4021
4022 case Builtin::BIstdc_memreverse8:
4023 case Builtin::BI__builtin_stdc_memreverse8: {
4025 if (E->getArg(0)->EvaluateAsInt(R, getContext())) {
4026 uint64_t Size = R.Val.getInt().getZExtValue();
4027 if (Size <= 1) {
4028 EmitIgnoredExpr(E->getArg(1));
4029 return RValue::get(nullptr);
4030 }
4031 if (Size == 2 || Size == 4 || Size == 8) {
4032 llvm::Type *IntTy = Builder.getIntNTy(Size * 8);
4033 Address PtrAddr = EmitPointerWithAlignment(E->getArg(1));
4034 Address Addr = PtrAddr.withElementType(IntTy);
4035 Value *Val = Builder.CreateLoad(Addr);
4036 Function *F = CGM.getIntrinsic(Intrinsic::bswap, IntTy);
4037 Value *Swapped = Builder.CreateCall(F, Val);
4038 Builder.CreateStore(Swapped, Addr);
4039 return RValue::get(nullptr);
4040 }
4041 }
4042
4043 // General case: fall back to the library function stdc_memreverse8.
4044 break;
4045 }
4046
4047 case Builtin::BI__builtin_constant_p: {
4048 llvm::Type *ResultType = ConvertType(E->getType());
4049
4050 const Expr *Arg = E->getArg(0);
4051 QualType ArgType = Arg->getType();
4052 // FIXME: The allowance for Obj-C pointers and block pointers is historical
4053 // and likely a mistake.
4054 if (!ArgType->isIntegralOrEnumerationType() && !ArgType->isFloatingType() &&
4055 !ArgType->isObjCObjectPointerType() && !ArgType->isBlockPointerType())
4056 // Per the GCC documentation, only numeric constants are recognized after
4057 // inlining.
4058 return RValue::get(ConstantInt::get(ResultType, 0));
4059
4060 if (Arg->HasSideEffects(getContext()))
4061 // The argument is unevaluated, so be conservative if it might have
4062 // side-effects.
4063 return RValue::get(ConstantInt::get(ResultType, 0));
4064
4065 Value *ArgValue = EmitScalarExpr(Arg);
4066 if (ArgType->isObjCObjectPointerType()) {
4067 // Convert Objective-C objects to id because we cannot distinguish between
4068 // LLVM types for Obj-C classes as they are opaque.
4069 ArgType = CGM.getContext().getObjCIdType();
4070 ArgValue = Builder.CreateBitCast(ArgValue, ConvertType(ArgType));
4071 }
4072 Function *F =
4073 CGM.getIntrinsic(Intrinsic::is_constant, ConvertType(ArgType));
4074 Value *Result = Builder.CreateCall(F, ArgValue);
4075 if (Result->getType() != ResultType)
4076 Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/false);
4077 return RValue::get(Result);
4078 }
4079 case Builtin::BI__builtin_dynamic_object_size:
4080 case Builtin::BI__builtin_object_size: {
4081 unsigned Type =
4082 E->getArg(1)->EvaluateKnownConstInt(getContext()).getZExtValue();
4083 auto *ResType = cast<llvm::IntegerType>(ConvertType(E->getType()));
4084
4085 // We pass this builtin onto the optimizer so that it can figure out the
4086 // object size in more complex cases.
4087 bool IsDynamic = BuiltinID == Builtin::BI__builtin_dynamic_object_size;
4088 return RValue::get(emitBuiltinObjectSize(E->getArg(0), Type, ResType,
4089 /*EmittedE=*/nullptr, IsDynamic));
4090 }
4091 case Builtin::BI__builtin_counted_by_ref: {
4092 // Default to returning '(void *) 0'.
4093 llvm::Value *Result = llvm::ConstantPointerNull::get(
4094 llvm::PointerType::getUnqual(getLLVMContext()));
4095
4096 const Expr *Arg = E->getArg(0)->IgnoreParenImpCasts();
4097
4098 if (auto *UO = dyn_cast<UnaryOperator>(Arg);
4099 UO && UO->getOpcode() == UO_AddrOf) {
4100 Arg = UO->getSubExpr()->IgnoreParenImpCasts();
4101
4102 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Arg))
4103 Arg = ASE->getBase()->IgnoreParenImpCasts();
4104 }
4105
4106 if (const MemberExpr *ME = dyn_cast_if_present<MemberExpr>(Arg)) {
4107 if (auto *CATy =
4109 CATy && CATy->getKind() == CountAttributedType::CountedBy) {
4110 const auto *MemberDecl = cast<FieldDecl>(ME->getMemberDecl());
4111 if (const FieldDecl *CountFD = MemberDecl->findCountedByField())
4112 Result = GetCountedByFieldExprGEP(Arg, MemberDecl, CountFD);
4113 else
4114 llvm::report_fatal_error("Cannot find the counted_by 'count' field");
4115 }
4116 }
4117
4118 return RValue::get(Result);
4119 }
4120 case Builtin::BI__builtin_prefetch: {
4121 Value *Locality, *RW, *Address = EmitScalarExpr(E->getArg(0));
4122 unsigned ICEArguments = (1 << 1) | (1 << 2);
4123 RW = (E->getNumArgs() > 1) ? EmitScalarOrConstFoldImmArg(ICEArguments, 1, E)
4124 : llvm::ConstantInt::get(Int32Ty, 0);
4125 RW = Builder.CreateZExtOrTrunc(RW, Int32Ty);
4126 Locality = (E->getNumArgs() > 2)
4127 ? EmitScalarOrConstFoldImmArg(ICEArguments, 2, E)
4128 : llvm::ConstantInt::get(Int32Ty, 3);
4129 Locality = Builder.CreateZExtOrTrunc(Locality, Int32Ty);
4130 Value *Data = llvm::ConstantInt::get(Int32Ty, 1);
4131 Function *F = CGM.getIntrinsic(Intrinsic::prefetch, Address->getType());
4132 Builder.CreateCall(F, {Address, RW, Locality, Data});
4133 return RValue::get(nullptr);
4134 }
4135 case Builtin::BI__builtin_readcyclecounter: {
4136 Function *F = CGM.getIntrinsic(Intrinsic::readcyclecounter);
4137 return RValue::get(Builder.CreateCall(F));
4138 }
4139 case Builtin::BI__builtin_readsteadycounter: {
4140 Function *F = CGM.getIntrinsic(Intrinsic::readsteadycounter);
4141 return RValue::get(Builder.CreateCall(F));
4142 }
4143 case Builtin::BI__builtin___clear_cache: {
4144 Value *Begin = EmitScalarExpr(E->getArg(0));
4145 Value *End = EmitScalarExpr(E->getArg(1));
4146 Function *F = CGM.getIntrinsic(Intrinsic::clear_cache, {CGM.DefaultPtrTy});
4147 return RValue::get(Builder.CreateCall(F, {Begin, End}));
4148 }
4149 case Builtin::BI__builtin_trap:
4150 EmitTrapCall(Intrinsic::trap);
4151 return RValue::get(nullptr);
4152 case Builtin::BI__builtin_verbose_trap: {
4153 llvm::DebugLoc CallLocation = Builder.getCurrentDebugLocation();
4154 llvm::DILocation *TrapLocation = CallLocation;
4155 if (getDebugInfo()) {
4156 TrapLocation = getDebugInfo()->CreateTrapFailureMessageFor(
4157 TrapLocation, *E->getArg(0)->tryEvaluateString(getContext()),
4159 // Keep the trap on the builtin's source line. A line-zero location would
4160 // leave the trap attributed to the preceding line in the line table.
4161 TrapLocation = llvm::DILocation::get(
4162 getLLVMContext(), CallLocation.getLine(), CallLocation.getCol(),
4163 TrapLocation->getScope(), TrapLocation->getInlinedAt());
4164 }
4165 ApplyDebugLocation ApplyTrapDI(*this, TrapLocation);
4166 // Currently no attempt is made to prevent traps from being merged.
4167 EmitTrapCall(Intrinsic::trap);
4168 return RValue::get(nullptr);
4169 }
4170 case Builtin::BI__debugbreak:
4171 EmitTrapCall(Intrinsic::debugtrap);
4172 return RValue::get(nullptr);
4173 case Builtin::BI__builtin_unreachable: {
4175
4176 // We do need to preserve an insertion point.
4177 EmitBlock(createBasicBlock("unreachable.cont"));
4178
4179 return RValue::get(nullptr);
4180 }
4181
4182 case Builtin::BI__builtin_powi:
4183 case Builtin::BI__builtin_powif:
4184 case Builtin::BI__builtin_powil: {
4185 llvm::Value *Src0 = EmitScalarExpr(E->getArg(0));
4186 llvm::Value *Src1 = EmitScalarExpr(E->getArg(1));
4187
4188 if (Builder.getIsFPConstrained()) {
4189 // FIXME: llvm.powi has 2 mangling types,
4190 // llvm.experimental.constrained.powi has one.
4191 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
4192 Function *F = CGM.getIntrinsic(Intrinsic::experimental_constrained_powi,
4193 Src0->getType());
4194 return RValue::get(Builder.CreateConstrainedFPCall(F, { Src0, Src1 }));
4195 }
4196
4197 Function *F = CGM.getIntrinsic(Intrinsic::powi,
4198 { Src0->getType(), Src1->getType() });
4199 return RValue::get(Builder.CreateCall(F, { Src0, Src1 }));
4200 }
4201 case Builtin::BI__builtin_frexpl: {
4202 // Linux PPC will not be adding additional PPCDoubleDouble support.
4203 // WIP to switch default to IEEE long double. Will emit libcall for
4204 // frexpl instead of legalizing this type in the BE.
4205 if (&getTarget().getLongDoubleFormat() == &llvm::APFloat::PPCDoubleDouble())
4206 break;
4207 [[fallthrough]];
4208 }
4209 case Builtin::BI__builtin_frexp:
4210 case Builtin::BI__builtin_frexpf:
4211 case Builtin::BI__builtin_frexpf128:
4212 case Builtin::BI__builtin_frexpf16:
4213 return RValue::get(emitFrexpBuiltin(*this, E, Intrinsic::frexp));
4214 case Builtin::BImodf:
4215 case Builtin::BImodff:
4216 case Builtin::BImodfl:
4217 case Builtin::BI__builtin_modf:
4218 case Builtin::BI__builtin_modff:
4219 case Builtin::BI__builtin_modfl:
4220 if (Builder.getIsFPConstrained())
4221 break; // TODO: Emit constrained modf intrinsic once one exists.
4222 return RValue::get(emitModfBuiltin(*this, E, Intrinsic::modf));
4223 case Builtin::BI__builtin_isgreater:
4224 case Builtin::BI__builtin_isgreaterequal:
4225 case Builtin::BI__builtin_isless:
4226 case Builtin::BI__builtin_islessequal:
4227 case Builtin::BI__builtin_islessgreater:
4228 case Builtin::BI__builtin_isunordered: {
4229 // Ordered comparisons: we know the arguments to these are matching scalar
4230 // floating point values.
4231 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
4232 Value *LHS = EmitScalarExpr(E->getArg(0));
4233 Value *RHS = EmitScalarExpr(E->getArg(1));
4234
4235 switch (BuiltinID) {
4236 default: llvm_unreachable("Unknown ordered comparison");
4237 case Builtin::BI__builtin_isgreater:
4238 LHS = Builder.CreateFCmpOGT(LHS, RHS, "cmp");
4239 break;
4240 case Builtin::BI__builtin_isgreaterequal:
4241 LHS = Builder.CreateFCmpOGE(LHS, RHS, "cmp");
4242 break;
4243 case Builtin::BI__builtin_isless:
4244 LHS = Builder.CreateFCmpOLT(LHS, RHS, "cmp");
4245 break;
4246 case Builtin::BI__builtin_islessequal:
4247 LHS = Builder.CreateFCmpOLE(LHS, RHS, "cmp");
4248 break;
4249 case Builtin::BI__builtin_islessgreater:
4250 LHS = Builder.CreateFCmpONE(LHS, RHS, "cmp");
4251 break;
4252 case Builtin::BI__builtin_isunordered:
4253 LHS = Builder.CreateFCmpUNO(LHS, RHS, "cmp");
4254 break;
4255 }
4256 // ZExt bool to int type.
4257 return RValue::get(Builder.CreateZExt(LHS, ConvertType(E->getType())));
4258 }
4259
4260 case Builtin::BI__builtin_isnan: {
4261 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
4262 Value *V = EmitScalarExpr(E->getArg(0));
4263 if (Value *Result = tryUseTestFPKind(*this, BuiltinID, V))
4264 return RValue::get(Result);
4265 return RValue::get(
4266 Builder.CreateZExt(Builder.createIsFPClass(V, FPClassTest::fcNan),
4267 ConvertType(E->getType())));
4268 }
4269
4270 case Builtin::BI__builtin_issignaling: {
4271 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
4272 Value *V = EmitScalarExpr(E->getArg(0));
4273 return RValue::get(
4274 Builder.CreateZExt(Builder.createIsFPClass(V, FPClassTest::fcSNan),
4275 ConvertType(E->getType())));
4276 }
4277
4278 case Builtin::BI__builtin_isinf: {
4279 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
4280 Value *V = EmitScalarExpr(E->getArg(0));
4281 if (Value *Result = tryUseTestFPKind(*this, BuiltinID, V))
4282 return RValue::get(Result);
4283 return RValue::get(
4284 Builder.CreateZExt(Builder.createIsFPClass(V, FPClassTest::fcInf),
4285 ConvertType(E->getType())));
4286 }
4287
4288 case Builtin::BIfinite:
4289 case Builtin::BI__finite:
4290 case Builtin::BIfinitef:
4291 case Builtin::BI__finitef:
4292 case Builtin::BIfinitel:
4293 case Builtin::BI__finitel:
4294 case Builtin::BI__builtin_isfinite: {
4295 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
4296 Value *V = EmitScalarExpr(E->getArg(0));
4297 if (Value *Result = tryUseTestFPKind(*this, BuiltinID, V))
4298 return RValue::get(Result);
4299 return RValue::get(
4300 Builder.CreateZExt(Builder.createIsFPClass(V, FPClassTest::fcFinite),
4301 ConvertType(E->getType())));
4302 }
4303
4304 case Builtin::BI__builtin_isnormal: {
4305 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
4306 Value *V = EmitScalarExpr(E->getArg(0));
4307 return RValue::get(
4308 Builder.CreateZExt(Builder.createIsFPClass(V, FPClassTest::fcNormal),
4309 ConvertType(E->getType())));
4310 }
4311
4312 case Builtin::BI__builtin_issubnormal: {
4313 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
4314 Value *V = EmitScalarExpr(E->getArg(0));
4315 return RValue::get(
4316 Builder.CreateZExt(Builder.createIsFPClass(V, FPClassTest::fcSubnormal),
4317 ConvertType(E->getType())));
4318 }
4319
4320 case Builtin::BI__builtin_iszero: {
4321 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
4322 Value *V = EmitScalarExpr(E->getArg(0));
4323 return RValue::get(
4324 Builder.CreateZExt(Builder.createIsFPClass(V, FPClassTest::fcZero),
4325 ConvertType(E->getType())));
4326 }
4327
4328 case Builtin::BI__builtin_isfpclass: {
4330 if (!E->getArg(1)->EvaluateAsInt(Result, CGM.getContext()))
4331 break;
4332 uint64_t Test = Result.Val.getInt().getLimitedValue();
4333 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
4334 Value *V = EmitScalarExpr(E->getArg(0));
4335 return RValue::get(Builder.CreateZExt(Builder.createIsFPClass(V, Test),
4336 ConvertType(E->getType())));
4337 }
4338
4339 case Builtin::BI__builtin_nondeterministic_value: {
4340 llvm::Type *Ty = ConvertType(E->getArg(0)->getType());
4341
4342 Value *Result = PoisonValue::get(Ty);
4343 Result = Builder.CreateFreeze(Result);
4344
4345 return RValue::get(Result);
4346 }
4347
4348 case Builtin::BI__builtin_elementwise_abs: {
4349 Value *Result;
4350 QualType QT = E->getArg(0)->getType();
4351
4352 if (auto *VecTy = QT->getAs<VectorType>())
4353 QT = VecTy->getElementType();
4354 else if (auto *MatTy = QT->getAs<ConstantMatrixType>())
4355 QT = MatTy->getElementType();
4356 if (QT->isIntegerType())
4357 Result = Builder.CreateBinaryIntrinsic(
4358 Intrinsic::abs, EmitScalarExpr(E->getArg(0)), Builder.getFalse(),
4359 nullptr, "elt.abs");
4360 else
4361 Result = emitBuiltinWithOneOverloadedType<1>(*this, E, Intrinsic::fabs,
4362 "elt.abs");
4363
4364 return RValue::get(Result);
4365 }
4366 case Builtin::BI__builtin_elementwise_bitreverse:
4368 *this, E, Intrinsic::bitreverse, "elt.bitreverse"));
4369 case Builtin::BI__builtin_elementwise_popcount:
4371 *this, E, Intrinsic::ctpop, "elt.ctpop"));
4372 case Builtin::BI__builtin_elementwise_canonicalize:
4374 *this, E, Intrinsic::canonicalize, "elt.canonicalize"));
4375 case Builtin::BI__builtin_elementwise_copysign:
4376 return RValue::get(
4377 emitBuiltinWithOneOverloadedType<2>(*this, E, Intrinsic::copysign));
4378 case Builtin::BI__builtin_elementwise_fshl:
4379 return RValue::get(
4380 emitBuiltinWithOneOverloadedType<3>(*this, E, Intrinsic::fshl));
4381 case Builtin::BI__builtin_elementwise_fshr:
4382 return RValue::get(
4383 emitBuiltinWithOneOverloadedType<3>(*this, E, Intrinsic::fshr));
4384 case Builtin::BI__builtin_elementwise_clmul:
4385 return RValue::get(
4386 emitBuiltinWithOneOverloadedType<2>(*this, E, Intrinsic::clmul));
4387 case Builtin::BI__builtin_elementwise_pext:
4388 return RValue::get(
4389 emitBuiltinWithOneOverloadedType<2>(*this, E, Intrinsic::pext));
4390 case Builtin::BI__builtin_elementwise_pdep:
4391 return RValue::get(
4392 emitBuiltinWithOneOverloadedType<2>(*this, E, Intrinsic::pdep));
4393
4394 case Builtin::BI__builtin_elementwise_add_sat:
4395 case Builtin::BI__builtin_elementwise_sub_sat: {
4396 Value *Op0 = EmitScalarExpr(E->getArg(0));
4397 Value *Op1 = EmitScalarExpr(E->getArg(1));
4398 Value *Result;
4399 assert(Op0->getType()->isIntOrIntVectorTy() && "integer type expected");
4400 QualType Ty = E->getArg(0)->getType();
4401 if (auto *VecTy = Ty->getAs<VectorType>())
4402 Ty = VecTy->getElementType();
4403 bool IsSigned = Ty->isSignedIntegerType();
4404 unsigned Opc;
4405 if (BuiltinIDIfNoAsmLabel == Builtin::BI__builtin_elementwise_add_sat)
4406 Opc = IsSigned ? Intrinsic::sadd_sat : Intrinsic::uadd_sat;
4407 else
4408 Opc = IsSigned ? Intrinsic::ssub_sat : Intrinsic::usub_sat;
4409 Result = Builder.CreateBinaryIntrinsic(Opc, Op0, Op1, nullptr, "elt.sat");
4410 return RValue::get(Result);
4411 }
4412
4413 case Builtin::BI__builtin_elementwise_max: {
4414 Value *Op0 = EmitScalarExpr(E->getArg(0));
4415 Value *Op1 = EmitScalarExpr(E->getArg(1));
4416 Value *Result;
4417 if (Op0->getType()->isIntOrIntVectorTy()) {
4418 QualType Ty = E->getArg(0)->getType();
4419 Result = Builder.CreateBinaryIntrinsic(
4420 Ty->hasSignedIntegerRepresentation() ? Intrinsic::smax
4421 : Intrinsic::umax,
4422 Op0, Op1, nullptr, "elt.max");
4423 } else
4424 Result = Builder.CreateMaxNum(Op0, Op1, /*FMFSource=*/nullptr, "elt.max");
4425 return RValue::get(Result);
4426 }
4427 case Builtin::BI__builtin_elementwise_min: {
4428 Value *Op0 = EmitScalarExpr(E->getArg(0));
4429 Value *Op1 = EmitScalarExpr(E->getArg(1));
4430 Value *Result;
4431 if (Op0->getType()->isIntOrIntVectorTy()) {
4432 QualType Ty = E->getArg(0)->getType();
4433 Result = Builder.CreateBinaryIntrinsic(
4434 Ty->hasSignedIntegerRepresentation() ? Intrinsic::smin
4435 : Intrinsic::umin,
4436 Op0, Op1, nullptr, "elt.min");
4437 } else
4438 Result = Builder.CreateMinNum(Op0, Op1, /*FMFSource=*/nullptr, "elt.min");
4439 return RValue::get(Result);
4440 }
4441
4442 case Builtin::BI__builtin_elementwise_maxnum: {
4443 Value *Op0 = EmitScalarExpr(E->getArg(0));
4444 Value *Op1 = EmitScalarExpr(E->getArg(1));
4445 Value *Result = Builder.CreateBinaryIntrinsic(llvm::Intrinsic::maxnum, Op0,
4446 Op1, nullptr, "elt.maxnum");
4447 return RValue::get(Result);
4448 }
4449
4450 case Builtin::BI__builtin_elementwise_minnum: {
4451 Value *Op0 = EmitScalarExpr(E->getArg(0));
4452 Value *Op1 = EmitScalarExpr(E->getArg(1));
4453 Value *Result = Builder.CreateBinaryIntrinsic(llvm::Intrinsic::minnum, Op0,
4454 Op1, nullptr, "elt.minnum");
4455 return RValue::get(Result);
4456 }
4457
4458 case Builtin::BI__builtin_elementwise_maximum: {
4459 Value *Op0 = EmitScalarExpr(E->getArg(0));
4460 Value *Op1 = EmitScalarExpr(E->getArg(1));
4461 Value *Result = Builder.CreateBinaryIntrinsic(Intrinsic::maximum, Op0, Op1,
4462 nullptr, "elt.maximum");
4463 return RValue::get(Result);
4464 }
4465
4466 case Builtin::BI__builtin_elementwise_minimum: {
4467 Value *Op0 = EmitScalarExpr(E->getArg(0));
4468 Value *Op1 = EmitScalarExpr(E->getArg(1));
4469 Value *Result = Builder.CreateBinaryIntrinsic(Intrinsic::minimum, Op0, Op1,
4470 nullptr, "elt.minimum");
4471 return RValue::get(Result);
4472 }
4473
4474 case Builtin::BI__builtin_elementwise_maximumnum: {
4475 Value *Op0 = EmitScalarExpr(E->getArg(0));
4476 Value *Op1 = EmitScalarExpr(E->getArg(1));
4477 Value *Result = Builder.CreateBinaryIntrinsic(
4478 Intrinsic::maximumnum, Op0, Op1, nullptr, "elt.maximumnum");
4479 return RValue::get(Result);
4480 }
4481
4482 case Builtin::BI__builtin_elementwise_minimumnum: {
4483 Value *Op0 = EmitScalarExpr(E->getArg(0));
4484 Value *Op1 = EmitScalarExpr(E->getArg(1));
4485 Value *Result = Builder.CreateBinaryIntrinsic(
4486 Intrinsic::minimumnum, Op0, Op1, nullptr, "elt.minimumnum");
4487 return RValue::get(Result);
4488 }
4489
4490 case Builtin::BI__builtin_reduce_max: {
4491 auto GetIntrinsicID = [this](QualType QT) {
4492 if (auto *VecTy = QT->getAs<VectorType>())
4493 QT = VecTy->getElementType();
4494 else if (QT->isSizelessVectorType())
4495 QT = QT->getSizelessVectorEltType(CGM.getContext());
4496
4497 if (QT->isSignedIntegerType())
4498 return Intrinsic::vector_reduce_smax;
4499 if (QT->isUnsignedIntegerType())
4500 return Intrinsic::vector_reduce_umax;
4501 assert(QT->isFloatingType() && "must have a float here");
4502 return Intrinsic::vector_reduce_fmax;
4503 };
4505 *this, E, GetIntrinsicID(E->getArg(0)->getType()), "rdx.min"));
4506 }
4507
4508 case Builtin::BI__builtin_reduce_min: {
4509 auto GetIntrinsicID = [this](QualType QT) {
4510 if (auto *VecTy = QT->getAs<VectorType>())
4511 QT = VecTy->getElementType();
4512 else if (QT->isSizelessVectorType())
4513 QT = QT->getSizelessVectorEltType(CGM.getContext());
4514
4515 if (QT->isSignedIntegerType())
4516 return Intrinsic::vector_reduce_smin;
4517 if (QT->isUnsignedIntegerType())
4518 return Intrinsic::vector_reduce_umin;
4519 assert(QT->isFloatingType() && "must have a float here");
4520 return Intrinsic::vector_reduce_fmin;
4521 };
4522
4524 *this, E, GetIntrinsicID(E->getArg(0)->getType()), "rdx.min"));
4525 }
4526
4527 case Builtin::BI__builtin_reduce_add:
4529 *this, E, Intrinsic::vector_reduce_add, "rdx.add"));
4530 case Builtin::BI__builtin_reduce_mul:
4532 *this, E, Intrinsic::vector_reduce_mul, "rdx.mul"));
4533 case Builtin::BI__builtin_reduce_xor:
4535 *this, E, Intrinsic::vector_reduce_xor, "rdx.xor"));
4536 case Builtin::BI__builtin_reduce_or:
4538 *this, E, Intrinsic::vector_reduce_or, "rdx.or"));
4539 case Builtin::BI__builtin_reduce_and:
4541 *this, E, Intrinsic::vector_reduce_and, "rdx.and"));
4542 case Builtin::BI__builtin_reduce_maximum:
4544 *this, E, Intrinsic::vector_reduce_fmaximum, "rdx.maximum"));
4545 case Builtin::BI__builtin_reduce_minimum:
4547 *this, E, Intrinsic::vector_reduce_fminimum, "rdx.minimum"));
4548 case Builtin::BI__builtin_reduce_assoc_fadd:
4549 case Builtin::BI__builtin_reduce_in_order_fadd: {
4550 llvm::Value *Vector = EmitScalarExpr(E->getArg(0));
4551 llvm::Type *ScalarTy = Vector->getType()->getScalarType();
4552 llvm::Value *StartValue = nullptr;
4553 if (E->getNumArgs() == 2)
4554 StartValue = Builder.CreateFPCast(EmitScalarExpr(E->getArg(1)), ScalarTy);
4555 llvm::Value *Args[] = {/*start_value=*/StartValue
4556 ? StartValue
4557 : llvm::ConstantFP::get(ScalarTy, -0.0F),
4558 /*vector=*/Vector};
4559 llvm::Function *F =
4560 CGM.getIntrinsic(Intrinsic::vector_reduce_fadd, Vector->getType());
4561 llvm::CallBase *Reduce = Builder.CreateCall(F, Args, "rdx.addf");
4562 if (BuiltinIDIfNoAsmLabel == Builtin::BI__builtin_reduce_assoc_fadd) {
4563 // `__builtin_reduce_assoc_fadd` is an associative reduction which
4564 // requires the reassoc FMF flag.
4565 llvm::FastMathFlags FMF;
4566 FMF.setAllowReassoc();
4567 cast<llvm::CallBase>(Reduce)->setFastMathFlags(FMF);
4568 }
4569 return RValue::get(Reduce);
4570 }
4571
4572 case Builtin::BI__builtin_matrix_transpose: {
4573 auto *MatrixTy = E->getArg(0)->getType()->castAs<ConstantMatrixType>();
4574 Value *MatValue = EmitScalarExpr(E->getArg(0));
4575 MatrixBuilder MB(Builder);
4576 Value *Result = MB.CreateMatrixTranspose(MatValue, MatrixTy->getNumRows(),
4577 MatrixTy->getNumColumns());
4578 return RValue::get(Result);
4579 }
4580
4581 case Builtin::BI__builtin_matrix_column_major_load: {
4582 MatrixBuilder MB(Builder);
4583 // Emit everything that isn't dependent on the first parameter type
4584 Value *Stride = EmitScalarExpr(E->getArg(3));
4585 const auto *ResultTy = E->getType()->getAs<ConstantMatrixType>();
4586 auto *PtrTy = E->getArg(0)->getType()->getAs<PointerType>();
4587 assert(PtrTy && "arg0 must be of pointer type");
4588 bool IsVolatile = PtrTy->getPointeeType().isVolatileQualified();
4589
4592 E->getArg(0)->getType(), E->getArg(0)->getExprLoc(), FD,
4593 0);
4594 Value *Result = MB.CreateColumnMajorLoad(
4595 Src.getElementType(), Src.emitRawPointer(*this),
4596 Align(Src.getAlignment().getQuantity()), Stride, IsVolatile,
4597 ResultTy->getNumRows(), ResultTy->getNumColumns(), "matrix");
4598 return RValue::get(Result);
4599 }
4600
4601 case Builtin::BI__builtin_matrix_column_major_store: {
4602 MatrixBuilder MB(Builder);
4603 Value *Matrix = EmitScalarExpr(E->getArg(0));
4605 Value *Stride = EmitScalarExpr(E->getArg(2));
4606
4607 const auto *MatrixTy = E->getArg(0)->getType()->getAs<ConstantMatrixType>();
4608 auto *PtrTy = E->getArg(1)->getType()->getAs<PointerType>();
4609 assert(PtrTy && "arg1 must be of pointer type");
4610 bool IsVolatile = PtrTy->getPointeeType().isVolatileQualified();
4611
4613 E->getArg(1)->getType(), E->getArg(1)->getExprLoc(), FD,
4614 0);
4615 Value *Result = MB.CreateColumnMajorStore(
4616 Matrix, Dst.emitRawPointer(*this),
4617 Align(Dst.getAlignment().getQuantity()), Stride, IsVolatile,
4618 MatrixTy->getNumRows(), MatrixTy->getNumColumns());
4620 return RValue::get(Result);
4621 }
4622
4623 case Builtin::BI__builtin_masked_load:
4624 case Builtin::BI__builtin_masked_expand_load: {
4625 llvm::Value *Mask = EmitScalarExpr(E->getArg(0));
4626 llvm::Value *Ptr = EmitScalarExpr(E->getArg(1));
4627
4628 llvm::Type *RetTy = CGM.getTypes().ConvertType(E->getType());
4629 llvm::Value *PassThru = llvm::PoisonValue::get(RetTy);
4630 if (E->getNumArgs() > 2)
4631 PassThru = EmitScalarExpr(E->getArg(2));
4632
4633 CharUnits Align = CGM.getNaturalTypeAlignment(
4634 E->getType()->getAs<VectorType>()->getElementType(), nullptr);
4635
4636 llvm::Value *Result;
4637 if (BuiltinID == Builtin::BI__builtin_masked_load)
4638 Result = Builder.CreateMaskedLoad(RetTy, Ptr, Align.getAsAlign(), Mask,
4639 PassThru, "masked_load");
4640 else
4641 Result = Builder.CreateMaskedExpandLoad(RetTy, Ptr, MaybeAlign(), Mask,
4642 PassThru, "masked_expand_load");
4643
4644 return RValue::get(Result);
4645 };
4646 case Builtin::BI__builtin_masked_gather: {
4647 llvm::Value *Mask = EmitScalarExpr(E->getArg(0));
4648 llvm::Value *Idx = EmitScalarExpr(E->getArg(1));
4649 llvm::Value *Ptr = EmitScalarExpr(E->getArg(2));
4650
4651 llvm::Type *RetTy = CGM.getTypes().ConvertType(E->getType());
4652 CharUnits Align = CGM.getNaturalTypeAlignment(
4653 E->getType()->getAs<VectorType>()->getElementType(), nullptr);
4654
4655 llvm::Value *PassThru = llvm::PoisonValue::get(RetTy);
4656 if (E->getNumArgs() > 3)
4657 PassThru = EmitScalarExpr(E->getArg(3));
4658
4659 llvm::Type *ElemTy = CGM.getTypes().ConvertType(
4661 llvm::Value *PtrVec = Builder.CreateGEP(ElemTy, Ptr, Idx);
4662
4663 llvm::Value *Result = Builder.CreateMaskedGather(
4664 RetTy, PtrVec, Align.getAsAlign(), Mask, PassThru, "masked_gather");
4665 return RValue::get(Result);
4666 }
4667 case Builtin::BI__builtin_masked_store:
4668 case Builtin::BI__builtin_masked_compress_store: {
4669 llvm::Value *Mask = EmitScalarExpr(E->getArg(0));
4670 llvm::Value *Val = EmitScalarExpr(E->getArg(1));
4671 llvm::Value *Ptr = EmitScalarExpr(E->getArg(2));
4672
4673 CharUnits Align = CGM.getNaturalTypeAlignment(
4675 nullptr);
4676
4677 if (BuiltinID == Builtin::BI__builtin_masked_store)
4678 Builder.CreateMaskedStore(Val, Ptr, Align.getAsAlign(), Mask);
4679 else
4680 Builder.CreateMaskedCompressStore(Val, Ptr, MaybeAlign(), Mask);
4681
4682 return RValue::get(nullptr);
4683 }
4684 case Builtin::BI__builtin_masked_scatter: {
4685 llvm::Value *Mask = EmitScalarExpr(E->getArg(0));
4686 llvm::Value *Idx = EmitScalarExpr(E->getArg(1));
4687 llvm::Value *Val = EmitScalarExpr(E->getArg(2));
4688 llvm::Value *Ptr = EmitScalarExpr(E->getArg(3));
4689
4690 CharUnits Align = CGM.getNaturalTypeAlignment(
4692 nullptr);
4693
4694 llvm::Type *ElemTy = CGM.getTypes().ConvertType(
4695 E->getArg(1)->getType()->getAs<VectorType>()->getElementType());
4696 llvm::Value *PtrVec = Builder.CreateGEP(ElemTy, Ptr, Idx);
4697
4698 Builder.CreateMaskedScatter(Val, PtrVec, Align.getAsAlign(), Mask);
4699 return RValue();
4700 }
4701 case Builtin::BI__builtin_isinf_sign: {
4702 // isinf_sign(x) -> fabs(x) == infinity ? (signbit(x) ? -1 : 1) : 0
4703 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
4704 // FIXME: for strictfp/IEEE-754 we need to not trap on SNaN here.
4705 Value *Arg = EmitScalarExpr(E->getArg(0));
4706 Value *AbsArg = EmitFAbs(*this, Arg);
4707 Value *IsInf = Builder.CreateFCmpOEQ(
4708 AbsArg, ConstantFP::getInfinity(Arg->getType()), "isinf");
4709 Value *IsNeg = EmitSignBit(*this, Arg);
4710
4711 llvm::Type *IntTy = ConvertType(E->getType());
4712 Value *Zero = Constant::getNullValue(IntTy);
4713 Value *One = ConstantInt::get(IntTy, 1);
4714 Value *NegativeOne = ConstantInt::getAllOnesValue(IntTy);
4715 Value *SignResult = Builder.CreateSelect(IsNeg, NegativeOne, One);
4716 Value *Result = Builder.CreateSelect(IsInf, SignResult, Zero);
4717 return RValue::get(Result);
4718 }
4719
4720 case Builtin::BI__builtin_flt_rounds: {
4721 Function *F = CGM.getIntrinsic(Intrinsic::get_rounding);
4722
4723 llvm::Type *ResultType = ConvertType(E->getType());
4724 Value *Result = Builder.CreateCall(F);
4725 if (Result->getType() != ResultType)
4726 Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
4727 "cast");
4728 return RValue::get(Result);
4729 }
4730
4731 case Builtin::BI__builtin_set_flt_rounds: {
4732 Function *F = CGM.getIntrinsic(Intrinsic::set_rounding);
4733
4734 Value *V = EmitScalarExpr(E->getArg(0));
4735 Builder.CreateCall(F, V);
4736 return RValue::get(nullptr);
4737 }
4738
4739 case Builtin::BI__builtin_fpclassify: {
4740 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
4741 // FIXME: for strictfp/IEEE-754 we need to not trap on SNaN here.
4742 Value *V = EmitScalarExpr(E->getArg(5));
4743 llvm::Type *Ty = ConvertType(E->getArg(5)->getType());
4744
4745 // Create Result
4746 BasicBlock *Begin = Builder.GetInsertBlock();
4747 BasicBlock *End = createBasicBlock("fpclassify_end", this->CurFn);
4748 Builder.SetInsertPoint(End);
4749 PHINode *Result =
4750 Builder.CreatePHI(ConvertType(E->getArg(0)->getType()), 4,
4751 "fpclassify_result");
4752
4753 // if (V==0) return FP_ZERO
4754 Builder.SetInsertPoint(Begin);
4755 Value *IsZero = Builder.CreateFCmpOEQ(V, Constant::getNullValue(Ty),
4756 "iszero");
4757 Value *ZeroLiteral = EmitScalarExpr(E->getArg(4));
4758 BasicBlock *NotZero = createBasicBlock("fpclassify_not_zero", this->CurFn);
4759 Builder.CreateCondBr(IsZero, End, NotZero);
4760 Result->addIncoming(ZeroLiteral, Begin);
4761
4762 // if (V != V) return FP_NAN
4763 Builder.SetInsertPoint(NotZero);
4764 Value *IsNan = Builder.CreateFCmpUNO(V, V, "cmp");
4765 Value *NanLiteral = EmitScalarExpr(E->getArg(0));
4766 BasicBlock *NotNan = createBasicBlock("fpclassify_not_nan", this->CurFn);
4767 Builder.CreateCondBr(IsNan, End, NotNan);
4768 Result->addIncoming(NanLiteral, NotZero);
4769
4770 // if (fabs(V) == infinity) return FP_INFINITY
4771 Builder.SetInsertPoint(NotNan);
4772 Value *VAbs = EmitFAbs(*this, V);
4773 Value *IsInf =
4774 Builder.CreateFCmpOEQ(VAbs, ConstantFP::getInfinity(V->getType()),
4775 "isinf");
4776 Value *InfLiteral = EmitScalarExpr(E->getArg(1));
4777 BasicBlock *NotInf = createBasicBlock("fpclassify_not_inf", this->CurFn);
4778 Builder.CreateCondBr(IsInf, End, NotInf);
4779 Result->addIncoming(InfLiteral, NotNan);
4780
4781 // if (fabs(V) >= MIN_NORMAL) return FP_NORMAL else FP_SUBNORMAL
4782 Builder.SetInsertPoint(NotInf);
4783 APFloat Smallest = APFloat::getSmallestNormalized(
4784 getContext().getFloatTypeSemantics(E->getArg(5)->getType()));
4785 Value *IsNormal =
4786 Builder.CreateFCmpUGE(VAbs, ConstantFP::get(V->getContext(), Smallest),
4787 "isnormal");
4788 Value *NormalResult =
4789 Builder.CreateSelect(IsNormal, EmitScalarExpr(E->getArg(2)),
4790 EmitScalarExpr(E->getArg(3)));
4791 Builder.CreateBr(End);
4792 Result->addIncoming(NormalResult, NotInf);
4793
4794 // return Result
4795 Builder.SetInsertPoint(End);
4796 return RValue::get(Result);
4797 }
4798
4799 // An alloca will always return a pointer to the alloca (stack) address
4800 // space. This address space need not be the same as the AST / Language
4801 // default (e.g. in C / C++ auto vars are in the generic address space). At
4802 // the AST level this is handled within CreateTempAlloca et al., but for the
4803 // builtin / dynamic alloca we have to handle it here. We use an explicit cast
4804 // instead of passing an AS to CreateAlloca so as to not inhibit optimisation.
4805 case Builtin::BIalloca:
4806 case Builtin::BI_alloca:
4807 case Builtin::BI__builtin_alloca_uninitialized:
4808 case Builtin::BI__builtin_alloca: {
4809 Value *Size = EmitScalarExpr(E->getArg(0));
4810 const TargetInfo &TI = getContext().getTargetInfo();
4811 // The alignment of the alloca should correspond to __BIGGEST_ALIGNMENT__.
4812 const Align SuitableAlignmentInBytes =
4813 CGM.getContext()
4814 .toCharUnitsFromBits(TI.getSuitableAlign())
4815 .getAsAlign();
4816 AllocaInst *AI = Builder.CreateAlloca(Builder.getInt8Ty(), Size);
4817 AI->setAlignment(SuitableAlignmentInBytes);
4818 if (BuiltinID != Builtin::BI__builtin_alloca_uninitialized)
4819 initializeAlloca(*this, AI, Size, SuitableAlignmentInBytes);
4820 if (AI->getAddressSpace() !=
4821 CGM.getContext().getTargetAddressSpace(
4823 llvm::Type *Ty = CGM.getTypes().ConvertType(E->getType());
4824 return RValue::get(performAddrSpaceCast(AI, Ty));
4825 }
4826 return RValue::get(AI);
4827 }
4828
4829 case Builtin::BI__builtin_alloca_with_align_uninitialized:
4830 case Builtin::BI__builtin_alloca_with_align: {
4831 Value *Size = EmitScalarExpr(E->getArg(0));
4832 Value *AlignmentInBitsValue = EmitScalarExpr(E->getArg(1));
4833 auto *AlignmentInBitsCI = cast<ConstantInt>(AlignmentInBitsValue);
4834 unsigned AlignmentInBits = AlignmentInBitsCI->getZExtValue();
4835 const Align AlignmentInBytes =
4836 CGM.getContext().toCharUnitsFromBits(AlignmentInBits).getAsAlign();
4837 AllocaInst *AI = Builder.CreateAlloca(Builder.getInt8Ty(), Size);
4838 AI->setAlignment(AlignmentInBytes);
4839 if (BuiltinID != Builtin::BI__builtin_alloca_with_align_uninitialized)
4840 initializeAlloca(*this, AI, Size, AlignmentInBytes);
4841 if (AI->getAddressSpace() !=
4842 CGM.getContext().getTargetAddressSpace(
4844 llvm::Type *Ty = CGM.getTypes().ConvertType(E->getType());
4845 return RValue::get(performAddrSpaceCast(AI, Ty));
4846 }
4847 return RValue::get(AI);
4848 }
4849
4850 case Builtin::BI__builtin_infer_alloc_token: {
4851 llvm::MDNode *MDN = buildAllocToken(E);
4852 llvm::Value *MDV = MetadataAsValue::get(getLLVMContext(), MDN);
4853 llvm::Function *F =
4854 CGM.getIntrinsic(llvm::Intrinsic::alloc_token_id, {IntPtrTy});
4855 llvm::CallBase *TokenID = Builder.CreateCall(F, MDV);
4856 return RValue::get(TokenID);
4857 }
4858
4859 case Builtin::BIbzero:
4860 case Builtin::BI__builtin_bzero: {
4862 Value *SizeVal = EmitScalarExpr(E->getArg(1));
4863 EmitNonNullArgCheck(Dest, E->getArg(0)->getType(),
4864 E->getArg(0)->getExprLoc(), FD, 0);
4865 auto *I = Builder.CreateMemSet(Dest, Builder.getInt8(0), SizeVal, false);
4866 addInstToNewSourceAtom(I, nullptr);
4867 return RValue::get(nullptr);
4868 }
4869
4870 case Builtin::BIbcopy:
4871 case Builtin::BI__builtin_bcopy: {
4874 Value *SizeVal = EmitScalarExpr(E->getArg(2));
4876 E->getArg(0)->getType(), E->getArg(0)->getExprLoc(), FD,
4877 0);
4879 E->getArg(1)->getType(), E->getArg(1)->getExprLoc(), FD,
4880 0);
4881 auto *I = Builder.CreateMemMove(Dest, Src, SizeVal, false);
4882 addInstToNewSourceAtom(I, nullptr);
4883 return RValue::get(nullptr);
4884 }
4885
4886 case Builtin::BImemcpy:
4887 case Builtin::BI__builtin_memcpy:
4888 case Builtin::BImempcpy:
4889 case Builtin::BI__builtin_mempcpy: {
4892 Value *SizeVal = EmitScalarExpr(E->getArg(2));
4893 EmitArgCheck(TCK_Store, Dest, E->getArg(0), 0);
4894 EmitArgCheck(TCK_Load, Src, E->getArg(1), 1);
4895 auto *I = Builder.CreateMemCpy(Dest, Src, SizeVal, false);
4896 addInstToNewSourceAtom(I, nullptr);
4897 if (BuiltinID == Builtin::BImempcpy ||
4898 BuiltinID == Builtin::BI__builtin_mempcpy)
4899 return RValue::get(Builder.CreateInBoundsGEP(
4900 Dest.getElementType(), Dest.emitRawPointer(*this), SizeVal));
4901 else
4902 return RValue::get(Dest, *this);
4903 }
4904
4905 case Builtin::BI__builtin_memcpy_inline: {
4908 uint64_t Size =
4909 E->getArg(2)->EvaluateKnownConstInt(getContext()).getZExtValue();
4910 EmitArgCheck(TCK_Store, Dest, E->getArg(0), 0);
4911 EmitArgCheck(TCK_Load, Src, E->getArg(1), 1);
4912 auto *I = Builder.CreateMemCpyInline(Dest, Src, Size);
4913 addInstToNewSourceAtom(I, nullptr);
4914 return RValue::get(nullptr);
4915 }
4916
4917 case Builtin::BI__builtin_char_memchr:
4918 BuiltinID = Builtin::BI__builtin_memchr;
4919 break;
4920
4921 case Builtin::BI__builtin___memcpy_chk: {
4922 // fold __builtin_memcpy_chk(x, y, cst1, cst2) to memcpy iff cst1<=cst2.
4923 Expr::EvalResult SizeResult, DstSizeResult;
4924 if (!E->getArg(2)->EvaluateAsInt(SizeResult, CGM.getContext()) ||
4925 !E->getArg(3)->EvaluateAsInt(DstSizeResult, CGM.getContext()))
4926 break;
4927 llvm::APSInt Size = SizeResult.Val.getInt();
4928 llvm::APSInt DstSize = DstSizeResult.Val.getInt();
4929 if (Size.ugt(DstSize))
4930 break;
4933 Value *SizeVal = llvm::ConstantInt::get(Builder.getContext(), Size);
4934 auto *I = Builder.CreateMemCpy(Dest, Src, SizeVal, false);
4935 addInstToNewSourceAtom(I, nullptr);
4936 return RValue::get(Dest, *this);
4937 }
4938
4939 case Builtin::BI__builtin_objc_memmove_collectable: {
4940 Address DestAddr = EmitPointerWithAlignment(E->getArg(0));
4941 Address SrcAddr = EmitPointerWithAlignment(E->getArg(1));
4942 Value *SizeVal = EmitScalarExpr(E->getArg(2));
4943 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this,
4944 DestAddr, SrcAddr, SizeVal);
4945 return RValue::get(DestAddr, *this);
4946 }
4947
4948 case Builtin::BI__builtin___memmove_chk: {
4949 // fold __builtin_memmove_chk(x, y, cst1, cst2) to memmove iff cst1<=cst2.
4950 Expr::EvalResult SizeResult, DstSizeResult;
4951 if (!E->getArg(2)->EvaluateAsInt(SizeResult, CGM.getContext()) ||
4952 !E->getArg(3)->EvaluateAsInt(DstSizeResult, CGM.getContext()))
4953 break;
4954 llvm::APSInt Size = SizeResult.Val.getInt();
4955 llvm::APSInt DstSize = DstSizeResult.Val.getInt();
4956 if (Size.ugt(DstSize))
4957 break;
4960 Value *SizeVal = llvm::ConstantInt::get(Builder.getContext(), Size);
4961 auto *I = Builder.CreateMemMove(Dest, Src, SizeVal, false);
4962 addInstToNewSourceAtom(I, nullptr);
4963 return RValue::get(Dest, *this);
4964 }
4965
4966 case Builtin::BI__builtin_trivially_relocate:
4967 case Builtin::BImemmove:
4968 case Builtin::BI__builtin_memmove: {
4971 Value *SizeVal = EmitScalarExpr(E->getArg(2));
4972 if (BuiltinIDIfNoAsmLabel == Builtin::BI__builtin_trivially_relocate)
4973 SizeVal = Builder.CreateMul(
4974 SizeVal,
4975 ConstantInt::get(
4976 SizeVal->getType(),
4977 getContext()
4978 .getTypeSizeInChars(E->getArg(0)->getType()->getPointeeType())
4979 .getQuantity()));
4980 EmitArgCheck(TCK_Store, Dest, E->getArg(0), 0);
4981 EmitArgCheck(TCK_Load, Src, E->getArg(1), 1);
4982 auto *I = Builder.CreateMemMove(Dest, Src, SizeVal, false);
4983 addInstToNewSourceAtom(I, nullptr);
4984 return RValue::get(Dest, *this);
4985 }
4986 case Builtin::BImemset:
4987 case Builtin::BI__builtin_memset: {
4989 Value *ByteVal = Builder.CreateTrunc(EmitScalarExpr(E->getArg(1)),
4990 Builder.getInt8Ty());
4991 Value *SizeVal = EmitScalarExpr(E->getArg(2));
4992 EmitNonNullArgCheck(Dest, E->getArg(0)->getType(),
4993 E->getArg(0)->getExprLoc(), FD, 0);
4994 auto *I = Builder.CreateMemSet(Dest, ByteVal, SizeVal, false);
4995 addInstToNewSourceAtom(I, ByteVal);
4996 return RValue::get(Dest, *this);
4997 }
4998 case Builtin::BI__builtin_memset_inline: {
5000 Value *ByteVal =
5001 Builder.CreateTrunc(EmitScalarExpr(E->getArg(1)), Builder.getInt8Ty());
5002 uint64_t Size =
5003 E->getArg(2)->EvaluateKnownConstInt(getContext()).getZExtValue();
5005 E->getArg(0)->getType(), E->getArg(0)->getExprLoc(), FD,
5006 0);
5007 auto *I = Builder.CreateMemSetInline(Dest, ByteVal, Size);
5008 addInstToNewSourceAtom(I, nullptr);
5009 return RValue::get(nullptr);
5010 }
5011 case Builtin::BI__builtin___memset_chk: {
5012 // fold __builtin_memset_chk(x, y, cst1, cst2) to memset iff cst1<=cst2.
5013 Expr::EvalResult SizeResult, DstSizeResult;
5014 if (!E->getArg(2)->EvaluateAsInt(SizeResult, CGM.getContext()) ||
5015 !E->getArg(3)->EvaluateAsInt(DstSizeResult, CGM.getContext()))
5016 break;
5017 llvm::APSInt Size = SizeResult.Val.getInt();
5018 llvm::APSInt DstSize = DstSizeResult.Val.getInt();
5019 if (Size.ugt(DstSize))
5020 break;
5022 Value *ByteVal = Builder.CreateTrunc(EmitScalarExpr(E->getArg(1)),
5023 Builder.getInt8Ty());
5024 Value *SizeVal = llvm::ConstantInt::get(Builder.getContext(), Size);
5025 auto *I = Builder.CreateMemSet(Dest, ByteVal, SizeVal, false);
5026 addInstToNewSourceAtom(I, nullptr);
5027 return RValue::get(Dest, *this);
5028 }
5029 case Builtin::BI__builtin_wmemchr: {
5030 // The MSVC runtime library does not provide a definition of wmemchr, so we
5031 // need an inline implementation.
5032 if (!getTarget().getTriple().isOSMSVCRT())
5033 break;
5034
5035 llvm::Type *WCharTy = ConvertType(getContext().WCharTy);
5036 Value *Str = EmitScalarExpr(E->getArg(0));
5037 Value *Chr = EmitScalarExpr(E->getArg(1));
5038 Value *Size = EmitScalarExpr(E->getArg(2));
5039
5040 BasicBlock *Entry = Builder.GetInsertBlock();
5041 BasicBlock *CmpEq = createBasicBlock("wmemchr.eq");
5042 BasicBlock *Next = createBasicBlock("wmemchr.next");
5043 BasicBlock *Exit = createBasicBlock("wmemchr.exit");
5044 Value *SizeEq0 = Builder.CreateICmpEQ(Size, ConstantInt::get(SizeTy, 0));
5045 Builder.CreateCondBr(SizeEq0, Exit, CmpEq);
5046
5047 EmitBlock(CmpEq);
5048 PHINode *StrPhi = Builder.CreatePHI(Str->getType(), 2);
5049 StrPhi->addIncoming(Str, Entry);
5050 PHINode *SizePhi = Builder.CreatePHI(SizeTy, 2);
5051 SizePhi->addIncoming(Size, Entry);
5052 CharUnits WCharAlign =
5054 Value *StrCh = Builder.CreateAlignedLoad(WCharTy, StrPhi, WCharAlign);
5055 Value *FoundChr = Builder.CreateConstInBoundsGEP1_32(WCharTy, StrPhi, 0);
5056 Value *StrEqChr = Builder.CreateICmpEQ(StrCh, Chr);
5057 Builder.CreateCondBr(StrEqChr, Exit, Next);
5058
5059 EmitBlock(Next);
5060 Value *NextStr = Builder.CreateConstInBoundsGEP1_32(WCharTy, StrPhi, 1);
5061 Value *NextSize = Builder.CreateSub(SizePhi, ConstantInt::get(SizeTy, 1));
5062 Value *NextSizeEq0 =
5063 Builder.CreateICmpEQ(NextSize, ConstantInt::get(SizeTy, 0));
5064 Builder.CreateCondBr(NextSizeEq0, Exit, CmpEq);
5065 StrPhi->addIncoming(NextStr, Next);
5066 SizePhi->addIncoming(NextSize, Next);
5067
5068 EmitBlock(Exit);
5069 PHINode *Ret = Builder.CreatePHI(Str->getType(), 3);
5070 Ret->addIncoming(llvm::Constant::getNullValue(Str->getType()), Entry);
5071 Ret->addIncoming(llvm::Constant::getNullValue(Str->getType()), Next);
5072 Ret->addIncoming(FoundChr, CmpEq);
5073 return RValue::get(Ret);
5074 }
5075 case Builtin::BI__builtin_wmemcmp: {
5076 // The MSVC runtime library does not provide a definition of wmemcmp, so we
5077 // need an inline implementation.
5078 if (!getTarget().getTriple().isOSMSVCRT())
5079 break;
5080
5081 llvm::Type *WCharTy = ConvertType(getContext().WCharTy);
5082
5083 Value *Dst = EmitScalarExpr(E->getArg(0));
5084 Value *Src = EmitScalarExpr(E->getArg(1));
5085 Value *Size = EmitScalarExpr(E->getArg(2));
5086
5087 BasicBlock *Entry = Builder.GetInsertBlock();
5088 BasicBlock *CmpGT = createBasicBlock("wmemcmp.gt");
5089 BasicBlock *CmpLT = createBasicBlock("wmemcmp.lt");
5090 BasicBlock *Next = createBasicBlock("wmemcmp.next");
5091 BasicBlock *Exit = createBasicBlock("wmemcmp.exit");
5092 Value *SizeEq0 = Builder.CreateICmpEQ(Size, ConstantInt::get(SizeTy, 0));
5093 Builder.CreateCondBr(SizeEq0, Exit, CmpGT);
5094
5095 EmitBlock(CmpGT);
5096 PHINode *DstPhi = Builder.CreatePHI(Dst->getType(), 2);
5097 DstPhi->addIncoming(Dst, Entry);
5098 PHINode *SrcPhi = Builder.CreatePHI(Src->getType(), 2);
5099 SrcPhi->addIncoming(Src, Entry);
5100 PHINode *SizePhi = Builder.CreatePHI(SizeTy, 2);
5101 SizePhi->addIncoming(Size, Entry);
5102 CharUnits WCharAlign =
5104 Value *DstCh = Builder.CreateAlignedLoad(WCharTy, DstPhi, WCharAlign);
5105 Value *SrcCh = Builder.CreateAlignedLoad(WCharTy, SrcPhi, WCharAlign);
5106 Value *DstGtSrc = Builder.CreateICmpUGT(DstCh, SrcCh);
5107 Builder.CreateCondBr(DstGtSrc, Exit, CmpLT);
5108
5109 EmitBlock(CmpLT);
5110 Value *DstLtSrc = Builder.CreateICmpULT(DstCh, SrcCh);
5111 Builder.CreateCondBr(DstLtSrc, Exit, Next);
5112
5113 EmitBlock(Next);
5114 Value *NextDst = Builder.CreateConstInBoundsGEP1_32(WCharTy, DstPhi, 1);
5115 Value *NextSrc = Builder.CreateConstInBoundsGEP1_32(WCharTy, SrcPhi, 1);
5116 Value *NextSize = Builder.CreateSub(SizePhi, ConstantInt::get(SizeTy, 1));
5117 Value *NextSizeEq0 =
5118 Builder.CreateICmpEQ(NextSize, ConstantInt::get(SizeTy, 0));
5119 Builder.CreateCondBr(NextSizeEq0, Exit, CmpGT);
5120 DstPhi->addIncoming(NextDst, Next);
5121 SrcPhi->addIncoming(NextSrc, Next);
5122 SizePhi->addIncoming(NextSize, Next);
5123
5124 EmitBlock(Exit);
5125 PHINode *Ret = Builder.CreatePHI(IntTy, 4);
5126 Ret->addIncoming(ConstantInt::get(IntTy, 0), Entry);
5127 Ret->addIncoming(ConstantInt::get(IntTy, 1), CmpGT);
5128 Ret->addIncoming(ConstantInt::getAllOnesValue(IntTy), CmpLT);
5129 Ret->addIncoming(ConstantInt::get(IntTy, 0), Next);
5130 return RValue::get(Ret);
5131 }
5132 case Builtin::BI__builtin_dwarf_cfa: {
5133 // The offset in bytes from the first argument to the CFA.
5134 //
5135 // Why on earth is this in the frontend? Is there any reason at
5136 // all that the backend can't reasonably determine this while
5137 // lowering llvm.eh.dwarf.cfa()?
5138 //
5139 // TODO: If there's a satisfactory reason, add a target hook for
5140 // this instead of hard-coding 0, which is correct for most targets.
5141 int32_t Offset = 0;
5142
5143 Function *F = CGM.getIntrinsic(Intrinsic::eh_dwarf_cfa);
5144 return RValue::get(Builder.CreateCall(F,
5145 llvm::ConstantInt::get(Int32Ty, Offset)));
5146 }
5147 case Builtin::BI__builtin_return_address: {
5148 Value *Depth = ConstantEmitter(*this).emitAbstract(E->getArg(0),
5149 getContext().UnsignedIntTy);
5150 Depth = Builder.CreateZExtOrTrunc(Depth, Int32Ty);
5151 Function *F =
5152 CGM.getIntrinsic(Intrinsic::returnaddress, {CGM.ProgramPtrTy});
5153 return RValue::get(Builder.CreateCall(F, Depth));
5154 }
5155 case Builtin::BI_ReturnAddress: {
5156 Function *F =
5157 CGM.getIntrinsic(Intrinsic::returnaddress, {CGM.ProgramPtrTy});
5158 return RValue::get(Builder.CreateCall(F, Builder.getInt32(0)));
5159 }
5160 case Builtin::BI__builtin_frame_address: {
5161 Value *Depth = ConstantEmitter(*this).emitAbstract(E->getArg(0),
5162 getContext().UnsignedIntTy);
5163 Depth = Builder.CreateZExtOrTrunc(Depth, Int32Ty);
5164 Function *F = CGM.getIntrinsic(Intrinsic::frameaddress, AllocaInt8PtrTy);
5165 return RValue::get(Builder.CreateCall(F, Depth));
5166 }
5167 case Builtin::BI__builtin_stack_address: {
5168 return RValue::get(Builder.CreateCall(
5169 CGM.getIntrinsic(Intrinsic::stackaddress, AllocaInt8PtrTy)));
5170 }
5171 case Builtin::BI__builtin_extract_return_addr: {
5174 return RValue::get(Result);
5175 }
5176 case Builtin::BI__builtin_frob_return_addr: {
5179 return RValue::get(Result);
5180 }
5181 case Builtin::BI__builtin_dwarf_sp_column: {
5182 llvm::IntegerType *Ty
5185 if (Column == -1) {
5186 CGM.ErrorUnsupported(E, "__builtin_dwarf_sp_column");
5187 return RValue::get(llvm::UndefValue::get(Ty));
5188 }
5189 return RValue::get(llvm::ConstantInt::get(Ty, Column, true));
5190 }
5191 case Builtin::BI__builtin_init_dwarf_reg_size_table: {
5193 if (getTargetHooks().initDwarfEHRegSizeTable(*this, Address))
5194 CGM.ErrorUnsupported(E, "__builtin_init_dwarf_reg_size_table");
5195 return RValue::get(llvm::UndefValue::get(ConvertType(E->getType())));
5196 }
5197 case Builtin::BI__builtin_eh_return: {
5198 Value *Int = EmitScalarExpr(E->getArg(0));
5199 Value *Ptr = EmitScalarExpr(E->getArg(1));
5200
5201 llvm::IntegerType *IntTy = cast<llvm::IntegerType>(Int->getType());
5202 assert((IntTy->getBitWidth() == 32 || IntTy->getBitWidth() == 64) &&
5203 "LLVM's __builtin_eh_return only supports 32- and 64-bit variants");
5204 Function *F =
5205 CGM.getIntrinsic(IntTy->getBitWidth() == 32 ? Intrinsic::eh_return_i32
5206 : Intrinsic::eh_return_i64);
5207 Builder.CreateCall(F, {Int, Ptr});
5208 Builder.CreateUnreachable();
5209
5210 // We do need to preserve an insertion point.
5211 EmitBlock(createBasicBlock("builtin_eh_return.cont"));
5212
5213 return RValue::get(nullptr);
5214 }
5215 case Builtin::BI__builtin_unwind_init: {
5216 Function *F = CGM.getIntrinsic(Intrinsic::eh_unwind_init);
5217 Builder.CreateCall(F);
5218 return RValue::get(nullptr);
5219 }
5220 case Builtin::BI__builtin_extend_pointer: {
5221 // Extends a pointer to the size of an _Unwind_Word, which is
5222 // uint64_t on all platforms. Generally this gets poked into a
5223 // register and eventually used as an address, so if the
5224 // addressing registers are wider than pointers and the platform
5225 // doesn't implicitly ignore high-order bits when doing
5226 // addressing, we need to make sure we zext / sext based on
5227 // the platform's expectations.
5228 //
5229 // See: http://gcc.gnu.org/ml/gcc-bugs/2002-02/msg00237.html
5230
5231 // Cast the pointer to intptr_t.
5232 Value *Ptr = EmitScalarExpr(E->getArg(0));
5233 Value *Result = Builder.CreatePtrToInt(Ptr, IntPtrTy, "extend.cast");
5234
5235 // If that's 64 bits, we're done.
5236 if (IntPtrTy->getBitWidth() == 64)
5237 return RValue::get(Result);
5238
5239 // Otherwise, ask the codegen data what to do.
5240 if (getTargetHooks().extendPointerWithSExt())
5241 return RValue::get(Builder.CreateSExt(Result, Int64Ty, "extend.sext"));
5242 else
5243 return RValue::get(Builder.CreateZExt(Result, Int64Ty, "extend.zext"));
5244 }
5245 case Builtin::BI__builtin_setjmp: {
5246 // Buffer is a void**.
5248
5249 if (getTarget().getTriple().getArch() == llvm::Triple::systemz) {
5250 // On this target, the back end fills in the context buffer completely.
5251 // It doesn't really matter if the frontend stores to the buffer before
5252 // calling setjmp, the back-end is going to overwrite them anyway.
5253 Function *F = CGM.getIntrinsic(Intrinsic::eh_sjlj_setjmp);
5254 return RValue::get(Builder.CreateCall(F, Buf.emitRawPointer(*this)));
5255 }
5256
5257 // Store the frame pointer to the setjmp buffer.
5258 Value *FrameAddr = Builder.CreateCall(
5259 CGM.getIntrinsic(Intrinsic::frameaddress, AllocaInt8PtrTy),
5260 ConstantInt::get(Int32Ty, 0));
5261 Builder.CreateStore(FrameAddr, Buf);
5262
5263 // Store the stack pointer to the setjmp buffer.
5264 Value *StackAddr = Builder.CreateStackSave();
5265 assert(Buf.emitRawPointer(*this)->getType() == StackAddr->getType());
5266
5267 Address StackSaveSlot = Builder.CreateConstInBoundsGEP(Buf, 2);
5268 Builder.CreateStore(StackAddr, StackSaveSlot);
5269
5270 // Call LLVM's EH setjmp, which is lightweight.
5271 Function *F = CGM.getIntrinsic(Intrinsic::eh_sjlj_setjmp);
5272 return RValue::get(Builder.CreateCall(F, Buf.emitRawPointer(*this)));
5273 }
5274 case Builtin::BI__builtin_longjmp: {
5275 Value *Buf = EmitScalarExpr(E->getArg(0));
5276
5277 // Call LLVM's EH longjmp, which is lightweight.
5278 Builder.CreateCall(CGM.getIntrinsic(Intrinsic::eh_sjlj_longjmp), Buf);
5279
5280 // longjmp doesn't return; mark this as unreachable.
5281 Builder.CreateUnreachable();
5282
5283 // We do need to preserve an insertion point.
5284 EmitBlock(createBasicBlock("longjmp.cont"));
5285
5286 return RValue::get(nullptr);
5287 }
5288 case Builtin::BI__builtin_launder: {
5289 const Expr *Arg = E->getArg(0);
5290 QualType ArgTy = Arg->getType()->getPointeeType();
5291 Value *Ptr = EmitScalarExpr(Arg);
5292 if (TypeRequiresBuiltinLaunder(CGM, ArgTy))
5293 Ptr = Builder.CreateLaunderInvariantGroup(Ptr);
5294
5295 return RValue::get(Ptr);
5296 }
5297 case Builtin::BI__builtin_clear_padding: {
5299 auto PointeeTy = E->getArg(0)->getType()->getPointeeType();
5300
5302 getContext().getPaddingIntervals(PointeeTy);
5303 for (const auto &Interval : Padding)
5304 ClearPadding(*this, Src, Interval);
5305
5306 return RValue::get(nullptr);
5307 }
5308 case Builtin::BI__sync_fetch_and_add:
5309 case Builtin::BI__sync_fetch_and_sub:
5310 case Builtin::BI__sync_fetch_and_or:
5311 case Builtin::BI__sync_fetch_and_and:
5312 case Builtin::BI__sync_fetch_and_xor:
5313 case Builtin::BI__sync_fetch_and_nand:
5314 case Builtin::BI__sync_add_and_fetch:
5315 case Builtin::BI__sync_sub_and_fetch:
5316 case Builtin::BI__sync_and_and_fetch:
5317 case Builtin::BI__sync_or_and_fetch:
5318 case Builtin::BI__sync_xor_and_fetch:
5319 case Builtin::BI__sync_nand_and_fetch:
5320 case Builtin::BI__sync_val_compare_and_swap:
5321 case Builtin::BI__sync_bool_compare_and_swap:
5322 case Builtin::BI__sync_lock_test_and_set:
5323 case Builtin::BI__sync_lock_release:
5324 case Builtin::BI__sync_swap:
5325 llvm_unreachable("Shouldn't make it through sema");
5326 case Builtin::BI__sync_fetch_and_add_1:
5327 case Builtin::BI__sync_fetch_and_add_2:
5328 case Builtin::BI__sync_fetch_and_add_4:
5329 case Builtin::BI__sync_fetch_and_add_8:
5330 case Builtin::BI__sync_fetch_and_add_16:
5331 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Add, E);
5332 case Builtin::BI__sync_fetch_and_sub_1:
5333 case Builtin::BI__sync_fetch_and_sub_2:
5334 case Builtin::BI__sync_fetch_and_sub_4:
5335 case Builtin::BI__sync_fetch_and_sub_8:
5336 case Builtin::BI__sync_fetch_and_sub_16:
5337 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Sub, E);
5338 case Builtin::BI__sync_fetch_and_or_1:
5339 case Builtin::BI__sync_fetch_and_or_2:
5340 case Builtin::BI__sync_fetch_and_or_4:
5341 case Builtin::BI__sync_fetch_and_or_8:
5342 case Builtin::BI__sync_fetch_and_or_16:
5343 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Or, E);
5344 case Builtin::BI__sync_fetch_and_and_1:
5345 case Builtin::BI__sync_fetch_and_and_2:
5346 case Builtin::BI__sync_fetch_and_and_4:
5347 case Builtin::BI__sync_fetch_and_and_8:
5348 case Builtin::BI__sync_fetch_and_and_16:
5349 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::And, E);
5350 case Builtin::BI__sync_fetch_and_xor_1:
5351 case Builtin::BI__sync_fetch_and_xor_2:
5352 case Builtin::BI__sync_fetch_and_xor_4:
5353 case Builtin::BI__sync_fetch_and_xor_8:
5354 case Builtin::BI__sync_fetch_and_xor_16:
5355 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Xor, E);
5356 case Builtin::BI__sync_fetch_and_nand_1:
5357 case Builtin::BI__sync_fetch_and_nand_2:
5358 case Builtin::BI__sync_fetch_and_nand_4:
5359 case Builtin::BI__sync_fetch_and_nand_8:
5360 case Builtin::BI__sync_fetch_and_nand_16:
5361 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Nand, E);
5362
5363 // Clang extensions: not overloaded yet.
5364 case Builtin::BI__sync_fetch_and_min:
5365 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Min, E);
5366 case Builtin::BI__sync_fetch_and_max:
5367 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Max, E);
5368 case Builtin::BI__sync_fetch_and_umin:
5369 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::UMin, E);
5370 case Builtin::BI__sync_fetch_and_umax:
5371 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::UMax, E);
5372
5373 case Builtin::BI__sync_add_and_fetch_1:
5374 case Builtin::BI__sync_add_and_fetch_2:
5375 case Builtin::BI__sync_add_and_fetch_4:
5376 case Builtin::BI__sync_add_and_fetch_8:
5377 case Builtin::BI__sync_add_and_fetch_16:
5378 return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Add, E,
5379 llvm::Instruction::Add);
5380 case Builtin::BI__sync_sub_and_fetch_1:
5381 case Builtin::BI__sync_sub_and_fetch_2:
5382 case Builtin::BI__sync_sub_and_fetch_4:
5383 case Builtin::BI__sync_sub_and_fetch_8:
5384 case Builtin::BI__sync_sub_and_fetch_16:
5385 return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Sub, E,
5386 llvm::Instruction::Sub);
5387 case Builtin::BI__sync_and_and_fetch_1:
5388 case Builtin::BI__sync_and_and_fetch_2:
5389 case Builtin::BI__sync_and_and_fetch_4:
5390 case Builtin::BI__sync_and_and_fetch_8:
5391 case Builtin::BI__sync_and_and_fetch_16:
5392 return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::And, E,
5393 llvm::Instruction::And);
5394 case Builtin::BI__sync_or_and_fetch_1:
5395 case Builtin::BI__sync_or_and_fetch_2:
5396 case Builtin::BI__sync_or_and_fetch_4:
5397 case Builtin::BI__sync_or_and_fetch_8:
5398 case Builtin::BI__sync_or_and_fetch_16:
5399 return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Or, E,
5400 llvm::Instruction::Or);
5401 case Builtin::BI__sync_xor_and_fetch_1:
5402 case Builtin::BI__sync_xor_and_fetch_2:
5403 case Builtin::BI__sync_xor_and_fetch_4:
5404 case Builtin::BI__sync_xor_and_fetch_8:
5405 case Builtin::BI__sync_xor_and_fetch_16:
5406 return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Xor, E,
5407 llvm::Instruction::Xor);
5408 case Builtin::BI__sync_nand_and_fetch_1:
5409 case Builtin::BI__sync_nand_and_fetch_2:
5410 case Builtin::BI__sync_nand_and_fetch_4:
5411 case Builtin::BI__sync_nand_and_fetch_8:
5412 case Builtin::BI__sync_nand_and_fetch_16:
5413 return EmitBinaryAtomicPost(*this, llvm::AtomicRMWInst::Nand, E,
5414 llvm::Instruction::And, true);
5415
5416 case Builtin::BI__sync_val_compare_and_swap_1:
5417 case Builtin::BI__sync_val_compare_and_swap_2:
5418 case Builtin::BI__sync_val_compare_and_swap_4:
5419 case Builtin::BI__sync_val_compare_and_swap_8:
5420 case Builtin::BI__sync_val_compare_and_swap_16:
5422 *this, E, false, AtomicOrdering::SequentiallyConsistent,
5423 AtomicOrdering::SequentiallyConsistent));
5424
5425 case Builtin::BI__sync_bool_compare_and_swap_1:
5426 case Builtin::BI__sync_bool_compare_and_swap_2:
5427 case Builtin::BI__sync_bool_compare_and_swap_4:
5428 case Builtin::BI__sync_bool_compare_and_swap_8:
5429 case Builtin::BI__sync_bool_compare_and_swap_16:
5431 *this, E, true, AtomicOrdering::SequentiallyConsistent,
5432 AtomicOrdering::SequentiallyConsistent));
5433
5434 case Builtin::BI__sync_swap_1:
5435 case Builtin::BI__sync_swap_2:
5436 case Builtin::BI__sync_swap_4:
5437 case Builtin::BI__sync_swap_8:
5438 case Builtin::BI__sync_swap_16:
5439 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Xchg, E);
5440
5441 case Builtin::BI__sync_lock_test_and_set_1:
5442 case Builtin::BI__sync_lock_test_and_set_2:
5443 case Builtin::BI__sync_lock_test_and_set_4:
5444 case Builtin::BI__sync_lock_test_and_set_8:
5445 case Builtin::BI__sync_lock_test_and_set_16:
5446 return EmitBinaryAtomic(*this, llvm::AtomicRMWInst::Xchg, E);
5447
5448 case Builtin::BI__sync_lock_release_1:
5449 case Builtin::BI__sync_lock_release_2:
5450 case Builtin::BI__sync_lock_release_4:
5451 case Builtin::BI__sync_lock_release_8:
5452 case Builtin::BI__sync_lock_release_16: {
5453 Address Ptr = CheckAtomicAlignment(*this, E);
5454 QualType ElTy = E->getArg(0)->getType()->getPointeeType();
5455
5456 llvm::Type *ITy = llvm::IntegerType::get(getLLVMContext(),
5457 getContext().getTypeSize(ElTy));
5458 llvm::StoreInst *Store =
5459 Builder.CreateStore(llvm::Constant::getNullValue(ITy), Ptr);
5460 Store->setAtomic(llvm::AtomicOrdering::Release);
5461 return RValue::get(nullptr);
5462 }
5463
5464 case Builtin::BI__sync_synchronize: {
5465 // We assume this is supposed to correspond to a C++0x-style
5466 // sequentially-consistent fence (i.e. this is only usable for
5467 // synchronization, not device I/O or anything like that). This intrinsic
5468 // is really badly designed in the sense that in theory, there isn't
5469 // any way to safely use it... but in practice, it mostly works
5470 // to use it with non-atomic loads and stores to get acquire/release
5471 // semantics.
5472 Builder.CreateFence(llvm::AtomicOrdering::SequentiallyConsistent);
5473 return RValue::get(nullptr);
5474 }
5475
5476 case Builtin::BI__builtin_nontemporal_load:
5477 return RValue::get(EmitNontemporalLoad(*this, E));
5478 case Builtin::BI__builtin_nontemporal_store:
5479 return RValue::get(EmitNontemporalStore(*this, E));
5480 case Builtin::BI__c11_atomic_is_lock_free:
5481 case Builtin::BI__atomic_is_lock_free: {
5482 // Call "bool __atomic_is_lock_free(size_t size, void *ptr)". For the
5483 // __c11 builtin, ptr is 0 (indicating a properly-aligned object), since
5484 // _Atomic(T) is always properly-aligned.
5485 const char *LibCallName = "__atomic_is_lock_free";
5486 CallArgList Args;
5487 Args.add(RValue::get(EmitScalarExpr(E->getArg(0))),
5488 getContext().getSizeType());
5489 if (BuiltinID == Builtin::BI__atomic_is_lock_free)
5490 Args.add(RValue::get(EmitScalarExpr(E->getArg(1))),
5492 else
5493 Args.add(RValue::get(llvm::Constant::getNullValue(VoidPtrTy)),
5495 const CGFunctionInfo &FuncInfo =
5496 CGM.getTypes().arrangeBuiltinFunctionCall(E->getType(), Args);
5497 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FuncInfo);
5498 llvm::FunctionCallee Func = CGM.CreateRuntimeFunction(FTy, LibCallName);
5499 return EmitCall(FuncInfo, CGCallee::forDirect(Func),
5500 ReturnValueSlot(), Args);
5501 }
5502
5503 case Builtin::BI__atomic_thread_fence:
5504 case Builtin::BI__atomic_signal_fence:
5505 case Builtin::BI__c11_atomic_thread_fence:
5506 case Builtin::BI__c11_atomic_signal_fence: {
5507 llvm::SyncScope::ID SSID;
5508 if (BuiltinID == Builtin::BI__atomic_signal_fence ||
5509 BuiltinID == Builtin::BI__c11_atomic_signal_fence)
5510 SSID = llvm::SyncScope::SingleThread;
5511 else
5512 SSID = llvm::SyncScope::System;
5513 Value *Order = EmitScalarExpr(E->getArg(0));
5514 if (isa<llvm::ConstantInt>(Order)) {
5515 int ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
5516 switch (ord) {
5517 case 0: // memory_order_relaxed
5518 default: // invalid order
5519 break;
5520 case 1: // memory_order_consume
5521 case 2: // memory_order_acquire
5522 emitAtomicFence(llvm::AtomicOrdering::Acquire, SSID);
5523 break;
5524 case 3: // memory_order_release
5525 emitAtomicFence(llvm::AtomicOrdering::Release, SSID);
5526 break;
5527 case 4: // memory_order_acq_rel
5528 emitAtomicFence(llvm::AtomicOrdering::AcquireRelease, SSID);
5529 break;
5530 case 5: // memory_order_seq_cst
5531 emitAtomicFence(llvm::AtomicOrdering::SequentiallyConsistent, SSID);
5532 break;
5533 }
5534 return RValue::get(nullptr);
5535 }
5536
5537 llvm::BasicBlock *AcquireBB, *ReleaseBB, *AcqRelBB, *SeqCstBB;
5538 AcquireBB = createBasicBlock("acquire", CurFn);
5539 ReleaseBB = createBasicBlock("release", CurFn);
5540 AcqRelBB = createBasicBlock("acqrel", CurFn);
5541 SeqCstBB = createBasicBlock("seqcst", CurFn);
5542 llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
5543
5544 Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
5545 llvm::SwitchInst *SI = Builder.CreateSwitch(Order, ContBB);
5546
5547 Builder.SetInsertPoint(AcquireBB);
5548 emitAtomicFence(llvm::AtomicOrdering::Acquire, SSID);
5549 Builder.CreateBr(ContBB);
5550 SI->addCase(Builder.getInt32(1), AcquireBB);
5551 SI->addCase(Builder.getInt32(2), AcquireBB);
5552
5553 Builder.SetInsertPoint(ReleaseBB);
5554 emitAtomicFence(llvm::AtomicOrdering::Release, SSID);
5555 Builder.CreateBr(ContBB);
5556 SI->addCase(Builder.getInt32(3), ReleaseBB);
5557
5558 Builder.SetInsertPoint(AcqRelBB);
5559 emitAtomicFence(llvm::AtomicOrdering::AcquireRelease, SSID);
5560 Builder.CreateBr(ContBB);
5561 SI->addCase(Builder.getInt32(4), AcqRelBB);
5562
5563 Builder.SetInsertPoint(SeqCstBB);
5564 emitAtomicFence(llvm::AtomicOrdering::SequentiallyConsistent, SSID);
5565 Builder.CreateBr(ContBB);
5566 SI->addCase(Builder.getInt32(5), SeqCstBB);
5567
5568 Builder.SetInsertPoint(ContBB);
5569 return RValue::get(nullptr);
5570 }
5571 case Builtin::BI__scoped_atomic_thread_fence: {
5573
5574 Value *Order = EmitScalarExpr(E->getArg(0));
5575 Value *Scope = EmitScalarExpr(E->getArg(1));
5576 auto Ord = dyn_cast<llvm::ConstantInt>(Order);
5577 auto Scp = dyn_cast<llvm::ConstantInt>(Scope);
5578 if (Ord && Scp) {
5579 SyncScope SS = ScopeModel->isValid(Scp->getZExtValue())
5580 ? ScopeModel->map(Scp->getZExtValue())
5581 : ScopeModel->map(ScopeModel->getFallBackValue());
5582 switch (Ord->getZExtValue()) {
5583 case 0: // memory_order_relaxed
5584 default: // invalid order
5585 break;
5586 case 1: // memory_order_consume
5587 case 2: // memory_order_acquire
5588 emitAtomicFence(llvm::AtomicOrdering::Acquire,
5589 getTargetHooks().getLLVMSyncScopeID(
5590 getLangOpts(), SS, llvm::AtomicOrdering::Acquire,
5591 getLLVMContext()));
5592 break;
5593 case 3: // memory_order_release
5594 emitAtomicFence(llvm::AtomicOrdering::Release,
5595 getTargetHooks().getLLVMSyncScopeID(
5596 getLangOpts(), SS, llvm::AtomicOrdering::Release,
5597 getLLVMContext()));
5598 break;
5599 case 4: // memory_order_acq_rel
5600 emitAtomicFence(llvm::AtomicOrdering::AcquireRelease,
5601 getTargetHooks().getLLVMSyncScopeID(
5602 getLangOpts(), SS,
5603 llvm::AtomicOrdering::AcquireRelease,
5604 getLLVMContext()));
5605 break;
5606 case 5: // memory_order_seq_cst
5607 emitAtomicFence(llvm::AtomicOrdering::SequentiallyConsistent,
5608 getTargetHooks().getLLVMSyncScopeID(
5609 getLangOpts(), SS,
5610 llvm::AtomicOrdering::SequentiallyConsistent,
5611 getLLVMContext()));
5612 break;
5613 }
5614 return RValue::get(nullptr);
5615 }
5616
5617 llvm::BasicBlock *ContBB = createBasicBlock("atomic.scope.continue", CurFn);
5618
5620 OrderBBs;
5621 if (Ord) {
5622 switch (Ord->getZExtValue()) {
5623 case 0: // memory_order_relaxed
5624 default: // invalid order
5625 ContBB->eraseFromParent();
5626 return RValue::get(nullptr);
5627 case 1: // memory_order_consume
5628 case 2: // memory_order_acquire
5629 OrderBBs.emplace_back(Builder.GetInsertBlock(),
5630 llvm::AtomicOrdering::Acquire);
5631 break;
5632 case 3: // memory_order_release
5633 OrderBBs.emplace_back(Builder.GetInsertBlock(),
5634 llvm::AtomicOrdering::Release);
5635 break;
5636 case 4: // memory_order_acq_rel
5637 OrderBBs.emplace_back(Builder.GetInsertBlock(),
5638 llvm::AtomicOrdering::AcquireRelease);
5639 break;
5640 case 5: // memory_order_seq_cst
5641 OrderBBs.emplace_back(Builder.GetInsertBlock(),
5642 llvm::AtomicOrdering::SequentiallyConsistent);
5643 break;
5644 }
5645 } else {
5646 llvm::BasicBlock *AcquireBB = createBasicBlock("acquire", CurFn);
5647 llvm::BasicBlock *ReleaseBB = createBasicBlock("release", CurFn);
5648 llvm::BasicBlock *AcqRelBB = createBasicBlock("acqrel", CurFn);
5649 llvm::BasicBlock *SeqCstBB = createBasicBlock("seqcst", CurFn);
5650
5651 Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
5652 llvm::SwitchInst *SI = Builder.CreateSwitch(Order, ContBB);
5653 SI->addCase(Builder.getInt32(1), AcquireBB);
5654 SI->addCase(Builder.getInt32(2), AcquireBB);
5655 SI->addCase(Builder.getInt32(3), ReleaseBB);
5656 SI->addCase(Builder.getInt32(4), AcqRelBB);
5657 SI->addCase(Builder.getInt32(5), SeqCstBB);
5658
5659 OrderBBs.emplace_back(AcquireBB, llvm::AtomicOrdering::Acquire);
5660 OrderBBs.emplace_back(ReleaseBB, llvm::AtomicOrdering::Release);
5661 OrderBBs.emplace_back(AcqRelBB, llvm::AtomicOrdering::AcquireRelease);
5662 OrderBBs.emplace_back(SeqCstBB,
5663 llvm::AtomicOrdering::SequentiallyConsistent);
5664 }
5665
5666 for (auto &[OrderBB, Ordering] : OrderBBs) {
5667 Builder.SetInsertPoint(OrderBB);
5668 if (Scp) {
5669 SyncScope SS = ScopeModel->isValid(Scp->getZExtValue())
5670 ? ScopeModel->map(Scp->getZExtValue())
5671 : ScopeModel->map(ScopeModel->getFallBackValue());
5672 emitAtomicFence(Ordering,
5673 getTargetHooks().getLLVMSyncScopeID(
5674 getLangOpts(), SS, Ordering, getLLVMContext()));
5675 Builder.CreateBr(ContBB);
5676 } else {
5677 llvm::DenseMap<unsigned, llvm::BasicBlock *> BBs;
5678 for (unsigned Scp : ScopeModel->getRuntimeValues())
5679 BBs[Scp] = createBasicBlock(getAsString(ScopeModel->map(Scp)), CurFn);
5680
5681 auto *SC = Builder.CreateIntCast(Scope, Builder.getInt32Ty(), false);
5682 llvm::SwitchInst *SI = Builder.CreateSwitch(SC, ContBB);
5683 for (unsigned Scp : ScopeModel->getRuntimeValues()) {
5684 auto *B = BBs[Scp];
5685 SI->addCase(Builder.getInt32(Scp), B);
5686
5687 Builder.SetInsertPoint(B);
5688 emitAtomicFence(Ordering, getTargetHooks().getLLVMSyncScopeID(
5689 getLangOpts(), ScopeModel->map(Scp),
5690 Ordering, getLLVMContext()));
5691 Builder.CreateBr(ContBB);
5692 }
5693 }
5694 }
5695
5696 Builder.SetInsertPoint(ContBB);
5697 return RValue::get(nullptr);
5698 }
5699
5700 case Builtin::BI__builtin_signbit:
5701 case Builtin::BI__builtin_signbitf:
5702 case Builtin::BI__builtin_signbitl: {
5703 return RValue::get(
5704 Builder.CreateZExt(EmitSignBit(*this, EmitScalarExpr(E->getArg(0))),
5705 ConvertType(E->getType())));
5706 }
5707 case Builtin::BI__warn_memset_zero_len:
5708 return RValue::getIgnored();
5709 case Builtin::BI__annotation: {
5710 // Re-encode each wide string to UTF8 and make an MDString.
5712 for (const Expr *Arg : E->arguments()) {
5713 const auto *Str = cast<StringLiteral>(Arg->IgnoreParenCasts());
5714 assert(Str->getCharByteWidth() == 2 || Str->getCharByteWidth() == 4);
5715 StringRef WideBytes = Str->getBytes();
5716 std::string StrUtf8;
5717 bool Converted =
5718 (Str->getCharByteWidth() == 2)
5719 ? convertUTF16ToUTF8String(
5720 ArrayRef(WideBytes.data(), WideBytes.size()), StrUtf8)
5721 : convertUTF32ToUTF8String(
5722 ArrayRef(WideBytes.data(), WideBytes.size()), StrUtf8);
5723 if (!Converted) {
5724 CGM.ErrorUnsupported(E, "non-Unicode __annotation argument");
5725 continue;
5726 }
5727 Strings.push_back(llvm::MDString::get(getLLVMContext(), StrUtf8));
5728 }
5729
5730 // Build and MDTuple of MDStrings and emit the intrinsic call.
5731 llvm::Function *F = CGM.getIntrinsic(Intrinsic::codeview_annotation, {});
5732 MDTuple *StrTuple = MDTuple::get(getLLVMContext(), Strings);
5733 Builder.CreateCall(F, MetadataAsValue::get(getLLVMContext(), StrTuple));
5734 return RValue::getIgnored();
5735 }
5736 case Builtin::BI__builtin_annotation: {
5737 llvm::Value *AnnVal = EmitScalarExpr(E->getArg(0));
5738 llvm::Function *F = CGM.getIntrinsic(
5739 Intrinsic::annotation, {AnnVal->getType(), CGM.ConstGlobalsPtrTy});
5740
5741 // Get the annotation string, go through casts. Sema requires this to be a
5742 // non-wide string literal, potentially casted, so the cast<> is safe.
5743 const Expr *AnnotationStrExpr = E->getArg(1)->IgnoreParenCasts();
5744 StringRef Str = cast<StringLiteral>(AnnotationStrExpr)->getString();
5745 return RValue::get(
5746 EmitAnnotationCall(F, AnnVal, Str, E->getExprLoc(), nullptr));
5747 }
5748 case Builtin::BI__builtin_addcb:
5749 case Builtin::BI__builtin_addcs:
5750 case Builtin::BI__builtin_addc:
5751 case Builtin::BI__builtin_addcl:
5752 case Builtin::BI__builtin_addcll:
5753 case Builtin::BI__builtin_subcb:
5754 case Builtin::BI__builtin_subcs:
5755 case Builtin::BI__builtin_subc:
5756 case Builtin::BI__builtin_subcl:
5757 case Builtin::BI__builtin_subcll: {
5758
5759 // We translate all of these builtins from expressions of the form:
5760 // int x = ..., y = ..., carryin = ..., carryout, result;
5761 // result = __builtin_addc(x, y, carryin, &carryout);
5762 //
5763 // to LLVM IR of the form:
5764 //
5765 // %tmp1 = call {i32, i1} @llvm.uadd.with.overflow.i32(i32 %x, i32 %y)
5766 // %tmpsum1 = extractvalue {i32, i1} %tmp1, 0
5767 // %carry1 = extractvalue {i32, i1} %tmp1, 1
5768 // %tmp2 = call {i32, i1} @llvm.uadd.with.overflow.i32(i32 %tmpsum1,
5769 // i32 %carryin)
5770 // %result = extractvalue {i32, i1} %tmp2, 0
5771 // %carry2 = extractvalue {i32, i1} %tmp2, 1
5772 // %tmp3 = or i1 %carry1, %carry2
5773 // %tmp4 = zext i1 %tmp3 to i32
5774 // store i32 %tmp4, i32* %carryout
5775
5776 // Scalarize our inputs.
5777 llvm::Value *X = EmitScalarExpr(E->getArg(0));
5778 llvm::Value *Y = EmitScalarExpr(E->getArg(1));
5779 llvm::Value *Carryin = EmitScalarExpr(E->getArg(2));
5780 Address CarryOutPtr = EmitPointerWithAlignment(E->getArg(3));
5781
5782 // Decide if we are lowering to a uadd.with.overflow or usub.with.overflow.
5783 Intrinsic::ID IntrinsicId;
5784 switch (BuiltinID) {
5785 default: llvm_unreachable("Unknown multiprecision builtin id.");
5786 case Builtin::BI__builtin_addcb:
5787 case Builtin::BI__builtin_addcs:
5788 case Builtin::BI__builtin_addc:
5789 case Builtin::BI__builtin_addcl:
5790 case Builtin::BI__builtin_addcll:
5791 IntrinsicId = Intrinsic::uadd_with_overflow;
5792 break;
5793 case Builtin::BI__builtin_subcb:
5794 case Builtin::BI__builtin_subcs:
5795 case Builtin::BI__builtin_subc:
5796 case Builtin::BI__builtin_subcl:
5797 case Builtin::BI__builtin_subcll:
5798 IntrinsicId = Intrinsic::usub_with_overflow;
5799 break;
5800 }
5801
5802 // Construct our resulting LLVM IR expression.
5803 llvm::Value *Carry1;
5804 llvm::Value *Sum1 = EmitOverflowIntrinsic(*this, IntrinsicId,
5805 X, Y, Carry1);
5806 llvm::Value *Carry2;
5807 llvm::Value *Sum2 = EmitOverflowIntrinsic(*this, IntrinsicId,
5808 Sum1, Carryin, Carry2);
5809 llvm::Value *CarryOut = Builder.CreateZExt(Builder.CreateOr(Carry1, Carry2),
5810 X->getType());
5811 Builder.CreateStore(CarryOut, CarryOutPtr);
5812 return RValue::get(Sum2);
5813 }
5814
5815 case Builtin::BI__builtin_add_overflow:
5816 case Builtin::BI__builtin_sub_overflow:
5817 case Builtin::BI__builtin_mul_overflow: {
5818 const clang::Expr *LeftArg = E->getArg(0);
5819 const clang::Expr *RightArg = E->getArg(1);
5820 const clang::Expr *ResultArg = E->getArg(2);
5821
5822 clang::QualType ResultQTy =
5823 ResultArg->getType()->castAs<PointerType>()->getPointeeType();
5824
5825 WidthAndSignedness LeftInfo =
5826 getIntegerWidthAndSignedness(CGM.getContext(), LeftArg->getType());
5827 WidthAndSignedness RightInfo =
5828 getIntegerWidthAndSignedness(CGM.getContext(), RightArg->getType());
5829 WidthAndSignedness ResultInfo =
5830 getIntegerWidthAndSignedness(CGM.getContext(), ResultQTy);
5831
5832 // Handle mixed-sign multiplication as a special case, because adding
5833 // runtime or backend support for our generic irgen would be too expensive.
5834 if (isSpecialMixedSignMultiply(BuiltinID, LeftInfo, RightInfo, ResultInfo))
5835 return EmitCheckedMixedSignMultiply(*this, LeftArg, LeftInfo, RightArg,
5836 RightInfo, ResultArg, ResultQTy,
5837 ResultInfo);
5838
5839 if (isSpecialUnsignedMultiplySignedResult(BuiltinID, LeftInfo, RightInfo,
5840 ResultInfo))
5842 *this, LeftArg, LeftInfo, RightArg, RightInfo, ResultArg, ResultQTy,
5843 ResultInfo);
5844
5845 WidthAndSignedness EncompassingInfo =
5846 EncompassingIntegerType({LeftInfo, RightInfo, ResultInfo});
5847
5848 llvm::Type *EncompassingLLVMTy =
5849 llvm::IntegerType::get(CGM.getLLVMContext(), EncompassingInfo.Width);
5850
5851 llvm::Type *ResultLLVMTy = CGM.getTypes().ConvertType(ResultQTy);
5852
5853 Intrinsic::ID IntrinsicId;
5854 switch (BuiltinID) {
5855 default:
5856 llvm_unreachable("Unknown overflow builtin id.");
5857 case Builtin::BI__builtin_add_overflow:
5858 IntrinsicId = EncompassingInfo.Signed ? Intrinsic::sadd_with_overflow
5859 : Intrinsic::uadd_with_overflow;
5860 break;
5861 case Builtin::BI__builtin_sub_overflow:
5862 IntrinsicId = EncompassingInfo.Signed ? Intrinsic::ssub_with_overflow
5863 : Intrinsic::usub_with_overflow;
5864 break;
5865 case Builtin::BI__builtin_mul_overflow:
5866 IntrinsicId = EncompassingInfo.Signed ? Intrinsic::smul_with_overflow
5867 : Intrinsic::umul_with_overflow;
5868 break;
5869 }
5870
5871 llvm::Value *Left = EmitScalarExpr(LeftArg);
5872 llvm::Value *Right = EmitScalarExpr(RightArg);
5873 Address ResultPtr = EmitPointerWithAlignment(ResultArg);
5874
5875 // Extend each operand to the encompassing type.
5876 Left = Builder.CreateIntCast(Left, EncompassingLLVMTy, LeftInfo.Signed);
5877 Right = Builder.CreateIntCast(Right, EncompassingLLVMTy, RightInfo.Signed);
5878
5879 // Perform the operation on the extended values.
5880 llvm::Value *Overflow, *Result;
5881 Result = EmitOverflowIntrinsic(*this, IntrinsicId, Left, Right, Overflow);
5882
5883 if (EncompassingInfo.Width > ResultInfo.Width) {
5884 // The encompassing type is wider than the result type, so we need to
5885 // truncate it.
5886 llvm::Value *ResultTrunc = Builder.CreateTrunc(Result, ResultLLVMTy);
5887
5888 // To see if the truncation caused an overflow, we will extend
5889 // the result and then compare it to the original result.
5890 llvm::Value *ResultTruncExt = Builder.CreateIntCast(
5891 ResultTrunc, EncompassingLLVMTy, ResultInfo.Signed);
5892 llvm::Value *TruncationOverflow =
5893 Builder.CreateICmpNE(Result, ResultTruncExt);
5894
5895 Overflow = Builder.CreateOr(Overflow, TruncationOverflow);
5896 Result = ResultTrunc;
5897 }
5898
5899 // Finally, store the result using the pointer.
5900 bool isVolatile =
5901 ResultArg->getType()->getPointeeType().isVolatileQualified();
5902 Builder.CreateStore(EmitToMemory(Result, ResultQTy), ResultPtr, isVolatile);
5903
5904 return RValue::get(Overflow);
5905 }
5906
5907 case Builtin::BI__builtin_uadd_overflow:
5908 case Builtin::BI__builtin_uaddl_overflow:
5909 case Builtin::BI__builtin_uaddll_overflow:
5910 case Builtin::BI__builtin_usub_overflow:
5911 case Builtin::BI__builtin_usubl_overflow:
5912 case Builtin::BI__builtin_usubll_overflow:
5913 case Builtin::BI__builtin_umul_overflow:
5914 case Builtin::BI__builtin_umull_overflow:
5915 case Builtin::BI__builtin_umulll_overflow:
5916 case Builtin::BI__builtin_sadd_overflow:
5917 case Builtin::BI__builtin_saddl_overflow:
5918 case Builtin::BI__builtin_saddll_overflow:
5919 case Builtin::BI__builtin_ssub_overflow:
5920 case Builtin::BI__builtin_ssubl_overflow:
5921 case Builtin::BI__builtin_ssubll_overflow:
5922 case Builtin::BI__builtin_smul_overflow:
5923 case Builtin::BI__builtin_smull_overflow:
5924 case Builtin::BI__builtin_smulll_overflow: {
5925
5926 // We translate all of these builtins directly to the relevant llvm IR node.
5927
5928 // Scalarize our inputs.
5929 llvm::Value *X = EmitScalarExpr(E->getArg(0));
5930 llvm::Value *Y = EmitScalarExpr(E->getArg(1));
5931 Address SumOutPtr = EmitPointerWithAlignment(E->getArg(2));
5932
5933 // Decide which of the overflow intrinsics we are lowering to:
5934 Intrinsic::ID IntrinsicId;
5935 switch (BuiltinID) {
5936 default: llvm_unreachable("Unknown overflow builtin id.");
5937 case Builtin::BI__builtin_uadd_overflow:
5938 case Builtin::BI__builtin_uaddl_overflow:
5939 case Builtin::BI__builtin_uaddll_overflow:
5940 IntrinsicId = Intrinsic::uadd_with_overflow;
5941 break;
5942 case Builtin::BI__builtin_usub_overflow:
5943 case Builtin::BI__builtin_usubl_overflow:
5944 case Builtin::BI__builtin_usubll_overflow:
5945 IntrinsicId = Intrinsic::usub_with_overflow;
5946 break;
5947 case Builtin::BI__builtin_umul_overflow:
5948 case Builtin::BI__builtin_umull_overflow:
5949 case Builtin::BI__builtin_umulll_overflow:
5950 IntrinsicId = Intrinsic::umul_with_overflow;
5951 break;
5952 case Builtin::BI__builtin_sadd_overflow:
5953 case Builtin::BI__builtin_saddl_overflow:
5954 case Builtin::BI__builtin_saddll_overflow:
5955 IntrinsicId = Intrinsic::sadd_with_overflow;
5956 break;
5957 case Builtin::BI__builtin_ssub_overflow:
5958 case Builtin::BI__builtin_ssubl_overflow:
5959 case Builtin::BI__builtin_ssubll_overflow:
5960 IntrinsicId = Intrinsic::ssub_with_overflow;
5961 break;
5962 case Builtin::BI__builtin_smul_overflow:
5963 case Builtin::BI__builtin_smull_overflow:
5964 case Builtin::BI__builtin_smulll_overflow:
5965 IntrinsicId = Intrinsic::smul_with_overflow;
5966 break;
5967 }
5968
5969
5970 llvm::Value *Carry;
5971 llvm::Value *Sum = EmitOverflowIntrinsic(*this, IntrinsicId, X, Y, Carry);
5972 Builder.CreateStore(Sum, SumOutPtr);
5973
5974 return RValue::get(Carry);
5975 }
5976 case Builtin::BIaddressof:
5977 case Builtin::BI__addressof:
5978 case Builtin::BI__builtin_addressof:
5979 return RValue::get(EmitLValue(E->getArg(0)).getPointer(*this));
5980 case Builtin::BI__builtin_function_start:
5981 return RValue::get(CGM.GetFunctionStart(
5982 E->getArg(0)->getAsBuiltinConstantDeclRef(CGM.getContext())));
5983 case Builtin::BI__builtin_operator_new:
5985 E->getCallee()->getType()->castAs<FunctionProtoType>(), E, false);
5986 case Builtin::BI__builtin_operator_delete:
5988 E->getCallee()->getType()->castAs<FunctionProtoType>(), E, true);
5989 return RValue::get(nullptr);
5990
5991 case Builtin::BI__builtin_is_aligned:
5992 return EmitBuiltinIsAligned(E);
5993 case Builtin::BI__builtin_align_up:
5994 return EmitBuiltinAlignTo(E, true);
5995 case Builtin::BI__builtin_align_down:
5996 return EmitBuiltinAlignTo(E, false);
5997
5998 case Builtin::BI__noop:
5999 // __noop always evaluates to an integer literal zero.
6000 return RValue::get(ConstantInt::get(IntTy, 0));
6001 case Builtin::BI__builtin_call_with_static_chain: {
6002 const CallExpr *Call = cast<CallExpr>(E->getArg(0));
6003 const Expr *Chain = E->getArg(1);
6004 return EmitCall(Call->getCallee()->getType(),
6005 EmitCallee(Call->getCallee()), Call, ReturnValue,
6006 EmitScalarExpr(Chain));
6007 }
6008 case Builtin::BI_InterlockedExchange8:
6009 case Builtin::BI_InterlockedExchange16:
6010 case Builtin::BI_InterlockedExchange:
6011 case Builtin::BI_InterlockedExchangePointer:
6012 return RValue::get(
6014 case Builtin::BI_InterlockedCompareExchangePointer:
6015 return RValue::get(
6017 case Builtin::BI_InterlockedCompareExchangePointer_nf:
6018 return RValue::get(
6020 case Builtin::BI_InterlockedCompareExchange8:
6021 case Builtin::BI_InterlockedCompareExchange16:
6022 case Builtin::BI_InterlockedCompareExchange:
6023 case Builtin::BI_InterlockedCompareExchange64:
6024 return RValue::get(EmitAtomicCmpXchgForMSIntrin(*this, E));
6025 case Builtin::BI_InterlockedIncrement16:
6026 case Builtin::BI_InterlockedIncrement:
6027 return RValue::get(
6029 case Builtin::BI_InterlockedDecrement16:
6030 case Builtin::BI_InterlockedDecrement:
6031 return RValue::get(
6033 case Builtin::BI_InterlockedAnd8:
6034 case Builtin::BI_InterlockedAnd16:
6035 case Builtin::BI_InterlockedAnd:
6037 case Builtin::BI_InterlockedExchangeAdd8:
6038 case Builtin::BI_InterlockedExchangeAdd16:
6039 case Builtin::BI_InterlockedExchangeAdd:
6040 return RValue::get(
6042 case Builtin::BI_InterlockedExchangeSub8:
6043 case Builtin::BI_InterlockedExchangeSub16:
6044 case Builtin::BI_InterlockedExchangeSub:
6045 return RValue::get(
6047 case Builtin::BI_InterlockedOr8:
6048 case Builtin::BI_InterlockedOr16:
6049 case Builtin::BI_InterlockedOr:
6051 case Builtin::BI_InterlockedXor8:
6052 case Builtin::BI_InterlockedXor16:
6053 case Builtin::BI_InterlockedXor:
6055
6056 case Builtin::BI_bittest64:
6057 case Builtin::BI_bittest:
6058 case Builtin::BI_bittestandcomplement64:
6059 case Builtin::BI_bittestandcomplement:
6060 case Builtin::BI_bittestandreset64:
6061 case Builtin::BI_bittestandreset:
6062 case Builtin::BI_bittestandset64:
6063 case Builtin::BI_bittestandset:
6064 case Builtin::BI_interlockedbittestandreset:
6065 case Builtin::BI_interlockedbittestandreset64:
6066 case Builtin::BI_interlockedbittestandreset64_acq:
6067 case Builtin::BI_interlockedbittestandreset64_rel:
6068 case Builtin::BI_interlockedbittestandreset64_nf:
6069 case Builtin::BI_interlockedbittestandset64:
6070 case Builtin::BI_interlockedbittestandset64_acq:
6071 case Builtin::BI_interlockedbittestandset64_rel:
6072 case Builtin::BI_interlockedbittestandset64_nf:
6073 case Builtin::BI_interlockedbittestandset:
6074 case Builtin::BI_interlockedbittestandset_acq:
6075 case Builtin::BI_interlockedbittestandset_rel:
6076 case Builtin::BI_interlockedbittestandset_nf:
6077 case Builtin::BI_interlockedbittestandreset_acq:
6078 case Builtin::BI_interlockedbittestandreset_rel:
6079 case Builtin::BI_interlockedbittestandreset_nf:
6080 return RValue::get(EmitBitTestIntrinsic(*this, BuiltinID, E));
6081
6082 // These builtins exist to emit regular volatile loads and stores not
6083 // affected by the -fms-volatile setting.
6084 case Builtin::BI__iso_volatile_load8:
6085 case Builtin::BI__iso_volatile_load16:
6086 case Builtin::BI__iso_volatile_load32:
6087 case Builtin::BI__iso_volatile_load64:
6088 return RValue::get(EmitISOVolatileLoad(*this, E));
6089 case Builtin::BI__iso_volatile_store8:
6090 case Builtin::BI__iso_volatile_store16:
6091 case Builtin::BI__iso_volatile_store32:
6092 case Builtin::BI__iso_volatile_store64:
6093 return RValue::get(EmitISOVolatileStore(*this, E));
6094
6095 case Builtin::BI__builtin_ptrauth_sign_constant:
6096 return RValue::get(ConstantEmitter(*this).emitAbstract(E, E->getType()));
6097
6098 case Builtin::BI__builtin_ptrauth_auth:
6099 case Builtin::BI__builtin_ptrauth_auth_and_resign:
6100 case Builtin::BI__builtin_ptrauth_auth_with_pc_and_resign:
6101 case Builtin::BI__builtin_ptrauth_auth_load_relative_and_sign:
6102 case Builtin::BI__builtin_ptrauth_blend_discriminator:
6103 case Builtin::BI__builtin_ptrauth_sign_generic_data:
6104 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
6105 case Builtin::BI__builtin_ptrauth_strip: {
6106 // Emit the arguments.
6108 for (auto argExpr : E->arguments())
6109 Args.push_back(EmitScalarExpr(argExpr));
6110
6111 // Cast the value to intptr_t, saving its original type.
6112 llvm::Type *OrigValueType = Args[0]->getType();
6113 if (OrigValueType->isPointerTy())
6114 Args[0] = Builder.CreatePtrToInt(Args[0], IntPtrTy);
6115
6116 switch (BuiltinID) {
6117 case Builtin::BI__builtin_ptrauth_auth_with_pc_and_resign:
6118 // Convert oldDiscriminator (arg 2), oldPC (arg 3) and newDiscriminator
6119 // (arg 5) to intptr_t
6120 if (Args[2]->getType()->isPointerTy())
6121 Args[2] = Builder.CreatePtrToInt(Args[2], IntPtrTy);
6122 if (Args[3]->getType()->isPointerTy())
6123 Args[3] = Builder.CreatePtrToInt(Args[3], IntPtrTy);
6124 if (Args[5]->getType()->isPointerTy())
6125 Args[5] = Builder.CreatePtrToInt(Args[5], IntPtrTy);
6126 break;
6127
6128 case Builtin::BI__builtin_ptrauth_auth_and_resign:
6129 case Builtin::BI__builtin_ptrauth_auth_load_relative_and_sign:
6130 if (Args[4]->getType()->isPointerTy())
6131 Args[4] = Builder.CreatePtrToInt(Args[4], IntPtrTy);
6132 [[fallthrough]];
6133
6134 case Builtin::BI__builtin_ptrauth_auth:
6135 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
6136 if (Args[2]->getType()->isPointerTy())
6137 Args[2] = Builder.CreatePtrToInt(Args[2], IntPtrTy);
6138 break;
6139
6140 case Builtin::BI__builtin_ptrauth_sign_generic_data:
6141 if (Args[1]->getType()->isPointerTy())
6142 Args[1] = Builder.CreatePtrToInt(Args[1], IntPtrTy);
6143 break;
6144
6145 case Builtin::BI__builtin_ptrauth_blend_discriminator:
6146 case Builtin::BI__builtin_ptrauth_strip:
6147 break;
6148 }
6149
6150 // Call the intrinsic.
6151 auto IntrinsicID = [&]() -> unsigned {
6152 switch (BuiltinID) {
6153 case Builtin::BI__builtin_ptrauth_auth:
6154 return Intrinsic::ptrauth_auth;
6155 case Builtin::BI__builtin_ptrauth_auth_and_resign:
6156 return Intrinsic::ptrauth_resign;
6157 case Builtin::BI__builtin_ptrauth_auth_with_pc_and_resign:
6158 return Intrinsic::ptrauth_auth_with_pc_and_resign;
6159 case Builtin::BI__builtin_ptrauth_auth_load_relative_and_sign:
6160 return Intrinsic::ptrauth_resign_load_relative;
6161 case Builtin::BI__builtin_ptrauth_blend_discriminator:
6162 return Intrinsic::ptrauth_blend;
6163 case Builtin::BI__builtin_ptrauth_sign_generic_data:
6164 return Intrinsic::ptrauth_sign_generic;
6165 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
6166 return Intrinsic::ptrauth_sign;
6167 case Builtin::BI__builtin_ptrauth_strip:
6168 return Intrinsic::ptrauth_strip;
6169 }
6170 llvm_unreachable("bad ptrauth intrinsic");
6171 }();
6172 auto Intrinsic = CGM.getIntrinsic(IntrinsicID);
6173 llvm::Value *Result = EmitRuntimeCall(Intrinsic, Args);
6174
6175 if (BuiltinID != Builtin::BI__builtin_ptrauth_sign_generic_data &&
6176 BuiltinID != Builtin::BI__builtin_ptrauth_blend_discriminator &&
6177 OrigValueType->isPointerTy()) {
6178 Result = Builder.CreateIntToPtr(Result, OrigValueType);
6179 }
6180 return RValue::get(Result);
6181 }
6182
6183 case Builtin::BI__builtin_get_vtable_pointer: {
6184 const Expr *Target = E->getArg(0);
6185 QualType TargetType = Target->getType();
6186 const CXXRecordDecl *Decl = TargetType->getPointeeCXXRecordDecl();
6187 assert(Decl);
6188 auto ThisAddress = EmitPointerWithAlignment(Target);
6189 assert(ThisAddress.isValid());
6190 llvm::Value *VTablePointer =
6192 return RValue::get(VTablePointer);
6193 }
6194
6195 case Builtin::BI__exception_code:
6196 case Builtin::BI_exception_code:
6198 case Builtin::BI__exception_info:
6199 case Builtin::BI_exception_info:
6201 case Builtin::BI__abnormal_termination:
6202 case Builtin::BI_abnormal_termination:
6204 case Builtin::BI_setjmpex:
6205 if (getTarget().getTriple().isOSMSVCRT() && E->getNumArgs() == 1 &&
6206 E->getArg(0)->getType()->isPointerType())
6207 return EmitMSVCRTSetJmp(*this, MSVCSetJmpKind::_setjmpex, E);
6208 break;
6209 case Builtin::BI_setjmp:
6210 if (getTarget().getTriple().isOSMSVCRT() && E->getNumArgs() == 1 &&
6211 E->getArg(0)->getType()->isPointerType()) {
6212 if (getTarget().getTriple().getArch() == llvm::Triple::x86)
6213 return EmitMSVCRTSetJmp(*this, MSVCSetJmpKind::_setjmp3, E);
6214 else if (getTarget().getTriple().getArch() == llvm::Triple::aarch64)
6215 return EmitMSVCRTSetJmp(*this, MSVCSetJmpKind::_setjmpex, E);
6216 return EmitMSVCRTSetJmp(*this, MSVCSetJmpKind::_setjmp, E);
6217 }
6218 break;
6219
6220 // C++ std:: builtins.
6221 case Builtin::BImove:
6222 case Builtin::BImove_if_noexcept:
6223 case Builtin::BIforward:
6224 case Builtin::BIforward_like:
6225 case Builtin::BIas_const:
6226 return RValue::get(EmitLValue(E->getArg(0)).getPointer(*this));
6227 case Builtin::BI__GetExceptionInfo: {
6228 if (llvm::GlobalVariable *GV =
6229 CGM.getCXXABI().getThrowInfo(FD->getParamDecl(0)->getType()))
6230 return RValue::get(GV);
6231 break;
6232 }
6233
6234 case Builtin::BI__fastfail:
6236
6237 case Builtin::BI__builtin_coro_id:
6238 return EmitCoroutineIntrinsic(E, Intrinsic::coro_id);
6239 case Builtin::BI__builtin_coro_promise:
6240 return EmitCoroutineIntrinsic(E, Intrinsic::coro_promise);
6241 case Builtin::BI__builtin_coro_resume:
6242 EmitCoroutineIntrinsic(E, Intrinsic::coro_resume);
6243 return RValue::get(nullptr);
6244 case Builtin::BI__builtin_coro_frame:
6245 return EmitCoroutineIntrinsic(E, Intrinsic::coro_frame);
6246 case Builtin::BI__builtin_coro_noop:
6247 return EmitCoroutineIntrinsic(E, Intrinsic::coro_noop);
6248 case Builtin::BI__builtin_coro_free:
6249 return EmitCoroutineIntrinsic(E, Intrinsic::coro_free);
6250 case Builtin::BI__builtin_coro_destroy:
6251 EmitCoroutineIntrinsic(E, Intrinsic::coro_destroy);
6252 return RValue::get(nullptr);
6253 case Builtin::BI__builtin_coro_done:
6254 return EmitCoroutineIntrinsic(E, Intrinsic::coro_done);
6255 case Builtin::BI__builtin_coro_alloc:
6256 return EmitCoroutineIntrinsic(E, Intrinsic::coro_alloc);
6257 case Builtin::BI__builtin_coro_begin:
6258 return EmitCoroutineIntrinsic(E, Intrinsic::coro_begin);
6259 case Builtin::BI__builtin_coro_end:
6260 return EmitCoroutineIntrinsic(E, Intrinsic::coro_end);
6261 case Builtin::BI__builtin_coro_suspend:
6262 return EmitCoroutineIntrinsic(E, Intrinsic::coro_suspend);
6263 case Builtin::BI__builtin_coro_size:
6264 return EmitCoroutineIntrinsic(E, Intrinsic::coro_size);
6265 case Builtin::BI__builtin_coro_align:
6266 return EmitCoroutineIntrinsic(E, Intrinsic::coro_align);
6267
6268 // OpenCL v2.0 s6.13.16.2, Built-in pipe read and write functions
6269 case Builtin::BIread_pipe:
6270 case Builtin::BIwrite_pipe: {
6271 Value *Arg0 = EmitScalarExpr(E->getArg(0)),
6272 *Arg1 = EmitScalarExpr(E->getArg(1));
6273 CGOpenCLRuntime OpenCLRT(CGM);
6274 Value *PacketSize = OpenCLRT.getPipeElemSize(E->getArg(0));
6275 Value *PacketAlign = OpenCLRT.getPipeElemAlign(E->getArg(0));
6276
6277 // Type of the generic packet parameter.
6278 unsigned GenericAS =
6280 llvm::Type *I8PTy = llvm::PointerType::get(getLLVMContext(), GenericAS);
6281
6282 // Testing which overloaded version we should generate the call for.
6283 if (2U == E->getNumArgs()) {
6284 const char *Name = (BuiltinID == Builtin::BIread_pipe) ? "__read_pipe_2"
6285 : "__write_pipe_2";
6286 // Creating a generic function type to be able to call with any builtin or
6287 // user defined type.
6288 llvm::Type *ArgTys[] = {Arg0->getType(), I8PTy, Int32Ty, Int32Ty};
6289 llvm::FunctionType *FTy = llvm::FunctionType::get(Int32Ty, ArgTys, false);
6290 Value *ACast = Builder.CreateAddrSpaceCast(Arg1, I8PTy);
6291 return RValue::get(
6292 EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
6293 {Arg0, ACast, PacketSize, PacketAlign}));
6294 } else {
6295 assert(4 == E->getNumArgs() &&
6296 "Illegal number of parameters to pipe function");
6297 const char *Name = (BuiltinID == Builtin::BIread_pipe) ? "__read_pipe_4"
6298 : "__write_pipe_4";
6299
6300 llvm::Type *ArgTys[] = {Arg0->getType(), Arg1->getType(), Int32Ty, I8PTy,
6301 Int32Ty, Int32Ty};
6302 Value *Arg2 = EmitScalarExpr(E->getArg(2)),
6303 *Arg3 = EmitScalarExpr(E->getArg(3));
6304 llvm::FunctionType *FTy = llvm::FunctionType::get(Int32Ty, ArgTys, false);
6305 Value *ACast = Builder.CreateAddrSpaceCast(Arg3, I8PTy);
6306 // We know the third argument is an integer type, but we may need to cast
6307 // it to i32.
6308 if (Arg2->getType() != Int32Ty)
6309 Arg2 = Builder.CreateZExtOrTrunc(Arg2, Int32Ty);
6310 return RValue::get(
6311 EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
6312 {Arg0, Arg1, Arg2, ACast, PacketSize, PacketAlign}));
6313 }
6314 }
6315 // OpenCL v2.0 s6.13.16 ,s9.17.3.5 - Built-in pipe reserve read and write
6316 // functions
6317 case Builtin::BIreserve_read_pipe:
6318 case Builtin::BIreserve_write_pipe:
6319 case Builtin::BIwork_group_reserve_read_pipe:
6320 case Builtin::BIwork_group_reserve_write_pipe:
6321 case Builtin::BIsub_group_reserve_read_pipe:
6322 case Builtin::BIsub_group_reserve_write_pipe: {
6323 // Composing the mangled name for the function.
6324 const char *Name;
6325 if (BuiltinID == Builtin::BIreserve_read_pipe)
6326 Name = "__reserve_read_pipe";
6327 else if (BuiltinID == Builtin::BIreserve_write_pipe)
6328 Name = "__reserve_write_pipe";
6329 else if (BuiltinID == Builtin::BIwork_group_reserve_read_pipe)
6330 Name = "__work_group_reserve_read_pipe";
6331 else if (BuiltinID == Builtin::BIwork_group_reserve_write_pipe)
6332 Name = "__work_group_reserve_write_pipe";
6333 else if (BuiltinID == Builtin::BIsub_group_reserve_read_pipe)
6334 Name = "__sub_group_reserve_read_pipe";
6335 else
6336 Name = "__sub_group_reserve_write_pipe";
6337
6338 Value *Arg0 = EmitScalarExpr(E->getArg(0)),
6339 *Arg1 = EmitScalarExpr(E->getArg(1));
6340 llvm::Type *ReservedIDTy = ConvertType(getContext().OCLReserveIDTy);
6341 CGOpenCLRuntime OpenCLRT(CGM);
6342 Value *PacketSize = OpenCLRT.getPipeElemSize(E->getArg(0));
6343 Value *PacketAlign = OpenCLRT.getPipeElemAlign(E->getArg(0));
6344
6345 // Building the generic function prototype.
6346 llvm::Type *ArgTys[] = {Arg0->getType(), Int32Ty, Int32Ty, Int32Ty};
6347 llvm::FunctionType *FTy =
6348 llvm::FunctionType::get(ReservedIDTy, ArgTys, false);
6349 // We know the second argument is an integer type, but we may need to cast
6350 // it to i32.
6351 if (Arg1->getType() != Int32Ty)
6352 Arg1 = Builder.CreateZExtOrTrunc(Arg1, Int32Ty);
6353 return RValue::get(EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
6354 {Arg0, Arg1, PacketSize, PacketAlign}));
6355 }
6356 // OpenCL v2.0 s6.13.16, s9.17.3.5 - Built-in pipe commit read and write
6357 // functions
6358 case Builtin::BIcommit_read_pipe:
6359 case Builtin::BIcommit_write_pipe:
6360 case Builtin::BIwork_group_commit_read_pipe:
6361 case Builtin::BIwork_group_commit_write_pipe:
6362 case Builtin::BIsub_group_commit_read_pipe:
6363 case Builtin::BIsub_group_commit_write_pipe: {
6364 const char *Name;
6365 if (BuiltinID == Builtin::BIcommit_read_pipe)
6366 Name = "__commit_read_pipe";
6367 else if (BuiltinID == Builtin::BIcommit_write_pipe)
6368 Name = "__commit_write_pipe";
6369 else if (BuiltinID == Builtin::BIwork_group_commit_read_pipe)
6370 Name = "__work_group_commit_read_pipe";
6371 else if (BuiltinID == Builtin::BIwork_group_commit_write_pipe)
6372 Name = "__work_group_commit_write_pipe";
6373 else if (BuiltinID == Builtin::BIsub_group_commit_read_pipe)
6374 Name = "__sub_group_commit_read_pipe";
6375 else
6376 Name = "__sub_group_commit_write_pipe";
6377
6378 Value *Arg0 = EmitScalarExpr(E->getArg(0)),
6379 *Arg1 = EmitScalarExpr(E->getArg(1));
6380 CGOpenCLRuntime OpenCLRT(CGM);
6381 Value *PacketSize = OpenCLRT.getPipeElemSize(E->getArg(0));
6382 Value *PacketAlign = OpenCLRT.getPipeElemAlign(E->getArg(0));
6383
6384 // Building the generic function prototype.
6385 llvm::Type *ArgTys[] = {Arg0->getType(), Arg1->getType(), Int32Ty, Int32Ty};
6386 llvm::FunctionType *FTy = llvm::FunctionType::get(
6387 llvm::Type::getVoidTy(getLLVMContext()), ArgTys, false);
6388
6389 return RValue::get(EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
6390 {Arg0, Arg1, PacketSize, PacketAlign}));
6391 }
6392 // OpenCL v2.0 s6.13.16.4 Built-in pipe query functions
6393 case Builtin::BIget_pipe_num_packets:
6394 case Builtin::BIget_pipe_max_packets: {
6395 const char *BaseName;
6396 const auto *PipeTy = E->getArg(0)->getType()->castAs<PipeType>();
6397 if (BuiltinID == Builtin::BIget_pipe_num_packets)
6398 BaseName = "__get_pipe_num_packets";
6399 else
6400 BaseName = "__get_pipe_max_packets";
6401 std::string Name = std::string(BaseName) +
6402 std::string(PipeTy->isReadOnly() ? "_ro" : "_wo");
6403
6404 // Building the generic function prototype.
6405 Value *Arg0 = EmitScalarExpr(E->getArg(0));
6406 CGOpenCLRuntime OpenCLRT(CGM);
6407 Value *PacketSize = OpenCLRT.getPipeElemSize(E->getArg(0));
6408 Value *PacketAlign = OpenCLRT.getPipeElemAlign(E->getArg(0));
6409 llvm::Type *ArgTys[] = {Arg0->getType(), Int32Ty, Int32Ty};
6410 llvm::FunctionType *FTy = llvm::FunctionType::get(Int32Ty, ArgTys, false);
6411
6412 return RValue::get(EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
6413 {Arg0, PacketSize, PacketAlign}));
6414 }
6415
6416 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
6417 case Builtin::BIto_global:
6418 case Builtin::BIto_local:
6419 case Builtin::BIto_private: {
6420 auto Arg0 = EmitScalarExpr(E->getArg(0));
6421 auto NewArgT = llvm::PointerType::get(
6423 CGM.getContext().getTargetAddressSpace(LangAS::opencl_generic));
6424 auto NewRetT = llvm::PointerType::get(
6426 CGM.getContext().getTargetAddressSpace(
6428 auto FTy = llvm::FunctionType::get(NewRetT, {NewArgT}, false);
6429 llvm::Value *NewArg;
6430 if (Arg0->getType()->getPointerAddressSpace() !=
6431 NewArgT->getPointerAddressSpace())
6432 NewArg = Builder.CreateAddrSpaceCast(Arg0, NewArgT);
6433 else
6434 NewArg = Builder.CreateBitOrPointerCast(Arg0, NewArgT);
6435 auto NewName = std::string("__") + E->getDirectCallee()->getName().str();
6436 auto NewCall =
6437 EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, NewName), {NewArg});
6438 return RValue::get(Builder.CreateBitOrPointerCast(NewCall,
6439 ConvertType(E->getType())));
6440 }
6441
6442 // OpenCL v2.0, s6.13.17 - Enqueue kernel function.
6443 // Table 6.13.17.1 specifies four overload forms of enqueue_kernel.
6444 // The code below expands the builtin call to a call to one of the following
6445 // functions that an OpenCL runtime library will have to provide:
6446 // __enqueue_kernel_basic
6447 // __enqueue_kernel_varargs
6448 // __enqueue_kernel_basic_events
6449 // __enqueue_kernel_events_varargs
6450 case Builtin::BIenqueue_kernel: {
6451 StringRef Name; // Generated function call name
6452 unsigned NumArgs = E->getNumArgs();
6453
6454 llvm::Type *QueueTy = ConvertType(getContext().OCLQueueTy);
6455 llvm::Type *GenericVoidPtrTy = Builder.getPtrTy(
6456 getContext().getTargetAddressSpace(LangAS::opencl_generic));
6457
6458 llvm::Value *Queue = EmitScalarExpr(E->getArg(0));
6459 llvm::Value *Flags = EmitScalarExpr(E->getArg(1));
6460 LValue NDRangeL = EmitAggExprToLValue(E->getArg(2));
6461 llvm::Value *Range = NDRangeL.getAddress().emitRawPointer(*this);
6462
6463 // FIXME: Look through the addrspacecast which may exist to the stack
6464 // temporary as a hack.
6465 //
6466 // This is hardcoding the assumed ABI of the target function. This assumes
6467 // direct passing for every argument except NDRange, which is assumed to be
6468 // byval or byref indirect passed.
6469 //
6470 // This should be fixed to query a signature from CGOpenCLRuntime, and go
6471 // through EmitCallArgs to get the correct target ABI.
6472 Range = Range->stripPointerCasts();
6473
6474 llvm::Type *RangePtrTy = Range->getType();
6475
6476 if (NumArgs == 4) {
6477 // The most basic form of the call with parameters:
6478 // queue_t, kernel_enqueue_flags_t, ndrange_t, block(void)
6479 Name = "__enqueue_kernel_basic";
6480 llvm::Type *ArgTys[] = {QueueTy, Int32Ty, RangePtrTy, GenericVoidPtrTy,
6481 GenericVoidPtrTy};
6482 llvm::FunctionType *FTy = llvm::FunctionType::get(Int32Ty, ArgTys, false);
6483
6484 auto Info =
6485 CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(3));
6486 llvm::Value *Kernel =
6487 Builder.CreatePointerCast(Info.KernelHandle, GenericVoidPtrTy);
6488 llvm::Value *Block =
6489 Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
6490
6491 auto RTCall = EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name),
6492 {Queue, Flags, Range, Kernel, Block});
6493 return RValue::get(RTCall);
6494 }
6495 assert(NumArgs >= 5 && "Invalid enqueue_kernel signature");
6496
6497 // Create a temporary array to hold the sizes of local pointer arguments
6498 // for the block. \p First is the position of the first size argument.
6499 auto CreateArrayForSizeVar =
6500 [=](unsigned First) -> std::pair<llvm::Value *, llvm::Value *> {
6501 llvm::APInt ArraySize(32, NumArgs - First);
6503 getContext().getSizeType(), ArraySize, nullptr,
6505 /*IndexTypeQuals=*/0);
6506 auto Tmp = CreateMemTempWithoutCast(SizeArrayTy, "block_sizes");
6507 llvm::Value *Alloca = Tmp.getPointer();
6508 llvm::Value *ElemPtr;
6509 EmitLifetimeStart(Alloca);
6510 // Each of the following arguments specifies the size of the corresponding
6511 // argument passed to the enqueued block.
6512 auto *Zero = llvm::ConstantInt::get(IntTy, 0);
6513 for (unsigned I = First; I < NumArgs; ++I) {
6514 auto *Index = llvm::ConstantInt::get(IntTy, I - First);
6515 auto *GEP =
6516 Builder.CreateGEP(Tmp.getElementType(), Alloca, {Zero, Index});
6517 if (I == First)
6518 ElemPtr = GEP;
6519 auto *V =
6520 Builder.CreateZExtOrTrunc(EmitScalarExpr(E->getArg(I)), SizeTy);
6521 Builder.CreateAlignedStore(
6522 V, GEP, CGM.getDataLayout().getPrefTypeAlign(SizeTy));
6523 }
6524 return {ElemPtr, Alloca};
6525 };
6526
6527 // Could have events and/or varargs.
6528 if (E->getArg(3)->getType()->isBlockPointerType()) {
6529 // No events passed, but has variadic arguments.
6530 Name = "__enqueue_kernel_varargs";
6531 auto Info =
6532 CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(3));
6533 llvm::Value *Kernel =
6534 Builder.CreatePointerCast(Info.KernelHandle, GenericVoidPtrTy);
6535 auto *Block = Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
6536 auto [ElemPtr, TmpPtr] = CreateArrayForSizeVar(4);
6537
6538 // Create a vector of the arguments, as well as a constant value to
6539 // express to the runtime the number of variadic arguments.
6540 llvm::Value *const Args[] = {Queue, Flags,
6541 Range, Kernel,
6542 Block, ConstantInt::get(IntTy, NumArgs - 4),
6543 ElemPtr};
6544 llvm::Type *const ArgTys[] = {
6545 QueueTy, IntTy, RangePtrTy, GenericVoidPtrTy,
6546 GenericVoidPtrTy, IntTy, ElemPtr->getType()};
6547
6548 llvm::FunctionType *FTy = llvm::FunctionType::get(Int32Ty, ArgTys, false);
6549 auto Call = RValue::get(
6550 EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name), Args));
6551 EmitLifetimeEnd(TmpPtr);
6552 return Call;
6553 }
6554 // Any calls now have event arguments passed.
6555 if (NumArgs >= 7) {
6556 llvm::PointerType *PtrTy = llvm::PointerType::get(
6557 CGM.getLLVMContext(),
6558 CGM.getContext().getTargetAddressSpace(LangAS::opencl_generic));
6559
6560 llvm::Value *NumEvents =
6561 Builder.CreateZExtOrTrunc(EmitScalarExpr(E->getArg(3)), Int32Ty);
6562
6563 // Since SemaOpenCLBuiltinEnqueueKernel allows fifth and sixth arguments
6564 // to be a null pointer constant (including `0` literal), we can take it
6565 // into account and emit null pointer directly.
6566 llvm::Value *EventWaitList = nullptr;
6567 if (E->getArg(4)->isNullPointerConstant(
6569 EventWaitList = llvm::ConstantPointerNull::get(PtrTy);
6570 } else {
6571 EventWaitList =
6572 E->getArg(4)->getType()->isArrayType()
6574 : EmitScalarExpr(E->getArg(4));
6575 // Convert to generic address space.
6576 EventWaitList = Builder.CreatePointerCast(EventWaitList, PtrTy);
6577 }
6578 llvm::Value *EventRet = nullptr;
6579 if (E->getArg(5)->isNullPointerConstant(
6581 EventRet = llvm::ConstantPointerNull::get(PtrTy);
6582 } else {
6583 EventRet =
6584 Builder.CreatePointerCast(EmitScalarExpr(E->getArg(5)), PtrTy);
6585 }
6586
6587 auto Info =
6588 CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(6));
6589 llvm::Value *Kernel =
6590 Builder.CreatePointerCast(Info.KernelHandle, GenericVoidPtrTy);
6591 llvm::Value *Block =
6592 Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
6593
6594 std::vector<llvm::Type *> ArgTys = {
6595 QueueTy, Int32Ty, RangePtrTy, Int32Ty,
6596 PtrTy, PtrTy, GenericVoidPtrTy, GenericVoidPtrTy};
6597
6598 std::vector<llvm::Value *> Args = {Queue, Flags, Range,
6599 NumEvents, EventWaitList, EventRet,
6600 Kernel, Block};
6601
6602 if (NumArgs == 7) {
6603 // Has events but no variadics.
6604 Name = "__enqueue_kernel_basic_events";
6605 llvm::FunctionType *FTy =
6606 llvm::FunctionType::get(Int32Ty, ArgTys, false);
6607 return RValue::get(
6608 EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name), Args));
6609 }
6610 // Has event info and variadics
6611 // Pass the number of variadics to the runtime function too.
6612 Args.push_back(ConstantInt::get(Int32Ty, NumArgs - 7));
6613 ArgTys.push_back(Int32Ty);
6614 Name = "__enqueue_kernel_events_varargs";
6615
6616 auto [ElemPtr, TmpPtr] = CreateArrayForSizeVar(7);
6617 Args.push_back(ElemPtr);
6618 ArgTys.push_back(ElemPtr->getType());
6619
6620 llvm::FunctionType *FTy = llvm::FunctionType::get(Int32Ty, ArgTys, false);
6621 auto Call = RValue::get(
6622 EmitRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name), Args));
6623 EmitLifetimeEnd(TmpPtr);
6624 return Call;
6625 }
6626 llvm_unreachable("Unexpected enqueue_kernel signature");
6627 }
6628 // OpenCL v2.0 s6.13.17.6 - Kernel query functions need bitcast of block
6629 // parameter.
6630 case Builtin::BIget_kernel_work_group_size: {
6631 llvm::Type *GenericVoidPtrTy = Builder.getPtrTy(
6632 getContext().getTargetAddressSpace(LangAS::opencl_generic));
6633 auto Info =
6634 CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(0));
6635 Value *Kernel =
6636 Builder.CreatePointerCast(Info.KernelHandle, GenericVoidPtrTy);
6637 Value *Arg = Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
6639 CGM.CreateRuntimeFunction(
6640 llvm::FunctionType::get(IntTy, {GenericVoidPtrTy, GenericVoidPtrTy},
6641 false),
6642 "__get_kernel_work_group_size_impl"),
6643 {Kernel, Arg}));
6644 }
6645 case Builtin::BIget_kernel_preferred_work_group_size_multiple: {
6646 llvm::Type *GenericVoidPtrTy = Builder.getPtrTy(
6647 getContext().getTargetAddressSpace(LangAS::opencl_generic));
6648 auto Info =
6649 CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(0));
6650 Value *Kernel =
6651 Builder.CreatePointerCast(Info.KernelHandle, GenericVoidPtrTy);
6652 Value *Arg = Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
6654 CGM.CreateRuntimeFunction(
6655 llvm::FunctionType::get(IntTy, {GenericVoidPtrTy, GenericVoidPtrTy},
6656 false),
6657 "__get_kernel_preferred_work_group_size_multiple_impl"),
6658 {Kernel, Arg}));
6659 }
6660 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
6661 case Builtin::BIget_kernel_sub_group_count_for_ndrange: {
6662 llvm::Type *GenericVoidPtrTy = Builder.getPtrTy(
6663 getContext().getTargetAddressSpace(LangAS::opencl_generic));
6664 LValue NDRangeL = EmitAggExprToLValue(E->getArg(0));
6665 llvm::Value *NDRange = NDRangeL.getAddress().emitRawPointer(*this);
6666 auto Info =
6667 CGM.getOpenCLRuntime().emitOpenCLEnqueuedBlock(*this, E->getArg(1));
6668 Value *Kernel =
6669 Builder.CreatePointerCast(Info.KernelHandle, GenericVoidPtrTy);
6670 Value *Block = Builder.CreatePointerCast(Info.BlockArg, GenericVoidPtrTy);
6671 const char *Name =
6672 BuiltinID == Builtin::BIget_kernel_max_sub_group_size_for_ndrange
6673 ? "__get_kernel_max_sub_group_size_for_ndrange_impl"
6674 : "__get_kernel_sub_group_count_for_ndrange_impl";
6676 CGM.CreateRuntimeFunction(
6677 llvm::FunctionType::get(
6678 IntTy, {NDRange->getType(), GenericVoidPtrTy, GenericVoidPtrTy},
6679 false),
6680 Name),
6681 {NDRange, Kernel, Block}));
6682 }
6683 case Builtin::BI__builtin_store_half:
6684 case Builtin::BI__builtin_store_halff: {
6685 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E);
6686 Value *Val = EmitScalarExpr(E->getArg(0));
6688 Value *HalfVal = Builder.CreateFPTrunc(Val, Builder.getHalfTy());
6689 Builder.CreateStore(HalfVal, Address);
6690 return RValue::get(nullptr);
6691 }
6692 case Builtin::BI__builtin_load_half: {
6694 Value *HalfVal = Builder.CreateLoad(Address);
6695 return RValue::get(Builder.CreateFPExt(HalfVal, Builder.getDoubleTy()));
6696 }
6697 case Builtin::BI__builtin_load_halff: {
6699 Value *HalfVal = Builder.CreateLoad(Address);
6700 return RValue::get(Builder.CreateFPExt(HalfVal, Builder.getFloatTy()));
6701 }
6702 case Builtin::BI__builtin_printf:
6703 case Builtin::BIprintf:
6704 if (getTarget().getTriple().isNVPTX() ||
6705 getTarget().getTriple().isAMDGCN() ||
6706 (getTarget().getTriple().isSPIRV() &&
6707 getTarget().getTriple().getVendor() == Triple::VendorType::AMD)) {
6708 if (getTarget().getTriple().isNVPTX())
6710 if ((getTarget().getTriple().isAMDGCN() ||
6711 getTarget().getTriple().isSPIRV()) &&
6712 getLangOpts().HIP)
6714 }
6715
6716 break;
6717 case Builtin::BI__builtin_canonicalize:
6718 case Builtin::BI__builtin_canonicalizef:
6719 case Builtin::BI__builtin_canonicalizef16:
6720 case Builtin::BI__builtin_canonicalizel:
6721 return RValue::get(
6722 emitBuiltinWithOneOverloadedType<1>(*this, E, Intrinsic::canonicalize));
6723
6724 case Builtin::BI__builtin_thread_pointer: {
6725 if (!getContext().getTargetInfo().isTLSSupported())
6726 CGM.ErrorUnsupported(E, "__builtin_thread_pointer");
6727
6728 return RValue::get(Builder.CreateIntrinsic(llvm::Intrinsic::thread_pointer,
6729 {GlobalsInt8PtrTy}, {}));
6730 }
6731 case Builtin::BI__builtin_os_log_format:
6732 return emitBuiltinOSLogFormat(*E);
6733
6734 case Builtin::BI__xray_customevent: {
6736 return RValue::getIgnored();
6737
6738 if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
6740 return RValue::getIgnored();
6741
6742 if (const auto *XRayAttr = CurFuncDecl->getAttr<XRayInstrumentAttr>())
6743 if (XRayAttr->neverXRayInstrument() && !AlwaysEmitXRayCustomEvents())
6744 return RValue::getIgnored();
6745
6746 Function *F = CGM.getIntrinsic(Intrinsic::xray_customevent);
6747 auto FTy = F->getFunctionType();
6748 auto Arg0 = E->getArg(0);
6749 auto Arg0Val = EmitScalarExpr(Arg0);
6750 auto Arg0Ty = Arg0->getType();
6751 auto PTy0 = FTy->getParamType(0);
6752 if (PTy0 != Arg0Val->getType()) {
6753 if (Arg0Ty->isArrayType())
6754 Arg0Val = EmitArrayToPointerDecay(Arg0).emitRawPointer(*this);
6755 else
6756 Arg0Val = Builder.CreatePointerCast(Arg0Val, PTy0);
6757 }
6758 auto Arg1 = EmitScalarExpr(E->getArg(1));
6759 auto PTy1 = FTy->getParamType(1);
6760 if (PTy1 != Arg1->getType())
6761 Arg1 = Builder.CreateTruncOrBitCast(Arg1, PTy1);
6762 return RValue::get(Builder.CreateCall(F, {Arg0Val, Arg1}));
6763 }
6764
6765 case Builtin::BI__xray_typedevent: {
6766 // TODO: There should be a way to always emit events even if the current
6767 // function is not instrumented. Losing events in a stream can cripple
6768 // a trace.
6770 return RValue::getIgnored();
6771
6772 if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
6774 return RValue::getIgnored();
6775
6776 if (const auto *XRayAttr = CurFuncDecl->getAttr<XRayInstrumentAttr>())
6777 if (XRayAttr->neverXRayInstrument() && !AlwaysEmitXRayTypedEvents())
6778 return RValue::getIgnored();
6779
6780 Function *F = CGM.getIntrinsic(Intrinsic::xray_typedevent);
6781 auto FTy = F->getFunctionType();
6782 auto Arg0 = EmitScalarExpr(E->getArg(0));
6783 auto PTy0 = FTy->getParamType(0);
6784 if (PTy0 != Arg0->getType())
6785 Arg0 = Builder.CreateTruncOrBitCast(Arg0, PTy0);
6786 auto Arg1 = E->getArg(1);
6787 auto Arg1Val = EmitScalarExpr(Arg1);
6788 auto Arg1Ty = Arg1->getType();
6789 auto PTy1 = FTy->getParamType(1);
6790 if (PTy1 != Arg1Val->getType()) {
6791 if (Arg1Ty->isArrayType())
6792 Arg1Val = EmitArrayToPointerDecay(Arg1).emitRawPointer(*this);
6793 else
6794 Arg1Val = Builder.CreatePointerCast(Arg1Val, PTy1);
6795 }
6796 auto Arg2 = EmitScalarExpr(E->getArg(2));
6797 auto PTy2 = FTy->getParamType(2);
6798 if (PTy2 != Arg2->getType())
6799 Arg2 = Builder.CreateTruncOrBitCast(Arg2, PTy2);
6800 return RValue::get(Builder.CreateCall(F, {Arg0, Arg1Val, Arg2}));
6801 }
6802
6803 case Builtin::BI__builtin_ms_va_start:
6804 case Builtin::BI__builtin_ms_va_end:
6805 return RValue::get(
6807 BuiltinID == Builtin::BI__builtin_ms_va_start));
6808
6809 case Builtin::BI__builtin_ms_va_copy: {
6810 // Lower this manually. We can't reliably determine whether or not any
6811 // given va_copy() is for a Win64 va_list from the calling convention
6812 // alone, because it's legal to do this from a System V ABI function.
6813 // With opaque pointer types, we won't have enough information in LLVM
6814 // IR to determine this from the argument types, either. Best to do it
6815 // now, while we have enough information.
6816 Address DestAddr = EmitMSVAListRef(E->getArg(0));
6817 Address SrcAddr = EmitMSVAListRef(E->getArg(1));
6818
6819 DestAddr = DestAddr.withElementType(Int8PtrTy);
6820 SrcAddr = SrcAddr.withElementType(Int8PtrTy);
6821
6822 Value *ArgPtr = Builder.CreateLoad(SrcAddr, "ap.val");
6823 return RValue::get(Builder.CreateStore(ArgPtr, DestAddr));
6824 }
6825
6826 case Builtin::BI__builtin_zos_va_start:
6827 case Builtin::BI__builtin_zos_va_end: {
6828 // The va_list is an array with 2 elements, called curr and next.
6829 // Element curr is set to 0. For builtin_zos_va_start, next is initialized
6830 // with a call to @llvm.va_start. Otherwise, next is passed to @llvm.va_end.
6831 Address VAList = EmitZOSVAListRef(E->getArg(0));
6832 llvm::Type *VAListTy = ConvertType(getContext().getBuiltinZOSVaListType());
6833 VAList = VAList.withElementType(VAListTy);
6834 Address Curr = Builder.CreateConstArrayGEP(VAList, 0, "curr");
6835 Value *Zero = llvm::Constant::getNullValue(VoidPtrTy);
6836 Builder.CreateStore(Zero, Curr);
6837 Address Next = Builder.CreateConstArrayGEP(VAList, 1, "next");
6838 return RValue::get(
6839 EmitVAStartEnd(Next.emitRawPointer(*this),
6840 BuiltinID == Builtin::BI__builtin_zos_va_start));
6841 }
6842 case Builtin::BI__builtin_zos_va_copy: {
6843 // Lower this manually because later can't reliably determine the type.
6844 Address Dest = EmitZOSVAListRef(E->getArg(0));
6845 Address Src = EmitZOSVAListRef(E->getArg(1));
6846 llvm::Type *VAListTy = ConvertType(getContext().getBuiltinZOSVaListType());
6847 uint64_t SizeBytes =
6848 CGM.getDataLayout().getTypeAllocSize(VAListTy).getFixedValue();
6849 Value *SizeVal = llvm::ConstantInt::get(Int64Ty, SizeBytes);
6850 Builder.CreateMemCpy(Dest, Src, SizeVal, false);
6851 return RValue::get(Dest.emitRawPointer(*this));
6852 }
6853
6854 case Builtin::BI__builtin_get_device_side_mangled_name: {
6855 auto Name = CGM.getCUDARuntime().getDeviceSideName(
6856 cast<DeclRefExpr>(E->getArg(0)->IgnoreImpCasts())->getDecl());
6857 auto Str = CGM.GetAddrOfConstantCString(Name, "");
6858 return RValue::get(Str.getPointer());
6859 }
6860 }
6861
6862 // If this is an alias for a lib function (e.g. __builtin_sin), emit
6863 // the call using the normal call path, but using the unmangled
6864 // version of the function name.
6865 const auto &BI = getContext().BuiltinInfo;
6866 if (!shouldEmitBuiltinAsIR(BuiltinID, BI, *this) &&
6867 BI.isLibFunction(BuiltinID))
6868 return emitLibraryCall(*this, FD, E,
6869 CGM.getBuiltinLibFunction(FD, BuiltinID));
6870
6871 // If this is a predefined lib function (e.g. malloc), emit the call
6872 // using exactly the normal call path.
6873 if (BI.isPredefinedLibFunction(BuiltinID))
6874 return emitLibraryCall(*this, FD, E, CGM.getRawFunctionPointer(FD));
6875
6876 // Check that a call to a target specific builtin has the correct target
6877 // features.
6878 // This is down here to avoid non-target specific builtins, however, if
6879 // generic builtins start to require generic target features then we
6880 // can move this up to the beginning of the function.
6881 checkTargetFeatures(E, FD);
6882
6883 if (unsigned VectorWidth = getContext().BuiltinInfo.getRequiredVectorWidth(BuiltinID))
6884 LargestVectorWidth = std::max(LargestVectorWidth, VectorWidth);
6885
6886 // See if we have a target specific intrinsic.
6887 std::string Name = getContext().BuiltinInfo.getName(BuiltinID);
6888 Intrinsic::ID IntrinsicID = Intrinsic::not_intrinsic;
6889 StringRef Prefix =
6890 llvm::Triple::getArchTypePrefix(getTarget().getTriple().getArch());
6891 if (!Prefix.empty()) {
6892 IntrinsicID = Intrinsic::getIntrinsicForClangBuiltin(Prefix.data(), Name);
6893 if (IntrinsicID == Intrinsic::not_intrinsic && Prefix == "spv" &&
6894 getTarget().getTriple().getOS() == llvm::Triple::OSType::AMDHSA)
6895 IntrinsicID = Intrinsic::getIntrinsicForClangBuiltin("amdgcn", Name);
6896 // NOTE we don't need to perform a compatibility flag check here since the
6897 // intrinsics are declared in Builtins*.def via LANGBUILTIN which filter the
6898 // MS builtins via ALL_MS_LANGUAGES and are filtered earlier.
6899 if (IntrinsicID == Intrinsic::not_intrinsic)
6900 IntrinsicID = Intrinsic::getIntrinsicForMSBuiltin(Prefix.data(), Name);
6901 }
6902
6903 if (IntrinsicID != Intrinsic::not_intrinsic) {
6905
6906 // Find out if any arguments are required to be integer constant
6907 // expressions.
6908 unsigned ICEArguments = 0;
6910 getContext().GetBuiltinType(BuiltinID, Error, &ICEArguments);
6911 assert(Error == ASTContext::GE_None && "Should not codegen an error");
6912
6913 Function *F = CGM.getIntrinsic(IntrinsicID);
6914 llvm::FunctionType *FTy = F->getFunctionType();
6915
6916 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
6917 Value *ArgValue = EmitScalarOrConstFoldImmArg(ICEArguments, i, E);
6918 // If the intrinsic arg type is different from the builtin arg type
6919 // we need to do a bit cast.
6920 llvm::Type *PTy = FTy->getParamType(i);
6921 if (PTy != ArgValue->getType()) {
6922 // XXX - vector of pointers?
6923 if (auto *PtrTy = dyn_cast<llvm::PointerType>(PTy)) {
6924 if (PtrTy->getAddressSpace() !=
6925 ArgValue->getType()->getPointerAddressSpace()) {
6926 ArgValue = Builder.CreateAddrSpaceCast(
6927 ArgValue, llvm::PointerType::get(getLLVMContext(),
6928 PtrTy->getAddressSpace()));
6929 }
6930 }
6931
6932 // Cast vector type (e.g., v256i32) to x86_amx, this only happen
6933 // in amx intrinsics.
6934 if (PTy->isX86_AMXTy())
6935 ArgValue = Builder.CreateIntrinsic(Intrinsic::x86_cast_vector_to_tile,
6936 {ArgValue->getType()}, {ArgValue});
6937 else
6938 ArgValue = Builder.CreateBitCast(ArgValue, PTy);
6939 }
6940
6941 Args.push_back(ArgValue);
6942 }
6943
6945
6946 Value *V = Builder.CreateCall(F, Args);
6947 QualType BuiltinRetType = E->getType();
6948
6949 llvm::Type *RetTy = VoidTy;
6950 if (!BuiltinRetType->isVoidType())
6951 RetTy = ConvertType(BuiltinRetType);
6952
6953 if (RetTy != V->getType()) {
6954 // XXX - vector of pointers?
6955 if (auto *PtrTy = dyn_cast<llvm::PointerType>(RetTy)) {
6956 if (PtrTy->getAddressSpace() != V->getType()->getPointerAddressSpace()) {
6957 V = Builder.CreateAddrSpaceCast(
6958 V, llvm::PointerType::get(getLLVMContext(),
6959 PtrTy->getAddressSpace()));
6960 }
6961 }
6962
6963 // Cast x86_amx to vector type (e.g., v256i32), this only happen
6964 // in amx intrinsics.
6965 if (V->getType()->isX86_AMXTy())
6966 V = Builder.CreateIntrinsic(Intrinsic::x86_cast_tile_to_vector, {RetTy},
6967 {V});
6968 else
6969 V = Builder.CreateBitCast(V, RetTy);
6970 }
6971
6972 if (RetTy->isVoidTy())
6973 return RValue::get(nullptr);
6974
6975 return RValue::get(V);
6976 }
6977
6978 // Some target-specific builtins can have aggregate return values, e.g.
6979 // __builtin_arm_mve_vld2q_u32. So if the result is an aggregate, force
6980 // ReturnValue to be non-null, so that the target-specific emission code can
6981 // always just emit into it.
6983 if (EvalKind == TEK_Aggregate && ReturnValue.isNull()) {
6984 Address DestPtr = CreateMemTemp(E->getType(), "agg.tmp");
6985 ReturnValue = ReturnValueSlot(DestPtr, false);
6986 }
6987
6988 // Now see if we can emit a target-specific builtin.
6989 if (Value *V = EmitTargetBuiltinExpr(BuiltinID, E, ReturnValue)) {
6990 switch (EvalKind) {
6991 case TEK_Scalar:
6992 if (V->getType()->isVoidTy())
6993 return RValue::get(nullptr);
6994 return RValue::get(V);
6995 case TEK_Aggregate:
6996 return RValue::getAggregate(ReturnValue.getAddress(),
6997 ReturnValue.isVolatile());
6998 case TEK_Complex:
6999 llvm_unreachable("No current target builtin returns complex");
7000 }
7001 llvm_unreachable("Bad evaluation kind in EmitBuiltinExpr");
7002 }
7003
7004 // EmitHLSLBuiltinExpr will check getLangOpts().HLSL
7005 if (Value *V = EmitHLSLBuiltinExpr(BuiltinID, E, ReturnValue)) {
7006 switch (EvalKind) {
7007 case TEK_Scalar:
7008 if (V->getType()->isVoidTy())
7009 return RValue::get(nullptr);
7010 return RValue::get(V);
7011 case TEK_Aggregate:
7012 return RValue::getAggregate(ReturnValue.getAddress(),
7013 ReturnValue.isVolatile());
7014 case TEK_Complex:
7015 llvm_unreachable("No current hlsl builtin returns complex");
7016 }
7017 llvm_unreachable("Bad evaluation kind in EmitBuiltinExpr");
7018 }
7019
7020 if (getLangOpts().HIPStdPar && getLangOpts().CUDAIsDevice)
7021 return EmitHipStdParUnsupportedBuiltin(this, FD);
7022
7023 ErrorUnsupported(E, "builtin function");
7024
7025 // Unknown builtin, for now just dump it out and return undef.
7026 return GetUndefRValue(E->getType());
7027}
7028
7029namespace {
7030struct BuiltinAlignArgs {
7031 llvm::Value *Src = nullptr;
7032 llvm::Type *SrcType = nullptr;
7033 llvm::Value *Alignment = nullptr;
7034 llvm::Value *Mask = nullptr;
7035 llvm::IntegerType *IntType = nullptr;
7036
7037 BuiltinAlignArgs(const CallExpr *E, CodeGenFunction &CGF) {
7038 QualType AstType = E->getArg(0)->getType();
7039 if (AstType->isArrayType())
7040 Src = CGF.EmitArrayToPointerDecay(E->getArg(0)).emitRawPointer(CGF);
7041 else
7042 Src = CGF.EmitScalarExpr(E->getArg(0));
7043 SrcType = Src->getType();
7044 if (SrcType->isPointerTy()) {
7045 IntType = IntegerType::get(
7046 CGF.getLLVMContext(),
7047 CGF.CGM.getDataLayout().getIndexTypeSizeInBits(SrcType));
7048 } else {
7049 assert(SrcType->isIntegerTy());
7050 IntType = cast<llvm::IntegerType>(SrcType);
7051 }
7052 Alignment = CGF.EmitScalarExpr(E->getArg(1));
7053 Alignment = CGF.Builder.CreateZExtOrTrunc(Alignment, IntType, "alignment");
7054 auto *One = llvm::ConstantInt::get(IntType, 1);
7055 Mask = CGF.Builder.CreateSub(Alignment, One, "mask");
7056 }
7057};
7058} // namespace
7059
7060/// Generate (x & (y-1)) == 0.
7062 BuiltinAlignArgs Args(E, *this);
7063 llvm::Value *SrcAddress = Args.Src;
7064 if (Args.SrcType->isPointerTy())
7065 SrcAddress =
7066 Builder.CreateBitOrPointerCast(Args.Src, Args.IntType, "src_addr");
7067 return RValue::get(Builder.CreateICmpEQ(
7068 Builder.CreateAnd(SrcAddress, Args.Mask, "set_bits"),
7069 llvm::Constant::getNullValue(Args.IntType), "is_aligned"));
7070}
7071
7072/// Generate (x & ~(y-1)) to align down or ((x+(y-1)) & ~(y-1)) to align up.
7073/// Note: For pointer types we can avoid ptrtoint/inttoptr pairs by using the
7074/// llvm.ptrmask intrinsic (with a GEP before in the align_up case).
7076 BuiltinAlignArgs Args(E, *this);
7077 llvm::Value *SrcForMask = Args.Src;
7078 if (AlignUp) {
7079 // When aligning up we have to first add the mask to ensure we go over the
7080 // next alignment value and then align down to the next valid multiple.
7081 // By adding the mask, we ensure that align_up on an already aligned
7082 // value will not change the value.
7083 if (Args.Src->getType()->isPointerTy()) {
7084 if (getLangOpts().PointerOverflowDefined)
7085 SrcForMask =
7086 Builder.CreateGEP(Int8Ty, SrcForMask, Args.Mask, "over_boundary");
7087 else
7088 SrcForMask = EmitCheckedInBoundsGEP(Int8Ty, SrcForMask, Args.Mask,
7089 /*SignedIndices=*/true,
7090 /*isSubtraction=*/false,
7091 E->getExprLoc(), "over_boundary");
7092 } else {
7093 SrcForMask = Builder.CreateAdd(SrcForMask, Args.Mask, "over_boundary");
7094 }
7095 }
7096 // Invert the mask to only clear the lower bits.
7097 llvm::Value *InvertedMask = Builder.CreateNot(Args.Mask, "inverted_mask");
7098 llvm::Value *Result = nullptr;
7099 if (Args.Src->getType()->isPointerTy()) {
7100 Result = Builder.CreateIntrinsic(
7101 Intrinsic::ptrmask, {Args.SrcType, Args.IntType},
7102 {SrcForMask, InvertedMask}, nullptr, "aligned_result");
7103 } else {
7104 Result = Builder.CreateAnd(SrcForMask, InvertedMask, "aligned_result");
7105 }
7106 assert(Result->getType() == Args.SrcType);
7107 return RValue::get(Result);
7108}
#define V(N, I)
static void ClearPadding(CodeGenFunction &CGF, Address Src, const ASTContext::BitInterval &PaddingInterval)
static char bitActionToX86BTCode(BitTest::ActionKind A)
static Value * EmitAtomicCmpXchg128ForMSIntrin(CodeGenFunction &CGF, const CallExpr *E, AtomicOrdering SuccessOrdering)
static void emitSincosBuiltin(CodeGenFunction &CGF, const CallExpr *E, Intrinsic::ID IntrinsicID)
static CanQualType getOSLogArgType(ASTContext &C, int Size)
Get the argument type for arguments to os_log_helper.
static Value * EmitOverflowCheckedAbs(CodeGenFunction &CGF, const CallExpr *E, bool SanitizeOverflow)
static llvm::Value * EmitBitCountExpr(CodeGenFunction &CGF, const Expr *E)
static Value * tryUseTestFPKind(CodeGenFunction &CGF, unsigned BuiltinID, Value *V)
static bool areBOSTypesCompatible(int From, int To)
Checks if using the result of __builtin_object_size(p, From) in place of __builtin_object_size(p,...
static std::pair< llvm::Value *, llvm::Value * > GetCountFieldAndIndex(CodeGenFunction &CGF, const MemberExpr *ME, const FieldDecl *ArrayFD, const FieldDecl *CountFD, const Expr *Idx, llvm::IntegerType *ResType, bool IsSigned)
Value * EmitFromInt(CodeGenFunction &CGF, llvm::Value *V, QualType T, llvm::Type *ResultType)
Value * MakeAtomicCmpXchgValue(CodeGenFunction &CGF, const CallExpr *E, bool ReturnBool, llvm::AtomicOrdering SuccessOrdering, llvm::AtomicOrdering FailureOrdering)
Utility to insert an atomic cmpxchg instruction.
static Value * EmitAtomicIncrementValue(CodeGenFunction &CGF, const CallExpr *E, AtomicOrdering Ordering=AtomicOrdering::SequentiallyConsistent)
static RValue EmitMSVCRTSetJmp(CodeGenFunction &CGF, MSVCSetJmpKind SJKind, const CallExpr *E)
MSVC handles setjmp a bit differently on different platforms.
#define MUTATE_LDBL(func)
static Value * emitMaybeConstrainedFPToIntRoundBuiltin(CodeGenFunction &CGF, const CallExpr *E, unsigned IntrinsicID, unsigned ConstrainedIntrinsicID)
static bool TypeRequiresBuiltinLaunder(CodeGenModule &CGM, QualType Ty)
Determine if the specified type requires laundering by checking if it is a dynamic class type or cont...
static Value * EmitISOVolatileLoad(CodeGenFunction &CGF, const CallExpr *E)
static Value * EmitTargetArchBuiltinExpr(CodeGenFunction *CGF, unsigned BuiltinID, const CallExpr *E, ReturnValueSlot ReturnValue, llvm::Triple::ArchType Arch)
Definition CGBuiltin.cpp:74
static RValue EmitBinaryAtomicPost(CodeGenFunction &CGF, llvm::AtomicRMWInst::BinOp Kind, const CallExpr *E, Instruction::BinaryOps Op, bool Invert=false)
Utility to insert an atomic instruction based Intrinsic::ID and the expression node,...
Value * EmitToInt(CodeGenFunction &CGF, llvm::Value *V, QualType T, llvm::IntegerType *IntType)
Emit the conversions required to turn the given value into an integer of the given size.
static llvm::Value * EmitBitTestIntrinsic(CodeGenFunction &CGF, unsigned BuiltinID, const CallExpr *E)
Emit a _bittest* intrinsic.
static Value * EmitSignBit(CodeGenFunction &CGF, Value *V)
Emit the computation of the sign bit for a floating point value.
static Value * EmitFAbs(CodeGenFunction &CGF, Value *V)
EmitFAbs - Emit a call to @llvm.fabs().
static llvm::Value * EmitPositiveResultOrZero(CodeGenFunction &CGF, llvm::Value *Res, llvm::Value *Index, llvm::IntegerType *ResType, bool IsSigned)
static bool shouldEmitBuiltinAsIR(unsigned BuiltinID, const Builtin::Context &BI, const CodeGenFunction &CGF)
Some builtins do not have library implementation on some targets and are instead emitted as LLVM IRs ...
Definition CGBuiltin.cpp:50
void appendDefaultIntrinsicArgs(SmallVectorImpl< llvm::Value * > &Args, llvm::Function *F)
static bool isSpecialUnsignedMultiplySignedResult(unsigned BuiltinID, WidthAndSignedness Op1Info, WidthAndSignedness Op2Info, WidthAndSignedness ResultInfo)
static llvm::Value * getDefaultBuiltinObjectSizeResult(unsigned Type, llvm::IntegerType *ResType)
static RValue EmitCheckedMixedSignMultiply(CodeGenFunction &CGF, const clang::Expr *Op1, WidthAndSignedness Op1Info, const clang::Expr *Op2, WidthAndSignedness Op2Info, const clang::Expr *ResultArg, QualType ResultQTy, WidthAndSignedness ResultInfo)
Emit a checked mixed-sign multiply.
static unsigned mutateLongDoubleBuiltin(unsigned BuiltinID)
static RValue EmitBinaryAtomic(CodeGenFunction &CGF, llvm::AtomicRMWInst::BinOp Kind, const CallExpr *E)
static void initializeAlloca(CodeGenFunction &CGF, AllocaInst *AI, Value *Size, Align AlignmentInBytes)
static Value * EmitAtomicCmpXchgForMSIntrin(CodeGenFunction &CGF, const CallExpr *E, AtomicOrdering SuccessOrdering=AtomicOrdering::SequentiallyConsistent)
This function should be invoked to emit atomic cmpxchg for Microsoft's _InterlockedCompareExchange* i...
static bool isSpecialMixedSignMultiply(unsigned BuiltinID, WidthAndSignedness Op1Info, WidthAndSignedness Op2Info, WidthAndSignedness ResultInfo)
Determine if a binop is a checked mixed-sign multiply we can specialize.
static Value * emitFrexpBuiltin(CodeGenFunction &CGF, const CallExpr *E, Intrinsic::ID IntrinsicID)
static llvm::Value * emitModfBuiltin(CodeGenFunction &CGF, const CallExpr *E, Intrinsic::ID IntrinsicID)
static Value * EmitNontemporalStore(CodeGenFunction &CGF, const CallExpr *E)
static const FieldDecl * FindFlexibleArrayMemberField(CodeGenFunction &CGF, ASTContext &Ctx, const RecordDecl *RD)
Find a struct's flexible array member.
static Value * EmitISOVolatileStore(CodeGenFunction &CGF, const CallExpr *E)
static RValue EmitHipStdParUnsupportedBuiltin(CodeGenFunction *CGF, const FunctionDecl *FD)
static llvm::Value * EmitX86BitTestIntrinsic(CodeGenFunction &CGF, BitTest BT, const CallExpr *E, Value *BitBase, Value *BitPos)
static RValue EmitCheckedUnsignedMultiplySignedResult(CodeGenFunction &CGF, const clang::Expr *Op1, WidthAndSignedness Op1Info, const clang::Expr *Op2, WidthAndSignedness Op2Info, const clang::Expr *ResultArg, QualType ResultQTy, WidthAndSignedness ResultInfo)
Address CheckAtomicAlignment(CodeGenFunction &CGF, const CallExpr *E)
static Value * EmitNontemporalLoad(CodeGenFunction &CGF, const CallExpr *E)
static llvm::AtomicOrdering getBitTestAtomicOrdering(BitTest::InterlockingKind I)
static bool GetFieldOffset(ASTContext &Ctx, const RecordDecl *RD, const FieldDecl *FD, int64_t &Offset)
Calculate the offset of a struct field.
Value * MakeBinaryAtomicValue(CodeGenFunction &CGF, llvm::AtomicRMWInst::BinOp Kind, const CallExpr *E, AtomicOrdering Ordering)
Utility to insert an atomic instruction based on Intrinsic::ID and the expression node.
llvm::Value * EmitOverflowIntrinsic(CodeGenFunction &CGF, const Intrinsic::ID IntrinsicID, llvm::Value *X, llvm::Value *Y, llvm::Value *&Carry)
Emit a call to llvm.
static Value * EmitAbs(CodeGenFunction &CGF, Value *ArgValue, bool HasNSW)
static Value * EmitAtomicDecrementValue(CodeGenFunction &CGF, const CallExpr *E, AtomicOrdering Ordering=AtomicOrdering::SequentiallyConsistent)
llvm::Value * emitBuiltinWithOneOverloadedType(clang::CodeGen::CodeGenFunction &CGF, const clang::CallExpr *E, unsigned IntrinsicID, llvm::StringRef Name="")
Definition CGBuiltin.h:63
static mlir::Value emitBinaryExpMaybeConstrainedFPBuiltin(CIRGenFunction &cgf, const CallExpr *e, llvm::StringRef intrinsicName, llvm::StringRef constrainedIntrinsicName)
static mlir::Value emitBinaryMaybeConstrainedFPBuiltin(CIRGenFunction &cgf, const CallExpr &e)
static RValue emitUnaryMaybeConstrainedFPBuiltin(CIRGenFunction &cgf, const CallExpr &e)
static bool shouldEmitBuiltinAsIR(unsigned builtinID, const Builtin::Context &bi, const CIRGenFunction &cgf)
static RValue emitTernaryMaybeConstrainedFPBuiltin(CIRGenFunction &cgf, const CallExpr &e)
static RValue emitLibraryCall(CIRGenFunction &cgf, const FunctionDecl *fd, const CallExpr *e, mlir::Operation *calleeValue)
static WidthAndSignedness getIntegerWidthAndSignedness(const clang::ASTContext &astContext, const clang::QualType type)
static struct WidthAndSignedness EncompassingIntegerType(ArrayRef< struct WidthAndSignedness > types)
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Next
The next token in the unwrapped line.
Result
Implement __builtin_bit_cast and related operations.
#define X(type, name)
Definition Value.h:97
static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target)
static StringRef getTriple(const Command &Job)
SanitizerHandler
static QualType getPointeeType(const MemRegion *R)
__DEVICE__ float modf(float __x, float *__iptr)
__DEVICE__ double nan(const char *)
APSInt & getInt()
Definition APValue.h:511
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:239
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getIntWidth(QualType T) const
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
CanQualType VoidPtrTy
IdentifierTable & Idents
Definition ASTContext.h:850
Builtin::Context & BuiltinInfo
Definition ASTContext.h:852
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
llvm::ArrayRef< BitInterval > getPaddingIntervals(QualType Ty) const
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:969
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
unsigned getTargetAddressSpace(LangAS AS) const
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
@ GE_None
No error.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
QualType getElementType() const
Definition TypeBase.h:3831
static std::unique_ptr< AtomicScopeModel > create(AtomicScopeModelKind K)
Create an atomic scope model by AtomicScopeModelKind.
Definition SyncScope.h:299
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:236
bool shouldGenerateFPMathIntrinsic(unsigned BuiltinID, llvm::Triple Trip, std::optional< bool > ErrnoOverwritten, bool MathErrnoEnabled, bool HasOptNoneAttr, bool IsOptimizationEnabled) const
Determine whether we can generate LLVM intrinsics for the given builtin ID, based on whether it has s...
Definition Builtins.cpp:242
std::string getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition Builtins.cpp:94
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2987
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3191
bool hasStoredFPFeatures() const
Definition Expr.h:3146
SourceLocation getBeginLoc() const
Definition Expr.h:3321
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3170
Expr * getCallee()
Definition Expr.h:3134
FPOptionsOverride getFPFeatures() const
Definition Expr.h:3286
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3178
arg_range arguments()
Definition Expr.h:3239
CastKind getCastKind() const
Definition Expr.h:3764
Expr * getSubExpr()
Definition Expr.h:3770
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
CharUnits alignmentAtOffset(CharUnits offset) const
Given that this is a non-zero alignment value, what is the alignment at the given offset?
Definition CharUnits.h:175
bool isZero() const
Test whether the quantity equals zero.
Definition CharUnits.h:101
llvm::Align getAsAlign() const
Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit bytes.
Definition CharUnits.h:157
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:153
static CharUnits One()
Construct a CharUnits quantity of one.
Definition CharUnits.h:55
static CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:58
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition Address.h:128
llvm::Value * getBasePointer() const
Definition Address.h:198
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition Address.h:253
CharUnits getAlignment() const
Definition Address.h:194
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition Address.h:209
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Definition Address.h:276
llvm::PointerType * getType() const
Return the type of the pointer value.
Definition Address.h:204
A scoped helper to set the current debug location to the specified location or preferred location of ...
static ApplyDebugLocation CreateArtificial(CodeGenFunction &CGF)
Apply TemporaryLocation if it is valid.
static ApplyDebugLocation CreateEmpty(CodeGenFunction &CGF)
Set the IRBuilder to not attach debug locations.
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition CGBuilder.h:146
llvm::StoreInst * CreateAlignedStore(llvm::Value *Val, llvm::Value *Addr, CharUnits Align, bool IsVolatile=false)
Definition CGBuilder.h:153
Address CreateGEP(CodeGenFunction &CGF, Address Addr, llvm::Value *Index, const llvm::Twine &Name="")
Definition CGBuilder.h:302
llvm::AtomicRMWInst * CreateAtomicRMW(llvm::AtomicRMWInst::BinOp Op, Address Addr, llvm::Value *Val, llvm::AtomicOrdering Ordering, llvm::SyncScope::ID SSID=llvm::SyncScope::System)
Definition CGBuilder.h:190
llvm::CallInst * CreateMemSet(Address Dest, llvm::Value *Value, llvm::Value *Size, bool IsVolatile=false)
Definition CGBuilder.h:430
llvm::AtomicCmpXchgInst * CreateAtomicCmpXchg(Address Addr, llvm::Value *Cmp, llvm::Value *New, llvm::AtomicOrdering SuccessOrdering, llvm::AtomicOrdering FailureOrdering, llvm::SyncScope::ID SSID=llvm::SyncScope::System)
Definition CGBuilder.h:179
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition CGBuilder.h:118
llvm::LoadInst * CreateAlignedLoad(llvm::Type *Ty, llvm::Value *Addr, CharUnits Align, const llvm::Twine &Name="")
Definition CGBuilder.h:138
Address CreateInBoundsGEP(Address Addr, ArrayRef< llvm::Value * > IdxList, llvm::Type *ElementType, CharUnits Align, const Twine &Name="")
Definition CGBuilder.h:356
All available information about a concrete callee.
Definition CGCall.h:66
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition CGCall.h:140
llvm::DILocation * CreateTrapFailureMessageFor(llvm::DebugLoc TrapLocation, StringRef Category, StringRef FailureMsg)
Create a debug location from TrapLocation that adds an artificial inline frame where the frame name i...
CGFunctionInfo - Class to encapsulate the information about a function definition.
llvm::Value * getPipeElemAlign(const Expr *PipeArg)
llvm::Value * getPipeElemSize(const Expr *PipeArg)
llvm::StructType * getLLVMType() const
Return the "complete object" LLVM type associated with this record.
CallArgList - Type for representing both the value and type of arguments in a call.
Definition CGCall.h:277
void add(RValue rvalue, QualType type)
Definition CGCall.h:305
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
RValue EmitAMDGPUDevicePrintfCallExpr(const CallExpr *E)
llvm::Value * GetVTablePtr(Address This, llvm::Type *VTableTy, const CXXRecordDecl *VTableClass, VTableAuthMode AuthMode=VTableAuthMode::Authenticate)
GetVTablePtr - Return the Value of the vtable pointer member pointed to by This.
Definition CGClass.cpp:2721
RValue EmitNVPTXDevicePrintfCallExpr(const CallExpr *E)
llvm::Value * EmitAVRBuiltinExpr(unsigned BuiltinID, const CallExpr *E)
Definition AVR.cpp:22
llvm::CallInst * EmitTrapCall(llvm::Intrinsic::ID IntrID, bool EnsureInsertPoint=true)
Emit a call to trap or debugtrap.
Definition CGExpr.cpp:4736
RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID)
llvm::Value * performAddrSpaceCast(llvm::Value *Src, llvm::Type *DestTy)
llvm::Value * EmitScalarOrConstFoldImmArg(unsigned ICEArguments, unsigned Idx, const CallExpr *E)
SanitizerSet SanOpts
Sanitizers enabled for this function.
void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl)
llvm::Value * GetCountedByFieldExprGEP(const Expr *Base, const FieldDecl *FD, const FieldDecl *CountDecl)
Definition CGExpr.cpp:1228
llvm::Type * ConvertType(QualType T)
void addInstToNewSourceAtom(llvm::Instruction *KeyInstruction, llvm::Value *Backup)
Add KeyInstruction and an optional Backup instruction to a new atom group (See ApplyAtomGroup for mor...
BuiltinCheckKind
Specifies which type of sanitizer check to apply when handling a particular builtin.
llvm::Value * EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E)
Definition SystemZ.cpp:86
llvm::CallBase * EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee, ArrayRef< llvm::Value * > args, const Twine &name="")
Emits a call or invoke instruction to the given runtime function.
Definition CGCall.cpp:5510
llvm::Value * EmitSEHAbnormalTermination()
RValue emitStdcFirstBit(const CallExpr *E, llvm::Intrinsic::ID IntID, bool InvertArg)
llvm::Value * EmitARCRetain(QualType type, llvm::Value *value)
Produce the code to do a retain.
Definition CGObjC.cpp:2347
CleanupKind getARCCleanupKind()
Retrieves the default cleanup kind for an ARC cleanup.
llvm::Value * EmitVAStartEnd(llvm::Value *ArgValue, bool IsStart)
Emits a call to an LLVM variable-argument intrinsic, either llvm.va_start or llvm....
RValue emitStdcBitWidthMinus(const CallExpr *E, llvm::Intrinsic::ID IntID, bool IsPop)
llvm::Value * EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E)
Definition AMDGPU.cpp:559
llvm::Constant * EmitCheckSourceLocation(SourceLocation Loc)
Emit a description of a source location in a format suitable for passing to a runtime sanitizer handl...
Definition CGExpr.cpp:4171
void SetSqrtFPAccuracy(llvm::Value *Val)
Set the minimum required accuracy of the given sqrt operation based on CodeGenOpts.
Definition CGExpr.cpp:7440
RValue emitBuiltinOSLogFormat(const CallExpr &E)
Emit IR for __builtin_os_log_format.
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
llvm::Function * generateBuiltinOSLogHelperFunction(const analyze_os_log::OSLogBufferLayout &Layout, CharUnits BufferAlignment)
const LangOptions & getLangOpts() const
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
Address makeNaturalAddressForPointer(llvm::Value *Ptr, QualType T, CharUnits Alignment=CharUnits::Zero(), bool ForPointeeType=false, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
Construct an address with the natural alignment of T.
TypeCheckKind
Situations in which we might emit a check for the suitability of a pointer or glvalue.
@ TCK_Store
Checking the destination of a store. Must be suitably sized and aligned.
@ TCK_Load
Checking the operand of a load. Must be suitably sized and aligned.
llvm::Value * EmitRISCVBuiltinExpr(unsigned BuiltinID, const CallExpr *E, ReturnValueSlot ReturnValue)
Definition RISCV.cpp:1079
llvm::Value * EmitCheckedArgForBuiltin(const Expr *E, BuiltinCheckKind Kind)
Emits an argument for a call to a builtin.
llvm::Constant * EmitCheckTypeDescriptor(QualType T)
Emit a description of a type in a format suitable for passing to a runtime sanitizer handler.
Definition CGExpr.cpp:4061
void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc, AbstractCallee AC, unsigned ParmNum)
Create a check for a function parameter that may potentially be declared as non-null.
Definition CGCall.cpp:4961
const TargetInfo & getTarget() const
RValue emitRotate(const CallExpr *E, bool IsRotateRight)
llvm::Value * EmitAnnotationCall(llvm::Function *AnnotationFn, llvm::Value *AnnotatedVal, StringRef AnnotationStr, SourceLocation Location, const AnnotateAttr *Attr)
Emit an annotation call (intrinsic).
llvm::Value * EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E, ReturnValueSlot ReturnValue, llvm::Triple::ArchType Arch)
Definition ARM.cpp:2162
CGCallee EmitCallee(const Expr *E)
Definition CGExpr.cpp:6779
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
Definition CGExpr.cpp:261
void pushCleanupAfterFullExpr(CleanupKind Kind, As... A)
Queue a cleanup to be pushed after finishing the current full-expression, potentially with an active ...
llvm::Value * EmitBPFBuiltinExpr(unsigned BuiltinID, const CallExpr *E)
Definition ARM.cpp:7224
bool AlwaysEmitXRayCustomEvents() const
AlwaysEmitXRayCustomEvents - Return true if we must unconditionally emit XRay custom event handling c...
void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn, const CGFunctionInfo &FnInfo, const FunctionArgList &Args, SourceLocation Loc=SourceLocation(), SourceLocation StartLoc=SourceLocation())
Emit code for the start of a function.
LValue EmitAggExprToLValue(const Expr *E)
EmitAggExprToLValue - Emit the computation of the specified expression of aggregate type into a tempo...
llvm::Value * EvaluateExprAsBool(const Expr *E)
EvaluateExprAsBool - Perform the usual unary conversions on the specified expression and compare the ...
Definition CGExpr.cpp:242
llvm::Value * EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E)
Definition PPC.cpp:205
void EmitCheck(ArrayRef< std::pair< llvm::Value *, SanitizerKind::SanitizerOrdinal > > Checked, SanitizerHandler Check, ArrayRef< llvm::Constant * > StaticArgs, ArrayRef< llvm::Value * > DynamicArgs, const TrapReason *TR=nullptr)
Create a basic block that will either trap or call a handler function in the UBSan runtime with the p...
Definition CGExpr.cpp:4319
bool AlwaysEmitXRayTypedEvents() const
AlwaysEmitXRayTypedEvents - Return true if clang must unconditionally emit XRay typed event handling ...
llvm::Value * getTypeSize(QualType Ty)
Returns calculated size of the specified type.
bool EmitLifetimeStart(llvm::Value *Addr)
Emit a lifetime.begin marker if some criteria are satisfied.
Definition CGDecl.cpp:1363
llvm::MDNode * buildAllocToken(QualType AllocType)
Build metadata used by the AllocToken instrumentation.
Definition CGExpr.cpp:1350
llvm::Value * EmitToMemory(llvm::Value *Value, QualType Ty)
EmitToMemory - Change a scalar value from its value representation to its in-memory representation.
Definition CGExpr.cpp:2271
ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal=false, bool IgnoreImag=false)
EmitComplexExpr - Emit the computation of the specified expression of complex type,...
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::CallBase **CallOrInvoke, bool IsMustTail, SourceLocation Loc, bool IsVirtualFunctionPointerThunk=false)
EmitCall - Generate a call of the given function, expecting the given result type,...
Definition CGCall.cpp:5666
const TargetCodeGenInfo & getTargetHooks() const
RValue EmitBuiltinAlignTo(const CallExpr *E, bool AlignUp)
Emit IR for __builtin_align_up/__builtin_align_down.
void EmitLifetimeEnd(llvm::Value *Addr)
Definition CGDecl.cpp:1375
RawAddress CreateMemTempWithoutCast(QualType T, const Twine &Name="tmp")
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen without...
Definition CGExpr.cpp:234
llvm::Value * EmitWebAssemblyBuiltinExpr(unsigned BuiltinID, const CallExpr *E)
bool IsInPreservedAIRegion
True if CodeGen currently emits code inside presereved access index region.
llvm::FenceInst * emitAtomicFence(llvm::AtomicOrdering Order, llvm::SyncScope::ID SSID=llvm::SyncScope::System)
Emit a fence instruction, applying relevant target-specific metadata when applicable.
llvm::Value * EmitDirectXBuiltinExpr(unsigned BuiltinID, const CallExpr *E)
Definition DirectX.cpp:22
llvm::Value * EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E, llvm::Triple::ArchType Arch)
Definition ARM.cpp:4470
llvm::Value * EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID, const CallExpr *E)
llvm::Value * EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty, SourceLocation Loc, AlignmentSource Source=AlignmentSource::Type, bool isNontemporal=false)
EmitLoadOfScalar - Load a scalar value from an address, taking care to appropriately convert from the...
const Decl * CurFuncDecl
CurFuncDecl - Holds the Decl for the current outermost non-closure context.
Address EmitArrayToPointerDecay(const Expr *Array, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
Definition CGExpr.cpp:4773
void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray)
Definition CGDecl.cpp:2415
llvm::Value * EmitSPIRVBuiltinExpr(unsigned BuiltinID, const CallExpr *E)
Definition SPIR.cpp:22
RValue EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID, const CallExpr *E, ReturnValueSlot ReturnValue)
Address EmitVAListRef(const Expr *E)
RValue GetUndefRValue(QualType Ty)
GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
Definition CGExpr.cpp:1642
RValue EmitBuiltinIsAligned(const CallExpr *E)
Emit IR for __builtin_is_aligned.
RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type, const CallExpr *TheCallExpr, bool IsDelete)
llvm::CallInst * EmitRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
llvm::Value * EmitHexagonBuiltinExpr(unsigned BuiltinID, const CallExpr *E)
Definition Hexagon.cpp:77
Address EmitZOSVAListRef(const Expr *E)
Emit a "reference" to a __builtin_zos_va_list; this is always the address of the expression,...
CodeGenTypes & getTypes() const
RValue emitStdcCountIntrinsic(const CallExpr *E, llvm::Intrinsic::ID IntID, bool InvertArg, bool IsPop=false)
llvm::Value * EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E)
Definition X86.cpp:784
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, LValue LV, QualType Type, SanitizerSet SkippedChecks=SanitizerSet(), llvm::Value *ArraySize=nullptr)
Address EmitPointerWithAlignment(const Expr *Addr, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitPointerWithAlignment - Given an expression with a pointer type, emit the value and compute our be...
Definition CGExpr.cpp:1625
RawAddress CreateMemTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen and cas...
Definition CGExpr.cpp:198
llvm::Value * EmitCheckedInBoundsGEP(llvm::Type *ElemTy, llvm::Value *Ptr, ArrayRef< llvm::Value * > IdxList, bool SignedIndices, bool IsSubtraction, SourceLocation Loc, const Twine &Name="")
Same as IRBuilder::CreateInBoundsGEP, but additionally emits a check to detect undefined behavior whe...
Address EmitMSVAListRef(const Expr *E)
Emit a "reference" to a __builtin_ms_va_list; this is always the value of the expression,...
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
void EmitTrapCheck(llvm::Value *Checked, SanitizerHandler CheckHandlerID, bool NoMerge=false, const TrapReason *TR=nullptr)
Create a basic block that will call the trap intrinsic, and emit a conditional branch to it,...
Definition CGExpr.cpp:4658
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
llvm::Value * EmitFromMemory(llvm::Value *Value, QualType Ty)
EmitFromMemory - Change a scalar value from its memory representation to its value representation.
Definition CGExpr.cpp:2305
llvm::Value * EmitCheckedArgForAssume(const Expr *E)
Emits an argument for a call to a __builtin_assume.
llvm::Value * EmitLoadOfCountedByField(const Expr *Base, const FieldDecl *FD, const FieldDecl *CountDecl)
Build an expression accessing the "counted_by" field.
Definition CGExpr.cpp:1281
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
llvm::Value * EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E)
Definition NVPTX.cpp:446
void EmitUnreachable(SourceLocation Loc)
Emit a reached-unreachable diagnostic if Loc is valid and runtime checking is enabled.
Definition CGExpr.cpp:4646
void ErrorUnsupported(const Stmt *S, const char *Type)
ErrorUnsupported - Print out an error that codegen doesn't support the specified stmt yet.
std::pair< llvm::Value *, llvm::Value * > ComplexPairTy
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
LValue EmitLValue(const Expr *E, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitLValue - Emit code to compute a designator that specifies the location of the expression.
Definition CGExpr.cpp:1741
bool ShouldXRayInstrumentFunction() const
ShouldXRayInstrument - Return true if the current function should be instrumented with XRay nop sleds...
llvm::LLVMContext & getLLVMContext()
llvm::Value * EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E, ReturnValueSlot ReturnValue)
EmitTargetBuiltinExpr - Emit the given builtin call.
void emitAlignmentAssumption(llvm::Value *PtrValue, QualType Ty, SourceLocation Loc, SourceLocation AssumptionLoc, llvm::Value *Alignment, llvm::Value *OffsetValue=nullptr)
llvm::Value * EmitHLSLBuiltinExpr(unsigned BuiltinID, const CallExpr *E, ReturnValueSlot ReturnValue)
void EmitARCIntrinsicUse(ArrayRef< llvm::Value * > values)
Given a number of pointers, inform the optimizer that they're being intrinsically used up until this ...
Definition CGObjC.cpp:2186
void EmitStoreOfScalar(llvm::Value *Value, Address Addr, bool Volatile, QualType Ty, AlignmentSource Source=AlignmentSource::Type, bool isInit=false, bool isNontemporal=false)
EmitStoreOfScalar - Store a scalar value to an address, taking care to appropriately convert from the...
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition CGStmt.cpp:654
This class organizes the cross-function state that is used while generating LLVM code.
llvm::Module & getModule() const
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false, bool AssumeConvergent=false)
Create or return a runtime function declaration with the specified type and name.
llvm::Constant * getBuiltinLibFunction(const FunctionDecl *FD, unsigned BuiltinID)
Given a builtin id for a function like "__builtin_fabsf", return a Function* for "fabsf".
DiagnosticsEngine & getDiags() const
const LangOptions & getLangOpts() const
const TargetInfo & getTarget() const
const llvm::DataLayout & getDataLayout() const
const llvm::Triple & getTriple() const
ASTContext & getContext() const
const TargetCodeGenInfo & getTargetCodeGenInfo()
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
llvm::LLVMContext & getLLVMContext()
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys={})
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition CGCall.cpp:2064
const CGRecordLayout & getCGRecordLayout(const RecordDecl *)
getCGRecordLayout - Return record layout info for the given record decl.
llvm::Constant * emitAbstract(const Expr *E, QualType T)
Emit the result of the given expression as an abstract constant, asserting that it succeeded.
FunctionArgList - Type for representing both the decl and type of parameters to a function.
Definition CGCall.h:378
LValue - This represents an lvalue references.
Definition CGValue.h:183
llvm::Value * getPointer(CodeGenFunction &CGF) const
Address getAddress() const
Definition CGValue.h:373
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition CGValue.h:42
static RValue getIgnored()
Definition CGValue.h:94
static RValue get(llvm::Value *V)
Definition CGValue.h:99
static RValue getAggregate(Address addr, bool isVolatile=false)
Convert an Address to an RValue.
Definition CGValue.h:126
static RValue getComplex(llvm::Value *V1, llvm::Value *V2)
Definition CGValue.h:109
An abstract representation of an aligned address.
Definition Address.h:42
ReturnValueSlot - Contains the address where the return value of a function can be stored,...
Definition CGCall.h:384
virtual bool supportsLibCall() const
supportsLibCall - Query to whether or not target supports all lib calls.
Definition TargetInfo.h:109
virtual llvm::Value * encodeReturnAddress(CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const
Performs the code-generation required to convert the address of an instruction into a return address ...
Definition TargetInfo.h:207
virtual llvm::Value * decodeReturnAddress(CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const
Performs the code-generation required to convert a return address as stored by the system into the ac...
Definition TargetInfo.h:197
virtual int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const
Determines the DWARF register number for the stack pointer, for exception-handling purposes.
Definition TargetInfo.h:179
virtual llvm::Value * testFPKind(llvm::Value *V, unsigned BuiltinID, CGBuilderTy &Builder, CodeGenModule &CGM) const
Performs a target specific test of a floating point value for things like IsNaN, Infinity,...
Definition TargetInfo.h:216
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3361
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4489
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition TypeBase.h:3508
BoundsAttrKind getKind() const
Definition TypeBase.h:3547
static bool isFlexibleArrayMemberLike(const ASTContext &Context, const Decl *D, QualType Ty, LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel, bool IgnoreTemplateOrMacroSubstitution)
Whether it resembles a flexible array member.
Definition DeclBase.cpp:463
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
bool hasAttr() const
Definition DeclBase.h:585
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:232
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
This represents one expression.
Definition Expr.h:113
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parentheses and casts which do not change the value (including ptr->int casts of the sa...
Definition Expr.cpp:3150
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3128
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3123
bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFloat - Return true if this is a constant which we can fold and convert to a floating point...
bool isPRValue() const
Definition Expr.h:286
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:855
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3722
std::optional< std::string > tryEvaluateString(ASTContext &Ctx) const
If the current Expr can be evaluated to a pointer to a null-terminated constant string,...
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3103
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition Expr.cpp:4104
std::optional< uint64_t > tryEvaluateObjectSize(const ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:145
const ValueDecl * getAsBuiltinConstantDeclRef(const ASTContext &Context) const
If this expression is an unambiguous reference to a single declaration, in the style of __builtin_fun...
Definition Expr.cpp:232
Represents difference between two FPOptions values.
LangOptions::FPExceptionModeKind getExceptionMode() const
Represents a member of a struct/union/class.
Definition Decl.h:3295
const FieldDecl * findCountedByField() const
Find the FieldDecl specified in a FAM's "counted_by" attribute.
Definition Decl.cpp:4920
Represents a function declaration or definition.
Definition Decl.h:2059
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2928
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5415
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:60
const Decl * getDecl() const
Definition GlobalDecl.h:115
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
static ImplicitParamDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
Definition Decl.cpp:5673
@ FPE_Ignore
Assume that floating-point exceptions are masked.
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3408
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3491
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:302
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition Decl.h:318
PipeType - OpenCL20.
Definition TypeBase.h:8274
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3402
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8529
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8571
bool requiresBuiltinLaunder(const ASTContext &Context) const
Returns true if this type requires laundering by checking if it is a dynamic class type,...
Definition Type.cpp:5808
Represents a struct/union/class.
Definition Decl.h:4460
field_range fields() const
Definition Decl.h:4663
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
Encodes a location in the source.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
bool isUnion() const
Definition Decl.h:4063
Exposes information about the current target.
Definition TargetInfo.h:226
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
bool isBigEndian() const
virtual bool checkArithmeticFenceSupported() const
Controls if __arithmetic_fence is supported in the targeted backend.
unsigned getSuitableAlign() const
Return the alignment that is the largest alignment ever used for any scalar/SIMD data type on the tar...
Definition TargetInfo.h:741
virtual std::string_view getClobbers() const =0
Returns a string of target-specific clobbers, in LLVM format.
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isBlockPointerType() const
Definition TypeBase.h:8702
bool isVoidType() const
Definition TypeBase.h:9067
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2390
bool isArrayType() const
Definition TypeBase.h:8781
bool isCountAttributedType() const
Definition Type.cpp:872
bool isPointerType() const
Definition TypeBase.h:8682
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9111
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9361
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition Type.cpp:2078
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:883
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2434
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2653
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9294
QualType getType() const
Definition Decl.h:724
QualType getType() const
Definition Value.cpp:238
Represents a GCC generic vector type.
Definition TypeBase.h:4272
QualType getElementType() const
Definition TypeBase.h:4286
SmallVector< OSLogBufferItem, 4 > Items
Definition OSLog.h:113
unsigned char getNumArgsByte() const
Definition OSLog.h:148
unsigned char getSummaryByte() const
Definition OSLog.h:139
Defines the clang::TargetInfo interface.
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
Definition CGValue.h:155
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
Definition CGValue.h:146
llvm::Constant * initializationPatternFor(CodeGenModule &, llvm::Type *)
TypeEvaluationKind
The kind of evaluation to perform on values of a particular type.
@ EHCleanup
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
constexpr XRayInstrMask Typed
Definition XRayInstr.h:42
constexpr XRayInstrMask Custom
Definition XRayInstr.h:41
bool computeOSLogBufferLayout(clang::ASTContext &Ctx, const clang::CallExpr *E, OSLogBufferLayout &layout)
Definition OSLog.cpp:192
bool Mul(InterpState &S, CodePtr OpPC)
Definition Interp.h:487
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
const Expr * findStructFieldAccess(const Expr *E, const Expr **OutArrayIndex=nullptr, QualType *OutArrayElementTy=nullptr)
Walk E through parens, implicit casts, unary &/*, array subscripts and comma operators to find the he...
Definition Expr.cpp:5801
@ Success
Annotation was successful.
Definition Parser.h:65
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Asm
Assembly: we accept this only so that we can preprocess it.
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
SyncScope
Defines sync scope values used internally by clang.
Definition SyncScope.h:43
llvm::StringRef getAsString(SyncScope S)
Definition SyncScope.h:63
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Other
Other implicit parameter.
Definition Decl.h:1775
long int64_t
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
int32_t uint32_t
int32_t uint32_t uint32_t __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 uint8_t
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:666
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:668
void clear(SanitizerMask K=SanitizerKind::All)
Disable the sanitizers specified in K.
Definition Sanitizers.h:195
void set(SanitizerMask K, bool Value)
Enable or disable a certain (single) sanitizer.
Definition Sanitizers.h:187
#define sinh(__x)
Definition tgmath.h:373
#define asin(__x)
Definition tgmath.h:112
#define scalbln(__x, __y)
Definition tgmath.h:1182
#define sqrt(__x)
Definition tgmath.h:520
#define acos(__x)
Definition tgmath.h:83
#define fmin(__x, __y)
Definition tgmath.h:780
#define exp(__x)
Definition tgmath.h:431
#define ilogb(__x)
Definition tgmath.h:851
#define copysign(__x, __y)
Definition tgmath.h:618
#define erf(__x)
Definition tgmath.h:636
#define atanh(__x)
Definition tgmath.h:228
#define remquo(__x, __y, __z)
Definition tgmath.h:1111
#define nextafter(__x, __y)
Definition tgmath.h:1055
#define frexp(__x, __y)
Definition tgmath.h:816
#define asinh(__x)
Definition tgmath.h:199
#define erfc(__x)
Definition tgmath.h:653
#define atan2(__x, __y)
Definition tgmath.h:566
#define nexttoward(__x, __y)
Definition tgmath.h:1073
#define hypot(__x, __y)
Definition tgmath.h:833
#define exp2(__x)
Definition tgmath.h:670
#define sin(__x)
Definition tgmath.h:286
#define cbrt(__x)
Definition tgmath.h:584
#define log2(__x)
Definition tgmath.h:970
#define llround(__x)
Definition tgmath.h:919
#define cosh(__x)
Definition tgmath.h:344
#define trunc(__x)
Definition tgmath.h:1216
#define fmax(__x, __y)
Definition tgmath.h:762
#define ldexp(__x, __y)
Definition tgmath.h:868
#define acosh(__x)
Definition tgmath.h:170
#define tgamma(__x)
Definition tgmath.h:1199
#define scalbn(__x, __y)
Definition tgmath.h:1165
#define round(__x)
Definition tgmath.h:1148
#define fmod(__x, __y)
Definition tgmath.h:798
#define llrint(__x)
Definition tgmath.h:902
#define tan(__x)
Definition tgmath.h:315
#define cos(__x)
Definition tgmath.h:257
#define log10(__x)
Definition tgmath.h:936
#define fabs(__x)
Definition tgmath.h:549
#define pow(__x, __y)
Definition tgmath.h:490
#define log1p(__x)
Definition tgmath.h:953
#define rint(__x)
Definition tgmath.h:1131
#define expm1(__x)
Definition tgmath.h:687
#define remainder(__x, __y)
Definition tgmath.h:1090
#define fdim(__x, __y)
Definition tgmath.h:704
#define lgamma(__x)
Definition tgmath.h:885
#define tanh(__x)
Definition tgmath.h:402
#define lrint(__x)
Definition tgmath.h:1004
#define atan(__x)
Definition tgmath.h:141
#define floor(__x)
Definition tgmath.h:722
#define ceil(__x)
Definition tgmath.h:601
#define log(__x)
Definition tgmath.h:460
#define logb(__x)
Definition tgmath.h:987
#define nearbyint(__x)
Definition tgmath.h:1038
#define lround(__x)
Definition tgmath.h:1021
#define fma(__x, __y, __z)
Definition tgmath.h:742