clang 24.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 QualType getAtomicType() const { return atomicTy; }
72 CharUnits getAtomicAlignment() const { return atomicAlign; }
73 TypeEvaluationKind getEvaluationKind() const { return evaluationKind; }
74 mlir::Value getAtomicPointer() const {
75 if (lvalue.isSimple())
76 return lvalue.getPointer();
78 return nullptr;
79 }
80 bool shouldUseLibCall() const { return useLibCall; }
81 const LValue &getAtomicLValue() const { return lvalue; }
82 Address getAtomicAddress() const {
83 mlir::Type elemTy;
84 if (lvalue.isSimple()) {
85 elemTy = lvalue.getAddress().getElementType();
86 } else {
88 cgf.cgm.errorNYI(loc, "AtomicInfo::getAtomicAddress: non-simple lvalue");
89 }
90 return Address(getAtomicPointer(), elemTy, getAtomicAlignment());
91 }
92
93 /// Is the atomic size larger than the underlying value type?
94 ///
95 /// Note that the absence of padding does not mean that atomic
96 /// objects are completely interchangeable with non-atomic
97 /// objects: we might have promoted the alignment of a type
98 /// without making it bigger.
99 bool hasPadding() const { return (valueSizeInBits != atomicSizeInBits); }
100
101 bool emitMemSetZeroIfNecessary() const;
102
103 mlir::Value getScalarRValValueOrNull(RValue rvalue) const;
104
105 /// Cast the given pointer to an integer pointer suitable for atomic
106 /// operations on the source.
107 Address castToAtomicIntPointer(Address addr) const;
108
109 /// If addr is compatible with the iN that will be used for an atomic
110 /// operation, bitcast it. Otherwise, create a temporary that is suitable and
111 /// copy the value across.
112 Address convertToAtomicIntPointer(Address addr, mlir::Location loc) const;
113
114 /// Turn an atomic-layout object into an r-value.
115 RValue convertAtomicTempToRValue(Address addr, AggValueSlot resultSlot,
116 SourceLocation loc, bool asValue) const;
117
118 /// Converts a rvalue to integer value.
119 mlir::Value convertRValueToInt(RValue rvalue, mlir::Location loc,
120 bool cmpxchg = false) const;
121
122 RValue convertToValueOrAtomic(mlir::Value intVal, AggValueSlot resultSlot,
123 SourceLocation loc, bool asValue,
124 bool cmpxchg = false) const;
125
126 /// Copy an atomic r-value into atomic-layout memory.
127 void emitCopyIntoMemory(RValue rvalue) const;
128
129 /// Project an l-value down to the value field.
130 LValue projectValue() const {
131 assert(lvalue.isSimple());
132 Address addr = getAtomicAddress();
133 if (hasPadding())
134 addr = cgf.getBuilder().createGetMember(loc, addr, /*name=*/"value",
135 /*index=*/0,
136 cgf.cgm.getDataLayout());
137
139 return LValue::makeAddr(addr, getValueType(), lvalue.getBaseInfo());
140 }
141
142 /// Emits atomic load.
143 /// \returns Loaded value.
144 RValue emitAtomicLoad(AggValueSlot resultSlot, SourceLocation loc,
145 bool asValue, cir::MemOrder order, bool isVolatile);
146
147 /// Materialize an atomic r-value in atomic-layout memory.
148 Address materializeRValue(RValue rvalue, mlir::Location loc) const;
149
150 /// Creates temp alloca for intermediate operations on atomic value.
151 Address createTempAlloca() const;
152
153private:
154 bool requiresMemSetZero(mlir::Type ty) const;
155
156 /// Emits atomic load as a CIR operation.
157 mlir::Value emitAtomicLoadOp(cir::MemOrder order, bool isVolatile,
158 bool cmpxchg = false);
159};
160} // namespace
161
162/// Attach the AMDGPU atomic metadata markers that the current atomic options
163/// call for. The "no.X" metadata is emitted when the corresponding option is
164/// off, since it asserts the absence of that memory kind. The clang::atomic
165/// attribute is what turns the options on and off.
166static void setAMDGPUAtomicMetadata(CIRGenFunction &cgf, mlir::Operation *op,
167 const AtomicExpr *expr) {
168 // TODO: AMDGPUTargetCodeGenInfo::setTargetAtomicMetadata also calls
169 // CGF.AddAMDGPUAvailableVisibleMMRA on every atomic instruction; this is
170 // tied to the AMDGPUAvailableVisible statement attribute, which
171 // CIRGenStmt.cpp's emitAttributedStmt currently rejects via errorNYI.
173
174 const llvm::Triple &triple = cgf.cgm.getTriple();
175 bool isAMDGCN = triple.isAMDGCN();
176 bool isAMDSPIRV = triple.isSPIRV() && triple.getVendor() == llvm::Triple::AMD;
177 if (!isAMDGCN && !isAMDSPIRV)
178 return;
179
180 // Lowering keeps this only on a flat pointer.
181 mlir::UnitAttr unit = cgf.getBuilder().getUnitAttr();
182 if (isAMDGCN && expr->threadPrivateMemoryAtomicsAreUndefined())
183 op->setAttr(cir::CIRDialect::getAMDGPUNoPrivateAddrSpaceAttrName(), unit);
184
185 // Only a read-modify-write instruction carries these; a plain load, store or
186 // cmpxchg does not.
187 if (!mlir::isa<cir::AtomicFetchOp, cir::AtomicXchgOp>(op))
188 return;
189
190 clang::AtomicOptions atomicOpts = cgf.cgm.getAtomicOpts();
192 op->setAttr(cir::CIRDialect::getAMDGPUNoFineGrainedMemoryAttrName(), unit);
194 op->setAttr(cir::CIRDialect::getAMDGPUNoRemoteMemoryAttrName(), unit);
195 // Denormal flushing only matters for a float add.
196 auto fetchOp = mlir::dyn_cast<cir::AtomicFetchOp>(op);
197 if (fetchOp &&
199 fetchOp.getBinop() == cir::AtomicFetchKind::Add &&
200 mlir::isa<cir::SingleType>(fetchOp.getVal().getType()))
201 op->setAttr(cir::CIRDialect::getAMDGPUIgnoreDenormalModeAttrName(), unit);
202}
203
204// This function emits any expression (scalar, complex, or aggregate)
205// into a temporary alloca.
207 Address declPtr = cgf.createMemTemp(
208 e->getType(), cgf.getLoc(e->getSourceRange()), ".atomictmp");
209 cgf.emitAnyExprToMem(e, declPtr, e->getType().getQualifiers(),
210 /*Init*/ true);
211 return declPtr;
212}
213
214/// Does a store of the given IR type modify the full expected width?
215static bool isFullSizeType(CIRGenModule &cgm, mlir::Type ty,
216 uint64_t expectedSize) {
217 return cgm.getDataLayout().getTypeStoreSize(ty) * 8 == expectedSize;
218}
219
220/// Does the atomic type require memsetting to zero before initialization?
221///
222/// The IR type is provided as a way of making certain queries faster.
223bool AtomicInfo::requiresMemSetZero(mlir::Type ty) const {
224 // If the atomic type has size padding, we definitely need a memset.
225 if (hasPadding())
226 return true;
227
228 // Otherwise, do some simple heuristics to try to avoid it:
229 switch (getEvaluationKind()) {
230 // For scalars and complexes, check whether the store size of the
231 // type uses the full size.
232 case cir::TEK_Scalar:
233 return !isFullSizeType(cgf.cgm, ty, atomicSizeInBits);
234 case cir::TEK_Complex:
235 return !isFullSizeType(cgf.cgm,
236 mlir::cast<cir::ComplexType>(ty).getElementType(),
237 atomicSizeInBits / 2);
238 // Padding in structs has an undefined bit pattern. User beware.
240 return false;
241 }
242 llvm_unreachable("bad evaluation kind");
243}
244
245Address AtomicInfo::convertToAtomicIntPointer(Address addr,
246 mlir::Location loc) const {
247 mlir::Type ty = addr.getElementType();
248 uint64_t sourceSizeInBits = cgf.cgm.getDataLayout().getTypeSizeInBits(ty);
249 if (sourceSizeInBits != atomicSizeInBits) {
250 CIRGenBuilderTy &builder = cgf.getBuilder();
251
252 Address tmp = createTempAlloca();
253 mlir::Value zero = builder.getConstInt(loc, cgf.cgm.uInt8Ty, 0);
254 unsigned size =
255 cgf.getContext().toCharUnitsFromBits(atomicSizeInBits).getQuantity();
256 mlir::Value memSetSize = builder.getConstInt(loc, cgf.cgm.uInt64Ty, size);
257 addr = addr.withElementType(builder, cgf.cgm.voidTy);
258 tmp = tmp.withElementType(builder, cgf.cgm.voidTy);
259 builder.createMemSet(loc, tmp, zero, memSetSize);
260
261 builder.createMemCpy(
262 loc, tmp, addr,
263 builder.getConstInt(loc, cgf.cgm.uInt64Ty,
264 std::min(atomicSizeInBits, sourceSizeInBits) / 8));
265 addr = tmp;
266 }
267
268 return castToAtomicIntPointer(addr);
269}
270
271RValue AtomicInfo::convertAtomicTempToRValue(Address addr,
272 AggValueSlot resultSlot,
273 SourceLocation loc,
274 bool asValue) const {
275 if (lvalue.isSimple()) {
276 if (evaluationKind == TEK_Aggregate)
277 return resultSlot.asRValue();
278
279 // Drill into the padding structure if we have one.
280 if (hasPadding()) {
281 cgf.cgm.errorNYI(loc,
282 "AtomicInfo::convertAtomicTempToRValue: hasPadding");
283 return RValue::get(nullptr);
284 }
285
286 // Otherwise, just convert the temporary to an r-value using the
287 // normal conversion routine.
288 return cgf.convertTempToRValue(addr, getValueType(), loc);
289 }
290
291 cgf.cgm.errorNYI(
292 loc, "AtomicInfo::convertAtomicTempToRValue: lvalue is not simple");
293 return RValue::get(nullptr);
294}
295
296RValue AtomicInfo::emitAtomicLoad(AggValueSlot resultSlot, SourceLocation loc,
297 bool asValue, cir::MemOrder order,
298 bool isVolatile) {
299 // Check whether we should use a library call.
300 if (shouldUseLibCall()) {
302 cgf.cgm.errorNYI(loc, "emitAtomicLoad: emit atomic lib call");
303 return RValue::get(nullptr);
304 }
305
306 // Okay, we're doing this natively.
307 mlir::Value loadOp = emitAtomicLoadOp(order, isVolatile);
308
309 // If we're ignoring an aggregate return, don't do anything.
310 if (getEvaluationKind() == TEK_Aggregate && resultSlot.isIgnored())
311 return RValue::getAggregate(Address::invalid(), false);
312
313 // Okay, turn that back into the original value or atomic (for non-simple
314 // lvalues) type.
315 return convertToValueOrAtomic(loadOp, resultSlot, loc, asValue);
316}
317
318Address AtomicInfo::createTempAlloca() const {
319 // Remove addrspace info from the atomic pointer element when making the
320 // alloca pointer element.
321 QualType tmpTy = (lvalue.isBitField() && valueSizeInBits > atomicSizeInBits)
322 ? valueTy
323 : atomicTy.getUnqualifiedType();
324 Address tempAlloca =
325 cgf.createMemTemp(tmpTy, getAtomicAlignment(), loc, "atomic-temp");
326
327 // Cast to pointer to value type for bitfields.
328 if (lvalue.isBitField()) {
329 cgf.cgm.errorNYI(loc, "AtomicInfo::createTempAlloca: bitfield lvalue");
330 }
331
332 return tempAlloca;
333}
334
335mlir::Value AtomicInfo::getScalarRValValueOrNull(RValue rvalue) const {
336 if (rvalue.isScalar() && (!hasPadding() || !lvalue.isSimple()))
337 return rvalue.getValue();
338 return nullptr;
339}
340
341Address AtomicInfo::castToAtomicIntPointer(Address addr) const {
342 auto intTy = mlir::dyn_cast<cir::IntType>(addr.getElementType());
343 // Don't bother with int casts if the integer size is the same.
344 if (intTy && intTy.getWidth() == atomicSizeInBits)
345 return addr;
346 auto ty = cgf.getBuilder().getUIntNTy(atomicSizeInBits);
347 return addr.withElementType(cgf.getBuilder(), ty);
348}
349
350bool AtomicInfo::emitMemSetZeroIfNecessary() const {
351 assert(lvalue.isSimple());
352 Address addr = lvalue.getAddress();
353 if (!requiresMemSetZero(addr.getElementType()))
354 return false;
355
356 addr = addr.withElementType(cgf.getBuilder(), cgf.cgm.voidTy);
357 mlir::Value zero = cgf.getBuilder().getConstInt(loc, cgf.cgm.uInt8Ty, 0);
358 mlir::Value memSetSize = cgf.getBuilder().getConstInt(
359 loc, cgf.cgm.uInt64Ty,
360 cgf.getContext().toCharUnitsFromBits(atomicSizeInBits).getQuantity());
361
362 cgf.getBuilder().createMemSet(loc, addr, zero, memSetSize);
363 return true;
364}
365
366/// Return true if \param valueTy is a type that should be casted to integer
367/// around the atomic memory operation. If \param cmpxchg is true, then the
368/// cast of a floating point type is made as that instruction can not have
369/// floating point operands. TODO: Allow compare-and-exchange and FP - see
370/// comment in CIRGenAtomicExpandPass.cpp.
371static bool shouldCastToInt(mlir::Type valueTy, bool cmpxchg) {
372 if (cir::isAnyFloatingPointType(valueTy))
373 return isa<cir::FP80Type>(valueTy) || cmpxchg;
374 return !isa<cir::IntType>(valueTy) && !isa<cir::PointerType>(valueTy);
375}
376
377mlir::Value AtomicInfo::emitAtomicLoadOp(cir::MemOrder order, bool isVolatile,
378 bool cmpxchg) {
379 Address addr = getAtomicAddress();
380 if (shouldCastToInt(addr.getElementType(), cmpxchg))
381 addr = castToAtomicIntPointer(addr);
382
383 cir::LoadOp op =
384 cgf.getBuilder().createLoad(loc, addr, /*isVolatile=*/isVolatile);
385 op.setMemOrder(order);
386
388 return op;
389}
390
391mlir::Value AtomicInfo::convertRValueToInt(RValue rvalue, mlir::Location loc,
392 bool cmpxchg) const {
393 // If we've got a scalar value of the right size, try to avoid going
394 // through memory. Floats get casted if needed by AtomicExpandPass.
395 if (mlir::Value value = getScalarRValValueOrNull(rvalue)) {
396 if (!shouldCastToInt(value.getType(), cmpxchg))
397 return cgf.emitToMemory(value, valueTy);
398
399 cgf.cgm.errorNYI(
400 loc, "AtomicInfo::convertRValueToInt: cast scalar rvalue to int");
401 return nullptr;
402 }
403
404 // Otherwise, we need to go through memory.
405 // Put the r-value in memory.
406 Address addr = materializeRValue(rvalue, loc);
407
408 // Cast the temporary to the atomic int type and pull a value out.
409 addr = castToAtomicIntPointer(addr);
410
411 return cgf.getBuilder().createLoad(loc, addr);
412}
413
414RValue AtomicInfo::convertToValueOrAtomic(mlir::Value intVal,
415 AggValueSlot resultSlot,
416 SourceLocation loc, bool asValue,
417 bool cmpxchg) const {
418 // Try not to in some easy cases.
419 assert((mlir::isa<cir::IntType, cir::PointerType, cir::FPTypeInterface>(
420 intVal.getType())) &&
421 "Expected integer, pointer or floating point value when converting "
422 "result.");
423 bool isWholeValue =
424 !lvalue.isBitField() || lvalue.getBitFieldInfo().size == valueSizeInBits;
425 if (getEvaluationKind() == TEK_Scalar &&
426 ((isWholeValue && !hasPadding()) || !asValue)) {
427 mlir::Type valTy = asValue ? cgf.convertTypeForMem(valueTy)
428 : getAtomicAddress().getElementType();
429 if (!shouldCastToInt(valTy, cmpxchg)) {
430 assert((!mlir::isa<cir::IntType>(valTy) || intVal.getType() == valTy) &&
431 "Different integer types.");
432 return RValue::get(cgf.emitFromMemory(intVal, valueTy));
433 }
434
435 cgf.cgm.errorNYI("convertToValueOrAtomic: convert through bitcast");
436 return RValue::get(nullptr);
437 }
438
439 // Create a temporary. This needs to be big enough to hold the
440 // atomic integer.
441 Address temp = Address::invalid();
442 bool tempIsVolatile = false;
443 if (asValue && getEvaluationKind() == TEK_Aggregate) {
444 assert(!resultSlot.isIgnored());
445 temp = resultSlot.getAddress();
446 tempIsVolatile = resultSlot.isVolatile();
447 } else {
448 temp = createTempAlloca();
449 }
450
451 // Slam the integer into the temporary.
452 Address castTemp = castToAtomicIntPointer(temp);
453 cgf.getBuilder().createStore(cgf.getLoc(loc), intVal, castTemp,
454 tempIsVolatile);
455 return convertAtomicTempToRValue(temp, resultSlot, loc, asValue);
456}
457
458/// Copy an r-value into memory as part of storing to an atomic type.
459/// This needs to create a bit-pattern suitable for atomic operations.
460void AtomicInfo::emitCopyIntoMemory(RValue rvalue) const {
461 assert(lvalue.isSimple());
462
463 // If we have an r-value, the rvalue should be of the atomic type,
464 // which means that the caller is responsible for having zeroed
465 // any padding. Just do an aggregate copy of that type.
466 if (rvalue.isAggregate()) {
467 cgf.cgm.errorNYI("copying aggregate into atomic lvalue");
468 return;
469 }
470
471 // Okay, otherwise we're copying stuff.
472
473 // Zero out the buffer if necessary.
474 emitMemSetZeroIfNecessary();
475
476 // Drill past the padding if present.
477 LValue tempLValue = projectValue();
478
479 // Okay, store the rvalue in.
480 if (rvalue.isScalar()) {
481 cgf.emitStoreOfScalar(rvalue.getValue(), tempLValue, /*isInit=*/true);
482 } else {
483 cgf.emitStoreOfComplex(loc, rvalue.getComplexValue(), tempLValue,
484 /*isInit=*/true);
485 }
486}
487
488/// Materialize an r-value into memory for the purposes of storing it
489/// to an atomic type.
490Address AtomicInfo::materializeRValue(RValue rvalue, mlir::Location loc) const {
491 // Aggregate r-values are already in memory, and EmitAtomicStore
492 // requires them to be values of the atomic type.
493 if (rvalue.isAggregate())
494 return rvalue.getAggregateAddress();
495
496 // Otherwise, make a temporary and materialize into it.
497 LValue tempLV = cgf.makeAddrLValue(createTempAlloca(), getAtomicType());
498 AtomicInfo atomics(cgf, tempLV, loc);
499
500 atomics.emitCopyIntoMemory(rvalue);
501 return tempLV.getAddress();
502}
503
504static void emitDefaultCaseLabel(CIRGenBuilderTy &builder, mlir::Location loc) {
505 mlir::ArrayAttr valuesAttr = builder.getArrayAttr({});
506 mlir::OpBuilder::InsertPoint insertPoint;
507 cir::CaseOp::create(builder, loc, valuesAttr, cir::CaseOpKind::Default,
508 insertPoint);
509 builder.restoreInsertionPoint(insertPoint);
510}
511
512// Create a "case" operation with the given list of orders as its values. Also
513// create the region that will hold the body of the switch-case label.
514static void emitMemOrderCaseLabel(CIRGenBuilderTy &builder, mlir::Location loc,
515 mlir::Type orderType,
518 for (cir::MemOrder order : orders)
519 orderAttrs.push_back(cir::IntAttr::get(orderType, static_cast<int>(order)));
520 mlir::ArrayAttr ordersAttr = builder.getArrayAttr(orderAttrs);
521
522 mlir::OpBuilder::InsertPoint insertPoint;
523 cir::CaseOp::create(builder, loc, ordersAttr, cir::CaseOpKind::Anyof,
524 insertPoint);
525 builder.restoreInsertionPoint(insertPoint);
526}
527
528static void emitAtomicCmpXchg(CIRGenFunction &cgf, AtomicExpr *e, bool isWeak,
529 Address dest, Address ptr, Address val1,
530 Address val2, Address expectedResult,
531 uint64_t size, cir::MemOrder successOrder,
532 cir::MemOrder failureOrder,
533 cir::SyncScopeKind scope) {
534 mlir::Location loc = cgf.getLoc(e->getSourceRange());
535
536 CIRGenBuilderTy &builder = cgf.getBuilder();
537 mlir::Value expected = builder.createLoad(loc, val1);
538 mlir::Value desired = builder.createLoad(loc, val2);
539
540 auto cmpxchg = cir::AtomicCmpXchgOp::create(
541 builder, loc, expected.getType(), builder.getBoolTy(), ptr.getPointer(),
542 expected, desired,
543 cir::MemOrderAttr::get(&cgf.getMLIRContext(), successOrder),
544 cir::MemOrderAttr::get(&cgf.getMLIRContext(), failureOrder),
545 cir::SyncScopeKindAttr::get(&cgf.getMLIRContext(), scope),
546 builder.getI64IntegerAttr(ptr.getAlignment().getAsAlign().value()));
547
548 cmpxchg.setIsVolatile(e->isVolatile());
549 cmpxchg.setWeak(isWeak);
550 setAMDGPUAtomicMetadata(cgf, cmpxchg, e);
551
552 mlir::Value failed = builder.createNot(cmpxchg.getSuccess());
553 cir::IfOp::create(
554 builder, loc, failed, /*withElseRegion=*/false,
555 [&](mlir::OpBuilder &, mlir::Location) {
556 uint64_t expectedSizeInBytes = cgf.cgm.getDataLayout().getTypeStoreSize(
557 expectedResult.getElementType());
558
559 if (expectedSizeInBytes == size) {
560 Address storeAddr = expectedResult.withElementType(
561 builder, cmpxchg.getOld().getType());
562 builder.createStore(loc, cmpxchg.getOld(), storeAddr);
564 } else {
565 Address oldTmp = cgf.createTempAlloca(
566 cmpxchg.getOld().getType(), ptr.getAlignment(), loc, "old.tmp");
567 builder.createStore(loc, cmpxchg.getOld(), oldTmp);
569
570 Address oldTmpVoid = oldTmp.withElementType(builder, cgf.cgm.voidTy);
571 Address expectedVoid =
572 expectedResult.withElementType(builder, cgf.cgm.voidTy);
573 builder.createMemCpy(
574 loc, expectedVoid, oldTmpVoid,
575 builder.getConstInt(loc, cgf.cgm.uInt64Ty, expectedSizeInBytes));
576 }
577 builder.createYield(loc);
578 });
579
580 // Update the memory at Dest with Success's value.
581 cgf.emitStoreOfScalar(cmpxchg.getSuccess(),
582 cgf.makeAddrLValue(dest, e->getType()),
583 /*isInit=*/false);
584}
585
587 CIRGenFunction &cgf, AtomicExpr *e, bool isWeak, Address dest, Address ptr,
588 Address val1, Address val2, Address expectedResult, Expr *failureOrderExpr,
589 uint64_t size, cir::MemOrder successOrder, cir::SyncScopeKind scope) {
590 Expr::EvalResult failureOrderEval;
591 if (failureOrderExpr->EvaluateAsInt(failureOrderEval, cgf.getContext())) {
592 uint64_t failureOrderInt = failureOrderEval.Val.getInt().getZExtValue();
593
594 cir::MemOrder failureOrder;
595 if (!cir::isValidCIRAtomicOrderingCABI(failureOrderInt)) {
596 failureOrder = cir::MemOrder::Relaxed;
597 } else {
598 switch ((cir::MemOrder)failureOrderInt) {
599 case cir::MemOrder::Relaxed:
600 // 31.7.2.18: "The failure argument shall not be memory_order_release
601 // nor memory_order_acq_rel". Fallback to monotonic.
602 case cir::MemOrder::Release:
603 case cir::MemOrder::AcquireRelease:
604 failureOrder = cir::MemOrder::Relaxed;
605 break;
606 case cir::MemOrder::Consume:
607 case cir::MemOrder::Acquire:
608 failureOrder = cir::MemOrder::Acquire;
609 break;
610 case cir::MemOrder::SequentiallyConsistent:
611 failureOrder = cir::MemOrder::SequentiallyConsistent;
612 break;
613 }
614 }
615
616 // Prior to c++17, "the failure argument shall be no stronger than the
617 // success argument". This condition has been lifted and the only
618 // precondition is 31.7.2.18. Effectively treat this as a DR and skip
619 // language version checks.
620 emitAtomicCmpXchg(cgf, e, isWeak, dest, ptr, val1, val2, expectedResult,
621 size, successOrder, failureOrder, scope);
622 return;
623 }
624
625 // The failure memory order is not a compile time constant. The CIR atomic ops
626 // require a constant value, so that memory order is known at compile time. In
627 // this case, we can switch based on the memory order and call each variant
628 // individually.
629 mlir::Value failureOrderVal = cgf.emitScalarExpr(failureOrderExpr);
630 mlir::Location atomicLoc = cgf.getLoc(e->getSourceRange());
631 cir::SwitchOp::create(
632 cgf.getBuilder(), atomicLoc, failureOrderVal,
633 [&](mlir::OpBuilder &b, mlir::Location loc, mlir::OperationState &os) {
634 mlir::Block *switchBlock = cgf.getBuilder().getBlock();
635
636 // case cir::MemOrder::Relaxed:
637 // // 31.7.2.18: "The failure argument shall not be
638 // memory_order_release
639 // // nor memory_order_acq_rel". Fallback to monotonic.
640 // case cir::MemOrder::Release:
641 // case cir::MemOrder::AcquireRelease:
642 // Note: Since there are 3 options, this makes sense to just emit as a
643 // 'default', which prevents user code from 'falling off' of this,
644 // which seems reasonable. Also, 'relaxed' being the default behavior
645 // is also probably the least harmful.
646 emitDefaultCaseLabel(cgf.getBuilder(), atomicLoc);
647 emitAtomicCmpXchg(cgf, e, isWeak, dest, ptr, val1, val2, expectedResult,
648 size, successOrder, cir::MemOrder::Relaxed, scope);
649 cgf.getBuilder().createBreak(atomicLoc);
650 cgf.getBuilder().setInsertionPointToEnd(switchBlock);
651
652 // case cir::MemOrder::Consume:
653 // case cir::MemOrder::Acquire:
654 emitMemOrderCaseLabel(cgf.getBuilder(), loc, failureOrderVal.getType(),
655 {cir::MemOrder::Consume, cir::MemOrder::Acquire});
656 emitAtomicCmpXchg(cgf, e, isWeak, dest, ptr, val1, val2, expectedResult,
657 size, successOrder, cir::MemOrder::Acquire, scope);
658 cgf.getBuilder().createBreak(atomicLoc);
659 cgf.getBuilder().setInsertionPointToEnd(switchBlock);
660
661 // case cir::MemOrder::SequentiallyConsistent:
662 emitMemOrderCaseLabel(cgf.getBuilder(), loc, failureOrderVal.getType(),
663 {cir::MemOrder::SequentiallyConsistent});
664 emitAtomicCmpXchg(cgf, e, isWeak, dest, ptr, val1, val2, expectedResult,
665 size, successOrder,
666 cir::MemOrder::SequentiallyConsistent, scope);
667 cgf.getBuilder().createBreak(atomicLoc);
668 cgf.getBuilder().setInsertionPointToEnd(switchBlock);
669
670 cgf.getBuilder().createYield(atomicLoc);
671 });
672}
673
674// A version of the emitAtomicCmpXchgFailureSet function that ALSO checks
675// whether it is 'weak' or not (by adding an 'if' around it, and calling
676// emitAtomicCmpXchgFailureSet 2x).
678 CIRGenFunction &cgf, AtomicExpr *e, Expr *isWeakExpr, Address dest,
679 Address ptr, Address val1, Address val2, Address expectedResult,
680 Expr *failureOrderExpr, uint64_t size, cir::MemOrder successOrder,
681 cir::SyncScopeKind scope) {
682 mlir::Value isWeakVal = cgf.emitScalarExpr(isWeakExpr);
683 // The AST seems to be inserting a 'bool' cast (even in C mode) here, so we'll
684 // just emit it like a scalar.
685 assert(isWeakVal.getType() == cgf.getBuilder().getBoolTy());
686 mlir::Location atomicLoc = cgf.getLoc(e->getSourceRange());
687
688 // Unlike classic compiler, we use an 'if' here instead of a switch, simply to
689 // make this more readable/logical, plus we don't allow switch over a bool in
690 // CIR.
691 cir::IfOp::create(
692 cgf.getBuilder(), atomicLoc, isWeakVal, /*elseRegion=*/true,
693 [&](mlir::OpBuilder &b, mlir::Location loc) {
694 emitAtomicCmpXchgFailureSet(cgf, e, /*isWeak=*/true, dest, ptr, val1,
695 val2, expectedResult, failureOrderExpr,
696 size, successOrder, scope);
697 cgf.getBuilder().createYield(atomicLoc);
698 },
699 [&](mlir::OpBuilder &b, mlir::Location loc) {
700 emitAtomicCmpXchgFailureSet(cgf, e, /*isWeak=*/false, dest, ptr, val1,
701 val2, expectedResult, failureOrderExpr,
702 size, successOrder, scope);
703 cgf.getBuilder().createYield(atomicLoc);
704 });
705}
706
708 Address ptr, Address val1, Address val2,
709 Address expectedResult, Expr *isWeakExpr,
710 Expr *failureOrderExpr, int64_t size,
711 cir::MemOrder order, cir::SyncScopeKind scope) {
713 llvm::StringRef opName;
714
715 CIRGenBuilderTy &builder = cgf.getBuilder();
716 mlir::Location loc = cgf.getLoc(expr->getSourceRange());
717 auto orderAttr = cir::MemOrderAttr::get(builder.getContext(), order);
718 auto scopeAttr = cir::SyncScopeKindAttr::get(builder.getContext(), scope);
719 cir::AtomicFetchKindAttr fetchAttr;
720 bool fetchFirst = true;
721
722 auto handleFetchOp = [&](cir::AtomicFetchKind kind) {
723 opName = cir::AtomicFetchOp::getOperationName();
724 fetchAttr = cir::AtomicFetchKindAttr::get(builder.getContext(), kind);
725 };
726
727 switch (expr->getOp()) {
728 case AtomicExpr::AO__c11_atomic_init:
729 llvm_unreachable("already handled!");
730
731 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
732 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
733 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
734 emitAtomicCmpXchgFailureSet(cgf, expr, /*isWeak=*/false, dest, ptr, val1,
735 val2, expectedResult, failureOrderExpr, size,
736 order, scope);
737 return;
738
739 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
740 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
741 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
742 emitAtomicCmpXchgFailureSet(cgf, expr, /*isWeak=*/true, dest, ptr, val1,
743 val2, expectedResult, failureOrderExpr, size,
744 order, scope);
745 return;
746
747 case AtomicExpr::AO__atomic_compare_exchange:
748 case AtomicExpr::AO__atomic_compare_exchange_n:
749 case AtomicExpr::AO__scoped_atomic_compare_exchange:
750 case AtomicExpr::AO__scoped_atomic_compare_exchange_n: {
751 bool isWeak = false;
752 if (isWeakExpr->EvaluateAsBooleanCondition(isWeak, cgf.getContext())) {
753 emitAtomicCmpXchgFailureSet(cgf, expr, isWeak, dest, ptr, val1, val2,
754 expectedResult, failureOrderExpr, size, order,
755 scope);
756 } else {
758 cgf, expr, isWeakExpr, dest, ptr, val1, val2, expectedResult,
759 failureOrderExpr, size, order, scope);
760 }
761 return;
762 }
763
764 case AtomicExpr::AO__c11_atomic_load:
765 case AtomicExpr::AO__atomic_load_n:
766 case AtomicExpr::AO__atomic_load:
767 case AtomicExpr::AO__scoped_atomic_load_n:
768 case AtomicExpr::AO__scoped_atomic_load:
769 case AtomicExpr::AO__hip_atomic_load:
770 case AtomicExpr::AO__opencl_atomic_load: {
771 cir::LoadOp load =
772 builder.createLoad(loc, ptr, /*isVolatile=*/expr->isVolatile());
773
774 load->setAttr("mem_order", orderAttr);
775 load->setAttr("sync_scope", scopeAttr);
776
777 builder.createStore(loc, load->getResult(0), dest);
778 return;
779 }
780
781 case AtomicExpr::AO__c11_atomic_store:
782 case AtomicExpr::AO__atomic_store_n:
783 case AtomicExpr::AO__atomic_store:
784 case AtomicExpr::AO__scoped_atomic_store:
785 case AtomicExpr::AO__scoped_atomic_store_n:
786 case AtomicExpr::AO__hip_atomic_store:
787 case AtomicExpr::AO__opencl_atomic_store: {
788 cir::LoadOp loadVal1 = builder.createLoad(loc, val1);
789
791
792 builder.createStore(loc, loadVal1, ptr, expr->isVolatile(),
793 /*isNontemporal=*/false,
794 /*align=*/mlir::IntegerAttr{}, scopeAttr, orderAttr);
795 return;
796 }
797
798 case AtomicExpr::AO__c11_atomic_exchange:
799 case AtomicExpr::AO__atomic_exchange_n:
800 case AtomicExpr::AO__atomic_exchange:
801 case AtomicExpr::AO__scoped_atomic_exchange_n:
802 case AtomicExpr::AO__scoped_atomic_exchange:
803 case AtomicExpr::AO__hip_atomic_exchange:
804 case AtomicExpr::AO__opencl_atomic_exchange:
805 opName = cir::AtomicXchgOp::getOperationName();
806 break;
807
808 case AtomicExpr::AO__atomic_add_fetch:
809 case AtomicExpr::AO__scoped_atomic_add_fetch:
810 fetchFirst = false;
811 [[fallthrough]];
812 case AtomicExpr::AO__c11_atomic_fetch_add:
813 case AtomicExpr::AO__atomic_fetch_add:
814 case AtomicExpr::AO__scoped_atomic_fetch_add:
815 case AtomicExpr::AO__hip_atomic_fetch_add:
816 case AtomicExpr::AO__opencl_atomic_fetch_add:
817 handleFetchOp(cir::AtomicFetchKind::Add);
818 break;
819
820 case AtomicExpr::AO__atomic_sub_fetch:
821 case AtomicExpr::AO__scoped_atomic_sub_fetch:
822 fetchFirst = false;
823 [[fallthrough]];
824 case AtomicExpr::AO__c11_atomic_fetch_sub:
825 case AtomicExpr::AO__atomic_fetch_sub:
826 case AtomicExpr::AO__scoped_atomic_fetch_sub:
827 case AtomicExpr::AO__hip_atomic_fetch_sub:
828 case AtomicExpr::AO__opencl_atomic_fetch_sub:
829 handleFetchOp(cir::AtomicFetchKind::Sub);
830 break;
831
832 case AtomicExpr::AO__atomic_min_fetch:
833 case AtomicExpr::AO__scoped_atomic_min_fetch:
834 fetchFirst = false;
835 [[fallthrough]];
836 case AtomicExpr::AO__c11_atomic_fetch_min:
837 case AtomicExpr::AO__atomic_fetch_min:
838 case AtomicExpr::AO__scoped_atomic_fetch_min:
839 case AtomicExpr::AO__hip_atomic_fetch_min:
840 case AtomicExpr::AO__opencl_atomic_fetch_min:
841 handleFetchOp(cir::AtomicFetchKind::Min);
842 break;
843
844 case AtomicExpr::AO__atomic_fetch_fminimum:
845 case AtomicExpr::AO__scoped_atomic_fetch_fminimum:
846 assert(expr->getValueType()->isFloatingType() &&
847 "fminimum operations only support floating-point types");
848 handleFetchOp(cir::AtomicFetchKind::Minimum);
849 break;
850
851 case AtomicExpr::AO__atomic_fetch_fminimum_num:
852 case AtomicExpr::AO__scoped_atomic_fetch_fminimum_num:
853 assert(expr->getValueType()->isFloatingType() &&
854 "fminimum_num operations only support floating-point types");
855 handleFetchOp(cir::AtomicFetchKind::MinimumNum);
856 break;
857
858 case AtomicExpr::AO__atomic_max_fetch:
859 case AtomicExpr::AO__scoped_atomic_max_fetch:
860 fetchFirst = false;
861 [[fallthrough]];
862 case AtomicExpr::AO__c11_atomic_fetch_max:
863 case AtomicExpr::AO__atomic_fetch_max:
864 case AtomicExpr::AO__scoped_atomic_fetch_max:
865 case AtomicExpr::AO__hip_atomic_fetch_max:
866 case AtomicExpr::AO__opencl_atomic_fetch_max:
867 handleFetchOp(cir::AtomicFetchKind::Max);
868 break;
869
870 case AtomicExpr::AO__atomic_fetch_fmaximum:
871 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum:
872 assert(expr->getValueType()->isFloatingType() &&
873 "fmaximum operations only support floating-point types");
874 handleFetchOp(cir::AtomicFetchKind::Maximum);
875 break;
876
877 case AtomicExpr::AO__atomic_fetch_fmaximum_num:
878 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum_num:
879 assert(expr->getValueType()->isFloatingType() &&
880 "fmaximum_num operations only support floating-point types");
881 handleFetchOp(cir::AtomicFetchKind::MaximumNum);
882 break;
883
884 case AtomicExpr::AO__atomic_and_fetch:
885 case AtomicExpr::AO__scoped_atomic_and_fetch:
886 fetchFirst = false;
887 [[fallthrough]];
888 case AtomicExpr::AO__c11_atomic_fetch_and:
889 case AtomicExpr::AO__atomic_fetch_and:
890 case AtomicExpr::AO__scoped_atomic_fetch_and:
891 case AtomicExpr::AO__hip_atomic_fetch_and:
892 case AtomicExpr::AO__opencl_atomic_fetch_and:
893 handleFetchOp(cir::AtomicFetchKind::And);
894 break;
895
896 case AtomicExpr::AO__atomic_or_fetch:
897 case AtomicExpr::AO__scoped_atomic_or_fetch:
898 fetchFirst = false;
899 [[fallthrough]];
900 case AtomicExpr::AO__c11_atomic_fetch_or:
901 case AtomicExpr::AO__atomic_fetch_or:
902 case AtomicExpr::AO__scoped_atomic_fetch_or:
903 case AtomicExpr::AO__hip_atomic_fetch_or:
904 case AtomicExpr::AO__opencl_atomic_fetch_or:
905 handleFetchOp(cir::AtomicFetchKind::Or);
906 break;
907
908 case AtomicExpr::AO__atomic_xor_fetch:
909 case AtomicExpr::AO__scoped_atomic_xor_fetch:
910 fetchFirst = false;
911 [[fallthrough]];
912 case AtomicExpr::AO__c11_atomic_fetch_xor:
913 case AtomicExpr::AO__atomic_fetch_xor:
914 case AtomicExpr::AO__scoped_atomic_fetch_xor:
915 case AtomicExpr::AO__hip_atomic_fetch_xor:
916 case AtomicExpr::AO__opencl_atomic_fetch_xor:
917 handleFetchOp(cir::AtomicFetchKind::Xor);
918 break;
919
920 case AtomicExpr::AO__atomic_nand_fetch:
921 case AtomicExpr::AO__scoped_atomic_nand_fetch:
922 fetchFirst = false;
923 [[fallthrough]];
924 case AtomicExpr::AO__c11_atomic_fetch_nand:
925 case AtomicExpr::AO__atomic_fetch_nand:
926 case AtomicExpr::AO__scoped_atomic_fetch_nand:
927 handleFetchOp(cir::AtomicFetchKind::Nand);
928 break;
929
930 case AtomicExpr::AO__atomic_test_and_set: {
931 auto op = cir::AtomicTestAndSetOp::create(
932 builder, loc, ptr.getPointer(), order,
933 builder.getI64IntegerAttr(ptr.getAlignment().getQuantity()),
934 expr->isVolatile());
935 builder.createStore(loc, op, dest);
936 return;
937 }
938
939 case AtomicExpr::AO__atomic_clear: {
940 cir::AtomicClearOp::create(
941 builder, loc, ptr.getPointer(), order,
942 builder.getI64IntegerAttr(ptr.getAlignment().getQuantity()),
943 expr->isVolatile());
944 return;
945 }
946
947 case AtomicExpr::AO__atomic_fetch_uinc:
948 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
949 handleFetchOp(cir::AtomicFetchKind::UIncWrap);
950 break;
951
952 case AtomicExpr::AO__atomic_fetch_udec:
953 case AtomicExpr::AO__scoped_atomic_fetch_udec:
954 handleFetchOp(cir::AtomicFetchKind::UDecWrap);
955 break;
956
957 case AtomicExpr::AO__opencl_atomic_init:
958 cgf.cgm.errorNYI(expr->getSourceRange(), "emitAtomicOp: expr op NYI");
959 return;
960 }
961
962 assert(!opName.empty() && "expected operation name to build");
963 mlir::Value loadVal1 = builder.createLoad(loc, val1);
964
965 SmallVector<mlir::Value> atomicOperands = {ptr.getPointer(), loadVal1};
966 SmallVector<mlir::Type> atomicResTys = {loadVal1.getType()};
967 mlir::Operation *rmwOp = builder.create(loc, builder.getStringAttr(opName),
968 atomicOperands, atomicResTys);
969
970 if (fetchAttr)
971 rmwOp->setAttr("binop", fetchAttr);
972 rmwOp->setAttr("mem_order", orderAttr);
973 rmwOp->setAttr("sync_scope", scopeAttr);
974 rmwOp->setAttr("alignment", builder.getAlignmentAttr(ptr.getAlignment()));
975 if (expr->isVolatile())
976 rmwOp->setAttr("is_volatile", builder.getUnitAttr());
977 if (fetchFirst && opName == cir::AtomicFetchOp::getOperationName())
978 rmwOp->setAttr("fetch_first", builder.getUnitAttr());
979
980 setAMDGPUAtomicMetadata(cgf, rmwOp, expr);
981
982 mlir::Value result = rmwOp->getResult(0);
983
984 builder.createStore(loc, result, dest);
985}
986
987// Map clang sync scope to CIR sync scope.
988static cir::SyncScopeKind convertSyncScopeToCIR(CIRGenFunction &cgf,
989 clang::SyncScope scope) {
990 switch (scope) {
992 return cir::SyncScopeKind::SingleThread;
994 return cir::SyncScopeKind::System;
996 return cir::SyncScopeKind::Device;
998 return cir::SyncScopeKind::Workgroup;
1000 return cir::SyncScopeKind::Wavefront;
1002 return cir::SyncScopeKind::Cluster;
1003
1005 return cir::SyncScopeKind::HIPSingleThread;
1007 return cir::SyncScopeKind::HIPSystem;
1009 return cir::SyncScopeKind::HIPAgent;
1011 return cir::SyncScopeKind::HIPWorkgroup;
1013 return cir::SyncScopeKind::HIPWavefront;
1015 return cir::SyncScopeKind::HIPCluster;
1016
1018 return cir::SyncScopeKind::OpenCLWorkGroup;
1020 return cir::SyncScopeKind::OpenCLDevice;
1022 return cir::SyncScopeKind::OpenCLAllSVMDevices;
1024 return cir::SyncScopeKind::OpenCLSubGroup;
1025 }
1026
1027 llvm_unreachable("unhandled sync scope");
1028}
1029
1030static std::optional<cir::MemOrder>
1031getEffectiveAtomicMemOrder(cir::MemOrder oriOrder, bool isStore, bool isLoad,
1032 bool isFence) {
1033 // Some memory orders are not supported by partial atomic operation:
1034 // {memory_order_releaxed} is not valid for fence operations.
1035 // {memory_order_consume, memory_order_acquire} are not valid for write-only
1036 // operations.
1037 // {memory_order_release} is not valid for read-only operations.
1038 // {memory_order_acq_rel} is only valid for read-write operations.
1039 if (isStore) {
1040 if (oriOrder == cir::MemOrder::Consume ||
1041 oriOrder == cir::MemOrder::Acquire ||
1042 oriOrder == cir::MemOrder::AcquireRelease)
1043 return std::nullopt;
1044 } else if (isLoad) {
1045 if (oriOrder == cir::MemOrder::Release ||
1046 oriOrder == cir::MemOrder::AcquireRelease)
1047 return std::nullopt;
1048 } else if (isFence) {
1049 if (oriOrder == cir::MemOrder::Relaxed)
1050 return std::nullopt;
1051 }
1052 // memory_order_consume is not implemented, it is always treated like
1053 // memory_order_acquire
1054 if (oriOrder == cir::MemOrder::Consume)
1055 return cir::MemOrder::Acquire;
1056 return oriOrder;
1057}
1058
1060 CIRGenFunction &cgf, mlir::Value order, bool isStore, bool isLoad,
1061 bool isFence, llvm::function_ref<void(cir::MemOrder)> emitAtomicOpFn) {
1062 if (!order)
1063 return;
1064 // The memory order is not known at compile-time. The atomic operations
1065 // can't handle runtime memory orders; the memory order must be hard coded.
1066 // Generate a "switch" statement that converts a runtime value into a
1067 // compile-time value.
1068 CIRGenBuilderTy &builder = cgf.getBuilder();
1069 cir::SwitchOp::create(
1070 builder, order.getLoc(), order,
1071 [&](mlir::OpBuilder &, mlir::Location loc, mlir::OperationState &) {
1072 mlir::Block *switchBlock = builder.getBlock();
1073
1074 auto emitMemOrderCase = [&](llvm::ArrayRef<cir::MemOrder> caseOrders) {
1075 // Checking there are same effective memory order for each case.
1076 for (int i = 1, e = caseOrders.size(); i < e; i++)
1077 assert((getEffectiveAtomicMemOrder(caseOrders[i - 1], isStore,
1078 isLoad, isFence) ==
1079 getEffectiveAtomicMemOrder(caseOrders[i], isStore, isLoad,
1080 isFence)) &&
1081 "Effective memory order must be same!");
1082 // Emit case label and atomic opeartion if neccessary.
1083 if (caseOrders.empty()) {
1084 emitDefaultCaseLabel(builder, loc);
1085 // There is no good way to report an unsupported memory order at
1086 // runtime, hence the fallback to memory_order_relaxed.
1087 if (!isFence)
1088 emitAtomicOpFn(cir::MemOrder::Relaxed);
1089 } else if (std::optional<cir::MemOrder> actualOrder =
1090 getEffectiveAtomicMemOrder(caseOrders[0], isStore,
1091 isLoad, isFence)) {
1092 // Included in default case.
1093 if (!isFence && actualOrder == cir::MemOrder::Relaxed)
1094 return;
1095 // Creating case operation for effective memory order. If there are
1096 // multiple cases in `caseOrders`, the actual order of each case
1097 // must be same, this needs to be guaranteed by the caller.
1098 emitMemOrderCaseLabel(builder, loc, order.getType(), caseOrders);
1099 emitAtomicOpFn(actualOrder.value());
1100 } else {
1101 // Do nothing if (!caseOrders.empty() && !actualOrder)
1102 return;
1103 }
1104 builder.createBreak(loc);
1105 builder.setInsertionPointToEnd(switchBlock);
1106 };
1107
1108 emitMemOrderCase(/*default:*/ {});
1109 emitMemOrderCase({cir::MemOrder::Relaxed});
1110 emitMemOrderCase({cir::MemOrder::Consume, cir::MemOrder::Acquire});
1111 emitMemOrderCase({cir::MemOrder::Release});
1112 emitMemOrderCase({cir::MemOrder::AcquireRelease});
1113 emitMemOrderCase({cir::MemOrder::SequentiallyConsistent});
1114
1115 builder.createYield(loc);
1116 });
1117}
1118
1120 CIRGenFunction &cgf, const AtomicScopeModel *scopeModel, mlir::Value scope,
1121 llvm::function_ref<void(cir::SyncScopeKind)> emitAtomicOp) {
1122 CIRGenBuilderTy &builder = cgf.getBuilder();
1123 llvm::ArrayRef<unsigned> allScopes = scopeModel->getRuntimeValues();
1124 unsigned fallback = scopeModel->getFallBackValue();
1125
1126 cir::SwitchOp::create(
1127 builder, scope.getLoc(), scope,
1128 [&](mlir::OpBuilder &, mlir::Location loc, mlir::OperationState &) {
1129 mlir::Block *switchBlock = builder.getBlock();
1130
1131 // Default case -- use fallback scope
1132 cir::SyncScopeKind fallbackScope =
1133 convertSyncScopeToCIR(cgf, scopeModel->map(fallback));
1134 emitDefaultCaseLabel(builder, loc);
1135 emitAtomicOp(fallbackScope);
1136 builder.createBreak(loc);
1137 builder.setInsertionPointToEnd(switchBlock);
1138
1139 // Emit a switch case for each non-fallback runtime scope value
1140 for (unsigned runtimeScopeValue : allScopes) {
1141 if (runtimeScopeValue == fallback)
1142 continue;
1143
1144 cir::SyncScopeKind cirScope =
1145 convertSyncScopeToCIR(cgf, scopeModel->map(runtimeScopeValue));
1146
1147 mlir::ArrayAttr casesAttr = builder.getArrayAttr(
1148 {cir::IntAttr::get(scope.getType(), runtimeScopeValue)});
1149 mlir::OpBuilder::InsertPoint insertPoint;
1150 cir::CaseOp::create(builder, loc, casesAttr, cir::CaseOpKind::Equal,
1151 insertPoint);
1152
1153 builder.restoreInsertionPoint(insertPoint);
1154 emitAtomicOp(cirScope);
1155 builder.createBreak(loc);
1156 builder.setInsertionPointToEnd(switchBlock);
1157 }
1158
1159 builder.createYield(loc);
1160 });
1161}
1162
1164 const EmittedOrderOrScope &order, bool isStore, bool isLoad, bool isFence,
1165 llvm::function_ref<void(cir::MemOrder)> emitAtomicOpFn) {
1166 if (order.eval.has_value()) {
1167 uint64_t constOrder = order.eval->Val.getInt().getZExtValue();
1168 // We should not ever get to a case where the ordering isn't a valid CABI
1169 // value, but it's hard to enforce that in general.
1170 if (!cir::isValidCIRAtomicOrderingCABI(constOrder))
1171 return;
1172 cir::MemOrder oriOrder = static_cast<cir::MemOrder>(constOrder);
1173 if (std::optional<cir::MemOrder> actualOrder =
1174 getEffectiveAtomicMemOrder(oriOrder, isStore, isLoad, isFence))
1175 emitAtomicOpFn(actualOrder.value());
1176 return;
1177 }
1178
1179 // Emit `SwitchOp` to convert dynamic value to static value.
1180 emitAtomicExprWithDynamicMemOrder(*this, order.value, isStore, isLoad,
1181 isFence, emitAtomicOpFn);
1182}
1183
1185 const AtomicScopeModel *scopeModel, const EmittedOrderOrScope &scope,
1186 llvm::function_ref<void(cir::SyncScopeKind)> emitAtomicOp) {
1187 if (!scopeModel || !scope.value) {
1188 emitAtomicOp(cir::SyncScopeKind::System);
1189 return;
1190 }
1191
1192 if (scope.eval.has_value()) {
1193 cir::SyncScopeKind mappedScope = convertSyncScopeToCIR(
1194 *this, scopeModel->map(scope.eval->Val.getInt().getZExtValue()));
1195 emitAtomicOp(mappedScope);
1196 return;
1197 }
1198
1199 // Emit a switch op to match dynamic sync scope values to static sync scopes.
1200 emitAtomicExprWithDynamicSyncScope(*this, scopeModel, scope.value,
1201 emitAtomicOp);
1202}
1203
1204static RValue emitAtomicLibCall(CIRGenFunction &cgf, llvm::StringRef funcName,
1205 QualType resultType, CallArgList &args) {
1206 const CIRGenFunctionInfo &fnInfo =
1207 cgf.cgm.getTypes().arrangeBuiltinFunctionCall(resultType, args);
1208 cir::FuncType fnTy = cgf.cgm.getTypes().getFunctionType(fnInfo);
1209
1210 mlir::NamedAttrList fnAttrs;
1212
1213 cir::FuncOp fn = cgf.cgm.createRuntimeFunction(fnTy, funcName, fnAttrs);
1214 auto callee = CIRGenCallee::forDirect(fn);
1215 return cgf.emitCall(fnInfo, callee, ReturnValueSlot(), args,
1216 /*isMustTail=*/false);
1217}
1218
1220 CIRGenFunction &cgf, AtomicExpr *e, Address atomicPtr, Address dest,
1221 Address val1, Address val2, uint64_t atomicTySize, QualType resultTy,
1222 const CIRGenFunction::EmittedOrderOrScope &successOrder) {
1223 mlir::Location loc = cgf.getLoc(e->getSourceRange());
1224
1225 CallArgList args;
1226 // For non-optimized library calls, the size is the first parameter.
1227 args.add(
1228 RValue::get(cgf.getBuilder().getConstInt(loc, cgf.sizeTy, atomicTySize)),
1229 cgf.getContext().getSizeType());
1230
1231 // The atomic address is the second parameter.
1232 // The OpenCL atomic library functions only accept pointer arguments to
1233 // generic address space.
1234 auto castToGenericAddrSpace = [&](mlir::Value v, QualType pt) {
1235 if (!e->isOpenCL())
1236 return cgf.getBuilder().createPtrBitcast(v, cgf.voidTy);
1237
1239 cgf.cgm.errorNYI(loc, "emitLibCallForAtomicExpr: openCL");
1240 return cgf.getBuilder().createPtrBitcast(v, cgf.voidTy);
1241 };
1242 args.add(RValue::get(castToGenericAddrSpace(atomicPtr.emitRawPointer(),
1243 e->getPtr()->getType())),
1244 cgf.getContext().VoidPtrTy);
1245
1246 mlir::Value order = successOrder.value;
1247
1248 // The next 1-3 parameters are op-dependent.
1249 llvm::StringRef calleeName;
1250 QualType retTy;
1251 bool hasRetTy = false;
1252 switch (e->getOp()) {
1253 case AtomicExpr::AO__c11_atomic_init:
1254 case AtomicExpr::AO__opencl_atomic_init:
1255 llvm_unreachable("Already handled!");
1256
1257 // There is only one libcall for compare an exchange, because there is no
1258 // optimisation benefit possible from a libcall version of a weak compare
1259 // and exchange.
1260 // bool __atomic_compare_exchange(size_t size, void *mem, void *expected,
1261 // void *desired, int success, int failure)
1262 case AtomicExpr::AO__atomic_compare_exchange:
1263 case AtomicExpr::AO__atomic_compare_exchange_n:
1264 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1265 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1266 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
1267 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
1268 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
1269 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
1270 case AtomicExpr::AO__scoped_atomic_compare_exchange:
1271 case AtomicExpr::AO__scoped_atomic_compare_exchange_n: {
1272 calleeName = "__atomic_compare_exchange";
1273 retTy = cgf.getContext().BoolTy;
1274 hasRetTy = true;
1275 mlir::Value orderFail = cgf.emitScalarExpr(e->getOrderFail());
1276 args.add(RValue::get(castToGenericAddrSpace(val1.emitRawPointer(),
1277 e->getVal1()->getType())),
1278 cgf.getContext().VoidPtrTy);
1279 args.add(RValue::get(castToGenericAddrSpace(val2.emitRawPointer(),
1280 e->getVal2()->getType())),
1281 cgf.getContext().VoidPtrTy);
1282 args.add(RValue::get(order), cgf.getContext().IntTy);
1283 order = orderFail;
1284 break;
1285 }
1286
1287 // void __atomic_exchange(size_t size, void *mem, void *val, void *return,
1288 // int order)
1289 case AtomicExpr::AO__atomic_exchange:
1290 case AtomicExpr::AO__atomic_exchange_n:
1291 case AtomicExpr::AO__c11_atomic_exchange:
1292 case AtomicExpr::AO__hip_atomic_exchange:
1293 case AtomicExpr::AO__opencl_atomic_exchange:
1294 case AtomicExpr::AO__scoped_atomic_exchange:
1295 case AtomicExpr::AO__scoped_atomic_exchange_n:
1296 calleeName = "__atomic_exchange";
1297 args.add(RValue::get(castToGenericAddrSpace(val1.emitRawPointer(),
1298 e->getVal1()->getType())),
1299 cgf.getContext().VoidPtrTy);
1300 break;
1301
1302 // void __atomic_store(size_t size, void *mem, void *val, int order)
1303 case AtomicExpr::AO__atomic_store:
1304 case AtomicExpr::AO__atomic_store_n:
1305 case AtomicExpr::AO__c11_atomic_store:
1306 case AtomicExpr::AO__hip_atomic_store:
1307 case AtomicExpr::AO__opencl_atomic_store:
1308 case AtomicExpr::AO__scoped_atomic_store:
1309 case AtomicExpr::AO__scoped_atomic_store_n:
1310 calleeName = "__atomic_store";
1311 retTy = cgf.getContext().VoidTy;
1312 hasRetTy = true;
1313 args.add(RValue::get(castToGenericAddrSpace(val1.emitRawPointer(),
1314 e->getVal1()->getType())),
1315 cgf.getContext().VoidPtrTy);
1316 break;
1317
1318 // void __atomic_load(size_t size, void *mem, void *return, int order)
1319 case AtomicExpr::AO__atomic_load:
1320 case AtomicExpr::AO__atomic_load_n:
1321 case AtomicExpr::AO__c11_atomic_load:
1322 case AtomicExpr::AO__hip_atomic_load:
1323 case AtomicExpr::AO__opencl_atomic_load:
1324 case AtomicExpr::AO__scoped_atomic_load:
1325 case AtomicExpr::AO__scoped_atomic_load_n:
1326 calleeName = "__atomic_load";
1327 break;
1328
1329 case AtomicExpr::AO__atomic_add_fetch:
1330 case AtomicExpr::AO__scoped_atomic_add_fetch:
1331 case AtomicExpr::AO__atomic_fetch_add:
1332 case AtomicExpr::AO__c11_atomic_fetch_add:
1333 case AtomicExpr::AO__hip_atomic_fetch_add:
1334 case AtomicExpr::AO__opencl_atomic_fetch_add:
1335 case AtomicExpr::AO__scoped_atomic_fetch_add:
1336 case AtomicExpr::AO__atomic_and_fetch:
1337 case AtomicExpr::AO__scoped_atomic_and_fetch:
1338 case AtomicExpr::AO__atomic_fetch_and:
1339 case AtomicExpr::AO__c11_atomic_fetch_and:
1340 case AtomicExpr::AO__hip_atomic_fetch_and:
1341 case AtomicExpr::AO__opencl_atomic_fetch_and:
1342 case AtomicExpr::AO__scoped_atomic_fetch_and:
1343 case AtomicExpr::AO__atomic_or_fetch:
1344 case AtomicExpr::AO__scoped_atomic_or_fetch:
1345 case AtomicExpr::AO__atomic_fetch_or:
1346 case AtomicExpr::AO__c11_atomic_fetch_or:
1347 case AtomicExpr::AO__hip_atomic_fetch_or:
1348 case AtomicExpr::AO__opencl_atomic_fetch_or:
1349 case AtomicExpr::AO__scoped_atomic_fetch_or:
1350 case AtomicExpr::AO__atomic_sub_fetch:
1351 case AtomicExpr::AO__scoped_atomic_sub_fetch:
1352 case AtomicExpr::AO__atomic_fetch_sub:
1353 case AtomicExpr::AO__c11_atomic_fetch_sub:
1354 case AtomicExpr::AO__hip_atomic_fetch_sub:
1355 case AtomicExpr::AO__opencl_atomic_fetch_sub:
1356 case AtomicExpr::AO__scoped_atomic_fetch_sub:
1357 case AtomicExpr::AO__atomic_xor_fetch:
1358 case AtomicExpr::AO__scoped_atomic_xor_fetch:
1359 case AtomicExpr::AO__atomic_fetch_xor:
1360 case AtomicExpr::AO__c11_atomic_fetch_xor:
1361 case AtomicExpr::AO__hip_atomic_fetch_xor:
1362 case AtomicExpr::AO__opencl_atomic_fetch_xor:
1363 case AtomicExpr::AO__scoped_atomic_fetch_xor:
1364 case AtomicExpr::AO__atomic_nand_fetch:
1365 case AtomicExpr::AO__atomic_fetch_nand:
1366 case AtomicExpr::AO__c11_atomic_fetch_nand:
1367 case AtomicExpr::AO__scoped_atomic_fetch_nand:
1368 case AtomicExpr::AO__scoped_atomic_nand_fetch:
1369 case AtomicExpr::AO__atomic_min_fetch:
1370 case AtomicExpr::AO__atomic_fetch_min:
1371 case AtomicExpr::AO__c11_atomic_fetch_min:
1372 case AtomicExpr::AO__hip_atomic_fetch_min:
1373 case AtomicExpr::AO__opencl_atomic_fetch_min:
1374 case AtomicExpr::AO__scoped_atomic_fetch_min:
1375 case AtomicExpr::AO__scoped_atomic_min_fetch:
1376 case AtomicExpr::AO__atomic_max_fetch:
1377 case AtomicExpr::AO__atomic_fetch_max:
1378 case AtomicExpr::AO__c11_atomic_fetch_max:
1379 case AtomicExpr::AO__hip_atomic_fetch_max:
1380 case AtomicExpr::AO__opencl_atomic_fetch_max:
1381 case AtomicExpr::AO__scoped_atomic_fetch_max:
1382 case AtomicExpr::AO__scoped_atomic_max_fetch:
1383 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
1384 case AtomicExpr::AO__scoped_atomic_fetch_udec:
1385 case AtomicExpr::AO__atomic_fetch_fmaximum:
1386 case AtomicExpr::AO__atomic_fetch_fmaximum_num:
1387 case AtomicExpr::AO__atomic_fetch_fminimum:
1388 case AtomicExpr::AO__atomic_fetch_fminimum_num:
1389 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum:
1390 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum_num:
1391 case AtomicExpr::AO__scoped_atomic_fetch_fminimum:
1392 case AtomicExpr::AO__scoped_atomic_fetch_fminimum_num:
1393 case AtomicExpr::AO__atomic_test_and_set:
1394 case AtomicExpr::AO__atomic_clear:
1395 case AtomicExpr::AO__atomic_fetch_uinc:
1396 case AtomicExpr::AO__atomic_fetch_udec:
1397 llvm_unreachable("Integral atomic operations always become atomicrmw!");
1398 }
1399
1400 if (e->isOpenCL()) {
1402 cgf.cgm.errorNYI(loc, "emitLibCallForAtomicExpr: openCL");
1403 return RValue::get(nullptr);
1404 }
1405
1406 // By default, assume we return a value of the atomic type.
1407 if (!hasRetTy) {
1408 // Value is returned through parameter before the order.
1409 retTy = cgf.getContext().VoidTy;
1410 args.add(RValue::get(castToGenericAddrSpace(dest.emitRawPointer(), retTy)),
1411 cgf.getContext().VoidPtrTy);
1412 }
1413
1414 // Order is always the last parameter.
1415 args.add(RValue::get(order), cgf.getContext().IntTy);
1416 if (e->isOpenCL()) {
1418 cgf.cgm.errorNYI(loc, "emitLibCallForAtomicExpr: openCL");
1419 return RValue::get(nullptr);
1420 }
1421
1422 RValue res = emitAtomicLibCall(cgf, calleeName, retTy, args);
1423
1424 // The value is returned directly from the libcall.
1425 if (e->isCmpXChg())
1426 return res;
1427
1428 if (resultTy->isVoidType())
1429 return RValue::get(nullptr);
1430
1431 return cgf.convertTempToRValue(
1432 dest.withElementType(cgf.getBuilder(), cgf.convertTypeForMem(resultTy)),
1433 resultTy, e->getExprLoc());
1434}
1435
1437 QualType atomicTy = e->getPtr()->getType()->getPointeeType();
1438 QualType memTy = atomicTy;
1439 if (const auto *ty = atomicTy->getAs<AtomicType>())
1440 memTy = ty->getValueType();
1441
1442 Expr *isWeakExpr = nullptr;
1443 Expr *orderFailExpr = nullptr;
1444
1445 Address val1 = Address::invalid();
1446 Address val2 = Address::invalid();
1447 Address dest = Address::invalid();
1449
1451 if (e->getOp() == AtomicExpr::AO__c11_atomic_init) {
1452 LValue lvalue = makeAddrLValue(ptr, atomicTy);
1453 emitAtomicInit(e->getVal1(), lvalue);
1454 return RValue::get(nullptr);
1455 }
1456
1457 TypeInfoChars typeInfo = getContext().getTypeInfoInChars(atomicTy);
1458 uint64_t size = typeInfo.Width.getQuantity();
1459
1460 EmittedOrderOrScope order(*this, e->getOrder());
1461 EmittedOrderOrScope scope;
1462 if (e->getScopeModel())
1463 scope = EmittedOrderOrScope(*this, e->getScope());
1464
1465 switch (e->getOp()) {
1466 default:
1467 cgm.errorNYI(e->getSourceRange(), "atomic op NYI");
1468 return RValue::get(nullptr);
1469
1470 case AtomicExpr::AO__c11_atomic_init:
1471 llvm_unreachable("already handled above with emitAtomicInit");
1472
1473 case AtomicExpr::AO__atomic_load_n:
1474 case AtomicExpr::AO__scoped_atomic_load_n:
1475 case AtomicExpr::AO__c11_atomic_load:
1476 case AtomicExpr::AO__opencl_atomic_load:
1477 case AtomicExpr::AO__hip_atomic_load:
1478 case AtomicExpr::AO__atomic_test_and_set:
1479 case AtomicExpr::AO__atomic_clear:
1480 break;
1481
1482 case AtomicExpr::AO__atomic_load:
1483 case AtomicExpr::AO__scoped_atomic_load:
1484 dest = emitPointerWithAlignment(e->getVal1());
1485 break;
1486
1487 case AtomicExpr::AO__atomic_store:
1488 case AtomicExpr::AO__scoped_atomic_store:
1489 val1 = emitPointerWithAlignment(e->getVal1());
1490 break;
1491
1492 case AtomicExpr::AO__atomic_exchange:
1493 case AtomicExpr::AO__scoped_atomic_exchange:
1494 val1 = emitPointerWithAlignment(e->getVal1());
1495 dest = emitPointerWithAlignment(e->getVal2());
1496 break;
1497
1498 case AtomicExpr::AO__atomic_compare_exchange:
1499 case AtomicExpr::AO__atomic_compare_exchange_n:
1500 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1501 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1502 case AtomicExpr::AO__scoped_atomic_compare_exchange:
1503 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
1504 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
1505 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
1506 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
1507 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
1508 val1 = emitPointerWithAlignment(e->getVal1());
1509 if (e->getOp() == AtomicExpr::AO__atomic_compare_exchange ||
1510 e->getOp() == AtomicExpr::AO__scoped_atomic_compare_exchange)
1511 val2 = emitPointerWithAlignment(e->getVal2());
1512 else
1513 val2 = emitValToTemp(*this, e->getVal2());
1514 orderFailExpr = e->getOrderFail();
1515 if (e->getOp() == AtomicExpr::AO__atomic_compare_exchange_n ||
1516 e->getOp() == AtomicExpr::AO__atomic_compare_exchange ||
1517 e->getOp() == AtomicExpr::AO__scoped_atomic_compare_exchange_n ||
1518 e->getOp() == AtomicExpr::AO__scoped_atomic_compare_exchange)
1519 isWeakExpr = e->getWeak();
1520 break;
1521
1522 case AtomicExpr::AO__c11_atomic_fetch_add:
1523 case AtomicExpr::AO__c11_atomic_fetch_sub:
1524 if (memTy->isPointerType()) {
1525 // For pointer arithmetic, we're required to do a bit of math:
1526 // adding 1 to an int* is not the same as adding 1 to a uintptr_t.
1527 // ... but only for the C11 builtins. The GNU builtins expect the
1528 // user to multiply by sizeof(T).
1529 QualType val1Ty = e->getVal1()->getType();
1530 mlir::Location loc = getLoc(e->getSourceRange());
1531 mlir::Value val1Scalar = emitScalarExpr(e->getVal1());
1532 CharUnits pointeeIncAmt =
1533 getContext().getTypeSizeInChars(memTy->getPointeeType());
1534 mlir::Value scale = builder.getConstInt(loc, val1Scalar.getType(),
1535 pointeeIncAmt.getQuantity());
1536 val1Scalar = builder.createMul(loc, val1Scalar, scale);
1537 val1 = createMemTemp(val1Ty, loc, ".atomictmp");
1538 emitStoreOfScalar(val1Scalar, makeAddrLValue(val1, val1Ty),
1539 /*isInit=*/true);
1540 }
1541 [[fallthrough]];
1542 case AtomicExpr::AO__atomic_fetch_add:
1543 case AtomicExpr::AO__atomic_fetch_sub:
1544 case AtomicExpr::AO__atomic_add_fetch:
1545 case AtomicExpr::AO__atomic_sub_fetch:
1546 if (memTy->isPointerType()) {
1547 // Fetch-and-update atomic operation on pointers should treat the pointer
1548 // value as uintptr_t values
1549 if (!val1.isValid())
1550 val1 = emitValToTemp(*this, e->getVal1());
1551 ptr = ptr.withElementType(builder, val1.getElementType());
1552 break;
1553 }
1554 [[fallthrough]];
1555 case AtomicExpr::AO__atomic_fetch_max:
1556 case AtomicExpr::AO__atomic_fetch_min:
1557 case AtomicExpr::AO__atomic_max_fetch:
1558 case AtomicExpr::AO__atomic_min_fetch:
1559 case AtomicExpr::AO__c11_atomic_fetch_max:
1560 case AtomicExpr::AO__c11_atomic_fetch_min:
1561 case AtomicExpr::AO__scoped_atomic_fetch_add:
1562 case AtomicExpr::AO__scoped_atomic_fetch_max:
1563 case AtomicExpr::AO__scoped_atomic_fetch_min:
1564 case AtomicExpr::AO__scoped_atomic_fetch_sub:
1565 case AtomicExpr::AO__scoped_atomic_fetch_fminimum:
1566 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum:
1567 case AtomicExpr::AO__scoped_atomic_fetch_fminimum_num:
1568 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum_num:
1569 case AtomicExpr::AO__scoped_atomic_add_fetch:
1570 case AtomicExpr::AO__scoped_atomic_max_fetch:
1571 case AtomicExpr::AO__scoped_atomic_min_fetch:
1572 case AtomicExpr::AO__scoped_atomic_sub_fetch:
1573 [[fallthrough]];
1574
1575 case AtomicExpr::AO__atomic_fetch_and:
1576 case AtomicExpr::AO__atomic_fetch_nand:
1577 case AtomicExpr::AO__atomic_fetch_or:
1578 case AtomicExpr::AO__atomic_fetch_xor:
1579 case AtomicExpr::AO__atomic_and_fetch:
1580 case AtomicExpr::AO__atomic_nand_fetch:
1581 case AtomicExpr::AO__atomic_or_fetch:
1582 case AtomicExpr::AO__atomic_xor_fetch:
1583 case AtomicExpr::AO__atomic_exchange_n:
1584 case AtomicExpr::AO__atomic_store_n:
1585 case AtomicExpr::AO__c11_atomic_fetch_and:
1586 case AtomicExpr::AO__c11_atomic_fetch_nand:
1587 case AtomicExpr::AO__c11_atomic_fetch_or:
1588 case AtomicExpr::AO__c11_atomic_fetch_xor:
1589 case AtomicExpr::AO__c11_atomic_exchange:
1590 case AtomicExpr::AO__c11_atomic_store:
1591 case AtomicExpr::AO__scoped_atomic_fetch_and:
1592 case AtomicExpr::AO__scoped_atomic_fetch_nand:
1593 case AtomicExpr::AO__scoped_atomic_fetch_or:
1594 case AtomicExpr::AO__scoped_atomic_fetch_xor:
1595 case AtomicExpr::AO__scoped_atomic_and_fetch:
1596 case AtomicExpr::AO__scoped_atomic_nand_fetch:
1597 case AtomicExpr::AO__scoped_atomic_or_fetch:
1598 case AtomicExpr::AO__scoped_atomic_xor_fetch:
1599 case AtomicExpr::AO__scoped_atomic_store_n:
1600 case AtomicExpr::AO__scoped_atomic_exchange_n:
1601 case AtomicExpr::AO__atomic_fetch_uinc:
1602 case AtomicExpr::AO__atomic_fetch_udec:
1603 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
1604 case AtomicExpr::AO__scoped_atomic_fetch_udec:
1605 case AtomicExpr::AO__atomic_fetch_fminimum:
1606 case AtomicExpr::AO__atomic_fetch_fmaximum:
1607 case AtomicExpr::AO__atomic_fetch_fminimum_num:
1608 case AtomicExpr::AO__atomic_fetch_fmaximum_num:
1609 case AtomicExpr::AO__hip_atomic_exchange:
1610 case AtomicExpr::AO__hip_atomic_store:
1611 case AtomicExpr::AO__hip_atomic_fetch_add:
1612 case AtomicExpr::AO__hip_atomic_fetch_sub:
1613 case AtomicExpr::AO__hip_atomic_fetch_min:
1614 case AtomicExpr::AO__hip_atomic_fetch_max:
1615 case AtomicExpr::AO__hip_atomic_fetch_and:
1616 case AtomicExpr::AO__hip_atomic_fetch_or:
1617 case AtomicExpr::AO__hip_atomic_fetch_xor:
1618 case AtomicExpr::AO__opencl_atomic_exchange:
1619 case AtomicExpr::AO__opencl_atomic_store:
1620 case AtomicExpr::AO__opencl_atomic_fetch_add:
1621 case AtomicExpr::AO__opencl_atomic_fetch_sub:
1622 case AtomicExpr::AO__opencl_atomic_fetch_min:
1623 case AtomicExpr::AO__opencl_atomic_fetch_max:
1624 case AtomicExpr::AO__opencl_atomic_fetch_and:
1625 case AtomicExpr::AO__opencl_atomic_fetch_or:
1626 case AtomicExpr::AO__opencl_atomic_fetch_xor:
1627 val1 = emitValToTemp(*this, e->getVal1());
1628 break;
1629 }
1630
1631 QualType resultTy = e->getType().getUnqualifiedType();
1632
1633 bool shouldCastToIntPtrTy =
1635
1636 // The inlined atomics only function on iN types, where N is a power of 2. We
1637 // need to make sure (via temporaries if necessary) that all incoming values
1638 // are compatible.
1639 mlir::Location loc = getLoc(e->getSourceRange());
1640 LValue atomicValue = makeAddrLValue(ptr, atomicTy);
1641 AtomicInfo atomics(*this, atomicValue, loc);
1642
1643 // Save val1's address before it is (possibly) converted to a temporary
1644 // sized to the full atomic width below.
1645 Address originalVal1 = val1;
1646
1647 if (shouldCastToIntPtrTy) {
1648 ptr = atomics.castToAtomicIntPointer(ptr);
1649 if (val1.isValid())
1650 val1 = atomics.convertToAtomicIntPointer(val1, loc);
1651 if (val2.isValid())
1652 val2 = atomics.convertToAtomicIntPointer(val2, loc);
1653 }
1654 if (dest.isValid()) {
1655 if (shouldCastToIntPtrTy)
1656 dest = atomics.castToAtomicIntPointer(dest);
1657 } else if (e->isCmpXChg()) {
1658 dest = createMemTemp(resultTy, loc, "cmpxchg.bool");
1659 } else if (e->getOp() == AtomicExpr::AO__atomic_test_and_set) {
1660 dest = createMemTemp(resultTy, loc, "test_and_set.bool");
1661 } else if (!resultTy->isVoidType()) {
1662 dest = atomics.createTempAlloca();
1663 if (shouldCastToIntPtrTy)
1664 dest = atomics.castToAtomicIntPointer(dest);
1665 }
1666
1667 bool powerOf2Size = (size & (size - 1)) == 0;
1668 bool useLibCall = !powerOf2Size || (size > 16);
1669
1670 // For atomics larger than 16 bytes, emit a libcall from the frontend. This
1671 // avoids the overhead of dealing with excessively-large value types in IR.
1672 // Non-power-of-2 values also lower to libcall here, as they are not currently
1673 // permitted in IR instructions (although that constraint could be relaxed in
1674 // the future). For other cases where a libcall is required on a given
1675 // platform, we let the backend handle it (this includes handling for all of
1676 // the size-optimized libcall variants, which are only valid up to 16 bytes.)
1677 //
1678 // See: https://llvm.org/docs/Atomics.html#libcalls-atomic
1679 if (useLibCall)
1680 return emitLibCallForAtomicExpr(*this, e, ptr, dest, val1, val2, size,
1681 resultTy, order);
1682
1683 bool isStore = e->getOp() == AtomicExpr::AO__c11_atomic_store ||
1684 e->getOp() == AtomicExpr::AO__opencl_atomic_store ||
1685 e->getOp() == AtomicExpr::AO__hip_atomic_store ||
1686 e->getOp() == AtomicExpr::AO__atomic_store ||
1687 e->getOp() == AtomicExpr::AO__atomic_store_n ||
1688 e->getOp() == AtomicExpr::AO__scoped_atomic_store ||
1689 e->getOp() == AtomicExpr::AO__scoped_atomic_store_n ||
1690 e->getOp() == AtomicExpr::AO__atomic_clear;
1691 bool isLoad = e->getOp() == AtomicExpr::AO__c11_atomic_load ||
1692 e->getOp() == AtomicExpr::AO__opencl_atomic_load ||
1693 e->getOp() == AtomicExpr::AO__hip_atomic_load ||
1694 e->getOp() == AtomicExpr::AO__atomic_load ||
1695 e->getOp() == AtomicExpr::AO__atomic_load_n ||
1696 e->getOp() == AtomicExpr::AO__scoped_atomic_load ||
1697 e->getOp() == AtomicExpr::AO__scoped_atomic_load_n;
1698
1700 order, isStore, isLoad, /*isFence*/ false, [&](cir::MemOrder memOrder) {
1701 std::unique_ptr<AtomicScopeModel> scopeModel = e->getScopeModel();
1703 scopeModel.get(), scope, [&](cir::SyncScopeKind scope) {
1704 emitAtomicOp(*this, e, dest, ptr, val1, val2, originalVal1,
1705 isWeakExpr, orderFailExpr, size, memOrder, scope);
1706 });
1707 });
1708
1709 if (resultTy->isVoidType())
1710 return RValue::get(nullptr);
1711
1712 return convertTempToRValue(
1713 dest.withElementType(builder, convertTypeForMem(resultTy)), resultTy,
1714 e->getExprLoc());
1715}
1716
1718 AggValueSlot slot) {
1719 if (lvalue.getType()->isAtomicType())
1720 return emitAtomicLoad(lvalue, loc, cir::MemOrder::SequentiallyConsistent,
1721 /*isVolatile=*/lvalue.isVolatileQualified(), slot);
1722 return emitAtomicLoad(lvalue, loc, cir::MemOrder::Acquire,
1723 /*isVolatile=*/true, slot);
1724}
1725
1727 cir::MemOrder order, bool isVolatile,
1728 AggValueSlot slot) {
1729 AtomicInfo info(*this, lvalue, getLoc(loc));
1730 return info.emitAtomicLoad(slot, loc, /*asValue=*/true, order, isVolatile);
1731}
1732
1733void CIRGenFunction::emitAtomicStore(RValue rvalue, LValue dest, bool isInit) {
1734 bool isVolatile = dest.isVolatileQualified();
1735 auto order = cir::MemOrder::SequentiallyConsistent;
1736 if (!dest.getType()->isAtomicType()) {
1738 }
1739 return emitAtomicStore(rvalue, dest, order, isVolatile, isInit);
1740}
1741
1742/// Emit a store to an l-value of atomic type.
1743///
1744/// Note that the r-value is expected to be an r-value of the atomic type; this
1745/// means that for aggregate r-values, it should include storage for any padding
1746/// that was necessary.
1748 cir::MemOrder order, bool isVolatile,
1749 bool isInit) {
1750 // If this is an aggregate r-value, it should agree in type except
1751 // maybe for address-space qualification.
1752 mlir::Location loc = dest.getPointer().getLoc();
1753 assert(!rvalue.isAggregate() ||
1755 dest.getAddress().getElementType());
1756
1757 AtomicInfo atomics(*this, dest, loc);
1758 LValue lvalue = atomics.getAtomicLValue();
1759
1760 if (lvalue.isSimple()) {
1761 // If this is an initialization, just put the value there normally.
1762 if (isInit) {
1763 atomics.emitCopyIntoMemory(rvalue);
1764 return;
1765 }
1766
1767 // Check whether we should use a library call.
1768 if (atomics.shouldUseLibCall()) {
1770 cgm.errorNYI(loc, "emitAtomicStore: atomic store with library call");
1771 return;
1772 }
1773
1774 // Okay, we're doing this natively.
1775 mlir::Value valueToStore = atomics.convertRValueToInt(rvalue, loc);
1776
1777 // Do the atomic store.
1778 Address addr = atomics.getAtomicAddress();
1779 if (mlir::Value value = atomics.getScalarRValValueOrNull(rvalue)) {
1780 if (shouldCastToInt(value.getType(), /*CmpXchg=*/false)) {
1781 addr = atomics.castToAtomicIntPointer(addr);
1782 valueToStore =
1783 builder.createIntCast(valueToStore, addr.getElementType());
1784 }
1785 }
1786 cir::StoreOp store = builder.createStore(loc, valueToStore, addr);
1787
1788 // Initializations don't need to be atomic.
1789 if (!isInit) {
1791 store.setMemOrder(order);
1792 }
1793
1794 // Other decoration.
1795 if (isVolatile)
1796 store.setIsVolatile(true);
1797
1799 return;
1800 }
1801
1802 cgm.errorNYI(loc, "emitAtomicStore: non-simple atomic lvalue");
1804}
1805
1807 AtomicInfo atomics(*this, dest, getLoc(init->getSourceRange()));
1808
1809 switch (atomics.getEvaluationKind()) {
1810 case cir::TEK_Scalar: {
1811 mlir::Value value = emitScalarExpr(init);
1812 atomics.emitCopyIntoMemory(RValue::get(value));
1813 return;
1814 }
1815
1816 case cir::TEK_Complex: {
1817 mlir::Value value = emitComplexExpr(init);
1818 atomics.emitCopyIntoMemory(RValue::get(value));
1819 return;
1820 }
1821
1822 case cir::TEK_Aggregate: {
1823 // Fix up the destination if the initializer isn't an expression
1824 // of atomic type.
1825 bool zeroed = false;
1826 if (!init->getType()->isAtomicType()) {
1827 zeroed = atomics.emitMemSetZeroIfNecessary();
1828 dest = atomics.projectValue();
1829 }
1830
1831 // Evaluate the expression directly into the destination.
1837
1838 emitAggExpr(init, slot);
1839 return;
1840 }
1841 }
1842
1843 llvm_unreachable("bad evaluation kind");
1844}
static bool shouldCastToInt(mlir::Type valueTy, bool cmpxchg)
Return true if.
static Address emitValToTemp(CIRGenFunction &cgf, Expr *e)
static void emitAtomicExprWithDynamicSyncScope(CIRGenFunction &cgf, const AtomicScopeModel *scopeModel, mlir::Value scope, llvm::function_ref< void(cir::SyncScopeKind)> emitAtomicOp)
static void emitMemOrderCaseLabel(CIRGenBuilderTy &builder, mlir::Location loc, mlir::Type orderType, llvm::ArrayRef< cir::MemOrder > orders)
static cir::SyncScopeKind convertSyncScopeToCIR(CIRGenFunction &cgf, 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 emitDefaultCaseLabel(CIRGenBuilderTy &builder, mlir::Location loc)
static void emitAtomicCmpXchgFailureSetCheckWeak(CIRGenFunction &cgf, AtomicExpr *e, Expr *isWeakExpr, Address dest, Address ptr, Address val1, Address val2, Address expectedResult, Expr *failureOrderExpr, uint64_t size, cir::MemOrder successOrder, cir::SyncScopeKind scope)
static RValue emitLibCallForAtomicExpr(CIRGenFunction &cgf, AtomicExpr *e, Address atomicPtr, Address dest, Address val1, Address val2, uint64_t atomicTySize, QualType resultTy, const CIRGenFunction::EmittedOrderOrScope &successOrder)
static void setAMDGPUAtomicMetadata(CIRGenFunction &cgf, mlir::Operation *op, const AtomicExpr *expr)
Attach the AMDGPU atomic metadata markers that the current atomic options call for.
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, Address expectedResult, Expr *failureOrderExpr, uint64_t size, cir::MemOrder successOrder, cir::SyncScopeKind scope)
static void emitAtomicCmpXchg(CIRGenFunction &cgf, AtomicExpr *e, bool isWeak, Address dest, Address ptr, Address val1, Address val2, Address expectedResult, uint64_t size, cir::MemOrder successOrder, cir::MemOrder failureOrder, cir::SyncScopeKind scope)
static void emitAtomicOp(CIRGenFunction &cgf, AtomicExpr *expr, Address dest, Address ptr, Address val1, Address val2, Address expectedResult, Expr *isWeakExpr, Expr *failureOrderExpr, int64_t size, cir::MemOrder order, cir::SyncScopeKind scope)
static std::optional< cir::MemOrder > getEffectiveAtomicMemOrder(cir::MemOrder oriOrder, bool isStore, bool isLoad, bool isFence)
static RValue emitAtomicLibCall(CIRGenFunction &cgf, llvm::StringRef funcName, QualType resultType, CallArgList &args)
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
cir::BreakOp createBreak(mlir::Location loc)
Create a break operation.
mlir::Value createPtrBitcast(mlir::Value src, mlir::Type newPointeeTy)
mlir::IntegerAttr getAlignmentAttr(clang::CharUnits alignment)
mlir::Value createNot(mlir::Location loc, mlir::Value value)
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:577
CanQualType VoidPtrTy
CanQualType BoolTy
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
CanQualType IntTy
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
CanQualType VoidTy
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:974
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:7014
static std::unique_ptr< AtomicScopeModel > getScopeModel(AtomicOp Op)
Get atomic scope model for the atomic op code.
Definition Expr.h:7163
Expr * getVal2() const
Definition Expr.h:7065
Expr * getOrder() const
Definition Expr.h:7048
Expr * getScope() const
Definition Expr.h:7051
bool isCmpXChg() const
Definition Expr.h:7098
AtomicOp getOp() const
Definition Expr.h:7077
bool isOpenCL() const
Definition Expr.h:7126
Expr * getVal1() const
Definition Expr.h:7055
Expr * getPtr() const
Definition Expr.h:7045
Expr * getWeak() const
Definition Expr.h:7071
Expr * getOrderFail() const
Definition Expr.h:7061
bool isVolatile() const
Definition Expr.h:7094
Defines the interface for sync scope model.
Definition SyncScope.h:105
virtual ArrayRef< unsigned > getRuntimeValues() const =0
Get all possible sync scope values that might be encountered at runtime for the current language.
virtual SyncScope map(unsigned S) const =0
Maps language specific sync scope values to internal SyncScope enum.
virtual unsigned getFallBackValue() const =0
If atomic builtin function is called with invalid sync scope value at runtime, it will fall back to a...
mlir::Value getPointer() const
Definition Address.h:98
mlir::Type getElementType() const
Definition Address.h:125
static Address invalid()
Definition Address.h:76
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:138
bool isValid() const
Definition Address.h:77
mlir::Value emitRawPointer() const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition Address.h:112
An aggregate value slot.
static AggValueSlot forLValue(const LValue &LV, IsDestructed_t isDestructed, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed)
cir::LoadOp createLoad(mlir::Location loc, Address addr, bool isVolatile=false, bool isNontemporal=false)
cir::StoreOp createStore(mlir::Location loc, mlir::Value val, Address dst, bool isVolatile=false, bool isNontemporal=false, mlir::IntegerAttr align={}, cir::SyncScopeKindAttr scope={}, cir::MemOrderAttr order={})
cir::MemCpyOp createMemCpy(mlir::Location loc, Address dst, Address src, mlir::Value len)
cir::ConstantOp getConstInt(mlir::Location loc, llvm::APSInt intVal)
cir::MemSetOp createMemSet(mlir::Location loc, mlir::Value dst, mlir::Value val, mlir::Value len)
cir::IntType getUIntNTy(int n)
static CIRGenCallee forDirect(mlir::Operation *funcPtr, const CIRGenCalleeInfo &abstractInfo=CIRGenCalleeInfo())
Definition CIRGenCall.h:92
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...
cir::AllocaOp createTempAlloca(mlir::Type ty, mlir::Location loc, const Twine &name="tmp", mlir::Value arraySize=nullptr, bool insertIntoFnEntryBlock=false)
This creates an alloca and inserts it into the entry block if ArraySize is nullptr,...
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)
RValue emitAtomicLoad(LValue lvalue, SourceLocation loc, AggValueSlot slot=AggValueSlot::ignored())
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 emitStoreOfComplex(mlir::Location loc, mlir::Value v, LValue dest, bool isInit)
EmitStoreOfComplex - Store a complex number into the specified l-value.
void emitAtomicExprWithSyncScope(const AtomicScopeModel *scopeModel, const EmittedOrderOrScope &scope, llvm::function_ref< void(cir::SyncScopeKind)> 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.
void emitAtomicExprWithMemOrder(const EmittedOrderOrScope &order, bool isStore, bool isLoad, bool isFence, llvm::function_ref< void(cir::MemOrder)> emitAtomicOp)
CIRGenBuilderTy & getBuilder()
mlir::MLIRContext & getMLIRContext()
void emitAtomicInit(Expr *init, LValue dest)
RValue emitCall(const CIRGenFunctionInfo &funcInfo, const CIRGenCallee &callee, ReturnValueSlot returnValue, const CallArgList &args, cir::CIRCallOpInterface *callOp, bool isMustTail, SourceRange clangLoc)
LValue makeAddrLValue(Address addr, QualType ty, AlignmentSource source=AlignmentSource::Type)
void emitAtomicStore(RValue rvalue, LValue dest, bool isInit)
clang::ASTContext & getContext() const
mlir::Value emitFromMemory(mlir::Value value, clang::QualType ty)
EmitFromMemory - Change a scalar value from its memory representation to its value representation.
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.
clang::AtomicOptions getAtomicOpts() const
The atomic options in effect at the point currently being emitted.
const llvm::Triple & getTriple() const
const cir::CIRDataLayout & getDataLayout() const
cir::FuncOp createRuntimeFunction(cir::FuncType ty, llvm::StringRef name, mlir::NamedAttrList extraAttrs={}, bool isLocal=false, bool assumeConvergent=false)
const CIRGenFunctionInfo & arrangeBuiltinFunctionCall(QualType resultType, const CallArgList &args)
A builtin function is a freestanding function using the default C conventions.
cir::FuncType getFunctionType(const CIRGenFunctionInfo &info)
Get the CIR function type for.
void add(RValue rvalue, clang::QualType type)
Definition CIRGenCall.h:241
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
static RValue getAggregate(Address addr, bool isVolatile=false)
Convert an Address to an RValue.
mlir::Value getValue() const
Return the value of this scalar value.
Definition CIRGenValue.h:57
bool isScalar() const
Definition CIRGenValue.h:49
mlir::Value getComplexValue() const
Return the value of this complex value.
Definition CIRGenValue.h:63
Contains the address where the return value of a function can be stored, and whether the address is v...
Definition CIRGenCall.h:262
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
llvm::Align getAsAlign() const
Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit bytes.
Definition CharUnits.h:159
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
This represents one expression.
Definition Expr.h:114
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:283
QualType getType() const
Definition Expr.h:146
A (possibly-)qualified type.
Definition TypeBase.h:938
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8618
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8672
Encodes a location in the source.
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:860
bool isVoidType() const
Definition TypeBase.h:9200
bool isPointerType() const
Definition TypeBase.h:8815
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isAtomicType() const
Definition TypeBase.h:9007
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9431
bool isValidCIRAtomicOrderingCABI(Int value)
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
@ Address
A pointer to a ValueDecl.
Definition Primitives.h:28
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
SyncScope
Defines sync scope values used internally by clang.
Definition SyncScope.h:43
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t int64_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
static bool atomicAMDGPUAvailableVisibleMMRA()
static bool atomicInfoGetAtomicPointer()
static bool aggValueSlotGC()
static bool opLoadStoreAtomic()
static bool opLoadStoreTbaa()
static bool opFuncExtraAttrs()
static bool atomicUseLibCall()
static bool atomicOpenMP()
static bool atomicMicrosoftVolatile()
static bool atomicSyncScopeID()
static bool generateDebugInfo()
static bool atomicInfoGetAtomicAddress()
bool getOption(AtomicOptionKind Kind) const
An emitted atomic order or scope value with optional constant evaluation.
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:667
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:669