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 "clang/Frontend/FrontendDiagnostic.h" |
32 | #include "llvm/ADT/APFloat.h" |
33 | #include "llvm/ADT/APInt.h" |
34 | #include "llvm/ADT/SmallPtrSet.h" |
35 | #include "llvm/ADT/StringExtras.h" |
36 | #include "llvm/Analysis/ValueTracking.h" |
37 | #include "llvm/IR/DataLayout.h" |
38 | #include "llvm/IR/InlineAsm.h" |
39 | #include "llvm/IR/Intrinsics.h" |
40 | #include "llvm/IR/IntrinsicsAArch64.h" |
41 | #include "llvm/IR/IntrinsicsAMDGPU.h" |
42 | #include "llvm/IR/IntrinsicsARM.h" |
43 | #include "llvm/IR/IntrinsicsBPF.h" |
44 | #include "llvm/IR/IntrinsicsHexagon.h" |
45 | #include "llvm/IR/IntrinsicsLoongArch.h" |
46 | #include "llvm/IR/IntrinsicsNVPTX.h" |
47 | #include "llvm/IR/IntrinsicsPowerPC.h" |
48 | #include "llvm/IR/IntrinsicsR600.h" |
49 | #include "llvm/IR/IntrinsicsRISCV.h" |
50 | #include "llvm/IR/IntrinsicsS390.h" |
51 | #include "llvm/IR/IntrinsicsVE.h" |
52 | #include "llvm/IR/IntrinsicsWebAssembly.h" |
53 | #include "llvm/IR/IntrinsicsX86.h" |
54 | #include "llvm/IR/MDBuilder.h" |
55 | #include "llvm/IR/MatrixBuilder.h" |
56 | #include "llvm/Support/ConvertUTF.h" |
57 | #include "llvm/Support/ScopedPrinter.h" |
58 | #include "llvm/TargetParser/AArch64TargetParser.h" |
59 | #include "llvm/TargetParser/X86TargetParser.h" |
60 | #include <optional> |
61 | #include <sstream> |
62 | |
63 | using namespace clang; |
64 | using namespace CodeGen; |
65 | using namespace llvm; |
66 | |
67 | static void initializeAlloca(CodeGenFunction &CGF, AllocaInst *AI, Value *Size, |
68 | Align AlignmentInBytes) { |
69 | ConstantInt *Byte; |
70 | switch (CGF.getLangOpts().getTrivialAutoVarInit()) { |
71 | case LangOptions::TrivialAutoVarInitKind::Uninitialized: |
72 | // Nothing to initialize. |
73 | return; |
74 | case LangOptions::TrivialAutoVarInitKind::Zero: |
75 | Byte = CGF.Builder.getInt8(C: 0x00); |
76 | break; |
77 | case LangOptions::TrivialAutoVarInitKind::Pattern: { |
78 | llvm::Type *Int8 = llvm::IntegerType::getInt8Ty(C&: CGF.CGM.getLLVMContext()); |
79 | Byte = llvm::dyn_cast<llvm::ConstantInt>( |
80 | Val: initializationPatternFor(CGF.CGM, Int8)); |
81 | break; |
82 | } |
83 | } |
84 | if (CGF.CGM.stopAutoInit()) |
85 | return; |
86 | auto *I = CGF.Builder.CreateMemSet(Ptr: AI, Val: Byte, Size, Align: AlignmentInBytes); |
87 | I->addAnnotationMetadata(Annotation: "auto-init" ); |
88 | } |
89 | |
90 | /// getBuiltinLibFunction - Given a builtin id for a function like |
91 | /// "__builtin_fabsf", return a Function* for "fabsf". |
92 | llvm::Constant *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD, |
93 | unsigned BuiltinID) { |
94 | assert(Context.BuiltinInfo.isLibFunction(BuiltinID)); |
95 | |
96 | // Get the name, skip over the __builtin_ prefix (if necessary). |
97 | StringRef Name; |
98 | GlobalDecl D(FD); |
99 | |
100 | // TODO: This list should be expanded or refactored after all GCC-compatible |
101 | // std libcall builtins are implemented. |
102 | static SmallDenseMap<unsigned, StringRef, 8> F128Builtins{ |
103 | {Builtin::BI__builtin_printf, "__printfieee128" }, |
104 | {Builtin::BI__builtin_vsnprintf, "__vsnprintfieee128" }, |
105 | {Builtin::BI__builtin_vsprintf, "__vsprintfieee128" }, |
106 | {Builtin::BI__builtin_sprintf, "__sprintfieee128" }, |
107 | {Builtin::BI__builtin_snprintf, "__snprintfieee128" }, |
108 | {Builtin::BI__builtin_fprintf, "__fprintfieee128" }, |
109 | {Builtin::BI__builtin_nexttowardf128, "__nexttowardieee128" }, |
110 | }; |
111 | |
112 | // The AIX library functions frexpl, ldexpl, and modfl are for 128-bit |
113 | // IBM 'long double' (i.e. __ibm128). Map to the 'double' versions |
114 | // if it is 64-bit 'long double' mode. |
115 | static SmallDenseMap<unsigned, StringRef, 4> AIXLongDouble64Builtins{ |
116 | {Builtin::BI__builtin_frexpl, "frexp" }, |
117 | {Builtin::BI__builtin_ldexpl, "ldexp" }, |
118 | {Builtin::BI__builtin_modfl, "modf" }, |
119 | }; |
120 | |
121 | // If the builtin has been declared explicitly with an assembler label, |
122 | // use the mangled name. This differs from the plain label on platforms |
123 | // that prefix labels. |
124 | if (FD->hasAttr<AsmLabelAttr>()) |
125 | Name = getMangledName(D); |
126 | else { |
127 | // TODO: This mutation should also be applied to other targets other than |
128 | // PPC, after backend supports IEEE 128-bit style libcalls. |
129 | if (getTriple().isPPC64() && |
130 | &getTarget().getLongDoubleFormat() == &llvm::APFloat::IEEEquad() && |
131 | F128Builtins.find(Val: BuiltinID) != F128Builtins.end()) |
132 | Name = F128Builtins[BuiltinID]; |
133 | else if (getTriple().isOSAIX() && |
134 | &getTarget().getLongDoubleFormat() == |
135 | &llvm::APFloat::IEEEdouble() && |
136 | AIXLongDouble64Builtins.find(Val: BuiltinID) != |
137 | AIXLongDouble64Builtins.end()) |
138 | Name = AIXLongDouble64Builtins[BuiltinID]; |
139 | else |
140 | Name = Context.BuiltinInfo.getName(BuiltinID).substr(10); |
141 | } |
142 | |
143 | llvm::FunctionType *Ty = |
144 | cast<llvm::FunctionType>(getTypes().ConvertType(T: FD->getType())); |
145 | |
146 | return GetOrCreateLLVMFunction(Name, Ty, D, /*ForVTable=*/false); |
147 | } |
148 | |
149 | /// Emit the conversions required to turn the given value into an |
150 | /// integer of the given size. |
151 | static Value *EmitToInt(CodeGenFunction &CGF, llvm::Value *V, |
152 | QualType T, llvm::IntegerType *IntType) { |
153 | V = CGF.EmitToMemory(V, T); |
154 | |
155 | if (V->getType()->isPointerTy()) |
156 | return CGF.Builder.CreatePtrToInt(V, DestTy: IntType); |
157 | |
158 | assert(V->getType() == IntType); |
159 | return V; |
160 | } |
161 | |
162 | static Value *EmitFromInt(CodeGenFunction &CGF, llvm::Value *V, |
163 | QualType T, llvm::Type *ResultType) { |
164 | V = CGF.EmitFromMemory(V, T); |
165 | |
166 | if (ResultType->isPointerTy()) |
167 | return CGF.Builder.CreateIntToPtr(V, DestTy: ResultType); |
168 | |
169 | assert(V->getType() == ResultType); |
170 | return V; |
171 | } |
172 | |
173 | static llvm::Value *CheckAtomicAlignment(CodeGenFunction &CGF, |
174 | const CallExpr *E) { |
175 | ASTContext &Ctx = CGF.getContext(); |
176 | Address Ptr = CGF.EmitPointerWithAlignment(E->getArg(0)); |
177 | unsigned Bytes = Ptr.getElementType()->isPointerTy() |
178 | ? Ctx.getTypeSizeInChars(Ctx.VoidPtrTy).getQuantity() |
179 | : Ptr.getElementType()->getScalarSizeInBits() / 8; |
180 | unsigned Align = Ptr.getAlignment().getQuantity(); |
181 | if (Align % Bytes != 0) { |
182 | DiagnosticsEngine &Diags = CGF.CGM.getDiags(); |
183 | Diags.Report(E->getBeginLoc(), diag::warn_sync_op_misaligned); |
184 | } |
185 | return Ptr.getPointer(); |
186 | } |
187 | |
188 | /// Utility to insert an atomic instruction based on Intrinsic::ID |
189 | /// and the expression node. |
190 | static Value *MakeBinaryAtomicValue( |
191 | CodeGenFunction &CGF, llvm::AtomicRMWInst::BinOp Kind, const CallExpr *E, |
192 | AtomicOrdering Ordering = AtomicOrdering::SequentiallyConsistent) { |
193 | |
194 | QualType T = E->getType(); |
195 | assert(E->getArg(0)->getType()->isPointerType()); |
196 | assert(CGF.getContext().hasSameUnqualifiedType(T, |
197 | E->getArg(0)->getType()->getPointeeType())); |
198 | assert(CGF.getContext().hasSameUnqualifiedType(T, E->getArg(1)->getType())); |
199 | |
200 | llvm::Value *DestPtr = CheckAtomicAlignment(CGF, E); |
201 | unsigned AddrSpace = DestPtr->getType()->getPointerAddressSpace(); |
202 | |
203 | llvm::IntegerType *IntType = |
204 | llvm::IntegerType::get(CGF.getLLVMContext(), |
205 | CGF.getContext().getTypeSize(T)); |
206 | llvm::Type *IntPtrType = IntType->getPointerTo(AddrSpace); |
207 | |
208 | llvm::Value *Args[2]; |
209 | Args[0] = CGF.Builder.CreateBitCast(V: DestPtr, DestTy: IntPtrType); |
210 | Args[1] = CGF.EmitScalarExpr(E->getArg(1)); |
211 | llvm::Type *ValueType = Args[1]->getType(); |
212 | Args[1] = EmitToInt(CGF, Args[1], T, IntType); |
213 | |
214 | llvm::Value *Result = CGF.Builder.CreateAtomicRMW( |
215 | Op: Kind, Ptr: Args[0], Val: Args[1], Ordering); |
216 | return EmitFromInt(CGF, Result, T, ValueType); |
217 | } |
218 | |
219 | static Value *EmitNontemporalStore(CodeGenFunction &CGF, const CallExpr *E) { |
220 | Value *Val = CGF.EmitScalarExpr(E->getArg(0)); |
221 | Value *Address = CGF.EmitScalarExpr(E->getArg(1)); |
222 | |
223 | // Convert the type of the pointer to a pointer to the stored type. |
224 | Val = CGF.EmitToMemory(Val, E->getArg(0)->getType()); |
225 | unsigned SrcAddrSpace = Address->getType()->getPointerAddressSpace(); |
226 | Value *BC = CGF.Builder.CreateBitCast( |
227 | V: Address, DestTy: llvm::PointerType::get(ElementType: Val->getType(), AddressSpace: SrcAddrSpace), Name: "cast" ); |
228 | LValue LV = CGF.MakeNaturalAlignAddrLValue(BC, E->getArg(0)->getType()); |
229 | LV.setNontemporal(true); |
230 | CGF.EmitStoreOfScalar(value: Val, lvalue: LV, isInit: false); |
231 | return nullptr; |
232 | } |
233 | |
234 | static Value *EmitNontemporalLoad(CodeGenFunction &CGF, const CallExpr *E) { |
235 | Value *Address = CGF.EmitScalarExpr(E->getArg(0)); |
236 | |
237 | LValue LV = CGF.MakeNaturalAlignAddrLValue(Address, E->getType()); |
238 | LV.setNontemporal(true); |
239 | return CGF.EmitLoadOfScalar(LV, E->getExprLoc()); |
240 | } |
241 | |
242 | static RValue EmitBinaryAtomic(CodeGenFunction &CGF, |
243 | llvm::AtomicRMWInst::BinOp Kind, |
244 | const CallExpr *E) { |
245 | return RValue::get(MakeBinaryAtomicValue(CGF, Kind, E)); |
246 | } |
247 | |
248 | /// Utility to insert an atomic instruction based Intrinsic::ID and |
249 | /// the expression node, where the return value is the result of the |
250 | /// operation. |
251 | static RValue EmitBinaryAtomicPost(CodeGenFunction &CGF, |
252 | llvm::AtomicRMWInst::BinOp Kind, |
253 | const CallExpr *E, |
254 | Instruction::BinaryOps Op, |
255 | bool Invert = false) { |
256 | QualType T = E->getType(); |
257 | assert(E->getArg(0)->getType()->isPointerType()); |
258 | assert(CGF.getContext().hasSameUnqualifiedType(T, |
259 | E->getArg(0)->getType()->getPointeeType())); |
260 | assert(CGF.getContext().hasSameUnqualifiedType(T, E->getArg(1)->getType())); |
261 | |
262 | llvm::Value *DestPtr = CheckAtomicAlignment(CGF, E); |
263 | unsigned AddrSpace = DestPtr->getType()->getPointerAddressSpace(); |
264 | |
265 | llvm::IntegerType *IntType = |
266 | llvm::IntegerType::get(CGF.getLLVMContext(), |
267 | CGF.getContext().getTypeSize(T)); |
268 | llvm::Type *IntPtrType = IntType->getPointerTo(AddrSpace); |
269 | |
270 | llvm::Value *Args[2]; |
271 | Args[1] = CGF.EmitScalarExpr(E->getArg(1)); |
272 | llvm::Type *ValueType = Args[1]->getType(); |
273 | Args[1] = EmitToInt(CGF, Args[1], T, IntType); |
274 | Args[0] = CGF.Builder.CreateBitCast(V: DestPtr, DestTy: IntPtrType); |
275 | |
276 | llvm::Value *Result = CGF.Builder.CreateAtomicRMW( |
277 | Op: Kind, Ptr: Args[0], Val: Args[1], Ordering: llvm::AtomicOrdering::SequentiallyConsistent); |
278 | Result = CGF.Builder.CreateBinOp(Opc: Op, LHS: Result, RHS: Args[1]); |
279 | if (Invert) |
280 | Result = |
281 | CGF.Builder.CreateBinOp(Opc: llvm::Instruction::Xor, LHS: Result, |
282 | RHS: llvm::ConstantInt::getAllOnesValue(Ty: IntType)); |
283 | Result = EmitFromInt(CGF, Result, T, ValueType); |
284 | return RValue::get(V: Result); |
285 | } |
286 | |
287 | /// Utility to insert an atomic cmpxchg instruction. |
288 | /// |
289 | /// @param CGF The current codegen function. |
290 | /// @param E Builtin call expression to convert to cmpxchg. |
291 | /// arg0 - address to operate on |
292 | /// arg1 - value to compare with |
293 | /// arg2 - new value |
294 | /// @param ReturnBool Specifies whether to return success flag of |
295 | /// cmpxchg result or the old value. |
296 | /// |
297 | /// @returns result of cmpxchg, according to ReturnBool |
298 | /// |
299 | /// Note: In order to lower Microsoft's _InterlockedCompareExchange* intrinsics |
300 | /// invoke the function EmitAtomicCmpXchgForMSIntrin. |
301 | static Value *MakeAtomicCmpXchgValue(CodeGenFunction &CGF, const CallExpr *E, |
302 | bool ReturnBool) { |
303 | QualType T = ReturnBool ? E->getArg(1)->getType() : E->getType(); |
304 | llvm::Value *DestPtr = CheckAtomicAlignment(CGF, E); |
305 | unsigned AddrSpace = DestPtr->getType()->getPointerAddressSpace(); |
306 | |
307 | llvm::IntegerType *IntType = llvm::IntegerType::get( |
308 | CGF.getLLVMContext(), CGF.getContext().getTypeSize(T)); |
309 | llvm::Type *IntPtrType = IntType->getPointerTo(AddrSpace); |
310 | |
311 | Value *Args[3]; |
312 | Args[0] = CGF.Builder.CreateBitCast(V: DestPtr, DestTy: IntPtrType); |
313 | Args[1] = CGF.EmitScalarExpr(E->getArg(1)); |
314 | llvm::Type *ValueType = Args[1]->getType(); |
315 | Args[1] = EmitToInt(CGF, Args[1], T, IntType); |
316 | Args[2] = EmitToInt(CGF, CGF.EmitScalarExpr(E->getArg(2)), T, IntType); |
317 | |
318 | Value *Pair = CGF.Builder.CreateAtomicCmpXchg( |
319 | Ptr: Args[0], Cmp: Args[1], New: Args[2], SuccessOrdering: llvm::AtomicOrdering::SequentiallyConsistent, |
320 | FailureOrdering: llvm::AtomicOrdering::SequentiallyConsistent); |
321 | if (ReturnBool) |
322 | // Extract boolean success flag and zext it to int. |
323 | return CGF.Builder.CreateZExt(CGF.Builder.CreateExtractValue(Pair, 1), |
324 | CGF.ConvertType(E->getType())); |
325 | else |
326 | // Extract old value and emit it using the same type as compare value. |
327 | return EmitFromInt(CGF, CGF.Builder.CreateExtractValue(Pair, 0), T, |
328 | ValueType); |
329 | } |
330 | |
331 | /// This function should be invoked to emit atomic cmpxchg for Microsoft's |
332 | /// _InterlockedCompareExchange* intrinsics which have the following signature: |
333 | /// T _InterlockedCompareExchange(T volatile *Destination, |
334 | /// T Exchange, |
335 | /// T Comparand); |
336 | /// |
337 | /// Whereas the llvm 'cmpxchg' instruction has the following syntax: |
338 | /// cmpxchg *Destination, Comparand, Exchange. |
339 | /// So we need to swap Comparand and Exchange when invoking |
340 | /// CreateAtomicCmpXchg. That is the reason we could not use the above utility |
341 | /// function MakeAtomicCmpXchgValue since it expects the arguments to be |
342 | /// already swapped. |
343 | |
344 | static |
345 | Value *EmitAtomicCmpXchgForMSIntrin(CodeGenFunction &CGF, const CallExpr *E, |
346 | AtomicOrdering SuccessOrdering = AtomicOrdering::SequentiallyConsistent) { |
347 | assert(E->getArg(0)->getType()->isPointerType()); |
348 | assert(CGF.getContext().hasSameUnqualifiedType( |
349 | E->getType(), E->getArg(0)->getType()->getPointeeType())); |
350 | assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), |
351 | E->getArg(1)->getType())); |
352 | assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), |
353 | E->getArg(2)->getType())); |
354 | |
355 | auto *Destination = CGF.EmitScalarExpr(E->getArg(0)); |
356 | auto *Comparand = CGF.EmitScalarExpr(E->getArg(2)); |
357 | auto *Exchange = CGF.EmitScalarExpr(E->getArg(1)); |
358 | |
359 | // For Release ordering, the failure ordering should be Monotonic. |
360 | auto FailureOrdering = SuccessOrdering == AtomicOrdering::Release ? |
361 | AtomicOrdering::Monotonic : |
362 | SuccessOrdering; |
363 | |
364 | // The atomic instruction is marked volatile for consistency with MSVC. This |
365 | // blocks the few atomics optimizations that LLVM has. If we want to optimize |
366 | // _Interlocked* operations in the future, we will have to remove the volatile |
367 | // marker. |
368 | auto *Result = CGF.Builder.CreateAtomicCmpXchg( |
369 | Destination, Comparand, Exchange, |
370 | SuccessOrdering, FailureOrdering); |
371 | Result->setVolatile(true); |
372 | return CGF.Builder.CreateExtractValue(Result, 0); |
373 | } |
374 | |
375 | // 64-bit Microsoft platforms support 128 bit cmpxchg operations. They are |
376 | // prototyped like this: |
377 | // |
378 | // unsigned char _InterlockedCompareExchange128...( |
379 | // __int64 volatile * _Destination, |
380 | // __int64 _ExchangeHigh, |
381 | // __int64 _ExchangeLow, |
382 | // __int64 * _ComparandResult); |
383 | static Value *EmitAtomicCmpXchg128ForMSIntrin(CodeGenFunction &CGF, |
384 | const CallExpr *E, |
385 | AtomicOrdering SuccessOrdering) { |
386 | assert(E->getNumArgs() == 4); |
387 | llvm::Value *Destination = CGF.EmitScalarExpr(E->getArg(0)); |
388 | llvm::Value *ExchangeHigh = CGF.EmitScalarExpr(E->getArg(1)); |
389 | llvm::Value *ExchangeLow = CGF.EmitScalarExpr(E->getArg(2)); |
390 | llvm::Value *ComparandPtr = CGF.EmitScalarExpr(E->getArg(3)); |
391 | |
392 | assert(Destination->getType()->isPointerTy()); |
393 | assert(!ExchangeHigh->getType()->isPointerTy()); |
394 | assert(!ExchangeLow->getType()->isPointerTy()); |
395 | assert(ComparandPtr->getType()->isPointerTy()); |
396 | |
397 | // For Release ordering, the failure ordering should be Monotonic. |
398 | auto FailureOrdering = SuccessOrdering == AtomicOrdering::Release |
399 | ? AtomicOrdering::Monotonic |
400 | : SuccessOrdering; |
401 | |
402 | // Convert to i128 pointers and values. |
403 | llvm::Type *Int128Ty = llvm::IntegerType::get(C&: CGF.getLLVMContext(), NumBits: 128); |
404 | llvm::Type *Int128PtrTy = Int128Ty->getPointerTo(); |
405 | Destination = CGF.Builder.CreateBitCast(V: Destination, DestTy: Int128PtrTy); |
406 | Address ComparandResult(CGF.Builder.CreateBitCast(V: ComparandPtr, DestTy: Int128PtrTy), |
407 | Int128Ty, CGF.getContext().toCharUnitsFromBits(128)); |
408 | |
409 | // (((i128)hi) << 64) | ((i128)lo) |
410 | ExchangeHigh = CGF.Builder.CreateZExt(V: ExchangeHigh, DestTy: Int128Ty); |
411 | ExchangeLow = CGF.Builder.CreateZExt(V: ExchangeLow, DestTy: Int128Ty); |
412 | ExchangeHigh = |
413 | CGF.Builder.CreateShl(LHS: ExchangeHigh, RHS: llvm::ConstantInt::get(Ty: Int128Ty, V: 64)); |
414 | llvm::Value *Exchange = CGF.Builder.CreateOr(LHS: ExchangeHigh, RHS: ExchangeLow); |
415 | |
416 | // Load the comparand for the instruction. |
417 | llvm::Value *Comparand = CGF.Builder.CreateLoad(Addr: ComparandResult); |
418 | |
419 | auto *CXI = CGF.Builder.CreateAtomicCmpXchg(Ptr: Destination, Cmp: Comparand, New: Exchange, |
420 | SuccessOrdering, FailureOrdering); |
421 | |
422 | // The atomic instruction is marked volatile for consistency with MSVC. This |
423 | // blocks the few atomics optimizations that LLVM has. If we want to optimize |
424 | // _Interlocked* operations in the future, we will have to remove the volatile |
425 | // marker. |
426 | CXI->setVolatile(true); |
427 | |
428 | // Store the result as an outparameter. |
429 | CGF.Builder.CreateStore(Val: CGF.Builder.CreateExtractValue(Agg: CXI, Idxs: 0), |
430 | Addr: ComparandResult); |
431 | |
432 | // Get the success boolean and zero extend it to i8. |
433 | Value *Success = CGF.Builder.CreateExtractValue(Agg: CXI, Idxs: 1); |
434 | return CGF.Builder.CreateZExt(V: Success, DestTy: CGF.Int8Ty); |
435 | } |
436 | |
437 | static Value *EmitAtomicIncrementValue(CodeGenFunction &CGF, const CallExpr *E, |
438 | AtomicOrdering Ordering = AtomicOrdering::SequentiallyConsistent) { |
439 | assert(E->getArg(0)->getType()->isPointerType()); |
440 | |
441 | auto *IntTy = CGF.ConvertType(E->getType()); |
442 | auto *Result = CGF.Builder.CreateAtomicRMW( |
443 | AtomicRMWInst::Add, |
444 | CGF.EmitScalarExpr(E->getArg(0)), |
445 | ConstantInt::get(IntTy, 1), |
446 | Ordering); |
447 | return CGF.Builder.CreateAdd(Result, ConstantInt::get(IntTy, 1)); |
448 | } |
449 | |
450 | static Value *EmitAtomicDecrementValue(CodeGenFunction &CGF, const CallExpr *E, |
451 | AtomicOrdering Ordering = AtomicOrdering::SequentiallyConsistent) { |
452 | assert(E->getArg(0)->getType()->isPointerType()); |
453 | |
454 | auto *IntTy = CGF.ConvertType(E->getType()); |
455 | auto *Result = CGF.Builder.CreateAtomicRMW( |
456 | AtomicRMWInst::Sub, |
457 | CGF.EmitScalarExpr(E->getArg(0)), |
458 | ConstantInt::get(IntTy, 1), |
459 | Ordering); |
460 | return CGF.Builder.CreateSub(Result, ConstantInt::get(IntTy, 1)); |
461 | } |
462 | |
463 | // Build a plain volatile load. |
464 | static Value *EmitISOVolatileLoad(CodeGenFunction &CGF, const CallExpr *E) { |
465 | Value *Ptr = CGF.EmitScalarExpr(E->getArg(0)); |
466 | QualType ElTy = E->getArg(0)->getType()->getPointeeType(); |
467 | CharUnits LoadSize = CGF.getContext().getTypeSizeInChars(ElTy); |
468 | llvm::Type *ITy = |
469 | llvm::IntegerType::get(CGF.getLLVMContext(), LoadSize.getQuantity() * 8); |
470 | Ptr = CGF.Builder.CreateBitCast(V: Ptr, DestTy: ITy->getPointerTo()); |
471 | llvm::LoadInst *Load = CGF.Builder.CreateAlignedLoad(ITy, Ptr, LoadSize); |
472 | Load->setVolatile(true); |
473 | return Load; |
474 | } |
475 | |
476 | // Build a plain volatile store. |
477 | static Value *EmitISOVolatileStore(CodeGenFunction &CGF, const CallExpr *E) { |
478 | Value *Ptr = CGF.EmitScalarExpr(E->getArg(0)); |
479 | Value *Value = CGF.EmitScalarExpr(E->getArg(1)); |
480 | QualType ElTy = E->getArg(0)->getType()->getPointeeType(); |
481 | CharUnits StoreSize = CGF.getContext().getTypeSizeInChars(ElTy); |
482 | llvm::Type *ITy = |
483 | llvm::IntegerType::get(CGF.getLLVMContext(), StoreSize.getQuantity() * 8); |
484 | Ptr = CGF.Builder.CreateBitCast(V: Ptr, DestTy: ITy->getPointerTo()); |
485 | llvm::StoreInst *Store = |
486 | CGF.Builder.CreateAlignedStore(Value, Ptr, StoreSize); |
487 | Store->setVolatile(true); |
488 | return Store; |
489 | } |
490 | |
491 | // Emit a simple mangled intrinsic that has 1 argument and a return type |
492 | // matching the argument type. Depending on mode, this may be a constrained |
493 | // floating-point intrinsic. |
494 | static Value *emitUnaryMaybeConstrainedFPBuiltin(CodeGenFunction &CGF, |
495 | const CallExpr *E, unsigned IntrinsicID, |
496 | unsigned ConstrainedIntrinsicID) { |
497 | llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0)); |
498 | |
499 | if (CGF.Builder.getIsFPConstrained()) { |
500 | CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E); |
501 | Function *F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID, Src0->getType()); |
502 | return CGF.Builder.CreateConstrainedFPCall(Callee: F, Args: { Src0 }); |
503 | } else { |
504 | Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType()); |
505 | return CGF.Builder.CreateCall(Callee: F, Args: Src0); |
506 | } |
507 | } |
508 | |
509 | // Emit an intrinsic that has 2 operands of the same type as its result. |
510 | // Depending on mode, this may be a constrained floating-point intrinsic. |
511 | static Value *emitBinaryMaybeConstrainedFPBuiltin(CodeGenFunction &CGF, |
512 | const CallExpr *E, unsigned IntrinsicID, |
513 | unsigned ConstrainedIntrinsicID) { |
514 | llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0)); |
515 | llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1)); |
516 | |
517 | if (CGF.Builder.getIsFPConstrained()) { |
518 | CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E); |
519 | Function *F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID, Src0->getType()); |
520 | return CGF.Builder.CreateConstrainedFPCall(Callee: F, Args: { Src0, Src1 }); |
521 | } else { |
522 | Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType()); |
523 | return CGF.Builder.CreateCall(Callee: F, Args: { Src0, Src1 }); |
524 | } |
525 | } |
526 | |
527 | // Emit an intrinsic that has 3 operands of the same type as its result. |
528 | // Depending on mode, this may be a constrained floating-point intrinsic. |
529 | static Value *emitTernaryMaybeConstrainedFPBuiltin(CodeGenFunction &CGF, |
530 | const CallExpr *E, unsigned IntrinsicID, |
531 | unsigned ConstrainedIntrinsicID) { |
532 | llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0)); |
533 | llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1)); |
534 | llvm::Value *Src2 = CGF.EmitScalarExpr(E->getArg(2)); |
535 | |
536 | if (CGF.Builder.getIsFPConstrained()) { |
537 | CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E); |
538 | Function *F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID, Src0->getType()); |
539 | return CGF.Builder.CreateConstrainedFPCall(Callee: F, Args: { Src0, Src1, Src2 }); |
540 | } else { |
541 | Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType()); |
542 | return CGF.Builder.CreateCall(Callee: F, Args: { Src0, Src1, Src2 }); |
543 | } |
544 | } |
545 | |
546 | // Emit an intrinsic where all operands are of the same type as the result. |
547 | // Depending on mode, this may be a constrained floating-point intrinsic. |
548 | static Value *emitCallMaybeConstrainedFPBuiltin(CodeGenFunction &CGF, |
549 | unsigned IntrinsicID, |
550 | unsigned ConstrainedIntrinsicID, |
551 | llvm::Type *Ty, |
552 | ArrayRef<Value *> Args) { |
553 | Function *F; |
554 | if (CGF.Builder.getIsFPConstrained()) |
555 | F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID, Ty); |
556 | else |
557 | F = CGF.CGM.getIntrinsic(IntrinsicID, Ty); |
558 | |
559 | if (CGF.Builder.getIsFPConstrained()) |
560 | return CGF.Builder.CreateConstrainedFPCall(Callee: F, Args); |
561 | else |
562 | return CGF.Builder.CreateCall(Callee: F, Args); |
563 | } |
564 | |
565 | // Emit a simple mangled intrinsic that has 1 argument and a return type |
566 | // matching the argument type. |
567 | static Value *emitUnaryBuiltin(CodeGenFunction &CGF, const CallExpr *E, |
568 | unsigned IntrinsicID, |
569 | llvm::StringRef Name = "" ) { |
570 | llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0)); |
571 | |
572 | Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType()); |
573 | return CGF.Builder.CreateCall(Callee: F, Args: Src0, Name); |
574 | } |
575 | |
576 | // Emit an intrinsic that has 2 operands of the same type as its result. |
577 | static Value *emitBinaryBuiltin(CodeGenFunction &CGF, |
578 | const CallExpr *E, |
579 | unsigned IntrinsicID) { |
580 | llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0)); |
581 | llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1)); |
582 | |
583 | Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType()); |
584 | return CGF.Builder.CreateCall(Callee: F, Args: { Src0, Src1 }); |
585 | } |
586 | |
587 | // Emit an intrinsic that has 3 operands of the same type as its result. |
588 | static Value *emitTernaryBuiltin(CodeGenFunction &CGF, |
589 | const CallExpr *E, |
590 | unsigned IntrinsicID) { |
591 | llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0)); |
592 | llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1)); |
593 | llvm::Value *Src2 = CGF.EmitScalarExpr(E->getArg(2)); |
594 | |
595 | Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType()); |
596 | return CGF.Builder.CreateCall(Callee: F, Args: { Src0, Src1, Src2 }); |
597 | } |
598 | |
599 | // Emit an intrinsic that has 1 float or double operand, and 1 integer. |
600 | static Value *emitFPIntBuiltin(CodeGenFunction &CGF, |
601 | const CallExpr *E, |
602 | unsigned IntrinsicID) { |
603 | llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0)); |
604 | llvm::Value *Src1 = CGF.EmitScalarExpr(E->getArg(1)); |
605 | |
606 | Function *F = CGF.CGM.getIntrinsic(IntrinsicID, Src0->getType()); |
607 | return CGF.Builder.CreateCall(Callee: F, Args: {Src0, Src1}); |
608 | } |
609 | |
610 | // Emit an intrinsic that has overloaded integer result and fp operand. |
611 | static Value * |
612 | emitMaybeConstrainedFPToIntRoundBuiltin(CodeGenFunction &CGF, const CallExpr *E, |
613 | unsigned IntrinsicID, |
614 | unsigned ConstrainedIntrinsicID) { |
615 | llvm::Type *ResultType = CGF.ConvertType(E->getType()); |
616 | llvm::Value *Src0 = CGF.EmitScalarExpr(E->getArg(0)); |
617 | |
618 | if (CGF.Builder.getIsFPConstrained()) { |
619 | CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E); |
620 | Function *F = CGF.CGM.getIntrinsic(ConstrainedIntrinsicID, |
621 | {ResultType, Src0->getType()}); |
622 | return CGF.Builder.CreateConstrainedFPCall(Callee: F, Args: {Src0}); |
623 | } else { |
624 | Function *F = |
625 | CGF.CGM.getIntrinsic(IntrinsicID, {ResultType, Src0->getType()}); |
626 | return CGF.Builder.CreateCall(Callee: F, Args: Src0); |
627 | } |
628 | } |
629 | |
630 | /// EmitFAbs - Emit a call to @llvm.fabs(). |
631 | static Value *EmitFAbs(CodeGenFunction &CGF, Value *V) { |
632 | Function *F = CGF.CGM.getIntrinsic(Intrinsic::fabs, V->getType()); |
633 | llvm::CallInst *Call = CGF.Builder.CreateCall(Callee: F, Args: V); |
634 | Call->setDoesNotAccessMemory(); |
635 | return Call; |
636 | } |
637 | |
638 | /// Emit the computation of the sign bit for a floating point value. Returns |
639 | /// the i1 sign bit value. |
640 | static Value *EmitSignBit(CodeGenFunction &CGF, Value *V) { |
641 | LLVMContext &C = CGF.CGM.getLLVMContext(); |
642 | |
643 | llvm::Type *Ty = V->getType(); |
644 | int Width = Ty->getPrimitiveSizeInBits(); |
645 | llvm::Type *IntTy = llvm::IntegerType::get(C, NumBits: Width); |
646 | V = CGF.Builder.CreateBitCast(V, DestTy: IntTy); |
647 | if (Ty->isPPC_FP128Ty()) { |
648 | // We want the sign bit of the higher-order double. The bitcast we just |
649 | // did works as if the double-double was stored to memory and then |
650 | // read as an i128. The "store" will put the higher-order double in the |
651 | // lower address in both little- and big-Endian modes, but the "load" |
652 | // will treat those bits as a different part of the i128: the low bits in |
653 | // little-Endian, the high bits in big-Endian. Therefore, on big-Endian |
654 | // we need to shift the high bits down to the low before truncating. |
655 | Width >>= 1; |
656 | if (CGF.getTarget().isBigEndian()) { |
657 | Value *ShiftCst = llvm::ConstantInt::get(Ty: IntTy, V: Width); |
658 | V = CGF.Builder.CreateLShr(LHS: V, RHS: ShiftCst); |
659 | } |
660 | // We are truncating value in order to extract the higher-order |
661 | // double, which we will be using to extract the sign from. |
662 | IntTy = llvm::IntegerType::get(C, NumBits: Width); |
663 | V = CGF.Builder.CreateTrunc(V, DestTy: IntTy); |
664 | } |
665 | Value *Zero = llvm::Constant::getNullValue(Ty: IntTy); |
666 | return CGF.Builder.CreateICmpSLT(LHS: V, RHS: Zero); |
667 | } |
668 | |
669 | static RValue emitLibraryCall(CodeGenFunction &CGF, const FunctionDecl *FD, |
670 | const CallExpr *E, llvm::Constant *calleeValue) { |
671 | CGCallee callee = CGCallee::forDirect(calleeValue, GlobalDecl(FD)); |
672 | return CGF.EmitCall(E->getCallee()->getType(), callee, E, ReturnValueSlot()); |
673 | } |
674 | |
675 | /// Emit a call to llvm.{sadd,uadd,ssub,usub,smul,umul}.with.overflow.* |
676 | /// depending on IntrinsicID. |
677 | /// |
678 | /// \arg CGF The current codegen function. |
679 | /// \arg IntrinsicID The ID for the Intrinsic we wish to generate. |
680 | /// \arg X The first argument to the llvm.*.with.overflow.*. |
681 | /// \arg Y The second argument to the llvm.*.with.overflow.*. |
682 | /// \arg Carry The carry returned by the llvm.*.with.overflow.*. |
683 | /// \returns The result (i.e. sum/product) returned by the intrinsic. |
684 | static llvm::Value *EmitOverflowIntrinsic(CodeGenFunction &CGF, |
685 | const llvm::Intrinsic::ID IntrinsicID, |
686 | llvm::Value *X, llvm::Value *Y, |
687 | llvm::Value *&Carry) { |
688 | // Make sure we have integers of the same width. |
689 | assert(X->getType() == Y->getType() && |
690 | "Arguments must be the same type. (Did you forget to make sure both " |
691 | "arguments have the same integer width?)" ); |
692 | |
693 | Function *Callee = CGF.CGM.getIntrinsic(IntrinsicID, X->getType()); |
694 | llvm::Value *Tmp = CGF.Builder.CreateCall(Callee, Args: {X, Y}); |
695 | Carry = CGF.Builder.CreateExtractValue(Agg: Tmp, Idxs: 1); |
696 | return CGF.Builder.CreateExtractValue(Agg: Tmp, Idxs: 0); |
697 | } |
698 | |
699 | static Value *emitRangedBuiltin(CodeGenFunction &CGF, |
700 | unsigned IntrinsicID, |
701 | int low, int high) { |
702 | llvm::MDBuilder MDHelper(CGF.getLLVMContext()); |
703 | llvm::MDNode *RNode = MDHelper.createRange(Lo: APInt(32, low), Hi: APInt(32, high)); |
704 | Function *F = CGF.CGM.getIntrinsic(IntrinsicID, {}); |
705 | llvm::Instruction *Call = CGF.Builder.CreateCall(Callee: F); |
706 | Call->setMetadata(KindID: llvm::LLVMContext::MD_range, Node: RNode); |
707 | Call->setMetadata(KindID: llvm::LLVMContext::MD_noundef, |
708 | Node: llvm::MDNode::get(Context&: CGF.getLLVMContext(), MDs: std::nullopt)); |
709 | return Call; |
710 | } |
711 | |
712 | namespace { |
713 | struct WidthAndSignedness { |
714 | unsigned Width; |
715 | bool Signed; |
716 | }; |
717 | } |
718 | |
719 | static WidthAndSignedness |
720 | getIntegerWidthAndSignedness(const clang::ASTContext &context, |
721 | const clang::QualType Type) { |
722 | assert(Type->isIntegerType() && "Given type is not an integer." ); |
723 | unsigned Width = Type->isBooleanType() ? 1 |
724 | : Type->isBitIntType() ? context.getIntWidth(Type) |
725 | : context.getTypeInfo(Type).Width; |
726 | bool Signed = Type->isSignedIntegerType(); |
727 | return {.Width: Width, .Signed: Signed}; |
728 | } |
729 | |
730 | // Given one or more integer types, this function produces an integer type that |
731 | // encompasses them: any value in one of the given types could be expressed in |
732 | // the encompassing type. |
733 | static struct WidthAndSignedness |
734 | EncompassingIntegerType(ArrayRef<struct WidthAndSignedness> Types) { |
735 | assert(Types.size() > 0 && "Empty list of types." ); |
736 | |
737 | // If any of the given types is signed, we must return a signed type. |
738 | bool Signed = false; |
739 | for (const auto &Type : Types) { |
740 | Signed |= Type.Signed; |
741 | } |
742 | |
743 | // The encompassing type must have a width greater than or equal to the width |
744 | // of the specified types. Additionally, if the encompassing type is signed, |
745 | // its width must be strictly greater than the width of any unsigned types |
746 | // given. |
747 | unsigned Width = 0; |
748 | for (const auto &Type : Types) { |
749 | unsigned MinWidth = Type.Width + (Signed && !Type.Signed); |
750 | if (Width < MinWidth) { |
751 | Width = MinWidth; |
752 | } |
753 | } |
754 | |
755 | return {.Width: Width, .Signed: Signed}; |
756 | } |
757 | |
758 | Value *CodeGenFunction::EmitVAStartEnd(Value *ArgValue, bool IsStart) { |
759 | llvm::Type *DestType = Int8PtrTy; |
760 | if (ArgValue->getType() != DestType) |
761 | ArgValue = |
762 | Builder.CreateBitCast(V: ArgValue, DestTy: DestType, Name: ArgValue->getName().data()); |
763 | |
764 | Intrinsic::ID inst = IsStart ? Intrinsic::vastart : Intrinsic::vaend; |
765 | return Builder.CreateCall(CGM.getIntrinsic(inst), ArgValue); |
766 | } |
767 | |
768 | /// Checks if using the result of __builtin_object_size(p, @p From) in place of |
769 | /// __builtin_object_size(p, @p To) is correct |
770 | static bool areBOSTypesCompatible(int From, int To) { |
771 | // Note: Our __builtin_object_size implementation currently treats Type=0 and |
772 | // Type=2 identically. Encoding this implementation detail here may make |
773 | // improving __builtin_object_size difficult in the future, so it's omitted. |
774 | return From == To || (From == 0 && To == 1) || (From == 3 && To == 2); |
775 | } |
776 | |
777 | static llvm::Value * |
778 | getDefaultBuiltinObjectSizeResult(unsigned Type, llvm::IntegerType *ResType) { |
779 | return ConstantInt::get(Ty: ResType, V: (Type & 2) ? 0 : -1, /*isSigned=*/IsSigned: true); |
780 | } |
781 | |
782 | llvm::Value * |
783 | CodeGenFunction::evaluateOrEmitBuiltinObjectSize(const Expr *E, unsigned Type, |
784 | llvm::IntegerType *ResType, |
785 | llvm::Value *EmittedE, |
786 | bool IsDynamic) { |
787 | uint64_t ObjectSize; |
788 | if (!E->tryEvaluateObjectSize(ObjectSize, getContext(), Type)) |
789 | return emitBuiltinObjectSize(E, Type, ResType, EmittedE, IsDynamic); |
790 | return ConstantInt::get(Ty: ResType, V: ObjectSize, /*isSigned=*/IsSigned: true); |
791 | } |
792 | |
793 | /// Returns a Value corresponding to the size of the given expression. |
794 | /// This Value may be either of the following: |
795 | /// - A llvm::Argument (if E is a param with the pass_object_size attribute on |
796 | /// it) |
797 | /// - A call to the @llvm.objectsize intrinsic |
798 | /// |
799 | /// EmittedE is the result of emitting `E` as a scalar expr. If it's non-null |
800 | /// and we wouldn't otherwise try to reference a pass_object_size parameter, |
801 | /// we'll call @llvm.objectsize on EmittedE, rather than emitting E. |
802 | llvm::Value * |
803 | CodeGenFunction::emitBuiltinObjectSize(const Expr *E, unsigned Type, |
804 | llvm::IntegerType *ResType, |
805 | llvm::Value *EmittedE, bool IsDynamic) { |
806 | // We need to reference an argument if the pointer is a parameter with the |
807 | // pass_object_size attribute. |
808 | if (auto *D = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) { |
809 | auto *Param = dyn_cast<ParmVarDecl>(D->getDecl()); |
810 | auto *PS = D->getDecl()->getAttr<PassObjectSizeAttr>(); |
811 | if (Param != nullptr && PS != nullptr && |
812 | areBOSTypesCompatible(PS->getType(), Type)) { |
813 | auto Iter = SizeArguments.find(Param); |
814 | assert(Iter != SizeArguments.end()); |
815 | |
816 | const ImplicitParamDecl *D = Iter->second; |
817 | auto DIter = LocalDeclMap.find(D); |
818 | assert(DIter != LocalDeclMap.end()); |
819 | |
820 | return EmitLoadOfScalar(DIter->second, /*Volatile=*/false, |
821 | getContext().getSizeType(), E->getBeginLoc()); |
822 | } |
823 | } |
824 | |
825 | // LLVM can't handle Type=3 appropriately, and __builtin_object_size shouldn't |
826 | // evaluate E for side-effects. In either case, we shouldn't lower to |
827 | // @llvm.objectsize. |
828 | if (Type == 3 || (!EmittedE && E->HasSideEffects(getContext()))) |
829 | return getDefaultBuiltinObjectSizeResult(Type, ResType); |
830 | |
831 | Value *Ptr = EmittedE ? EmittedE : EmitScalarExpr(E); |
832 | assert(Ptr->getType()->isPointerTy() && |
833 | "Non-pointer passed to __builtin_object_size?" ); |
834 | |
835 | Function *F = |
836 | CGM.getIntrinsic(Intrinsic::objectsize, {ResType, Ptr->getType()}); |
837 | |
838 | // LLVM only supports 0 and 2, make sure that we pass along that as a boolean. |
839 | Value *Min = Builder.getInt1(V: (Type & 2) != 0); |
840 | // For GCC compatibility, __builtin_object_size treat NULL as unknown size. |
841 | Value *NullIsUnknown = Builder.getTrue(); |
842 | Value *Dynamic = Builder.getInt1(V: IsDynamic); |
843 | return Builder.CreateCall(Callee: F, Args: {Ptr, Min, NullIsUnknown, Dynamic}); |
844 | } |
845 | |
846 | namespace { |
847 | /// A struct to generically describe a bit test intrinsic. |
848 | struct BitTest { |
849 | enum ActionKind : uint8_t { TestOnly, Complement, Reset, Set }; |
850 | enum InterlockingKind : uint8_t { |
851 | Unlocked, |
852 | Sequential, |
853 | Acquire, |
854 | Release, |
855 | NoFence |
856 | }; |
857 | |
858 | ActionKind Action; |
859 | InterlockingKind Interlocking; |
860 | bool Is64Bit; |
861 | |
862 | static BitTest decodeBitTestBuiltin(unsigned BuiltinID); |
863 | }; |
864 | } // namespace |
865 | |
866 | BitTest BitTest::decodeBitTestBuiltin(unsigned BuiltinID) { |
867 | switch (BuiltinID) { |
868 | // Main portable variants. |
869 | case Builtin::BI_bittest: |
870 | return {.Action: TestOnly, .Interlocking: Unlocked, .Is64Bit: false}; |
871 | case Builtin::BI_bittestandcomplement: |
872 | return {.Action: Complement, .Interlocking: Unlocked, .Is64Bit: false}; |
873 | case Builtin::BI_bittestandreset: |
874 | return {.Action: Reset, .Interlocking: Unlocked, .Is64Bit: false}; |
875 | case Builtin::BI_bittestandset: |
876 | return {.Action: Set, .Interlocking: Unlocked, .Is64Bit: false}; |
877 | case Builtin::BI_interlockedbittestandreset: |
878 | return {.Action: Reset, .Interlocking: Sequential, .Is64Bit: false}; |
879 | case Builtin::BI_interlockedbittestandset: |
880 | return {.Action: Set, .Interlocking: Sequential, .Is64Bit: false}; |
881 | |
882 | // X86-specific 64-bit variants. |
883 | case Builtin::BI_bittest64: |
884 | return {.Action: TestOnly, .Interlocking: Unlocked, .Is64Bit: true}; |
885 | case Builtin::BI_bittestandcomplement64: |
886 | return {.Action: Complement, .Interlocking: Unlocked, .Is64Bit: true}; |
887 | case Builtin::BI_bittestandreset64: |
888 | return {.Action: Reset, .Interlocking: Unlocked, .Is64Bit: true}; |
889 | case Builtin::BI_bittestandset64: |
890 | return {.Action: Set, .Interlocking: Unlocked, .Is64Bit: true}; |
891 | case Builtin::BI_interlockedbittestandreset64: |
892 | return {.Action: Reset, .Interlocking: Sequential, .Is64Bit: true}; |
893 | case Builtin::BI_interlockedbittestandset64: |
894 | return {.Action: Set, .Interlocking: Sequential, .Is64Bit: true}; |
895 | |
896 | // ARM/AArch64-specific ordering variants. |
897 | case Builtin::BI_interlockedbittestandset_acq: |
898 | return {.Action: Set, .Interlocking: Acquire, .Is64Bit: false}; |
899 | case Builtin::BI_interlockedbittestandset_rel: |
900 | return {.Action: Set, .Interlocking: Release, .Is64Bit: false}; |
901 | case Builtin::BI_interlockedbittestandset_nf: |
902 | return {.Action: Set, .Interlocking: NoFence, .Is64Bit: false}; |
903 | case Builtin::BI_interlockedbittestandreset_acq: |
904 | return {.Action: Reset, .Interlocking: Acquire, .Is64Bit: false}; |
905 | case Builtin::BI_interlockedbittestandreset_rel: |
906 | return {.Action: Reset, .Interlocking: Release, .Is64Bit: false}; |
907 | case Builtin::BI_interlockedbittestandreset_nf: |
908 | return {.Action: Reset, .Interlocking: NoFence, .Is64Bit: false}; |
909 | } |
910 | llvm_unreachable("expected only bittest intrinsics" ); |
911 | } |
912 | |
913 | static char bitActionToX86BTCode(BitTest::ActionKind A) { |
914 | switch (A) { |
915 | case BitTest::TestOnly: return '\0'; |
916 | case BitTest::Complement: return 'c'; |
917 | case BitTest::Reset: return 'r'; |
918 | case BitTest::Set: return 's'; |
919 | } |
920 | llvm_unreachable("invalid action" ); |
921 | } |
922 | |
923 | static llvm::Value *EmitX86BitTestIntrinsic(CodeGenFunction &CGF, |
924 | BitTest BT, |
925 | const CallExpr *E, Value *BitBase, |
926 | Value *BitPos) { |
927 | char Action = bitActionToX86BTCode(A: BT.Action); |
928 | char SizeSuffix = BT.Is64Bit ? 'q' : 'l'; |
929 | |
930 | // Build the assembly. |
931 | SmallString<64> Asm; |
932 | raw_svector_ostream AsmOS(Asm); |
933 | if (BT.Interlocking != BitTest::Unlocked) |
934 | AsmOS << "lock " ; |
935 | AsmOS << "bt" ; |
936 | if (Action) |
937 | AsmOS << Action; |
938 | AsmOS << SizeSuffix << " $2, ($1)" ; |
939 | |
940 | // Build the constraints. FIXME: We should support immediates when possible. |
941 | std::string Constraints = "={@ccc},r,r,~{cc},~{memory}" ; |
942 | std::string_view MachineClobbers = CGF.getTarget().getClobbers(); |
943 | if (!MachineClobbers.empty()) { |
944 | Constraints += ','; |
945 | Constraints += MachineClobbers; |
946 | } |
947 | llvm::IntegerType *IntType = llvm::IntegerType::get( |
948 | CGF.getLLVMContext(), |
949 | CGF.getContext().getTypeSize(E->getArg(1)->getType())); |
950 | llvm::Type *IntPtrType = IntType->getPointerTo(); |
951 | llvm::FunctionType *FTy = |
952 | llvm::FunctionType::get(Result: CGF.Int8Ty, Params: {IntPtrType, IntType}, isVarArg: false); |
953 | |
954 | llvm::InlineAsm *IA = |
955 | llvm::InlineAsm::get(Ty: FTy, AsmString: Asm, Constraints, /*hasSideEffects=*/true); |
956 | return CGF.Builder.CreateCall(Callee: IA, Args: {BitBase, BitPos}); |
957 | } |
958 | |
959 | static llvm::AtomicOrdering |
960 | getBitTestAtomicOrdering(BitTest::InterlockingKind I) { |
961 | switch (I) { |
962 | case BitTest::Unlocked: return llvm::AtomicOrdering::NotAtomic; |
963 | case BitTest::Sequential: return llvm::AtomicOrdering::SequentiallyConsistent; |
964 | case BitTest::Acquire: return llvm::AtomicOrdering::Acquire; |
965 | case BitTest::Release: return llvm::AtomicOrdering::Release; |
966 | case BitTest::NoFence: return llvm::AtomicOrdering::Monotonic; |
967 | } |
968 | llvm_unreachable("invalid interlocking" ); |
969 | } |
970 | |
971 | /// Emit a _bittest* intrinsic. These intrinsics take a pointer to an array of |
972 | /// bits and a bit position and read and optionally modify the bit at that |
973 | /// position. The position index can be arbitrarily large, i.e. it can be larger |
974 | /// than 31 or 63, so we need an indexed load in the general case. |
975 | static llvm::Value *EmitBitTestIntrinsic(CodeGenFunction &CGF, |
976 | unsigned BuiltinID, |
977 | const CallExpr *E) { |
978 | Value *BitBase = CGF.EmitScalarExpr(E->getArg(0)); |
979 | Value *BitPos = CGF.EmitScalarExpr(E->getArg(1)); |
980 | |
981 | BitTest BT = BitTest::decodeBitTestBuiltin(BuiltinID); |
982 | |
983 | // X86 has special BT, BTC, BTR, and BTS instructions that handle the array |
984 | // indexing operation internally. Use them if possible. |
985 | if (CGF.getTarget().getTriple().isX86()) |
986 | return EmitX86BitTestIntrinsic(CGF, BT, E, BitBase, BitPos); |
987 | |
988 | // Otherwise, use generic code to load one byte and test the bit. Use all but |
989 | // the bottom three bits as the array index, and the bottom three bits to form |
990 | // a mask. |
991 | // Bit = BitBaseI8[BitPos >> 3] & (1 << (BitPos & 0x7)) != 0; |
992 | Value *ByteIndex = CGF.Builder.CreateAShr( |
993 | LHS: BitPos, RHS: llvm::ConstantInt::get(Ty: BitPos->getType(), V: 3), Name: "bittest.byteidx" ); |
994 | Value *BitBaseI8 = CGF.Builder.CreatePointerCast(V: BitBase, DestTy: CGF.Int8PtrTy); |
995 | Address ByteAddr(CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, BitBaseI8, |
996 | ByteIndex, "bittest.byteaddr" ), |
997 | CGF.Int8Ty, CharUnits::One()); |
998 | Value *PosLow = |
999 | CGF.Builder.CreateAnd(LHS: CGF.Builder.CreateTrunc(V: BitPos, DestTy: CGF.Int8Ty), |
1000 | RHS: llvm::ConstantInt::get(Ty: CGF.Int8Ty, V: 0x7)); |
1001 | |
1002 | // The updating instructions will need a mask. |
1003 | Value *Mask = nullptr; |
1004 | if (BT.Action != BitTest::TestOnly) { |
1005 | Mask = CGF.Builder.CreateShl(LHS: llvm::ConstantInt::get(Ty: CGF.Int8Ty, V: 1), RHS: PosLow, |
1006 | Name: "bittest.mask" ); |
1007 | } |
1008 | |
1009 | // Check the action and ordering of the interlocked intrinsics. |
1010 | llvm::AtomicOrdering Ordering = getBitTestAtomicOrdering(I: BT.Interlocking); |
1011 | |
1012 | Value *OldByte = nullptr; |
1013 | if (Ordering != llvm::AtomicOrdering::NotAtomic) { |
1014 | // Emit a combined atomicrmw load/store operation for the interlocked |
1015 | // intrinsics. |
1016 | llvm::AtomicRMWInst::BinOp RMWOp = llvm::AtomicRMWInst::Or; |
1017 | if (BT.Action == BitTest::Reset) { |
1018 | Mask = CGF.Builder.CreateNot(V: Mask); |
1019 | RMWOp = llvm::AtomicRMWInst::And; |
1020 | } |
1021 | OldByte = CGF.Builder.CreateAtomicRMW(Op: RMWOp, Ptr: ByteAddr.getPointer(), Val: Mask, |
1022 | Ordering); |
1023 | } else { |
1024 | // Emit a plain load for the non-interlocked intrinsics. |
1025 | OldByte = CGF.Builder.CreateLoad(Addr: ByteAddr, Name: "bittest.byte" ); |
1026 | Value *NewByte = nullptr; |
1027 | switch (BT.Action) { |
1028 | case BitTest::TestOnly: |
1029 | // Don't store anything. |
1030 | break; |
1031 | case BitTest::Complement: |
1032 | NewByte = CGF.Builder.CreateXor(LHS: OldByte, RHS: Mask); |
1033 | break; |
1034 | case BitTest::Reset: |
1035 | NewByte = CGF.Builder.CreateAnd(LHS: OldByte, RHS: CGF.Builder.CreateNot(V: Mask)); |
1036 | break; |
1037 | case BitTest::Set: |
1038 | NewByte = CGF.Builder.CreateOr(LHS: OldByte, RHS: Mask); |
1039 | break; |
1040 | } |
1041 | if (NewByte) |
1042 | CGF.Builder.CreateStore(Val: NewByte, Addr: ByteAddr); |
1043 | } |
1044 | |
1045 | // However we loaded the old byte, either by plain load or atomicrmw, shift |
1046 | // the bit into the low position and mask it to 0 or 1. |
1047 | Value *ShiftedByte = CGF.Builder.CreateLShr(LHS: OldByte, RHS: PosLow, Name: "bittest.shr" ); |
1048 | return CGF.Builder.CreateAnd( |
1049 | LHS: ShiftedByte, RHS: llvm::ConstantInt::get(Ty: CGF.Int8Ty, V: 1), Name: "bittest.res" ); |
1050 | } |
1051 | |
1052 | static llvm::Value *emitPPCLoadReserveIntrinsic(CodeGenFunction &CGF, |
1053 | unsigned BuiltinID, |
1054 | const CallExpr *E) { |
1055 | Value *Addr = CGF.EmitScalarExpr(E->getArg(0)); |
1056 | |
1057 | SmallString<64> Asm; |
1058 | raw_svector_ostream AsmOS(Asm); |
1059 | llvm::IntegerType *RetType = CGF.Int32Ty; |
1060 | |
1061 | switch (BuiltinID) { |
1062 | case clang::PPC::BI__builtin_ppc_ldarx: |
1063 | AsmOS << "ldarx " ; |
1064 | RetType = CGF.Int64Ty; |
1065 | break; |
1066 | case clang::PPC::BI__builtin_ppc_lwarx: |
1067 | AsmOS << "lwarx " ; |
1068 | RetType = CGF.Int32Ty; |
1069 | break; |
1070 | case clang::PPC::BI__builtin_ppc_lharx: |
1071 | AsmOS << "lharx " ; |
1072 | RetType = CGF.Int16Ty; |
1073 | break; |
1074 | case clang::PPC::BI__builtin_ppc_lbarx: |
1075 | AsmOS << "lbarx " ; |
1076 | RetType = CGF.Int8Ty; |
1077 | break; |
1078 | default: |
1079 | llvm_unreachable("Expected only PowerPC load reserve intrinsics" ); |
1080 | } |
1081 | |
1082 | AsmOS << "$0, ${1:y}" ; |
1083 | |
1084 | std::string Constraints = "=r,*Z,~{memory}" ; |
1085 | std::string_view MachineClobbers = CGF.getTarget().getClobbers(); |
1086 | if (!MachineClobbers.empty()) { |
1087 | Constraints += ','; |
1088 | Constraints += MachineClobbers; |
1089 | } |
1090 | |
1091 | llvm::Type *IntPtrType = RetType->getPointerTo(); |
1092 | llvm::FunctionType *FTy = |
1093 | llvm::FunctionType::get(Result: RetType, Params: {IntPtrType}, isVarArg: false); |
1094 | |
1095 | llvm::InlineAsm *IA = |
1096 | llvm::InlineAsm::get(Ty: FTy, AsmString: Asm, Constraints, /*hasSideEffects=*/true); |
1097 | llvm::CallInst *CI = CGF.Builder.CreateCall(Callee: IA, Args: {Addr}); |
1098 | CI->addParamAttr( |
1099 | 0, Attribute::get(CGF.getLLVMContext(), Attribute::ElementType, RetType)); |
1100 | return CI; |
1101 | } |
1102 | |
1103 | namespace { |
1104 | enum class MSVCSetJmpKind { |
1105 | _setjmpex, |
1106 | _setjmp3, |
1107 | _setjmp |
1108 | }; |
1109 | } |
1110 | |
1111 | /// MSVC handles setjmp a bit differently on different platforms. On every |
1112 | /// architecture except 32-bit x86, the frame address is passed. On x86, extra |
1113 | /// parameters can be passed as variadic arguments, but we always pass none. |
1114 | static RValue EmitMSVCRTSetJmp(CodeGenFunction &CGF, MSVCSetJmpKind SJKind, |
1115 | const CallExpr *E) { |
1116 | llvm::Value *Arg1 = nullptr; |
1117 | llvm::Type *Arg1Ty = nullptr; |
1118 | StringRef Name; |
1119 | bool IsVarArg = false; |
1120 | if (SJKind == MSVCSetJmpKind::_setjmp3) { |
1121 | Name = "_setjmp3" ; |
1122 | Arg1Ty = CGF.Int32Ty; |
1123 | Arg1 = llvm::ConstantInt::get(Ty: CGF.IntTy, V: 0); |
1124 | IsVarArg = true; |
1125 | } else { |
1126 | Name = SJKind == MSVCSetJmpKind::_setjmp ? "_setjmp" : "_setjmpex" ; |
1127 | Arg1Ty = CGF.Int8PtrTy; |
1128 | if (CGF.getTarget().getTriple().getArch() == llvm::Triple::aarch64) { |
1129 | Arg1 = CGF.Builder.CreateCall( |
1130 | CGF.CGM.getIntrinsic(Intrinsic::sponentry, CGF.AllocaInt8PtrTy)); |
1131 | } else |
1132 | Arg1 = CGF.Builder.CreateCall( |
1133 | CGF.CGM.getIntrinsic(Intrinsic::frameaddress, CGF.AllocaInt8PtrTy), |
1134 | llvm::ConstantInt::get(CGF.Int32Ty, 0)); |
1135 | } |
1136 | |
1137 | // Mark the call site and declaration with ReturnsTwice. |
1138 | llvm::Type *ArgTypes[2] = {CGF.Int8PtrTy, Arg1Ty}; |
1139 | llvm::AttributeList ReturnsTwiceAttr = llvm::AttributeList::get( |
1140 | CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex, |
1141 | llvm::Attribute::ReturnsTwice); |
1142 | llvm::FunctionCallee SetJmpFn = CGF.CGM.CreateRuntimeFunction( |
1143 | llvm::FunctionType::get(Result: CGF.IntTy, Params: ArgTypes, isVarArg: IsVarArg), Name, |
1144 | ReturnsTwiceAttr, /*Local=*/true); |
1145 | |
1146 | llvm::Value *Buf = CGF.Builder.CreateBitOrPointerCast( |
1147 | CGF.EmitScalarExpr(E->getArg(0)), CGF.Int8PtrTy); |
1148 | llvm::Value *Args[] = {Buf, Arg1}; |
1149 | llvm::CallBase *CB = CGF.EmitRuntimeCallOrInvoke(SetJmpFn, Args); |
1150 | CB->setAttributes(ReturnsTwiceAttr); |
1151 | return RValue::get(V: CB); |
1152 | } |
1153 | |
1154 | // Many of MSVC builtins are on x64, ARM and AArch64; to avoid repeating code, |
1155 | // we handle them here. |
1156 | enum class CodeGenFunction::MSVCIntrin { |
1157 | _BitScanForward, |
1158 | _BitScanReverse, |
1159 | _InterlockedAnd, |
1160 | _InterlockedDecrement, |
1161 | _InterlockedExchange, |
1162 | _InterlockedExchangeAdd, |
1163 | _InterlockedExchangeSub, |
1164 | _InterlockedIncrement, |
1165 | _InterlockedOr, |
1166 | _InterlockedXor, |
1167 | _InterlockedExchangeAdd_acq, |
1168 | _InterlockedExchangeAdd_rel, |
1169 | _InterlockedExchangeAdd_nf, |
1170 | _InterlockedExchange_acq, |
1171 | _InterlockedExchange_rel, |
1172 | _InterlockedExchange_nf, |
1173 | _InterlockedCompareExchange_acq, |
1174 | _InterlockedCompareExchange_rel, |
1175 | _InterlockedCompareExchange_nf, |
1176 | _InterlockedCompareExchange128, |
1177 | _InterlockedCompareExchange128_acq, |
1178 | _InterlockedCompareExchange128_rel, |
1179 | _InterlockedCompareExchange128_nf, |
1180 | _InterlockedOr_acq, |
1181 | _InterlockedOr_rel, |
1182 | _InterlockedOr_nf, |
1183 | _InterlockedXor_acq, |
1184 | _InterlockedXor_rel, |
1185 | _InterlockedXor_nf, |
1186 | _InterlockedAnd_acq, |
1187 | _InterlockedAnd_rel, |
1188 | _InterlockedAnd_nf, |
1189 | _InterlockedIncrement_acq, |
1190 | _InterlockedIncrement_rel, |
1191 | _InterlockedIncrement_nf, |
1192 | _InterlockedDecrement_acq, |
1193 | _InterlockedDecrement_rel, |
1194 | _InterlockedDecrement_nf, |
1195 | __fastfail, |
1196 | }; |
1197 | |
1198 | static std::optional<CodeGenFunction::MSVCIntrin> |
1199 | translateArmToMsvcIntrin(unsigned BuiltinID) { |
1200 | using MSVCIntrin = CodeGenFunction::MSVCIntrin; |
1201 | switch (BuiltinID) { |
1202 | default: |
1203 | return std::nullopt; |
1204 | case clang::ARM::BI_BitScanForward: |
1205 | case clang::ARM::BI_BitScanForward64: |
1206 | return MSVCIntrin::_BitScanForward; |
1207 | case clang::ARM::BI_BitScanReverse: |
1208 | case clang::ARM::BI_BitScanReverse64: |
1209 | return MSVCIntrin::_BitScanReverse; |
1210 | case clang::ARM::BI_InterlockedAnd64: |
1211 | return MSVCIntrin::_InterlockedAnd; |
1212 | case clang::ARM::BI_InterlockedExchange64: |
1213 | return MSVCIntrin::_InterlockedExchange; |
1214 | case clang::ARM::BI_InterlockedExchangeAdd64: |
1215 | return MSVCIntrin::_InterlockedExchangeAdd; |
1216 | case clang::ARM::BI_InterlockedExchangeSub64: |
1217 | return MSVCIntrin::_InterlockedExchangeSub; |
1218 | case clang::ARM::BI_InterlockedOr64: |
1219 | return MSVCIntrin::_InterlockedOr; |
1220 | case clang::ARM::BI_InterlockedXor64: |
1221 | return MSVCIntrin::_InterlockedXor; |
1222 | case clang::ARM::BI_InterlockedDecrement64: |
1223 | return MSVCIntrin::_InterlockedDecrement; |
1224 | case clang::ARM::BI_InterlockedIncrement64: |
1225 | return MSVCIntrin::_InterlockedIncrement; |
1226 | case clang::ARM::BI_InterlockedExchangeAdd8_acq: |
1227 | case clang::ARM::BI_InterlockedExchangeAdd16_acq: |
1228 | case clang::ARM::BI_InterlockedExchangeAdd_acq: |
1229 | case clang::ARM::BI_InterlockedExchangeAdd64_acq: |
1230 | return MSVCIntrin::_InterlockedExchangeAdd_acq; |
1231 | case clang::ARM::BI_InterlockedExchangeAdd8_rel: |
1232 | case clang::ARM::BI_InterlockedExchangeAdd16_rel: |
1233 | case clang::ARM::BI_InterlockedExchangeAdd_rel: |
1234 | case clang::ARM::BI_InterlockedExchangeAdd64_rel: |
1235 | return MSVCIntrin::_InterlockedExchangeAdd_rel; |
1236 | case clang::ARM::BI_InterlockedExchangeAdd8_nf: |
1237 | case clang::ARM::BI_InterlockedExchangeAdd16_nf: |
1238 | case clang::ARM::BI_InterlockedExchangeAdd_nf: |
1239 | case clang::ARM::BI_InterlockedExchangeAdd64_nf: |
1240 | return MSVCIntrin::_InterlockedExchangeAdd_nf; |
1241 | case clang::ARM::BI_InterlockedExchange8_acq: |
1242 | case clang::ARM::BI_InterlockedExchange16_acq: |
1243 | case clang::ARM::BI_InterlockedExchange_acq: |
1244 | case clang::ARM::BI_InterlockedExchange64_acq: |
1245 | return MSVCIntrin::_InterlockedExchange_acq; |
1246 | case clang::ARM::BI_InterlockedExchange8_rel: |
1247 | case clang::ARM::BI_InterlockedExchange16_rel: |
1248 | case clang::ARM::BI_InterlockedExchange_rel: |
1249 | case clang::ARM::BI_InterlockedExchange64_rel: |
1250 | return MSVCIntrin::_InterlockedExchange_rel; |
1251 | case clang::ARM::BI_InterlockedExchange8_nf: |
1252 | case clang::ARM::BI_InterlockedExchange16_nf: |
1253 | case clang::ARM::BI_InterlockedExchange_nf: |
1254 | case clang::ARM::BI_InterlockedExchange64_nf: |
1255 | return MSVCIntrin::_InterlockedExchange_nf; |
1256 | case clang::ARM::BI_InterlockedCompareExchange8_acq: |
1257 | case clang::ARM::BI_InterlockedCompareExchange16_acq: |
1258 | case clang::ARM::BI_InterlockedCompareExchange_acq: |
1259 | case clang::ARM::BI_InterlockedCompareExchange64_acq: |
1260 | return MSVCIntrin::_InterlockedCompareExchange_acq; |
1261 | case clang::ARM::BI_InterlockedCompareExchange8_rel: |
1262 | case clang::ARM::BI_InterlockedCompareExchange16_rel: |
1263 | case clang::ARM::BI_InterlockedCompareExchange_rel: |
1264 | case clang::ARM::BI_InterlockedCompareExchange64_rel: |
1265 | return MSVCIntrin::_InterlockedCompareExchange_rel; |
1266 | case clang::ARM::BI_InterlockedCompareExchange8_nf: |
1267 | case clang::ARM::BI_InterlockedCompareExchange16_nf: |
1268 | case clang::ARM::BI_InterlockedCompareExchange_nf: |
1269 | case clang::ARM::BI_InterlockedCompareExchange64_nf: |
1270 | return MSVCIntrin::_InterlockedCompareExchange_nf; |
1271 | case clang::ARM::BI_InterlockedOr8_acq: |
1272 | case clang::ARM::BI_InterlockedOr16_acq: |
1273 | case clang::ARM::BI_InterlockedOr_acq: |
1274 | case clang::ARM::BI_InterlockedOr64_acq: |
1275 | return MSVCIntrin::_InterlockedOr_acq; |
1276 | case clang::ARM::BI_InterlockedOr8_rel: |
1277 | case clang::ARM::BI_InterlockedOr16_rel: |
1278 | case clang::ARM::BI_InterlockedOr_rel: |
1279 | case clang::ARM::BI_InterlockedOr64_rel: |
1280 | return MSVCIntrin::_InterlockedOr_rel; |
1281 | case clang::ARM::BI_InterlockedOr8_nf: |
1282 | case clang::ARM::BI_InterlockedOr16_nf: |
1283 | case clang::ARM::BI_InterlockedOr_nf: |
1284 | case clang::ARM::BI_InterlockedOr64_nf: |
1285 | return MSVCIntrin::_InterlockedOr_nf; |
1286 | case clang::ARM::BI_InterlockedXor8_acq: |
1287 | case clang::ARM::BI_InterlockedXor16_acq: |
1288 | case clang::ARM::BI_InterlockedXor_acq: |
1289 | case clang::ARM::BI_InterlockedXor64_acq: |
1290 | return MSVCIntrin::_InterlockedXor_acq; |
1291 | case clang::ARM::BI_InterlockedXor8_rel: |
1292 | case clang::ARM::BI_InterlockedXor16_rel: |
1293 | case clang::ARM::BI_InterlockedXor_rel: |
1294 | case clang::ARM::BI_InterlockedXor64_rel: |
1295 | return MSVCIntrin::_InterlockedXor_rel; |
1296 | case clang::ARM::BI_InterlockedXor8_nf: |
1297 | case clang::ARM::BI_InterlockedXor16_nf: |
1298 | case clang::ARM::BI_InterlockedXor_nf: |
1299 | case clang::ARM::BI_InterlockedXor64_nf: |
1300 | return MSVCIntrin::_InterlockedXor_nf; |
1301 | case clang::ARM::BI_InterlockedAnd8_acq: |
1302 | case clang::ARM::BI_InterlockedAnd16_acq: |
1303 | case clang::ARM::BI_InterlockedAnd_acq: |
1304 | case clang::ARM::BI_InterlockedAnd64_acq: |
1305 | return MSVCIntrin::_InterlockedAnd_acq; |
1306 | case clang::ARM::BI_InterlockedAnd8_rel: |
1307 | case clang::ARM::BI_InterlockedAnd16_rel: |
1308 | case clang::ARM::BI_InterlockedAnd_rel: |
1309 | case clang::ARM::BI_InterlockedAnd64_rel: |
1310 | return MSVCIntrin::_InterlockedAnd_rel; |
1311 | case clang::ARM::BI_InterlockedAnd8_nf: |
1312 | case clang::ARM::BI_InterlockedAnd16_nf: |
1313 | case clang::ARM::BI_InterlockedAnd_nf: |
1314 | case clang::ARM::BI_InterlockedAnd64_nf: |
1315 | return MSVCIntrin::_InterlockedAnd_nf; |
1316 | case clang::ARM::BI_InterlockedIncrement16_acq: |
1317 | case clang::ARM::BI_InterlockedIncrement_acq: |
1318 | case clang::ARM::BI_InterlockedIncrement64_acq: |
1319 | return MSVCIntrin::_InterlockedIncrement_acq; |
1320 | case clang::ARM::BI_InterlockedIncrement16_rel: |
1321 | case clang::ARM::BI_InterlockedIncrement_rel: |
1322 | case clang::ARM::BI_InterlockedIncrement64_rel: |
1323 | return MSVCIntrin::_InterlockedIncrement_rel; |
1324 | case clang::ARM::BI_InterlockedIncrement16_nf: |
1325 | case clang::ARM::BI_InterlockedIncrement_nf: |
1326 | case clang::ARM::BI_InterlockedIncrement64_nf: |
1327 | return MSVCIntrin::_InterlockedIncrement_nf; |
1328 | case clang::ARM::BI_InterlockedDecrement16_acq: |
1329 | case clang::ARM::BI_InterlockedDecrement_acq: |
1330 | case clang::ARM::BI_InterlockedDecrement64_acq: |
1331 | return MSVCIntrin::_InterlockedDecrement_acq; |
1332 | case clang::ARM::BI_InterlockedDecrement16_rel: |
1333 | case clang::ARM::BI_InterlockedDecrement_rel: |
1334 | case clang::ARM::BI_InterlockedDecrement64_rel: |
1335 | return MSVCIntrin::_InterlockedDecrement_rel; |
1336 | case clang::ARM::BI_InterlockedDecrement16_nf: |
1337 | case clang::ARM::BI_InterlockedDecrement_nf: |
1338 | case clang::ARM::BI_InterlockedDecrement64_nf: |
1339 | return MSVCIntrin::_InterlockedDecrement_nf; |
1340 | } |
1341 | llvm_unreachable("must return from switch" ); |
1342 | } |
1343 | |
1344 | static std::optional<CodeGenFunction::MSVCIntrin> |
1345 | translateAarch64ToMsvcIntrin(unsigned BuiltinID) { |
1346 | using MSVCIntrin = CodeGenFunction::MSVCIntrin; |
1347 | switch (BuiltinID) { |
1348 | default: |
1349 | return std::nullopt; |
1350 | case clang::AArch64::BI_BitScanForward: |
1351 | case clang::AArch64::BI_BitScanForward64: |
1352 | return MSVCIntrin::_BitScanForward; |
1353 | case clang::AArch64::BI_BitScanReverse: |
1354 | case clang::AArch64::BI_BitScanReverse64: |
1355 | return MSVCIntrin::_BitScanReverse; |
1356 | case clang::AArch64::BI_InterlockedAnd64: |
1357 | return MSVCIntrin::_InterlockedAnd; |
1358 | case clang::AArch64::BI_InterlockedExchange64: |
1359 | return MSVCIntrin::_InterlockedExchange; |
1360 | case clang::AArch64::BI_InterlockedExchangeAdd64: |
1361 | return MSVCIntrin::_InterlockedExchangeAdd; |
1362 | case clang::AArch64::BI_InterlockedExchangeSub64: |
1363 | return MSVCIntrin::_InterlockedExchangeSub; |
1364 | case clang::AArch64::BI_InterlockedOr64: |
1365 | return MSVCIntrin::_InterlockedOr; |
1366 | case clang::AArch64::BI_InterlockedXor64: |
1367 | return MSVCIntrin::_InterlockedXor; |
1368 | case clang::AArch64::BI_InterlockedDecrement64: |
1369 | return MSVCIntrin::_InterlockedDecrement; |
1370 | case clang::AArch64::BI_InterlockedIncrement64: |
1371 | return MSVCIntrin::_InterlockedIncrement; |
1372 | case clang::AArch64::BI_InterlockedExchangeAdd8_acq: |
1373 | case clang::AArch64::BI_InterlockedExchangeAdd16_acq: |
1374 | case clang::AArch64::BI_InterlockedExchangeAdd_acq: |
1375 | case clang::AArch64::BI_InterlockedExchangeAdd64_acq: |
1376 | return MSVCIntrin::_InterlockedExchangeAdd_acq; |
1377 | case clang::AArch64::BI_InterlockedExchangeAdd8_rel: |
1378 | case clang::AArch64::BI_InterlockedExchangeAdd16_rel: |
1379 | case clang::AArch64::BI_InterlockedExchangeAdd_rel: |
1380 | case clang::AArch64::BI_InterlockedExchangeAdd64_rel: |
1381 | return MSVCIntrin::_InterlockedExchangeAdd_rel; |
1382 | case clang::AArch64::BI_InterlockedExchangeAdd8_nf: |
1383 | case clang::AArch64::BI_InterlockedExchangeAdd16_nf: |
1384 | case clang::AArch64::BI_InterlockedExchangeAdd_nf: |
1385 | case clang::AArch64::BI_InterlockedExchangeAdd64_nf: |
1386 | return MSVCIntrin::_InterlockedExchangeAdd_nf; |
1387 | case clang::AArch64::BI_InterlockedExchange8_acq: |
1388 | case clang::AArch64::BI_InterlockedExchange16_acq: |
1389 | case clang::AArch64::BI_InterlockedExchange_acq: |
1390 | case clang::AArch64::BI_InterlockedExchange64_acq: |
1391 | return MSVCIntrin::_InterlockedExchange_acq; |
1392 | case clang::AArch64::BI_InterlockedExchange8_rel: |
1393 | case clang::AArch64::BI_InterlockedExchange16_rel: |
1394 | case clang::AArch64::BI_InterlockedExchange_rel: |
1395 | case clang::AArch64::BI_InterlockedExchange64_rel: |
1396 | return MSVCIntrin::_InterlockedExchange_rel; |
1397 | case clang::AArch64::BI_InterlockedExchange8_nf: |
1398 | case clang::AArch64::BI_InterlockedExchange16_nf: |
1399 | case clang::AArch64::BI_InterlockedExchange_nf: |
1400 | case clang::AArch64::BI_InterlockedExchange64_nf: |
1401 | return MSVCIntrin::_InterlockedExchange_nf; |
1402 | case clang::AArch64::BI_InterlockedCompareExchange8_acq: |
1403 | case clang::AArch64::BI_InterlockedCompareExchange16_acq: |
1404 | case clang::AArch64::BI_InterlockedCompareExchange_acq: |
1405 | case clang::AArch64::BI_InterlockedCompareExchange64_acq: |
1406 | return MSVCIntrin::_InterlockedCompareExchange_acq; |
1407 | case clang::AArch64::BI_InterlockedCompareExchange8_rel: |
1408 | case clang::AArch64::BI_InterlockedCompareExchange16_rel: |
1409 | case clang::AArch64::BI_InterlockedCompareExchange_rel: |
1410 | case clang::AArch64::BI_InterlockedCompareExchange64_rel: |
1411 | return MSVCIntrin::_InterlockedCompareExchange_rel; |
1412 | case clang::AArch64::BI_InterlockedCompareExchange8_nf: |
1413 | case clang::AArch64::BI_InterlockedCompareExchange16_nf: |
1414 | case clang::AArch64::BI_InterlockedCompareExchange_nf: |
1415 | case clang::AArch64::BI_InterlockedCompareExchange64_nf: |
1416 | return MSVCIntrin::_InterlockedCompareExchange_nf; |
1417 | case clang::AArch64::BI_InterlockedCompareExchange128: |
1418 | return MSVCIntrin::_InterlockedCompareExchange128; |
1419 | case clang::AArch64::BI_InterlockedCompareExchange128_acq: |
1420 | return MSVCIntrin::_InterlockedCompareExchange128_acq; |
1421 | case clang::AArch64::BI_InterlockedCompareExchange128_nf: |
1422 | return MSVCIntrin::_InterlockedCompareExchange128_nf; |
1423 | case clang::AArch64::BI_InterlockedCompareExchange128_rel: |
1424 | return MSVCIntrin::_InterlockedCompareExchange128_rel; |
1425 | case clang::AArch64::BI_InterlockedOr8_acq: |
1426 | case clang::AArch64::BI_InterlockedOr16_acq: |
1427 | case clang::AArch64::BI_InterlockedOr_acq: |
1428 | case clang::AArch64::BI_InterlockedOr64_acq: |
1429 | return MSVCIntrin::_InterlockedOr_acq; |
1430 | case clang::AArch64::BI_InterlockedOr8_rel: |
1431 | case clang::AArch64::BI_InterlockedOr16_rel: |
1432 | case clang::AArch64::BI_InterlockedOr_rel: |
1433 | case clang::AArch64::BI_InterlockedOr64_rel: |
1434 | return MSVCIntrin::_InterlockedOr_rel; |
1435 | case clang::AArch64::BI_InterlockedOr8_nf: |
1436 | case clang::AArch64::BI_InterlockedOr16_nf: |
1437 | case clang::AArch64::BI_InterlockedOr_nf: |
1438 | case clang::AArch64::BI_InterlockedOr64_nf: |
1439 | return MSVCIntrin::_InterlockedOr_nf; |
1440 | case clang::AArch64::BI_InterlockedXor8_acq: |
1441 | case clang::AArch64::BI_InterlockedXor16_acq: |
1442 | case clang::AArch64::BI_InterlockedXor_acq: |
1443 | case clang::AArch64::BI_InterlockedXor64_acq: |
1444 | return MSVCIntrin::_InterlockedXor_acq; |
1445 | case clang::AArch64::BI_InterlockedXor8_rel: |
1446 | case clang::AArch64::BI_InterlockedXor16_rel: |
1447 | case clang::AArch64::BI_InterlockedXor_rel: |
1448 | case clang::AArch64::BI_InterlockedXor64_rel: |
1449 | return MSVCIntrin::_InterlockedXor_rel; |
1450 | case clang::AArch64::BI_InterlockedXor8_nf: |
1451 | case clang::AArch64::BI_InterlockedXor16_nf: |
1452 | case clang::AArch64::BI_InterlockedXor_nf: |
1453 | case clang::AArch64::BI_InterlockedXor64_nf: |
1454 | return MSVCIntrin::_InterlockedXor_nf; |
1455 | case clang::AArch64::BI_InterlockedAnd8_acq: |
1456 | case clang::AArch64::BI_InterlockedAnd16_acq: |
1457 | case clang::AArch64::BI_InterlockedAnd_acq: |
1458 | case clang::AArch64::BI_InterlockedAnd64_acq: |
1459 | return MSVCIntrin::_InterlockedAnd_acq; |
1460 | case clang::AArch64::BI_InterlockedAnd8_rel: |
1461 | case clang::AArch64::BI_InterlockedAnd16_rel: |
1462 | case clang::AArch64::BI_InterlockedAnd_rel: |
1463 | case clang::AArch64::BI_InterlockedAnd64_rel: |
1464 | return MSVCIntrin::_InterlockedAnd_rel; |
1465 | case clang::AArch64::BI_InterlockedAnd8_nf: |
1466 | case clang::AArch64::BI_InterlockedAnd16_nf: |
1467 | case clang::AArch64::BI_InterlockedAnd_nf: |
1468 | case clang::AArch64::BI_InterlockedAnd64_nf: |
1469 | return MSVCIntrin::_InterlockedAnd_nf; |
1470 | case clang::AArch64::BI_InterlockedIncrement16_acq: |
1471 | case clang::AArch64::BI_InterlockedIncrement_acq: |
1472 | case clang::AArch64::BI_InterlockedIncrement64_acq: |
1473 | return MSVCIntrin::_InterlockedIncrement_acq; |
1474 | case clang::AArch64::BI_InterlockedIncrement16_rel: |
1475 | case clang::AArch64::BI_InterlockedIncrement_rel: |
1476 | case clang::AArch64::BI_InterlockedIncrement64_rel: |
1477 | return MSVCIntrin::_InterlockedIncrement_rel; |
1478 | case clang::AArch64::BI_InterlockedIncrement16_nf: |
1479 | case clang::AArch64::BI_InterlockedIncrement_nf: |
1480 | case clang::AArch64::BI_InterlockedIncrement64_nf: |
1481 | return MSVCIntrin::_InterlockedIncrement_nf; |
1482 | case clang::AArch64::BI_InterlockedDecrement16_acq: |
1483 | case clang::AArch64::BI_InterlockedDecrement_acq: |
1484 | case clang::AArch64::BI_InterlockedDecrement64_acq: |
1485 | return MSVCIntrin::_InterlockedDecrement_acq; |
1486 | case clang::AArch64::BI_InterlockedDecrement16_rel: |
1487 | case clang::AArch64::BI_InterlockedDecrement_rel: |
1488 | case clang::AArch64::BI_InterlockedDecrement64_rel: |
1489 | return MSVCIntrin::_InterlockedDecrement_rel; |
1490 | case clang::AArch64::BI_InterlockedDecrement16_nf: |
1491 | case clang::AArch64::BI_InterlockedDecrement_nf: |
1492 | case clang::AArch64::BI_InterlockedDecrement64_nf: |
1493 | return MSVCIntrin::_InterlockedDecrement_nf; |
1494 | } |
1495 | llvm_unreachable("must return from switch" ); |
1496 | } |
1497 | |
1498 | static std::optional<CodeGenFunction::MSVCIntrin> |
1499 | translateX86ToMsvcIntrin(unsigned BuiltinID) { |
1500 | using MSVCIntrin = CodeGenFunction::MSVCIntrin; |
1501 | switch (BuiltinID) { |
1502 | default: |
1503 | return std::nullopt; |
1504 | case clang::X86::BI_BitScanForward: |
1505 | case clang::X86::BI_BitScanForward64: |
1506 | return MSVCIntrin::_BitScanForward; |
1507 | case clang::X86::BI_BitScanReverse: |
1508 | case clang::X86::BI_BitScanReverse64: |
1509 | return MSVCIntrin::_BitScanReverse; |
1510 | case clang::X86::BI_InterlockedAnd64: |
1511 | return MSVCIntrin::_InterlockedAnd; |
1512 | case clang::X86::BI_InterlockedCompareExchange128: |
1513 | return MSVCIntrin::_InterlockedCompareExchange128; |
1514 | case clang::X86::BI_InterlockedExchange64: |
1515 | return MSVCIntrin::_InterlockedExchange; |
1516 | case clang::X86::BI_InterlockedExchangeAdd64: |
1517 | return MSVCIntrin::_InterlockedExchangeAdd; |
1518 | case clang::X86::BI_InterlockedExchangeSub64: |
1519 | return MSVCIntrin::_InterlockedExchangeSub; |
1520 | case clang::X86::BI_InterlockedOr64: |
1521 | return MSVCIntrin::_InterlockedOr; |
1522 | case clang::X86::BI_InterlockedXor64: |
1523 | return MSVCIntrin::_InterlockedXor; |
1524 | case clang::X86::BI_InterlockedDecrement64: |
1525 | return MSVCIntrin::_InterlockedDecrement; |
1526 | case clang::X86::BI_InterlockedIncrement64: |
1527 | return MSVCIntrin::_InterlockedIncrement; |
1528 | } |
1529 | llvm_unreachable("must return from switch" ); |
1530 | } |
1531 | |
1532 | // Emit an MSVC intrinsic. Assumes that arguments have *not* been evaluated. |
1533 | Value *CodeGenFunction::EmitMSVCBuiltinExpr(MSVCIntrin BuiltinID, |
1534 | const CallExpr *E) { |
1535 | switch (BuiltinID) { |
1536 | case MSVCIntrin::_BitScanForward: |
1537 | case MSVCIntrin::_BitScanReverse: { |
1538 | Address IndexAddress(EmitPointerWithAlignment(E->getArg(0))); |
1539 | Value *ArgValue = EmitScalarExpr(E->getArg(1)); |
1540 | |
1541 | llvm::Type *ArgType = ArgValue->getType(); |
1542 | llvm::Type *IndexType = IndexAddress.getElementType(); |
1543 | llvm::Type *ResultType = ConvertType(E->getType()); |
1544 | |
1545 | Value *ArgZero = llvm::Constant::getNullValue(Ty: ArgType); |
1546 | Value *ResZero = llvm::Constant::getNullValue(Ty: ResultType); |
1547 | Value *ResOne = llvm::ConstantInt::get(Ty: ResultType, V: 1); |
1548 | |
1549 | BasicBlock *Begin = Builder.GetInsertBlock(); |
1550 | BasicBlock *End = createBasicBlock("bitscan_end" , this->CurFn); |
1551 | Builder.SetInsertPoint(End); |
1552 | PHINode *Result = Builder.CreatePHI(Ty: ResultType, NumReservedValues: 2, Name: "bitscan_result" ); |
1553 | |
1554 | Builder.SetInsertPoint(Begin); |
1555 | Value *IsZero = Builder.CreateICmpEQ(LHS: ArgValue, RHS: ArgZero); |
1556 | BasicBlock *NotZero = createBasicBlock("bitscan_not_zero" , this->CurFn); |
1557 | Builder.CreateCondBr(Cond: IsZero, True: End, False: NotZero); |
1558 | Result->addIncoming(V: ResZero, BB: Begin); |
1559 | |
1560 | Builder.SetInsertPoint(NotZero); |
1561 | |
1562 | if (BuiltinID == MSVCIntrin::_BitScanForward) { |
1563 | Function *F = CGM.getIntrinsic(Intrinsic::cttz, ArgType); |
1564 | Value *ZeroCount = Builder.CreateCall(Callee: F, Args: {ArgValue, Builder.getTrue()}); |
1565 | ZeroCount = Builder.CreateIntCast(V: ZeroCount, DestTy: IndexType, isSigned: false); |
1566 | Builder.CreateStore(Val: ZeroCount, Addr: IndexAddress, IsVolatile: false); |
1567 | } else { |
1568 | unsigned ArgWidth = cast<llvm::IntegerType>(Val: ArgType)->getBitWidth(); |
1569 | Value *ArgTypeLastIndex = llvm::ConstantInt::get(Ty: IndexType, V: ArgWidth - 1); |
1570 | |
1571 | Function *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType); |
1572 | Value *ZeroCount = Builder.CreateCall(Callee: F, Args: {ArgValue, Builder.getTrue()}); |
1573 | ZeroCount = Builder.CreateIntCast(V: ZeroCount, DestTy: IndexType, isSigned: false); |
1574 | Value *Index = Builder.CreateNSWSub(LHS: ArgTypeLastIndex, RHS: ZeroCount); |
1575 | Builder.CreateStore(Val: Index, Addr: IndexAddress, IsVolatile: false); |
1576 | } |
1577 | Builder.CreateBr(Dest: End); |
1578 | Result->addIncoming(V: ResOne, BB: NotZero); |
1579 | |
1580 | Builder.SetInsertPoint(End); |
1581 | return Result; |
1582 | } |
1583 | case MSVCIntrin::_InterlockedAnd: |
1584 | return MakeBinaryAtomicValue(*this, AtomicRMWInst::And, E); |
1585 | case MSVCIntrin::_InterlockedExchange: |
1586 | return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xchg, E); |
1587 | case MSVCIntrin::_InterlockedExchangeAdd: |
1588 | return MakeBinaryAtomicValue(*this, AtomicRMWInst::Add, E); |
1589 | case MSVCIntrin::_InterlockedExchangeSub: |
1590 | return MakeBinaryAtomicValue(*this, AtomicRMWInst::Sub, E); |
1591 | case MSVCIntrin::_InterlockedOr: |
1592 | return MakeBinaryAtomicValue(*this, AtomicRMWInst::Or, E); |
1593 | case MSVCIntrin::_InterlockedXor: |
1594 | return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xor, E); |
1595 | case MSVCIntrin::_InterlockedExchangeAdd_acq: |
1596 | return MakeBinaryAtomicValue(*this, AtomicRMWInst::Add, E, |
1597 | AtomicOrdering::Acquire); |
1598 | case MSVCIntrin::_InterlockedExchangeAdd_rel: |
1599 | return MakeBinaryAtomicValue(*this, AtomicRMWInst::Add, E, |
1600 | AtomicOrdering::Release); |
1601 | case MSVCIntrin::_InterlockedExchangeAdd_nf: |
1602 | return MakeBinaryAtomicValue(*this, AtomicRMWInst::Add, E, |
1603 | AtomicOrdering::Monotonic); |
1604 | case MSVCIntrin::_InterlockedExchange_acq: |
1605 | return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xchg, E, |
1606 | AtomicOrdering::Acquire); |
1607 | case MSVCIntrin::_InterlockedExchange_rel: |
1608 | return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xchg, E, |
1609 | AtomicOrdering::Release); |
1610 | case MSVCIntrin::_InterlockedExchange_nf: |
1611 | return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xchg, E, |
1612 | AtomicOrdering::Monotonic); |
1613 | case MSVCIntrin::_InterlockedCompareExchange_acq: |
1614 | return EmitAtomicCmpXchgForMSIntrin(*this, E, AtomicOrdering::Acquire); |
1615 | case MSVCIntrin::_InterlockedCompareExchange_rel: |
1616 | return EmitAtomicCmpXchgForMSIntrin(*this, E, AtomicOrdering::Release); |
1617 | case MSVCIntrin::_InterlockedCompareExchange_nf: |
1618 | return EmitAtomicCmpXchgForMSIntrin(*this, E, AtomicOrdering::Monotonic); |
1619 | case MSVCIntrin::_InterlockedCompareExchange128: |
1620 | return EmitAtomicCmpXchg128ForMSIntrin( |
1621 | *this, E, AtomicOrdering::SequentiallyConsistent); |
1622 | case MSVCIntrin::_InterlockedCompareExchange128_acq: |
1623 | return EmitAtomicCmpXchg128ForMSIntrin(*this, E, AtomicOrdering::Acquire); |
1624 | case MSVCIntrin::_InterlockedCompareExchange128_rel: |
1625 | return EmitAtomicCmpXchg128ForMSIntrin(*this, E, AtomicOrdering::Release); |
1626 | case MSVCIntrin::_InterlockedCompareExchange128_nf: |
1627 | return EmitAtomicCmpXchg128ForMSIntrin(*this, E, AtomicOrdering::Monotonic); |
1628 | case MSVCIntrin::_InterlockedOr_acq: |
1629 | return MakeBinaryAtomicValue(*this, AtomicRMWInst::Or, E, |
1630 | AtomicOrdering::Acquire); |
1631 | case MSVCIntrin::_InterlockedOr_rel: |
1632 | return MakeBinaryAtomicValue(*this, AtomicRMWInst::Or, E, |
1633 | AtomicOrdering::Release); |
1634 | case MSVCIntrin::_InterlockedOr_nf: |
1635 | return MakeBinaryAtomicValue(*this, AtomicRMWInst::Or, E, |
1636 | AtomicOrdering::Monotonic); |
1637 | case MSVCIntrin::_InterlockedXor_acq: |
1638 | return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xor, E, |
1639 | AtomicOrdering::Acquire); |
1640 | case MSVCIntrin::_InterlockedXor_rel: |
1641 | return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xor, E, |
1642 | AtomicOrdering::Release); |
1643 | case MSVCIntrin::_InterlockedXor_nf: |
1644 | return MakeBinaryAtomicValue(*this, AtomicRMWInst::Xor, E, |
1645 | AtomicOrdering::Monotonic); |
1646 | case MSVCIntrin::_InterlockedAnd_acq: |
1647 | return MakeBinaryAtomicValue(*this, AtomicRMWInst::And, E, |
1648 | AtomicOrdering::Acquire); |
1649 | case MSVCIntrin::_InterlockedAnd_rel: |
1650 | return MakeBinaryAtomicValue(*this, AtomicRMWInst::And, E, |
1651 | AtomicOrdering::Release); |
1652 | case MSVCIntrin::_InterlockedAnd_nf: |
1653 | return MakeBinaryAtomicValue(*this, AtomicRMWInst::And, E, |
1654 | AtomicOrdering::Monotonic); |
1655 | case MSVCIntrin::_InterlockedIncrement_acq: |
1656 | return EmitAtomicIncrementValue(*this, E, AtomicOrdering::Acquire); |
1657 | case MSVCIntrin::_InterlockedIncrement_rel: |
1658 | return EmitAtomicIncrementValue(*this, E, AtomicOrdering::Release); |
1659 | case MSVCIntrin::_InterlockedIncrement_nf: |
1660 | return EmitAtomicIncrementValue(*this, E, AtomicOrdering::Monotonic); |
1661 | case MSVCIntrin::_InterlockedDecrement_acq: |
1662 | return EmitAtomicDecrementValue(*this, E, AtomicOrdering::Acquire); |
1663 | case MSVCIntrin::_InterlockedDecrement_rel: |
1664 | return EmitAtomicDecrementValue(*this, E, AtomicOrdering::Release); |
1665 | case MSVCIntrin::_InterlockedDecrement_nf: |
1666 | return EmitAtomicDecrementValue(*this, E, AtomicOrdering::Monotonic); |
1667 | |
1668 | case MSVCIntrin::_InterlockedDecrement: |
1669 | return EmitAtomicDecrementValue(*this, E); |
1670 | case MSVCIntrin::_InterlockedIncrement: |
1671 | return EmitAtomicIncrementValue(*this, E); |
1672 | |
1673 | case MSVCIntrin::__fastfail: { |
1674 | // Request immediate process termination from the kernel. The instruction |
1675 | // sequences to do this are documented on MSDN: |
1676 | // https://msdn.microsoft.com/en-us/library/dn774154.aspx |
1677 | llvm::Triple::ArchType ISA = getTarget().getTriple().getArch(); |
1678 | StringRef Asm, Constraints; |
1679 | switch (ISA) { |
1680 | default: |
1681 | ErrorUnsupported(E, "__fastfail call for this architecture" ); |
1682 | break; |
1683 | case llvm::Triple::x86: |
1684 | case llvm::Triple::x86_64: |
1685 | Asm = "int $$0x29" ; |
1686 | Constraints = "{cx}" ; |
1687 | break; |
1688 | case llvm::Triple::thumb: |
1689 | Asm = "udf #251" ; |
1690 | Constraints = "{r0}" ; |
1691 | break; |
1692 | case llvm::Triple::aarch64: |
1693 | Asm = "brk #0xF003" ; |
1694 | Constraints = "{w0}" ; |
1695 | } |
1696 | llvm::FunctionType *FTy = llvm::FunctionType::get(Result: VoidTy, Params: {Int32Ty}, isVarArg: false); |
1697 | llvm::InlineAsm *IA = |
1698 | llvm::InlineAsm::get(Ty: FTy, AsmString: Asm, Constraints, /*hasSideEffects=*/true); |
1699 | llvm::AttributeList NoReturnAttr = llvm::AttributeList::get( |
1700 | getLLVMContext(), llvm::AttributeList::FunctionIndex, |
1701 | llvm::Attribute::NoReturn); |
1702 | llvm::CallInst *CI = Builder.CreateCall(IA, EmitScalarExpr(E->getArg(0))); |
1703 | CI->setAttributes(NoReturnAttr); |
1704 | return CI; |
1705 | } |
1706 | } |
1707 | llvm_unreachable("Incorrect MSVC intrinsic!" ); |
1708 | } |
1709 | |
1710 | namespace { |
1711 | // ARC cleanup for __builtin_os_log_format |
1712 | struct CallObjCArcUse final : EHScopeStack::Cleanup { |
1713 | CallObjCArcUse(llvm::Value *object) : object(object) {} |
1714 | llvm::Value *object; |
1715 | |
1716 | void Emit(CodeGenFunction &CGF, Flags flags) override { |
1717 | CGF.EmitARCIntrinsicUse(object); |
1718 | } |
1719 | }; |
1720 | } |
1721 | |
1722 | Value *CodeGenFunction::EmitCheckedArgForBuiltin(const Expr *E, |
1723 | BuiltinCheckKind Kind) { |
1724 | assert((Kind == BCK_CLZPassedZero || Kind == BCK_CTZPassedZero) |
1725 | && "Unsupported builtin check kind" ); |
1726 | |
1727 | Value *ArgValue = EmitScalarExpr(E); |
1728 | if (!SanOpts.has(SanitizerKind::Builtin) || !getTarget().isCLZForZeroUndef()) |
1729 | return ArgValue; |
1730 | |
1731 | SanitizerScope SanScope(this); |
1732 | Value *Cond = Builder.CreateICmpNE( |
1733 | LHS: ArgValue, RHS: llvm::Constant::getNullValue(Ty: ArgValue->getType())); |
1734 | EmitCheck(std::make_pair(Cond, SanitizerKind::Builtin), |
1735 | SanitizerHandler::InvalidBuiltin, |
1736 | {EmitCheckSourceLocation(E->getExprLoc()), |
1737 | llvm::ConstantInt::get(Builder.getInt8Ty(), Kind)}, |
1738 | std::nullopt); |
1739 | return ArgValue; |
1740 | } |
1741 | |
1742 | /// Get the argument type for arguments to os_log_helper. |
1743 | static CanQualType getOSLogArgType(ASTContext &C, int Size) { |
1744 | QualType UnsignedTy = C.getIntTypeForBitwidth(Size * 8, /*Signed=*/false); |
1745 | return C.getCanonicalType(UnsignedTy); |
1746 | } |
1747 | |
1748 | llvm::Function *CodeGenFunction::generateBuiltinOSLogHelperFunction( |
1749 | const analyze_os_log::OSLogBufferLayout &Layout, |
1750 | CharUnits BufferAlignment) { |
1751 | ASTContext &Ctx = getContext(); |
1752 | |
1753 | llvm::SmallString<64> Name; |
1754 | { |
1755 | raw_svector_ostream OS(Name); |
1756 | OS << "__os_log_helper" ; |
1757 | OS << "_" << BufferAlignment.getQuantity(); |
1758 | OS << "_" << int(Layout.getSummaryByte()); |
1759 | OS << "_" << int(Layout.getNumArgsByte()); |
1760 | for (const auto &Item : Layout.Items) |
1761 | OS << "_" << int(Item.getSizeByte()) << "_" |
1762 | << int(Item.getDescriptorByte()); |
1763 | } |
1764 | |
1765 | if (llvm::Function *F = CGM.getModule().getFunction(Name)) |
1766 | return F; |
1767 | |
1768 | llvm::SmallVector<QualType, 4> ArgTys; |
1769 | FunctionArgList Args; |
1770 | Args.push_back(ImplicitParamDecl::Create( |
1771 | Ctx, nullptr, SourceLocation(), &Ctx.Idents.get("buffer" ), Ctx.VoidPtrTy, |
1772 | ImplicitParamDecl::Other)); |
1773 | ArgTys.emplace_back(Ctx.VoidPtrTy); |
1774 | |
1775 | for (unsigned int I = 0, E = Layout.Items.size(); I < E; ++I) { |
1776 | char Size = Layout.Items[I].getSizeByte(); |
1777 | if (!Size) |
1778 | continue; |
1779 | |
1780 | QualType ArgTy = getOSLogArgType(Ctx, Size); |
1781 | Args.push_back(ImplicitParamDecl::Create( |
1782 | Ctx, nullptr, SourceLocation(), |
1783 | &Ctx.Idents.get(std::string("arg" ) + llvm::to_string(I)), ArgTy, |
1784 | ImplicitParamDecl::Other)); |
1785 | ArgTys.emplace_back(ArgTy); |
1786 | } |
1787 | |
1788 | QualType ReturnTy = Ctx.VoidTy; |
1789 | |
1790 | // The helper function has linkonce_odr linkage to enable the linker to merge |
1791 | // identical functions. To ensure the merging always happens, 'noinline' is |
1792 | // attached to the function when compiling with -Oz. |
1793 | const CGFunctionInfo &FI = |
1794 | CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, Args); |
1795 | llvm::FunctionType *FuncTy = CGM.getTypes().GetFunctionType(Info: FI); |
1796 | llvm::Function *Fn = llvm::Function::Create( |
1797 | Ty: FuncTy, Linkage: llvm::GlobalValue::LinkOnceODRLinkage, N: Name, M: &CGM.getModule()); |
1798 | Fn->setVisibility(llvm::GlobalValue::HiddenVisibility); |
1799 | CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, Fn, /*IsThunk=*/false); |
1800 | CGM.SetLLVMFunctionAttributesForDefinition(D: nullptr, F: Fn); |
1801 | Fn->setDoesNotThrow(); |
1802 | |
1803 | // Attach 'noinline' at -Oz. |
1804 | if (CGM.getCodeGenOpts().OptimizeSize == 2) |
1805 | Fn->addFnAttr(llvm::Attribute::NoInline); |
1806 | |
1807 | auto NL = ApplyDebugLocation::CreateEmpty(CGF&: *this); |
1808 | StartFunction(GlobalDecl(), ReturnTy, Fn, FI, Args); |
1809 | |
1810 | // Create a scope with an artificial location for the body of this function. |
1811 | auto AL = ApplyDebugLocation::CreateArtificial(CGF&: *this); |
1812 | |
1813 | CharUnits Offset; |
1814 | Address BufAddr = |
1815 | Address(Builder.CreateLoad(GetAddrOfLocalVar(Args[0]), "buf" ), Int8Ty, |
1816 | BufferAlignment); |
1817 | Builder.CreateStore(Builder.getInt8(Layout.getSummaryByte()), |
1818 | Builder.CreateConstByteGEP(BufAddr, Offset++, "summary" )); |
1819 | Builder.CreateStore(Builder.getInt8(Layout.getNumArgsByte()), |
1820 | Builder.CreateConstByteGEP(BufAddr, Offset++, "numArgs" )); |
1821 | |
1822 | unsigned I = 1; |
1823 | for (const auto &Item : Layout.Items) { |
1824 | Builder.CreateStore( |
1825 | Builder.getInt8(Item.getDescriptorByte()), |
1826 | Builder.CreateConstByteGEP(BufAddr, Offset++, "argDescriptor" )); |
1827 | Builder.CreateStore( |
1828 | Builder.getInt8(Item.getSizeByte()), |
1829 | Builder.CreateConstByteGEP(BufAddr, Offset++, "argSize" )); |
1830 | |
1831 | CharUnits Size = Item.size(); |
1832 | if (!Size.getQuantity()) |
1833 | continue; |
1834 | |
1835 | Address Arg = GetAddrOfLocalVar(Args[I]); |
1836 | Address Addr = Builder.CreateConstByteGEP(BufAddr, Offset, "argData" ); |
1837 | Addr = |
1838 | Builder.CreateElementBitCast(Addr, Arg.getElementType(), "argDataCast" ); |
1839 | Builder.CreateStore(Builder.CreateLoad(Arg), Addr); |
1840 | Offset += Size; |
1841 | ++I; |
1842 | } |
1843 | |
1844 | FinishFunction(); |
1845 | |
1846 | return Fn; |
1847 | } |
1848 | |
1849 | RValue CodeGenFunction::emitBuiltinOSLogFormat(const CallExpr &E) { |
1850 | assert(E.getNumArgs() >= 2 && |
1851 | "__builtin_os_log_format takes at least 2 arguments" ); |
1852 | ASTContext &Ctx = getContext(); |
1853 | analyze_os_log::OSLogBufferLayout Layout; |
1854 | analyze_os_log::computeOSLogBufferLayout(Ctx, &E, Layout); |
1855 | Address BufAddr = EmitPointerWithAlignment(E.getArg(0)); |
1856 | llvm::SmallVector<llvm::Value *, 4> RetainableOperands; |
1857 | |
1858 | // Ignore argument 1, the format string. It is not currently used. |
1859 | CallArgList Args; |
1860 | Args.add(rvalue: RValue::get(V: BufAddr.getPointer()), type: Ctx.VoidPtrTy); |
1861 | |
1862 | for (const auto &Item : Layout.Items) { |
1863 | int Size = Item.getSizeByte(); |
1864 | if (!Size) |
1865 | continue; |
1866 | |
1867 | llvm::Value *ArgVal; |
1868 | |
1869 | if (Item.getKind() == analyze_os_log::OSLogBufferItem::MaskKind) { |
1870 | uint64_t Val = 0; |
1871 | for (unsigned I = 0, E = Item.getMaskType().size(); I < E; ++I) |
1872 | Val |= ((uint64_t)Item.getMaskType()[I]) << I * 8; |
1873 | ArgVal = llvm::Constant::getIntegerValue(Int64Ty, llvm::APInt(64, Val)); |
1874 | } else if (const Expr *TheExpr = Item.getExpr()) { |
1875 | ArgVal = EmitScalarExpr(TheExpr, /*Ignore*/ false); |
1876 | |
1877 | // If a temporary object that requires destruction after the full |
1878 | // expression is passed, push a lifetime-extended cleanup to extend its |
1879 | // lifetime to the end of the enclosing block scope. |
1880 | auto LifetimeExtendObject = [&](const Expr *E) { |
1881 | E = E->IgnoreParenCasts(); |
1882 | // Extend lifetimes of objects returned by function calls and message |
1883 | // sends. |
1884 | |
1885 | // FIXME: We should do this in other cases in which temporaries are |
1886 | // created including arguments of non-ARC types (e.g., C++ |
1887 | // temporaries). |
1888 | if (isa<CallExpr>(E) || isa<ObjCMessageExpr>(E)) |
1889 | return true; |
1890 | return false; |
1891 | }; |
1892 | |
1893 | if (TheExpr->getType()->isObjCRetainableType() && |
1894 | getLangOpts().ObjCAutoRefCount && LifetimeExtendObject(TheExpr)) { |
1895 | assert(getEvaluationKind(TheExpr->getType()) == TEK_Scalar && |
1896 | "Only scalar can be a ObjC retainable type" ); |
1897 | if (!isa<Constant>(ArgVal)) { |
1898 | CleanupKind Cleanup = getARCCleanupKind(); |
1899 | QualType Ty = TheExpr->getType(); |
1900 | Address Alloca = Address::invalid(); |
1901 | Address Addr = CreateMemTemp(Ty, "os.log.arg" , &Alloca); |
1902 | ArgVal = EmitARCRetain(Ty, ArgVal); |
1903 | Builder.CreateStore(ArgVal, Addr); |
1904 | pushLifetimeExtendedDestroy(Cleanup, Alloca, Ty, |
1905 | CodeGenFunction::destroyARCStrongPrecise, |
1906 | Cleanup & EHCleanup); |
1907 | |
1908 | // Push a clang.arc.use call to ensure ARC optimizer knows that the |
1909 | // argument has to be alive. |
1910 | if (CGM.getCodeGenOpts().OptimizationLevel != 0) |
1911 | pushCleanupAfterFullExpr<CallObjCArcUse>(Cleanup, ArgVal); |
1912 | } |
1913 | } |
1914 | } else { |
1915 | ArgVal = Builder.getInt32(Item.getConstValue().getQuantity()); |
1916 | } |
1917 | |
1918 | unsigned ArgValSize = |
1919 | CGM.getDataLayout().getTypeSizeInBits(ArgVal->getType()); |
1920 | llvm::IntegerType *IntTy = llvm::Type::getIntNTy(getLLVMContext(), |
1921 | ArgValSize); |
1922 | ArgVal = Builder.CreateBitOrPointerCast(ArgVal, IntTy); |
1923 | CanQualType ArgTy = getOSLogArgType(Ctx, Size); |
1924 | // If ArgVal has type x86_fp80, zero-extend ArgVal. |
1925 | ArgVal = Builder.CreateZExtOrBitCast(ArgVal, ConvertType(ArgTy)); |
1926 | Args.add(RValue::get(ArgVal), ArgTy); |
1927 | } |
1928 | |
1929 | const CGFunctionInfo &FI = |
1930 | CGM.getTypes().arrangeBuiltinFunctionCall(resultType: Ctx.VoidTy, args: Args); |
1931 | llvm::Function *F = CodeGenFunction(CGM).generateBuiltinOSLogHelperFunction( |
1932 | Layout, BufAddr.getAlignment()); |
1933 | EmitCall(CallInfo: FI, Callee: CGCallee::forDirect(functionPtr: F), ReturnValue: ReturnValueSlot(), Args); |
1934 | return RValue::get(V: BufAddr.getPointer()); |
1935 | } |
1936 | |
1937 | static bool isSpecialUnsignedMultiplySignedResult( |
1938 | unsigned BuiltinID, WidthAndSignedness Op1Info, WidthAndSignedness Op2Info, |
1939 | WidthAndSignedness ResultInfo) { |
1940 | return BuiltinID == Builtin::BI__builtin_mul_overflow && |
1941 | Op1Info.Width == Op2Info.Width && Op2Info.Width == ResultInfo.Width && |
1942 | !Op1Info.Signed && !Op2Info.Signed && ResultInfo.Signed; |
1943 | } |
1944 | |
1945 | static RValue EmitCheckedUnsignedMultiplySignedResult( |
1946 | CodeGenFunction &CGF, const clang::Expr *Op1, WidthAndSignedness Op1Info, |
1947 | const clang::Expr *Op2, WidthAndSignedness Op2Info, |
1948 | const clang::Expr *ResultArg, QualType ResultQTy, |
1949 | WidthAndSignedness ResultInfo) { |
1950 | assert(isSpecialUnsignedMultiplySignedResult( |
1951 | Builtin::BI__builtin_mul_overflow, Op1Info, Op2Info, ResultInfo) && |
1952 | "Cannot specialize this multiply" ); |
1953 | |
1954 | llvm::Value *V1 = CGF.EmitScalarExpr(E: Op1); |
1955 | llvm::Value *V2 = CGF.EmitScalarExpr(E: Op2); |
1956 | |
1957 | llvm::Value *HasOverflow; |
1958 | llvm::Value *Result = EmitOverflowIntrinsic( |
1959 | CGF, llvm::Intrinsic::umul_with_overflow, V1, V2, HasOverflow); |
1960 | |
1961 | // The intrinsic call will detect overflow when the value is > UINT_MAX, |
1962 | // however, since the original builtin had a signed result, we need to report |
1963 | // an overflow when the result is greater than INT_MAX. |
1964 | auto IntMax = llvm::APInt::getSignedMaxValue(numBits: ResultInfo.Width); |
1965 | llvm::Value *IntMaxValue = llvm::ConstantInt::get(Ty: Result->getType(), V: IntMax); |
1966 | |
1967 | llvm::Value *IntMaxOverflow = CGF.Builder.CreateICmpUGT(LHS: Result, RHS: IntMaxValue); |
1968 | HasOverflow = CGF.Builder.CreateOr(LHS: HasOverflow, RHS: IntMaxOverflow); |
1969 | |
1970 | bool isVolatile = |
1971 | ResultArg->getType()->getPointeeType().isVolatileQualified(); |
1972 | Address ResultPtr = CGF.EmitPointerWithAlignment(Addr: ResultArg); |
1973 | CGF.Builder.CreateStore(CGF.EmitToMemory(Result, ResultQTy), ResultPtr, |
1974 | isVolatile); |
1975 | return RValue::get(V: HasOverflow); |
1976 | } |
1977 | |
1978 | /// Determine if a binop is a checked mixed-sign multiply we can specialize. |
1979 | static bool isSpecialMixedSignMultiply(unsigned BuiltinID, |
1980 | WidthAndSignedness Op1Info, |
1981 | WidthAndSignedness Op2Info, |
1982 | WidthAndSignedness ResultInfo) { |
1983 | return BuiltinID == Builtin::BI__builtin_mul_overflow && |
1984 | std::max(Op1Info.Width, Op2Info.Width) >= ResultInfo.Width && |
1985 | Op1Info.Signed != Op2Info.Signed; |
1986 | } |
1987 | |
1988 | /// Emit a checked mixed-sign multiply. This is a cheaper specialization of |
1989 | /// the generic checked-binop irgen. |
1990 | static RValue |
1991 | EmitCheckedMixedSignMultiply(CodeGenFunction &CGF, const clang::Expr *Op1, |
1992 | WidthAndSignedness Op1Info, const clang::Expr *Op2, |
1993 | WidthAndSignedness Op2Info, |
1994 | const clang::Expr *ResultArg, QualType ResultQTy, |
1995 | WidthAndSignedness ResultInfo) { |
1996 | assert(isSpecialMixedSignMultiply(Builtin::BI__builtin_mul_overflow, Op1Info, |
1997 | Op2Info, ResultInfo) && |
1998 | "Not a mixed-sign multipliction we can specialize" ); |
1999 | |
2000 | // Emit the signed and unsigned operands. |
2001 | const clang::Expr *SignedOp = Op1Info.Signed ? Op1 : Op2; |
2002 | const clang::Expr *UnsignedOp = Op1Info.Signed ? Op2 : Op1; |
2003 | llvm::Value *Signed = CGF.EmitScalarExpr(E: SignedOp); |
2004 | llvm::Value *Unsigned = CGF.EmitScalarExpr(E: UnsignedOp); |
2005 | unsigned SignedOpWidth = Op1Info.Signed ? Op1Info.Width : Op2Info.Width; |
2006 | unsigned UnsignedOpWidth = Op1Info.Signed ? Op2Info.Width : Op1Info.Width; |
2007 | |
2008 | // One of the operands may be smaller than the other. If so, [s|z]ext it. |
2009 | if (SignedOpWidth < UnsignedOpWidth) |
2010 | Signed = CGF.Builder.CreateSExt(V: Signed, DestTy: Unsigned->getType(), Name: "op.sext" ); |
2011 | if (UnsignedOpWidth < SignedOpWidth) |
2012 | Unsigned = CGF.Builder.CreateZExt(V: Unsigned, DestTy: Signed->getType(), Name: "op.zext" ); |
2013 | |
2014 | llvm::Type *OpTy = Signed->getType(); |
2015 | llvm::Value *Zero = llvm::Constant::getNullValue(Ty: OpTy); |
2016 | Address ResultPtr = CGF.EmitPointerWithAlignment(Addr: ResultArg); |
2017 | llvm::Type *ResTy = ResultPtr.getElementType(); |
2018 | unsigned OpWidth = std::max(a: Op1Info.Width, b: Op2Info.Width); |
2019 | |
2020 | // Take the absolute value of the signed operand. |
2021 | llvm::Value *IsNegative = CGF.Builder.CreateICmpSLT(LHS: Signed, RHS: Zero); |
2022 | llvm::Value *AbsOfNegative = CGF.Builder.CreateSub(LHS: Zero, RHS: Signed); |
2023 | llvm::Value *AbsSigned = |
2024 | CGF.Builder.CreateSelect(C: IsNegative, True: AbsOfNegative, False: Signed); |
2025 | |
2026 | // Perform a checked unsigned multiplication. |
2027 | llvm::Value *UnsignedOverflow; |
2028 | llvm::Value *UnsignedResult = |
2029 | EmitOverflowIntrinsic(CGF, llvm::Intrinsic::umul_with_overflow, AbsSigned, |
2030 | Unsigned, UnsignedOverflow); |
2031 | |
2032 | llvm::Value *Overflow, *Result; |
2033 | if (ResultInfo.Signed) { |
2034 | // Signed overflow occurs if the result is greater than INT_MAX or lesser |
2035 | // than INT_MIN, i.e when |Result| > (INT_MAX + IsNegative). |
2036 | auto IntMax = |
2037 | llvm::APInt::getSignedMaxValue(numBits: ResultInfo.Width).zext(width: OpWidth); |
2038 | llvm::Value *MaxResult = |
2039 | CGF.Builder.CreateAdd(LHS: llvm::ConstantInt::get(Ty: OpTy, V: IntMax), |
2040 | RHS: CGF.Builder.CreateZExt(V: IsNegative, DestTy: OpTy)); |
2041 | llvm::Value *SignedOverflow = |
2042 | CGF.Builder.CreateICmpUGT(LHS: UnsignedResult, RHS: MaxResult); |
2043 | Overflow = CGF.Builder.CreateOr(LHS: UnsignedOverflow, RHS: SignedOverflow); |
2044 | |
2045 | // Prepare the signed result (possibly by negating it). |
2046 | llvm::Value *NegativeResult = CGF.Builder.CreateNeg(V: UnsignedResult); |
2047 | llvm::Value *SignedResult = |
2048 | CGF.Builder.CreateSelect(C: IsNegative, True: NegativeResult, False: UnsignedResult); |
2049 | Result = CGF.Builder.CreateTrunc(V: SignedResult, DestTy: ResTy); |
2050 | } else { |
2051 | // Unsigned overflow occurs if the result is < 0 or greater than UINT_MAX. |
2052 | llvm::Value *Underflow = CGF.Builder.CreateAnd( |
2053 | LHS: IsNegative, RHS: CGF.Builder.CreateIsNotNull(Arg: UnsignedResult)); |
2054 | Overflow = CGF.Builder.CreateOr(LHS: UnsignedOverflow, RHS: Underflow); |
2055 | if (ResultInfo.Width < OpWidth) { |
2056 | auto IntMax = |
2057 | llvm::APInt::getMaxValue(numBits: ResultInfo.Width).zext(width: OpWidth); |
2058 | llvm::Value *TruncOverflow = CGF.Builder.CreateICmpUGT( |
2059 | LHS: UnsignedResult, RHS: llvm::ConstantInt::get(Ty: OpTy, V: IntMax)); |
2060 | Overflow = CGF.Builder.CreateOr(LHS: Overflow, RHS: TruncOverflow); |
2061 | } |
2062 | |
2063 | // Negate the product if it would be negative in infinite precision. |
2064 | Result = CGF.Builder.CreateSelect( |
2065 | C: IsNegative, True: CGF.Builder.CreateNeg(V: UnsignedResult), False: UnsignedResult); |
2066 | |
2067 | Result = CGF.Builder.CreateTrunc(V: Result, DestTy: ResTy); |
2068 | } |
2069 | assert(Overflow && Result && "Missing overflow or result" ); |
2070 | |
2071 | bool isVolatile = |
2072 | ResultArg->getType()->getPointeeType().isVolatileQualified(); |
2073 | CGF.Builder.CreateStore(CGF.EmitToMemory(Result, ResultQTy), ResultPtr, |
2074 | isVolatile); |
2075 | return RValue::get(V: Overflow); |
2076 | } |
2077 | |
2078 | static bool |
2079 | TypeRequiresBuiltinLaunderImp(const ASTContext &Ctx, QualType Ty, |
2080 | llvm::SmallPtrSetImpl<const Decl *> &Seen) { |
2081 | if (const auto *Arr = Ctx.getAsArrayType(Ty)) |
2082 | Ty = Ctx.getBaseElementType(Arr); |
2083 | |
2084 | const auto *Record = Ty->getAsCXXRecordDecl(); |
2085 | if (!Record) |
2086 | return false; |
2087 | |
2088 | // We've already checked this type, or are in the process of checking it. |
2089 | if (!Seen.insert(Record).second) |
2090 | return false; |
2091 | |
2092 | assert(Record->hasDefinition() && |
2093 | "Incomplete types should already be diagnosed" ); |
2094 | |
2095 | if (Record->isDynamicClass()) |
2096 | return true; |
2097 | |
2098 | for (FieldDecl *F : Record->fields()) { |
2099 | if (TypeRequiresBuiltinLaunderImp(Ctx, F->getType(), Seen)) |
2100 | return true; |
2101 | } |
2102 | return false; |
2103 | } |
2104 | |
2105 | /// Determine if the specified type requires laundering by checking if it is a |
2106 | /// dynamic class type or contains a subobject which is a dynamic class type. |
2107 | static bool TypeRequiresBuiltinLaunder(CodeGenModule &CGM, QualType Ty) { |
2108 | if (!CGM.getCodeGenOpts().StrictVTablePointers) |
2109 | return false; |
2110 | llvm::SmallPtrSet<const Decl *, 16> Seen; |
2111 | return TypeRequiresBuiltinLaunderImp(CGM.getContext(), Ty, Seen); |
2112 | } |
2113 | |
2114 | RValue CodeGenFunction::emitRotate(const CallExpr *E, bool IsRotateRight) { |
2115 | llvm::Value *Src = EmitScalarExpr(E->getArg(0)); |
2116 | llvm::Value *ShiftAmt = EmitScalarExpr(E->getArg(1)); |
2117 | |
2118 | // The builtin's shift arg may have a different type than the source arg and |
2119 | // result, but the LLVM intrinsic uses the same type for all values. |
2120 | llvm::Type *Ty = Src->getType(); |
2121 | ShiftAmt = Builder.CreateIntCast(V: ShiftAmt, DestTy: Ty, isSigned: false); |
2122 | |
2123 | // Rotate is a special case of LLVM funnel shift - 1st 2 args are the same. |
2124 | unsigned IID = IsRotateRight ? Intrinsic::fshr : Intrinsic::fshl; |
2125 | Function *F = CGM.getIntrinsic(IID, Ty); |
2126 | return RValue::get(V: Builder.CreateCall(Callee: F, Args: { Src, Src, ShiftAmt })); |
2127 | } |
2128 | |
2129 | // Map math builtins for long-double to f128 version. |
2130 | static unsigned mutateLongDoubleBuiltin(unsigned BuiltinID) { |
2131 | switch (BuiltinID) { |
2132 | #define MUTATE_LDBL(func) \ |
2133 | case Builtin::BI__builtin_##func##l: \ |
2134 | return Builtin::BI__builtin_##func##f128; |
2135 | MUTATE_LDBL(sqrt) |
2136 | MUTATE_LDBL(cbrt) |
2137 | MUTATE_LDBL(fabs) |
2138 | MUTATE_LDBL(log) |
2139 | MUTATE_LDBL(log2) |
2140 | MUTATE_LDBL(log10) |
2141 | MUTATE_LDBL(log1p) |
2142 | MUTATE_LDBL(logb) |
2143 | MUTATE_LDBL(exp) |
2144 | MUTATE_LDBL(exp2) |
2145 | MUTATE_LDBL(expm1) |
2146 | MUTATE_LDBL(fdim) |
2147 | MUTATE_LDBL(hypot) |
2148 | MUTATE_LDBL(ilogb) |
2149 | MUTATE_LDBL(pow) |
2150 | MUTATE_LDBL(fmin) |
2151 | MUTATE_LDBL(fmax) |
2152 | MUTATE_LDBL(ceil) |
2153 | MUTATE_LDBL(trunc) |
2154 | MUTATE_LDBL(rint) |
2155 | MUTATE_LDBL(nearbyint) |
2156 | MUTATE_LDBL(round) |
2157 | MUTATE_LDBL(floor) |
2158 | MUTATE_LDBL(lround) |
2159 | MUTATE_LDBL(llround) |
2160 | MUTATE_LDBL(lrint) |
2161 | MUTATE_LDBL(llrint) |
2162 | MUTATE_LDBL(fmod) |
2163 | MUTATE_LDBL(modf) |
2164 | MUTATE_LDBL(nan) |
2165 | MUTATE_LDBL(nans) |
2166 | MUTATE_LDBL(inf) |
2167 | MUTATE_LDBL(fma) |
2168 | MUTATE_LDBL(sin) |
2169 | MUTATE_LDBL(cos) |
2170 | MUTATE_LDBL(tan) |
2171 | MUTATE_LDBL(sinh) |
2172 | MUTATE_LDBL(cosh) |
2173 | MUTATE_LDBL(tanh) |
2174 | MUTATE_LDBL(asin) |
2175 | MUTATE_LDBL(acos) |
2176 | MUTATE_LDBL(atan) |
2177 | MUTATE_LDBL(asinh) |
2178 | MUTATE_LDBL(acosh) |
2179 | MUTATE_LDBL(atanh) |
2180 | MUTATE_LDBL(atan2) |
2181 | MUTATE_LDBL(erf) |
2182 | MUTATE_LDBL(erfc) |
2183 | MUTATE_LDBL(ldexp) |
2184 | MUTATE_LDBL(frexp) |
2185 | MUTATE_LDBL(huge_val) |
2186 | MUTATE_LDBL(copysign) |
2187 | MUTATE_LDBL(nextafter) |
2188 | MUTATE_LDBL(nexttoward) |
2189 | MUTATE_LDBL(remainder) |
2190 | MUTATE_LDBL(remquo) |
2191 | MUTATE_LDBL(scalbln) |
2192 | MUTATE_LDBL(scalbn) |
2193 | MUTATE_LDBL(tgamma) |
2194 | MUTATE_LDBL(lgamma) |
2195 | #undef MUTATE_LDBL |
2196 | default: |
2197 | return BuiltinID; |
2198 | } |
2199 | } |
2200 | |
2201 | RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID, |
2202 | const CallExpr *E, |
2203 | ReturnValueSlot ReturnValue) { |
2204 | const FunctionDecl *FD = GD.getDecl()->getAsFunction(); |
2205 | // See if we can constant fold this builtin. If so, don't emit it at all. |
2206 | // TODO: Extend this handling to all builtin calls that we can constant-fold. |
2207 | Expr::EvalResult Result; |
2208 | if (E->isPRValue() && E->EvaluateAsRValue(Result, CGM.getContext()) && |
2209 | !Result.hasSideEffects()) { |
2210 | if (Result.Val.isInt()) |
2211 | return RValue::get(llvm::ConstantInt::get(getLLVMContext(), |
2212 | Result.Val.getInt())); |
2213 | if (Result.Val.isFloat()) |
2214 | return RValue::get(llvm::ConstantFP::get(getLLVMContext(), |
2215 | Result.Val.getFloat())); |
2216 | } |
2217 | |
2218 | // If current long-double semantics is IEEE 128-bit, replace math builtins |
2219 | // of long-double with f128 equivalent. |
2220 | // TODO: This mutation should also be applied to other targets other than PPC, |
2221 | // after backend supports IEEE 128-bit style libcalls. |
2222 | if (getTarget().getTriple().isPPC64() && |
2223 | &getTarget().getLongDoubleFormat() == &llvm::APFloat::IEEEquad()) |
2224 | BuiltinID = mutateLongDoubleBuiltin(BuiltinID); |
2225 | |
2226 | // If the builtin has been declared explicitly with an assembler label, |
2227 | // disable the specialized emitting below. Ideally we should communicate the |
2228 | // rename in IR, or at least avoid generating the intrinsic calls that are |
2229 | // likely to get lowered to the renamed library functions. |
2230 | const unsigned BuiltinIDIfNoAsmLabel = |
2231 | FD->hasAttr<AsmLabelAttr>() ? 0 : BuiltinID; |
2232 | |
2233 | // There are LLVM math intrinsics/instructions corresponding to math library |
2234 | // functions except the LLVM op will never set errno while the math library |
2235 | // might. Also, math builtins have the same semantics as their math library |
2236 | // twins. Thus, we can transform math library and builtin calls to their |
2237 | // LLVM counterparts if the call is marked 'const' (known to never set errno). |
2238 | // In case FP exceptions are enabled, the experimental versions of the |
2239 | // intrinsics model those. |
2240 | bool ConstWithoutErrnoAndExceptions = |
2241 | getContext().BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID); |
2242 | bool ConstWithoutExceptions = |
2243 | getContext().BuiltinInfo.isConstWithoutExceptions(BuiltinID); |
2244 | if (FD->hasAttr<ConstAttr>() || |
2245 | ((ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) && |
2246 | (!ConstWithoutErrnoAndExceptions || (!getLangOpts().MathErrno)))) { |
2247 | switch (BuiltinIDIfNoAsmLabel) { |
2248 | case Builtin::BIceil: |
2249 | case Builtin::BIceilf: |
2250 | case Builtin::BIceill: |
2251 | case Builtin::BI__builtin_ceil: |
2252 | case Builtin::BI__builtin_ceilf: |
2253 | case Builtin::BI__builtin_ceilf16: |
2254 | case Builtin::BI__builtin_ceill: |
2255 | case Builtin::BI__builtin_ceilf128: |
2256 | return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E, |
2257 | Intrinsic::ceil, |
2258 | Intrinsic::experimental_constrained_ceil)); |
2259 | |
2260 | case Builtin::BIcopysign: |
2261 | case Builtin::BIcopysignf: |
2262 | case Builtin::BIcopysignl: |
2263 | case Builtin::BI__builtin_copysign: |
2264 | case Builtin::BI__builtin_copysignf: |
2265 | case Builtin::BI__builtin_copysignf16: |
2266 | case Builtin::BI__builtin_copysignl: |
2267 | case Builtin::BI__builtin_copysignf128: |
2268 | return RValue::get(emitBinaryBuiltin(*this, E, Intrinsic::copysign)); |
2269 | |
2270 | case Builtin::BIcos: |
2271 | case Builtin::BIcosf: |
2272 | case Builtin::BIcosl: |
2273 | case Builtin::BI__builtin_cos: |
2274 | case Builtin::BI__builtin_cosf: |
2275 | case Builtin::BI__builtin_cosf16: |
2276 | case Builtin::BI__builtin_cosl: |
2277 | case Builtin::BI__builtin_cosf128: |
2278 | return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E, |
2279 | Intrinsic::cos, |
2280 | Intrinsic::experimental_constrained_cos)); |
2281 | |
2282 | case Builtin::BIexp: |
2283 | case Builtin::BIexpf: |
2284 | case Builtin::BIexpl: |
2285 | case Builtin::BI__builtin_exp: |
2286 | case Builtin::BI__builtin_expf: |
2287 | case Builtin::BI__builtin_expf16: |
2288 | case Builtin::BI__builtin_expl: |
2289 | case Builtin::BI__builtin_expf128: |
2290 | return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E, |
2291 | Intrinsic::exp, |
2292 | Intrinsic::experimental_constrained_exp)); |
2293 | |
2294 | case Builtin::BIexp2: |
2295 | case Builtin::BIexp2f: |
2296 | case Builtin::BIexp2l: |
2297 | case Builtin::BI__builtin_exp2: |
2298 | case Builtin::BI__builtin_exp2f: |
2299 | case Builtin::BI__builtin_exp2f16: |
2300 | case Builtin::BI__builtin_exp2l: |
2301 | case Builtin::BI__builtin_exp2f128: |
2302 | return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E, |
2303 | Intrinsic::exp2, |
2304 | Intrinsic::experimental_constrained_exp2)); |
2305 | |
2306 | case Builtin::BIfabs: |
2307 | case Builtin::BIfabsf: |
2308 | case Builtin::BIfabsl: |
2309 | case Builtin::BI__builtin_fabs: |
2310 | case Builtin::BI__builtin_fabsf: |
2311 | case Builtin::BI__builtin_fabsf16: |
2312 | case Builtin::BI__builtin_fabsl: |
2313 | case Builtin::BI__builtin_fabsf128: |
2314 | return RValue::get(emitUnaryBuiltin(*this, E, Intrinsic::fabs)); |
2315 | |
2316 | case Builtin::BIfloor: |
2317 | case Builtin::BIfloorf: |
2318 | case Builtin::BIfloorl: |
2319 | case Builtin::BI__builtin_floor: |
2320 | case Builtin::BI__builtin_floorf: |
2321 | case Builtin::BI__builtin_floorf16: |
2322 | case Builtin::BI__builtin_floorl: |
2323 | case Builtin::BI__builtin_floorf128: |
2324 | return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E, |
2325 | Intrinsic::floor, |
2326 | Intrinsic::experimental_constrained_floor)); |
2327 | |
2328 | case Builtin::BIfma: |
2329 | case Builtin::BIfmaf: |
2330 | case Builtin::BIfmal: |
2331 | case Builtin::BI__builtin_fma: |
2332 | case Builtin::BI__builtin_fmaf: |
2333 | case Builtin::BI__builtin_fmaf16: |
2334 | case Builtin::BI__builtin_fmal: |
2335 | case Builtin::BI__builtin_fmaf128: |
2336 | return RValue::get(emitTernaryMaybeConstrainedFPBuiltin(*this, E, |
2337 | Intrinsic::fma, |
2338 | Intrinsic::experimental_constrained_fma)); |
2339 | |
2340 | case Builtin::BIfmax: |
2341 | case Builtin::BIfmaxf: |
2342 | case Builtin::BIfmaxl: |
2343 | case Builtin::BI__builtin_fmax: |
2344 | case Builtin::BI__builtin_fmaxf: |
2345 | case Builtin::BI__builtin_fmaxf16: |
2346 | case Builtin::BI__builtin_fmaxl: |
2347 | case Builtin::BI__builtin_fmaxf128: |
2348 | return RValue::get(emitBinaryMaybeConstrainedFPBuiltin(*this, E, |
2349 | Intrinsic::maxnum, |
2350 | Intrinsic::experimental_constrained_maxnum)); |
2351 | |
2352 | case Builtin::BIfmin: |
2353 | case Builtin::BIfminf: |
2354 | case Builtin::BIfminl: |
2355 | case Builtin::BI__builtin_fmin: |
2356 | case Builtin::BI__builtin_fminf: |
2357 | case Builtin::BI__builtin_fminf16: |
2358 | case Builtin::BI__builtin_fminl: |
2359 | case Builtin::BI__builtin_fminf128: |
2360 | return RValue::get(emitBinaryMaybeConstrainedFPBuiltin(*this, E, |
2361 | Intrinsic::minnum, |
2362 | Intrinsic::experimental_constrained_minnum)); |
2363 | |
2364 | // fmod() is a special-case. It maps to the frem instruction rather than an |
2365 | // LLVM intrinsic. |
2366 | case Builtin::BIfmod: |
2367 | case Builtin::BIfmodf: |
2368 | case Builtin::BIfmodl: |
2369 | case Builtin::BI__builtin_fmod: |
2370 | case Builtin::BI__builtin_fmodf: |
2371 | case Builtin::BI__builtin_fmodf16: |
2372 | case Builtin::BI__builtin_fmodl: |
2373 | case Builtin::BI__builtin_fmodf128: { |
2374 | CodeGenFunction::CGFPOptionsRAII FPOptsRAII(*this, E); |
2375 | Value *Arg1 = EmitScalarExpr(E->getArg(0)); |
2376 | Value *Arg2 = EmitScalarExpr(E->getArg(1)); |
2377 | return RValue::get(V: Builder.CreateFRem(L: Arg1, R: Arg2, Name: "fmod" )); |
2378 | } |
2379 | |
2380 | case Builtin::BIlog: |
2381 | case Builtin::BIlogf: |
2382 | case Builtin::BIlogl: |
2383 | case Builtin::BI__builtin_log: |
2384 | case Builtin::BI__builtin_logf: |
2385 | case Builtin::BI__builtin_logf16: |
2386 | case Builtin::BI__builtin_logl: |
2387 | case Builtin::BI__builtin_logf128: |
2388 | return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E, |
2389 | Intrinsic::log, |
2390 | Intrinsic::experimental_constrained_log)); |
2391 | |
2392 | case Builtin::BIlog10: |
2393 | case Builtin::BIlog10f: |
2394 | case Builtin::BIlog10l: |
2395 | case Builtin::BI__builtin_log10: |
2396 | case Builtin::BI__builtin_log10f: |
2397 | case Builtin::BI__builtin_log10f16: |
2398 | case Builtin::BI__builtin_log10l: |
2399 | case Builtin::BI__builtin_log10f128: |
2400 | return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E, |
2401 | Intrinsic::log10, |
2402 | Intrinsic::experimental_constrained_log10)); |
2403 | |
2404 | case Builtin::BIlog2: |
2405 | case Builtin::BIlog2f: |
2406 | case Builtin::BIlog2l: |
2407 | case Builtin::BI__builtin_log2: |
2408 | case Builtin::BI__builtin_log2f: |
2409 | case Builtin::BI__builtin_log2f16: |
2410 | case Builtin::BI__builtin_log2l: |
2411 | case Builtin::BI__builtin_log2f128: |
2412 | return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E, |
2413 | Intrinsic::log2, |
2414 | Intrinsic::experimental_constrained_log2)); |
2415 | |
2416 | case Builtin::BInearbyint: |
2417 | case Builtin::BInearbyintf: |
2418 | case Builtin::BInearbyintl: |
2419 | case Builtin::BI__builtin_nearbyint: |
2420 | case Builtin::BI__builtin_nearbyintf: |
2421 | case Builtin::BI__builtin_nearbyintl: |
2422 | case Builtin::BI__builtin_nearbyintf128: |
2423 | return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E, |
2424 | Intrinsic::nearbyint, |
2425 | Intrinsic::experimental_constrained_nearbyint)); |
2426 | |
2427 | case Builtin::BIpow: |
2428 | case Builtin::BIpowf: |
2429 | case Builtin::BIpowl: |
2430 | case Builtin::BI__builtin_pow: |
2431 | case Builtin::BI__builtin_powf: |
2432 | case Builtin::BI__builtin_powf16: |
2433 | case Builtin::BI__builtin_powl: |
2434 | case Builtin::BI__builtin_powf128: |
2435 | return RValue::get(emitBinaryMaybeConstrainedFPBuiltin(*this, E, |
2436 | Intrinsic::pow, |
2437 | Intrinsic::experimental_constrained_pow)); |
2438 | |
2439 | case Builtin::BIrint: |
2440 | case Builtin::BIrintf: |
2441 | case Builtin::BIrintl: |
2442 | case Builtin::BI__builtin_rint: |
2443 | case Builtin::BI__builtin_rintf: |
2444 | case Builtin::BI__builtin_rintf16: |
2445 | case Builtin::BI__builtin_rintl: |
2446 | case Builtin::BI__builtin_rintf128: |
2447 | return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E, |
2448 | Intrinsic::rint, |
2449 | Intrinsic::experimental_constrained_rint)); |
2450 | |
2451 | case Builtin::BIround: |
2452 | case Builtin::BIroundf: |
2453 | case Builtin::BIroundl: |
2454 | case Builtin::BI__builtin_round: |
2455 | case Builtin::BI__builtin_roundf: |
2456 | case Builtin::BI__builtin_roundf16: |
2457 | case Builtin::BI__builtin_roundl: |
2458 | case Builtin::BI__builtin_roundf128: |
2459 | return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E, |
2460 | Intrinsic::round, |
2461 | Intrinsic::experimental_constrained_round)); |
2462 | |
2463 | case Builtin::BIroundeven: |
2464 | case Builtin::BIroundevenf: |
2465 | case Builtin::BIroundevenl: |
2466 | case Builtin::BI__builtin_roundeven: |
2467 | case Builtin::BI__builtin_roundevenf: |
2468 | case Builtin::BI__builtin_roundevenf16: |
2469 | case Builtin::BI__builtin_roundevenl: |
2470 | case Builtin::BI__builtin_roundevenf128: |
2471 | return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E, |
2472 | Intrinsic::roundeven, |
2473 | Intrinsic::experimental_constrained_roundeven)); |
2474 | |
2475 | case Builtin::BIsin: |
2476 | case Builtin::BIsinf: |
2477 | case Builtin::BIsinl: |
2478 | case Builtin::BI__builtin_sin: |
2479 | case Builtin::BI__builtin_sinf: |
2480 | case Builtin::BI__builtin_sinf16: |
2481 | case Builtin::BI__builtin_sinl: |
2482 | case Builtin::BI__builtin_sinf128: |
2483 | return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E, |
2484 | Intrinsic::sin, |
2485 | Intrinsic::experimental_constrained_sin)); |
2486 | |
2487 | case Builtin::BIsqrt: |
2488 | case Builtin::BIsqrtf: |
2489 | case Builtin::BIsqrtl: |
2490 | case Builtin::BI__builtin_sqrt: |
2491 | case Builtin::BI__builtin_sqrtf: |
2492 | case Builtin::BI__builtin_sqrtf16: |
2493 | case Builtin::BI__builtin_sqrtl: |
2494 | case Builtin::BI__builtin_sqrtf128: |
2495 | return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E, |
2496 | Intrinsic::sqrt, |
2497 | Intrinsic::experimental_constrained_sqrt)); |
2498 | |
2499 | case Builtin::BItrunc: |
2500 | case Builtin::BItruncf: |
2501 | case Builtin::BItruncl: |
2502 | case Builtin::BI__builtin_trunc: |
2503 | case Builtin::BI__builtin_truncf: |
2504 | case Builtin::BI__builtin_truncf16: |
2505 | case Builtin::BI__builtin_truncl: |
2506 | case Builtin::BI__builtin_truncf128: |
2507 | return RValue::get(emitUnaryMaybeConstrainedFPBuiltin(*this, E, |
2508 | Intrinsic::trunc, |
2509 | Intrinsic::experimental_constrained_trunc)); |
2510 | |
2511 | case Builtin::BIlround: |
2512 | case Builtin::BIlroundf: |
2513 | case Builtin::BIlroundl: |
2514 | case Builtin::BI__builtin_lround: |
2515 | case Builtin::BI__builtin_lroundf: |
2516 | case Builtin::BI__builtin_lroundl: |
2517 | case Builtin::BI__builtin_lroundf128: |
2518 | return RValue::get(emitMaybeConstrainedFPToIntRoundBuiltin( |
2519 | *this, E, Intrinsic::lround, |
2520 | Intrinsic::experimental_constrained_lround)); |
2521 | |
2522 | case Builtin::BIllround: |
2523 | case Builtin::BIllroundf: |
2524 | case Builtin::BIllroundl: |
2525 | case Builtin::BI__builtin_llround: |
2526 | case Builtin::BI__builtin_llroundf: |
2527 | case Builtin::BI__builtin_llroundl: |
2528 | case Builtin::BI__builtin_llroundf128: |
2529 | return RValue::get(emitMaybeConstrainedFPToIntRoundBuiltin( |
2530 | *this, E, Intrinsic::llround, |
2531 | Intrinsic::experimental_constrained_llround)); |
2532 | |
2533 | case Builtin::BIlrint: |
2534 | case Builtin::BIlrintf: |
2535 | case Builtin::BIlrintl: |
2536 | case Builtin::BI__builtin_lrint: |
2537 | case Builtin::BI__builtin_lrintf: |
2538 | case Builtin::BI__builtin_lrintl: |
2539 | case Builtin::BI__builtin_lrintf128: |
2540 | return RValue::get(emitMaybeConstrainedFPToIntRoundBuiltin( |
2541 | *this, E, Intrinsic::lrint, |
2542 | Intrinsic::experimental_constrained_lrint)); |
2543 | |
2544 | case Builtin::BIllrint: |
2545 | case Builtin::BIllrintf: |
2546 | case Builtin::BIllrintl: |
2547 | case Builtin::BI__builtin_llrint: |
2548 | case Builtin::BI__builtin_llrintf: |
2549 | case Builtin::BI__builtin_llrintl: |
2550 | case Builtin::BI__builtin_llrintf128: |
2551 | return RValue::get(emitMaybeConstrainedFPToIntRoundBuiltin( |
2552 | *this, E, Intrinsic::llrint, |
2553 | Intrinsic::experimental_constrained_llrint)); |
2554 | |
2555 | default: |
2556 | break; |
2557 | } |
2558 | } |
2559 | |
2560 | switch (BuiltinIDIfNoAsmLabel) { |
2561 | default: break; |
2562 | case Builtin::BI__builtin___CFStringMakeConstantString: |
2563 | case Builtin::BI__builtin___NSStringMakeConstantString: |
2564 | return RValue::get(ConstantEmitter(*this).emitAbstract(E, E->getType())); |
2565 | case Builtin::BI__builtin_stdarg_start: |
2566 | case Builtin::BI__builtin_va_start: |
2567 | case Builtin::BI__va_start: |
2568 | case Builtin::BI__builtin_va_end: |
2569 | EmitVAStartEnd(BuiltinID == Builtin::BI__va_start |
2570 | ? EmitScalarExpr(E->getArg(0)) |
2571 | : EmitVAListRef(E->getArg(0)).getPointer(), |
2572 | BuiltinID != Builtin::BI__builtin_va_end); |
2573 | return RValue::get(V: nullptr); |
2574 | case Builtin::BI__builtin_va_copy: { |
2575 | Value *DstPtr = EmitVAListRef(E->getArg(0)).getPointer(); |
2576 | Value *SrcPtr = EmitVAListRef(E->getArg(1)).getPointer(); |
2577 | |
2578 | llvm::Type *Type = Int8PtrTy; |
2579 | |
2580 | DstPtr = Builder.CreateBitCast(V: DstPtr, DestTy: Type); |
2581 | SrcPtr = Builder.CreateBitCast(V: SrcPtr, DestTy: Type); |
2582 | Builder.CreateCall(CGM.getIntrinsic(Intrinsic::vacopy), {DstPtr, SrcPtr}); |
2583 | return RValue::get(V: nullptr); |
2584 | } |
2585 | case Builtin::BI__builtin_abs: |
2586 | case Builtin::BI__builtin_labs: |
2587 | case Builtin::BI__builtin_llabs: { |
2588 | // X < 0 ? -X : X |
2589 | // The negation has 'nsw' because abs of INT_MIN is undefined. |
2590 | Value *ArgValue = EmitScalarExpr(E->getArg(0)); |
2591 | Value *NegOp = Builder.CreateNSWNeg(V: ArgValue, Name: "neg" ); |
2592 | Constant *Zero = llvm::Constant::getNullValue(Ty: ArgValue->getType()); |
2593 | Value *CmpResult = Builder.CreateICmpSLT(LHS: ArgValue, RHS: Zero, Name: "abscond" ); |
2594 | Value *Result = Builder.CreateSelect(C: CmpResult, True: NegOp, False: ArgValue, Name: "abs" ); |
2595 | return RValue::get(V: Result); |
2596 | } |
2597 | case Builtin::BI__builtin_complex: { |
2598 | Value *Real = EmitScalarExpr(E->getArg(0)); |
2599 | Value *Imag = EmitScalarExpr(E->getArg(1)); |
2600 | return RValue::getComplex(C: {Real, Imag}); |
2601 | } |
2602 | case Builtin::BI__builtin_conj: |
2603 | case Builtin::BI__builtin_conjf: |
2604 | case Builtin::BI__builtin_conjl: |
2605 | case Builtin::BIconj: |
2606 | case Builtin::BIconjf: |
2607 | case Builtin::BIconjl: { |
2608 | ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0)); |
2609 | Value *Real = ComplexVal.first; |
2610 | Value *Imag = ComplexVal.second; |
2611 | Imag = Builder.CreateFNeg(V: Imag, Name: "neg" ); |
2612 | return RValue::getComplex(C: std::make_pair(x&: Real, y&: Imag)); |
2613 | } |
2614 | case Builtin::BI__builtin_creal: |
2615 | case Builtin::BI__builtin_crealf: |
2616 | case Builtin::BI__builtin_creall: |
2617 | case Builtin::BIcreal: |
2618 | case Builtin::BIcrealf: |
2619 | case Builtin::BIcreall: { |
2620 | ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0)); |
2621 | return RValue::get(V: ComplexVal.first); |
2622 | } |
2623 | |
2624 | case Builtin::BI__builtin_preserve_access_index: { |
2625 | // Only enabled preserved access index region when debuginfo |
2626 | // is available as debuginfo is needed to preserve user-level |
2627 | // access pattern. |
2628 | if (!getDebugInfo()) { |
2629 | CGM.Error(E->getExprLoc(), "using builtin_preserve_access_index() without -g" ); |
2630 | return RValue::get(EmitScalarExpr(E->getArg(0))); |
2631 | } |
2632 | |
2633 | // Nested builtin_preserve_access_index() not supported |
2634 | if (IsInPreservedAIRegion) { |
2635 | CGM.Error(E->getExprLoc(), "nested builtin_preserve_access_index() not supported" ); |
2636 | return RValue::get(EmitScalarExpr(E->getArg(0))); |
2637 | } |
2638 | |
2639 | IsInPreservedAIRegion = true; |
2640 | Value *Res = EmitScalarExpr(E->getArg(0)); |
2641 | IsInPreservedAIRegion = false; |
2642 | return RValue::get(V: Res); |
2643 | } |
2644 | |
2645 | case Builtin::BI__builtin_cimag: |
2646 | case Builtin::BI__builtin_cimagf: |
2647 | case Builtin::BI__builtin_cimagl: |
2648 | case Builtin::BIcimag: |
2649 | case Builtin::BIcimagf: |
2650 | case Builtin::BIcimagl: { |
2651 | ComplexPairTy ComplexVal = EmitComplexExpr(E->getArg(0)); |
2652 | return RValue::get(V: ComplexVal.second); |
2653 | } |
2654 | |
2655 | case Builtin::BI__builtin_clrsb: |
2656 | case Builtin::BI__builtin_clrsbl: |
2657 | case Builtin::BI__builtin_clrsbll: { |
2658 | // clrsb(x) -> clz(x < 0 ? ~x : x) - 1 or |
2659 | Value *ArgValue = EmitScalarExpr(E->getArg(0)); |
2660 | |
2661 | llvm::Type *ArgType = ArgValue->getType(); |
2662 | Function *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType); |
2663 | |
2664 | llvm::Type *ResultType = ConvertType(E->getType()); |
2665 | Value *Zero = llvm::Constant::getNullValue(Ty: ArgType); |
2666 | Value *IsNeg = Builder.CreateICmpSLT(LHS: ArgValue, RHS: Zero, Name: "isneg" ); |
2667 | Value *Inverse = Builder.CreateNot(V: ArgValue, Name: "not" ); |
2668 | Value *Tmp = Builder.CreateSelect(C: IsNeg, True: Inverse, False: ArgValue); |
2669 | Value *Ctlz = Builder.CreateCall(Callee: F, Args: {Tmp, Builder.getFalse()}); |
2670 | Value *Result = Builder.CreateSub(LHS: Ctlz, RHS: llvm::ConstantInt::get(Ty: ArgType, V: 1)); |
2671 | Result = Builder.CreateIntCast(V: Result, DestTy: ResultType, /*isSigned*/true, |
2672 | Name: "cast" ); |
2673 | return RValue::get(V: Result); |
2674 | } |
2675 | case Builtin::BI__builtin_ctzs: |
2676 | case Builtin::BI__builtin_ctz: |
2677 | case Builtin::BI__builtin_ctzl: |
2678 | case Builtin::BI__builtin_ctzll: { |
2679 | Value *ArgValue = EmitCheckedArgForBuiltin(E->getArg(0), BCK_CTZPassedZero); |
2680 | |
2681 | llvm::Type *ArgType = ArgValue->getType(); |
2682 | Function *F = CGM.getIntrinsic(Intrinsic::cttz, ArgType); |
2683 | |
2684 | llvm::Type *ResultType = ConvertType(E->getType()); |
2685 | Value *ZeroUndef = Builder.getInt1(V: getTarget().isCLZForZeroUndef()); |
2686 | Value *Result = Builder.CreateCall(Callee: F, Args: {ArgValue, ZeroUndef}); |
2687 | if (Result->getType() != ResultType) |
2688 | Result = Builder.CreateIntCast(V: Result, DestTy: ResultType, /*isSigned*/true, |
2689 | Name: "cast" ); |
2690 | return RValue::get(V: Result); |
2691 | } |
2692 | case Builtin::BI__builtin_clzs: |
2693 | case Builtin::BI__builtin_clz: |
2694 | case Builtin::BI__builtin_clzl: |
2695 | case Builtin::BI__builtin_clzll: { |
2696 | Value *ArgValue = EmitCheckedArgForBuiltin(E->getArg(0), BCK_CLZPassedZero); |
2697 | |
2698 | llvm::Type *ArgType = ArgValue->getType(); |
2699 | Function *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType); |
2700 | |
2701 | llvm::Type *ResultType = ConvertType(E->getType()); |
2702 | Value *ZeroUndef = Builder.getInt1(V: getTarget().isCLZForZeroUndef()); |
2703 | Value *Result = Builder.CreateCall(Callee: F, Args: {ArgValue, ZeroUndef}); |
2704 | if (Result->getType() != ResultType) |
2705 | Result = Builder.CreateIntCast(V: Result, DestTy: ResultType, /*isSigned*/true, |
2706 | Name: "cast" ); |
2707 | return RValue::get(V: Result); |
2708 | } |
2709 | case Builtin::BI__builtin_ffs: |
2710 | case Builtin::BI__builtin_ffsl: |
2711 | case Builtin::BI__builtin_ffsll: { |
2712 | // ffs(x) -> x ? cttz(x) + 1 : 0 |
2713 | Value *ArgValue = EmitScalarExpr(E->getArg(0)); |
2714 | |
2715 | llvm::Type *ArgType = ArgValue->getType(); |
2716 | Function *F = CGM.getIntrinsic(Intrinsic::cttz, ArgType); |
2717 | |
2718 | llvm::Type *ResultType = ConvertType(E->getType()); |
2719 | Value *Tmp = |
2720 | Builder.CreateAdd(LHS: Builder.CreateCall(Callee: F, Args: {ArgValue, Builder.getTrue()}), |
2721 | RHS: llvm::ConstantInt::get(Ty: ArgType, V: 1)); |
2722 | Value *Zero = llvm::Constant::getNullValue(Ty: ArgType); |
2723 | Value *IsZero = Builder.CreateICmpEQ(LHS: ArgValue, RHS: Zero, Name: "iszero" ); |
2724 | Value *Result = Builder.CreateSelect(C: IsZero, True: Zero, False: Tmp, Name: "ffs" ); |
2725 | if (Result->getType() != ResultType) |
2726 | Result = Builder.CreateIntCast(V: Result, DestTy: ResultType, /*isSigned*/true, |
2727 | Name: "cast" ); |
2728 | return RValue::get(V: Result); |
2729 | } |
2730 | case Builtin::BI__builtin_parity: |
2731 | case Builtin::BI__builtin_parityl: |
2732 | case Builtin::BI__builtin_parityll: { |
2733 | // parity(x) -> ctpop(x) & 1 |
2734 | Value *ArgValue = EmitScalarExpr(E->getArg(0)); |
2735 | |
2736 | llvm::Type *ArgType = ArgValue->getType(); |
2737 | Function *F = CGM.getIntrinsic(Intrinsic::ctpop, ArgType); |
2738 | |
2739 | llvm::Type *ResultType = ConvertType(E->getType()); |
2740 | Value *Tmp = |
---|