Bug Summary

File:src/gnu/usr.bin/clang/libclangCodeGen/../../../llvm/clang/lib/CodeGen/CGBuiltin.cpp
Warning:line 15278, column 24
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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