Debian Codegraph @

clang/lib/CodeGen/CGBuiltin.cpp

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