clang 23.0.0git
CIRGenAtomic.cpp
Go to the documentation of this file.
1//===--- CIRGenAtomic.cpp - Emit CIR 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 "CIRGenFunction.h"
15
16using namespace clang;
17using namespace clang::CIRGen;
18using namespace cir;
19
20namespace {
21class AtomicInfo {
22 CIRGenFunction &cgf;
23 QualType atomicTy;
24 QualType valueTy;
25 uint64_t atomicSizeInBits = 0;
26 uint64_t valueSizeInBits = 0;
27 CharUnits atomicAlign;
28 CharUnits valueAlign;
29 TypeEvaluationKind evaluationKind = cir::TEK_Scalar;
30 bool useLibCall = true;
31 LValue lvalue;
32 mlir::Location loc;
33
34public:
35 AtomicInfo(CIRGenFunction &cgf, LValue &lvalue, mlir::Location loc)
36 : cgf(cgf), loc(loc) {
37 assert(!lvalue.isGlobalReg());
38 ASTContext &ctx = cgf.getContext();
39 if (lvalue.isSimple()) {
40 atomicTy = lvalue.getType();
41 if (auto *ty = atomicTy->getAs<AtomicType>())
42 valueTy = ty->getValueType();
43 else
44 valueTy = atomicTy;
45 evaluationKind = cgf.getEvaluationKind(valueTy);
46
47 TypeInfo valueTypeInfo = ctx.getTypeInfo(valueTy);
48 TypeInfo atomicTypeInfo = ctx.getTypeInfo(atomicTy);
49 uint64_t valueAlignInBits = valueTypeInfo.Align;
50 uint64_t atomicAlignInBits = atomicTypeInfo.Align;
51 valueSizeInBits = valueTypeInfo.Width;
52 atomicSizeInBits = atomicTypeInfo.Width;
53 assert(valueSizeInBits <= atomicSizeInBits);
54 assert(valueAlignInBits <= atomicAlignInBits);
55
56 atomicAlign = ctx.toCharUnitsFromBits(atomicAlignInBits);
57 valueAlign = ctx.toCharUnitsFromBits(valueAlignInBits);
58 if (lvalue.getAlignment().isZero())
59 lvalue.setAlignment(atomicAlign);
60
61 this->lvalue = lvalue;
62 } else {
64 cgf.cgm.errorNYI(loc, "AtomicInfo: non-simple lvalue");
65 }
66 useLibCall = !ctx.getTargetInfo().hasBuiltinAtomic(
67 atomicSizeInBits, ctx.toBits(lvalue.getAlignment()));
68 }
69
70 QualType getValueType() const { return valueTy; }
71 CharUnits getAtomicAlignment() const { return atomicAlign; }
72 TypeEvaluationKind getEvaluationKind() const { return evaluationKind; }
73 mlir::Value getAtomicPointer() const {
74 if (lvalue.isSimple())
75 return lvalue.getPointer();
77 return nullptr;
78 }
79 bool shouldUseLibCall() const { return useLibCall; }
80 const LValue &getAtomicLValue() const { return lvalue; }
81 Address getAtomicAddress() const {
82 mlir::Type elemTy;
83 if (lvalue.isSimple()) {
84 elemTy = lvalue.getAddress().getElementType();
85 } else {
87 cgf.cgm.errorNYI(loc, "AtomicInfo::getAtomicAddress: non-simple lvalue");
88 }
89 return Address(getAtomicPointer(), elemTy, getAtomicAlignment());
90 }
91
92 /// Is the atomic size larger than the underlying value type?
93 ///
94 /// Note that the absence of padding does not mean that atomic
95 /// objects are completely interchangeable with non-atomic
96 /// objects: we might have promoted the alignment of a type
97 /// without making it bigger.
98 bool hasPadding() const { return (valueSizeInBits != atomicSizeInBits); }
99
100 bool emitMemSetZeroIfNecessary() const;
101
102 mlir::Value getScalarRValValueOrNull(RValue rvalue) const;
103
104 /// Cast the given pointer to an integer pointer suitable for atomic
105 /// operations on the source.
106 Address castToAtomicIntPointer(Address addr) const;
107
108 /// If addr is compatible with the iN that will be used for an atomic
109 /// operation, bitcast it. Otherwise, create a temporary that is suitable and
110 /// copy the value across.
111 Address convertToAtomicIntPointer(Address addr) const;
112
113 /// Converts a rvalue to integer value.
114 mlir::Value convertRValueToInt(RValue rvalue, bool cmpxchg = false) const;
115
116 /// Copy an atomic r-value into atomic-layout memory.
117 void emitCopyIntoMemory(RValue rvalue) const;
118
119 /// Project an l-value down to the value field.
120 LValue projectValue() const {
121 assert(lvalue.isSimple());
122 Address addr = getAtomicAddress();
123 if (hasPadding()) {
124 cgf.cgm.errorNYI(loc, "AtomicInfo::projectValue: padding");
125 }
126
128 return LValue::makeAddr(addr, getValueType(), lvalue.getBaseInfo());
129 }
130
131 /// Creates temp alloca for intermediate operations on atomic value.
132 Address createTempAlloca() const;
133
134private:
135 bool requiresMemSetZero(mlir::Type ty) const;
136};
137} // namespace
138
139// This function emits any expression (scalar, complex, or aggregate)
140// into a temporary alloca.
142 Address declPtr = cgf.createMemTemp(
143 e->getType(), cgf.getLoc(e->getSourceRange()), ".atomictmp");
144 cgf.emitAnyExprToMem(e, declPtr, e->getType().getQualifiers(),
145 /*Init*/ true);
146 return declPtr;
147}
148
149/// Does a store of the given IR type modify the full expected width?
150static bool isFullSizeType(CIRGenModule &cgm, mlir::Type ty,
151 uint64_t expectedSize) {
152 return cgm.getDataLayout().getTypeStoreSize(ty) * 8 == expectedSize;
153}
154
155/// Does the atomic type require memsetting to zero before initialization?
156///
157/// The IR type is provided as a way of making certain queries faster.
158bool AtomicInfo::requiresMemSetZero(mlir::Type ty) const {
159 // If the atomic type has size padding, we definitely need a memset.
160 if (hasPadding())
161 return true;
162
163 // Otherwise, do some simple heuristics to try to avoid it:
164 switch (getEvaluationKind()) {
165 // For scalars and complexes, check whether the store size of the
166 // type uses the full size.
167 case cir::TEK_Scalar:
168 return !isFullSizeType(cgf.cgm, ty, atomicSizeInBits);
169 case cir::TEK_Complex:
170 return !isFullSizeType(cgf.cgm,
171 mlir::cast<cir::ComplexType>(ty).getElementType(),
172 atomicSizeInBits / 2);
173 // Padding in structs has an undefined bit pattern. User beware.
175 return false;
176 }
177 llvm_unreachable("bad evaluation kind");
178}
179
180Address AtomicInfo::convertToAtomicIntPointer(Address addr) const {
181 mlir::Type ty = addr.getElementType();
182 uint64_t sourceSizeInBits = cgf.cgm.getDataLayout().getTypeSizeInBits(ty);
183 if (sourceSizeInBits != atomicSizeInBits) {
184 cgf.cgm.errorNYI(
185 loc,
186 "AtomicInfo::convertToAtomicIntPointer: convert through temp alloca");
187 }
188
189 return castToAtomicIntPointer(addr);
190}
191
192Address AtomicInfo::createTempAlloca() const {
193 Address tempAlloca = cgf.createMemTemp(
194 (lvalue.isBitField() && valueSizeInBits > atomicSizeInBits) ? valueTy
195 : atomicTy,
196 getAtomicAlignment(), loc, "atomic-temp");
197
198 // Cast to pointer to value type for bitfields.
199 if (lvalue.isBitField()) {
200 cgf.cgm.errorNYI(loc, "AtomicInfo::createTempAlloca: bitfield lvalue");
201 }
202
203 return tempAlloca;
204}
205
206mlir::Value AtomicInfo::getScalarRValValueOrNull(RValue rvalue) const {
207 if (rvalue.isScalar() && (!hasPadding() || !lvalue.isSimple()))
208 return rvalue.getValue();
209 return nullptr;
210}
211
212Address AtomicInfo::castToAtomicIntPointer(Address addr) const {
213 auto intTy = mlir::dyn_cast<cir::IntType>(addr.getElementType());
214 // Don't bother with int casts if the integer size is the same.
215 if (intTy && intTy.getWidth() == atomicSizeInBits)
216 return addr;
217 auto ty = cgf.getBuilder().getUIntNTy(atomicSizeInBits);
218 return addr.withElementType(cgf.getBuilder(), ty);
219}
220
221bool AtomicInfo::emitMemSetZeroIfNecessary() const {
222 assert(lvalue.isSimple());
223 Address addr = lvalue.getAddress();
224 if (!requiresMemSetZero(addr.getElementType()))
225 return false;
226
227 cgf.cgm.errorNYI(loc,
228 "AtomicInfo::emitMemSetZeroIfNecaessary: emit memset zero");
229 return false;
230}
231
232/// Return true if \param valueTy is a type that should be casted to integer
233/// around the atomic memory operation. If \param cmpxchg is true, then the
234/// cast of a floating point type is made as that instruction can not have
235/// floating point operands. TODO: Allow compare-and-exchange and FP - see
236/// comment in CIRGenAtomicExpandPass.cpp.
237static bool shouldCastToInt(mlir::Type valueTy, bool cmpxchg) {
238 if (cir::isAnyFloatingPointType(valueTy))
239 return isa<cir::FP80Type>(valueTy) || cmpxchg;
240 return !isa<cir::IntType>(valueTy) && !isa<cir::PointerType>(valueTy);
241}
242
243mlir::Value AtomicInfo::convertRValueToInt(RValue rvalue, bool cmpxchg) const {
244 // If we've got a scalar value of the right size, try to avoid going
245 // through memory. Floats get casted if needed by AtomicExpandPass.
246 if (mlir::Value value = getScalarRValValueOrNull(rvalue)) {
247 if (!shouldCastToInt(value.getType(), cmpxchg))
248 return cgf.emitToMemory(value, valueTy);
249
250 cgf.cgm.errorNYI(
251 loc, "AtomicInfo::convertRValueToInt: cast scalar rvalue to int");
252 return nullptr;
253 }
254
255 cgf.cgm.errorNYI(
256 loc, "AtomicInfo::convertRValueToInt: cast non-scalar rvalue to int");
257 return nullptr;
258}
259
260/// Copy an r-value into memory as part of storing to an atomic type.
261/// This needs to create a bit-pattern suitable for atomic operations.
262void AtomicInfo::emitCopyIntoMemory(RValue rvalue) const {
263 assert(lvalue.isSimple());
264
265 // If we have an r-value, the rvalue should be of the atomic type,
266 // which means that the caller is responsible for having zeroed
267 // any padding. Just do an aggregate copy of that type.
268 if (rvalue.isAggregate()) {
269 cgf.cgm.errorNYI("copying aggregate into atomic lvalue");
270 return;
271 }
272
273 // Okay, otherwise we're copying stuff.
274
275 // Zero out the buffer if necessary.
276 emitMemSetZeroIfNecessary();
277
278 // Drill past the padding if present.
279 LValue tempLValue = projectValue();
280
281 // Okay, store the rvalue in.
282 if (rvalue.isScalar()) {
283 cgf.emitStoreOfScalar(rvalue.getValue(), tempLValue, /*isInit=*/true);
284 } else {
285 cgf.cgm.errorNYI("copying complex into atomic lvalue");
286 }
287}
288
290 mlir::Location loc) {
291 mlir::ArrayAttr ordersAttr = builder.getArrayAttr({});
292 mlir::OpBuilder::InsertPoint insertPoint;
293 cir::CaseOp::create(builder, loc, ordersAttr, cir::CaseOpKind::Default,
294 insertPoint);
295 builder.restoreInsertionPoint(insertPoint);
296}
297
298// Create a "case" operation with the given list of orders as its values. Also
299// create the region that will hold the body of the switch-case label.
300static void emitMemOrderCaseLabel(CIRGenBuilderTy &builder, mlir::Location loc,
301 mlir::Type orderType,
304 for (cir::MemOrder order : orders)
305 orderAttrs.push_back(cir::IntAttr::get(orderType, static_cast<int>(order)));
306 mlir::ArrayAttr ordersAttr = builder.getArrayAttr(orderAttrs);
307
308 mlir::OpBuilder::InsertPoint insertPoint;
309 cir::CaseOp::create(builder, loc, ordersAttr, cir::CaseOpKind::Anyof,
310 insertPoint);
311 builder.restoreInsertionPoint(insertPoint);
312}
313
314static void emitAtomicCmpXchg(CIRGenFunction &cgf, AtomicExpr *e, bool isWeak,
315 Address dest, Address ptr, Address val1,
316 Address val2, uint64_t size,
317 cir::MemOrder successOrder,
318 cir::MemOrder failureOrder,
319 cir::SyncScopeKind scope) {
320 mlir::Location loc = cgf.getLoc(e->getSourceRange());
321
322 CIRGenBuilderTy &builder = cgf.getBuilder();
323 mlir::Value expected = builder.createLoad(loc, val1);
324 mlir::Value desired = builder.createLoad(loc, val2);
325
326 auto cmpxchg = cir::AtomicCmpXchgOp::create(
327 builder, loc, expected.getType(), builder.getBoolTy(), ptr.getPointer(),
328 expected, desired,
329 cir::MemOrderAttr::get(&cgf.getMLIRContext(), successOrder),
330 cir::MemOrderAttr::get(&cgf.getMLIRContext(), failureOrder),
331 cir::SyncScopeKindAttr::get(&cgf.getMLIRContext(), scope),
332 builder.getI64IntegerAttr(ptr.getAlignment().getAsAlign().value()));
333
334 cmpxchg.setIsVolatile(e->isVolatile());
335 cmpxchg.setWeak(isWeak);
336
337 mlir::Value failed = builder.createNot(cmpxchg.getSuccess());
338 cir::IfOp::create(builder, loc, failed, /*withElseRegion=*/false,
339 [&](mlir::OpBuilder &, mlir::Location) {
340 auto ptrTy = mlir::cast<cir::PointerType>(
341 val1.getPointer().getType());
342 if (val1.getElementType() != ptrTy.getPointee()) {
343 val1 = val1.withPointer(builder.createPtrBitcast(
344 val1.getPointer(), val1.getElementType()));
345 }
346 builder.createStore(loc, cmpxchg.getOld(), val1);
347 builder.createYield(loc);
348 });
349
350 // Update the memory at Dest with Success's value.
351 cgf.emitStoreOfScalar(cmpxchg.getSuccess(),
352 cgf.makeAddrLValue(dest, e->getType()),
353 /*isInit=*/false);
354}
355
357 bool isWeak, Address dest, Address ptr,
358 Address val1, Address val2,
359 Expr *failureOrderExpr, uint64_t size,
360 cir::MemOrder successOrder,
361 cir::SyncScopeKind scope) {
362 Expr::EvalResult failureOrderEval;
363 if (failureOrderExpr->EvaluateAsInt(failureOrderEval, cgf.getContext())) {
364 uint64_t failureOrderInt = failureOrderEval.Val.getInt().getZExtValue();
365
366 cir::MemOrder failureOrder;
367 if (!cir::isValidCIRAtomicOrderingCABI(failureOrderInt)) {
368 failureOrder = cir::MemOrder::Relaxed;
369 } else {
370 switch ((cir::MemOrder)failureOrderInt) {
371 case cir::MemOrder::Relaxed:
372 // 31.7.2.18: "The failure argument shall not be memory_order_release
373 // nor memory_order_acq_rel". Fallback to monotonic.
374 case cir::MemOrder::Release:
375 case cir::MemOrder::AcquireRelease:
376 failureOrder = cir::MemOrder::Relaxed;
377 break;
378 case cir::MemOrder::Consume:
379 case cir::MemOrder::Acquire:
380 failureOrder = cir::MemOrder::Acquire;
381 break;
382 case cir::MemOrder::SequentiallyConsistent:
383 failureOrder = cir::MemOrder::SequentiallyConsistent;
384 break;
385 }
386 }
387
388 // Prior to c++17, "the failure argument shall be no stronger than the
389 // success argument". This condition has been lifted and the only
390 // precondition is 31.7.2.18. Effectively treat this as a DR and skip
391 // language version checks.
392 emitAtomicCmpXchg(cgf, e, isWeak, dest, ptr, val1, val2, size, successOrder,
393 failureOrder, scope);
394 return;
395 }
396
397 // The failure memory order is not a compile time constant. The CIR atomic ops
398 // require a constant value, so that memory order is known at compile time. In
399 // this case, we can switch based on the memory order and call each variant
400 // individually.
401 mlir::Value failureOrderVal = cgf.emitScalarExpr(failureOrderExpr);
402 mlir::Location atomicLoc = cgf.getLoc(e->getSourceRange());
403 cir::SwitchOp::create(
404 cgf.getBuilder(), atomicLoc, failureOrderVal,
405 [&](mlir::OpBuilder &b, mlir::Location loc, mlir::OperationState &os) {
406 mlir::Block *switchBlock = cgf.getBuilder().getBlock();
407
408 // case cir::MemOrder::Relaxed:
409 // // 31.7.2.18: "The failure argument shall not be
410 // memory_order_release
411 // // nor memory_order_acq_rel". Fallback to monotonic.
412 // case cir::MemOrder::Release:
413 // case cir::MemOrder::AcquireRelease:
414 // Note: Since there are 3 options, this makes sense to just emit as a
415 // 'default', which prevents user code from 'falling off' of this,
416 // which seems reasonable. Also, 'relaxed' being the default behavior
417 // is also probably the least harmful.
418 emitMemOrderDefaultCaseLabel(cgf.getBuilder(), atomicLoc);
419 emitAtomicCmpXchg(cgf, e, isWeak, dest, ptr, val1, val2, size,
420 successOrder, cir::MemOrder::Relaxed, scope);
421 cgf.getBuilder().createBreak(atomicLoc);
422 cgf.getBuilder().setInsertionPointToEnd(switchBlock);
423
424 // case cir::MemOrder::Consume:
425 // case cir::MemOrder::Acquire:
426 emitMemOrderCaseLabel(cgf.getBuilder(), loc, failureOrderVal.getType(),
427 {cir::MemOrder::Consume, cir::MemOrder::Acquire});
428 emitAtomicCmpXchg(cgf, e, isWeak, dest, ptr, val1, val2, size,
429 successOrder, cir::MemOrder::Acquire, scope);
430 cgf.getBuilder().createBreak(atomicLoc);
431 cgf.getBuilder().setInsertionPointToEnd(switchBlock);
432
433 // case cir::MemOrder::SequentiallyConsistent:
434 emitMemOrderCaseLabel(cgf.getBuilder(), loc, failureOrderVal.getType(),
435 {cir::MemOrder::SequentiallyConsistent});
436 emitAtomicCmpXchg(cgf, e, isWeak, dest, ptr, val1, val2, size,
437 successOrder, cir::MemOrder::SequentiallyConsistent,
438 scope);
439 cgf.getBuilder().createBreak(atomicLoc);
440 cgf.getBuilder().setInsertionPointToEnd(switchBlock);
441
442 cgf.getBuilder().createYield(atomicLoc);
443 });
444}
445
447 Address ptr, Address val1, Address val2,
448 Expr *isWeakExpr, Expr *failureOrderExpr, int64_t size,
449 cir::MemOrder order, cir::SyncScopeKind scope) {
451 llvm::StringRef opName;
452
453 CIRGenBuilderTy &builder = cgf.getBuilder();
454 mlir::Location loc = cgf.getLoc(expr->getSourceRange());
455 auto orderAttr = cir::MemOrderAttr::get(builder.getContext(), order);
456 auto scopeAttr = cir::SyncScopeKindAttr::get(builder.getContext(), scope);
457 cir::AtomicFetchKindAttr fetchAttr;
458 bool fetchFirst = true;
459
460 switch (expr->getOp()) {
461 case AtomicExpr::AO__c11_atomic_init:
462 llvm_unreachable("already handled!");
463
464 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
465 emitAtomicCmpXchgFailureSet(cgf, expr, /*isWeak=*/false, dest, ptr, val1,
466 val2, failureOrderExpr, size, order, scope);
467 return;
468
469 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
470 emitAtomicCmpXchgFailureSet(cgf, expr, /*isWeak=*/true, dest, ptr, val1,
471 val2, failureOrderExpr, size, order, scope);
472 return;
473
474 case AtomicExpr::AO__atomic_compare_exchange:
475 case AtomicExpr::AO__atomic_compare_exchange_n:
476 case AtomicExpr::AO__scoped_atomic_compare_exchange:
477 case AtomicExpr::AO__scoped_atomic_compare_exchange_n: {
478 bool isWeak = false;
479 if (isWeakExpr->EvaluateAsBooleanCondition(isWeak, cgf.getContext())) {
480 emitAtomicCmpXchgFailureSet(cgf, expr, isWeak, dest, ptr, val1, val2,
481 failureOrderExpr, size, order, scope);
482 } else {
484 cgf.cgm.errorNYI(expr->getSourceRange(),
485 "emitAtomicOp: non-constant isWeak");
486 }
487 return;
488 }
489
490 case AtomicExpr::AO__c11_atomic_load:
491 case AtomicExpr::AO__atomic_load_n:
492 case AtomicExpr::AO__atomic_load:
493 case AtomicExpr::AO__scoped_atomic_load_n:
494 case AtomicExpr::AO__scoped_atomic_load: {
495 cir::LoadOp load =
496 builder.createLoad(loc, ptr, /*isVolatile=*/expr->isVolatile());
497
498 load->setAttr("mem_order", orderAttr);
499 load->setAttr("sync_scope", scopeAttr);
500
501 builder.createStore(loc, load->getResult(0), dest);
502 return;
503 }
504
505 case AtomicExpr::AO__c11_atomic_store:
506 case AtomicExpr::AO__atomic_store_n:
507 case AtomicExpr::AO__atomic_store:
508 case AtomicExpr::AO__scoped_atomic_store:
509 case AtomicExpr::AO__scoped_atomic_store_n: {
510 cir::LoadOp loadVal1 = builder.createLoad(loc, val1);
511
513
514 builder.createStore(loc, loadVal1, ptr, expr->isVolatile(),
515 /*align=*/mlir::IntegerAttr{}, scopeAttr, orderAttr);
516 return;
517 }
518
519 case AtomicExpr::AO__c11_atomic_exchange:
520 case AtomicExpr::AO__atomic_exchange_n:
521 case AtomicExpr::AO__atomic_exchange:
522 case AtomicExpr::AO__scoped_atomic_exchange_n:
523 case AtomicExpr::AO__scoped_atomic_exchange:
524 opName = cir::AtomicXchgOp::getOperationName();
525 break;
526
527 case AtomicExpr::AO__atomic_add_fetch:
528 case AtomicExpr::AO__scoped_atomic_add_fetch:
529 fetchFirst = false;
530 [[fallthrough]];
531 case AtomicExpr::AO__c11_atomic_fetch_add:
532 case AtomicExpr::AO__atomic_fetch_add:
533 case AtomicExpr::AO__scoped_atomic_fetch_add:
534 opName = cir::AtomicFetchOp::getOperationName();
535 fetchAttr = cir::AtomicFetchKindAttr::get(builder.getContext(),
536 cir::AtomicFetchKind::Add);
537 break;
538
539 case AtomicExpr::AO__atomic_sub_fetch:
540 case AtomicExpr::AO__scoped_atomic_sub_fetch:
541 fetchFirst = false;
542 [[fallthrough]];
543 case AtomicExpr::AO__c11_atomic_fetch_sub:
544 case AtomicExpr::AO__atomic_fetch_sub:
545 case AtomicExpr::AO__scoped_atomic_fetch_sub:
546 opName = cir::AtomicFetchOp::getOperationName();
547 fetchAttr = cir::AtomicFetchKindAttr::get(builder.getContext(),
548 cir::AtomicFetchKind::Sub);
549 break;
550
551 case AtomicExpr::AO__atomic_min_fetch:
552 case AtomicExpr::AO__scoped_atomic_min_fetch:
553 fetchFirst = false;
554 [[fallthrough]];
555 case AtomicExpr::AO__c11_atomic_fetch_min:
556 case AtomicExpr::AO__atomic_fetch_min:
557 case AtomicExpr::AO__scoped_atomic_fetch_min:
558 opName = cir::AtomicFetchOp::getOperationName();
559 fetchAttr = cir::AtomicFetchKindAttr::get(builder.getContext(),
560 cir::AtomicFetchKind::Min);
561 break;
562
563 case AtomicExpr::AO__atomic_max_fetch:
564 case AtomicExpr::AO__scoped_atomic_max_fetch:
565 fetchFirst = false;
566 [[fallthrough]];
567 case AtomicExpr::AO__c11_atomic_fetch_max:
568 case AtomicExpr::AO__atomic_fetch_max:
569 case AtomicExpr::AO__scoped_atomic_fetch_max:
570 opName = cir::AtomicFetchOp::getOperationName();
571 fetchAttr = cir::AtomicFetchKindAttr::get(builder.getContext(),
572 cir::AtomicFetchKind::Max);
573 break;
574
575 case AtomicExpr::AO__atomic_and_fetch:
576 case AtomicExpr::AO__scoped_atomic_and_fetch:
577 fetchFirst = false;
578 [[fallthrough]];
579 case AtomicExpr::AO__c11_atomic_fetch_and:
580 case AtomicExpr::AO__atomic_fetch_and:
581 case AtomicExpr::AO__scoped_atomic_fetch_and:
582 opName = cir::AtomicFetchOp::getOperationName();
583 fetchAttr = cir::AtomicFetchKindAttr::get(builder.getContext(),
584 cir::AtomicFetchKind::And);
585 break;
586
587 case AtomicExpr::AO__atomic_or_fetch:
588 case AtomicExpr::AO__scoped_atomic_or_fetch:
589 fetchFirst = false;
590 [[fallthrough]];
591 case AtomicExpr::AO__c11_atomic_fetch_or:
592 case AtomicExpr::AO__atomic_fetch_or:
593 case AtomicExpr::AO__scoped_atomic_fetch_or:
594 opName = cir::AtomicFetchOp::getOperationName();
595 fetchAttr = cir::AtomicFetchKindAttr::get(builder.getContext(),
596 cir::AtomicFetchKind::Or);
597 break;
598
599 case AtomicExpr::AO__atomic_xor_fetch:
600 case AtomicExpr::AO__scoped_atomic_xor_fetch:
601 fetchFirst = false;
602 [[fallthrough]];
603 case AtomicExpr::AO__c11_atomic_fetch_xor:
604 case AtomicExpr::AO__atomic_fetch_xor:
605 case AtomicExpr::AO__scoped_atomic_fetch_xor:
606 opName = cir::AtomicFetchOp::getOperationName();
607 fetchAttr = cir::AtomicFetchKindAttr::get(builder.getContext(),
608 cir::AtomicFetchKind::Xor);
609 break;
610
611 case AtomicExpr::AO__atomic_nand_fetch:
612 case AtomicExpr::AO__scoped_atomic_nand_fetch:
613 fetchFirst = false;
614 [[fallthrough]];
615 case AtomicExpr::AO__c11_atomic_fetch_nand:
616 case AtomicExpr::AO__atomic_fetch_nand:
617 case AtomicExpr::AO__scoped_atomic_fetch_nand:
618 opName = cir::AtomicFetchOp::getOperationName();
619 fetchAttr = cir::AtomicFetchKindAttr::get(builder.getContext(),
620 cir::AtomicFetchKind::Nand);
621 break;
622
623 case AtomicExpr::AO__atomic_test_and_set: {
624 auto op = cir::AtomicTestAndSetOp::create(
625 builder, loc, ptr.getPointer(), order,
626 builder.getI64IntegerAttr(ptr.getAlignment().getQuantity()),
627 expr->isVolatile());
628 builder.createStore(loc, op, dest);
629 return;
630 }
631
632 case AtomicExpr::AO__atomic_clear: {
633 cir::AtomicClearOp::create(
634 builder, loc, ptr.getPointer(), order,
635 builder.getI64IntegerAttr(ptr.getAlignment().getQuantity()),
636 expr->isVolatile());
637 return;
638 }
639
640 case AtomicExpr::AO__opencl_atomic_init:
641
642 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
643 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
644
645 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
646 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
647
648 case AtomicExpr::AO__opencl_atomic_load:
649 case AtomicExpr::AO__hip_atomic_load:
650
651 case AtomicExpr::AO__opencl_atomic_store:
652 case AtomicExpr::AO__hip_atomic_store:
653
654 case AtomicExpr::AO__hip_atomic_exchange:
655 case AtomicExpr::AO__opencl_atomic_exchange:
656
657 case AtomicExpr::AO__hip_atomic_fetch_add:
658 case AtomicExpr::AO__opencl_atomic_fetch_add:
659
660 case AtomicExpr::AO__hip_atomic_fetch_sub:
661 case AtomicExpr::AO__opencl_atomic_fetch_sub:
662
663 case AtomicExpr::AO__hip_atomic_fetch_min:
664 case AtomicExpr::AO__opencl_atomic_fetch_min:
665
666 case AtomicExpr::AO__hip_atomic_fetch_max:
667 case AtomicExpr::AO__opencl_atomic_fetch_max:
668
669 case AtomicExpr::AO__hip_atomic_fetch_and:
670 case AtomicExpr::AO__opencl_atomic_fetch_and:
671
672 case AtomicExpr::AO__hip_atomic_fetch_or:
673 case AtomicExpr::AO__opencl_atomic_fetch_or:
674
675 case AtomicExpr::AO__hip_atomic_fetch_xor:
676 case AtomicExpr::AO__opencl_atomic_fetch_xor:
677
678 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
679 case AtomicExpr::AO__scoped_atomic_fetch_udec:
680 case AtomicExpr::AO__atomic_fetch_uinc:
681 case AtomicExpr::AO__atomic_fetch_udec:
682 cgf.cgm.errorNYI(expr->getSourceRange(), "emitAtomicOp: expr op NYI");
683 return;
684 }
685
686 assert(!opName.empty() && "expected operation name to build");
687 mlir::Value loadVal1 = builder.createLoad(loc, val1);
688
689 SmallVector<mlir::Value> atomicOperands = {ptr.getPointer(), loadVal1};
690 SmallVector<mlir::Type> atomicResTys = {loadVal1.getType()};
691 mlir::Operation *rmwOp = builder.create(loc, builder.getStringAttr(opName),
692 atomicOperands, atomicResTys);
693
694 if (fetchAttr)
695 rmwOp->setAttr("binop", fetchAttr);
696 rmwOp->setAttr("mem_order", orderAttr);
697 rmwOp->setAttr("sync_scope", scopeAttr);
698 if (expr->isVolatile())
699 rmwOp->setAttr("is_volatile", builder.getUnitAttr());
700 if (fetchFirst && opName == cir::AtomicFetchOp::getOperationName())
701 rmwOp->setAttr("fetch_first", builder.getUnitAttr());
702
703 mlir::Value result = rmwOp->getResult(0);
704 builder.createStore(loc, result, dest);
705}
706
707// Map clang sync scope to CIR sync scope.
708static cir::SyncScopeKind convertSyncScopeToCIR(CIRGenFunction &cgf,
709 SourceRange range,
710 clang::SyncScope scope) {
711 switch (scope) {
712 default: {
714 cgf.cgm.errorNYI(range, "convertSyncScopeToCIR: unhandled sync scope");
715 return cir::SyncScopeKind::System;
716 }
717
719 return cir::SyncScopeKind::SingleThread;
721 return cir::SyncScopeKind::System;
722 }
723}
724
726 Address ptr, Address val1, Address val2,
727 Expr *isWeakExpr, Expr *failureOrderExpr, int64_t size,
728 cir::MemOrder order,
729 const std::optional<Expr::EvalResult> &scopeConst,
730 mlir::Value scopeValue) {
731 std::unique_ptr<AtomicScopeModel> scopeModel = expr->getScopeModel();
732
733 if (!scopeModel) {
734 emitAtomicOp(cgf, expr, dest, ptr, val1, val2, isWeakExpr, failureOrderExpr,
735 size, order, cir::SyncScopeKind::System);
736 return;
737 }
738
739 if (scopeConst.has_value()) {
740 cir::SyncScopeKind mappedScope = convertSyncScopeToCIR(
741 cgf, expr->getScope()->getSourceRange(),
742 scopeModel->map(scopeConst->Val.getInt().getZExtValue()));
743 emitAtomicOp(cgf, expr, dest, ptr, val1, val2, isWeakExpr, failureOrderExpr,
744 size, order, mappedScope);
745 return;
746 }
747
749 cgf.cgm.errorNYI(expr->getSourceRange(), "emitAtomicOp: dynamic sync scope");
750}
751
752static std::optional<cir::MemOrder>
753getEffectiveAtomicMemOrder(cir::MemOrder oriOrder, bool isStore, bool isLoad,
754 bool isFence) {
755 // Some memory orders are not supported by partial atomic operation:
756 // {memory_order_releaxed} is not valid for fence operations.
757 // {memory_order_consume, memory_order_acquire} are not valid for write-only
758 // operations.
759 // {memory_order_release} is not valid for read-only operations.
760 // {memory_order_acq_rel} is only valid for read-write operations.
761 if (isStore) {
762 if (oriOrder == cir::MemOrder::Consume ||
763 oriOrder == cir::MemOrder::Acquire ||
764 oriOrder == cir::MemOrder::AcquireRelease)
765 return std::nullopt;
766 } else if (isLoad) {
767 if (oriOrder == cir::MemOrder::Release ||
768 oriOrder == cir::MemOrder::AcquireRelease)
769 return std::nullopt;
770 } else if (isFence) {
771 if (oriOrder == cir::MemOrder::Relaxed)
772 return std::nullopt;
773 }
774 // memory_order_consume is not implemented, it is always treated like
775 // memory_order_acquire
776 if (oriOrder == cir::MemOrder::Consume)
777 return cir::MemOrder::Acquire;
778 return oriOrder;
779}
780
782 CIRGenFunction &cgf, mlir::Value order, bool isStore, bool isLoad,
783 bool isFence, llvm::function_ref<void(cir::MemOrder)> emitAtomicOpFn) {
784 if (!order)
785 return;
786 // The memory order is not known at compile-time. The atomic operations
787 // can't handle runtime memory orders; the memory order must be hard coded.
788 // Generate a "switch" statement that converts a runtime value into a
789 // compile-time value.
790 CIRGenBuilderTy &builder = cgf.getBuilder();
791 cir::SwitchOp::create(
792 builder, order.getLoc(), order,
793 [&](mlir::OpBuilder &, mlir::Location loc, mlir::OperationState &) {
794 mlir::Block *switchBlock = builder.getBlock();
795
796 auto emitMemOrderCase = [&](llvm::ArrayRef<cir::MemOrder> caseOrders) {
797 // Checking there are same effective memory order for each case.
798 for (int i = 1, e = caseOrders.size(); i < e; i++)
799 assert((getEffectiveAtomicMemOrder(caseOrders[i - 1], isStore,
800 isLoad, isFence) ==
801 getEffectiveAtomicMemOrder(caseOrders[i], isStore, isLoad,
802 isFence)) &&
803 "Effective memory order must be same!");
804 // Emit case label and atomic opeartion if neccessary.
805 if (caseOrders.empty()) {
806 emitMemOrderDefaultCaseLabel(builder, loc);
807 // There is no good way to report an unsupported memory order at
808 // runtime, hence the fallback to memory_order_relaxed.
809 if (!isFence)
810 emitAtomicOpFn(cir::MemOrder::Relaxed);
811 } else if (std::optional<cir::MemOrder> actualOrder =
812 getEffectiveAtomicMemOrder(caseOrders[0], isStore,
813 isLoad, isFence)) {
814 // Included in default case.
815 if (!isFence && actualOrder == cir::MemOrder::Relaxed)
816 return;
817 // Creating case operation for effective memory order. If there are
818 // multiple cases in `caseOrders`, the actual order of each case
819 // must be same, this needs to be guaranteed by the caller.
820 emitMemOrderCaseLabel(builder, loc, order.getType(), caseOrders);
821 emitAtomicOpFn(actualOrder.value());
822 } else {
823 // Do nothing if (!caseOrders.empty() && !actualOrder)
824 return;
825 }
826 builder.createBreak(loc);
827 builder.setInsertionPointToEnd(switchBlock);
828 };
829
830 emitMemOrderCase(/*default:*/ {});
831 emitMemOrderCase({cir::MemOrder::Relaxed});
832 emitMemOrderCase({cir::MemOrder::Consume, cir::MemOrder::Acquire});
833 emitMemOrderCase({cir::MemOrder::Release});
834 emitMemOrderCase({cir::MemOrder::AcquireRelease});
835 emitMemOrderCase({cir::MemOrder::SequentiallyConsistent});
836
837 builder.createYield(loc);
838 });
839}
840
842 const Expr *memOrder, bool isStore, bool isLoad, bool isFence,
843 llvm::function_ref<void(cir::MemOrder)> emitAtomicOpFn) {
844 // Emit the memory order operand, and try to evaluate it as a constant.
845 Expr::EvalResult eval;
846 if (memOrder->EvaluateAsInt(eval, getContext())) {
847 uint64_t constOrder = eval.Val.getInt().getZExtValue();
848 // We should not ever get to a case where the ordering isn't a valid CABI
849 // value, but it's hard to enforce that in general.
850 if (!cir::isValidCIRAtomicOrderingCABI(constOrder))
851 return;
852 cir::MemOrder oriOrder = static_cast<cir::MemOrder>(constOrder);
853 if (std::optional<cir::MemOrder> actualOrder =
854 getEffectiveAtomicMemOrder(oriOrder, isStore, isLoad, isFence))
855 emitAtomicOpFn(actualOrder.value());
856 return;
857 }
858
859 // Otherwise, handle variable memory ordering. Emit `SwitchOp` to convert
860 // dynamic value to static value.
861 mlir::Value dynOrder = emitScalarExpr(memOrder);
862 emitAtomicExprWithDynamicMemOrder(*this, dynOrder, isStore, isLoad, isFence,
863 emitAtomicOpFn);
864}
865
867 QualType atomicTy = e->getPtr()->getType()->getPointeeType();
868 QualType memTy = atomicTy;
869 if (const auto *ty = atomicTy->getAs<AtomicType>())
870 memTy = ty->getValueType();
871
872 Expr *isWeakExpr = nullptr;
873 Expr *orderFailExpr = nullptr;
874
875 Address val1 = Address::invalid();
876 Address val2 = Address::invalid();
877 Address dest = Address::invalid();
879
881 if (e->getOp() == AtomicExpr::AO__c11_atomic_init) {
882 LValue lvalue = makeAddrLValue(ptr, atomicTy);
883 emitAtomicInit(e->getVal1(), lvalue);
884 return RValue::get(nullptr);
885 }
886
887 TypeInfoChars typeInfo = getContext().getTypeInfoInChars(atomicTy);
888 uint64_t size = typeInfo.Width.getQuantity();
889
890 // Emit the sync scope operand, and try to evaluate it as a constant.
891 mlir::Value scope =
892 e->getScopeModel() ? emitScalarExpr(e->getScope()) : nullptr;
893 std::optional<Expr::EvalResult> scopeConst;
894 if (Expr::EvalResult eval;
895 e->getScopeModel() && e->getScope()->EvaluateAsInt(eval, getContext()))
896 scopeConst.emplace(std::move(eval));
897
898 switch (e->getOp()) {
899 default:
900 cgm.errorNYI(e->getSourceRange(), "atomic op NYI");
901 return RValue::get(nullptr);
902
903 case AtomicExpr::AO__c11_atomic_init:
904 llvm_unreachable("already handled above with emitAtomicInit");
905
906 case AtomicExpr::AO__atomic_load_n:
907 case AtomicExpr::AO__scoped_atomic_load_n:
908 case AtomicExpr::AO__c11_atomic_load:
909 case AtomicExpr::AO__atomic_test_and_set:
910 case AtomicExpr::AO__atomic_clear:
911 break;
912
913 case AtomicExpr::AO__atomic_load:
914 case AtomicExpr::AO__scoped_atomic_load:
916 break;
917
918 case AtomicExpr::AO__atomic_store:
919 case AtomicExpr::AO__scoped_atomic_store:
921 break;
922
923 case AtomicExpr::AO__atomic_exchange:
924 case AtomicExpr::AO__scoped_atomic_exchange:
927 break;
928
929 case AtomicExpr::AO__atomic_compare_exchange:
930 case AtomicExpr::AO__atomic_compare_exchange_n:
931 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
932 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
933 case AtomicExpr::AO__scoped_atomic_compare_exchange:
934 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
936 if (e->getOp() == AtomicExpr::AO__atomic_compare_exchange ||
937 e->getOp() == AtomicExpr::AO__scoped_atomic_compare_exchange)
939 else
940 val2 = emitValToTemp(*this, e->getVal2());
941 orderFailExpr = e->getOrderFail();
942 if (e->getOp() == AtomicExpr::AO__atomic_compare_exchange_n ||
943 e->getOp() == AtomicExpr::AO__atomic_compare_exchange ||
944 e->getOp() == AtomicExpr::AO__scoped_atomic_compare_exchange_n ||
945 e->getOp() == AtomicExpr::AO__scoped_atomic_compare_exchange)
946 isWeakExpr = e->getWeak();
947 break;
948
949 case AtomicExpr::AO__c11_atomic_fetch_add:
950 case AtomicExpr::AO__c11_atomic_fetch_sub:
951 if (memTy->isPointerType()) {
952 cgm.errorNYI(e->getSourceRange(),
953 "atomic fetch-and-add and fetch-and-sub for pointers");
954 return RValue::get(nullptr);
955 }
956 [[fallthrough]];
957 case AtomicExpr::AO__atomic_fetch_add:
958 case AtomicExpr::AO__atomic_fetch_max:
959 case AtomicExpr::AO__atomic_fetch_min:
960 case AtomicExpr::AO__atomic_fetch_sub:
961 case AtomicExpr::AO__atomic_add_fetch:
962 case AtomicExpr::AO__atomic_max_fetch:
963 case AtomicExpr::AO__atomic_min_fetch:
964 case AtomicExpr::AO__atomic_sub_fetch:
965 case AtomicExpr::AO__c11_atomic_fetch_max:
966 case AtomicExpr::AO__c11_atomic_fetch_min:
967 case AtomicExpr::AO__scoped_atomic_fetch_add:
968 case AtomicExpr::AO__scoped_atomic_fetch_max:
969 case AtomicExpr::AO__scoped_atomic_fetch_min:
970 case AtomicExpr::AO__scoped_atomic_fetch_sub:
971 case AtomicExpr::AO__scoped_atomic_add_fetch:
972 case AtomicExpr::AO__scoped_atomic_max_fetch:
973 case AtomicExpr::AO__scoped_atomic_min_fetch:
974 case AtomicExpr::AO__scoped_atomic_sub_fetch:
975 [[fallthrough]];
976
977 case AtomicExpr::AO__atomic_fetch_and:
978 case AtomicExpr::AO__atomic_fetch_nand:
979 case AtomicExpr::AO__atomic_fetch_or:
980 case AtomicExpr::AO__atomic_fetch_xor:
981 case AtomicExpr::AO__atomic_and_fetch:
982 case AtomicExpr::AO__atomic_nand_fetch:
983 case AtomicExpr::AO__atomic_or_fetch:
984 case AtomicExpr::AO__atomic_xor_fetch:
985 case AtomicExpr::AO__atomic_exchange_n:
986 case AtomicExpr::AO__atomic_store_n:
987 case AtomicExpr::AO__c11_atomic_fetch_and:
988 case AtomicExpr::AO__c11_atomic_fetch_nand:
989 case AtomicExpr::AO__c11_atomic_fetch_or:
990 case AtomicExpr::AO__c11_atomic_fetch_xor:
991 case AtomicExpr::AO__c11_atomic_exchange:
992 case AtomicExpr::AO__c11_atomic_store:
993 case AtomicExpr::AO__scoped_atomic_fetch_and:
994 case AtomicExpr::AO__scoped_atomic_fetch_nand:
995 case AtomicExpr::AO__scoped_atomic_fetch_or:
996 case AtomicExpr::AO__scoped_atomic_fetch_xor:
997 case AtomicExpr::AO__scoped_atomic_and_fetch:
998 case AtomicExpr::AO__scoped_atomic_nand_fetch:
999 case AtomicExpr::AO__scoped_atomic_or_fetch:
1000 case AtomicExpr::AO__scoped_atomic_xor_fetch:
1001 case AtomicExpr::AO__scoped_atomic_store_n:
1002 case AtomicExpr::AO__scoped_atomic_exchange_n:
1003 val1 = emitValToTemp(*this, e->getVal1());
1004 break;
1005 }
1006
1007 QualType resultTy = e->getType().getUnqualifiedType();
1008
1009 bool shouldCastToIntPtrTy =
1011
1012 // The inlined atomics only function on iN types, where N is a power of 2. We
1013 // need to make sure (via temporaries if necessary) that all incoming values
1014 // are compatible.
1015 LValue atomicValue = makeAddrLValue(ptr, atomicTy);
1016 AtomicInfo atomics(*this, atomicValue, getLoc(e->getSourceRange()));
1017
1018 if (shouldCastToIntPtrTy) {
1019 ptr = atomics.castToAtomicIntPointer(ptr);
1020 if (val1.isValid())
1021 val1 = atomics.convertToAtomicIntPointer(val1);
1022 }
1023 if (dest.isValid()) {
1024 if (shouldCastToIntPtrTy)
1025 dest = atomics.castToAtomicIntPointer(dest);
1026 } else if (e->isCmpXChg()) {
1027 dest = createMemTemp(resultTy, getLoc(e->getSourceRange()), "cmpxchg.bool");
1028 } else if (e->getOp() == AtomicExpr::AO__atomic_test_and_set) {
1029 dest = createMemTemp(resultTy, getLoc(e->getSourceRange()),
1030 "test_and_set.bool");
1031 } else if (!resultTy->isVoidType()) {
1032 dest = atomics.createTempAlloca();
1033 if (shouldCastToIntPtrTy)
1034 dest = atomics.castToAtomicIntPointer(dest);
1035 }
1036
1037 bool powerOf2Size = (size & (size - 1)) == 0;
1038 bool useLibCall = !powerOf2Size || (size > 16);
1039
1040 // For atomics larger than 16 bytes, emit a libcall from the frontend. This
1041 // avoids the overhead of dealing with excessively-large value types in IR.
1042 // Non-power-of-2 values also lower to libcall here, as they are not currently
1043 // permitted in IR instructions (although that constraint could be relaxed in
1044 // the future). For other cases where a libcall is required on a given
1045 // platform, we let the backend handle it (this includes handling for all of
1046 // the size-optimized libcall variants, which are only valid up to 16 bytes.)
1047 //
1048 // See: https://llvm.org/docs/Atomics.html#libcalls-atomic
1049 if (useLibCall) {
1051 cgm.errorNYI(e->getSourceRange(), "emitAtomicExpr: emit atomic lib call");
1052 return RValue::get(nullptr);
1053 }
1054
1055 bool isStore = e->getOp() == AtomicExpr::AO__c11_atomic_store ||
1056 e->getOp() == AtomicExpr::AO__opencl_atomic_store ||
1057 e->getOp() == AtomicExpr::AO__hip_atomic_store ||
1058 e->getOp() == AtomicExpr::AO__atomic_store ||
1059 e->getOp() == AtomicExpr::AO__atomic_store_n ||
1060 e->getOp() == AtomicExpr::AO__scoped_atomic_store ||
1061 e->getOp() == AtomicExpr::AO__scoped_atomic_store_n ||
1062 e->getOp() == AtomicExpr::AO__atomic_clear;
1063 bool isLoad = e->getOp() == AtomicExpr::AO__c11_atomic_load ||
1064 e->getOp() == AtomicExpr::AO__opencl_atomic_load ||
1065 e->getOp() == AtomicExpr::AO__hip_atomic_load ||
1066 e->getOp() == AtomicExpr::AO__atomic_load ||
1067 e->getOp() == AtomicExpr::AO__atomic_load_n ||
1068 e->getOp() == AtomicExpr::AO__scoped_atomic_load ||
1069 e->getOp() == AtomicExpr::AO__scoped_atomic_load_n;
1070
1071 auto emitAtomicOpCallBackFn = [&](cir::MemOrder memOrder) {
1072 emitAtomicOp(*this, e, dest, ptr, val1, val2, isWeakExpr, orderFailExpr,
1073 size, memOrder, scopeConst, scope);
1074 };
1075 emitAtomicExprWithMemOrder(e->getOrder(), isStore, isLoad, /*isFence*/ false,
1076 emitAtomicOpCallBackFn);
1077
1078 if (resultTy->isVoidType())
1079 return RValue::get(nullptr);
1080
1081 return convertTempToRValue(
1082 dest.withElementType(builder, convertTypeForMem(resultTy)), resultTy,
1083 e->getExprLoc());
1084}
1085
1086void CIRGenFunction::emitAtomicStore(RValue rvalue, LValue dest, bool isInit) {
1087 bool isVolatile = dest.isVolatileQualified();
1088 auto order = cir::MemOrder::SequentiallyConsistent;
1089 if (!dest.getType()->isAtomicType()) {
1091 }
1092 return emitAtomicStore(rvalue, dest, order, isVolatile, isInit);
1093}
1094
1095/// Emit a store to an l-value of atomic type.
1096///
1097/// Note that the r-value is expected to be an r-value of the atomic type; this
1098/// means that for aggregate r-values, it should include storage for any padding
1099/// that was necessary.
1101 cir::MemOrder order, bool isVolatile,
1102 bool isInit) {
1103 // If this is an aggregate r-value, it should agree in type except
1104 // maybe for address-space qualification.
1105 mlir::Location loc = dest.getPointer().getLoc();
1106 assert(!rvalue.isAggregate() ||
1108 dest.getAddress().getElementType());
1109
1110 AtomicInfo atomics(*this, dest, loc);
1111 LValue lvalue = atomics.getAtomicLValue();
1112
1113 if (lvalue.isSimple()) {
1114 // If this is an initialization, just put the value there normally.
1115 if (isInit) {
1116 atomics.emitCopyIntoMemory(rvalue);
1117 return;
1118 }
1119
1120 // Check whether we should use a library call.
1121 if (atomics.shouldUseLibCall()) {
1123 cgm.errorNYI(loc, "emitAtomicStore: atomic store with library call");
1124 return;
1125 }
1126
1127 // Okay, we're doing this natively.
1128 mlir::Value valueToStore = atomics.convertRValueToInt(rvalue);
1129
1130 // Do the atomic store.
1131 Address addr = atomics.getAtomicAddress();
1132 if (mlir::Value value = atomics.getScalarRValValueOrNull(rvalue)) {
1133 if (shouldCastToInt(value.getType(), /*CmpXchg=*/false)) {
1134 addr = atomics.castToAtomicIntPointer(addr);
1135 valueToStore =
1136 builder.createIntCast(valueToStore, addr.getElementType());
1137 }
1138 }
1139 cir::StoreOp store = builder.createStore(loc, valueToStore, addr);
1140
1141 // Initializations don't need to be atomic.
1142 if (!isInit) {
1144 store.setMemOrder(order);
1145 }
1146
1147 // Other decoration.
1148 if (isVolatile)
1149 store.setIsVolatile(true);
1150
1152 return;
1153 }
1154
1155 cgm.errorNYI(loc, "emitAtomicStore: non-simple atomic lvalue");
1157}
1158
1160 AtomicInfo atomics(*this, dest, getLoc(init->getSourceRange()));
1161
1162 switch (atomics.getEvaluationKind()) {
1163 case cir::TEK_Scalar: {
1164 mlir::Value value = emitScalarExpr(init);
1165 atomics.emitCopyIntoMemory(RValue::get(value));
1166 return;
1167 }
1168
1169 case cir::TEK_Complex: {
1170 mlir::Value value = emitComplexExpr(init);
1171 atomics.emitCopyIntoMemory(RValue::get(value));
1172 return;
1173 }
1174
1175 case cir::TEK_Aggregate: {
1176 // Fix up the destination if the initializer isn't an expression
1177 // of atomic type.
1178 bool zeroed = false;
1179 if (!init->getType()->isAtomicType()) {
1180 zeroed = atomics.emitMemSetZeroIfNecessary();
1181 dest = atomics.projectValue();
1182 }
1183
1184 // Evaluate the expression directly into the destination.
1190
1191 emitAggExpr(init, slot);
1192 return;
1193 }
1194 }
1195
1196 llvm_unreachable("bad evaluation kind");
1197}
static bool shouldCastToInt(mlir::Type valueTy, bool cmpxchg)
Return true if.
static Address emitValToTemp(CIRGenFunction &cgf, Expr *e)
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 void emitMemOrderCaseLabel(CIRGenBuilderTy &builder, mlir::Location loc, mlir::Type orderType, llvm::ArrayRef< cir::MemOrder > orders)
static cir::SyncScopeKind convertSyncScopeToCIR(CIRGenFunction &cgf, SourceRange range, clang::SyncScope scope)
static void emitAtomicExprWithDynamicMemOrder(CIRGenFunction &cgf, mlir::Value order, bool isStore, bool isLoad, bool isFence, llvm::function_ref< void(cir::MemOrder)> emitAtomicOpFn)
static void emitAtomicOp(CIRGenFunction &cgf, AtomicExpr *expr, Address dest, Address ptr, Address val1, Address val2, Expr *isWeakExpr, Expr *failureOrderExpr, int64_t size, cir::MemOrder order, 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 emitMemOrderDefaultCaseLabel(CIRGenBuilderTy &builder, mlir::Location loc)
static std::optional< cir::MemOrder > getEffectiveAtomicMemOrder(cir::MemOrder oriOrder, bool isStore, bool isLoad, bool isFence)
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)
__device__ __2f16 b
cir::BreakOp createBreak(mlir::Location loc)
Create a break operation.
mlir::Value createNot(mlir::Value value)
mlir::Value createPtrBitcast(mlir::Value src, mlir::Type newPointeeTy)
cir::YieldOp createYield(mlir::Location loc, mlir::ValueRange value={})
Create a yield operation.
cir::BoolType getBoolTy()
llvm::TypeSize getTypeSizeInBits(mlir::Type ty) const
llvm::TypeSize getTypeStoreSize(mlir::Type ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type.
APSInt & getInt()
Definition APValue.h:508
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:916
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
Expr * getScope() const
Definition Expr.h:6964
bool isCmpXChg() const
Definition Expr.h:7011
AtomicOp getOp() const
Definition Expr.h:6990
Expr * getVal1() const
Definition Expr.h:6968
Expr * getPtr() const
Definition Expr.h:6958
Expr * getWeak() const
Definition Expr.h:6984
Expr * getOrderFail() const
Definition Expr.h:6974
bool isVolatile() const
Definition Expr.h:7007
Address withPointer(mlir::Value newPtr) const
Return address with different pointer, but same element type and alignment.
Definition Address.h:81
mlir::Value getPointer() const
Definition Address.h:96
mlir::Type getElementType() const
Definition Address.h:123
static Address invalid()
Definition Address.h:74
Address withElementType(CIRGenBuilderTy &builder, mlir::Type ElemTy) const
Return address with different element type, a bitcast pointer, and the same alignment.
clang::CharUnits getAlignment() const
Definition Address.h:136
bool isValid() const
Definition Address.h:75
An aggregate value slot.
static AggValueSlot forLValue(const LValue &LV, IsDestructed_t isDestructed, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed)
cir::StoreOp createStore(mlir::Location loc, mlir::Value val, Address dst, bool isVolatile=false, mlir::IntegerAttr align={}, cir::SyncScopeKindAttr scope={}, cir::MemOrderAttr order={})
cir::LoadOp createLoad(mlir::Location loc, Address addr, bool isVolatile=false)
cir::IntType getUIntNTy(int n)
RValue convertTempToRValue(Address addr, clang::QualType type, clang::SourceLocation loc)
Given the address of a temporary variable, produce an r-value of its type.
Address emitPointerWithAlignment(const clang::Expr *expr, LValueBaseInfo *baseInfo=nullptr)
Given an expression with a pointer type, emit the value and compute our best estimate of the alignmen...
mlir::Value emitComplexExpr(const Expr *e)
Emit the computation of the specified expression of complex type, returning the result.
mlir::Location getLoc(clang::SourceLocation srcLoc)
Helpers to convert Clang's SourceLocation to a MLIR Location.
void emitAnyExprToMem(const Expr *e, Address location, Qualifiers quals, bool isInitializer)
Emits the code necessary to evaluate an arbitrary expression into the given memory location.
RValue emitAtomicExpr(AtomicExpr *e)
mlir::Type convertTypeForMem(QualType t)
void emitStoreOfScalar(mlir::Value value, Address addr, bool isVolatile, clang::QualType ty, LValueBaseInfo baseInfo, bool isInit=false, bool isNontemporal=false)
void emitAtomicExprWithMemOrder(const Expr *memOrder, bool isStore, bool isLoad, bool isFence, llvm::function_ref< void(cir::MemOrder)> emitAtomicOp)
mlir::Value emitToMemory(mlir::Value value, clang::QualType ty)
Given a value and its clang type, returns the value casted to its memory representation.
mlir::Value emitScalarExpr(const clang::Expr *e, bool ignoreResultAssign=false)
Emit the computation of the specified expression of scalar type.
CIRGenBuilderTy & getBuilder()
mlir::MLIRContext & getMLIRContext()
void emitAtomicInit(Expr *init, LValue dest)
LValue makeAddrLValue(Address addr, QualType ty, AlignmentSource source=AlignmentSource::Type)
void emitAtomicStore(RValue rvalue, LValue dest, bool isInit)
clang::ASTContext & getContext() const
Address createMemTemp(QualType t, mlir::Location loc, const Twine &name="tmp", Address *alloca=nullptr, mlir::OpBuilder::InsertPoint ip={})
Create a temporary memory object of the given type, with appropriate alignmen and cast it to the defa...
void emitAggExpr(const clang::Expr *e, AggValueSlot slot)
This class organizes the cross-function state that is used while generating CIR code.
DiagnosticBuilder errorNYI(SourceLocation, llvm::StringRef)
Helpers to emit "not yet implemented" error diagnostics.
const cir::CIRDataLayout getDataLayout() const
Address getAddress() const
clang::QualType getType() const
mlir::Value getPointer() const
bool isVolatileQualified() const
bool isSimple() const
This trivial value class is used to represent the result of an expression that is evaluated.
Definition CIRGenValue.h:33
Address getAggregateAddress() const
Return the value of the address of the aggregate.
Definition CIRGenValue.h:69
bool isAggregate() const
Definition CIRGenValue.h:51
static RValue get(mlir::Value v)
Definition CIRGenValue.h:83
mlir::Value getValue() const
Return the value of this scalar value.
Definition CIRGenValue.h:57
bool isScalar() const
Definition CIRGenValue.h:49
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
This represents one expression.
Definition Expr.h:112
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
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
A (possibly-)qualified type.
Definition TypeBase.h:937
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
A trivial tuple used to represent a source range.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
virtual bool hasBuiltinAtomic(uint64_t AtomicSizeInBits, uint64_t AlignmentInBits) const
Returns true if the given target supports lock-free atomic operations at the specified width and alig...
Definition TargetInfo.h:864
bool isVoidType() const
Definition TypeBase.h:8991
bool isPointerType() const
Definition TypeBase.h:8625
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
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9218
bool isValidCIRAtomicOrderingCABI(Int value)
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
SyncScope
Defines sync scope values used internally by clang.
Definition SyncScope.h:42
unsigned long uint64_t
static bool atomicInfoGetAtomicPointer()
static bool aggValueSlotGC()
static bool opLoadStoreAtomic()
static bool opLoadStoreTbaa()
static bool atomicUseLibCall()
static bool atomicOpenMP()
static bool atomicMicrosoftVolatile()
static bool atomicSyncScopeID()
static bool atomicInfoGetAtomicAddress()
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:648
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:650