Bug Summary

File:build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/CodeGen/CGBuiltin.cpp
Warning:line 12306, column 22
Division by zero

Annotated Source Code

Press '?' to see keyboard shortcuts

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