clang 23.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.DefaultPtrTy, "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, Address Val1,
378 Address Val2, Address ExpectedResult,
379 uint64_t Size, llvm::AtomicOrdering SuccessOrder,
380 llvm::AtomicOrdering FailureOrder,
381 llvm::SyncScope::ID Scope) {
382 // Note that cmpxchg doesn't support weak cmpxchg, at least at the moment.
383 llvm::Value *Expected = CGF.Builder.CreateLoad(Val1);
384 llvm::Value *Desired = CGF.Builder.CreateLoad(Val2);
385
386 llvm::AtomicCmpXchgInst *Pair = CGF.Builder.CreateAtomicCmpXchg(
387 Ptr, Expected, Desired, SuccessOrder, FailureOrder, Scope);
388 Pair->setVolatile(E->isVolatile());
389 Pair->setWeak(IsWeak);
390 CGF.getTargetHooks().setTargetAtomicMetadata(CGF, *Pair, E);
391
392 // Cmp holds the result of the compare-exchange operation: true on success,
393 // false on failure.
394 llvm::Value *Old = CGF.Builder.CreateExtractValue(Pair, 0);
395 llvm::Value *Cmp = CGF.Builder.CreateExtractValue(Pair, 1);
396
397 // This basic block is used to hold the store instruction if the operation
398 // failed.
399 llvm::BasicBlock *StoreExpectedBB =
400 CGF.createBasicBlock("cmpxchg.store_expected", CGF.CurFn);
401
402 // This basic block is the exit point of the operation, we should end up
403 // here regardless of whether or not the operation succeeded.
404 llvm::BasicBlock *ContinueBB =
405 CGF.createBasicBlock("cmpxchg.continue", CGF.CurFn);
406
407 // Update Expected if Expected isn't equal to Old, otherwise branch to the
408 // exit point.
409 CGF.Builder.CreateCondBr(Cmp, ContinueBB, StoreExpectedBB);
410
411 CGF.Builder.SetInsertPoint(StoreExpectedBB);
412 // Update the memory at Expected with Old's value.
413 llvm::Type *ExpectedType = ExpectedResult.getElementType();
414 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
415 uint64_t ExpectedSizeInBytes = DL.getTypeStoreSize(ExpectedType);
416
417 if (ExpectedSizeInBytes == Size) {
418 // Sizes match: store directly
419 auto *I = CGF.Builder.CreateStore(Old, ExpectedResult);
420 CGF.addInstToCurrentSourceAtom(I, Old);
421 } else {
422 // store only the first ExpectedSizeInBytes bytes of Old
423 llvm::Type *OldType = Old->getType();
424
425 // Allocate temporary storage for Old value
426 Address OldTmp =
427 CGF.CreateTempAlloca(OldType, Ptr.getAlignment(), "old.tmp");
428
429 // Store Old into this temporary
430 auto *I = CGF.Builder.CreateStore(Old, OldTmp);
431 CGF.addInstToCurrentSourceAtom(I, Old);
432
433 // Perform memcpy for first ExpectedSizeInBytes bytes
434 CGF.Builder.CreateMemCpy(ExpectedResult, OldTmp, ExpectedSizeInBytes,
435 /*isVolatile=*/false);
436 }
437
438 // Finally, branch to the exit point.
439 CGF.Builder.CreateBr(ContinueBB);
440
441 CGF.Builder.SetInsertPoint(ContinueBB);
442 // Update the memory at Dest with Cmp's value.
443 CGF.EmitStoreOfScalar(Cmp, CGF.MakeAddrLValue(Dest, E->getType()));
444}
445
446/// Given an ordering required on success, emit all possible cmpxchg
447/// instructions to cope with the provided (but possibly only dynamically known)
448/// FailureOrder.
450 CodeGenFunction &CGF, AtomicExpr *E, bool IsWeak, Address Dest, Address Ptr,
451 Address Val1, Address Val2, Address ExpectedResult,
452 llvm::Value *FailureOrderVal, uint64_t Size,
453 llvm::AtomicOrdering SuccessOrder, llvm::SyncScope::ID Scope) {
454 llvm::AtomicOrdering FailureOrder;
455 if (llvm::ConstantInt *FO = dyn_cast<llvm::ConstantInt>(FailureOrderVal)) {
456 auto FOS = FO->getSExtValue();
457 if (!llvm::isValidAtomicOrderingCABI(FOS))
458 FailureOrder = llvm::AtomicOrdering::Monotonic;
459 else
460 switch ((llvm::AtomicOrderingCABI)FOS) {
461 case llvm::AtomicOrderingCABI::relaxed:
462 // 31.7.2.18: "The failure argument shall not be memory_order_release
463 // nor memory_order_acq_rel". Fallback to monotonic.
464 case llvm::AtomicOrderingCABI::release:
465 case llvm::AtomicOrderingCABI::acq_rel:
466 FailureOrder = llvm::AtomicOrdering::Monotonic;
467 break;
468 case llvm::AtomicOrderingCABI::consume:
469 case llvm::AtomicOrderingCABI::acquire:
470 FailureOrder = llvm::AtomicOrdering::Acquire;
471 break;
472 case llvm::AtomicOrderingCABI::seq_cst:
473 FailureOrder = llvm::AtomicOrdering::SequentiallyConsistent;
474 break;
475 }
476 // Prior to c++17, "the failure argument shall be no stronger than the
477 // success argument". This condition has been lifted and the only
478 // precondition is 31.7.2.18. Effectively treat this as a DR and skip
479 // language version checks.
480 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, ExpectedResult,
481 Size, SuccessOrder, FailureOrder, Scope);
482 return;
483 }
484
485 // Create all the relevant BB's
486 auto *MonotonicBB = CGF.createBasicBlock("monotonic_fail", CGF.CurFn);
487 auto *AcquireBB = CGF.createBasicBlock("acquire_fail", CGF.CurFn);
488 auto *SeqCstBB = CGF.createBasicBlock("seqcst_fail", CGF.CurFn);
489 auto *ContBB = CGF.createBasicBlock("atomic.continue", CGF.CurFn);
490
491 // MonotonicBB is arbitrarily chosen as the default case; in practice, this
492 // doesn't matter unless someone is crazy enough to use something that
493 // doesn't fold to a constant for the ordering.
494 llvm::SwitchInst *SI = CGF.Builder.CreateSwitch(FailureOrderVal, MonotonicBB);
495 // Implemented as acquire, since it's the closest in LLVM.
496 SI->addCase(CGF.Builder.getInt32((int)llvm::AtomicOrderingCABI::consume),
497 AcquireBB);
498 SI->addCase(CGF.Builder.getInt32((int)llvm::AtomicOrderingCABI::acquire),
499 AcquireBB);
500 SI->addCase(CGF.Builder.getInt32((int)llvm::AtomicOrderingCABI::seq_cst),
501 SeqCstBB);
502
503 // Emit all the different atomics
504 CGF.Builder.SetInsertPoint(MonotonicBB);
505 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, ExpectedResult, Size,
506 SuccessOrder, llvm::AtomicOrdering::Monotonic, Scope);
507 CGF.Builder.CreateBr(ContBB);
508
509 CGF.Builder.SetInsertPoint(AcquireBB);
510 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, ExpectedResult, Size,
511 SuccessOrder, llvm::AtomicOrdering::Acquire, Scope);
512 CGF.Builder.CreateBr(ContBB);
513
514 CGF.Builder.SetInsertPoint(SeqCstBB);
515 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, ExpectedResult, Size,
516 SuccessOrder, llvm::AtomicOrdering::SequentiallyConsistent,
517 Scope);
518 CGF.Builder.CreateBr(ContBB);
519
520 CGF.Builder.SetInsertPoint(ContBB);
521}
522
523/// Duplicate the atomic min/max operation in conventional IR for the builtin
524/// variants that return the new rather than the original value.
525static llvm::Value *EmitPostAtomicMinMax(CGBuilderTy &Builder,
527 bool IsSigned,
528 llvm::Value *OldVal,
529 llvm::Value *RHS) {
530 const bool IsFP = OldVal->getType()->isFloatingPointTy();
531
532 if (IsFP) {
533 llvm::Intrinsic::ID IID = (Op == AtomicExpr::AO__atomic_max_fetch ||
534 Op == AtomicExpr::AO__scoped_atomic_max_fetch)
535 ? llvm::Intrinsic::maxnum
536 : llvm::Intrinsic::minnum;
537
538 return Builder.CreateBinaryIntrinsic(IID, OldVal, RHS, llvm::FMFSource(),
539 "newval");
540 }
541
542 llvm::CmpInst::Predicate Pred;
543 switch (Op) {
544 default:
545 llvm_unreachable("Unexpected min/max operation");
546 case AtomicExpr::AO__atomic_max_fetch:
547 case AtomicExpr::AO__scoped_atomic_max_fetch:
548 Pred = IsSigned ? llvm::CmpInst::ICMP_SGT : llvm::CmpInst::ICMP_UGT;
549 break;
550 case AtomicExpr::AO__atomic_min_fetch:
551 case AtomicExpr::AO__scoped_atomic_min_fetch:
552 Pred = IsSigned ? llvm::CmpInst::ICMP_SLT : llvm::CmpInst::ICMP_ULT;
553 break;
554 }
555 llvm::Value *Cmp = Builder.CreateICmp(Pred, OldVal, RHS, "tst");
556 return Builder.CreateSelect(Cmp, OldVal, RHS, "newval");
557}
558
560 Address Ptr, Address Val1, Address Val2,
561 Address ExpectedResult, llvm::Value *IsWeak,
562 llvm::Value *FailureOrder, uint64_t Size,
563 llvm::AtomicOrdering Order,
564 llvm::SyncScope::ID Scope) {
565 llvm::AtomicRMWInst::BinOp Op = llvm::AtomicRMWInst::Add;
566 bool PostOpMinMax = false;
567 unsigned PostOp = 0;
568
569 switch (E->getOp()) {
570 case AtomicExpr::AO__c11_atomic_init:
571 case AtomicExpr::AO__opencl_atomic_init:
572 llvm_unreachable("Already handled!");
573
574 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
575 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
576 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
577 emitAtomicCmpXchgFailureSet(CGF, E, false, Dest, Ptr, Val1, Val2,
578 ExpectedResult, FailureOrder, Size, Order,
579 Scope);
580 return;
581 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
582 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
583 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
584 emitAtomicCmpXchgFailureSet(CGF, E, true, Dest, Ptr, Val1, Val2,
585 ExpectedResult, FailureOrder, Size, Order,
586 Scope);
587 return;
588 case AtomicExpr::AO__atomic_compare_exchange:
589 case AtomicExpr::AO__atomic_compare_exchange_n:
590 case AtomicExpr::AO__scoped_atomic_compare_exchange:
591 case AtomicExpr::AO__scoped_atomic_compare_exchange_n: {
592 if (llvm::ConstantInt *IsWeakC = dyn_cast<llvm::ConstantInt>(IsWeak)) {
593 emitAtomicCmpXchgFailureSet(CGF, E, IsWeakC->getZExtValue(), Dest, Ptr,
594 Val1, Val2, ExpectedResult, FailureOrder,
595 Size, Order, Scope);
596 } else {
597 // Create all the relevant BB's
598 llvm::BasicBlock *StrongBB =
599 CGF.createBasicBlock("cmpxchg.strong", CGF.CurFn);
600 llvm::BasicBlock *WeakBB = CGF.createBasicBlock("cmxchg.weak", CGF.CurFn);
601 llvm::BasicBlock *ContBB =
602 CGF.createBasicBlock("cmpxchg.continue", CGF.CurFn);
603
604 llvm::SwitchInst *SI = CGF.Builder.CreateSwitch(IsWeak, WeakBB);
605 SI->addCase(CGF.Builder.getInt1(false), StrongBB);
606
607 CGF.Builder.SetInsertPoint(StrongBB);
608 emitAtomicCmpXchgFailureSet(CGF, E, false, Dest, Ptr, Val1, Val2,
609 ExpectedResult, FailureOrder, Size, Order,
610 Scope);
611 CGF.Builder.CreateBr(ContBB);
612
613 CGF.Builder.SetInsertPoint(WeakBB);
614 emitAtomicCmpXchgFailureSet(CGF, E, true, Dest, Ptr, Val1, Val2,
615 ExpectedResult, FailureOrder, Size, Order,
616 Scope);
617 CGF.Builder.CreateBr(ContBB);
618
619 CGF.Builder.SetInsertPoint(ContBB);
620 }
621 return;
622 }
623 case AtomicExpr::AO__c11_atomic_load:
624 case AtomicExpr::AO__opencl_atomic_load:
625 case AtomicExpr::AO__hip_atomic_load:
626 case AtomicExpr::AO__atomic_load_n:
627 case AtomicExpr::AO__atomic_load:
628 case AtomicExpr::AO__scoped_atomic_load_n:
629 case AtomicExpr::AO__scoped_atomic_load: {
630 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Ptr);
631 Load->setAtomic(Order, Scope);
632 Load->setVolatile(E->isVolatile());
633 CGF.maybeAttachRangeForLoad(Load, E->getValueType(), E->getExprLoc());
634 auto *I = CGF.Builder.CreateStore(Load, Dest);
635 CGF.addInstToCurrentSourceAtom(I, Load);
636 return;
637 }
638
639 case AtomicExpr::AO__c11_atomic_store:
640 case AtomicExpr::AO__opencl_atomic_store:
641 case AtomicExpr::AO__hip_atomic_store:
642 case AtomicExpr::AO__atomic_store:
643 case AtomicExpr::AO__atomic_store_n:
644 case AtomicExpr::AO__scoped_atomic_store:
645 case AtomicExpr::AO__scoped_atomic_store_n: {
646 llvm::Value *LoadVal1 = CGF.Builder.CreateLoad(Val1);
647 llvm::StoreInst *Store = CGF.Builder.CreateStore(LoadVal1, Ptr);
648 Store->setAtomic(Order, Scope);
649 Store->setVolatile(E->isVolatile());
650 CGF.addInstToCurrentSourceAtom(Store, LoadVal1);
651 return;
652 }
653
654 case AtomicExpr::AO__c11_atomic_exchange:
655 case AtomicExpr::AO__hip_atomic_exchange:
656 case AtomicExpr::AO__opencl_atomic_exchange:
657 case AtomicExpr::AO__atomic_exchange_n:
658 case AtomicExpr::AO__atomic_exchange:
659 case AtomicExpr::AO__scoped_atomic_exchange_n:
660 case AtomicExpr::AO__scoped_atomic_exchange:
661 Op = llvm::AtomicRMWInst::Xchg;
662 break;
663
664 case AtomicExpr::AO__atomic_add_fetch:
665 case AtomicExpr::AO__scoped_atomic_add_fetch:
666 PostOp = E->getValueType()->isFloatingType() ? llvm::Instruction::FAdd
667 : llvm::Instruction::Add;
668 [[fallthrough]];
669 case AtomicExpr::AO__c11_atomic_fetch_add:
670 case AtomicExpr::AO__hip_atomic_fetch_add:
671 case AtomicExpr::AO__opencl_atomic_fetch_add:
672 case AtomicExpr::AO__atomic_fetch_add:
673 case AtomicExpr::AO__scoped_atomic_fetch_add:
674 Op = E->getValueType()->isFloatingType() ? llvm::AtomicRMWInst::FAdd
675 : llvm::AtomicRMWInst::Add;
676 break;
677
678 case AtomicExpr::AO__atomic_sub_fetch:
679 case AtomicExpr::AO__scoped_atomic_sub_fetch:
680 PostOp = E->getValueType()->isFloatingType() ? llvm::Instruction::FSub
681 : llvm::Instruction::Sub;
682 [[fallthrough]];
683 case AtomicExpr::AO__c11_atomic_fetch_sub:
684 case AtomicExpr::AO__hip_atomic_fetch_sub:
685 case AtomicExpr::AO__opencl_atomic_fetch_sub:
686 case AtomicExpr::AO__atomic_fetch_sub:
687 case AtomicExpr::AO__scoped_atomic_fetch_sub:
688 Op = E->getValueType()->isFloatingType() ? llvm::AtomicRMWInst::FSub
689 : llvm::AtomicRMWInst::Sub;
690 break;
691
692 case AtomicExpr::AO__atomic_min_fetch:
693 case AtomicExpr::AO__scoped_atomic_min_fetch:
694 PostOpMinMax = true;
695 [[fallthrough]];
696 case AtomicExpr::AO__c11_atomic_fetch_min:
697 case AtomicExpr::AO__hip_atomic_fetch_min:
698 case AtomicExpr::AO__opencl_atomic_fetch_min:
699 case AtomicExpr::AO__atomic_fetch_min:
700 case AtomicExpr::AO__scoped_atomic_fetch_min:
701 Op = E->getValueType()->isFloatingType()
702 ? llvm::AtomicRMWInst::FMin
703 : (E->getValueType()->isSignedIntegerType()
704 ? llvm::AtomicRMWInst::Min
705 : llvm::AtomicRMWInst::UMin);
706 break;
707
708 case AtomicExpr::AO__atomic_max_fetch:
709 case AtomicExpr::AO__scoped_atomic_max_fetch:
710 PostOpMinMax = true;
711 [[fallthrough]];
712 case AtomicExpr::AO__c11_atomic_fetch_max:
713 case AtomicExpr::AO__hip_atomic_fetch_max:
714 case AtomicExpr::AO__opencl_atomic_fetch_max:
715 case AtomicExpr::AO__atomic_fetch_max:
716 case AtomicExpr::AO__scoped_atomic_fetch_max:
717 Op = E->getValueType()->isFloatingType()
718 ? llvm::AtomicRMWInst::FMax
719 : (E->getValueType()->isSignedIntegerType()
720 ? llvm::AtomicRMWInst::Max
721 : llvm::AtomicRMWInst::UMax);
722 break;
723
724 case AtomicExpr::AO__atomic_and_fetch:
725 case AtomicExpr::AO__scoped_atomic_and_fetch:
726 PostOp = llvm::Instruction::And;
727 [[fallthrough]];
728 case AtomicExpr::AO__c11_atomic_fetch_and:
729 case AtomicExpr::AO__hip_atomic_fetch_and:
730 case AtomicExpr::AO__opencl_atomic_fetch_and:
731 case AtomicExpr::AO__atomic_fetch_and:
732 case AtomicExpr::AO__scoped_atomic_fetch_and:
733 Op = llvm::AtomicRMWInst::And;
734 break;
735
736 case AtomicExpr::AO__atomic_or_fetch:
737 case AtomicExpr::AO__scoped_atomic_or_fetch:
738 PostOp = llvm::Instruction::Or;
739 [[fallthrough]];
740 case AtomicExpr::AO__c11_atomic_fetch_or:
741 case AtomicExpr::AO__hip_atomic_fetch_or:
742 case AtomicExpr::AO__opencl_atomic_fetch_or:
743 case AtomicExpr::AO__atomic_fetch_or:
744 case AtomicExpr::AO__scoped_atomic_fetch_or:
745 Op = llvm::AtomicRMWInst::Or;
746 break;
747
748 case AtomicExpr::AO__atomic_xor_fetch:
749 case AtomicExpr::AO__scoped_atomic_xor_fetch:
750 PostOp = llvm::Instruction::Xor;
751 [[fallthrough]];
752 case AtomicExpr::AO__c11_atomic_fetch_xor:
753 case AtomicExpr::AO__hip_atomic_fetch_xor:
754 case AtomicExpr::AO__opencl_atomic_fetch_xor:
755 case AtomicExpr::AO__atomic_fetch_xor:
756 case AtomicExpr::AO__scoped_atomic_fetch_xor:
757 Op = llvm::AtomicRMWInst::Xor;
758 break;
759
760 case AtomicExpr::AO__atomic_nand_fetch:
761 case AtomicExpr::AO__scoped_atomic_nand_fetch:
762 PostOp = llvm::Instruction::And; // the NOT is special cased below
763 [[fallthrough]];
764 case AtomicExpr::AO__c11_atomic_fetch_nand:
765 case AtomicExpr::AO__atomic_fetch_nand:
766 case AtomicExpr::AO__scoped_atomic_fetch_nand:
767 Op = llvm::AtomicRMWInst::Nand;
768 break;
769
770 case AtomicExpr::AO__atomic_fetch_uinc:
771 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
772 Op = llvm::AtomicRMWInst::UIncWrap;
773 break;
774 case AtomicExpr::AO__atomic_fetch_udec:
775 case AtomicExpr::AO__scoped_atomic_fetch_udec:
776 Op = llvm::AtomicRMWInst::UDecWrap;
777 break;
778
779 case AtomicExpr::AO__atomic_test_and_set: {
780 llvm::AtomicRMWInst *RMWI =
781 CGF.emitAtomicRMWInst(llvm::AtomicRMWInst::Xchg, Ptr,
782 CGF.Builder.getInt8(1), Order, Scope, E);
783 RMWI->setVolatile(E->isVolatile());
784 llvm::Value *Result = CGF.EmitToMemory(
785 CGF.Builder.CreateIsNotNull(RMWI, "tobool"), E->getType());
786 auto *I = CGF.Builder.CreateStore(Result, Dest);
787 CGF.addInstToCurrentSourceAtom(I, Result);
788 return;
789 }
790
791 case AtomicExpr::AO__atomic_clear: {
792 llvm::StoreInst *Store =
793 CGF.Builder.CreateStore(CGF.Builder.getInt8(0), Ptr);
794 Store->setAtomic(Order, Scope);
795 Store->setVolatile(E->isVolatile());
796 CGF.addInstToCurrentSourceAtom(Store, nullptr);
797 return;
798 }
799 }
800
801 llvm::Value *LoadVal1 = CGF.Builder.CreateLoad(Val1);
802 llvm::AtomicRMWInst *RMWI =
803 CGF.emitAtomicRMWInst(Op, Ptr, LoadVal1, Order, Scope, E);
804 RMWI->setVolatile(E->isVolatile());
805
806 // For __atomic_*_fetch operations, perform the operation again to
807 // determine the value which was written.
808 llvm::Value *Result = RMWI;
809 if (PostOpMinMax)
810 Result = EmitPostAtomicMinMax(CGF.Builder, E->getOp(),
812 RMWI, LoadVal1);
813 else if (PostOp)
814 Result = CGF.Builder.CreateBinOp((llvm::Instruction::BinaryOps)PostOp, RMWI,
815 LoadVal1);
816 if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch ||
817 E->getOp() == AtomicExpr::AO__scoped_atomic_nand_fetch)
818 Result = CGF.Builder.CreateNot(Result);
819 auto *I = CGF.Builder.CreateStore(Result, Dest);
820 CGF.addInstToCurrentSourceAtom(I, Result);
821}
822
823// This function emits any expression (scalar, complex, or aggregate)
824// into a temporary alloca.
825static Address
827 Address DeclPtr = CGF.CreateMemTemp(E->getType(), ".atomictmp");
828 CGF.EmitAnyExprToMem(E, DeclPtr, E->getType().getQualifiers(),
829 /*Init*/ true);
830 return DeclPtr;
831}
832
833/// Return true if \param ValTy is a type that should be casted to integer
834/// around the atomic memory operation. If \param CmpXchg is true, then the
835/// cast of a floating point type is made as that instruction can not have
836/// floating point operands. TODO: Allow compare-and-exchange and FP - see
837/// comment in AtomicExpandPass.cpp.
838static bool shouldCastToInt(llvm::Type *ValTy, bool CmpXchg) {
839 if (ValTy->isFloatingPointTy())
840 return ValTy->isX86_FP80Ty() || CmpXchg;
841 return !ValTy->isIntegerTy() && !ValTy->isPointerTy();
842}
843
845 Address Ptr, Address Val1, Address Val2,
846 Address OriginalVal1, llvm::Value *IsWeak,
847 llvm::Value *FailureOrder, uint64_t Size,
848 llvm::AtomicOrdering Order, llvm::Value *Scope) {
849 auto ScopeModel = Expr->getScopeModel();
850
851 // LLVM atomic instructions always have sync scope. If clang atomic
852 // expression has no scope operand, use default LLVM sync scope.
853 if (!ScopeModel) {
854 llvm::SyncScope::ID SS;
855 if (CGF.getLangOpts().OpenCL)
856 // OpenCL approach is: "The functions that do not have memory_scope
857 // argument have the same semantics as the corresponding functions with
858 // the memory_scope argument set to memory_scope_device." See ref.:
859 // https://registry.khronos.org/OpenCL/specs/3.0-unified/html/OpenCL_C.html#atomic-functions
862 Order, CGF.getLLVMContext());
863 else
864 SS = llvm::SyncScope::System;
865 EmitAtomicOp(CGF, Expr, Dest, Ptr, Val1, Val2, OriginalVal1, IsWeak,
866 FailureOrder, Size, Order, SS);
867 return;
868 }
869
870 // Handle constant scope.
871 if (auto SC = dyn_cast<llvm::ConstantInt>(Scope)) {
872 auto SCID = CGF.getTargetHooks().getLLVMSyncScopeID(
873 CGF.CGM.getLangOpts(), ScopeModel->map(SC->getZExtValue()),
874 Order, CGF.CGM.getLLVMContext());
875 EmitAtomicOp(CGF, Expr, Dest, Ptr, Val1, Val2, OriginalVal1, IsWeak,
876 FailureOrder, Size, Order, SCID);
877 return;
878 }
879
880 // Handle non-constant scope.
881 auto &Builder = CGF.Builder;
882 auto Scopes = ScopeModel->getRuntimeValues();
883 llvm::DenseMap<unsigned, llvm::BasicBlock *> BB;
884 for (auto S : Scopes)
885 BB[S] = CGF.createBasicBlock(getAsString(ScopeModel->map(S)), CGF.CurFn);
886
887 llvm::BasicBlock *ContBB =
888 CGF.createBasicBlock("atomic.scope.continue", CGF.CurFn);
889
890 auto *SC = Builder.CreateIntCast(Scope, Builder.getInt32Ty(), false);
891 // If unsupported sync scope is encountered at run time, assume a fallback
892 // sync scope value.
893 auto FallBack = ScopeModel->getFallBackValue();
894 llvm::SwitchInst *SI = Builder.CreateSwitch(SC, BB[FallBack]);
895 for (auto S : Scopes) {
896 auto *B = BB[S];
897 if (S != FallBack)
898 SI->addCase(Builder.getInt32(S), B);
899
900 Builder.SetInsertPoint(B);
901 EmitAtomicOp(CGF, Expr, Dest, Ptr, Val1, Val2, OriginalVal1, IsWeak,
902 FailureOrder, Size, Order,
904 CGF.CGM.getLangOpts(), ScopeModel->map(S), Order,
905 CGF.getLLVMContext()));
906 Builder.CreateBr(ContBB);
907 }
908
909 Builder.SetInsertPoint(ContBB);
910}
911
914
915 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
916 QualType MemTy = AtomicTy;
917 if (const AtomicType *AT = AtomicTy->getAs<AtomicType>())
918 MemTy = AT->getValueType();
919 llvm::Value *IsWeak = nullptr, *OrderFail = nullptr;
920
921 Address Val1 = Address::invalid();
922 Address Val2 = Address::invalid();
923 Address Dest = Address::invalid();
925
926 if (E->getOp() == AtomicExpr::AO__c11_atomic_init ||
927 E->getOp() == AtomicExpr::AO__opencl_atomic_init) {
928 LValue lvalue = MakeAddrLValue(Ptr, AtomicTy);
929 EmitAtomicInit(E->getVal1(), lvalue);
930 return RValue::get(nullptr);
931 }
932
933 auto TInfo = getContext().getTypeInfoInChars(AtomicTy);
934 uint64_t Size = TInfo.Width.getQuantity();
935 unsigned MaxInlineWidthInBits = getTarget().getMaxAtomicInlineWidth();
936
937 CharUnits MaxInlineWidth =
938 getContext().toCharUnitsFromBits(MaxInlineWidthInBits);
939 DiagnosticsEngine &Diags = CGM.getDiags();
940 bool Misaligned = !Ptr.getAlignment().isMultipleOf(TInfo.Width);
941 bool Oversized = getContext().toBits(TInfo.Width) > MaxInlineWidthInBits;
942 if (Misaligned) {
943 Diags.Report(E->getBeginLoc(), diag::warn_atomic_op_misaligned)
944 << (int)TInfo.Width.getQuantity()
945 << (int)Ptr.getAlignment().getQuantity();
946 }
947 if (Oversized) {
948 Diags.Report(E->getBeginLoc(), diag::warn_atomic_op_oversized)
949 << (int)TInfo.Width.getQuantity() << (int)MaxInlineWidth.getQuantity();
950 }
951
952 llvm::Value *Order = EmitScalarExpr(E->getOrder());
953 llvm::Value *Scope =
954 E->getScopeModel() ? EmitScalarExpr(E->getScope()) : nullptr;
955
956 switch (E->getOp()) {
957 case AtomicExpr::AO__c11_atomic_init:
958 case AtomicExpr::AO__opencl_atomic_init:
959 llvm_unreachable("Already handled above with EmitAtomicInit!");
960
961 case AtomicExpr::AO__atomic_load_n:
962 case AtomicExpr::AO__scoped_atomic_load_n:
963 case AtomicExpr::AO__c11_atomic_load:
964 case AtomicExpr::AO__opencl_atomic_load:
965 case AtomicExpr::AO__hip_atomic_load:
966 case AtomicExpr::AO__atomic_test_and_set:
967 case AtomicExpr::AO__atomic_clear:
968 break;
969
970 case AtomicExpr::AO__atomic_load:
971 case AtomicExpr::AO__scoped_atomic_load:
973 break;
974
975 case AtomicExpr::AO__atomic_store:
976 case AtomicExpr::AO__scoped_atomic_store:
978 break;
979
980 case AtomicExpr::AO__atomic_exchange:
981 case AtomicExpr::AO__scoped_atomic_exchange:
984 break;
985
986 case AtomicExpr::AO__atomic_compare_exchange:
987 case AtomicExpr::AO__atomic_compare_exchange_n:
988 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
989 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
990 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
991 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
992 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
993 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
994 case AtomicExpr::AO__scoped_atomic_compare_exchange:
995 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
997 if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange ||
998 E->getOp() == AtomicExpr::AO__scoped_atomic_compare_exchange)
1000 else
1001 Val2 = EmitValToTemp(*this, E->getVal2());
1002 OrderFail = EmitScalarExpr(E->getOrderFail());
1003 if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange_n ||
1004 E->getOp() == AtomicExpr::AO__atomic_compare_exchange ||
1005 E->getOp() == AtomicExpr::AO__scoped_atomic_compare_exchange_n ||
1006 E->getOp() == AtomicExpr::AO__scoped_atomic_compare_exchange)
1007 IsWeak = EmitScalarExpr(E->getWeak());
1008 break;
1009
1010 case AtomicExpr::AO__c11_atomic_fetch_add:
1011 case AtomicExpr::AO__c11_atomic_fetch_sub:
1012 case AtomicExpr::AO__hip_atomic_fetch_add:
1013 case AtomicExpr::AO__hip_atomic_fetch_sub:
1014 case AtomicExpr::AO__opencl_atomic_fetch_add:
1015 case AtomicExpr::AO__opencl_atomic_fetch_sub:
1016 if (MemTy->isPointerType()) {
1017 // For pointer arithmetic, we're required to do a bit of math:
1018 // adding 1 to an int* is not the same as adding 1 to a uintptr_t.
1019 // ... but only for the C11 builtins. The GNU builtins expect the
1020 // user to multiply by sizeof(T).
1021 QualType Val1Ty = E->getVal1()->getType();
1022 llvm::Value *Val1Scalar = EmitScalarExpr(E->getVal1());
1023 CharUnits PointeeIncAmt =
1024 getContext().getTypeSizeInChars(MemTy->getPointeeType());
1025 Val1Scalar = Builder.CreateMul(Val1Scalar, CGM.getSize(PointeeIncAmt));
1026 auto Temp = CreateMemTemp(Val1Ty, ".atomictmp");
1027 Val1 = Temp;
1028 EmitStoreOfScalar(Val1Scalar, MakeAddrLValue(Temp, Val1Ty));
1029 break;
1030 }
1031 [[fallthrough]];
1032 case AtomicExpr::AO__atomic_fetch_add:
1033 case AtomicExpr::AO__atomic_fetch_max:
1034 case AtomicExpr::AO__atomic_fetch_min:
1035 case AtomicExpr::AO__atomic_fetch_sub:
1036 case AtomicExpr::AO__atomic_add_fetch:
1037 case AtomicExpr::AO__atomic_max_fetch:
1038 case AtomicExpr::AO__atomic_min_fetch:
1039 case AtomicExpr::AO__atomic_sub_fetch:
1040 case AtomicExpr::AO__c11_atomic_fetch_max:
1041 case AtomicExpr::AO__c11_atomic_fetch_min:
1042 case AtomicExpr::AO__opencl_atomic_fetch_max:
1043 case AtomicExpr::AO__opencl_atomic_fetch_min:
1044 case AtomicExpr::AO__hip_atomic_fetch_max:
1045 case AtomicExpr::AO__hip_atomic_fetch_min:
1046 case AtomicExpr::AO__scoped_atomic_fetch_add:
1047 case AtomicExpr::AO__scoped_atomic_fetch_max:
1048 case AtomicExpr::AO__scoped_atomic_fetch_min:
1049 case AtomicExpr::AO__scoped_atomic_fetch_sub:
1050 case AtomicExpr::AO__scoped_atomic_add_fetch:
1051 case AtomicExpr::AO__scoped_atomic_max_fetch:
1052 case AtomicExpr::AO__scoped_atomic_min_fetch:
1053 case AtomicExpr::AO__scoped_atomic_sub_fetch:
1054 [[fallthrough]];
1055
1056 case AtomicExpr::AO__atomic_fetch_and:
1057 case AtomicExpr::AO__atomic_fetch_nand:
1058 case AtomicExpr::AO__atomic_fetch_or:
1059 case AtomicExpr::AO__atomic_fetch_xor:
1060 case AtomicExpr::AO__atomic_fetch_uinc:
1061 case AtomicExpr::AO__atomic_fetch_udec:
1062 case AtomicExpr::AO__atomic_and_fetch:
1063 case AtomicExpr::AO__atomic_nand_fetch:
1064 case AtomicExpr::AO__atomic_or_fetch:
1065 case AtomicExpr::AO__atomic_xor_fetch:
1066 case AtomicExpr::AO__atomic_store_n:
1067 case AtomicExpr::AO__atomic_exchange_n:
1068 case AtomicExpr::AO__c11_atomic_fetch_and:
1069 case AtomicExpr::AO__c11_atomic_fetch_nand:
1070 case AtomicExpr::AO__c11_atomic_fetch_or:
1071 case AtomicExpr::AO__c11_atomic_fetch_xor:
1072 case AtomicExpr::AO__c11_atomic_store:
1073 case AtomicExpr::AO__c11_atomic_exchange:
1074 case AtomicExpr::AO__hip_atomic_fetch_and:
1075 case AtomicExpr::AO__hip_atomic_fetch_or:
1076 case AtomicExpr::AO__hip_atomic_fetch_xor:
1077 case AtomicExpr::AO__hip_atomic_store:
1078 case AtomicExpr::AO__hip_atomic_exchange:
1079 case AtomicExpr::AO__opencl_atomic_fetch_and:
1080 case AtomicExpr::AO__opencl_atomic_fetch_or:
1081 case AtomicExpr::AO__opencl_atomic_fetch_xor:
1082 case AtomicExpr::AO__opencl_atomic_store:
1083 case AtomicExpr::AO__opencl_atomic_exchange:
1084 case AtomicExpr::AO__scoped_atomic_fetch_and:
1085 case AtomicExpr::AO__scoped_atomic_fetch_nand:
1086 case AtomicExpr::AO__scoped_atomic_fetch_or:
1087 case AtomicExpr::AO__scoped_atomic_fetch_xor:
1088 case AtomicExpr::AO__scoped_atomic_and_fetch:
1089 case AtomicExpr::AO__scoped_atomic_nand_fetch:
1090 case AtomicExpr::AO__scoped_atomic_or_fetch:
1091 case AtomicExpr::AO__scoped_atomic_xor_fetch:
1092 case AtomicExpr::AO__scoped_atomic_store_n:
1093 case AtomicExpr::AO__scoped_atomic_exchange_n:
1094 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
1095 case AtomicExpr::AO__scoped_atomic_fetch_udec:
1096 Val1 = EmitValToTemp(*this, E->getVal1());
1097 break;
1098 }
1099
1100 QualType RValTy = E->getType().getUnqualifiedType();
1101 bool ShouldCastToIntPtrTy =
1103
1104 // The inlined atomics only function on iN types, where N is a power of 2. We
1105 // need to make sure (via temporaries if necessary) that all incoming values
1106 // are compatible.
1107 LValue AtomicVal = MakeAddrLValue(Ptr, AtomicTy);
1108 AtomicInfo Atomics(*this, AtomicVal);
1109
1110 Address OriginalVal1 = Val1;
1111 if (ShouldCastToIntPtrTy) {
1112 Ptr = Atomics.castToAtomicIntPointer(Ptr);
1113 if (Val1.isValid())
1114 Val1 = Atomics.convertToAtomicIntPointer(Val1);
1115 if (Val2.isValid())
1116 Val2 = Atomics.convertToAtomicIntPointer(Val2);
1117 }
1118 if (Dest.isValid()) {
1119 if (ShouldCastToIntPtrTy)
1120 Dest = Atomics.castToAtomicIntPointer(Dest);
1121 } else if (E->isCmpXChg())
1122 Dest = CreateMemTemp(RValTy, "cmpxchg.bool");
1123 else if (!RValTy->isVoidType()) {
1124 Dest = Atomics.CreateTempAlloca();
1125 if (ShouldCastToIntPtrTy)
1126 Dest = Atomics.castToAtomicIntPointer(Dest);
1127 }
1128
1129 bool PowerOf2Size = (Size & (Size - 1)) == 0;
1130 bool UseLibcall = !PowerOf2Size || (Size > 16);
1131
1132 // For atomics larger than 16 bytes, emit a libcall from the frontend. This
1133 // avoids the overhead of dealing with excessively-large value types in IR.
1134 // Non-power-of-2 values also lower to libcall here, as they are not currently
1135 // permitted in IR instructions (although that constraint could be relaxed in
1136 // the future). For other cases where a libcall is required on a given
1137 // platform, we let the backend handle it (this includes handling for all of
1138 // the size-optimized libcall variants, which are only valid up to 16 bytes.)
1139 //
1140 // See: https://llvm.org/docs/Atomics.html#libcalls-atomic
1141 if (UseLibcall) {
1142 CallArgList Args;
1143 // For non-optimized library calls, the size is the first parameter.
1144 Args.add(RValue::get(llvm::ConstantInt::get(SizeTy, Size)),
1145 getContext().getSizeType());
1146
1147 // The atomic address is the second parameter.
1148 // The OpenCL atomic library functions only accept pointer arguments to
1149 // generic address space.
1150 auto CastToGenericAddrSpace = [&](llvm::Value *V, QualType PT) {
1151 if (!E->isOpenCL())
1152 return V;
1153 auto AS = PT->castAs<PointerType>()->getPointeeType().getAddressSpace();
1154 if (AS == LangAS::opencl_generic)
1155 return V;
1156 auto DestAS = getContext().getTargetAddressSpace(LangAS::opencl_generic);
1157 auto *DestType = llvm::PointerType::get(getLLVMContext(), DestAS);
1158
1159 return performAddrSpaceCast(V, DestType);
1160 };
1161
1162 Args.add(RValue::get(CastToGenericAddrSpace(Ptr.emitRawPointer(*this),
1163 E->getPtr()->getType())),
1165
1166 // The next 1-3 parameters are op-dependent.
1167 std::string LibCallName;
1168 QualType RetTy;
1169 bool HaveRetTy = false;
1170 switch (E->getOp()) {
1171 case AtomicExpr::AO__c11_atomic_init:
1172 case AtomicExpr::AO__opencl_atomic_init:
1173 llvm_unreachable("Already handled!");
1174
1175 // There is only one libcall for compare an exchange, because there is no
1176 // optimisation benefit possible from a libcall version of a weak compare
1177 // and exchange.
1178 // bool __atomic_compare_exchange(size_t size, void *mem, void *expected,
1179 // void *desired, int success, int failure)
1180 case AtomicExpr::AO__atomic_compare_exchange:
1181 case AtomicExpr::AO__atomic_compare_exchange_n:
1182 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1183 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1184 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
1185 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
1186 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
1187 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
1188 case AtomicExpr::AO__scoped_atomic_compare_exchange:
1189 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
1190 LibCallName = "__atomic_compare_exchange";
1191 RetTy = getContext().BoolTy;
1192 HaveRetTy = true;
1193 Args.add(RValue::get(CastToGenericAddrSpace(Val1.emitRawPointer(*this),
1194 E->getVal1()->getType())),
1196 Args.add(RValue::get(CastToGenericAddrSpace(Val2.emitRawPointer(*this),
1197 E->getVal2()->getType())),
1199 Args.add(RValue::get(Order), getContext().IntTy);
1200 Order = OrderFail;
1201 break;
1202 // void __atomic_exchange(size_t size, void *mem, void *val, void *return,
1203 // int order)
1204 case AtomicExpr::AO__atomic_exchange:
1205 case AtomicExpr::AO__atomic_exchange_n:
1206 case AtomicExpr::AO__c11_atomic_exchange:
1207 case AtomicExpr::AO__hip_atomic_exchange:
1208 case AtomicExpr::AO__opencl_atomic_exchange:
1209 case AtomicExpr::AO__scoped_atomic_exchange:
1210 case AtomicExpr::AO__scoped_atomic_exchange_n:
1211 LibCallName = "__atomic_exchange";
1212 Args.add(RValue::get(CastToGenericAddrSpace(Val1.emitRawPointer(*this),
1213 E->getVal1()->getType())),
1215 break;
1216 // void __atomic_store(size_t size, void *mem, void *val, int order)
1217 case AtomicExpr::AO__atomic_store:
1218 case AtomicExpr::AO__atomic_store_n:
1219 case AtomicExpr::AO__c11_atomic_store:
1220 case AtomicExpr::AO__hip_atomic_store:
1221 case AtomicExpr::AO__opencl_atomic_store:
1222 case AtomicExpr::AO__scoped_atomic_store:
1223 case AtomicExpr::AO__scoped_atomic_store_n:
1224 LibCallName = "__atomic_store";
1225 RetTy = getContext().VoidTy;
1226 HaveRetTy = true;
1227 Args.add(RValue::get(CastToGenericAddrSpace(Val1.emitRawPointer(*this),
1228 E->getVal1()->getType())),
1230 break;
1231 // void __atomic_load(size_t size, void *mem, void *return, int order)
1232 case AtomicExpr::AO__atomic_load:
1233 case AtomicExpr::AO__atomic_load_n:
1234 case AtomicExpr::AO__c11_atomic_load:
1235 case AtomicExpr::AO__hip_atomic_load:
1236 case AtomicExpr::AO__opencl_atomic_load:
1237 case AtomicExpr::AO__scoped_atomic_load:
1238 case AtomicExpr::AO__scoped_atomic_load_n:
1239 LibCallName = "__atomic_load";
1240 break;
1241 case AtomicExpr::AO__atomic_add_fetch:
1242 case AtomicExpr::AO__scoped_atomic_add_fetch:
1243 case AtomicExpr::AO__atomic_fetch_add:
1244 case AtomicExpr::AO__c11_atomic_fetch_add:
1245 case AtomicExpr::AO__hip_atomic_fetch_add:
1246 case AtomicExpr::AO__opencl_atomic_fetch_add:
1247 case AtomicExpr::AO__scoped_atomic_fetch_add:
1248 case AtomicExpr::AO__atomic_and_fetch:
1249 case AtomicExpr::AO__scoped_atomic_and_fetch:
1250 case AtomicExpr::AO__atomic_fetch_and:
1251 case AtomicExpr::AO__c11_atomic_fetch_and:
1252 case AtomicExpr::AO__hip_atomic_fetch_and:
1253 case AtomicExpr::AO__opencl_atomic_fetch_and:
1254 case AtomicExpr::AO__scoped_atomic_fetch_and:
1255 case AtomicExpr::AO__atomic_or_fetch:
1256 case AtomicExpr::AO__scoped_atomic_or_fetch:
1257 case AtomicExpr::AO__atomic_fetch_or:
1258 case AtomicExpr::AO__c11_atomic_fetch_or:
1259 case AtomicExpr::AO__hip_atomic_fetch_or:
1260 case AtomicExpr::AO__opencl_atomic_fetch_or:
1261 case AtomicExpr::AO__scoped_atomic_fetch_or:
1262 case AtomicExpr::AO__atomic_sub_fetch:
1263 case AtomicExpr::AO__scoped_atomic_sub_fetch:
1264 case AtomicExpr::AO__atomic_fetch_sub:
1265 case AtomicExpr::AO__c11_atomic_fetch_sub:
1266 case AtomicExpr::AO__hip_atomic_fetch_sub:
1267 case AtomicExpr::AO__opencl_atomic_fetch_sub:
1268 case AtomicExpr::AO__scoped_atomic_fetch_sub:
1269 case AtomicExpr::AO__atomic_xor_fetch:
1270 case AtomicExpr::AO__scoped_atomic_xor_fetch:
1271 case AtomicExpr::AO__atomic_fetch_xor:
1272 case AtomicExpr::AO__c11_atomic_fetch_xor:
1273 case AtomicExpr::AO__hip_atomic_fetch_xor:
1274 case AtomicExpr::AO__opencl_atomic_fetch_xor:
1275 case AtomicExpr::AO__scoped_atomic_fetch_xor:
1276 case AtomicExpr::AO__atomic_nand_fetch:
1277 case AtomicExpr::AO__atomic_fetch_nand:
1278 case AtomicExpr::AO__c11_atomic_fetch_nand:
1279 case AtomicExpr::AO__scoped_atomic_fetch_nand:
1280 case AtomicExpr::AO__scoped_atomic_nand_fetch:
1281 case AtomicExpr::AO__atomic_min_fetch:
1282 case AtomicExpr::AO__atomic_fetch_min:
1283 case AtomicExpr::AO__c11_atomic_fetch_min:
1284 case AtomicExpr::AO__hip_atomic_fetch_min:
1285 case AtomicExpr::AO__opencl_atomic_fetch_min:
1286 case AtomicExpr::AO__scoped_atomic_fetch_min:
1287 case AtomicExpr::AO__scoped_atomic_min_fetch:
1288 case AtomicExpr::AO__atomic_max_fetch:
1289 case AtomicExpr::AO__atomic_fetch_max:
1290 case AtomicExpr::AO__c11_atomic_fetch_max:
1291 case AtomicExpr::AO__hip_atomic_fetch_max:
1292 case AtomicExpr::AO__opencl_atomic_fetch_max:
1293 case AtomicExpr::AO__scoped_atomic_fetch_max:
1294 case AtomicExpr::AO__scoped_atomic_max_fetch:
1295 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
1296 case AtomicExpr::AO__scoped_atomic_fetch_udec:
1297 case AtomicExpr::AO__atomic_test_and_set:
1298 case AtomicExpr::AO__atomic_clear:
1299 case AtomicExpr::AO__atomic_fetch_uinc:
1300 case AtomicExpr::AO__atomic_fetch_udec:
1301 llvm_unreachable("Integral atomic operations always become atomicrmw!");
1302 }
1303
1304 if (E->isOpenCL()) {
1305 LibCallName =
1306 std::string("__opencl") + StringRef(LibCallName).drop_front(1).str();
1307 }
1308 // By default, assume we return a value of the atomic type.
1309 if (!HaveRetTy) {
1310 // Value is returned through parameter before the order.
1311 RetTy = getContext().VoidTy;
1312 Args.add(RValue::get(
1313 CastToGenericAddrSpace(Dest.emitRawPointer(*this), RetTy)),
1315 }
1316 // Order is always the last parameter.
1317 Args.add(RValue::get(Order),
1318 getContext().IntTy);
1319 if (E->isOpenCL())
1321
1322 RValue Res = emitAtomicLibcall(*this, LibCallName, RetTy, Args);
1323 // The value is returned directly from the libcall.
1324 if (E->isCmpXChg())
1325 return Res;
1326
1327 if (RValTy->isVoidType())
1328 return RValue::get(nullptr);
1329
1331 RValTy, E->getExprLoc());
1332 }
1333
1334 bool IsStore = E->getOp() == AtomicExpr::AO__c11_atomic_store ||
1335 E->getOp() == AtomicExpr::AO__opencl_atomic_store ||
1336 E->getOp() == AtomicExpr::AO__hip_atomic_store ||
1337 E->getOp() == AtomicExpr::AO__atomic_store ||
1338 E->getOp() == AtomicExpr::AO__atomic_store_n ||
1339 E->getOp() == AtomicExpr::AO__scoped_atomic_store ||
1340 E->getOp() == AtomicExpr::AO__scoped_atomic_store_n ||
1341 E->getOp() == AtomicExpr::AO__atomic_clear;
1342 bool IsLoad = E->getOp() == AtomicExpr::AO__c11_atomic_load ||
1343 E->getOp() == AtomicExpr::AO__opencl_atomic_load ||
1344 E->getOp() == AtomicExpr::AO__hip_atomic_load ||
1345 E->getOp() == AtomicExpr::AO__atomic_load ||
1346 E->getOp() == AtomicExpr::AO__atomic_load_n ||
1347 E->getOp() == AtomicExpr::AO__scoped_atomic_load ||
1348 E->getOp() == AtomicExpr::AO__scoped_atomic_load_n;
1349
1350 if (isa<llvm::ConstantInt>(Order)) {
1351 auto ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
1352 // We should not ever get to a case where the ordering isn't a valid C ABI
1353 // value, but it's hard to enforce that in general.
1354 if (llvm::isValidAtomicOrderingCABI(ord))
1355 switch ((llvm::AtomicOrderingCABI)ord) {
1356 case llvm::AtomicOrderingCABI::relaxed:
1357 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, OriginalVal1, IsWeak,
1358 OrderFail, Size, llvm::AtomicOrdering::Monotonic, Scope);
1359 break;
1360 case llvm::AtomicOrderingCABI::consume:
1361 case llvm::AtomicOrderingCABI::acquire:
1362 if (IsStore)
1363 break; // Avoid crashing on code with undefined behavior
1364 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, OriginalVal1, IsWeak,
1365 OrderFail, Size, llvm::AtomicOrdering::Acquire, Scope);
1366 break;
1367 case llvm::AtomicOrderingCABI::release:
1368 if (IsLoad)
1369 break; // Avoid crashing on code with undefined behavior
1370 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, OriginalVal1, IsWeak,
1371 OrderFail, Size, llvm::AtomicOrdering::Release, Scope);
1372 break;
1373 case llvm::AtomicOrderingCABI::acq_rel:
1374 if (IsLoad || IsStore)
1375 break; // Avoid crashing on code with undefined behavior
1376 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, OriginalVal1, IsWeak,
1377 OrderFail, Size, llvm::AtomicOrdering::AcquireRelease,
1378 Scope);
1379 break;
1380 case llvm::AtomicOrderingCABI::seq_cst:
1381 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, OriginalVal1, IsWeak,
1382 OrderFail, Size,
1383 llvm::AtomicOrdering::SequentiallyConsistent, Scope);
1384 break;
1385 }
1386 if (RValTy->isVoidType())
1387 return RValue::get(nullptr);
1388
1390 RValTy, E->getExprLoc());
1391 }
1392
1393 // Long case, when Order isn't obviously constant.
1394
1395 // Create all the relevant BB's
1396 llvm::BasicBlock *MonotonicBB = nullptr, *AcquireBB = nullptr,
1397 *ReleaseBB = nullptr, *AcqRelBB = nullptr,
1398 *SeqCstBB = nullptr;
1399 MonotonicBB = createBasicBlock("monotonic", CurFn);
1400 if (!IsStore)
1401 AcquireBB = createBasicBlock("acquire", CurFn);
1402 if (!IsLoad)
1403 ReleaseBB = createBasicBlock("release", CurFn);
1404 if (!IsLoad && !IsStore)
1405 AcqRelBB = createBasicBlock("acqrel", CurFn);
1406 SeqCstBB = createBasicBlock("seqcst", CurFn);
1407 llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
1408
1409 // Create the switch for the split
1410 // MonotonicBB is arbitrarily chosen as the default case; in practice, this
1411 // doesn't matter unless someone is crazy enough to use something that
1412 // doesn't fold to a constant for the ordering.
1413 Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
1414 llvm::SwitchInst *SI = Builder.CreateSwitch(Order, MonotonicBB);
1415
1416 // Emit all the different atomics
1417 Builder.SetInsertPoint(MonotonicBB);
1418 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, OriginalVal1, IsWeak, OrderFail,
1419 Size, llvm::AtomicOrdering::Monotonic, Scope);
1420 Builder.CreateBr(ContBB);
1421 if (!IsStore) {
1422 Builder.SetInsertPoint(AcquireBB);
1423 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, OriginalVal1, IsWeak,
1424 OrderFail, Size, llvm::AtomicOrdering::Acquire, Scope);
1425 Builder.CreateBr(ContBB);
1426 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::consume),
1427 AcquireBB);
1428 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::acquire),
1429 AcquireBB);
1430 }
1431 if (!IsLoad) {
1432 Builder.SetInsertPoint(ReleaseBB);
1433 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, OriginalVal1, IsWeak,
1434 OrderFail, Size, llvm::AtomicOrdering::Release, Scope);
1435 Builder.CreateBr(ContBB);
1436 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::release),
1437 ReleaseBB);
1438 }
1439 if (!IsLoad && !IsStore) {
1440 Builder.SetInsertPoint(AcqRelBB);
1441 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, OriginalVal1, IsWeak,
1442 OrderFail, Size, llvm::AtomicOrdering::AcquireRelease, Scope);
1443 Builder.CreateBr(ContBB);
1444 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::acq_rel),
1445 AcqRelBB);
1446 }
1447 Builder.SetInsertPoint(SeqCstBB);
1448 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, OriginalVal1, IsWeak, OrderFail,
1449 Size, llvm::AtomicOrdering::SequentiallyConsistent, Scope);
1450 Builder.CreateBr(ContBB);
1451 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::seq_cst),
1452 SeqCstBB);
1453
1454 // Cleanup and return
1455 Builder.SetInsertPoint(ContBB);
1456 if (RValTy->isVoidType())
1457 return RValue::get(nullptr);
1458
1459 assert(Atomics.getValueSizeInBits() <= Atomics.getAtomicSizeInBits());
1461 RValTy, E->getExprLoc());
1462}
1463
1464Address AtomicInfo::castToAtomicIntPointer(Address addr) const {
1465 llvm::IntegerType *ty =
1466 llvm::IntegerType::get(CGF.getLLVMContext(), AtomicSizeInBits);
1467 return addr.withElementType(ty);
1468}
1469
1470Address AtomicInfo::convertToAtomicIntPointer(Address Addr) const {
1471 llvm::Type *Ty = Addr.getElementType();
1472 uint64_t SourceSizeInBits = CGF.CGM.getDataLayout().getTypeSizeInBits(Ty);
1473 if (SourceSizeInBits != AtomicSizeInBits) {
1474 Address Tmp = CreateTempAlloca();
1476 Tmp.emitRawPointer(CGF), llvm::ConstantInt::get(CGF.Int8Ty, 0),
1477 CGF.getContext().toCharUnitsFromBits(AtomicSizeInBits).getQuantity(),
1478 Tmp.getAlignment().getAsAlign());
1479
1480 CGF.Builder.CreateMemCpy(Tmp, Addr,
1481 std::min(AtomicSizeInBits, SourceSizeInBits) / 8);
1482 Addr = Tmp;
1483 }
1484
1485 return castToAtomicIntPointer(Addr);
1486}
1487
1488RValue AtomicInfo::convertAtomicTempToRValue(Address addr,
1489 AggValueSlot resultSlot,
1490 SourceLocation loc,
1491 bool asValue) const {
1492 if (LVal.isSimple()) {
1493 if (EvaluationKind == TEK_Aggregate)
1494 return resultSlot.asRValue();
1495
1496 // Drill into the padding structure if we have one.
1497 if (hasPadding())
1498 addr = CGF.Builder.CreateStructGEP(addr, 0);
1499
1500 // Otherwise, just convert the temporary to an r-value using the
1501 // normal conversion routine.
1502 return CGF.convertTempToRValue(addr, getValueType(), loc);
1503 }
1504 if (!asValue)
1505 // Get RValue from temp memory as atomic for non-simple lvalues
1506 return RValue::get(CGF.Builder.CreateLoad(addr));
1507 if (LVal.isBitField())
1508 return CGF.EmitLoadOfBitfieldLValue(
1509 LValue::MakeBitfield(addr, LVal.getBitFieldInfo(), LVal.getType(),
1510 LVal.getBaseInfo(), TBAAAccessInfo()), loc);
1511 if (LVal.isVectorElt())
1512 return CGF.EmitLoadOfLValue(
1513 LValue::MakeVectorElt(addr, LVal.getVectorIdx(), LVal.getType(),
1514 LVal.getBaseInfo(), TBAAAccessInfo()), loc);
1515 assert(LVal.isExtVectorElt());
1516 return CGF.EmitLoadOfExtVectorElementLValue(LValue::MakeExtVectorElt(
1517 addr, LVal.getExtVectorElts(), LVal.getType(),
1518 LVal.getBaseInfo(), TBAAAccessInfo()));
1519}
1520
1521RValue AtomicInfo::ConvertToValueOrAtomic(llvm::Value *Val,
1522 AggValueSlot ResultSlot,
1523 SourceLocation Loc, bool AsValue,
1524 bool CmpXchg) const {
1525 // Try not to in some easy cases.
1526 assert((Val->getType()->isIntegerTy() || Val->getType()->isPointerTy() ||
1527 Val->getType()->isIEEELikeFPTy()) &&
1528 "Expected integer, pointer or floating point value when converting "
1529 "result.");
1530 if (getEvaluationKind() == TEK_Scalar &&
1531 (((!LVal.isBitField() ||
1532 LVal.getBitFieldInfo().Size == ValueSizeInBits) &&
1533 !hasPadding()) ||
1534 !AsValue)) {
1535 auto *ValTy = AsValue
1536 ? CGF.ConvertTypeForMem(ValueTy)
1537 : getAtomicAddress().getElementType();
1538 if (!shouldCastToInt(ValTy, CmpXchg)) {
1539 assert((!ValTy->isIntegerTy() || Val->getType() == ValTy) &&
1540 "Different integer types.");
1541 return RValue::get(CGF.EmitFromMemory(Val, ValueTy));
1542 }
1543 if (llvm::CastInst::isBitCastable(Val->getType(), ValTy))
1544 return RValue::get(CGF.Builder.CreateBitCast(Val, ValTy));
1545 }
1546
1547 // Create a temporary. This needs to be big enough to hold the
1548 // atomic integer.
1549 Address Temp = Address::invalid();
1550 bool TempIsVolatile = false;
1551 if (AsValue && getEvaluationKind() == TEK_Aggregate) {
1552 assert(!ResultSlot.isIgnored());
1553 Temp = ResultSlot.getAddress();
1554 TempIsVolatile = ResultSlot.isVolatile();
1555 } else {
1556 Temp = CreateTempAlloca();
1557 }
1558
1559 // Slam the integer into the temporary.
1560 Address CastTemp = castToAtomicIntPointer(Temp);
1561 CGF.Builder.CreateStore(Val, CastTemp)->setVolatile(TempIsVolatile);
1562
1563 return convertAtomicTempToRValue(Temp, ResultSlot, Loc, AsValue);
1564}
1565
1566void AtomicInfo::EmitAtomicLoadLibcall(llvm::Value *AddForLoaded,
1567 llvm::AtomicOrdering AO, bool) {
1568 // void __atomic_load(size_t size, void *mem, void *return, int order);
1569 CallArgList Args;
1570 Args.add(RValue::get(getAtomicSizeValue()), CGF.getContext().getSizeType());
1571 Args.add(RValue::get(getAtomicPointer()), CGF.getContext().VoidPtrTy);
1572 Args.add(RValue::get(AddForLoaded), CGF.getContext().VoidPtrTy);
1573 Args.add(
1574 RValue::get(llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(AO))),
1575 CGF.getContext().IntTy);
1576 emitAtomicLibcall(CGF, "__atomic_load", CGF.getContext().VoidTy, Args);
1577}
1578
1579llvm::Value *AtomicInfo::EmitAtomicLoadOp(llvm::AtomicOrdering AO,
1580 bool IsVolatile, bool CmpXchg) {
1581 // Okay, we're doing this natively.
1582 Address Addr = getAtomicAddress();
1583 if (shouldCastToInt(Addr.getElementType(), CmpXchg))
1584 Addr = castToAtomicIntPointer(Addr);
1585 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Addr, "atomic-load");
1586 Load->setAtomic(AO);
1587
1588 // Other decoration.
1589 if (IsVolatile)
1590 Load->setVolatile(true);
1591 CGF.CGM.DecorateInstructionWithTBAA(Load, LVal.getTBAAInfo());
1592 return Load;
1593}
1594
1595/// An LValue is a candidate for having its loads and stores be made atomic if
1596/// we are operating under /volatile:ms *and* the LValue itself is volatile and
1597/// performing such an operation can be performed without a libcall.
1599 if (!CGM.getLangOpts().MSVolatile) return false;
1600 AtomicInfo AI(*this, LV);
1601 bool IsVolatile = LV.isVolatile() || hasVolatileMember(LV.getType());
1602 // An atomic is inline if we don't need to use a libcall.
1603 bool AtomicIsInline = !AI.shouldUseLibcall();
1604 // MSVC doesn't seem to do this for types wider than a pointer.
1605 if (getContext().getTypeSize(LV.getType()) >
1606 getContext().getTypeSize(getContext().getIntPtrType()))
1607 return false;
1608 return IsVolatile && AtomicIsInline;
1609}
1610
1612 AggValueSlot Slot) {
1613 llvm::AtomicOrdering AO;
1614 bool IsVolatile = LV.isVolatileQualified();
1615 if (LV.getType()->isAtomicType()) {
1616 AO = llvm::AtomicOrdering::SequentiallyConsistent;
1617 } else {
1618 AO = llvm::AtomicOrdering::Acquire;
1619 IsVolatile = true;
1620 }
1621 return EmitAtomicLoad(LV, SL, AO, IsVolatile, Slot);
1622}
1623
1624RValue AtomicInfo::EmitAtomicLoad(AggValueSlot ResultSlot, SourceLocation Loc,
1625 bool AsValue, llvm::AtomicOrdering AO,
1626 bool IsVolatile) {
1627 // Check whether we should use a library call.
1628 if (shouldUseLibcall()) {
1629 Address TempAddr = Address::invalid();
1630 if (LVal.isSimple() && !ResultSlot.isIgnored()) {
1631 assert(getEvaluationKind() == TEK_Aggregate);
1632 TempAddr = ResultSlot.getAddress();
1633 } else
1634 TempAddr = CreateTempAlloca();
1635
1636 EmitAtomicLoadLibcall(TempAddr.emitRawPointer(CGF), AO, IsVolatile);
1637
1638 // Okay, turn that back into the original value or whole atomic (for
1639 // non-simple lvalues) type.
1640 return convertAtomicTempToRValue(TempAddr, ResultSlot, Loc, AsValue);
1641 }
1642
1643 // Okay, we're doing this natively.
1644 auto *Load = EmitAtomicLoadOp(AO, IsVolatile);
1645
1646 // If we're ignoring an aggregate return, don't do anything.
1647 if (getEvaluationKind() == TEK_Aggregate && ResultSlot.isIgnored())
1648 return RValue::getAggregate(Address::invalid(), false);
1649
1650 // Okay, turn that back into the original value or atomic (for non-simple
1651 // lvalues) type.
1652 return ConvertToValueOrAtomic(Load, ResultSlot, Loc, AsValue);
1653}
1654
1655/// Emit a load from an l-value of atomic type. Note that the r-value
1656/// we produce is an r-value of the atomic *value* type.
1658 llvm::AtomicOrdering AO, bool IsVolatile,
1659 AggValueSlot resultSlot) {
1660 AtomicInfo Atomics(*this, src);
1661 return Atomics.EmitAtomicLoad(resultSlot, loc, /*AsValue=*/true, AO,
1662 IsVolatile);
1663}
1664
1665/// Copy an r-value into memory as part of storing to an atomic type.
1666/// This needs to create a bit-pattern suitable for atomic operations.
1667void AtomicInfo::emitCopyIntoMemory(RValue rvalue) const {
1668 assert(LVal.isSimple());
1669 // If we have an r-value, the rvalue should be of the atomic type,
1670 // which means that the caller is responsible for having zeroed
1671 // any padding. Just do an aggregate copy of that type.
1672 if (rvalue.isAggregate()) {
1673 LValue Dest = CGF.MakeAddrLValue(getAtomicAddress(), getAtomicType());
1674 LValue Src = CGF.MakeAddrLValue(rvalue.getAggregateAddress(),
1675 getAtomicType());
1676 bool IsVolatile = rvalue.isVolatileQualified() ||
1677 LVal.isVolatileQualified();
1678 CGF.EmitAggregateCopy(Dest, Src, getAtomicType(),
1679 AggValueSlot::DoesNotOverlap, IsVolatile);
1680 return;
1681 }
1682
1683 // Okay, otherwise we're copying stuff.
1684
1685 // Zero out the buffer if necessary.
1686 emitMemSetZeroIfNecessary();
1687
1688 // Drill past the padding if present.
1689 LValue TempLVal = projectValue();
1690
1691 // Okay, store the rvalue in.
1692 if (rvalue.isScalar()) {
1693 CGF.EmitStoreOfScalar(rvalue.getScalarVal(), TempLVal, /*init*/ true);
1694 } else {
1695 CGF.EmitStoreOfComplex(rvalue.getComplexVal(), TempLVal, /*init*/ true);
1696 }
1697}
1698
1699
1700/// Materialize an r-value into memory for the purposes of storing it
1701/// to an atomic type.
1702Address AtomicInfo::materializeRValue(RValue rvalue) const {
1703 // Aggregate r-values are already in memory, and EmitAtomicStore
1704 // requires them to be values of the atomic type.
1705 if (rvalue.isAggregate())
1706 return rvalue.getAggregateAddress();
1707
1708 // Otherwise, make a temporary and materialize into it.
1709 LValue TempLV = CGF.MakeAddrLValue(CreateTempAlloca(), getAtomicType());
1710 AtomicInfo Atomics(CGF, TempLV);
1711 Atomics.emitCopyIntoMemory(rvalue);
1712 return TempLV.getAddress();
1713}
1714
1715llvm::Value *AtomicInfo::getScalarRValValueOrNull(RValue RVal) const {
1716 if (RVal.isScalar() && (!hasPadding() || !LVal.isSimple()))
1717 return RVal.getScalarVal();
1718 return nullptr;
1719}
1720
1721llvm::Value *AtomicInfo::convertRValueToInt(RValue RVal, bool CmpXchg) const {
1722 // If we've got a scalar value of the right size, try to avoid going
1723 // through memory. Floats get casted if needed by AtomicExpandPass.
1724 if (llvm::Value *Value = getScalarRValValueOrNull(RVal)) {
1725 if (!shouldCastToInt(Value->getType(), CmpXchg))
1726 return CGF.EmitToMemory(Value, ValueTy);
1727 else {
1728 llvm::IntegerType *InputIntTy = llvm::IntegerType::get(
1729 CGF.getLLVMContext(),
1730 LVal.isSimple() ? getValueSizeInBits() : getAtomicSizeInBits());
1731 if (llvm::BitCastInst::isBitCastable(Value->getType(), InputIntTy))
1732 return CGF.Builder.CreateBitCast(Value, InputIntTy);
1733 }
1734 }
1735 // Otherwise, we need to go through memory.
1736 // Put the r-value in memory.
1737 Address Addr = materializeRValue(RVal);
1738
1739 // Cast the temporary to the atomic int type and pull a value out.
1740 Addr = castToAtomicIntPointer(Addr);
1741 return CGF.Builder.CreateLoad(Addr);
1742}
1743
1744std::pair<llvm::Value *, llvm::Value *> AtomicInfo::EmitAtomicCompareExchangeOp(
1745 llvm::Value *ExpectedVal, llvm::Value *DesiredVal,
1746 llvm::AtomicOrdering Success, llvm::AtomicOrdering Failure, bool IsWeak) {
1747 // Do the atomic store.
1748 Address Addr = getAtomicAddressAsAtomicIntPointer();
1749 auto *Inst = CGF.Builder.CreateAtomicCmpXchg(Addr, ExpectedVal, DesiredVal,
1750 Success, Failure);
1751 // Other decoration.
1752 Inst->setVolatile(LVal.isVolatileQualified());
1753 Inst->setWeak(IsWeak);
1754
1755 // Okay, turn that back into the original value type.
1756 auto *PreviousVal = CGF.Builder.CreateExtractValue(Inst, /*Idxs=*/0);
1757 auto *SuccessFailureVal = CGF.Builder.CreateExtractValue(Inst, /*Idxs=*/1);
1758 return std::make_pair(PreviousVal, SuccessFailureVal);
1759}
1760
1761llvm::Value *
1762AtomicInfo::EmitAtomicCompareExchangeLibcall(llvm::Value *ExpectedAddr,
1763 llvm::Value *DesiredAddr,
1764 llvm::AtomicOrdering Success,
1765 llvm::AtomicOrdering Failure) {
1766 // bool __atomic_compare_exchange(size_t size, void *obj, void *expected,
1767 // void *desired, int success, int failure);
1768 CallArgList Args;
1769 Args.add(RValue::get(getAtomicSizeValue()), CGF.getContext().getSizeType());
1770 Args.add(RValue::get(getAtomicPointer()), CGF.getContext().VoidPtrTy);
1771 Args.add(RValue::get(ExpectedAddr), CGF.getContext().VoidPtrTy);
1772 Args.add(RValue::get(DesiredAddr), CGF.getContext().VoidPtrTy);
1773 Args.add(RValue::get(
1774 llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(Success))),
1775 CGF.getContext().IntTy);
1776 Args.add(RValue::get(
1777 llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(Failure))),
1778 CGF.getContext().IntTy);
1779 auto SuccessFailureRVal = emitAtomicLibcall(CGF, "__atomic_compare_exchange",
1780 CGF.getContext().BoolTy, Args);
1781
1782 return SuccessFailureRVal.getScalarVal();
1783}
1784
1785std::pair<RValue, llvm::Value *> AtomicInfo::EmitAtomicCompareExchange(
1786 RValue Expected, RValue Desired, llvm::AtomicOrdering Success,
1787 llvm::AtomicOrdering Failure, bool IsWeak) {
1788 // Check whether we should use a library call.
1789 if (shouldUseLibcall()) {
1790 // Produce a source address.
1791 Address ExpectedAddr = materializeRValue(Expected);
1792 llvm::Value *ExpectedPtr = ExpectedAddr.emitRawPointer(CGF);
1793 llvm::Value *DesiredPtr = materializeRValue(Desired).emitRawPointer(CGF);
1794 auto *Res = EmitAtomicCompareExchangeLibcall(ExpectedPtr, DesiredPtr,
1795 Success, Failure);
1796 return std::make_pair(
1797 convertAtomicTempToRValue(ExpectedAddr, AggValueSlot::ignored(),
1798 SourceLocation(), /*AsValue=*/false),
1799 Res);
1800 }
1801
1802 // If we've got a scalar value of the right size, try to avoid going
1803 // through memory.
1804 auto *ExpectedVal = convertRValueToInt(Expected, /*CmpXchg=*/true);
1805 auto *DesiredVal = convertRValueToInt(Desired, /*CmpXchg=*/true);
1806 auto Res = EmitAtomicCompareExchangeOp(ExpectedVal, DesiredVal, Success,
1807 Failure, IsWeak);
1808 return std::make_pair(
1809 ConvertToValueOrAtomic(Res.first, AggValueSlot::ignored(),
1810 SourceLocation(), /*AsValue=*/false,
1811 /*CmpXchg=*/true),
1812 Res.second);
1813}
1814
1815static void
1816EmitAtomicUpdateValue(CodeGenFunction &CGF, AtomicInfo &Atomics, RValue OldRVal,
1817 const llvm::function_ref<RValue(RValue)> &UpdateOp,
1818 Address DesiredAddr) {
1819 RValue UpRVal;
1820 LValue AtomicLVal = Atomics.getAtomicLValue();
1821 LValue DesiredLVal;
1822 if (AtomicLVal.isSimple()) {
1823 UpRVal = OldRVal;
1824 DesiredLVal = CGF.MakeAddrLValue(DesiredAddr, AtomicLVal.getType());
1825 } else {
1826 // Build new lvalue for temp address.
1827 Address Ptr = Atomics.materializeRValue(OldRVal);
1828 LValue UpdateLVal;
1829 if (AtomicLVal.isBitField()) {
1830 UpdateLVal =
1831 LValue::MakeBitfield(Ptr, AtomicLVal.getBitFieldInfo(),
1832 AtomicLVal.getType(),
1833 AtomicLVal.getBaseInfo(),
1834 AtomicLVal.getTBAAInfo());
1835 DesiredLVal =
1836 LValue::MakeBitfield(DesiredAddr, AtomicLVal.getBitFieldInfo(),
1837 AtomicLVal.getType(), AtomicLVal.getBaseInfo(),
1838 AtomicLVal.getTBAAInfo());
1839 } else if (AtomicLVal.isVectorElt()) {
1840 UpdateLVal = LValue::MakeVectorElt(Ptr, AtomicLVal.getVectorIdx(),
1841 AtomicLVal.getType(),
1842 AtomicLVal.getBaseInfo(),
1843 AtomicLVal.getTBAAInfo());
1844 DesiredLVal = LValue::MakeVectorElt(
1845 DesiredAddr, AtomicLVal.getVectorIdx(), AtomicLVal.getType(),
1846 AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
1847 } else {
1848 assert(AtomicLVal.isExtVectorElt());
1849 UpdateLVal = LValue::MakeExtVectorElt(Ptr, AtomicLVal.getExtVectorElts(),
1850 AtomicLVal.getType(),
1851 AtomicLVal.getBaseInfo(),
1852 AtomicLVal.getTBAAInfo());
1853 DesiredLVal = LValue::MakeExtVectorElt(
1854 DesiredAddr, AtomicLVal.getExtVectorElts(), AtomicLVal.getType(),
1855 AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
1856 }
1857 UpRVal = CGF.EmitLoadOfLValue(UpdateLVal, SourceLocation());
1858 }
1859 // Store new value in the corresponding memory area.
1860 RValue NewRVal = UpdateOp(UpRVal);
1861 if (NewRVal.isScalar()) {
1862 CGF.EmitStoreThroughLValue(NewRVal, DesiredLVal);
1863 } else {
1864 assert(NewRVal.isComplex());
1865 CGF.EmitStoreOfComplex(NewRVal.getComplexVal(), DesiredLVal,
1866 /*isInit=*/false);
1867 }
1868}
1869
1870void AtomicInfo::EmitAtomicUpdateLibcall(
1871 llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1872 bool IsVolatile) {
1873 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1874
1875 Address ExpectedAddr = CreateTempAlloca();
1876
1877 EmitAtomicLoadLibcall(ExpectedAddr.emitRawPointer(CGF), AO, IsVolatile);
1878 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1879 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1880 CGF.EmitBlock(ContBB);
1881 Address DesiredAddr = CreateTempAlloca();
1882 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
1883 requiresMemSetZero(getAtomicAddress().getElementType())) {
1884 auto *OldVal = CGF.Builder.CreateLoad(ExpectedAddr);
1885 CGF.Builder.CreateStore(OldVal, DesiredAddr);
1886 }
1887 auto OldRVal = convertAtomicTempToRValue(ExpectedAddr,
1889 SourceLocation(), /*AsValue=*/false);
1890 EmitAtomicUpdateValue(CGF, *this, OldRVal, UpdateOp, DesiredAddr);
1891 llvm::Value *ExpectedPtr = ExpectedAddr.emitRawPointer(CGF);
1892 llvm::Value *DesiredPtr = DesiredAddr.emitRawPointer(CGF);
1893 auto *Res =
1894 EmitAtomicCompareExchangeLibcall(ExpectedPtr, DesiredPtr, AO, Failure);
1895 CGF.Builder.CreateCondBr(Res, ExitBB, ContBB);
1896 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1897}
1898
1899void AtomicInfo::EmitAtomicUpdateOp(
1900 llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1901 bool IsVolatile) {
1902 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1903
1904 // Do the atomic load.
1905 auto *OldVal = EmitAtomicLoadOp(Failure, IsVolatile, /*CmpXchg=*/true);
1906 // For non-simple lvalues perform compare-and-swap procedure.
1907 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1908 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1909 auto *CurBB = CGF.Builder.GetInsertBlock();
1910 CGF.EmitBlock(ContBB);
1911 llvm::PHINode *PHI = CGF.Builder.CreatePHI(OldVal->getType(),
1912 /*NumReservedValues=*/2);
1913 PHI->addIncoming(OldVal, CurBB);
1914 Address NewAtomicAddr = CreateTempAlloca();
1915 Address NewAtomicIntAddr =
1916 shouldCastToInt(NewAtomicAddr.getElementType(), /*CmpXchg=*/true)
1917 ? castToAtomicIntPointer(NewAtomicAddr)
1918 : NewAtomicAddr;
1919
1920 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
1921 requiresMemSetZero(getAtomicAddress().getElementType())) {
1922 CGF.Builder.CreateStore(PHI, NewAtomicIntAddr);
1923 }
1924 auto OldRVal = ConvertToValueOrAtomic(PHI, AggValueSlot::ignored(),
1925 SourceLocation(), /*AsValue=*/false,
1926 /*CmpXchg=*/true);
1927 EmitAtomicUpdateValue(CGF, *this, OldRVal, UpdateOp, NewAtomicAddr);
1928 auto *DesiredVal = CGF.Builder.CreateLoad(NewAtomicIntAddr);
1929 // Try to write new value using cmpxchg operation.
1930 auto Res = EmitAtomicCompareExchangeOp(PHI, DesiredVal, AO, Failure);
1931 PHI->addIncoming(Res.first, CGF.Builder.GetInsertBlock());
1932 CGF.Builder.CreateCondBr(Res.second, ExitBB, ContBB);
1933 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1934}
1935
1936static void EmitAtomicUpdateValue(CodeGenFunction &CGF, AtomicInfo &Atomics,
1937 RValue UpdateRVal, Address DesiredAddr) {
1938 LValue AtomicLVal = Atomics.getAtomicLValue();
1939 LValue DesiredLVal;
1940 // Build new lvalue for temp address.
1941 if (AtomicLVal.isBitField()) {
1942 DesiredLVal =
1943 LValue::MakeBitfield(DesiredAddr, AtomicLVal.getBitFieldInfo(),
1944 AtomicLVal.getType(), AtomicLVal.getBaseInfo(),
1945 AtomicLVal.getTBAAInfo());
1946 } else if (AtomicLVal.isVectorElt()) {
1947 DesiredLVal =
1948 LValue::MakeVectorElt(DesiredAddr, AtomicLVal.getVectorIdx(),
1949 AtomicLVal.getType(), AtomicLVal.getBaseInfo(),
1950 AtomicLVal.getTBAAInfo());
1951 } else {
1952 assert(AtomicLVal.isExtVectorElt());
1953 DesiredLVal = LValue::MakeExtVectorElt(
1954 DesiredAddr, AtomicLVal.getExtVectorElts(), AtomicLVal.getType(),
1955 AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
1956 }
1957 // Store new value in the corresponding memory area.
1958 assert(UpdateRVal.isScalar());
1959 CGF.EmitStoreThroughLValue(UpdateRVal, DesiredLVal);
1960}
1961
1962void AtomicInfo::EmitAtomicUpdateLibcall(llvm::AtomicOrdering AO,
1963 RValue UpdateRVal, bool IsVolatile) {
1964 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1965
1966 Address ExpectedAddr = CreateTempAlloca();
1967
1968 EmitAtomicLoadLibcall(ExpectedAddr.emitRawPointer(CGF), AO, IsVolatile);
1969 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1970 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1971 CGF.EmitBlock(ContBB);
1972 Address DesiredAddr = CreateTempAlloca();
1973 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
1974 requiresMemSetZero(getAtomicAddress().getElementType())) {
1975 auto *OldVal = CGF.Builder.CreateLoad(ExpectedAddr);
1976 CGF.Builder.CreateStore(OldVal, DesiredAddr);
1977 }
1978 EmitAtomicUpdateValue(CGF, *this, UpdateRVal, DesiredAddr);
1979 llvm::Value *ExpectedPtr = ExpectedAddr.emitRawPointer(CGF);
1980 llvm::Value *DesiredPtr = DesiredAddr.emitRawPointer(CGF);
1981 auto *Res =
1982 EmitAtomicCompareExchangeLibcall(ExpectedPtr, DesiredPtr, AO, Failure);
1983 CGF.Builder.CreateCondBr(Res, ExitBB, ContBB);
1984 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1985}
1986
1987void AtomicInfo::EmitAtomicUpdateOp(llvm::AtomicOrdering AO, RValue UpdateRVal,
1988 bool IsVolatile) {
1989 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1990
1991 // Do the atomic load.
1992 auto *OldVal = EmitAtomicLoadOp(Failure, IsVolatile, /*CmpXchg=*/true);
1993 // For non-simple lvalues perform compare-and-swap procedure.
1994 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1995 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1996 auto *CurBB = CGF.Builder.GetInsertBlock();
1997 CGF.EmitBlock(ContBB);
1998 llvm::PHINode *PHI = CGF.Builder.CreatePHI(OldVal->getType(),
1999 /*NumReservedValues=*/2);
2000 PHI->addIncoming(OldVal, CurBB);
2001 Address NewAtomicAddr = CreateTempAlloca();
2002 Address NewAtomicIntAddr = castToAtomicIntPointer(NewAtomicAddr);
2003 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
2004 requiresMemSetZero(getAtomicAddress().getElementType())) {
2005 CGF.Builder.CreateStore(PHI, NewAtomicIntAddr);
2006 }
2007 EmitAtomicUpdateValue(CGF, *this, UpdateRVal, NewAtomicAddr);
2008 auto *DesiredVal = CGF.Builder.CreateLoad(NewAtomicIntAddr);
2009 // Try to write new value using cmpxchg operation.
2010 auto Res = EmitAtomicCompareExchangeOp(PHI, DesiredVal, AO, Failure);
2011 PHI->addIncoming(Res.first, CGF.Builder.GetInsertBlock());
2012 CGF.Builder.CreateCondBr(Res.second, ExitBB, ContBB);
2013 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
2014}
2015
2016void AtomicInfo::EmitAtomicUpdate(
2017 llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
2018 bool IsVolatile) {
2019 if (shouldUseLibcall()) {
2020 EmitAtomicUpdateLibcall(AO, UpdateOp, IsVolatile);
2021 } else {
2022 EmitAtomicUpdateOp(AO, UpdateOp, IsVolatile);
2023 }
2024}
2025
2026void AtomicInfo::EmitAtomicUpdate(llvm::AtomicOrdering AO, RValue UpdateRVal,
2027 bool IsVolatile) {
2028 if (shouldUseLibcall()) {
2029 EmitAtomicUpdateLibcall(AO, UpdateRVal, IsVolatile);
2030 } else {
2031 EmitAtomicUpdateOp(AO, UpdateRVal, IsVolatile);
2032 }
2033}
2034
2036 bool isInit) {
2037 bool IsVolatile = lvalue.isVolatileQualified();
2038 llvm::AtomicOrdering AO;
2039 if (lvalue.getType()->isAtomicType()) {
2040 AO = llvm::AtomicOrdering::SequentiallyConsistent;
2041 } else {
2042 AO = llvm::AtomicOrdering::Release;
2043 IsVolatile = true;
2044 }
2045 return EmitAtomicStore(rvalue, lvalue, AO, IsVolatile, isInit);
2046}
2047
2048/// Emit a store to an l-value of atomic type.
2049///
2050/// Note that the r-value is expected to be an r-value *of the atomic
2051/// type*; this means that for aggregate r-values, it should include
2052/// storage for any padding that was necessary.
2054 llvm::AtomicOrdering AO, bool IsVolatile,
2055 bool isInit) {
2056 // If this is an aggregate r-value, it should agree in type except
2057 // maybe for address-space qualification.
2058 assert(!rvalue.isAggregate() ||
2060 dest.getAddress().getElementType());
2061
2062 AtomicInfo atomics(*this, dest);
2063 LValue LVal = atomics.getAtomicLValue();
2064
2065 // If this is an initialization, just put the value there normally.
2066 if (LVal.isSimple()) {
2067 if (isInit) {
2068 atomics.emitCopyIntoMemory(rvalue);
2069 return;
2070 }
2071
2072 // Check whether we should use a library call.
2073 if (atomics.shouldUseLibcall()) {
2074 // Produce a source address.
2075 Address srcAddr = atomics.materializeRValue(rvalue);
2076
2077 // void __atomic_store(size_t size, void *mem, void *val, int order)
2078 CallArgList args;
2079 args.add(RValue::get(atomics.getAtomicSizeValue()),
2080 getContext().getSizeType());
2081 args.add(RValue::get(atomics.getAtomicPointer()), getContext().VoidPtrTy);
2082 args.add(RValue::get(srcAddr.emitRawPointer(*this)),
2084 args.add(
2085 RValue::get(llvm::ConstantInt::get(IntTy, (int)llvm::toCABI(AO))),
2086 getContext().IntTy);
2087 emitAtomicLibcall(*this, "__atomic_store", getContext().VoidTy, args);
2088 return;
2089 }
2090
2091 // Okay, we're doing this natively.
2092 llvm::Value *ValToStore = atomics.convertRValueToInt(rvalue);
2093
2094 // Do the atomic store.
2095 Address Addr = atomics.getAtomicAddress();
2096 if (llvm::Value *Value = atomics.getScalarRValValueOrNull(rvalue))
2097 if (shouldCastToInt(Value->getType(), /*CmpXchg=*/false)) {
2098 Addr = atomics.castToAtomicIntPointer(Addr);
2099 ValToStore = Builder.CreateIntCast(ValToStore, Addr.getElementType(),
2100 /*isSigned=*/false);
2101 }
2102 llvm::StoreInst *store = Builder.CreateStore(ValToStore, Addr);
2103
2104 if (AO == llvm::AtomicOrdering::Acquire)
2105 AO = llvm::AtomicOrdering::Monotonic;
2106 else if (AO == llvm::AtomicOrdering::AcquireRelease)
2107 AO = llvm::AtomicOrdering::Release;
2108 // Initializations don't need to be atomic.
2109 if (!isInit)
2110 store->setAtomic(AO);
2111
2112 // Other decoration.
2113 if (IsVolatile)
2114 store->setVolatile(true);
2115 CGM.DecorateInstructionWithTBAA(store, dest.getTBAAInfo());
2116 return;
2117 }
2118
2119 // Emit simple atomic update operation.
2120 atomics.EmitAtomicUpdate(AO, rvalue, IsVolatile);
2121}
2122
2123/// Emit a compare-and-exchange op for atomic type.
2124///
2125std::pair<RValue, llvm::Value *> CodeGenFunction::EmitAtomicCompareExchange(
2126 LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
2127 llvm::AtomicOrdering Success, llvm::AtomicOrdering Failure, bool IsWeak,
2128 AggValueSlot Slot) {
2129 // If this is an aggregate r-value, it should agree in type except
2130 // maybe for address-space qualification.
2131 assert(!Expected.isAggregate() ||
2132 Expected.getAggregateAddress().getElementType() ==
2133 Obj.getAddress().getElementType());
2134 assert(!Desired.isAggregate() ||
2135 Desired.getAggregateAddress().getElementType() ==
2136 Obj.getAddress().getElementType());
2137 AtomicInfo Atomics(*this, Obj);
2138
2139 return Atomics.EmitAtomicCompareExchange(Expected, Desired, Success, Failure,
2140 IsWeak);
2141}
2142
2143llvm::AtomicRMWInst *
2144CodeGenFunction::emitAtomicRMWInst(llvm::AtomicRMWInst::BinOp Op, Address Addr,
2145 llvm::Value *Val, llvm::AtomicOrdering Order,
2146 llvm::SyncScope::ID SSID,
2147 const AtomicExpr *AE) {
2148 llvm::AtomicRMWInst *RMW =
2149 Builder.CreateAtomicRMW(Op, Addr, Val, Order, SSID);
2150 getTargetHooks().setTargetAtomicMetadata(*this, *RMW, AE);
2151 return RMW;
2152}
2153
2155 LValue LVal, llvm::AtomicOrdering AO,
2156 const llvm::function_ref<RValue(RValue)> &UpdateOp, bool IsVolatile) {
2157 AtomicInfo Atomics(*this, LVal);
2158 Atomics.EmitAtomicUpdate(AO, UpdateOp, IsVolatile);
2159}
2160
2162 AtomicInfo atomics(*this, dest);
2163
2164 switch (atomics.getEvaluationKind()) {
2165 case TEK_Scalar: {
2166 llvm::Value *value = EmitScalarExpr(init);
2167 atomics.emitCopyIntoMemory(RValue::get(value));
2168 return;
2169 }
2170
2171 case TEK_Complex: {
2172 ComplexPairTy value = EmitComplexExpr(init);
2173 atomics.emitCopyIntoMemory(RValue::getComplex(value));
2174 return;
2175 }
2176
2177 case TEK_Aggregate: {
2178 // Fix up the destination if the initializer isn't an expression
2179 // of atomic type.
2180 bool Zeroed = false;
2181 if (!init->getType()->isAtomicType()) {
2182 Zeroed = atomics.emitMemSetZeroIfNecessary();
2183 dest = atomics.projectValue();
2184 }
2185
2186 // Evaluate the expression directly into the destination.
2192
2193 EmitAggExpr(init, slot);
2194 return;
2195 }
2196 }
2197 llvm_unreachable("bad evaluation kind");
2198}
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:525
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:826
static RValue emitAtomicLibcall(CodeGenFunction &CGF, StringRef fnName, QualType resultType, CallArgList &args)
Definition CGAtomic.cpp:314
static void EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *E, Address Dest, Address Ptr, Address Val1, Address Val2, Address ExpectedResult, llvm::Value *IsWeak, llvm::Value *FailureOrder, uint64_t Size, llvm::AtomicOrdering Order, llvm::SyncScope::ID Scope)
Definition CGAtomic.cpp:559
static Address EmitPointerWithAlignment(const Expr *E, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo, KnownNonNull_t IsKnownNonNull, CodeGenFunction &CGF)
Definition CGExpr.cpp:1452
static bool shouldCastToInt(mlir::Type valueTy, bool cmpxchg)
Return true if.
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, cir::SyncScopeKind scope)
static bool isFullSizeType(CIRGenModule &cgm, mlir::Type ty, uint64_t expectedSize)
Does a store of the given IR type modify the full expected width?
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, cir::SyncScopeKind scope)
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:6927
static std::unique_ptr< AtomicScopeModel > getScopeModel(AtomicOp Op)
Get atomic scope model for the atomic op code.
Definition Expr.h:7076
Expr * getVal2() const
Definition Expr.h:6978
Expr * getOrder() const
Definition Expr.h:6961
QualType getValueType() const
Definition Expr.cpp:5359
Expr * getScope() const
Definition Expr.h:6964
bool isCmpXChg() const
Definition Expr.h:7011
AtomicOp getOp() const
Definition Expr.h:6990
bool isOpenCL() const
Definition Expr.h:7039
Expr * getVal1() const
Definition Expr.h:6968
Expr * getPtr() const
Definition Expr.h:6958
Expr * getWeak() const
Definition Expr.h:6984
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:7058
Expr * getOrderFail() const
Definition Expr.h:6974
bool isVolatile() const
Definition Expr.h:7007
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
Definition CharUnits.h:189
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
bool isMultipleOf(CharUnits N) const
Test whether this is a multiple of the other value.
Definition CharUnits.h:143
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:551
static AggValueSlot ignored()
ignored - Returns an aggregate value slot indicating that the aggregate value is being ignored.
Definition CGValue.h:619
Address getAddress() const
Definition CGValue.h:691
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:649
RValue asRValue() const
Definition CGValue.h:713
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:146
Address CreatePointerBitCastOrAddrSpaceCast(Address Addr, llvm::Type *Ty, llvm::Type *ElementTy, const llvm::Twine &Name="")
Definition CGBuilder.h:213
llvm::CallInst * CreateMemSet(Address Dest, llvm::Value *Value, llvm::Value *Size, bool IsVolatile=false)
Definition CGBuilder.h:408
Address CreateStructGEP(Address Addr, unsigned Index, const llvm::Twine &Name="")
Definition CGBuilder.h:229
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:179
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition CGBuilder.h:118
llvm::CallInst * CreateMemCpy(Address Dest, Address Src, llvm::Value *Size, bool IsVolatile=false)
Definition CGBuilder.h:375
Address CreateAddrSpaceCast(Address Addr, llvm::Type *Ty, llvm::Type *ElementTy, const llvm::Twine &Name="")
Definition CGBuilder.h:199
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...
llvm::Value * performAddrSpaceCast(llvm::Value *Src, llvm::Type *DestTy)
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:7141
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:2082
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:2497
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:2223
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates an alloca and inserts it into the entry block if ArraySize is nullptr...
Definition CGExpr.cpp:153
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:5342
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:2738
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:302
llvm::Type * ConvertTypeForMem(QualType T)
RValue EmitLoadOfBitfieldLValue(LValue LV, SourceLocation Loc)
Definition CGExpr.cpp:2612
RValue EmitAtomicExpr(AtomicExpr *E)
Definition CGAtomic.cpp:912
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:189
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:2649
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:2257
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:640
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:1801
const CGFunctionInfo & arrangeBuiltinFunctionCall(QualType resultType, const CallArgList &args)
Definition CGCall.cpp:731
LValue - This represents an lvalue references.
Definition CGValue.h:183
bool isSimple() const
Definition CGValue.h:286
bool isVolatileQualified() const
Definition CGValue.h:297
bool isVolatile() const
Definition CGValue.h:340
Address getAddress() const
Definition CGValue.h:373
QualType getType() const
Definition CGValue.h:303
TBAAAccessInfo getTBAAInfo() const
Definition CGValue.h:347
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:99
static RValue getAggregate(Address addr, bool isVolatile=false)
Convert an Address to an RValue.
Definition CGValue.h:126
static RValue getComplex(llvm::Value *V1, llvm::Value *V2)
Definition CGValue.h:109
bool isAggregate() const
Definition CGValue.h:66
Address getAggregateAddress() const
getAggregateAddr() - Return the Value* of the address of the aggregate.
Definition CGValue.h:84
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition CGValue.h:72
bool isComplex() const
Definition CGValue.h:65
bool isVolatileQualified() const
Definition CGValue.h:69
std::pair< llvm::Value *, llvm::Value * > getComplexVal() const
getComplexVal - Return the real/imag components of this complex value.
Definition CGValue.h:79
ReturnValueSlot - Contains the address where the return value of a function can be stored,...
Definition CGCall.h:379
llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts, SyncScope Scope, llvm::AtomicOrdering Ordering, llvm::LLVMContext &Ctx) const
Get the syncscope used in LLVM IR as a SyncScope ID.
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:341
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:232
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:277
QualType getType() const
Definition Expr.h:144
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3336
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:8514
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8428
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8482
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:8991
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2230
bool isPointerType() const
Definition TypeBase.h:8625
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9285
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:753
bool isAtomicType() const
Definition TypeBase.h:8817
bool isFloatingType() const
Definition Type.cpp:2341
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9218
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:1986
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::Expected< QualType > ExpectedType
llvm::StringRef getAsString(SyncScope S)
Definition SyncScope.h:62
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