Thanks to visit codestin.com
Credit goes to clang.llvm.org

clang 22.0.0git
CGAtomic.cpp
Go to the documentation of this file.
1//===--- CGAtomic.cpp - Emit LLVM IR for atomic operations ----------------===//
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 file contains the code for emitting atomic operations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGCall.h"
14#include "CGRecordLayout.h"
15#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
17#include "TargetInfo.h"
21#include "llvm/ADT/DenseMap.h"
22#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/Intrinsics.h"
24
25using namespace clang;
26using namespace CodeGen;
27
28namespace {
29 class AtomicInfo {
30 CodeGenFunction &CGF;
31 QualType AtomicTy;
32 QualType ValueTy;
33 uint64_t AtomicSizeInBits;
34 uint64_t ValueSizeInBits;
35 CharUnits AtomicAlign;
36 CharUnits ValueAlign;
37 TypeEvaluationKind EvaluationKind;
38 bool UseLibcall;
39 LValue LVal;
40 CGBitFieldInfo BFI;
41 public:
42 AtomicInfo(CodeGenFunction &CGF, LValue &lvalue)
43 : CGF(CGF), AtomicSizeInBits(0), ValueSizeInBits(0),
44 EvaluationKind(TEK_Scalar), UseLibcall(true) {
45 assert(!lvalue.isGlobalReg());
46 ASTContext &C = CGF.getContext();
47 if (lvalue.isSimple()) {
48 AtomicTy = lvalue.getType();
49 if (auto *ATy = AtomicTy->getAs<AtomicType>())
50 ValueTy = ATy->getValueType();
51 else
52 ValueTy = AtomicTy;
53 EvaluationKind = CGF.getEvaluationKind(ValueTy);
54
55 uint64_t ValueAlignInBits;
56 uint64_t AtomicAlignInBits;
57 TypeInfo ValueTI = C.getTypeInfo(ValueTy);
58 ValueSizeInBits = ValueTI.Width;
59 ValueAlignInBits = ValueTI.Align;
60
61 TypeInfo AtomicTI = C.getTypeInfo(AtomicTy);
62 AtomicSizeInBits = AtomicTI.Width;
63 AtomicAlignInBits = AtomicTI.Align;
64
65 assert(ValueSizeInBits <= AtomicSizeInBits);
66 assert(ValueAlignInBits <= AtomicAlignInBits);
67
68 AtomicAlign = C.toCharUnitsFromBits(AtomicAlignInBits);
69 ValueAlign = C.toCharUnitsFromBits(ValueAlignInBits);
70 if (lvalue.getAlignment().isZero())
71 lvalue.setAlignment(AtomicAlign);
72
73 LVal = lvalue;
74 } else if (lvalue.isBitField()) {
75 ValueTy = lvalue.getType();
76 ValueSizeInBits = C.getTypeSize(ValueTy);
77 auto &OrigBFI = lvalue.getBitFieldInfo();
78 auto Offset = OrigBFI.Offset % C.toBits(lvalue.getAlignment());
79 AtomicSizeInBits = C.toBits(
80 C.toCharUnitsFromBits(Offset + OrigBFI.Size + C.getCharWidth() - 1)
81 .alignTo(lvalue.getAlignment()));
82 llvm::Value *BitFieldPtr = lvalue.getRawBitFieldPointer(CGF);
83 auto OffsetInChars =
84 (C.toCharUnitsFromBits(OrigBFI.Offset) / lvalue.getAlignment()) *
85 lvalue.getAlignment();
86 llvm::Value *StoragePtr = CGF.Builder.CreateConstGEP1_64(
87 CGF.Int8Ty, BitFieldPtr, OffsetInChars.getQuantity());
88 StoragePtr = CGF.Builder.CreateAddrSpaceCast(
89 StoragePtr, CGF.UnqualPtrTy, "atomic_bitfield_base");
90 BFI = OrigBFI;
91 BFI.Offset = Offset;
92 BFI.StorageSize = AtomicSizeInBits;
93 BFI.StorageOffset += OffsetInChars;
94 llvm::Type *StorageTy = CGF.Builder.getIntNTy(AtomicSizeInBits);
95 LVal = LValue::MakeBitfield(
96 Address(StoragePtr, StorageTy, lvalue.getAlignment()), BFI,
97 lvalue.getType(), lvalue.getBaseInfo(), lvalue.getTBAAInfo());
98 AtomicTy = C.getIntTypeForBitwidth(AtomicSizeInBits, OrigBFI.IsSigned);
99 if (AtomicTy.isNull()) {
100 llvm::APInt Size(
101 /*numBits=*/32,
102 C.toCharUnitsFromBits(AtomicSizeInBits).getQuantity());
103 AtomicTy = C.getConstantArrayType(C.CharTy, Size, nullptr,
104 ArraySizeModifier::Normal,
105 /*IndexTypeQuals=*/0);
106 }
107 AtomicAlign = ValueAlign = lvalue.getAlignment();
108 } else if (lvalue.isVectorElt()) {
109 ValueTy = lvalue.getType()->castAs<VectorType>()->getElementType();
110 ValueSizeInBits = C.getTypeSize(ValueTy);
111 AtomicTy = lvalue.getType();
112 AtomicSizeInBits = C.getTypeSize(AtomicTy);
113 AtomicAlign = ValueAlign = lvalue.getAlignment();
114 LVal = lvalue;
115 } else {
116 assert(lvalue.isExtVectorElt());
117 ValueTy = lvalue.getType();
118 ValueSizeInBits = C.getTypeSize(ValueTy);
119 AtomicTy = ValueTy = CGF.getContext().getExtVectorType(
120 lvalue.getType(), cast<llvm::FixedVectorType>(
121 lvalue.getExtVectorAddress().getElementType())
122 ->getNumElements());
123 AtomicSizeInBits = C.getTypeSize(AtomicTy);
124 AtomicAlign = ValueAlign = lvalue.getAlignment();
125 LVal = lvalue;
126 }
127 UseLibcall = !C.getTargetInfo().hasBuiltinAtomic(
128 AtomicSizeInBits, C.toBits(lvalue.getAlignment()));
129 }
130
131 QualType getAtomicType() const { return AtomicTy; }
132 QualType getValueType() const { return ValueTy; }
133 CharUnits getAtomicAlignment() const { return AtomicAlign; }
134 uint64_t getAtomicSizeInBits() const { return AtomicSizeInBits; }
135 uint64_t getValueSizeInBits() const { return ValueSizeInBits; }
136 TypeEvaluationKind getEvaluationKind() const { return EvaluationKind; }
137 bool shouldUseLibcall() const { return UseLibcall; }
138 const LValue &getAtomicLValue() const { return LVal; }
139 llvm::Value *getAtomicPointer() const {
140 if (LVal.isSimple())
141 return LVal.emitRawPointer(CGF);
142 else if (LVal.isBitField())
143 return LVal.getRawBitFieldPointer(CGF);
144 else if (LVal.isVectorElt())
145 return LVal.getRawVectorPointer(CGF);
146 assert(LVal.isExtVectorElt());
147 return LVal.getRawExtVectorPointer(CGF);
148 }
149 Address getAtomicAddress() const {
150 llvm::Type *ElTy;
151 if (LVal.isSimple())
152 ElTy = LVal.getAddress().getElementType();
153 else if (LVal.isBitField())
154 ElTy = LVal.getBitFieldAddress().getElementType();
155 else if (LVal.isVectorElt())
156 ElTy = LVal.getVectorAddress().getElementType();
157 else
158 ElTy = LVal.getExtVectorAddress().getElementType();
159 return Address(getAtomicPointer(), ElTy, getAtomicAlignment());
160 }
161
162 Address getAtomicAddressAsAtomicIntPointer() const {
163 return castToAtomicIntPointer(getAtomicAddress());
164 }
165
166 /// Is the atomic size larger than the underlying value type?
167 ///
168 /// Note that the absence of padding does not mean that atomic
169 /// objects are completely interchangeable with non-atomic
170 /// objects: we might have promoted the alignment of a type
171 /// without making it bigger.
172 bool hasPadding() const {
173 return (ValueSizeInBits != AtomicSizeInBits);
174 }
175
176 bool emitMemSetZeroIfNecessary() const;
177
178 llvm::Value *getAtomicSizeValue() const {
179 CharUnits size = CGF.getContext().toCharUnitsFromBits(AtomicSizeInBits);
180 return CGF.CGM.getSize(size);
181 }
182
183 /// Cast the given pointer to an integer pointer suitable for atomic
184 /// operations if the source.
185 Address castToAtomicIntPointer(Address Addr) const;
186
187 /// If Addr is compatible with the iN that will be used for an atomic
188 /// operation, bitcast it. Otherwise, create a temporary that is suitable
189 /// and copy the value across.
190 Address convertToAtomicIntPointer(Address Addr) const;
191
192 /// Turn an atomic-layout object into an r-value.
193 RValue convertAtomicTempToRValue(Address addr, AggValueSlot resultSlot,
194 SourceLocation loc, bool AsValue) const;
195
196 llvm::Value *getScalarRValValueOrNull(RValue RVal) const;
197
198 /// Converts an rvalue to integer value if needed.
199 llvm::Value *convertRValueToInt(RValue RVal, bool CmpXchg = false) const;
200
201 RValue ConvertToValueOrAtomic(llvm::Value *IntVal, AggValueSlot ResultSlot,
202 SourceLocation Loc, bool AsValue,
203 bool CmpXchg = false) const;
204
205 /// Copy an atomic r-value into atomic-layout memory.
206 void emitCopyIntoMemory(RValue rvalue) const;
207
208 /// Project an l-value down to the value field.
209 LValue projectValue() const {
210 assert(LVal.isSimple());
211 Address addr = getAtomicAddress();
212 if (hasPadding())
213 addr = CGF.Builder.CreateStructGEP(addr, 0);
214
215 return LValue::MakeAddr(addr, getValueType(), CGF.getContext(),
216 LVal.getBaseInfo(), LVal.getTBAAInfo());
217 }
218
219 /// Emits atomic load.
220 /// \returns Loaded value.
221 RValue EmitAtomicLoad(AggValueSlot ResultSlot, SourceLocation Loc,
222 bool AsValue, llvm::AtomicOrdering AO,
223 bool IsVolatile);
224
225 /// Emits atomic compare-and-exchange sequence.
226 /// \param Expected Expected value.
227 /// \param Desired Desired value.
228 /// \param Success Atomic ordering for success operation.
229 /// \param Failure Atomic ordering for failed operation.
230 /// \param IsWeak true if atomic operation is weak, false otherwise.
231 /// \returns Pair of values: previous value from storage (value type) and
232 /// boolean flag (i1 type) with true if success and false otherwise.
233 std::pair<RValue, llvm::Value *>
234 EmitAtomicCompareExchange(RValue Expected, RValue Desired,
235 llvm::AtomicOrdering Success =
236 llvm::AtomicOrdering::SequentiallyConsistent,
237 llvm::AtomicOrdering Failure =
238 llvm::AtomicOrdering::SequentiallyConsistent,
239 bool IsWeak = false);
240
241 /// Emits atomic update.
242 /// \param AO Atomic ordering.
243 /// \param UpdateOp Update operation for the current lvalue.
244 void EmitAtomicUpdate(llvm::AtomicOrdering AO,
245 const llvm::function_ref<RValue(RValue)> &UpdateOp,
246 bool IsVolatile);
247 /// Emits atomic update.
248 /// \param AO Atomic ordering.
249 void EmitAtomicUpdate(llvm::AtomicOrdering AO, RValue UpdateRVal,
250 bool IsVolatile);
251
252 /// Materialize an atomic r-value in atomic-layout memory.
253 Address materializeRValue(RValue rvalue) const;
254
255 /// Creates temp alloca for intermediate operations on atomic value.
256 Address CreateTempAlloca() const;
257 private:
258 bool requiresMemSetZero(llvm::Type *type) const;
259
260
261 /// Emits atomic load as a libcall.
262 void EmitAtomicLoadLibcall(llvm::Value *AddForLoaded,
263 llvm::AtomicOrdering AO, bool IsVolatile);
264 /// Emits atomic load as LLVM instruction.
265 llvm::Value *EmitAtomicLoadOp(llvm::AtomicOrdering AO, bool IsVolatile,
266 bool CmpXchg = false);
267 /// Emits atomic compare-and-exchange op as a libcall.
268 llvm::Value *EmitAtomicCompareExchangeLibcall(
269 llvm::Value *ExpectedAddr, llvm::Value *DesiredAddr,
270 llvm::AtomicOrdering Success =
271 llvm::AtomicOrdering::SequentiallyConsistent,
272 llvm::AtomicOrdering Failure =
273 llvm::AtomicOrdering::SequentiallyConsistent);
274 /// Emits atomic compare-and-exchange op as LLVM instruction.
275 std::pair<llvm::Value *, llvm::Value *> EmitAtomicCompareExchangeOp(
276 llvm::Value *ExpectedVal, llvm::Value *DesiredVal,
277 llvm::AtomicOrdering Success =
278 llvm::AtomicOrdering::SequentiallyConsistent,
279 llvm::AtomicOrdering Failure =
280 llvm::AtomicOrdering::SequentiallyConsistent,
281 bool IsWeak = false);
282 /// Emit atomic update as libcalls.
283 void
284 EmitAtomicUpdateLibcall(llvm::AtomicOrdering AO,
285 const llvm::function_ref<RValue(RValue)> &UpdateOp,
286 bool IsVolatile);
287 /// Emit atomic update as LLVM instructions.
288 void EmitAtomicUpdateOp(llvm::AtomicOrdering AO,
289 const llvm::function_ref<RValue(RValue)> &UpdateOp,
290 bool IsVolatile);
291 /// Emit atomic update as libcalls.
292 void EmitAtomicUpdateLibcall(llvm::AtomicOrdering AO, RValue UpdateRVal,
293 bool IsVolatile);
294 /// Emit atomic update as LLVM instructions.
295 void EmitAtomicUpdateOp(llvm::AtomicOrdering AO, RValue UpdateRal,
296 bool IsVolatile);
297 };
298}
299
300Address AtomicInfo::CreateTempAlloca() const {
301 Address TempAlloca = CGF.CreateMemTemp(
302 (LVal.isBitField() && ValueSizeInBits > AtomicSizeInBits) ? ValueTy
303 : AtomicTy,
304 getAtomicAlignment(),
305 "atomic-temp");
306 // Cast to pointer to value type for bitfields.
307 if (LVal.isBitField())
309 TempAlloca, getAtomicAddress().getType(),
310 getAtomicAddress().getElementType());
311 return TempAlloca;
312}
313
315 StringRef fnName,
316 QualType resultType,
317 CallArgList &args) {
318 const CGFunctionInfo &fnInfo =
319 CGF.CGM.getTypes().arrangeBuiltinFunctionCall(resultType, args);
320 llvm::FunctionType *fnTy = CGF.CGM.getTypes().GetFunctionType(fnInfo);
321 llvm::AttrBuilder fnAttrB(CGF.getLLVMContext());
322 fnAttrB.addAttribute(llvm::Attribute::NoUnwind);
323 fnAttrB.addAttribute(llvm::Attribute::WillReturn);
324 llvm::AttributeList fnAttrs = llvm::AttributeList::get(
325 CGF.getLLVMContext(), llvm::AttributeList::FunctionIndex, fnAttrB);
326
327 llvm::FunctionCallee fn =
328 CGF.CGM.CreateRuntimeFunction(fnTy, fnName, fnAttrs);
329 auto callee = CGCallee::forDirect(fn);
330 return CGF.EmitCall(fnInfo, callee, ReturnValueSlot(), args);
331}
332
333/// Does a store of the given IR type modify the full expected width?
334static bool isFullSizeType(CodeGenModule &CGM, llvm::Type *type,
335 uint64_t expectedSize) {
336 return (CGM.getDataLayout().getTypeStoreSize(type) * 8 == expectedSize);
337}
338
339/// Does the atomic type require memsetting to zero before initialization?
340///
341/// The IR type is provided as a way of making certain queries faster.
342bool AtomicInfo::requiresMemSetZero(llvm::Type *type) const {
343 // If the atomic type has size padding, we definitely need a memset.
344 if (hasPadding()) return true;
345
346 // Otherwise, do some simple heuristics to try to avoid it:
347 switch (getEvaluationKind()) {
348 // For scalars and complexes, check whether the store size of the
349 // type uses the full size.
350 case TEK_Scalar:
351 return !isFullSizeType(CGF.CGM, type, AtomicSizeInBits);
352 case TEK_Complex:
353 return !isFullSizeType(CGF.CGM, type->getStructElementType(0),
354 AtomicSizeInBits / 2);
355
356 // Padding in structs has an undefined bit pattern. User beware.
357 case TEK_Aggregate:
358 return false;
359 }
360 llvm_unreachable("bad evaluation kind");
361}
362
363bool AtomicInfo::emitMemSetZeroIfNecessary() const {
364 assert(LVal.isSimple());
365 Address addr = LVal.getAddress();
366 if (!requiresMemSetZero(addr.getElementType()))
367 return false;
368
370 addr.emitRawPointer(CGF), llvm::ConstantInt::get(CGF.Int8Ty, 0),
371 CGF.getContext().toCharUnitsFromBits(AtomicSizeInBits).getQuantity(),
372 LVal.getAlignment().getAsAlign());
373 return true;
374}
375
376static void emitAtomicCmpXchg(CodeGenFunction &CGF, AtomicExpr *E, bool IsWeak,
377 Address Dest, Address Ptr,
378 Address Val1, Address Val2,
379 uint64_t Size,
380 llvm::AtomicOrdering SuccessOrder,
381 llvm::AtomicOrdering FailureOrder,
382 llvm::SyncScope::ID Scope) {
383 // Note that cmpxchg doesn't support weak cmpxchg, at least at the moment.
384 llvm::Value *Expected = CGF.Builder.CreateLoad(Val1);
385 llvm::Value *Desired = CGF.Builder.CreateLoad(Val2);
386
387 llvm::AtomicCmpXchgInst *Pair = CGF.Builder.CreateAtomicCmpXchg(
388 Ptr, Expected, Desired, SuccessOrder, FailureOrder, Scope);
389 Pair->setVolatile(E->isVolatile());
390 Pair->setWeak(IsWeak);
391 CGF.getTargetHooks().setTargetAtomicMetadata(CGF, *Pair, E);
392
393 // Cmp holds the result of the compare-exchange operation: true on success,
394 // false on failure.
395 llvm::Value *Old = CGF.Builder.CreateExtractValue(Pair, 0);
396 llvm::Value *Cmp = CGF.Builder.CreateExtractValue(Pair, 1);
397
398 // This basic block is used to hold the store instruction if the operation
399 // failed.
400 llvm::BasicBlock *StoreExpectedBB =
401 CGF.createBasicBlock("cmpxchg.store_expected", CGF.CurFn);
402
403 // This basic block is the exit point of the operation, we should end up
404 // here regardless of whether or not the operation succeeded.
405 llvm::BasicBlock *ContinueBB =
406 CGF.createBasicBlock("cmpxchg.continue", CGF.CurFn);
407
408 // Update Expected if Expected isn't equal to Old, otherwise branch to the
409 // exit point.
410 CGF.Builder.CreateCondBr(Cmp, ContinueBB, StoreExpectedBB);
411
412 CGF.Builder.SetInsertPoint(StoreExpectedBB);
413 // Update the memory at Expected with Old's value.
414 auto *I = CGF.Builder.CreateStore(Old, Val1);
415 CGF.addInstToCurrentSourceAtom(I, Old);
416
417 // Finally, branch to the exit point.
418 CGF.Builder.CreateBr(ContinueBB);
419
420 CGF.Builder.SetInsertPoint(ContinueBB);
421 // Update the memory at Dest with Cmp's value.
422 CGF.EmitStoreOfScalar(Cmp, CGF.MakeAddrLValue(Dest, E->getType()));
423}
424
425/// Given an ordering required on success, emit all possible cmpxchg
426/// instructions to cope with the provided (but possibly only dynamically known)
427/// FailureOrder.
429 bool IsWeak, Address Dest, Address Ptr,
430 Address Val1, Address Val2,
431 llvm::Value *FailureOrderVal,
432 uint64_t Size,
433 llvm::AtomicOrdering SuccessOrder,
434 llvm::SyncScope::ID Scope) {
435 llvm::AtomicOrdering FailureOrder;
436 if (llvm::ConstantInt *FO = dyn_cast<llvm::ConstantInt>(FailureOrderVal)) {
437 auto FOS = FO->getSExtValue();
438 if (!llvm::isValidAtomicOrderingCABI(FOS))
439 FailureOrder = llvm::AtomicOrdering::Monotonic;
440 else
441 switch ((llvm::AtomicOrderingCABI)FOS) {
442 case llvm::AtomicOrderingCABI::relaxed:
443 // 31.7.2.18: "The failure argument shall not be memory_order_release
444 // nor memory_order_acq_rel". Fallback to monotonic.
445 case llvm::AtomicOrderingCABI::release:
446 case llvm::AtomicOrderingCABI::acq_rel:
447 FailureOrder = llvm::AtomicOrdering::Monotonic;
448 break;
449 case llvm::AtomicOrderingCABI::consume:
450 case llvm::AtomicOrderingCABI::acquire:
451 FailureOrder = llvm::AtomicOrdering::Acquire;
452 break;
453 case llvm::AtomicOrderingCABI::seq_cst:
454 FailureOrder = llvm::AtomicOrdering::SequentiallyConsistent;
455 break;
456 }
457 // Prior to c++17, "the failure argument shall be no stronger than the
458 // success argument". This condition has been lifted and the only
459 // precondition is 31.7.2.18. Effectively treat this as a DR and skip
460 // language version checks.
461 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, Size, SuccessOrder,
462 FailureOrder, Scope);
463 return;
464 }
465
466 // Create all the relevant BB's
467 auto *MonotonicBB = CGF.createBasicBlock("monotonic_fail", CGF.CurFn);
468 auto *AcquireBB = CGF.createBasicBlock("acquire_fail", CGF.CurFn);
469 auto *SeqCstBB = CGF.createBasicBlock("seqcst_fail", CGF.CurFn);
470 auto *ContBB = CGF.createBasicBlock("atomic.continue", CGF.CurFn);
471
472 // MonotonicBB is arbitrarily chosen as the default case; in practice, this
473 // doesn't matter unless someone is crazy enough to use something that
474 // doesn't fold to a constant for the ordering.
475 llvm::SwitchInst *SI = CGF.Builder.CreateSwitch(FailureOrderVal, MonotonicBB);
476 // Implemented as acquire, since it's the closest in LLVM.
477 SI->addCase(CGF.Builder.getInt32((int)llvm::AtomicOrderingCABI::consume),
478 AcquireBB);
479 SI->addCase(CGF.Builder.getInt32((int)llvm::AtomicOrderingCABI::acquire),
480 AcquireBB);
481 SI->addCase(CGF.Builder.getInt32((int)llvm::AtomicOrderingCABI::seq_cst),
482 SeqCstBB);
483
484 // Emit all the different atomics
485 CGF.Builder.SetInsertPoint(MonotonicBB);
486 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2,
487 Size, SuccessOrder, llvm::AtomicOrdering::Monotonic, Scope);
488 CGF.Builder.CreateBr(ContBB);
489
490 CGF.Builder.SetInsertPoint(AcquireBB);
491 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, Size, SuccessOrder,
492 llvm::AtomicOrdering::Acquire, Scope);
493 CGF.Builder.CreateBr(ContBB);
494
495 CGF.Builder.SetInsertPoint(SeqCstBB);
496 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, Size, SuccessOrder,
497 llvm::AtomicOrdering::SequentiallyConsistent, Scope);
498 CGF.Builder.CreateBr(ContBB);
499
500 CGF.Builder.SetInsertPoint(ContBB);
501}
502
503/// Duplicate the atomic min/max operation in conventional IR for the builtin
504/// variants that return the new rather than the original value.
505static llvm::Value *EmitPostAtomicMinMax(CGBuilderTy &Builder,
507 bool IsSigned,
508 llvm::Value *OldVal,
509 llvm::Value *RHS) {
510 llvm::CmpInst::Predicate Pred;
511 switch (Op) {
512 default:
513 llvm_unreachable("Unexpected min/max operation");
514 case AtomicExpr::AO__atomic_max_fetch:
515 case AtomicExpr::AO__scoped_atomic_max_fetch:
516 Pred = IsSigned ? llvm::CmpInst::ICMP_SGT : llvm::CmpInst::ICMP_UGT;
517 break;
518 case AtomicExpr::AO__atomic_min_fetch:
519 case AtomicExpr::AO__scoped_atomic_min_fetch:
520 Pred = IsSigned ? llvm::CmpInst::ICMP_SLT : llvm::CmpInst::ICMP_ULT;
521 break;
522 }
523 llvm::Value *Cmp = Builder.CreateICmp(Pred, OldVal, RHS, "tst");
524 return Builder.CreateSelect(Cmp, OldVal, RHS, "newval");
525}
526
528 Address Ptr, Address Val1, Address Val2,
529 llvm::Value *IsWeak, llvm::Value *FailureOrder,
530 uint64_t Size, llvm::AtomicOrdering Order,
531 llvm::SyncScope::ID Scope) {
532 llvm::AtomicRMWInst::BinOp Op = llvm::AtomicRMWInst::Add;
533 bool PostOpMinMax = false;
534 unsigned PostOp = 0;
535
536 switch (E->getOp()) {
537 case AtomicExpr::AO__c11_atomic_init:
538 case AtomicExpr::AO__opencl_atomic_init:
539 llvm_unreachable("Already handled!");
540
541 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
542 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
543 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
544 emitAtomicCmpXchgFailureSet(CGF, E, false, Dest, Ptr, Val1, Val2,
545 FailureOrder, Size, Order, Scope);
546 return;
547 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
548 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
549 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
550 emitAtomicCmpXchgFailureSet(CGF, E, true, Dest, Ptr, Val1, Val2,
551 FailureOrder, Size, Order, Scope);
552 return;
553 case AtomicExpr::AO__atomic_compare_exchange:
554 case AtomicExpr::AO__atomic_compare_exchange_n:
555 case AtomicExpr::AO__scoped_atomic_compare_exchange:
556 case AtomicExpr::AO__scoped_atomic_compare_exchange_n: {
557 if (llvm::ConstantInt *IsWeakC = dyn_cast<llvm::ConstantInt>(IsWeak)) {
558 emitAtomicCmpXchgFailureSet(CGF, E, IsWeakC->getZExtValue(), Dest, Ptr,
559 Val1, Val2, FailureOrder, Size, Order, Scope);
560 } else {
561 // Create all the relevant BB's
562 llvm::BasicBlock *StrongBB =
563 CGF.createBasicBlock("cmpxchg.strong", CGF.CurFn);
564 llvm::BasicBlock *WeakBB = CGF.createBasicBlock("cmxchg.weak", CGF.CurFn);
565 llvm::BasicBlock *ContBB =
566 CGF.createBasicBlock("cmpxchg.continue", CGF.CurFn);
567
568 llvm::SwitchInst *SI = CGF.Builder.CreateSwitch(IsWeak, WeakBB);
569 SI->addCase(CGF.Builder.getInt1(false), StrongBB);
570
571 CGF.Builder.SetInsertPoint(StrongBB);
572 emitAtomicCmpXchgFailureSet(CGF, E, false, Dest, Ptr, Val1, Val2,
573 FailureOrder, Size, Order, Scope);
574 CGF.Builder.CreateBr(ContBB);
575
576 CGF.Builder.SetInsertPoint(WeakBB);
577 emitAtomicCmpXchgFailureSet(CGF, E, true, Dest, Ptr, Val1, Val2,
578 FailureOrder, Size, Order, Scope);
579 CGF.Builder.CreateBr(ContBB);
580
581 CGF.Builder.SetInsertPoint(ContBB);
582 }
583 return;
584 }
585 case AtomicExpr::AO__c11_atomic_load:
586 case AtomicExpr::AO__opencl_atomic_load:
587 case AtomicExpr::AO__hip_atomic_load:
588 case AtomicExpr::AO__atomic_load_n:
589 case AtomicExpr::AO__atomic_load:
590 case AtomicExpr::AO__scoped_atomic_load_n:
591 case AtomicExpr::AO__scoped_atomic_load: {
592 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Ptr);
593 Load->setAtomic(Order, Scope);
594 Load->setVolatile(E->isVolatile());
595 CGF.maybeAttachRangeForLoad(Load, E->getValueType(), E->getExprLoc());
596 auto *I = CGF.Builder.CreateStore(Load, Dest);
597 CGF.addInstToCurrentSourceAtom(I, Load);
598 return;
599 }
600
601 case AtomicExpr::AO__c11_atomic_store:
602 case AtomicExpr::AO__opencl_atomic_store:
603 case AtomicExpr::AO__hip_atomic_store:
604 case AtomicExpr::AO__atomic_store:
605 case AtomicExpr::AO__atomic_store_n:
606 case AtomicExpr::AO__scoped_atomic_store:
607 case AtomicExpr::AO__scoped_atomic_store_n: {
608 llvm::Value *LoadVal1 = CGF.Builder.CreateLoad(Val1);
609 llvm::StoreInst *Store = CGF.Builder.CreateStore(LoadVal1, Ptr);
610 Store->setAtomic(Order, Scope);
611 Store->setVolatile(E->isVolatile());
612 CGF.addInstToCurrentSourceAtom(Store, LoadVal1);
613 return;
614 }
615
616 case AtomicExpr::AO__c11_atomic_exchange:
617 case AtomicExpr::AO__hip_atomic_exchange:
618 case AtomicExpr::AO__opencl_atomic_exchange:
619 case AtomicExpr::AO__atomic_exchange_n:
620 case AtomicExpr::AO__atomic_exchange:
621 case AtomicExpr::AO__scoped_atomic_exchange_n:
622 case AtomicExpr::AO__scoped_atomic_exchange:
623 Op = llvm::AtomicRMWInst::Xchg;
624 break;
625
626 case AtomicExpr::AO__atomic_add_fetch:
627 case AtomicExpr::AO__scoped_atomic_add_fetch:
628 PostOp = E->getValueType()->isFloatingType() ? llvm::Instruction::FAdd
629 : llvm::Instruction::Add;
630 [[fallthrough]];
631 case AtomicExpr::AO__c11_atomic_fetch_add:
632 case AtomicExpr::AO__hip_atomic_fetch_add:
633 case AtomicExpr::AO__opencl_atomic_fetch_add:
634 case AtomicExpr::AO__atomic_fetch_add:
635 case AtomicExpr::AO__scoped_atomic_fetch_add:
636 Op = E->getValueType()->isFloatingType() ? llvm::AtomicRMWInst::FAdd
637 : llvm::AtomicRMWInst::Add;
638 break;
639
640 case AtomicExpr::AO__atomic_sub_fetch:
641 case AtomicExpr::AO__scoped_atomic_sub_fetch:
642 PostOp = E->getValueType()->isFloatingType() ? llvm::Instruction::FSub
643 : llvm::Instruction::Sub;
644 [[fallthrough]];
645 case AtomicExpr::AO__c11_atomic_fetch_sub:
646 case AtomicExpr::AO__hip_atomic_fetch_sub:
647 case AtomicExpr::AO__opencl_atomic_fetch_sub:
648 case AtomicExpr::AO__atomic_fetch_sub:
649 case AtomicExpr::AO__scoped_atomic_fetch_sub:
650 Op = E->getValueType()->isFloatingType() ? llvm::AtomicRMWInst::FSub
651 : llvm::AtomicRMWInst::Sub;
652 break;
653
654 case AtomicExpr::AO__atomic_min_fetch:
655 case AtomicExpr::AO__scoped_atomic_min_fetch:
656 PostOpMinMax = true;
657 [[fallthrough]];
658 case AtomicExpr::AO__c11_atomic_fetch_min:
659 case AtomicExpr::AO__hip_atomic_fetch_min:
660 case AtomicExpr::AO__opencl_atomic_fetch_min:
661 case AtomicExpr::AO__atomic_fetch_min:
662 case AtomicExpr::AO__scoped_atomic_fetch_min:
663 Op = E->getValueType()->isFloatingType()
664 ? llvm::AtomicRMWInst::FMin
665 : (E->getValueType()->isSignedIntegerType()
666 ? llvm::AtomicRMWInst::Min
667 : llvm::AtomicRMWInst::UMin);
668 break;
669
670 case AtomicExpr::AO__atomic_max_fetch:
671 case AtomicExpr::AO__scoped_atomic_max_fetch:
672 PostOpMinMax = true;
673 [[fallthrough]];
674 case AtomicExpr::AO__c11_atomic_fetch_max:
675 case AtomicExpr::AO__hip_atomic_fetch_max:
676 case AtomicExpr::AO__opencl_atomic_fetch_max:
677 case AtomicExpr::AO__atomic_fetch_max:
678 case AtomicExpr::AO__scoped_atomic_fetch_max:
679 Op = E->getValueType()->isFloatingType()
680 ? llvm::AtomicRMWInst::FMax
681 : (E->getValueType()->isSignedIntegerType()
682 ? llvm::AtomicRMWInst::Max
683 : llvm::AtomicRMWInst::UMax);
684 break;
685
686 case AtomicExpr::AO__atomic_and_fetch:
687 case AtomicExpr::AO__scoped_atomic_and_fetch:
688 PostOp = llvm::Instruction::And;
689 [[fallthrough]];
690 case AtomicExpr::AO__c11_atomic_fetch_and:
691 case AtomicExpr::AO__hip_atomic_fetch_and:
692 case AtomicExpr::AO__opencl_atomic_fetch_and:
693 case AtomicExpr::AO__atomic_fetch_and:
694 case AtomicExpr::AO__scoped_atomic_fetch_and:
695 Op = llvm::AtomicRMWInst::And;
696 break;
697
698 case AtomicExpr::AO__atomic_or_fetch:
699 case AtomicExpr::AO__scoped_atomic_or_fetch:
700 PostOp = llvm::Instruction::Or;
701 [[fallthrough]];
702 case AtomicExpr::AO__c11_atomic_fetch_or:
703 case AtomicExpr::AO__hip_atomic_fetch_or:
704 case AtomicExpr::AO__opencl_atomic_fetch_or:
705 case AtomicExpr::AO__atomic_fetch_or:
706 case AtomicExpr::AO__scoped_atomic_fetch_or:
707 Op = llvm::AtomicRMWInst::Or;
708 break;
709
710 case AtomicExpr::AO__atomic_xor_fetch:
711 case AtomicExpr::AO__scoped_atomic_xor_fetch:
712 PostOp = llvm::Instruction::Xor;
713 [[fallthrough]];
714 case AtomicExpr::AO__c11_atomic_fetch_xor:
715 case AtomicExpr::AO__hip_atomic_fetch_xor:
716 case AtomicExpr::AO__opencl_atomic_fetch_xor:
717 case AtomicExpr::AO__atomic_fetch_xor:
718 case AtomicExpr::AO__scoped_atomic_fetch_xor:
719 Op = llvm::AtomicRMWInst::Xor;
720 break;
721
722 case AtomicExpr::AO__atomic_nand_fetch:
723 case AtomicExpr::AO__scoped_atomic_nand_fetch:
724 PostOp = llvm::Instruction::And; // the NOT is special cased below
725 [[fallthrough]];
726 case AtomicExpr::AO__c11_atomic_fetch_nand:
727 case AtomicExpr::AO__atomic_fetch_nand:
728 case AtomicExpr::AO__scoped_atomic_fetch_nand:
729 Op = llvm::AtomicRMWInst::Nand;
730 break;
731
732 case AtomicExpr::AO__atomic_test_and_set: {
733 llvm::AtomicRMWInst *RMWI =
734 CGF.emitAtomicRMWInst(llvm::AtomicRMWInst::Xchg, Ptr,
735 CGF.Builder.getInt8(1), Order, Scope, E);
736 RMWI->setVolatile(E->isVolatile());
737 llvm::Value *Result = CGF.EmitToMemory(
738 CGF.Builder.CreateIsNotNull(RMWI, "tobool"), E->getType());
739 auto *I = CGF.Builder.CreateStore(Result, Dest);
740 CGF.addInstToCurrentSourceAtom(I, Result);
741 return;
742 }
743
744 case AtomicExpr::AO__atomic_clear: {
745 llvm::StoreInst *Store =
746 CGF.Builder.CreateStore(CGF.Builder.getInt8(0), Ptr);
747 Store->setAtomic(Order, Scope);
748 Store->setVolatile(E->isVolatile());
749 CGF.addInstToCurrentSourceAtom(Store, nullptr);
750 return;
751 }
752 }
753
754 llvm::Value *LoadVal1 = CGF.Builder.CreateLoad(Val1);
755 llvm::AtomicRMWInst *RMWI =
756 CGF.emitAtomicRMWInst(Op, Ptr, LoadVal1, Order, Scope, E);
757 RMWI->setVolatile(E->isVolatile());
758
759 // For __atomic_*_fetch operations, perform the operation again to
760 // determine the value which was written.
761 llvm::Value *Result = RMWI;
762 if (PostOpMinMax)
763 Result = EmitPostAtomicMinMax(CGF.Builder, E->getOp(),
765 RMWI, LoadVal1);
766 else if (PostOp)
767 Result = CGF.Builder.CreateBinOp((llvm::Instruction::BinaryOps)PostOp, RMWI,
768 LoadVal1);
769 if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch ||
770 E->getOp() == AtomicExpr::AO__scoped_atomic_nand_fetch)
771 Result = CGF.Builder.CreateNot(Result);
772 auto *I = CGF.Builder.CreateStore(Result, Dest);
773 CGF.addInstToCurrentSourceAtom(I, Result);
774}
775
776// This function emits any expression (scalar, complex, or aggregate)
777// into a temporary alloca.
778static Address
780 Address DeclPtr = CGF.CreateMemTemp(E->getType(), ".atomictmp");
781 CGF.EmitAnyExprToMem(E, DeclPtr, E->getType().getQualifiers(),
782 /*Init*/ true);
783 return DeclPtr;
784}
785
787 Address Ptr, Address Val1, Address Val2,
788 llvm::Value *IsWeak, llvm::Value *FailureOrder,
789 uint64_t Size, llvm::AtomicOrdering Order,
790 llvm::Value *Scope) {
791 auto ScopeModel = Expr->getScopeModel();
792
793 // LLVM atomic instructions always have sync scope. If clang atomic
794 // expression has no scope operand, use default LLVM sync scope.
795 if (!ScopeModel) {
796 llvm::SyncScope::ID SS;
797 if (CGF.getLangOpts().OpenCL)
798 // OpenCL approach is: "The functions that do not have memory_scope
799 // argument have the same semantics as the corresponding functions with
800 // the memory_scope argument set to memory_scope_device." See ref.:
801 // https://registry.khronos.org/OpenCL/specs/3.0-unified/html/OpenCL_C.html#atomic-functions
804 Order, CGF.getLLVMContext());
805 else
806 SS = llvm::SyncScope::System;
807 EmitAtomicOp(CGF, Expr, Dest, Ptr, Val1, Val2, IsWeak, FailureOrder, Size,
808 Order, SS);
809 return;
810 }
811
812 // Handle constant scope.
813 if (auto SC = dyn_cast<llvm::ConstantInt>(Scope)) {
814 auto SCID = CGF.getTargetHooks().getLLVMSyncScopeID(
815 CGF.CGM.getLangOpts(), ScopeModel->map(SC->getZExtValue()),
816 Order, CGF.CGM.getLLVMContext());
817 EmitAtomicOp(CGF, Expr, Dest, Ptr, Val1, Val2, IsWeak, FailureOrder, Size,
818 Order, SCID);
819 return;
820 }
821
822 // Handle non-constant scope.
823 auto &Builder = CGF.Builder;
824 auto Scopes = ScopeModel->getRuntimeValues();
825 llvm::DenseMap<unsigned, llvm::BasicBlock *> BB;
826 for (auto S : Scopes)
827 BB[S] = CGF.createBasicBlock(getAsString(ScopeModel->map(S)), CGF.CurFn);
828
829 llvm::BasicBlock *ContBB =
830 CGF.createBasicBlock("atomic.scope.continue", CGF.CurFn);
831
832 auto *SC = Builder.CreateIntCast(Scope, Builder.getInt32Ty(), false);
833 // If unsupported sync scope is encountered at run time, assume a fallback
834 // sync scope value.
835 auto FallBack = ScopeModel->getFallBackValue();
836 llvm::SwitchInst *SI = Builder.CreateSwitch(SC, BB[FallBack]);
837 for (auto S : Scopes) {
838 auto *B = BB[S];
839 if (S != FallBack)
840 SI->addCase(Builder.getInt32(S), B);
841
842 Builder.SetInsertPoint(B);
843 EmitAtomicOp(CGF, Expr, Dest, Ptr, Val1, Val2, IsWeak, FailureOrder, Size,
844 Order,
846 ScopeModel->map(S),
847 Order,
848 CGF.getLLVMContext()));
849 Builder.CreateBr(ContBB);
850 }
851
852 Builder.SetInsertPoint(ContBB);
853}
854
857
858 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
859 QualType MemTy = AtomicTy;
860 if (const AtomicType *AT = AtomicTy->getAs<AtomicType>())
861 MemTy = AT->getValueType();
862 llvm::Value *IsWeak = nullptr, *OrderFail = nullptr;
863
864 Address Val1 = Address::invalid();
865 Address Val2 = Address::invalid();
866 Address Dest = Address::invalid();
868
869 if (E->getOp() == AtomicExpr::AO__c11_atomic_init ||
870 E->getOp() == AtomicExpr::AO__opencl_atomic_init) {
871 LValue lvalue = MakeAddrLValue(Ptr, AtomicTy);
872 EmitAtomicInit(E->getVal1(), lvalue);
873 return RValue::get(nullptr);
874 }
875
876 auto TInfo = getContext().getTypeInfoInChars(AtomicTy);
877 uint64_t Size = TInfo.Width.getQuantity();
878 unsigned MaxInlineWidthInBits = getTarget().getMaxAtomicInlineWidth();
879
880 CharUnits MaxInlineWidth =
881 getContext().toCharUnitsFromBits(MaxInlineWidthInBits);
882 DiagnosticsEngine &Diags = CGM.getDiags();
883 bool Misaligned = (Ptr.getAlignment() % TInfo.Width) != 0;
884 bool Oversized = getContext().toBits(TInfo.Width) > MaxInlineWidthInBits;
885 if (Misaligned) {
886 Diags.Report(E->getBeginLoc(), diag::warn_atomic_op_misaligned)
887 << (int)TInfo.Width.getQuantity()
888 << (int)Ptr.getAlignment().getQuantity();
889 }
890 if (Oversized) {
891 Diags.Report(E->getBeginLoc(), diag::warn_atomic_op_oversized)
892 << (int)TInfo.Width.getQuantity() << (int)MaxInlineWidth.getQuantity();
893 }
894
895 llvm::Value *Order = EmitScalarExpr(E->getOrder());
896 llvm::Value *Scope =
897 E->getScopeModel() ? EmitScalarExpr(E->getScope()) : nullptr;
898 bool ShouldCastToIntPtrTy = true;
899
900 switch (E->getOp()) {
901 case AtomicExpr::AO__c11_atomic_init:
902 case AtomicExpr::AO__opencl_atomic_init:
903 llvm_unreachable("Already handled above with EmitAtomicInit!");
904
905 case AtomicExpr::AO__atomic_load_n:
906 case AtomicExpr::AO__scoped_atomic_load_n:
907 case AtomicExpr::AO__c11_atomic_load:
908 case AtomicExpr::AO__opencl_atomic_load:
909 case AtomicExpr::AO__hip_atomic_load:
910 case AtomicExpr::AO__atomic_test_and_set:
911 case AtomicExpr::AO__atomic_clear:
912 break;
913
914 case AtomicExpr::AO__atomic_load:
915 case AtomicExpr::AO__scoped_atomic_load:
917 break;
918
919 case AtomicExpr::AO__atomic_store:
920 case AtomicExpr::AO__scoped_atomic_store:
922 break;
923
924 case AtomicExpr::AO__atomic_exchange:
925 case AtomicExpr::AO__scoped_atomic_exchange:
928 break;
929
930 case AtomicExpr::AO__atomic_compare_exchange:
931 case AtomicExpr::AO__atomic_compare_exchange_n:
932 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
933 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
934 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
935 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
936 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
937 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
938 case AtomicExpr::AO__scoped_atomic_compare_exchange:
939 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
941 if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange ||
942 E->getOp() == AtomicExpr::AO__scoped_atomic_compare_exchange)
944 else
945 Val2 = EmitValToTemp(*this, E->getVal2());
946 OrderFail = EmitScalarExpr(E->getOrderFail());
947 if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange_n ||
948 E->getOp() == AtomicExpr::AO__atomic_compare_exchange ||
949 E->getOp() == AtomicExpr::AO__scoped_atomic_compare_exchange_n ||
950 E->getOp() == AtomicExpr::AO__scoped_atomic_compare_exchange)
951 IsWeak = EmitScalarExpr(E->getWeak());
952 break;
953
954 case AtomicExpr::AO__c11_atomic_fetch_add:
955 case AtomicExpr::AO__c11_atomic_fetch_sub:
956 case AtomicExpr::AO__hip_atomic_fetch_add:
957 case AtomicExpr::AO__hip_atomic_fetch_sub:
958 case AtomicExpr::AO__opencl_atomic_fetch_add:
959 case AtomicExpr::AO__opencl_atomic_fetch_sub:
960 if (MemTy->isPointerType()) {
961 // For pointer arithmetic, we're required to do a bit of math:
962 // adding 1 to an int* is not the same as adding 1 to a uintptr_t.
963 // ... but only for the C11 builtins. The GNU builtins expect the
964 // user to multiply by sizeof(T).
965 QualType Val1Ty = E->getVal1()->getType();
966 llvm::Value *Val1Scalar = EmitScalarExpr(E->getVal1());
967 CharUnits PointeeIncAmt =
968 getContext().getTypeSizeInChars(MemTy->getPointeeType());
969 Val1Scalar = Builder.CreateMul(Val1Scalar, CGM.getSize(PointeeIncAmt));
970 auto Temp = CreateMemTemp(Val1Ty, ".atomictmp");
971 Val1 = Temp;
972 EmitStoreOfScalar(Val1Scalar, MakeAddrLValue(Temp, Val1Ty));
973 break;
974 }
975 [[fallthrough]];
976 case AtomicExpr::AO__atomic_fetch_add:
977 case AtomicExpr::AO__atomic_fetch_max:
978 case AtomicExpr::AO__atomic_fetch_min:
979 case AtomicExpr::AO__atomic_fetch_sub:
980 case AtomicExpr::AO__atomic_add_fetch:
981 case AtomicExpr::AO__atomic_max_fetch:
982 case AtomicExpr::AO__atomic_min_fetch:
983 case AtomicExpr::AO__atomic_sub_fetch:
984 case AtomicExpr::AO__c11_atomic_fetch_max:
985 case AtomicExpr::AO__c11_atomic_fetch_min:
986 case AtomicExpr::AO__opencl_atomic_fetch_max:
987 case AtomicExpr::AO__opencl_atomic_fetch_min:
988 case AtomicExpr::AO__hip_atomic_fetch_max:
989 case AtomicExpr::AO__hip_atomic_fetch_min:
990 case AtomicExpr::AO__scoped_atomic_fetch_add:
991 case AtomicExpr::AO__scoped_atomic_fetch_max:
992 case AtomicExpr::AO__scoped_atomic_fetch_min:
993 case AtomicExpr::AO__scoped_atomic_fetch_sub:
994 case AtomicExpr::AO__scoped_atomic_add_fetch:
995 case AtomicExpr::AO__scoped_atomic_max_fetch:
996 case AtomicExpr::AO__scoped_atomic_min_fetch:
997 case AtomicExpr::AO__scoped_atomic_sub_fetch:
998 ShouldCastToIntPtrTy = !MemTy->isFloatingType();
999 [[fallthrough]];
1000
1001 case AtomicExpr::AO__atomic_fetch_and:
1002 case AtomicExpr::AO__atomic_fetch_nand:
1003 case AtomicExpr::AO__atomic_fetch_or:
1004 case AtomicExpr::AO__atomic_fetch_xor:
1005 case AtomicExpr::AO__atomic_and_fetch:
1006 case AtomicExpr::AO__atomic_nand_fetch:
1007 case AtomicExpr::AO__atomic_or_fetch:
1008 case AtomicExpr::AO__atomic_xor_fetch:
1009 case AtomicExpr::AO__atomic_store_n:
1010 case AtomicExpr::AO__atomic_exchange_n:
1011 case AtomicExpr::AO__c11_atomic_fetch_and:
1012 case AtomicExpr::AO__c11_atomic_fetch_nand:
1013 case AtomicExpr::AO__c11_atomic_fetch_or:
1014 case AtomicExpr::AO__c11_atomic_fetch_xor:
1015 case AtomicExpr::AO__c11_atomic_store:
1016 case AtomicExpr::AO__c11_atomic_exchange:
1017 case AtomicExpr::AO__hip_atomic_fetch_and:
1018 case AtomicExpr::AO__hip_atomic_fetch_or:
1019 case AtomicExpr::AO__hip_atomic_fetch_xor:
1020 case AtomicExpr::AO__hip_atomic_store:
1021 case AtomicExpr::AO__hip_atomic_exchange:
1022 case AtomicExpr::AO__opencl_atomic_fetch_and:
1023 case AtomicExpr::AO__opencl_atomic_fetch_or:
1024 case AtomicExpr::AO__opencl_atomic_fetch_xor:
1025 case AtomicExpr::AO__opencl_atomic_store:
1026 case AtomicExpr::AO__opencl_atomic_exchange:
1027 case AtomicExpr::AO__scoped_atomic_fetch_and:
1028 case AtomicExpr::AO__scoped_atomic_fetch_nand:
1029 case AtomicExpr::AO__scoped_atomic_fetch_or:
1030 case AtomicExpr::AO__scoped_atomic_fetch_xor:
1031 case AtomicExpr::AO__scoped_atomic_and_fetch:
1032 case AtomicExpr::AO__scoped_atomic_nand_fetch:
1033 case AtomicExpr::AO__scoped_atomic_or_fetch:
1034 case AtomicExpr::AO__scoped_atomic_xor_fetch:
1035 case AtomicExpr::AO__scoped_atomic_store_n:
1036 case AtomicExpr::AO__scoped_atomic_exchange_n:
1037 Val1 = EmitValToTemp(*this, E->getVal1());
1038 break;
1039 }
1040
1041 QualType RValTy = E->getType().getUnqualifiedType();
1042
1043 // The inlined atomics only function on iN types, where N is a power of 2. We
1044 // need to make sure (via temporaries if necessary) that all incoming values
1045 // are compatible.
1046 LValue AtomicVal = MakeAddrLValue(Ptr, AtomicTy);
1047 AtomicInfo Atomics(*this, AtomicVal);
1048
1049 if (ShouldCastToIntPtrTy) {
1050 Ptr = Atomics.castToAtomicIntPointer(Ptr);
1051 if (Val1.isValid())
1052 Val1 = Atomics.convertToAtomicIntPointer(Val1);
1053 if (Val2.isValid())
1054 Val2 = Atomics.convertToAtomicIntPointer(Val2);
1055 }
1056 if (Dest.isValid()) {
1057 if (ShouldCastToIntPtrTy)
1058 Dest = Atomics.castToAtomicIntPointer(Dest);
1059 } else if (E->isCmpXChg())
1060 Dest = CreateMemTemp(RValTy, "cmpxchg.bool");
1061 else if (!RValTy->isVoidType()) {
1062 Dest = Atomics.CreateTempAlloca();
1063 if (ShouldCastToIntPtrTy)
1064 Dest = Atomics.castToAtomicIntPointer(Dest);
1065 }
1066
1067 bool PowerOf2Size = (Size & (Size - 1)) == 0;
1068 bool UseLibcall = !PowerOf2Size || (Size > 16);
1069
1070 // For atomics larger than 16 bytes, emit a libcall from the frontend. This
1071 // avoids the overhead of dealing with excessively-large value types in IR.
1072 // Non-power-of-2 values also lower to libcall here, as they are not currently
1073 // permitted in IR instructions (although that constraint could be relaxed in
1074 // the future). For other cases where a libcall is required on a given
1075 // platform, we let the backend handle it (this includes handling for all of
1076 // the size-optimized libcall variants, which are only valid up to 16 bytes.)
1077 //
1078 // See: https://llvm.org/docs/Atomics.html#libcalls-atomic
1079 if (UseLibcall) {
1080 CallArgList Args;
1081 // For non-optimized library calls, the size is the first parameter.
1082 Args.add(RValue::get(llvm::ConstantInt::get(SizeTy, Size)),
1083 getContext().getSizeType());
1084
1085 // The atomic address is the second parameter.
1086 // The OpenCL atomic library functions only accept pointer arguments to
1087 // generic address space.
1088 auto CastToGenericAddrSpace = [&](llvm::Value *V, QualType PT) {
1089 if (!E->isOpenCL())
1090 return V;
1091 auto AS = PT->castAs<PointerType>()->getPointeeType().getAddressSpace();
1092 if (AS == LangAS::opencl_generic)
1093 return V;
1094 auto DestAS = getContext().getTargetAddressSpace(LangAS::opencl_generic);
1095 auto *DestType = llvm::PointerType::get(getLLVMContext(), DestAS);
1096
1097 return getTargetHooks().performAddrSpaceCast(*this, V, AS, DestType,
1098 false);
1099 };
1100
1101 Args.add(RValue::get(CastToGenericAddrSpace(Ptr.emitRawPointer(*this),
1102 E->getPtr()->getType())),
1104
1105 // The next 1-3 parameters are op-dependent.
1106 std::string LibCallName;
1107 QualType RetTy;
1108 bool HaveRetTy = false;
1109 switch (E->getOp()) {
1110 case AtomicExpr::AO__c11_atomic_init:
1111 case AtomicExpr::AO__opencl_atomic_init:
1112 llvm_unreachable("Already handled!");
1113
1114 // There is only one libcall for compare an exchange, because there is no
1115 // optimisation benefit possible from a libcall version of a weak compare
1116 // and exchange.
1117 // bool __atomic_compare_exchange(size_t size, void *mem, void *expected,
1118 // void *desired, int success, int failure)
1119 case AtomicExpr::AO__atomic_compare_exchange:
1120 case AtomicExpr::AO__atomic_compare_exchange_n:
1121 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1122 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1123 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
1124 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
1125 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
1126 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
1127 case AtomicExpr::AO__scoped_atomic_compare_exchange:
1128 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
1129 LibCallName = "__atomic_compare_exchange";
1130 RetTy = getContext().BoolTy;
1131 HaveRetTy = true;
1132 Args.add(RValue::get(CastToGenericAddrSpace(Val1.emitRawPointer(*this),
1133 E->getVal1()->getType())),
1135 Args.add(RValue::get(CastToGenericAddrSpace(Val2.emitRawPointer(*this),
1136 E->getVal2()->getType())),
1138 Args.add(RValue::get(Order), getContext().IntTy);
1139 Order = OrderFail;
1140 break;
1141 // void __atomic_exchange(size_t size, void *mem, void *val, void *return,
1142 // int order)
1143 case AtomicExpr::AO__atomic_exchange:
1144 case AtomicExpr::AO__atomic_exchange_n:
1145 case AtomicExpr::AO__c11_atomic_exchange:
1146 case AtomicExpr::AO__hip_atomic_exchange:
1147 case AtomicExpr::AO__opencl_atomic_exchange:
1148 case AtomicExpr::AO__scoped_atomic_exchange:
1149 case AtomicExpr::AO__scoped_atomic_exchange_n:
1150 LibCallName = "__atomic_exchange";
1151 Args.add(RValue::get(CastToGenericAddrSpace(Val1.emitRawPointer(*this),
1152 E->getVal1()->getType())),
1154 break;
1155 // void __atomic_store(size_t size, void *mem, void *val, int order)
1156 case AtomicExpr::AO__atomic_store:
1157 case AtomicExpr::AO__atomic_store_n:
1158 case AtomicExpr::AO__c11_atomic_store:
1159 case AtomicExpr::AO__hip_atomic_store:
1160 case AtomicExpr::AO__opencl_atomic_store:
1161 case AtomicExpr::AO__scoped_atomic_store:
1162 case AtomicExpr::AO__scoped_atomic_store_n:
1163 LibCallName = "__atomic_store";
1164 RetTy = getContext().VoidTy;
1165 HaveRetTy = true;
1166 Args.add(RValue::get(CastToGenericAddrSpace(Val1.emitRawPointer(*this),
1167 E->getVal1()->getType())),
1169 break;
1170 // void __atomic_load(size_t size, void *mem, void *return, int order)
1171 case AtomicExpr::AO__atomic_load:
1172 case AtomicExpr::AO__atomic_load_n:
1173 case AtomicExpr::AO__c11_atomic_load:
1174 case AtomicExpr::AO__hip_atomic_load:
1175 case AtomicExpr::AO__opencl_atomic_load:
1176 case AtomicExpr::AO__scoped_atomic_load:
1177 case AtomicExpr::AO__scoped_atomic_load_n:
1178 LibCallName = "__atomic_load";
1179 break;
1180 case AtomicExpr::AO__atomic_add_fetch:
1181 case AtomicExpr::AO__scoped_atomic_add_fetch:
1182 case AtomicExpr::AO__atomic_fetch_add:
1183 case AtomicExpr::AO__c11_atomic_fetch_add:
1184 case AtomicExpr::AO__hip_atomic_fetch_add:
1185 case AtomicExpr::AO__opencl_atomic_fetch_add:
1186 case AtomicExpr::AO__scoped_atomic_fetch_add:
1187 case AtomicExpr::AO__atomic_and_fetch:
1188 case AtomicExpr::AO__scoped_atomic_and_fetch:
1189 case AtomicExpr::AO__atomic_fetch_and:
1190 case AtomicExpr::AO__c11_atomic_fetch_and:
1191 case AtomicExpr::AO__hip_atomic_fetch_and:
1192 case AtomicExpr::AO__opencl_atomic_fetch_and:
1193 case AtomicExpr::AO__scoped_atomic_fetch_and:
1194 case AtomicExpr::AO__atomic_or_fetch:
1195 case AtomicExpr::AO__scoped_atomic_or_fetch:
1196 case AtomicExpr::AO__atomic_fetch_or:
1197 case AtomicExpr::AO__c11_atomic_fetch_or:
1198 case AtomicExpr::AO__hip_atomic_fetch_or:
1199 case AtomicExpr::AO__opencl_atomic_fetch_or:
1200 case AtomicExpr::AO__scoped_atomic_fetch_or:
1201 case AtomicExpr::AO__atomic_sub_fetch:
1202 case AtomicExpr::AO__scoped_atomic_sub_fetch:
1203 case AtomicExpr::AO__atomic_fetch_sub:
1204 case AtomicExpr::AO__c11_atomic_fetch_sub:
1205 case AtomicExpr::AO__hip_atomic_fetch_sub:
1206 case AtomicExpr::AO__opencl_atomic_fetch_sub:
1207 case AtomicExpr::AO__scoped_atomic_fetch_sub:
1208 case AtomicExpr::AO__atomic_xor_fetch:
1209 case AtomicExpr::AO__scoped_atomic_xor_fetch:
1210 case AtomicExpr::AO__atomic_fetch_xor:
1211 case AtomicExpr::AO__c11_atomic_fetch_xor:
1212 case AtomicExpr::AO__hip_atomic_fetch_xor:
1213 case AtomicExpr::AO__opencl_atomic_fetch_xor:
1214 case AtomicExpr::AO__scoped_atomic_fetch_xor:
1215 case AtomicExpr::AO__atomic_nand_fetch:
1216 case AtomicExpr::AO__atomic_fetch_nand:
1217 case AtomicExpr::AO__c11_atomic_fetch_nand:
1218 case AtomicExpr::AO__scoped_atomic_fetch_nand:
1219 case AtomicExpr::AO__scoped_atomic_nand_fetch:
1220 case AtomicExpr::AO__atomic_min_fetch:
1221 case AtomicExpr::AO__atomic_fetch_min:
1222 case AtomicExpr::AO__c11_atomic_fetch_min:
1223 case AtomicExpr::AO__hip_atomic_fetch_min:
1224 case AtomicExpr::AO__opencl_atomic_fetch_min:
1225 case AtomicExpr::AO__scoped_atomic_fetch_min:
1226 case AtomicExpr::AO__scoped_atomic_min_fetch:
1227 case AtomicExpr::AO__atomic_max_fetch:
1228 case AtomicExpr::AO__atomic_fetch_max:
1229 case AtomicExpr::AO__c11_atomic_fetch_max:
1230 case AtomicExpr::AO__hip_atomic_fetch_max:
1231 case AtomicExpr::AO__opencl_atomic_fetch_max:
1232 case AtomicExpr::AO__scoped_atomic_fetch_max:
1233 case AtomicExpr::AO__scoped_atomic_max_fetch:
1234 case AtomicExpr::AO__atomic_test_and_set:
1235 case AtomicExpr::AO__atomic_clear:
1236 llvm_unreachable("Integral atomic operations always become atomicrmw!");
1237 }
1238
1239 if (E->isOpenCL()) {
1240 LibCallName =
1241 std::string("__opencl") + StringRef(LibCallName).drop_front(1).str();
1242 }
1243 // By default, assume we return a value of the atomic type.
1244 if (!HaveRetTy) {
1245 // Value is returned through parameter before the order.
1246 RetTy = getContext().VoidTy;
1247 Args.add(RValue::get(
1248 CastToGenericAddrSpace(Dest.emitRawPointer(*this), RetTy)),
1250 }
1251 // Order is always the last parameter.
1252 Args.add(RValue::get(Order),
1253 getContext().IntTy);
1254 if (E->isOpenCL())
1256
1257 RValue Res = emitAtomicLibcall(*this, LibCallName, RetTy, Args);
1258 // The value is returned directly from the libcall.
1259 if (E->isCmpXChg())
1260 return Res;
1261
1262 if (RValTy->isVoidType())
1263 return RValue::get(nullptr);
1264
1266 RValTy, E->getExprLoc());
1267 }
1268
1269 bool IsStore = E->getOp() == AtomicExpr::AO__c11_atomic_store ||
1270 E->getOp() == AtomicExpr::AO__opencl_atomic_store ||
1271 E->getOp() == AtomicExpr::AO__hip_atomic_store ||
1272 E->getOp() == AtomicExpr::AO__atomic_store ||
1273 E->getOp() == AtomicExpr::AO__atomic_store_n ||
1274 E->getOp() == AtomicExpr::AO__scoped_atomic_store ||
1275 E->getOp() == AtomicExpr::AO__scoped_atomic_store_n ||
1276 E->getOp() == AtomicExpr::AO__atomic_clear;
1277 bool IsLoad = E->getOp() == AtomicExpr::AO__c11_atomic_load ||
1278 E->getOp() == AtomicExpr::AO__opencl_atomic_load ||
1279 E->getOp() == AtomicExpr::AO__hip_atomic_load ||
1280 E->getOp() == AtomicExpr::AO__atomic_load ||
1281 E->getOp() == AtomicExpr::AO__atomic_load_n ||
1282 E->getOp() == AtomicExpr::AO__scoped_atomic_load ||
1283 E->getOp() == AtomicExpr::AO__scoped_atomic_load_n;
1284
1285 if (isa<llvm::ConstantInt>(Order)) {
1286 auto ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
1287 // We should not ever get to a case where the ordering isn't a valid C ABI
1288 // value, but it's hard to enforce that in general.
1289 if (llvm::isValidAtomicOrderingCABI(ord))
1290 switch ((llvm::AtomicOrderingCABI)ord) {
1291 case llvm::AtomicOrderingCABI::relaxed:
1292 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1293 llvm::AtomicOrdering::Monotonic, Scope);
1294 break;
1295 case llvm::AtomicOrderingCABI::consume:
1296 case llvm::AtomicOrderingCABI::acquire:
1297 if (IsStore)
1298 break; // Avoid crashing on code with undefined behavior
1299 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1300 llvm::AtomicOrdering::Acquire, Scope);
1301 break;
1302 case llvm::AtomicOrderingCABI::release:
1303 if (IsLoad)
1304 break; // Avoid crashing on code with undefined behavior
1305 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1306 llvm::AtomicOrdering::Release, Scope);
1307 break;
1308 case llvm::AtomicOrderingCABI::acq_rel:
1309 if (IsLoad || IsStore)
1310 break; // Avoid crashing on code with undefined behavior
1311 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1312 llvm::AtomicOrdering::AcquireRelease, Scope);
1313 break;
1314 case llvm::AtomicOrderingCABI::seq_cst:
1315 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1316 llvm::AtomicOrdering::SequentiallyConsistent, Scope);
1317 break;
1318 }
1319 if (RValTy->isVoidType())
1320 return RValue::get(nullptr);
1321
1323 RValTy, E->getExprLoc());
1324 }
1325
1326 // Long case, when Order isn't obviously constant.
1327
1328 // Create all the relevant BB's
1329 llvm::BasicBlock *MonotonicBB = nullptr, *AcquireBB = nullptr,
1330 *ReleaseBB = nullptr, *AcqRelBB = nullptr,
1331 *SeqCstBB = nullptr;
1332 MonotonicBB = createBasicBlock("monotonic", CurFn);
1333 if (!IsStore)
1334 AcquireBB = createBasicBlock("acquire", CurFn);
1335 if (!IsLoad)
1336 ReleaseBB = createBasicBlock("release", CurFn);
1337 if (!IsLoad && !IsStore)
1338 AcqRelBB = createBasicBlock("acqrel", CurFn);
1339 SeqCstBB = createBasicBlock("seqcst", CurFn);
1340 llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
1341
1342 // Create the switch for the split
1343 // MonotonicBB is arbitrarily chosen as the default case; in practice, this
1344 // doesn't matter unless someone is crazy enough to use something that
1345 // doesn't fold to a constant for the ordering.
1346 Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
1347 llvm::SwitchInst *SI = Builder.CreateSwitch(Order, MonotonicBB);
1348
1349 // Emit all the different atomics
1350 Builder.SetInsertPoint(MonotonicBB);
1351 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1352 llvm::AtomicOrdering::Monotonic, Scope);
1353 Builder.CreateBr(ContBB);
1354 if (!IsStore) {
1355 Builder.SetInsertPoint(AcquireBB);
1356 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1357 llvm::AtomicOrdering::Acquire, Scope);
1358 Builder.CreateBr(ContBB);
1359 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::consume),
1360 AcquireBB);
1361 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::acquire),
1362 AcquireBB);
1363 }
1364 if (!IsLoad) {
1365 Builder.SetInsertPoint(ReleaseBB);
1366 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1367 llvm::AtomicOrdering::Release, Scope);
1368 Builder.CreateBr(ContBB);
1369 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::release),
1370 ReleaseBB);
1371 }
1372 if (!IsLoad && !IsStore) {
1373 Builder.SetInsertPoint(AcqRelBB);
1374 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1375 llvm::AtomicOrdering::AcquireRelease, Scope);
1376 Builder.CreateBr(ContBB);
1377 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::acq_rel),
1378 AcqRelBB);
1379 }
1380 Builder.SetInsertPoint(SeqCstBB);
1381 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1382 llvm::AtomicOrdering::SequentiallyConsistent, Scope);
1383 Builder.CreateBr(ContBB);
1384 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::seq_cst),
1385 SeqCstBB);
1386
1387 // Cleanup and return
1388 Builder.SetInsertPoint(ContBB);
1389 if (RValTy->isVoidType())
1390 return RValue::get(nullptr);
1391
1392 assert(Atomics.getValueSizeInBits() <= Atomics.getAtomicSizeInBits());
1394 RValTy, E->getExprLoc());
1395}
1396
1397Address AtomicInfo::castToAtomicIntPointer(Address addr) const {
1398 llvm::IntegerType *ty =
1399 llvm::IntegerType::get(CGF.getLLVMContext(), AtomicSizeInBits);
1400 return addr.withElementType(ty);
1401}
1402
1403Address AtomicInfo::convertToAtomicIntPointer(Address Addr) const {
1404 llvm::Type *Ty = Addr.getElementType();
1405 uint64_t SourceSizeInBits = CGF.CGM.getDataLayout().getTypeSizeInBits(Ty);
1406 if (SourceSizeInBits != AtomicSizeInBits) {
1407 Address Tmp = CreateTempAlloca();
1408 CGF.Builder.CreateMemCpy(Tmp, Addr,
1409 std::min(AtomicSizeInBits, SourceSizeInBits) / 8);
1410 Addr = Tmp;
1411 }
1412
1413 return castToAtomicIntPointer(Addr);
1414}
1415
1416RValue AtomicInfo::convertAtomicTempToRValue(Address addr,
1417 AggValueSlot resultSlot,
1418 SourceLocation loc,
1419 bool asValue) const {
1420 if (LVal.isSimple()) {
1421 if (EvaluationKind == TEK_Aggregate)
1422 return resultSlot.asRValue();
1423
1424 // Drill into the padding structure if we have one.
1425 if (hasPadding())
1426 addr = CGF.Builder.CreateStructGEP(addr, 0);
1427
1428 // Otherwise, just convert the temporary to an r-value using the
1429 // normal conversion routine.
1430 return CGF.convertTempToRValue(addr, getValueType(), loc);
1431 }
1432 if (!asValue)
1433 // Get RValue from temp memory as atomic for non-simple lvalues
1434 return RValue::get(CGF.Builder.CreateLoad(addr));
1435 if (LVal.isBitField())
1436 return CGF.EmitLoadOfBitfieldLValue(
1437 LValue::MakeBitfield(addr, LVal.getBitFieldInfo(), LVal.getType(),
1438 LVal.getBaseInfo(), TBAAAccessInfo()), loc);
1439 if (LVal.isVectorElt())
1440 return CGF.EmitLoadOfLValue(
1441 LValue::MakeVectorElt(addr, LVal.getVectorIdx(), LVal.getType(),
1442 LVal.getBaseInfo(), TBAAAccessInfo()), loc);
1443 assert(LVal.isExtVectorElt());
1444 return CGF.EmitLoadOfExtVectorElementLValue(LValue::MakeExtVectorElt(
1445 addr, LVal.getExtVectorElts(), LVal.getType(),
1446 LVal.getBaseInfo(), TBAAAccessInfo()));
1447}
1448
1449/// Return true if \param ValTy is a type that should be casted to integer
1450/// around the atomic memory operation. If \param CmpXchg is true, then the
1451/// cast of a floating point type is made as that instruction can not have
1452/// floating point operands. TODO: Allow compare-and-exchange and FP - see
1453/// comment in AtomicExpandPass.cpp.
1454static bool shouldCastToInt(llvm::Type *ValTy, bool CmpXchg) {
1455 if (ValTy->isFloatingPointTy())
1456 return ValTy->isX86_FP80Ty() || CmpXchg;
1457 return !ValTy->isIntegerTy() && !ValTy->isPointerTy();
1458}
1459
1460RValue AtomicInfo::ConvertToValueOrAtomic(llvm::Value *Val,
1461 AggValueSlot ResultSlot,
1462 SourceLocation Loc, bool AsValue,
1463 bool CmpXchg) const {
1464 // Try not to in some easy cases.
1465 assert((Val->getType()->isIntegerTy() || Val->getType()->isPointerTy() ||
1466 Val->getType()->isIEEELikeFPTy()) &&
1467 "Expected integer, pointer or floating point value when converting "
1468 "result.");
1469 if (getEvaluationKind() == TEK_Scalar &&
1470 (((!LVal.isBitField() ||
1471 LVal.getBitFieldInfo().Size == ValueSizeInBits) &&
1472 !hasPadding()) ||
1473 !AsValue)) {
1474 auto *ValTy = AsValue
1475 ? CGF.ConvertTypeForMem(ValueTy)
1476 : getAtomicAddress().getElementType();
1477 if (!shouldCastToInt(ValTy, CmpXchg)) {
1478 assert((!ValTy->isIntegerTy() || Val->getType() == ValTy) &&
1479 "Different integer types.");
1480 return RValue::get(CGF.EmitFromMemory(Val, ValueTy));
1481 }
1482 if (llvm::CastInst::isBitCastable(Val->getType(), ValTy))
1483 return RValue::get(CGF.Builder.CreateBitCast(Val, ValTy));
1484 }
1485
1486 // Create a temporary. This needs to be big enough to hold the
1487 // atomic integer.
1488 Address Temp = Address::invalid();
1489 bool TempIsVolatile = false;
1490 if (AsValue && getEvaluationKind() == TEK_Aggregate) {
1491 assert(!ResultSlot.isIgnored());
1492 Temp = ResultSlot.getAddress();
1493 TempIsVolatile = ResultSlot.isVolatile();
1494 } else {
1495 Temp = CreateTempAlloca();
1496 }
1497
1498 // Slam the integer into the temporary.
1499 Address CastTemp = castToAtomicIntPointer(Temp);
1500 CGF.Builder.CreateStore(Val, CastTemp)->setVolatile(TempIsVolatile);
1501
1502 return convertAtomicTempToRValue(Temp, ResultSlot, Loc, AsValue);
1503}
1504
1505void AtomicInfo::EmitAtomicLoadLibcall(llvm::Value *AddForLoaded,
1506 llvm::AtomicOrdering AO, bool) {
1507 // void __atomic_load(size_t size, void *mem, void *return, int order);
1508 CallArgList Args;
1509 Args.add(RValue::get(getAtomicSizeValue()), CGF.getContext().getSizeType());
1510 Args.add(RValue::get(getAtomicPointer()), CGF.getContext().VoidPtrTy);
1511 Args.add(RValue::get(AddForLoaded), CGF.getContext().VoidPtrTy);
1512 Args.add(
1513 RValue::get(llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(AO))),
1514 CGF.getContext().IntTy);
1515 emitAtomicLibcall(CGF, "__atomic_load", CGF.getContext().VoidTy, Args);
1516}
1517
1518llvm::Value *AtomicInfo::EmitAtomicLoadOp(llvm::AtomicOrdering AO,
1519 bool IsVolatile, bool CmpXchg) {
1520 // Okay, we're doing this natively.
1521 Address Addr = getAtomicAddress();
1522 if (shouldCastToInt(Addr.getElementType(), CmpXchg))
1523 Addr = castToAtomicIntPointer(Addr);
1524 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Addr, "atomic-load");
1525 Load->setAtomic(AO);
1526
1527 // Other decoration.
1528 if (IsVolatile)
1529 Load->setVolatile(true);
1530 CGF.CGM.DecorateInstructionWithTBAA(Load, LVal.getTBAAInfo());
1531 return Load;
1532}
1533
1534/// An LValue is a candidate for having its loads and stores be made atomic if
1535/// we are operating under /volatile:ms *and* the LValue itself is volatile and
1536/// performing such an operation can be performed without a libcall.
1538 if (!CGM.getLangOpts().MSVolatile) return false;
1539 AtomicInfo AI(*this, LV);
1540 bool IsVolatile = LV.isVolatile() || hasVolatileMember(LV.getType());
1541 // An atomic is inline if we don't need to use a libcall.
1542 bool AtomicIsInline = !AI.shouldUseLibcall();
1543 // MSVC doesn't seem to do this for types wider than a pointer.
1544 if (getContext().getTypeSize(LV.getType()) >
1545 getContext().getTypeSize(getContext().getIntPtrType()))
1546 return false;
1547 return IsVolatile && AtomicIsInline;
1548}
1549
1551 AggValueSlot Slot) {
1552 llvm::AtomicOrdering AO;
1553 bool IsVolatile = LV.isVolatileQualified();
1554 if (LV.getType()->isAtomicType()) {
1555 AO = llvm::AtomicOrdering::SequentiallyConsistent;
1556 } else {
1557 AO = llvm::AtomicOrdering::Acquire;
1558 IsVolatile = true;
1559 }
1560 return EmitAtomicLoad(LV, SL, AO, IsVolatile, Slot);
1561}
1562
1563RValue AtomicInfo::EmitAtomicLoad(AggValueSlot ResultSlot, SourceLocation Loc,
1564 bool AsValue, llvm::AtomicOrdering AO,
1565 bool IsVolatile) {
1566 // Check whether we should use a library call.
1567 if (shouldUseLibcall()) {
1568 Address TempAddr = Address::invalid();
1569 if (LVal.isSimple() && !ResultSlot.isIgnored()) {
1570 assert(getEvaluationKind() == TEK_Aggregate);
1571 TempAddr = ResultSlot.getAddress();
1572 } else
1573 TempAddr = CreateTempAlloca();
1574
1575 EmitAtomicLoadLibcall(TempAddr.emitRawPointer(CGF), AO, IsVolatile);
1576
1577 // Okay, turn that back into the original value or whole atomic (for
1578 // non-simple lvalues) type.
1579 return convertAtomicTempToRValue(TempAddr, ResultSlot, Loc, AsValue);
1580 }
1581
1582 // Okay, we're doing this natively.
1583 auto *Load = EmitAtomicLoadOp(AO, IsVolatile);
1584
1585 // If we're ignoring an aggregate return, don't do anything.
1586 if (getEvaluationKind() == TEK_Aggregate && ResultSlot.isIgnored())
1587 return RValue::getAggregate(Address::invalid(), false);
1588
1589 // Okay, turn that back into the original value or atomic (for non-simple
1590 // lvalues) type.
1591 return ConvertToValueOrAtomic(Load, ResultSlot, Loc, AsValue);
1592}
1593
1594/// Emit a load from an l-value of atomic type. Note that the r-value
1595/// we produce is an r-value of the atomic *value* type.
1597 llvm::AtomicOrdering AO, bool IsVolatile,
1598 AggValueSlot resultSlot) {
1599 AtomicInfo Atomics(*this, src);
1600 return Atomics.EmitAtomicLoad(resultSlot, loc, /*AsValue=*/true, AO,
1601 IsVolatile);
1602}
1603
1604/// Copy an r-value into memory as part of storing to an atomic type.
1605/// This needs to create a bit-pattern suitable for atomic operations.
1606void AtomicInfo::emitCopyIntoMemory(RValue rvalue) const {
1607 assert(LVal.isSimple());
1608 // If we have an r-value, the rvalue should be of the atomic type,
1609 // which means that the caller is responsible for having zeroed
1610 // any padding. Just do an aggregate copy of that type.
1611 if (rvalue.isAggregate()) {
1612 LValue Dest = CGF.MakeAddrLValue(getAtomicAddress(), getAtomicType());
1613 LValue Src = CGF.MakeAddrLValue(rvalue.getAggregateAddress(),
1614 getAtomicType());
1615 bool IsVolatile = rvalue.isVolatileQualified() ||
1616 LVal.isVolatileQualified();
1617 CGF.EmitAggregateCopy(Dest, Src, getAtomicType(),
1618 AggValueSlot::DoesNotOverlap, IsVolatile);
1619 return;
1620 }
1621
1622 // Okay, otherwise we're copying stuff.
1623
1624 // Zero out the buffer if necessary.
1625 emitMemSetZeroIfNecessary();
1626
1627 // Drill past the padding if present.
1628 LValue TempLVal = projectValue();
1629
1630 // Okay, store the rvalue in.
1631 if (rvalue.isScalar()) {
1632 CGF.EmitStoreOfScalar(rvalue.getScalarVal(), TempLVal, /*init*/ true);
1633 } else {
1634 CGF.EmitStoreOfComplex(rvalue.getComplexVal(), TempLVal, /*init*/ true);
1635 }
1636}
1637
1638
1639/// Materialize an r-value into memory for the purposes of storing it
1640/// to an atomic type.
1641Address AtomicInfo::materializeRValue(RValue rvalue) const {
1642 // Aggregate r-values are already in memory, and EmitAtomicStore
1643 // requires them to be values of the atomic type.
1644 if (rvalue.isAggregate())
1645 return rvalue.getAggregateAddress();
1646
1647 // Otherwise, make a temporary and materialize into it.
1648 LValue TempLV = CGF.MakeAddrLValue(CreateTempAlloca(), getAtomicType());
1649 AtomicInfo Atomics(CGF, TempLV);
1650 Atomics.emitCopyIntoMemory(rvalue);
1651 return TempLV.getAddress();
1652}
1653
1654llvm::Value *AtomicInfo::getScalarRValValueOrNull(RValue RVal) const {
1655 if (RVal.isScalar() && (!hasPadding() || !LVal.isSimple()))
1656 return RVal.getScalarVal();
1657 return nullptr;
1658}
1659
1660llvm::Value *AtomicInfo::convertRValueToInt(RValue RVal, bool CmpXchg) const {
1661 // If we've got a scalar value of the right size, try to avoid going
1662 // through memory. Floats get casted if needed by AtomicExpandPass.
1663 if (llvm::Value *Value = getScalarRValValueOrNull(RVal)) {
1664 if (!shouldCastToInt(Value->getType(), CmpXchg))
1665 return CGF.EmitToMemory(Value, ValueTy);
1666 else {
1667 llvm::IntegerType *InputIntTy = llvm::IntegerType::get(
1668 CGF.getLLVMContext(),
1669 LVal.isSimple() ? getValueSizeInBits() : getAtomicSizeInBits());
1670 if (llvm::BitCastInst::isBitCastable(Value->getType(), InputIntTy))
1671 return CGF.Builder.CreateBitCast(Value, InputIntTy);
1672 }
1673 }
1674 // Otherwise, we need to go through memory.
1675 // Put the r-value in memory.
1676 Address Addr = materializeRValue(RVal);
1677
1678 // Cast the temporary to the atomic int type and pull a value out.
1679 Addr = castToAtomicIntPointer(Addr);
1680 return CGF.Builder.CreateLoad(Addr);
1681}
1682
1683std::pair<llvm::Value *, llvm::Value *> AtomicInfo::EmitAtomicCompareExchangeOp(
1684 llvm::Value *ExpectedVal, llvm::Value *DesiredVal,
1685 llvm::AtomicOrdering Success, llvm::AtomicOrdering Failure, bool IsWeak) {
1686 // Do the atomic store.
1687 Address Addr = getAtomicAddressAsAtomicIntPointer();
1688 auto *Inst = CGF.Builder.CreateAtomicCmpXchg(Addr, ExpectedVal, DesiredVal,
1689 Success, Failure);
1690 // Other decoration.
1691 Inst->setVolatile(LVal.isVolatileQualified());
1692 Inst->setWeak(IsWeak);
1693
1694 // Okay, turn that back into the original value type.
1695 auto *PreviousVal = CGF.Builder.CreateExtractValue(Inst, /*Idxs=*/0);
1696 auto *SuccessFailureVal = CGF.Builder.CreateExtractValue(Inst, /*Idxs=*/1);
1697 return std::make_pair(PreviousVal, SuccessFailureVal);
1698}
1699
1700llvm::Value *
1701AtomicInfo::EmitAtomicCompareExchangeLibcall(llvm::Value *ExpectedAddr,
1702 llvm::Value *DesiredAddr,
1703 llvm::AtomicOrdering Success,
1704 llvm::AtomicOrdering Failure) {
1705 // bool __atomic_compare_exchange(size_t size, void *obj, void *expected,
1706 // void *desired, int success, int failure);
1707 CallArgList Args;
1708 Args.add(RValue::get(getAtomicSizeValue()), CGF.getContext().getSizeType());
1709 Args.add(RValue::get(getAtomicPointer()), CGF.getContext().VoidPtrTy);
1710 Args.add(RValue::get(ExpectedAddr), CGF.getContext().VoidPtrTy);
1711 Args.add(RValue::get(DesiredAddr), CGF.getContext().VoidPtrTy);
1712 Args.add(RValue::get(
1713 llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(Success))),
1714 CGF.getContext().IntTy);
1715 Args.add(RValue::get(
1716 llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(Failure))),
1717 CGF.getContext().IntTy);
1718 auto SuccessFailureRVal = emitAtomicLibcall(CGF, "__atomic_compare_exchange",
1719 CGF.getContext().BoolTy, Args);
1720
1721 return SuccessFailureRVal.getScalarVal();
1722}
1723
1724std::pair<RValue, llvm::Value *> AtomicInfo::EmitAtomicCompareExchange(
1725 RValue Expected, RValue Desired, llvm::AtomicOrdering Success,
1726 llvm::AtomicOrdering Failure, bool IsWeak) {
1727 // Check whether we should use a library call.
1728 if (shouldUseLibcall()) {
1729 // Produce a source address.
1730 Address ExpectedAddr = materializeRValue(Expected);
1731 llvm::Value *ExpectedPtr = ExpectedAddr.emitRawPointer(CGF);
1732 llvm::Value *DesiredPtr = materializeRValue(Desired).emitRawPointer(CGF);
1733 auto *Res = EmitAtomicCompareExchangeLibcall(ExpectedPtr, DesiredPtr,
1734 Success, Failure);
1735 return std::make_pair(
1736 convertAtomicTempToRValue(ExpectedAddr, AggValueSlot::ignored(),
1737 SourceLocation(), /*AsValue=*/false),
1738 Res);
1739 }
1740
1741 // If we've got a scalar value of the right size, try to avoid going
1742 // through memory.
1743 auto *ExpectedVal = convertRValueToInt(Expected, /*CmpXchg=*/true);
1744 auto *DesiredVal = convertRValueToInt(Desired, /*CmpXchg=*/true);
1745 auto Res = EmitAtomicCompareExchangeOp(ExpectedVal, DesiredVal, Success,
1746 Failure, IsWeak);
1747 return std::make_pair(
1748 ConvertToValueOrAtomic(Res.first, AggValueSlot::ignored(),
1749 SourceLocation(), /*AsValue=*/false,
1750 /*CmpXchg=*/true),
1751 Res.second);
1752}
1753
1754static void
1755EmitAtomicUpdateValue(CodeGenFunction &CGF, AtomicInfo &Atomics, RValue OldRVal,
1756 const llvm::function_ref<RValue(RValue)> &UpdateOp,
1757 Address DesiredAddr) {
1758 RValue UpRVal;
1759 LValue AtomicLVal = Atomics.getAtomicLValue();
1760 LValue DesiredLVal;
1761 if (AtomicLVal.isSimple()) {
1762 UpRVal = OldRVal;
1763 DesiredLVal = CGF.MakeAddrLValue(DesiredAddr, AtomicLVal.getType());
1764 } else {
1765 // Build new lvalue for temp address.
1766 Address Ptr = Atomics.materializeRValue(OldRVal);
1767 LValue UpdateLVal;
1768 if (AtomicLVal.isBitField()) {
1769 UpdateLVal =
1770 LValue::MakeBitfield(Ptr, AtomicLVal.getBitFieldInfo(),
1771 AtomicLVal.getType(),
1772 AtomicLVal.getBaseInfo(),
1773 AtomicLVal.getTBAAInfo());
1774 DesiredLVal =
1775 LValue::MakeBitfield(DesiredAddr, AtomicLVal.getBitFieldInfo(),
1776 AtomicLVal.getType(), AtomicLVal.getBaseInfo(),
1777 AtomicLVal.getTBAAInfo());
1778 } else if (AtomicLVal.isVectorElt()) {
1779 UpdateLVal = LValue::MakeVectorElt(Ptr, AtomicLVal.getVectorIdx(),
1780 AtomicLVal.getType(),
1781 AtomicLVal.getBaseInfo(),
1782 AtomicLVal.getTBAAInfo());
1783 DesiredLVal = LValue::MakeVectorElt(
1784 DesiredAddr, AtomicLVal.getVectorIdx(), AtomicLVal.getType(),
1785 AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
1786 } else {
1787 assert(AtomicLVal.isExtVectorElt());
1788 UpdateLVal = LValue::MakeExtVectorElt(Ptr, AtomicLVal.getExtVectorElts(),
1789 AtomicLVal.getType(),
1790 AtomicLVal.getBaseInfo(),
1791 AtomicLVal.getTBAAInfo());
1792 DesiredLVal = LValue::MakeExtVectorElt(
1793 DesiredAddr, AtomicLVal.getExtVectorElts(), AtomicLVal.getType(),
1794 AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
1795 }
1796 UpRVal = CGF.EmitLoadOfLValue(UpdateLVal, SourceLocation());
1797 }
1798 // Store new value in the corresponding memory area.
1799 RValue NewRVal = UpdateOp(UpRVal);
1800 if (NewRVal.isScalar()) {
1801 CGF.EmitStoreThroughLValue(NewRVal, DesiredLVal);
1802 } else {
1803 assert(NewRVal.isComplex());
1804 CGF.EmitStoreOfComplex(NewRVal.getComplexVal(), DesiredLVal,
1805 /*isInit=*/false);
1806 }
1807}
1808
1809void AtomicInfo::EmitAtomicUpdateLibcall(
1810 llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1811 bool IsVolatile) {
1812 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1813
1814 Address ExpectedAddr = CreateTempAlloca();
1815
1816 EmitAtomicLoadLibcall(ExpectedAddr.emitRawPointer(CGF), AO, IsVolatile);
1817 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1818 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1819 CGF.EmitBlock(ContBB);
1820 Address DesiredAddr = CreateTempAlloca();
1821 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
1822 requiresMemSetZero(getAtomicAddress().getElementType())) {
1823 auto *OldVal = CGF.Builder.CreateLoad(ExpectedAddr);
1824 CGF.Builder.CreateStore(OldVal, DesiredAddr);
1825 }
1826 auto OldRVal = convertAtomicTempToRValue(ExpectedAddr,
1828 SourceLocation(), /*AsValue=*/false);
1829 EmitAtomicUpdateValue(CGF, *this, OldRVal, UpdateOp, DesiredAddr);
1830 llvm::Value *ExpectedPtr = ExpectedAddr.emitRawPointer(CGF);
1831 llvm::Value *DesiredPtr = DesiredAddr.emitRawPointer(CGF);
1832 auto *Res =
1833 EmitAtomicCompareExchangeLibcall(ExpectedPtr, DesiredPtr, AO, Failure);
1834 CGF.Builder.CreateCondBr(Res, ExitBB, ContBB);
1835 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1836}
1837
1838void AtomicInfo::EmitAtomicUpdateOp(
1839 llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1840 bool IsVolatile) {
1841 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1842
1843 // Do the atomic load.
1844 auto *OldVal = EmitAtomicLoadOp(Failure, IsVolatile, /*CmpXchg=*/true);
1845 // For non-simple lvalues perform compare-and-swap procedure.
1846 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1847 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1848 auto *CurBB = CGF.Builder.GetInsertBlock();
1849 CGF.EmitBlock(ContBB);
1850 llvm::PHINode *PHI = CGF.Builder.CreatePHI(OldVal->getType(),
1851 /*NumReservedValues=*/2);
1852 PHI->addIncoming(OldVal, CurBB);
1853 Address NewAtomicAddr = CreateTempAlloca();
1854 Address NewAtomicIntAddr =
1855 shouldCastToInt(NewAtomicAddr.getElementType(), /*CmpXchg=*/true)
1856 ? castToAtomicIntPointer(NewAtomicAddr)
1857 : NewAtomicAddr;
1858
1859 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
1860 requiresMemSetZero(getAtomicAddress().getElementType())) {
1861 CGF.Builder.CreateStore(PHI, NewAtomicIntAddr);
1862 }
1863 auto OldRVal = ConvertToValueOrAtomic(PHI, AggValueSlot::ignored(),
1864 SourceLocation(), /*AsValue=*/false,
1865 /*CmpXchg=*/true);
1866 EmitAtomicUpdateValue(CGF, *this, OldRVal, UpdateOp, NewAtomicAddr);
1867 auto *DesiredVal = CGF.Builder.CreateLoad(NewAtomicIntAddr);
1868 // Try to write new value using cmpxchg operation.
1869 auto Res = EmitAtomicCompareExchangeOp(PHI, DesiredVal, AO, Failure);
1870 PHI->addIncoming(Res.first, CGF.Builder.GetInsertBlock());
1871 CGF.Builder.CreateCondBr(Res.second, ExitBB, ContBB);
1872 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1873}
1874
1875static void EmitAtomicUpdateValue(CodeGenFunction &CGF, AtomicInfo &Atomics,
1876 RValue UpdateRVal, Address DesiredAddr) {
1877 LValue AtomicLVal = Atomics.getAtomicLValue();
1878 LValue DesiredLVal;
1879 // Build new lvalue for temp address.
1880 if (AtomicLVal.isBitField()) {
1881 DesiredLVal =
1882 LValue::MakeBitfield(DesiredAddr, AtomicLVal.getBitFieldInfo(),
1883 AtomicLVal.getType(), AtomicLVal.getBaseInfo(),
1884 AtomicLVal.getTBAAInfo());
1885 } else if (AtomicLVal.isVectorElt()) {
1886 DesiredLVal =
1887 LValue::MakeVectorElt(DesiredAddr, AtomicLVal.getVectorIdx(),
1888 AtomicLVal.getType(), AtomicLVal.getBaseInfo(),
1889 AtomicLVal.getTBAAInfo());
1890 } else {
1891 assert(AtomicLVal.isExtVectorElt());
1892 DesiredLVal = LValue::MakeExtVectorElt(
1893 DesiredAddr, AtomicLVal.getExtVectorElts(), AtomicLVal.getType(),
1894 AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
1895 }
1896 // Store new value in the corresponding memory area.
1897 assert(UpdateRVal.isScalar());
1898 CGF.EmitStoreThroughLValue(UpdateRVal, DesiredLVal);
1899}
1900
1901void AtomicInfo::EmitAtomicUpdateLibcall(llvm::AtomicOrdering AO,
1902 RValue UpdateRVal, bool IsVolatile) {
1903 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1904
1905 Address ExpectedAddr = CreateTempAlloca();
1906
1907 EmitAtomicLoadLibcall(ExpectedAddr.emitRawPointer(CGF), AO, IsVolatile);
1908 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1909 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1910 CGF.EmitBlock(ContBB);
1911 Address DesiredAddr = CreateTempAlloca();
1912 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
1913 requiresMemSetZero(getAtomicAddress().getElementType())) {
1914 auto *OldVal = CGF.Builder.CreateLoad(ExpectedAddr);
1915 CGF.Builder.CreateStore(OldVal, DesiredAddr);
1916 }
1917 EmitAtomicUpdateValue(CGF, *this, UpdateRVal, DesiredAddr);
1918 llvm::Value *ExpectedPtr = ExpectedAddr.emitRawPointer(CGF);
1919 llvm::Value *DesiredPtr = DesiredAddr.emitRawPointer(CGF);
1920 auto *Res =
1921 EmitAtomicCompareExchangeLibcall(ExpectedPtr, DesiredPtr, AO, Failure);
1922 CGF.Builder.CreateCondBr(Res, ExitBB, ContBB);
1923 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1924}
1925
1926void AtomicInfo::EmitAtomicUpdateOp(llvm::AtomicOrdering AO, RValue UpdateRVal,
1927 bool IsVolatile) {
1928 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1929
1930 // Do the atomic load.
1931 auto *OldVal = EmitAtomicLoadOp(Failure, IsVolatile, /*CmpXchg=*/true);
1932 // For non-simple lvalues perform compare-and-swap procedure.
1933 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1934 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1935 auto *CurBB = CGF.Builder.GetInsertBlock();
1936 CGF.EmitBlock(ContBB);
1937 llvm::PHINode *PHI = CGF.Builder.CreatePHI(OldVal->getType(),
1938 /*NumReservedValues=*/2);
1939 PHI->addIncoming(OldVal, CurBB);
1940 Address NewAtomicAddr = CreateTempAlloca();
1941 Address NewAtomicIntAddr = castToAtomicIntPointer(NewAtomicAddr);
1942 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
1943 requiresMemSetZero(getAtomicAddress().getElementType())) {
1944 CGF.Builder.CreateStore(PHI, NewAtomicIntAddr);
1945 }
1946 EmitAtomicUpdateValue(CGF, *this, UpdateRVal, NewAtomicAddr);
1947 auto *DesiredVal = CGF.Builder.CreateLoad(NewAtomicIntAddr);
1948 // Try to write new value using cmpxchg operation.
1949 auto Res = EmitAtomicCompareExchangeOp(PHI, DesiredVal, AO, Failure);
1950 PHI->addIncoming(Res.first, CGF.Builder.GetInsertBlock());
1951 CGF.Builder.CreateCondBr(Res.second, ExitBB, ContBB);
1952 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1953}
1954
1955void AtomicInfo::EmitAtomicUpdate(
1956 llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1957 bool IsVolatile) {
1958 if (shouldUseLibcall()) {
1959 EmitAtomicUpdateLibcall(AO, UpdateOp, IsVolatile);
1960 } else {
1961 EmitAtomicUpdateOp(AO, UpdateOp, IsVolatile);
1962 }
1963}
1964
1965void AtomicInfo::EmitAtomicUpdate(llvm::AtomicOrdering AO, RValue UpdateRVal,
1966 bool IsVolatile) {
1967 if (shouldUseLibcall()) {
1968 EmitAtomicUpdateLibcall(AO, UpdateRVal, IsVolatile);
1969 } else {
1970 EmitAtomicUpdateOp(AO, UpdateRVal, IsVolatile);
1971 }
1972}
1973
1975 bool isInit) {
1976 bool IsVolatile = lvalue.isVolatileQualified();
1977 llvm::AtomicOrdering AO;
1978 if (lvalue.getType()->isAtomicType()) {
1979 AO = llvm::AtomicOrdering::SequentiallyConsistent;
1980 } else {
1981 AO = llvm::AtomicOrdering::Release;
1982 IsVolatile = true;
1983 }
1984 return EmitAtomicStore(rvalue, lvalue, AO, IsVolatile, isInit);
1985}
1986
1987/// Emit a store to an l-value of atomic type.
1988///
1989/// Note that the r-value is expected to be an r-value *of the atomic
1990/// type*; this means that for aggregate r-values, it should include
1991/// storage for any padding that was necessary.
1993 llvm::AtomicOrdering AO, bool IsVolatile,
1994 bool isInit) {
1995 // If this is an aggregate r-value, it should agree in type except
1996 // maybe for address-space qualification.
1997 assert(!rvalue.isAggregate() ||
1999 dest.getAddress().getElementType());
2000
2001 AtomicInfo atomics(*this, dest);
2002 LValue LVal = atomics.getAtomicLValue();
2003
2004 // If this is an initialization, just put the value there normally.
2005 if (LVal.isSimple()) {
2006 if (isInit) {
2007 atomics.emitCopyIntoMemory(rvalue);
2008 return;
2009 }
2010
2011 // Check whether we should use a library call.
2012 if (atomics.shouldUseLibcall()) {
2013 // Produce a source address.
2014 Address srcAddr = atomics.materializeRValue(rvalue);
2015
2016 // void __atomic_store(size_t size, void *mem, void *val, int order)
2017 CallArgList args;
2018 args.add(RValue::get(atomics.getAtomicSizeValue()),
2019 getContext().getSizeType());
2020 args.add(RValue::get(atomics.getAtomicPointer()), getContext().VoidPtrTy);
2021 args.add(RValue::get(srcAddr.emitRawPointer(*this)),
2023 args.add(
2024 RValue::get(llvm::ConstantInt::get(IntTy, (int)llvm::toCABI(AO))),
2025 getContext().IntTy);
2026 emitAtomicLibcall(*this, "__atomic_store", getContext().VoidTy, args);
2027 return;
2028 }
2029
2030 // Okay, we're doing this natively.
2031 llvm::Value *ValToStore = atomics.convertRValueToInt(rvalue);
2032
2033 // Do the atomic store.
2034 Address Addr = atomics.getAtomicAddress();
2035 if (llvm::Value *Value = atomics.getScalarRValValueOrNull(rvalue))
2036 if (shouldCastToInt(Value->getType(), /*CmpXchg=*/false)) {
2037 Addr = atomics.castToAtomicIntPointer(Addr);
2038 ValToStore = Builder.CreateIntCast(ValToStore, Addr.getElementType(),
2039 /*isSigned=*/false);
2040 }
2041 llvm::StoreInst *store = Builder.CreateStore(ValToStore, Addr);
2042
2043 if (AO == llvm::AtomicOrdering::Acquire)
2044 AO = llvm::AtomicOrdering::Monotonic;
2045 else if (AO == llvm::AtomicOrdering::AcquireRelease)
2046 AO = llvm::AtomicOrdering::Release;
2047 // Initializations don't need to be atomic.
2048 if (!isInit)
2049 store->setAtomic(AO);
2050
2051 // Other decoration.
2052 if (IsVolatile)
2053 store->setVolatile(true);
2054 CGM.DecorateInstructionWithTBAA(store, dest.getTBAAInfo());
2055 return;
2056 }
2057
2058 // Emit simple atomic update operation.
2059 atomics.EmitAtomicUpdate(AO, rvalue, IsVolatile);
2060}
2061
2062/// Emit a compare-and-exchange op for atomic type.
2063///
2064std::pair<RValue, llvm::Value *> CodeGenFunction::EmitAtomicCompareExchange(
2065 LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
2066 llvm::AtomicOrdering Success, llvm::AtomicOrdering Failure, bool IsWeak,
2067 AggValueSlot Slot) {
2068 // If this is an aggregate r-value, it should agree in type except
2069 // maybe for address-space qualification.
2070 assert(!Expected.isAggregate() ||
2071 Expected.getAggregateAddress().getElementType() ==
2072 Obj.getAddress().getElementType());
2073 assert(!Desired.isAggregate() ||
2074 Desired.getAggregateAddress().getElementType() ==
2075 Obj.getAddress().getElementType());
2076 AtomicInfo Atomics(*this, Obj);
2077
2078 return Atomics.EmitAtomicCompareExchange(Expected, Desired, Success, Failure,
2079 IsWeak);
2080}
2081
2082llvm::AtomicRMWInst *
2083CodeGenFunction::emitAtomicRMWInst(llvm::AtomicRMWInst::BinOp Op, Address Addr,
2084 llvm::Value *Val, llvm::AtomicOrdering Order,
2085 llvm::SyncScope::ID SSID,
2086 const AtomicExpr *AE) {
2087 llvm::AtomicRMWInst *RMW =
2088 Builder.CreateAtomicRMW(Op, Addr, Val, Order, SSID);
2089 getTargetHooks().setTargetAtomicMetadata(*this, *RMW, AE);
2090 return RMW;
2091}
2092
2094 LValue LVal, llvm::AtomicOrdering AO,
2095 const llvm::function_ref<RValue(RValue)> &UpdateOp, bool IsVolatile) {
2096 AtomicInfo Atomics(*this, LVal);
2097 Atomics.EmitAtomicUpdate(AO, UpdateOp, IsVolatile);
2098}
2099
2101 AtomicInfo atomics(*this, dest);
2102
2103 switch (atomics.getEvaluationKind()) {
2104 case TEK_Scalar: {
2105 llvm::Value *value = EmitScalarExpr(init);
2106 atomics.emitCopyIntoMemory(RValue::get(value));
2107 return;
2108 }
2109
2110 case TEK_Complex: {
2111 ComplexPairTy value = EmitComplexExpr(init);
2112 atomics.emitCopyIntoMemory(RValue::getComplex(value));
2113 return;
2114 }
2115
2116 case TEK_Aggregate: {
2117 // Fix up the destination if the initializer isn't an expression
2118 // of atomic type.
2119 bool Zeroed = false;
2120 if (!init->getType()->isAtomicType()) {
2121 Zeroed = atomics.emitMemSetZeroIfNecessary();
2122 dest = atomics.projectValue();
2123 }
2124
2125 // Evaluate the expression directly into the destination.
2131
2132 EmitAggExpr(init, slot);
2133 return;
2134 }
2135 }
2136 llvm_unreachable("bad evaluation kind");
2137}
Defines the clang::ASTContext interface.
#define V(N, I)
static llvm::Value * EmitPostAtomicMinMax(CGBuilderTy &Builder, AtomicExpr::AtomicOp Op, bool IsSigned, llvm::Value *OldVal, llvm::Value *RHS)
Duplicate the atomic min/max operation in conventional IR for the builtin variants that return the ne...
Definition CGAtomic.cpp:505
static void EmitAtomicUpdateValue(CodeGenFunction &CGF, AtomicInfo &Atomics, RValue OldRVal, const llvm::function_ref< RValue(RValue)> &UpdateOp, Address DesiredAddr)
static Address EmitValToTemp(CodeGenFunction &CGF, Expr *E)
Definition CGAtomic.cpp:779
static void EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *E, Address Dest, Address Ptr, Address Val1, Address Val2, llvm::Value *IsWeak, llvm::Value *FailureOrder, uint64_t Size, llvm::AtomicOrdering Order, llvm::SyncScope::ID Scope)
Definition CGAtomic.cpp:527
static RValue emitAtomicLibcall(CodeGenFunction &CGF, StringRef fnName, QualType resultType, CallArgList &args)
Definition CGAtomic.cpp:314
static bool shouldCastToInt(llvm::Type *ValTy, bool CmpXchg)
Return true if.
static Address EmitPointerWithAlignment(const Expr *E, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo, KnownNonNull_t IsKnownNonNull, CodeGenFunction &CGF)
Definition CGExpr.cpp:1376
static void emitAtomicCmpXchg(CIRGenFunction &cgf, AtomicExpr *e, bool isWeak, Address dest, Address ptr, Address val1, Address val2, uint64_t size, cir::MemOrder successOrder, cir::MemOrder failureOrder)
static void emitAtomicCmpXchgFailureSet(CIRGenFunction &cgf, AtomicExpr *e, bool isWeak, Address dest, Address ptr, Address val1, Address val2, Expr *failureOrderExpr, uint64_t size, cir::MemOrder successOrder)
static bool isFullSizeType(CIRGenModule &cgm, mlir::Type ty, uint64_t expectedSize)
Does a store of the given IR type modify the full expected width?
TokenType getType() const
Returns the token's type, e.g.
static QualType getPointeeType(const MemRegion *R)
CanQualType VoidPtrTy
CanQualType BoolTy
CanQualType IntTy
CanQualType VoidTy
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6814
static std::unique_ptr< AtomicScopeModel > getScopeModel(AtomicOp Op)
Get atomic scope model for the atomic op code.
Definition Expr.h:6963
Expr * getVal2() const
Definition Expr.h:6865
Expr * getOrder() const
Definition Expr.h:6848
QualType getValueType() const
Definition Expr.cpp:5258
Expr * getScope() const
Definition Expr.h:6851
bool isCmpXChg() const
Definition Expr.h:6898
AtomicOp getOp() const
Definition Expr.h:6877
bool isOpenCL() const
Definition Expr.h:6926
Expr * getVal1() const
Definition Expr.h:6855
Expr * getPtr() const
Definition Expr.h:6845
Expr * getWeak() const
Definition Expr.h:6871
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:6945
Expr * getOrderFail() const
Definition Expr.h:6861
bool isVolatile() const
Definition Expr.h:6894
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition Address.h:128
static Address invalid()
Definition Address.h:176
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition Address.h:253
CharUnits getAlignment() const
Definition Address.h:194
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition Address.h:209
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Definition Address.h:276
bool isValid() const
Definition Address.h:177
An aggregate value slot.
Definition CGValue.h:504
static AggValueSlot ignored()
ignored - Returns an aggregate value slot indicating that the aggregate value is being ignored.
Definition CGValue.h:572
Address getAddress() const
Definition CGValue.h:644
static AggValueSlot forLValue(const LValue &LV, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed, IsSanitizerChecked_t isChecked=IsNotSanitizerChecked)
Definition CGValue.h:602
RValue asRValue() const
Definition CGValue.h:666
A scoped helper to set the current source atom group for CGDebugInfo::addInstToCurrentSourceAtom.
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition CGBuilder.h:140
Address CreatePointerBitCastOrAddrSpaceCast(Address Addr, llvm::Type *Ty, llvm::Type *ElementTy, const llvm::Twine &Name="")
Definition CGBuilder.h:207
llvm::CallInst * CreateMemSet(Address Dest, llvm::Value *Value, llvm::Value *Size, bool IsVolatile=false)
Definition CGBuilder.h:402
Address CreateStructGEP(Address Addr, unsigned Index, const llvm::Twine &Name="")
Definition CGBuilder.h:223
llvm::AtomicCmpXchgInst * CreateAtomicCmpXchg(Address Addr, llvm::Value *Cmp, llvm::Value *New, llvm::AtomicOrdering SuccessOrdering, llvm::AtomicOrdering FailureOrdering, llvm::SyncScope::ID SSID=llvm::SyncScope::System)
Definition CGBuilder.h:173
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition CGBuilder.h:112
llvm::CallInst * CreateMemCpy(Address Dest, Address Src, llvm::Value *Size, bool IsVolatile=false)
Definition CGBuilder.h:369
Address CreateAddrSpaceCast(Address Addr, llvm::Type *Ty, llvm::Type *ElementTy, const llvm::Twine &Name="")
Definition CGBuilder.h:193
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
Definition CGCall.h:137
CGFunctionInfo - Class to encapsulate the information about a function definition.
CallArgList - Type for representing both the value and type of arguments in a call.
Definition CGCall.h:274
void add(RValue rvalue, QualType type)
Definition CGCall.h:302
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
void EmitAtomicInit(Expr *E, LValue lvalue)
RValue convertTempToRValue(Address addr, QualType type, SourceLocation Loc)
Given the address of a temporary variable, produce an r-value of its type.
Definition CGExpr.cpp:6631
bool hasVolatileMember(QualType T)
hasVolatileMember - returns true if aggregate type has a volatile member.
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
void addInstToCurrentSourceAtom(llvm::Instruction *KeyInstruction, llvm::Value *Backup)
See CGDebugInfo::addInstToCurrentSourceAtom.
const LangOptions & getLangOpts() const
void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO, const llvm::function_ref< RValue(RValue)> &UpdateOp, bool IsVolatile)
std::pair< RValue, llvm::Value * > EmitAtomicCompareExchange(LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc, llvm::AtomicOrdering Success=llvm::AtomicOrdering::SequentiallyConsistent, llvm::AtomicOrdering Failure=llvm::AtomicOrdering::SequentiallyConsistent, bool IsWeak=false, AggValueSlot Slot=AggValueSlot::ignored())
Emit a compare-and-exchange op for atomic type.
void maybeAttachRangeForLoad(llvm::LoadInst *Load, QualType Ty, SourceLocation Loc)
Definition CGExpr.cpp:2012
void EmitAggregateCopy(LValue Dest, LValue Src, QualType EltTy, AggValueSlot::Overlap_t MayOverlap, bool isVolatile=false)
EmitAggregateCopy - Emit an aggregate copy.
const TargetInfo & getTarget() const
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
Definition CGExpr.cpp:2336
RValue EmitAtomicLoad(LValue LV, SourceLocation SL, AggValueSlot Slot=AggValueSlot::ignored())
llvm::Value * getTypeSize(QualType Ty)
Returns calculated size of the specified type.
llvm::Value * EmitToMemory(llvm::Value *Value, QualType Ty)
EmitToMemory - Change a scalar value from its value representation to its in-memory representation.
Definition CGExpr.cpp:2153
ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal=false, bool IgnoreImag=false)
EmitComplexExpr - Emit the computation of the specified expression of complex type,...
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::CallBase **CallOrInvoke, bool IsMustTail, SourceLocation Loc, bool IsVirtualFunctionPointerThunk=false)
EmitCall - Generate a call of the given function, expecting the given result type,...
Definition CGCall.cpp:5241
const TargetCodeGenInfo & getTargetHooks() const
void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit)
EmitStoreOfComplex - Store a complex number into the specified l-value.
void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false)
EmitStoreThroughLValue - Store the specified rvalue into the specified lvalue, where both are guarant...
Definition CGExpr.cpp:2533
llvm::AtomicRMWInst * emitAtomicRMWInst(llvm::AtomicRMWInst::BinOp Op, Address Addr, llvm::Value *Val, llvm::AtomicOrdering Order=llvm::AtomicOrdering::SequentiallyConsistent, llvm::SyncScope::ID SSID=llvm::SyncScope::System, const AtomicExpr *AE=nullptr)
Emit an atomicrmw instruction, and applying relevant metadata when applicable.
void EmitAnyExprToMem(const Expr *E, Address Location, Qualifiers Quals, bool IsInitializer)
EmitAnyExprToMem - Emits the code necessary to evaluate an arbitrary expression into the given memory...
Definition CGExpr.cpp:293
llvm::Type * ConvertTypeForMem(QualType T)
RValue EmitLoadOfBitfieldLValue(LValue LV, SourceLocation Loc)
Definition CGExpr.cpp:2407
RValue EmitAtomicExpr(AtomicExpr *E)
Definition CGAtomic.cpp:855
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
bool LValueIsSuitableForInlineAtomic(LValue Src)
An LValue is a candidate for having its loads and stores be made atomic if we are operating under /vo...
RawAddress CreateMemTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen and cas...
Definition CGExpr.cpp:186
void EmitAggExpr(const Expr *E, AggValueSlot AS)
EmitAggExpr - Emit the computation of the specified expression of aggregate type.
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
RValue EmitLoadOfExtVectorElementLValue(LValue V)
Definition CGExpr.cpp:2444
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit)
llvm::Value * EmitFromMemory(llvm::Value *Value, QualType Ty)
EmitFromMemory - Change a scalar value from its memory representation to its value representation.
Definition CGExpr.cpp:2183
std::pair< llvm::Value *, llvm::Value * > ComplexPairTy
llvm::LLVMContext & getLLVMContext()
void EmitStoreOfScalar(llvm::Value *Value, Address Addr, bool Volatile, QualType Ty, AlignmentSource Source=AlignmentSource::Type, bool isInit=false, bool isNontemporal=false)
EmitStoreOfScalar - Store a scalar value to an address, taking care to appropriately convert from the...
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition CGStmt.cpp:652
This class organizes the cross-function state that is used while generating LLVM code.
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false, bool AssumeConvergent=false)
Create or return a runtime function declaration with the specified type and name.
const LangOptions & getLangOpts() const
const llvm::DataLayout & getDataLayout() const
void DecorateInstructionWithTBAA(llvm::Instruction *Inst, TBAAAccessInfo TBAAInfo)
DecorateInstructionWithTBAA - Decorate the instruction with a TBAA tag.
llvm::LLVMContext & getLLVMContext()
llvm::ConstantInt * getSize(CharUnits numChars)
Emit the given number of characters as a value of type size_t.
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition CGCall.cpp:1701
const CGFunctionInfo & arrangeBuiltinFunctionCall(QualType resultType, const CallArgList &args)
Definition CGCall.cpp:728
LValue - This represents an lvalue references.
Definition CGValue.h:182
bool isSimple() const
Definition CGValue.h:278
bool isVolatileQualified() const
Definition CGValue.h:285
bool isVolatile() const
Definition CGValue.h:328
Address getAddress() const
Definition CGValue.h:361
QualType getType() const
Definition CGValue.h:291
TBAAAccessInfo getTBAAInfo() const
Definition CGValue.h:335
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition CGValue.h:42
bool isScalar() const
Definition CGValue.h:64
static RValue get(llvm::Value *V)
Definition CGValue.h:98
static RValue getAggregate(Address addr, bool isVolatile=false)
Convert an Address to an RValue.
Definition CGValue.h:125
static RValue getComplex(llvm::Value *V1, llvm::Value *V2)
Definition CGValue.h:108
bool isAggregate() const
Definition CGValue.h:66
Address getAggregateAddress() const
getAggregateAddr() - Return the Value* of the address of the aggregate.
Definition CGValue.h:83
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition CGValue.h:71
bool isComplex() const
Definition CGValue.h:65
bool isVolatileQualified() const
Definition CGValue.h:68
std::pair< llvm::Value *, llvm::Value * > getComplexVal() const
getComplexVal - Return the real/imag components of this complex value.
Definition CGValue.h:78
ReturnValueSlot - Contains the address where the return value of a function can be stored,...
Definition CGCall.h:379
virtual llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts, SyncScope Scope, llvm::AtomicOrdering Ordering, llvm::LLVMContext &Ctx) const
Get the syncscope used in LLVM IR.
virtual void setTargetAtomicMetadata(CodeGenFunction &CGF, llvm::Instruction &AtomicInst, const AtomicExpr *Expr=nullptr) const
Allow the target to apply other metadata to an atomic instruction.
Definition TargetInfo.h:359
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:231
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
This represents one expression.
Definition Expr.h:112
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:273
QualType getType() const
Definition Expr.h:144
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3328
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8411
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8325
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8379
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
Encodes a location in the source.
bool isVoidType() const
Definition TypeBase.h:8878
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2205
bool isPointerType() const
Definition TypeBase.h:8522
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9165
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isAtomicType() const
Definition TypeBase.h:8704
bool isFloatingType() const
Definition Type.cpp:2304
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9098
QualType getType() const
Definition Value.cpp:237
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
bool Load(InterpState &S, CodePtr OpPC)
Definition Interp.h:1939
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ Success
Annotation was successful.
Definition Parser.h:65
llvm::StringRef getAsString(SyncScope S)
Definition SyncScope.h:60
U cast(CodeGen::Address addr)
Definition Address.h:327
unsigned long uint64_t
#define true
Definition stdbool.h:25
CharUnits StorageOffset
The offset of the bitfield storage from the start of the struct.
unsigned Offset
The offset within a contiguous run of bitfields that are represented as a single "field" within the L...
unsigned Size
The total size of the bit-field, in bits.
unsigned StorageSize
The storage size in bits which should be used when accessing this bitfield.
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64