blob: 47a82b602a0b97a5a5a4601cf17e1e58fc3fbaab [file] [log] [blame]
John McCallfc207f22013-03-07 21:37:12 +00001//===--- CGAtomic.cpp - Emit LLVM IR for atomic operations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the code for emitting atomic operations.
11//
12//===----------------------------------------------------------------------===//
13
John McCallfc207f22013-03-07 21:37:12 +000014#include "CGCall.h"
Alexey Bataevb57056f2015-01-22 06:17:56 +000015#include "CGRecordLayout.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000016#include "CodeGenFunction.h"
John McCallfc207f22013-03-07 21:37:12 +000017#include "CodeGenModule.h"
Yaxun Liu39195062017-08-04 18:16:31 +000018#include "TargetInfo.h"
John McCallfc207f22013-03-07 21:37:12 +000019#include "clang/AST/ASTContext.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000020#include "clang/CodeGen/CGFunctionInfo.h"
Tim Northover9dc1d0c2018-04-23 08:16:24 +000021#include "clang/Sema/SemaDiagnostic.h"
Yaxun Liu30d652a2017-08-15 16:02:49 +000022#include "llvm/ADT/DenseMap.h"
John McCallfc207f22013-03-07 21:37:12 +000023#include "llvm/IR/DataLayout.h"
24#include "llvm/IR/Intrinsics.h"
John McCalla8ec7eb2013-03-07 21:37:17 +000025#include "llvm/IR/Operator.h"
John McCallfc207f22013-03-07 21:37:12 +000026
27using namespace clang;
28using namespace CodeGen;
29
John McCalla8ec7eb2013-03-07 21:37:17 +000030namespace {
31 class AtomicInfo {
32 CodeGenFunction &CGF;
33 QualType AtomicTy;
34 QualType ValueTy;
35 uint64_t AtomicSizeInBits;
36 uint64_t ValueSizeInBits;
37 CharUnits AtomicAlign;
38 CharUnits ValueAlign;
39 CharUnits LValueAlign;
40 TypeEvaluationKind EvaluationKind;
41 bool UseLibcall;
Alexey Bataevb57056f2015-01-22 06:17:56 +000042 LValue LVal;
43 CGBitFieldInfo BFI;
John McCalla8ec7eb2013-03-07 21:37:17 +000044 public:
Alexey Bataevb57056f2015-01-22 06:17:56 +000045 AtomicInfo(CodeGenFunction &CGF, LValue &lvalue)
46 : CGF(CGF), AtomicSizeInBits(0), ValueSizeInBits(0),
47 EvaluationKind(TEK_Scalar), UseLibcall(true) {
48 assert(!lvalue.isGlobalReg());
John McCalla8ec7eb2013-03-07 21:37:17 +000049 ASTContext &C = CGF.getContext();
Alexey Bataevb57056f2015-01-22 06:17:56 +000050 if (lvalue.isSimple()) {
51 AtomicTy = lvalue.getType();
52 if (auto *ATy = AtomicTy->getAs<AtomicType>())
53 ValueTy = ATy->getValueType();
54 else
55 ValueTy = AtomicTy;
56 EvaluationKind = CGF.getEvaluationKind(ValueTy);
John McCalla8ec7eb2013-03-07 21:37:17 +000057
Alexey Bataevb57056f2015-01-22 06:17:56 +000058 uint64_t ValueAlignInBits;
59 uint64_t AtomicAlignInBits;
60 TypeInfo ValueTI = C.getTypeInfo(ValueTy);
61 ValueSizeInBits = ValueTI.Width;
62 ValueAlignInBits = ValueTI.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +000063
Alexey Bataevb57056f2015-01-22 06:17:56 +000064 TypeInfo AtomicTI = C.getTypeInfo(AtomicTy);
65 AtomicSizeInBits = AtomicTI.Width;
66 AtomicAlignInBits = AtomicTI.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +000067
Alexey Bataevb57056f2015-01-22 06:17:56 +000068 assert(ValueSizeInBits <= AtomicSizeInBits);
69 assert(ValueAlignInBits <= AtomicAlignInBits);
John McCalla8ec7eb2013-03-07 21:37:17 +000070
Alexey Bataevb57056f2015-01-22 06:17:56 +000071 AtomicAlign = C.toCharUnitsFromBits(AtomicAlignInBits);
72 ValueAlign = C.toCharUnitsFromBits(ValueAlignInBits);
73 if (lvalue.getAlignment().isZero())
74 lvalue.setAlignment(AtomicAlign);
John McCalla8ec7eb2013-03-07 21:37:17 +000075
Alexey Bataevb57056f2015-01-22 06:17:56 +000076 LVal = lvalue;
77 } else if (lvalue.isBitField()) {
Alexey Bataevb8329262015-02-27 06:33:30 +000078 ValueTy = lvalue.getType();
79 ValueSizeInBits = C.getTypeSize(ValueTy);
Alexey Bataevb57056f2015-01-22 06:17:56 +000080 auto &OrigBFI = lvalue.getBitFieldInfo();
81 auto Offset = OrigBFI.Offset % C.toBits(lvalue.getAlignment());
82 AtomicSizeInBits = C.toBits(
83 C.toCharUnitsFromBits(Offset + OrigBFI.Size + C.getCharWidth() - 1)
Rui Ueyama83aa9792016-01-14 21:00:27 +000084 .alignTo(lvalue.getAlignment()));
John McCall7f416cc2015-09-08 08:05:57 +000085 auto VoidPtrAddr = CGF.EmitCastToVoidPtr(lvalue.getBitFieldPointer());
Alexey Bataevb57056f2015-01-22 06:17:56 +000086 auto OffsetInChars =
87 (C.toCharUnitsFromBits(OrigBFI.Offset) / lvalue.getAlignment()) *
88 lvalue.getAlignment();
89 VoidPtrAddr = CGF.Builder.CreateConstGEP1_64(
90 VoidPtrAddr, OffsetInChars.getQuantity());
91 auto Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
92 VoidPtrAddr,
93 CGF.Builder.getIntNTy(AtomicSizeInBits)->getPointerTo(),
94 "atomic_bitfield_base");
95 BFI = OrigBFI;
96 BFI.Offset = Offset;
97 BFI.StorageSize = AtomicSizeInBits;
Ulrich Weigand03ce2a12015-07-10 17:30:00 +000098 BFI.StorageOffset += OffsetInChars;
John McCall7f416cc2015-09-08 08:05:57 +000099 LVal = LValue::MakeBitfield(Address(Addr, lvalue.getAlignment()),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +0000100 BFI, lvalue.getType(), lvalue.getBaseInfo(),
101 lvalue.getTBAAInfo());
Alexey Bataevb8329262015-02-27 06:33:30 +0000102 AtomicTy = C.getIntTypeForBitwidth(AtomicSizeInBits, OrigBFI.IsSigned);
103 if (AtomicTy.isNull()) {
104 llvm::APInt Size(
105 /*numBits=*/32,
106 C.toCharUnitsFromBits(AtomicSizeInBits).getQuantity());
107 AtomicTy = C.getConstantArrayType(C.CharTy, Size, ArrayType::Normal,
108 /*IndexTypeQuals=*/0);
109 }
110 AtomicAlign = ValueAlign = lvalue.getAlignment();
Alexey Bataevb57056f2015-01-22 06:17:56 +0000111 } else if (lvalue.isVectorElt()) {
Alexey Bataevb8329262015-02-27 06:33:30 +0000112 ValueTy = lvalue.getType()->getAs<VectorType>()->getElementType();
113 ValueSizeInBits = C.getTypeSize(ValueTy);
114 AtomicTy = lvalue.getType();
115 AtomicSizeInBits = C.getTypeSize(AtomicTy);
116 AtomicAlign = ValueAlign = lvalue.getAlignment();
Alexey Bataevb57056f2015-01-22 06:17:56 +0000117 LVal = lvalue;
118 } else {
119 assert(lvalue.isExtVectorElt());
Alexey Bataevb8329262015-02-27 06:33:30 +0000120 ValueTy = lvalue.getType();
121 ValueSizeInBits = C.getTypeSize(ValueTy);
122 AtomicTy = ValueTy = CGF.getContext().getExtVectorType(
John McCall7f416cc2015-09-08 08:05:57 +0000123 lvalue.getType(), lvalue.getExtVectorAddress()
124 .getElementType()->getVectorNumElements());
Alexey Bataevb8329262015-02-27 06:33:30 +0000125 AtomicSizeInBits = C.getTypeSize(AtomicTy);
126 AtomicAlign = ValueAlign = lvalue.getAlignment();
Alexey Bataevb57056f2015-01-22 06:17:56 +0000127 LVal = lvalue;
128 }
Alexey Bataev452d8e12014-12-15 05:25:25 +0000129 UseLibcall = !C.getTargetInfo().hasBuiltinAtomic(
130 AtomicSizeInBits, C.toBits(lvalue.getAlignment()));
John McCalla8ec7eb2013-03-07 21:37:17 +0000131 }
132
133 QualType getAtomicType() const { return AtomicTy; }
134 QualType getValueType() const { return ValueTy; }
135 CharUnits getAtomicAlignment() const { return AtomicAlign; }
136 CharUnits getValueAlignment() const { return ValueAlign; }
137 uint64_t getAtomicSizeInBits() const { return AtomicSizeInBits; }
Alexey Bataev452d8e12014-12-15 05:25:25 +0000138 uint64_t getValueSizeInBits() const { return ValueSizeInBits; }
John McCalla8ec7eb2013-03-07 21:37:17 +0000139 TypeEvaluationKind getEvaluationKind() const { return EvaluationKind; }
140 bool shouldUseLibcall() const { return UseLibcall; }
Alexey Bataevb57056f2015-01-22 06:17:56 +0000141 const LValue &getAtomicLValue() const { return LVal; }
John McCall7f416cc2015-09-08 08:05:57 +0000142 llvm::Value *getAtomicPointer() const {
Alexey Bataevb8329262015-02-27 06:33:30 +0000143 if (LVal.isSimple())
John McCall7f416cc2015-09-08 08:05:57 +0000144 return LVal.getPointer();
Alexey Bataevb8329262015-02-27 06:33:30 +0000145 else if (LVal.isBitField())
John McCall7f416cc2015-09-08 08:05:57 +0000146 return LVal.getBitFieldPointer();
Alexey Bataevb8329262015-02-27 06:33:30 +0000147 else if (LVal.isVectorElt())
John McCall7f416cc2015-09-08 08:05:57 +0000148 return LVal.getVectorPointer();
Alexey Bataevb8329262015-02-27 06:33:30 +0000149 assert(LVal.isExtVectorElt());
John McCall7f416cc2015-09-08 08:05:57 +0000150 return LVal.getExtVectorPointer();
151 }
152 Address getAtomicAddress() const {
153 return Address(getAtomicPointer(), getAtomicAlignment());
154 }
155
156 Address getAtomicAddressAsAtomicIntPointer() const {
157 return emitCastToAtomicIntPointer(getAtomicAddress());
Alexey Bataevb8329262015-02-27 06:33:30 +0000158 }
John McCalla8ec7eb2013-03-07 21:37:17 +0000159
160 /// Is the atomic size larger than the underlying value type?
161 ///
162 /// Note that the absence of padding does not mean that atomic
163 /// objects are completely interchangeable with non-atomic
164 /// objects: we might have promoted the alignment of a type
165 /// without making it bigger.
166 bool hasPadding() const {
167 return (ValueSizeInBits != AtomicSizeInBits);
168 }
169
Alexey Bataevb57056f2015-01-22 06:17:56 +0000170 bool emitMemSetZeroIfNecessary() const;
John McCalla8ec7eb2013-03-07 21:37:17 +0000171
172 llvm::Value *getAtomicSizeValue() const {
173 CharUnits size = CGF.getContext().toCharUnitsFromBits(AtomicSizeInBits);
174 return CGF.CGM.getSize(size);
175 }
176
Tim Northovercc2a6e02015-11-09 19:56:35 +0000177 /// Cast the given pointer to an integer pointer suitable for atomic
178 /// operations if the source.
179 Address emitCastToAtomicIntPointer(Address Addr) const;
180
181 /// If Addr is compatible with the iN that will be used for an atomic
182 /// operation, bitcast it. Otherwise, create a temporary that is suitable
183 /// and copy the value across.
184 Address convertToAtomicIntPointer(Address Addr) const;
John McCalla8ec7eb2013-03-07 21:37:17 +0000185
186 /// Turn an atomic-layout object into an r-value.
John McCall7f416cc2015-09-08 08:05:57 +0000187 RValue convertAtomicTempToRValue(Address addr, AggValueSlot resultSlot,
188 SourceLocation loc, bool AsValue) const;
John McCalla8ec7eb2013-03-07 21:37:17 +0000189
Alexey Bataev452d8e12014-12-15 05:25:25 +0000190 /// \brief Converts a rvalue to integer value.
191 llvm::Value *convertRValueToInt(RValue RVal) const;
192
Alexey Bataevb8329262015-02-27 06:33:30 +0000193 RValue ConvertIntToValueOrAtomic(llvm::Value *IntVal,
194 AggValueSlot ResultSlot,
195 SourceLocation Loc, bool AsValue) const;
Alexey Bataev452d8e12014-12-15 05:25:25 +0000196
John McCalla8ec7eb2013-03-07 21:37:17 +0000197 /// Copy an atomic r-value into atomic-layout memory.
Alexey Bataevb57056f2015-01-22 06:17:56 +0000198 void emitCopyIntoMemory(RValue rvalue) const;
John McCalla8ec7eb2013-03-07 21:37:17 +0000199
200 /// Project an l-value down to the value field.
Alexey Bataevb57056f2015-01-22 06:17:56 +0000201 LValue projectValue() const {
202 assert(LVal.isSimple());
John McCall7f416cc2015-09-08 08:05:57 +0000203 Address addr = getAtomicAddress();
John McCalla8ec7eb2013-03-07 21:37:17 +0000204 if (hasPadding())
John McCall7f416cc2015-09-08 08:05:57 +0000205 addr = CGF.Builder.CreateStructGEP(addr, 0, CharUnits());
John McCalla8ec7eb2013-03-07 21:37:17 +0000206
John McCall7f416cc2015-09-08 08:05:57 +0000207 return LValue::MakeAddr(addr, getValueType(), CGF.getContext(),
Ivan A. Kosarev383890b2017-10-06 08:17:48 +0000208 LVal.getBaseInfo(), LVal.getTBAAInfo());
John McCalla8ec7eb2013-03-07 21:37:17 +0000209 }
210
Alexey Bataevb8329262015-02-27 06:33:30 +0000211 /// \brief Emits atomic load.
212 /// \returns Loaded value.
213 RValue EmitAtomicLoad(AggValueSlot ResultSlot, SourceLocation Loc,
214 bool AsValue, llvm::AtomicOrdering AO,
215 bool IsVolatile);
216
217 /// \brief Emits atomic compare-and-exchange sequence.
218 /// \param Expected Expected value.
219 /// \param Desired Desired value.
220 /// \param Success Atomic ordering for success operation.
221 /// \param Failure Atomic ordering for failed operation.
222 /// \param IsWeak true if atomic operation is weak, false otherwise.
223 /// \returns Pair of values: previous value from storage (value type) and
224 /// boolean flag (i1 type) with true if success and false otherwise.
JF Bastien92f4ef12016-04-06 17:26:42 +0000225 std::pair<RValue, llvm::Value *>
226 EmitAtomicCompareExchange(RValue Expected, RValue Desired,
227 llvm::AtomicOrdering Success =
228 llvm::AtomicOrdering::SequentiallyConsistent,
229 llvm::AtomicOrdering Failure =
230 llvm::AtomicOrdering::SequentiallyConsistent,
231 bool IsWeak = false);
Alexey Bataevb8329262015-02-27 06:33:30 +0000232
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000233 /// \brief Emits atomic update.
NAKAMURA Takumid16af5d2015-05-15 13:47:52 +0000234 /// \param AO Atomic ordering.
235 /// \param UpdateOp Update operation for the current lvalue.
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000236 void EmitAtomicUpdate(llvm::AtomicOrdering AO,
237 const llvm::function_ref<RValue(RValue)> &UpdateOp,
238 bool IsVolatile);
239 /// \brief Emits atomic update.
NAKAMURA Takumid16af5d2015-05-15 13:47:52 +0000240 /// \param AO Atomic ordering.
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000241 void EmitAtomicUpdate(llvm::AtomicOrdering AO, RValue UpdateRVal,
242 bool IsVolatile);
243
John McCalla8ec7eb2013-03-07 21:37:17 +0000244 /// Materialize an atomic r-value in atomic-layout memory.
John McCall7f416cc2015-09-08 08:05:57 +0000245 Address materializeRValue(RValue rvalue) const;
John McCalla8ec7eb2013-03-07 21:37:17 +0000246
Tim Northovercc2a6e02015-11-09 19:56:35 +0000247 /// \brief Creates temp alloca for intermediate operations on atomic value.
248 Address CreateTempAlloca() const;
John McCalla8ec7eb2013-03-07 21:37:17 +0000249 private:
250 bool requiresMemSetZero(llvm::Type *type) const;
Alexey Bataevb8329262015-02-27 06:33:30 +0000251
Alexey Bataevb8329262015-02-27 06:33:30 +0000252
253 /// \brief Emits atomic load as a libcall.
254 void EmitAtomicLoadLibcall(llvm::Value *AddForLoaded,
255 llvm::AtomicOrdering AO, bool IsVolatile);
256 /// \brief Emits atomic load as LLVM instruction.
257 llvm::Value *EmitAtomicLoadOp(llvm::AtomicOrdering AO, bool IsVolatile);
258 /// \brief Emits atomic compare-and-exchange op as a libcall.
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000259 llvm::Value *EmitAtomicCompareExchangeLibcall(
260 llvm::Value *ExpectedAddr, llvm::Value *DesiredAddr,
JF Bastien92f4ef12016-04-06 17:26:42 +0000261 llvm::AtomicOrdering Success =
262 llvm::AtomicOrdering::SequentiallyConsistent,
263 llvm::AtomicOrdering Failure =
264 llvm::AtomicOrdering::SequentiallyConsistent);
Alexey Bataevb8329262015-02-27 06:33:30 +0000265 /// \brief Emits atomic compare-and-exchange op as LLVM instruction.
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000266 std::pair<llvm::Value *, llvm::Value *> EmitAtomicCompareExchangeOp(
267 llvm::Value *ExpectedVal, llvm::Value *DesiredVal,
JF Bastien92f4ef12016-04-06 17:26:42 +0000268 llvm::AtomicOrdering Success =
269 llvm::AtomicOrdering::SequentiallyConsistent,
270 llvm::AtomicOrdering Failure =
271 llvm::AtomicOrdering::SequentiallyConsistent,
Alexey Bataevb8329262015-02-27 06:33:30 +0000272 bool IsWeak = false);
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000273 /// \brief Emit atomic update as libcalls.
274 void
275 EmitAtomicUpdateLibcall(llvm::AtomicOrdering AO,
276 const llvm::function_ref<RValue(RValue)> &UpdateOp,
277 bool IsVolatile);
278 /// \brief Emit atomic update as LLVM instructions.
279 void EmitAtomicUpdateOp(llvm::AtomicOrdering AO,
280 const llvm::function_ref<RValue(RValue)> &UpdateOp,
281 bool IsVolatile);
282 /// \brief Emit atomic update as libcalls.
283 void EmitAtomicUpdateLibcall(llvm::AtomicOrdering AO, RValue UpdateRVal,
284 bool IsVolatile);
285 /// \brief Emit atomic update as LLVM instructions.
286 void EmitAtomicUpdateOp(llvm::AtomicOrdering AO, RValue UpdateRal,
287 bool IsVolatile);
John McCalla8ec7eb2013-03-07 21:37:17 +0000288 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000289}
John McCalla8ec7eb2013-03-07 21:37:17 +0000290
John McCall7f416cc2015-09-08 08:05:57 +0000291Address AtomicInfo::CreateTempAlloca() const {
292 Address TempAlloca = CGF.CreateMemTemp(
Alexey Bataevb8329262015-02-27 06:33:30 +0000293 (LVal.isBitField() && ValueSizeInBits > AtomicSizeInBits) ? ValueTy
294 : AtomicTy,
John McCall7f416cc2015-09-08 08:05:57 +0000295 getAtomicAlignment(),
Alexey Bataevb8329262015-02-27 06:33:30 +0000296 "atomic-temp");
Alexey Bataevb8329262015-02-27 06:33:30 +0000297 // Cast to pointer to value type for bitfields.
298 if (LVal.isBitField())
299 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +0000300 TempAlloca, getAtomicAddress().getType());
Alexey Bataevb8329262015-02-27 06:33:30 +0000301 return TempAlloca;
302}
303
John McCalla8ec7eb2013-03-07 21:37:17 +0000304static RValue emitAtomicLibcall(CodeGenFunction &CGF,
305 StringRef fnName,
306 QualType resultType,
307 CallArgList &args) {
308 const CGFunctionInfo &fnInfo =
John McCallc56a8b32016-03-11 04:30:31 +0000309 CGF.CGM.getTypes().arrangeBuiltinFunctionCall(resultType, args);
John McCalla8ec7eb2013-03-07 21:37:17 +0000310 llvm::FunctionType *fnTy = CGF.CGM.getTypes().GetFunctionType(fnInfo);
311 llvm::Constant *fn = CGF.CGM.CreateRuntimeFunction(fnTy, fnName);
John McCallb92ab1a2016-10-26 23:46:34 +0000312 auto callee = CGCallee::forDirect(fn);
313 return CGF.EmitCall(fnInfo, callee, ReturnValueSlot(), args);
John McCalla8ec7eb2013-03-07 21:37:17 +0000314}
315
316/// Does a store of the given IR type modify the full expected width?
317static bool isFullSizeType(CodeGenModule &CGM, llvm::Type *type,
318 uint64_t expectedSize) {
319 return (CGM.getDataLayout().getTypeStoreSize(type) * 8 == expectedSize);
320}
321
322/// Does the atomic type require memsetting to zero before initialization?
323///
324/// The IR type is provided as a way of making certain queries faster.
325bool AtomicInfo::requiresMemSetZero(llvm::Type *type) const {
326 // If the atomic type has size padding, we definitely need a memset.
327 if (hasPadding()) return true;
328
329 // Otherwise, do some simple heuristics to try to avoid it:
330 switch (getEvaluationKind()) {
331 // For scalars and complexes, check whether the store size of the
332 // type uses the full size.
333 case TEK_Scalar:
334 return !isFullSizeType(CGF.CGM, type, AtomicSizeInBits);
335 case TEK_Complex:
336 return !isFullSizeType(CGF.CGM, type->getStructElementType(0),
337 AtomicSizeInBits / 2);
338
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000339 // Padding in structs has an undefined bit pattern. User beware.
John McCalla8ec7eb2013-03-07 21:37:17 +0000340 case TEK_Aggregate:
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000341 return false;
John McCalla8ec7eb2013-03-07 21:37:17 +0000342 }
343 llvm_unreachable("bad evaluation kind");
344}
345
Alexey Bataevb57056f2015-01-22 06:17:56 +0000346bool AtomicInfo::emitMemSetZeroIfNecessary() const {
347 assert(LVal.isSimple());
John McCall7f416cc2015-09-08 08:05:57 +0000348 llvm::Value *addr = LVal.getPointer();
John McCalla8ec7eb2013-03-07 21:37:17 +0000349 if (!requiresMemSetZero(addr->getType()->getPointerElementType()))
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000350 return false;
John McCalla8ec7eb2013-03-07 21:37:17 +0000351
Alexey Bataevb8329262015-02-27 06:33:30 +0000352 CGF.Builder.CreateMemSet(
353 addr, llvm::ConstantInt::get(CGF.Int8Ty, 0),
354 CGF.getContext().toCharUnitsFromBits(AtomicSizeInBits).getQuantity(),
355 LVal.getAlignment().getQuantity());
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000356 return true;
John McCalla8ec7eb2013-03-07 21:37:17 +0000357}
358
Tim Northovercadbbe12014-06-13 19:43:04 +0000359static void emitAtomicCmpXchg(CodeGenFunction &CGF, AtomicExpr *E, bool IsWeak,
John McCall7f416cc2015-09-08 08:05:57 +0000360 Address Dest, Address Ptr,
361 Address Val1, Address Val2,
362 uint64_t Size,
Tim Northover9c177222014-03-13 19:25:48 +0000363 llvm::AtomicOrdering SuccessOrder,
Yaxun Liu39195062017-08-04 18:16:31 +0000364 llvm::AtomicOrdering FailureOrder,
365 llvm::SyncScope::ID Scope) {
Tim Northover9c177222014-03-13 19:25:48 +0000366 // Note that cmpxchg doesn't support weak cmpxchg, at least at the moment.
John McCall7f416cc2015-09-08 08:05:57 +0000367 llvm::Value *Expected = CGF.Builder.CreateLoad(Val1);
368 llvm::Value *Desired = CGF.Builder.CreateLoad(Val2);
Tim Northover9c177222014-03-13 19:25:48 +0000369
Tim Northoverb49b04b2014-06-13 14:24:59 +0000370 llvm::AtomicCmpXchgInst *Pair = CGF.Builder.CreateAtomicCmpXchg(
Yaxun Liu39195062017-08-04 18:16:31 +0000371 Ptr.getPointer(), Expected, Desired, SuccessOrder, FailureOrder,
372 Scope);
Tim Northoverb49b04b2014-06-13 14:24:59 +0000373 Pair->setVolatile(E->isVolatile());
Tim Northovercadbbe12014-06-13 19:43:04 +0000374 Pair->setWeak(IsWeak);
Tim Northover9c177222014-03-13 19:25:48 +0000375
376 // Cmp holds the result of the compare-exchange operation: true on success,
377 // false on failure.
Tim Northoverb49b04b2014-06-13 14:24:59 +0000378 llvm::Value *Old = CGF.Builder.CreateExtractValue(Pair, 0);
379 llvm::Value *Cmp = CGF.Builder.CreateExtractValue(Pair, 1);
Tim Northover9c177222014-03-13 19:25:48 +0000380
381 // This basic block is used to hold the store instruction if the operation
382 // failed.
383 llvm::BasicBlock *StoreExpectedBB =
384 CGF.createBasicBlock("cmpxchg.store_expected", CGF.CurFn);
385
386 // This basic block is the exit point of the operation, we should end up
387 // here regardless of whether or not the operation succeeded.
388 llvm::BasicBlock *ContinueBB =
389 CGF.createBasicBlock("cmpxchg.continue", CGF.CurFn);
390
391 // Update Expected if Expected isn't equal to Old, otherwise branch to the
392 // exit point.
393 CGF.Builder.CreateCondBr(Cmp, ContinueBB, StoreExpectedBB);
394
395 CGF.Builder.SetInsertPoint(StoreExpectedBB);
396 // Update the memory at Expected with Old's value.
John McCall7f416cc2015-09-08 08:05:57 +0000397 CGF.Builder.CreateStore(Old, Val1);
Tim Northover9c177222014-03-13 19:25:48 +0000398 // Finally, branch to the exit point.
399 CGF.Builder.CreateBr(ContinueBB);
400
401 CGF.Builder.SetInsertPoint(ContinueBB);
402 // Update the memory at Dest with Cmp's value.
403 CGF.EmitStoreOfScalar(Cmp, CGF.MakeAddrLValue(Dest, E->getType()));
Tim Northover9c177222014-03-13 19:25:48 +0000404}
405
406/// Given an ordering required on success, emit all possible cmpxchg
407/// instructions to cope with the provided (but possibly only dynamically known)
408/// FailureOrder.
409static void emitAtomicCmpXchgFailureSet(CodeGenFunction &CGF, AtomicExpr *E,
JF Bastiendda2cb12016-04-18 18:01:49 +0000410 bool IsWeak, Address Dest, Address Ptr,
411 Address Val1, Address Val2,
Tim Northover9c177222014-03-13 19:25:48 +0000412 llvm::Value *FailureOrderVal,
John McCall7f416cc2015-09-08 08:05:57 +0000413 uint64_t Size,
Yaxun Liu39195062017-08-04 18:16:31 +0000414 llvm::AtomicOrdering SuccessOrder,
415 llvm::SyncScope::ID Scope) {
Tim Northover9c177222014-03-13 19:25:48 +0000416 llvm::AtomicOrdering FailureOrder;
417 if (llvm::ConstantInt *FO = dyn_cast<llvm::ConstantInt>(FailureOrderVal)) {
JF Bastiendda2cb12016-04-18 18:01:49 +0000418 auto FOS = FO->getSExtValue();
419 if (!llvm::isValidAtomicOrderingCABI(FOS))
JF Bastien92f4ef12016-04-06 17:26:42 +0000420 FailureOrder = llvm::AtomicOrdering::Monotonic;
JF Bastiendda2cb12016-04-18 18:01:49 +0000421 else
422 switch ((llvm::AtomicOrderingCABI)FOS) {
423 case llvm::AtomicOrderingCABI::relaxed:
424 case llvm::AtomicOrderingCABI::release:
425 case llvm::AtomicOrderingCABI::acq_rel:
426 FailureOrder = llvm::AtomicOrdering::Monotonic;
427 break;
428 case llvm::AtomicOrderingCABI::consume:
429 case llvm::AtomicOrderingCABI::acquire:
430 FailureOrder = llvm::AtomicOrdering::Acquire;
431 break;
432 case llvm::AtomicOrderingCABI::seq_cst:
433 FailureOrder = llvm::AtomicOrdering::SequentiallyConsistent;
434 break;
435 }
JF Bastiendd11ee72016-04-06 23:37:36 +0000436 if (isStrongerThan(FailureOrder, SuccessOrder)) {
437 // Don't assert on undefined behavior "failure argument shall be no
438 // stronger than the success argument".
Tim Northover9c177222014-03-13 19:25:48 +0000439 FailureOrder =
JF Bastiendda2cb12016-04-18 18:01:49 +0000440 llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrder);
Tim Northover9c177222014-03-13 19:25:48 +0000441 }
JF Bastiendda2cb12016-04-18 18:01:49 +0000442 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, Size, SuccessOrder,
Yaxun Liu39195062017-08-04 18:16:31 +0000443 FailureOrder, Scope);
Tim Northover9c177222014-03-13 19:25:48 +0000444 return;
445 }
446
447 // Create all the relevant BB's
Craig Topper8a13c412014-05-21 05:09:00 +0000448 llvm::BasicBlock *MonotonicBB = nullptr, *AcquireBB = nullptr,
449 *SeqCstBB = nullptr;
Tim Northover9c177222014-03-13 19:25:48 +0000450 MonotonicBB = CGF.createBasicBlock("monotonic_fail", CGF.CurFn);
JF Bastien92f4ef12016-04-06 17:26:42 +0000451 if (SuccessOrder != llvm::AtomicOrdering::Monotonic &&
452 SuccessOrder != llvm::AtomicOrdering::Release)
Tim Northover9c177222014-03-13 19:25:48 +0000453 AcquireBB = CGF.createBasicBlock("acquire_fail", CGF.CurFn);
JF Bastien92f4ef12016-04-06 17:26:42 +0000454 if (SuccessOrder == llvm::AtomicOrdering::SequentiallyConsistent)
Tim Northover9c177222014-03-13 19:25:48 +0000455 SeqCstBB = CGF.createBasicBlock("seqcst_fail", CGF.CurFn);
456
457 llvm::BasicBlock *ContBB = CGF.createBasicBlock("atomic.continue", CGF.CurFn);
458
459 llvm::SwitchInst *SI = CGF.Builder.CreateSwitch(FailureOrderVal, MonotonicBB);
460
461 // Emit all the different atomics
462
463 // MonotonicBB is arbitrarily chosen as the default case; in practice, this
464 // doesn't matter unless someone is crazy enough to use something that
465 // doesn't fold to a constant for the ordering.
466 CGF.Builder.SetInsertPoint(MonotonicBB);
Tim Northovercadbbe12014-06-13 19:43:04 +0000467 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2,
Yaxun Liu39195062017-08-04 18:16:31 +0000468 Size, SuccessOrder, llvm::AtomicOrdering::Monotonic, Scope);
Tim Northover9c177222014-03-13 19:25:48 +0000469 CGF.Builder.CreateBr(ContBB);
470
471 if (AcquireBB) {
472 CGF.Builder.SetInsertPoint(AcquireBB);
Tim Northovercadbbe12014-06-13 19:43:04 +0000473 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2,
Yaxun Liu39195062017-08-04 18:16:31 +0000474 Size, SuccessOrder, llvm::AtomicOrdering::Acquire, Scope);
Tim Northover9c177222014-03-13 19:25:48 +0000475 CGF.Builder.CreateBr(ContBB);
JF Bastiendda2cb12016-04-18 18:01:49 +0000476 SI->addCase(CGF.Builder.getInt32((int)llvm::AtomicOrderingCABI::consume),
Tim Northover9c177222014-03-13 19:25:48 +0000477 AcquireBB);
JF Bastiendda2cb12016-04-18 18:01:49 +0000478 SI->addCase(CGF.Builder.getInt32((int)llvm::AtomicOrderingCABI::acquire),
Tim Northover9c177222014-03-13 19:25:48 +0000479 AcquireBB);
480 }
481 if (SeqCstBB) {
482 CGF.Builder.SetInsertPoint(SeqCstBB);
JF Bastien92f4ef12016-04-06 17:26:42 +0000483 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, Size, SuccessOrder,
Yaxun Liu39195062017-08-04 18:16:31 +0000484 llvm::AtomicOrdering::SequentiallyConsistent, Scope);
Tim Northover9c177222014-03-13 19:25:48 +0000485 CGF.Builder.CreateBr(ContBB);
JF Bastiendda2cb12016-04-18 18:01:49 +0000486 SI->addCase(CGF.Builder.getInt32((int)llvm::AtomicOrderingCABI::seq_cst),
Tim Northover9c177222014-03-13 19:25:48 +0000487 SeqCstBB);
488 }
489
490 CGF.Builder.SetInsertPoint(ContBB);
491}
492
John McCall7f416cc2015-09-08 08:05:57 +0000493static void EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *E, Address Dest,
494 Address Ptr, Address Val1, Address Val2,
Tim Northovercadbbe12014-06-13 19:43:04 +0000495 llvm::Value *IsWeak, llvm::Value *FailureOrder,
Yaxun Liu39195062017-08-04 18:16:31 +0000496 uint64_t Size, llvm::AtomicOrdering Order,
497 llvm::SyncScope::ID Scope) {
John McCallfc207f22013-03-07 21:37:12 +0000498 llvm::AtomicRMWInst::BinOp Op = llvm::AtomicRMWInst::Add;
499 llvm::Instruction::BinaryOps PostOp = (llvm::Instruction::BinaryOps)0;
500
501 switch (E->getOp()) {
502 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +0000503 case AtomicExpr::AO__opencl_atomic_init:
John McCallfc207f22013-03-07 21:37:12 +0000504 llvm_unreachable("Already handled!");
505
506 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
Yaxun Liu39195062017-08-04 18:16:31 +0000507 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
Tim Northovercadbbe12014-06-13 19:43:04 +0000508 emitAtomicCmpXchgFailureSet(CGF, E, false, Dest, Ptr, Val1, Val2,
Yaxun Liu39195062017-08-04 18:16:31 +0000509 FailureOrder, Size, Order, Scope);
John McCallfc207f22013-03-07 21:37:12 +0000510 return;
Tim Northovercadbbe12014-06-13 19:43:04 +0000511 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +0000512 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Tim Northovercadbbe12014-06-13 19:43:04 +0000513 emitAtomicCmpXchgFailureSet(CGF, E, true, Dest, Ptr, Val1, Val2,
Yaxun Liu39195062017-08-04 18:16:31 +0000514 FailureOrder, Size, Order, Scope);
Tim Northovercadbbe12014-06-13 19:43:04 +0000515 return;
516 case AtomicExpr::AO__atomic_compare_exchange:
517 case AtomicExpr::AO__atomic_compare_exchange_n: {
518 if (llvm::ConstantInt *IsWeakC = dyn_cast<llvm::ConstantInt>(IsWeak)) {
519 emitAtomicCmpXchgFailureSet(CGF, E, IsWeakC->getZExtValue(), Dest, Ptr,
Yaxun Liu39195062017-08-04 18:16:31 +0000520 Val1, Val2, FailureOrder, Size, Order, Scope);
Tim Northovercadbbe12014-06-13 19:43:04 +0000521 } else {
522 // Create all the relevant BB's
523 llvm::BasicBlock *StrongBB =
524 CGF.createBasicBlock("cmpxchg.strong", CGF.CurFn);
525 llvm::BasicBlock *WeakBB = CGF.createBasicBlock("cmxchg.weak", CGF.CurFn);
526 llvm::BasicBlock *ContBB =
527 CGF.createBasicBlock("cmpxchg.continue", CGF.CurFn);
528
529 llvm::SwitchInst *SI = CGF.Builder.CreateSwitch(IsWeak, WeakBB);
530 SI->addCase(CGF.Builder.getInt1(false), StrongBB);
531
532 CGF.Builder.SetInsertPoint(StrongBB);
533 emitAtomicCmpXchgFailureSet(CGF, E, false, Dest, Ptr, Val1, Val2,
Yaxun Liu39195062017-08-04 18:16:31 +0000534 FailureOrder, Size, Order, Scope);
Tim Northovercadbbe12014-06-13 19:43:04 +0000535 CGF.Builder.CreateBr(ContBB);
536
537 CGF.Builder.SetInsertPoint(WeakBB);
538 emitAtomicCmpXchgFailureSet(CGF, E, true, Dest, Ptr, Val1, Val2,
Yaxun Liu39195062017-08-04 18:16:31 +0000539 FailureOrder, Size, Order, Scope);
Tim Northovercadbbe12014-06-13 19:43:04 +0000540 CGF.Builder.CreateBr(ContBB);
541
542 CGF.Builder.SetInsertPoint(ContBB);
543 }
544 return;
545 }
John McCallfc207f22013-03-07 21:37:12 +0000546 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +0000547 case AtomicExpr::AO__opencl_atomic_load:
John McCallfc207f22013-03-07 21:37:12 +0000548 case AtomicExpr::AO__atomic_load_n:
549 case AtomicExpr::AO__atomic_load: {
550 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Ptr);
Yaxun Liu39195062017-08-04 18:16:31 +0000551 Load->setAtomic(Order, Scope);
John McCallfc207f22013-03-07 21:37:12 +0000552 Load->setVolatile(E->isVolatile());
John McCall7f416cc2015-09-08 08:05:57 +0000553 CGF.Builder.CreateStore(Load, Dest);
John McCallfc207f22013-03-07 21:37:12 +0000554 return;
555 }
556
557 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +0000558 case AtomicExpr::AO__opencl_atomic_store:
John McCallfc207f22013-03-07 21:37:12 +0000559 case AtomicExpr::AO__atomic_store:
560 case AtomicExpr::AO__atomic_store_n: {
John McCall7f416cc2015-09-08 08:05:57 +0000561 llvm::Value *LoadVal1 = CGF.Builder.CreateLoad(Val1);
John McCallfc207f22013-03-07 21:37:12 +0000562 llvm::StoreInst *Store = CGF.Builder.CreateStore(LoadVal1, Ptr);
Yaxun Liu39195062017-08-04 18:16:31 +0000563 Store->setAtomic(Order, Scope);
John McCallfc207f22013-03-07 21:37:12 +0000564 Store->setVolatile(E->isVolatile());
565 return;
566 }
567
568 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +0000569 case AtomicExpr::AO__opencl_atomic_exchange:
John McCallfc207f22013-03-07 21:37:12 +0000570 case AtomicExpr::AO__atomic_exchange_n:
571 case AtomicExpr::AO__atomic_exchange:
572 Op = llvm::AtomicRMWInst::Xchg;
573 break;
574
575 case AtomicExpr::AO__atomic_add_fetch:
576 PostOp = llvm::Instruction::Add;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000577 LLVM_FALLTHROUGH;
John McCallfc207f22013-03-07 21:37:12 +0000578 case AtomicExpr::AO__c11_atomic_fetch_add:
Yaxun Liu39195062017-08-04 18:16:31 +0000579 case AtomicExpr::AO__opencl_atomic_fetch_add:
John McCallfc207f22013-03-07 21:37:12 +0000580 case AtomicExpr::AO__atomic_fetch_add:
581 Op = llvm::AtomicRMWInst::Add;
582 break;
583
584 case AtomicExpr::AO__atomic_sub_fetch:
585 PostOp = llvm::Instruction::Sub;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000586 LLVM_FALLTHROUGH;
John McCallfc207f22013-03-07 21:37:12 +0000587 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +0000588 case AtomicExpr::AO__opencl_atomic_fetch_sub:
John McCallfc207f22013-03-07 21:37:12 +0000589 case AtomicExpr::AO__atomic_fetch_sub:
590 Op = llvm::AtomicRMWInst::Sub;
591 break;
592
Yaxun Liu39195062017-08-04 18:16:31 +0000593 case AtomicExpr::AO__opencl_atomic_fetch_min:
594 Op = E->getValueType()->isSignedIntegerType() ? llvm::AtomicRMWInst::Min
595 : llvm::AtomicRMWInst::UMin;
596 break;
597
598 case AtomicExpr::AO__opencl_atomic_fetch_max:
599 Op = E->getValueType()->isSignedIntegerType() ? llvm::AtomicRMWInst::Max
600 : llvm::AtomicRMWInst::UMax;
601 break;
602
John McCallfc207f22013-03-07 21:37:12 +0000603 case AtomicExpr::AO__atomic_and_fetch:
604 PostOp = llvm::Instruction::And;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000605 LLVM_FALLTHROUGH;
John McCallfc207f22013-03-07 21:37:12 +0000606 case AtomicExpr::AO__c11_atomic_fetch_and:
Yaxun Liu39195062017-08-04 18:16:31 +0000607 case AtomicExpr::AO__opencl_atomic_fetch_and:
John McCallfc207f22013-03-07 21:37:12 +0000608 case AtomicExpr::AO__atomic_fetch_and:
609 Op = llvm::AtomicRMWInst::And;
610 break;
611
612 case AtomicExpr::AO__atomic_or_fetch:
613 PostOp = llvm::Instruction::Or;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000614 LLVM_FALLTHROUGH;
John McCallfc207f22013-03-07 21:37:12 +0000615 case AtomicExpr::AO__c11_atomic_fetch_or:
Yaxun Liu39195062017-08-04 18:16:31 +0000616 case AtomicExpr::AO__opencl_atomic_fetch_or:
John McCallfc207f22013-03-07 21:37:12 +0000617 case AtomicExpr::AO__atomic_fetch_or:
618 Op = llvm::AtomicRMWInst::Or;
619 break;
620
621 case AtomicExpr::AO__atomic_xor_fetch:
622 PostOp = llvm::Instruction::Xor;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000623 LLVM_FALLTHROUGH;
John McCallfc207f22013-03-07 21:37:12 +0000624 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +0000625 case AtomicExpr::AO__opencl_atomic_fetch_xor:
John McCallfc207f22013-03-07 21:37:12 +0000626 case AtomicExpr::AO__atomic_fetch_xor:
627 Op = llvm::AtomicRMWInst::Xor;
628 break;
629
630 case AtomicExpr::AO__atomic_nand_fetch:
James Y Knight7aefb5b2015-11-12 18:37:29 +0000631 PostOp = llvm::Instruction::And; // the NOT is special cased below
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000632 LLVM_FALLTHROUGH;
John McCallfc207f22013-03-07 21:37:12 +0000633 case AtomicExpr::AO__atomic_fetch_nand:
634 Op = llvm::AtomicRMWInst::Nand;
635 break;
636 }
637
John McCall7f416cc2015-09-08 08:05:57 +0000638 llvm::Value *LoadVal1 = CGF.Builder.CreateLoad(Val1);
John McCallfc207f22013-03-07 21:37:12 +0000639 llvm::AtomicRMWInst *RMWI =
Yaxun Liu39195062017-08-04 18:16:31 +0000640 CGF.Builder.CreateAtomicRMW(Op, Ptr.getPointer(), LoadVal1, Order, Scope);
John McCallfc207f22013-03-07 21:37:12 +0000641 RMWI->setVolatile(E->isVolatile());
642
643 // For __atomic_*_fetch operations, perform the operation again to
644 // determine the value which was written.
645 llvm::Value *Result = RMWI;
646 if (PostOp)
647 Result = CGF.Builder.CreateBinOp(PostOp, RMWI, LoadVal1);
648 if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch)
649 Result = CGF.Builder.CreateNot(Result);
John McCall7f416cc2015-09-08 08:05:57 +0000650 CGF.Builder.CreateStore(Result, Dest);
John McCallfc207f22013-03-07 21:37:12 +0000651}
652
653// This function emits any expression (scalar, complex, or aggregate)
654// into a temporary alloca.
John McCall7f416cc2015-09-08 08:05:57 +0000655static Address
John McCallfc207f22013-03-07 21:37:12 +0000656EmitValToTemp(CodeGenFunction &CGF, Expr *E) {
John McCall7f416cc2015-09-08 08:05:57 +0000657 Address DeclPtr = CGF.CreateMemTemp(E->getType(), ".atomictmp");
John McCallfc207f22013-03-07 21:37:12 +0000658 CGF.EmitAnyExprToMem(E, DeclPtr, E->getType().getQualifiers(),
659 /*Init*/ true);
660 return DeclPtr;
661}
662
Yaxun Liu30d652a2017-08-15 16:02:49 +0000663static void EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *Expr, Address Dest,
664 Address Ptr, Address Val1, Address Val2,
665 llvm::Value *IsWeak, llvm::Value *FailureOrder,
666 uint64_t Size, llvm::AtomicOrdering Order,
667 llvm::Value *Scope) {
668 auto ScopeModel = Expr->getScopeModel();
669
670 // LLVM atomic instructions always have synch scope. If clang atomic
671 // expression has no scope operand, use default LLVM synch scope.
672 if (!ScopeModel) {
673 EmitAtomicOp(CGF, Expr, Dest, Ptr, Val1, Val2, IsWeak, FailureOrder, Size,
674 Order, CGF.CGM.getLLVMContext().getOrInsertSyncScopeID(""));
675 return;
676 }
677
678 // Handle constant scope.
679 if (auto SC = dyn_cast<llvm::ConstantInt>(Scope)) {
680 auto SCID = CGF.getTargetHooks().getLLVMSyncScopeID(
681 ScopeModel->map(SC->getZExtValue()), CGF.CGM.getLLVMContext());
682 EmitAtomicOp(CGF, Expr, Dest, Ptr, Val1, Val2, IsWeak, FailureOrder, Size,
683 Order, SCID);
684 return;
685 }
686
687 // Handle non-constant scope.
688 auto &Builder = CGF.Builder;
689 auto Scopes = ScopeModel->getRuntimeValues();
690 llvm::DenseMap<unsigned, llvm::BasicBlock *> BB;
691 for (auto S : Scopes)
692 BB[S] = CGF.createBasicBlock(getAsString(ScopeModel->map(S)), CGF.CurFn);
693
694 llvm::BasicBlock *ContBB =
695 CGF.createBasicBlock("atomic.scope.continue", CGF.CurFn);
696
697 auto *SC = Builder.CreateIntCast(Scope, Builder.getInt32Ty(), false);
698 // If unsupported synch scope is encountered at run time, assume a fallback
699 // synch scope value.
700 auto FallBack = ScopeModel->getFallBackValue();
701 llvm::SwitchInst *SI = Builder.CreateSwitch(SC, BB[FallBack]);
702 for (auto S : Scopes) {
703 auto *B = BB[S];
704 if (S != FallBack)
705 SI->addCase(Builder.getInt32(S), B);
706
707 Builder.SetInsertPoint(B);
708 EmitAtomicOp(CGF, Expr, Dest, Ptr, Val1, Val2, IsWeak, FailureOrder, Size,
709 Order,
710 CGF.getTargetHooks().getLLVMSyncScopeID(ScopeModel->map(S),
711 CGF.getLLVMContext()));
712 Builder.CreateBr(ContBB);
713 }
714
715 Builder.SetInsertPoint(ContBB);
716}
717
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000718static void
719AddDirectArgument(CodeGenFunction &CGF, CallArgList &Args,
Nick Lewycky2d84e842013-10-02 02:29:49 +0000720 bool UseOptimizedLibcall, llvm::Value *Val, QualType ValTy,
David Majnemer0392cf82014-08-29 07:27:49 +0000721 SourceLocation Loc, CharUnits SizeInChars) {
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000722 if (UseOptimizedLibcall) {
723 // Load value and pass it to the function directly.
John McCall7f416cc2015-09-08 08:05:57 +0000724 CharUnits Align = CGF.getContext().getTypeAlignInChars(ValTy);
David Majnemer0392cf82014-08-29 07:27:49 +0000725 int64_t SizeInBits = CGF.getContext().toBits(SizeInChars);
726 ValTy =
727 CGF.getContext().getIntTypeForBitwidth(SizeInBits, /*Signed=*/false);
728 llvm::Type *IPtrTy = llvm::IntegerType::get(CGF.getLLVMContext(),
729 SizeInBits)->getPointerTo();
John McCall7f416cc2015-09-08 08:05:57 +0000730 Address Ptr = Address(CGF.Builder.CreateBitCast(Val, IPtrTy), Align);
731 Val = CGF.EmitLoadOfScalar(Ptr, false,
732 CGF.getContext().getPointerType(ValTy),
David Majnemer0392cf82014-08-29 07:27:49 +0000733 Loc);
734 // Coerce the value into an appropriately sized integer type.
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000735 Args.add(RValue::get(Val), ValTy);
736 } else {
737 // Non-optimized functions always take a reference.
738 Args.add(RValue::get(CGF.EmitCastToVoidPtr(Val)),
739 CGF.getContext().VoidPtrTy);
740 }
741}
742
Tim Northovercc2a6e02015-11-09 19:56:35 +0000743RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E) {
John McCallfc207f22013-03-07 21:37:12 +0000744 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
745 QualType MemTy = AtomicTy;
746 if (const AtomicType *AT = AtomicTy->getAs<AtomicType>())
747 MemTy = AT->getValueType();
John McCall7f416cc2015-09-08 08:05:57 +0000748 llvm::Value *IsWeak = nullptr, *OrderFail = nullptr;
749
750 Address Val1 = Address::invalid();
751 Address Val2 = Address::invalid();
Tim Northovercc2a6e02015-11-09 19:56:35 +0000752 Address Dest = Address::invalid();
Wei Mi01414bd2017-09-25 19:57:59 +0000753 Address Ptr = EmitPointerWithAlignment(E->getPtr());
754
Tim Northover9dc1d0c2018-04-23 08:16:24 +0000755 if (E->getOp() == AtomicExpr::AO__c11_atomic_init ||
756 E->getOp() == AtomicExpr::AO__opencl_atomic_init) {
757 LValue lvalue = MakeAddrLValue(Ptr, AtomicTy);
758 EmitAtomicInit(E->getVal1(), lvalue);
759 return RValue::get(nullptr);
760 }
761
Wei Mi01414bd2017-09-25 19:57:59 +0000762 CharUnits sizeChars, alignChars;
763 std::tie(sizeChars, alignChars) = getContext().getTypeInfoInChars(AtomicTy);
764 uint64_t Size = sizeChars.getQuantity();
765 unsigned MaxInlineWidthInBits = getTarget().getMaxAtomicInlineWidth();
766 bool UseLibcall = ((Ptr.getAlignment() % sizeChars) != 0 ||
767 getContext().toBits(sizeChars) > MaxInlineWidthInBits);
John McCallfc207f22013-03-07 21:37:12 +0000768
Tim Northover9dc1d0c2018-04-23 08:16:24 +0000769 if (UseLibcall)
770 CGM.getDiags().Report(E->getLocStart(), diag::warn_atomic_op_misaligned);
John McCallfc207f22013-03-07 21:37:12 +0000771
Craig Topper8a13c412014-05-21 05:09:00 +0000772 llvm::Value *Order = EmitScalarExpr(E->getOrder());
Yaxun Liu30d652a2017-08-15 16:02:49 +0000773 llvm::Value *Scope =
774 E->getScopeModel() ? EmitScalarExpr(E->getScope()) : nullptr;
John McCallfc207f22013-03-07 21:37:12 +0000775
776 switch (E->getOp()) {
777 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +0000778 case AtomicExpr::AO__opencl_atomic_init:
James Y Knight81167fb2015-08-05 16:57:36 +0000779 llvm_unreachable("Already handled above with EmitAtomicInit!");
John McCallfc207f22013-03-07 21:37:12 +0000780
781 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +0000782 case AtomicExpr::AO__opencl_atomic_load:
John McCallfc207f22013-03-07 21:37:12 +0000783 case AtomicExpr::AO__atomic_load_n:
784 break;
785
786 case AtomicExpr::AO__atomic_load:
John McCall7f416cc2015-09-08 08:05:57 +0000787 Dest = EmitPointerWithAlignment(E->getVal1());
John McCallfc207f22013-03-07 21:37:12 +0000788 break;
789
790 case AtomicExpr::AO__atomic_store:
John McCall7f416cc2015-09-08 08:05:57 +0000791 Val1 = EmitPointerWithAlignment(E->getVal1());
John McCallfc207f22013-03-07 21:37:12 +0000792 break;
793
794 case AtomicExpr::AO__atomic_exchange:
John McCall7f416cc2015-09-08 08:05:57 +0000795 Val1 = EmitPointerWithAlignment(E->getVal1());
796 Dest = EmitPointerWithAlignment(E->getVal2());
John McCallfc207f22013-03-07 21:37:12 +0000797 break;
798
799 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
800 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +0000801 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
802 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
John McCallfc207f22013-03-07 21:37:12 +0000803 case AtomicExpr::AO__atomic_compare_exchange_n:
804 case AtomicExpr::AO__atomic_compare_exchange:
John McCall7f416cc2015-09-08 08:05:57 +0000805 Val1 = EmitPointerWithAlignment(E->getVal1());
John McCallfc207f22013-03-07 21:37:12 +0000806 if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange)
John McCall7f416cc2015-09-08 08:05:57 +0000807 Val2 = EmitPointerWithAlignment(E->getVal2());
John McCallfc207f22013-03-07 21:37:12 +0000808 else
809 Val2 = EmitValToTemp(*this, E->getVal2());
810 OrderFail = EmitScalarExpr(E->getOrderFail());
Yaxun Liu39195062017-08-04 18:16:31 +0000811 if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange_n ||
812 E->getOp() == AtomicExpr::AO__atomic_compare_exchange)
Tim Northovercadbbe12014-06-13 19:43:04 +0000813 IsWeak = EmitScalarExpr(E->getWeak());
John McCallfc207f22013-03-07 21:37:12 +0000814 break;
815
816 case AtomicExpr::AO__c11_atomic_fetch_add:
817 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +0000818 case AtomicExpr::AO__opencl_atomic_fetch_add:
819 case AtomicExpr::AO__opencl_atomic_fetch_sub:
John McCallfc207f22013-03-07 21:37:12 +0000820 if (MemTy->isPointerType()) {
821 // For pointer arithmetic, we're required to do a bit of math:
822 // adding 1 to an int* is not the same as adding 1 to a uintptr_t.
823 // ... but only for the C11 builtins. The GNU builtins expect the
824 // user to multiply by sizeof(T).
825 QualType Val1Ty = E->getVal1()->getType();
826 llvm::Value *Val1Scalar = EmitScalarExpr(E->getVal1());
827 CharUnits PointeeIncAmt =
828 getContext().getTypeSizeInChars(MemTy->getPointeeType());
829 Val1Scalar = Builder.CreateMul(Val1Scalar, CGM.getSize(PointeeIncAmt));
John McCall7f416cc2015-09-08 08:05:57 +0000830 auto Temp = CreateMemTemp(Val1Ty, ".atomictmp");
831 Val1 = Temp;
832 EmitStoreOfScalar(Val1Scalar, MakeAddrLValue(Temp, Val1Ty));
John McCallfc207f22013-03-07 21:37:12 +0000833 break;
834 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000835 LLVM_FALLTHROUGH;
John McCallfc207f22013-03-07 21:37:12 +0000836 case AtomicExpr::AO__atomic_fetch_add:
837 case AtomicExpr::AO__atomic_fetch_sub:
838 case AtomicExpr::AO__atomic_add_fetch:
839 case AtomicExpr::AO__atomic_sub_fetch:
840 case AtomicExpr::AO__c11_atomic_store:
841 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +0000842 case AtomicExpr::AO__opencl_atomic_store:
843 case AtomicExpr::AO__opencl_atomic_exchange:
John McCallfc207f22013-03-07 21:37:12 +0000844 case AtomicExpr::AO__atomic_store_n:
845 case AtomicExpr::AO__atomic_exchange_n:
846 case AtomicExpr::AO__c11_atomic_fetch_and:
847 case AtomicExpr::AO__c11_atomic_fetch_or:
848 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +0000849 case AtomicExpr::AO__opencl_atomic_fetch_and:
850 case AtomicExpr::AO__opencl_atomic_fetch_or:
851 case AtomicExpr::AO__opencl_atomic_fetch_xor:
852 case AtomicExpr::AO__opencl_atomic_fetch_min:
853 case AtomicExpr::AO__opencl_atomic_fetch_max:
John McCallfc207f22013-03-07 21:37:12 +0000854 case AtomicExpr::AO__atomic_fetch_and:
855 case AtomicExpr::AO__atomic_fetch_or:
856 case AtomicExpr::AO__atomic_fetch_xor:
857 case AtomicExpr::AO__atomic_fetch_nand:
858 case AtomicExpr::AO__atomic_and_fetch:
859 case AtomicExpr::AO__atomic_or_fetch:
860 case AtomicExpr::AO__atomic_xor_fetch:
861 case AtomicExpr::AO__atomic_nand_fetch:
862 Val1 = EmitValToTemp(*this, E->getVal1());
863 break;
864 }
865
David Majnemeree8d04d2014-12-12 08:16:09 +0000866 QualType RValTy = E->getType().getUnqualifiedType();
867
Tim Northovercc2a6e02015-11-09 19:56:35 +0000868 // The inlined atomics only function on iN types, where N is a power of 2. We
869 // need to make sure (via temporaries if necessary) that all incoming values
870 // are compatible.
871 LValue AtomicVal = MakeAddrLValue(Ptr, AtomicTy);
872 AtomicInfo Atomics(*this, AtomicVal);
873
874 Ptr = Atomics.emitCastToAtomicIntPointer(Ptr);
875 if (Val1.isValid()) Val1 = Atomics.convertToAtomicIntPointer(Val1);
876 if (Val2.isValid()) Val2 = Atomics.convertToAtomicIntPointer(Val2);
877 if (Dest.isValid())
878 Dest = Atomics.emitCastToAtomicIntPointer(Dest);
879 else if (E->isCmpXChg())
880 Dest = CreateMemTemp(RValTy, "cmpxchg.bool");
881 else if (!RValTy->isVoidType())
882 Dest = Atomics.emitCastToAtomicIntPointer(Atomics.CreateTempAlloca());
John McCallfc207f22013-03-07 21:37:12 +0000883
884 // Use a library call. See: http://gcc.gnu.org/wiki/Atomic/GCCMM/LIbrary .
885 if (UseLibcall) {
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000886 bool UseOptimizedLibcall = false;
887 switch (E->getOp()) {
James Y Knight81167fb2015-08-05 16:57:36 +0000888 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +0000889 case AtomicExpr::AO__opencl_atomic_init:
James Y Knight81167fb2015-08-05 16:57:36 +0000890 llvm_unreachable("Already handled above with EmitAtomicInit!");
891
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000892 case AtomicExpr::AO__c11_atomic_fetch_add:
Yaxun Liu39195062017-08-04 18:16:31 +0000893 case AtomicExpr::AO__opencl_atomic_fetch_add:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000894 case AtomicExpr::AO__atomic_fetch_add:
895 case AtomicExpr::AO__c11_atomic_fetch_and:
Yaxun Liu39195062017-08-04 18:16:31 +0000896 case AtomicExpr::AO__opencl_atomic_fetch_and:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000897 case AtomicExpr::AO__atomic_fetch_and:
898 case AtomicExpr::AO__c11_atomic_fetch_or:
Yaxun Liu39195062017-08-04 18:16:31 +0000899 case AtomicExpr::AO__opencl_atomic_fetch_or:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000900 case AtomicExpr::AO__atomic_fetch_or:
James Y Knight81167fb2015-08-05 16:57:36 +0000901 case AtomicExpr::AO__atomic_fetch_nand:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000902 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +0000903 case AtomicExpr::AO__opencl_atomic_fetch_sub:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000904 case AtomicExpr::AO__atomic_fetch_sub:
905 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +0000906 case AtomicExpr::AO__opencl_atomic_fetch_xor:
907 case AtomicExpr::AO__opencl_atomic_fetch_min:
908 case AtomicExpr::AO__opencl_atomic_fetch_max:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000909 case AtomicExpr::AO__atomic_fetch_xor:
James Y Knight81167fb2015-08-05 16:57:36 +0000910 case AtomicExpr::AO__atomic_add_fetch:
911 case AtomicExpr::AO__atomic_and_fetch:
912 case AtomicExpr::AO__atomic_nand_fetch:
913 case AtomicExpr::AO__atomic_or_fetch:
914 case AtomicExpr::AO__atomic_sub_fetch:
915 case AtomicExpr::AO__atomic_xor_fetch:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000916 // For these, only library calls for certain sizes exist.
917 UseOptimizedLibcall = true;
918 break;
James Y Knight81167fb2015-08-05 16:57:36 +0000919
920 case AtomicExpr::AO__c11_atomic_load:
921 case AtomicExpr::AO__c11_atomic_store:
922 case AtomicExpr::AO__c11_atomic_exchange:
923 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
924 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
Yaxun Liu39195062017-08-04 18:16:31 +0000925 case AtomicExpr::AO__opencl_atomic_load:
926 case AtomicExpr::AO__opencl_atomic_store:
927 case AtomicExpr::AO__opencl_atomic_exchange:
928 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
929 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
James Y Knight81167fb2015-08-05 16:57:36 +0000930 case AtomicExpr::AO__atomic_load_n:
931 case AtomicExpr::AO__atomic_load:
932 case AtomicExpr::AO__atomic_store_n:
933 case AtomicExpr::AO__atomic_store:
934 case AtomicExpr::AO__atomic_exchange_n:
935 case AtomicExpr::AO__atomic_exchange:
936 case AtomicExpr::AO__atomic_compare_exchange_n:
937 case AtomicExpr::AO__atomic_compare_exchange:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000938 // Only use optimized library calls for sizes for which they exist.
939 if (Size == 1 || Size == 2 || Size == 4 || Size == 8)
940 UseOptimizedLibcall = true;
941 break;
942 }
John McCallfc207f22013-03-07 21:37:12 +0000943
John McCallfc207f22013-03-07 21:37:12 +0000944 CallArgList Args;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000945 if (!UseOptimizedLibcall) {
946 // For non-optimized library calls, the size is the first parameter
947 Args.add(RValue::get(llvm::ConstantInt::get(SizeTy, Size)),
948 getContext().getSizeType());
949 }
950 // Atomic address is the first or second parameter
Yaxun Liu39195062017-08-04 18:16:31 +0000951 // The OpenCL atomic library functions only accept pointer arguments to
952 // generic address space.
953 auto CastToGenericAddrSpace = [&](llvm::Value *V, QualType PT) {
954 if (!E->isOpenCL())
955 return V;
956 auto AS = PT->getAs<PointerType>()->getPointeeType().getAddressSpace();
957 if (AS == LangAS::opencl_generic)
958 return V;
959 auto DestAS = getContext().getTargetAddressSpace(LangAS::opencl_generic);
960 auto T = V->getType();
961 auto *DestType = T->getPointerElementType()->getPointerTo(DestAS);
962
963 return getTargetHooks().performAddrSpaceCast(
964 *this, V, AS, LangAS::opencl_generic, DestType, false);
965 };
966
967 Args.add(RValue::get(CastToGenericAddrSpace(
968 EmitCastToVoidPtr(Ptr.getPointer()), E->getPtr()->getType())),
John McCall7f416cc2015-09-08 08:05:57 +0000969 getContext().VoidPtrTy);
John McCallfc207f22013-03-07 21:37:12 +0000970
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000971 std::string LibCallName;
Logan Chien74798a32014-03-26 17:35:01 +0000972 QualType LoweredMemTy =
973 MemTy->isPointerType() ? getContext().getIntPtrType() : MemTy;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000974 QualType RetTy;
975 bool HaveRetTy = false;
James Y Knight7aefb5b2015-11-12 18:37:29 +0000976 llvm::Instruction::BinaryOps PostOp = (llvm::Instruction::BinaryOps)0;
John McCallfc207f22013-03-07 21:37:12 +0000977 switch (E->getOp()) {
James Y Knight81167fb2015-08-05 16:57:36 +0000978 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +0000979 case AtomicExpr::AO__opencl_atomic_init:
James Y Knight81167fb2015-08-05 16:57:36 +0000980 llvm_unreachable("Already handled!");
981
John McCallfc207f22013-03-07 21:37:12 +0000982 // There is only one libcall for compare an exchange, because there is no
983 // optimisation benefit possible from a libcall version of a weak compare
984 // and exchange.
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000985 // bool __atomic_compare_exchange(size_t size, void *mem, void *expected,
John McCallfc207f22013-03-07 21:37:12 +0000986 // void *desired, int success, int failure)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000987 // bool __atomic_compare_exchange_N(T *mem, T *expected, T desired,
988 // int success, int failure)
John McCallfc207f22013-03-07 21:37:12 +0000989 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
990 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
Yaxun Liu39195062017-08-04 18:16:31 +0000991 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
992 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
John McCallfc207f22013-03-07 21:37:12 +0000993 case AtomicExpr::AO__atomic_compare_exchange:
994 case AtomicExpr::AO__atomic_compare_exchange_n:
995 LibCallName = "__atomic_compare_exchange";
996 RetTy = getContext().BoolTy;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000997 HaveRetTy = true;
Yaxun Liu39195062017-08-04 18:16:31 +0000998 Args.add(
999 RValue::get(CastToGenericAddrSpace(
1000 EmitCastToVoidPtr(Val1.getPointer()), E->getVal1()->getType())),
1001 getContext().VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00001002 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val2.getPointer(),
1003 MemTy, E->getExprLoc(), sizeChars);
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001004 Args.add(RValue::get(Order), getContext().IntTy);
John McCallfc207f22013-03-07 21:37:12 +00001005 Order = OrderFail;
1006 break;
1007 // void __atomic_exchange(size_t size, void *mem, void *val, void *return,
1008 // int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001009 // T __atomic_exchange_N(T *mem, T val, int order)
John McCallfc207f22013-03-07 21:37:12 +00001010 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00001011 case AtomicExpr::AO__opencl_atomic_exchange:
John McCallfc207f22013-03-07 21:37:12 +00001012 case AtomicExpr::AO__atomic_exchange_n:
1013 case AtomicExpr::AO__atomic_exchange:
1014 LibCallName = "__atomic_exchange";
John McCall7f416cc2015-09-08 08:05:57 +00001015 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1016 MemTy, E->getExprLoc(), sizeChars);
John McCallfc207f22013-03-07 21:37:12 +00001017 break;
1018 // void __atomic_store(size_t size, void *mem, void *val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001019 // void __atomic_store_N(T *mem, T val, int order)
John McCallfc207f22013-03-07 21:37:12 +00001020 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00001021 case AtomicExpr::AO__opencl_atomic_store:
John McCallfc207f22013-03-07 21:37:12 +00001022 case AtomicExpr::AO__atomic_store:
1023 case AtomicExpr::AO__atomic_store_n:
1024 LibCallName = "__atomic_store";
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001025 RetTy = getContext().VoidTy;
1026 HaveRetTy = true;
John McCall7f416cc2015-09-08 08:05:57 +00001027 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1028 MemTy, E->getExprLoc(), sizeChars);
John McCallfc207f22013-03-07 21:37:12 +00001029 break;
1030 // void __atomic_load(size_t size, void *mem, void *return, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001031 // T __atomic_load_N(T *mem, int order)
John McCallfc207f22013-03-07 21:37:12 +00001032 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00001033 case AtomicExpr::AO__opencl_atomic_load:
John McCallfc207f22013-03-07 21:37:12 +00001034 case AtomicExpr::AO__atomic_load:
1035 case AtomicExpr::AO__atomic_load_n:
1036 LibCallName = "__atomic_load";
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001037 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +00001038 // T __atomic_add_fetch_N(T *mem, T val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001039 // T __atomic_fetch_add_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +00001040 case AtomicExpr::AO__atomic_add_fetch:
1041 PostOp = llvm::Instruction::Add;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001042 LLVM_FALLTHROUGH;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001043 case AtomicExpr::AO__c11_atomic_fetch_add:
Yaxun Liu39195062017-08-04 18:16:31 +00001044 case AtomicExpr::AO__opencl_atomic_fetch_add:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001045 case AtomicExpr::AO__atomic_fetch_add:
1046 LibCallName = "__atomic_fetch_add";
John McCall7f416cc2015-09-08 08:05:57 +00001047 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1048 LoweredMemTy, E->getExprLoc(), sizeChars);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001049 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +00001050 // T __atomic_and_fetch_N(T *mem, T val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001051 // T __atomic_fetch_and_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +00001052 case AtomicExpr::AO__atomic_and_fetch:
1053 PostOp = llvm::Instruction::And;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001054 LLVM_FALLTHROUGH;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001055 case AtomicExpr::AO__c11_atomic_fetch_and:
Yaxun Liu39195062017-08-04 18:16:31 +00001056 case AtomicExpr::AO__opencl_atomic_fetch_and:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001057 case AtomicExpr::AO__atomic_fetch_and:
1058 LibCallName = "__atomic_fetch_and";
John McCall7f416cc2015-09-08 08:05:57 +00001059 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1060 MemTy, E->getExprLoc(), sizeChars);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001061 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +00001062 // T __atomic_or_fetch_N(T *mem, T val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001063 // T __atomic_fetch_or_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +00001064 case AtomicExpr::AO__atomic_or_fetch:
1065 PostOp = llvm::Instruction::Or;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001066 LLVM_FALLTHROUGH;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001067 case AtomicExpr::AO__c11_atomic_fetch_or:
Yaxun Liu39195062017-08-04 18:16:31 +00001068 case AtomicExpr::AO__opencl_atomic_fetch_or:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001069 case AtomicExpr::AO__atomic_fetch_or:
1070 LibCallName = "__atomic_fetch_or";
John McCall7f416cc2015-09-08 08:05:57 +00001071 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1072 MemTy, E->getExprLoc(), sizeChars);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001073 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +00001074 // T __atomic_sub_fetch_N(T *mem, T val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001075 // T __atomic_fetch_sub_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +00001076 case AtomicExpr::AO__atomic_sub_fetch:
1077 PostOp = llvm::Instruction::Sub;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001078 LLVM_FALLTHROUGH;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001079 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00001080 case AtomicExpr::AO__opencl_atomic_fetch_sub:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001081 case AtomicExpr::AO__atomic_fetch_sub:
1082 LibCallName = "__atomic_fetch_sub";
John McCall7f416cc2015-09-08 08:05:57 +00001083 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1084 LoweredMemTy, E->getExprLoc(), sizeChars);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001085 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +00001086 // T __atomic_xor_fetch_N(T *mem, T val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001087 // T __atomic_fetch_xor_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +00001088 case AtomicExpr::AO__atomic_xor_fetch:
1089 PostOp = llvm::Instruction::Xor;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001090 LLVM_FALLTHROUGH;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001091 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00001092 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001093 case AtomicExpr::AO__atomic_fetch_xor:
1094 LibCallName = "__atomic_fetch_xor";
John McCall7f416cc2015-09-08 08:05:57 +00001095 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1096 MemTy, E->getExprLoc(), sizeChars);
John McCallfc207f22013-03-07 21:37:12 +00001097 break;
Yaxun Liu39195062017-08-04 18:16:31 +00001098 case AtomicExpr::AO__opencl_atomic_fetch_min:
1099 LibCallName = E->getValueType()->isSignedIntegerType()
1100 ? "__atomic_fetch_min"
1101 : "__atomic_fetch_umin";
1102 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1103 LoweredMemTy, E->getExprLoc(), sizeChars);
1104 break;
1105 case AtomicExpr::AO__opencl_atomic_fetch_max:
1106 LibCallName = E->getValueType()->isSignedIntegerType()
1107 ? "__atomic_fetch_max"
1108 : "__atomic_fetch_umax";
1109 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1110 LoweredMemTy, E->getExprLoc(), sizeChars);
1111 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +00001112 // T __atomic_nand_fetch_N(T *mem, T val, int order)
James Y Knight81167fb2015-08-05 16:57:36 +00001113 // T __atomic_fetch_nand_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +00001114 case AtomicExpr::AO__atomic_nand_fetch:
1115 PostOp = llvm::Instruction::And; // the NOT is special cased below
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001116 LLVM_FALLTHROUGH;
James Y Knight81167fb2015-08-05 16:57:36 +00001117 case AtomicExpr::AO__atomic_fetch_nand:
1118 LibCallName = "__atomic_fetch_nand";
John McCall7f416cc2015-09-08 08:05:57 +00001119 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1120 MemTy, E->getExprLoc(), sizeChars);
James Y Knight81167fb2015-08-05 16:57:36 +00001121 break;
John McCallfc207f22013-03-07 21:37:12 +00001122 }
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001123
Yaxun Liu39195062017-08-04 18:16:31 +00001124 if (E->isOpenCL()) {
1125 LibCallName = std::string("__opencl") +
1126 StringRef(LibCallName).drop_front(1).str();
1127
1128 }
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001129 // Optimized functions have the size in their name.
1130 if (UseOptimizedLibcall)
1131 LibCallName += "_" + llvm::utostr(Size);
1132 // By default, assume we return a value of the atomic type.
1133 if (!HaveRetTy) {
1134 if (UseOptimizedLibcall) {
1135 // Value is returned directly.
David Majnemer0392cf82014-08-29 07:27:49 +00001136 // The function returns an appropriately sized integer type.
1137 RetTy = getContext().getIntTypeForBitwidth(
1138 getContext().toBits(sizeChars), /*Signed=*/false);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001139 } else {
1140 // Value is returned through parameter before the order.
1141 RetTy = getContext().VoidTy;
John McCall7f416cc2015-09-08 08:05:57 +00001142 Args.add(RValue::get(EmitCastToVoidPtr(Dest.getPointer())),
1143 getContext().VoidPtrTy);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001144 }
1145 }
John McCallfc207f22013-03-07 21:37:12 +00001146 // order is always the last parameter
1147 Args.add(RValue::get(Order),
1148 getContext().IntTy);
Yaxun Liu39195062017-08-04 18:16:31 +00001149 if (E->isOpenCL())
1150 Args.add(RValue::get(Scope), getContext().IntTy);
John McCallfc207f22013-03-07 21:37:12 +00001151
James Y Knight7aefb5b2015-11-12 18:37:29 +00001152 // PostOp is only needed for the atomic_*_fetch operations, and
1153 // thus is only needed for and implemented in the
1154 // UseOptimizedLibcall codepath.
1155 assert(UseOptimizedLibcall || !PostOp);
1156
David Majnemer659be552014-11-25 23:44:32 +00001157 RValue Res = emitAtomicLibcall(*this, LibCallName, RetTy, Args);
1158 // The value is returned directly from the libcall.
Tim Northovercc2a6e02015-11-09 19:56:35 +00001159 if (E->isCmpXChg())
David Majnemer659be552014-11-25 23:44:32 +00001160 return Res;
Tim Northovercc2a6e02015-11-09 19:56:35 +00001161
1162 // The value is returned directly for optimized libcalls but the expr
1163 // provided an out-param.
1164 if (UseOptimizedLibcall && Res.getScalarVal()) {
David Majnemer659be552014-11-25 23:44:32 +00001165 llvm::Value *ResVal = Res.getScalarVal();
James Y Knight7aefb5b2015-11-12 18:37:29 +00001166 if (PostOp) {
Yaxun Liu5b330e82018-03-15 15:25:19 +00001167 llvm::Value *LoadVal1 = Args[1].getRValue(*this).getScalarVal();
James Y Knight7aefb5b2015-11-12 18:37:29 +00001168 ResVal = Builder.CreateBinOp(PostOp, ResVal, LoadVal1);
1169 }
1170 if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch)
1171 ResVal = Builder.CreateNot(ResVal);
1172
Tim Northovercc2a6e02015-11-09 19:56:35 +00001173 Builder.CreateStore(
1174 ResVal,
1175 Builder.CreateBitCast(Dest, ResVal->getType()->getPointerTo()));
David Majnemer659be552014-11-25 23:44:32 +00001176 }
Tim Northovercc2a6e02015-11-09 19:56:35 +00001177
1178 if (RValTy->isVoidType())
1179 return RValue::get(nullptr);
1180
1181 return convertTempToRValue(
1182 Builder.CreateBitCast(Dest, ConvertTypeForMem(RValTy)->getPointerTo()),
1183 RValTy, E->getExprLoc());
John McCallfc207f22013-03-07 21:37:12 +00001184 }
1185
1186 bool IsStore = E->getOp() == AtomicExpr::AO__c11_atomic_store ||
Yaxun Liu39195062017-08-04 18:16:31 +00001187 E->getOp() == AtomicExpr::AO__opencl_atomic_store ||
John McCallfc207f22013-03-07 21:37:12 +00001188 E->getOp() == AtomicExpr::AO__atomic_store ||
1189 E->getOp() == AtomicExpr::AO__atomic_store_n;
1190 bool IsLoad = E->getOp() == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00001191 E->getOp() == AtomicExpr::AO__opencl_atomic_load ||
John McCallfc207f22013-03-07 21:37:12 +00001192 E->getOp() == AtomicExpr::AO__atomic_load ||
1193 E->getOp() == AtomicExpr::AO__atomic_load_n;
1194
John McCallfc207f22013-03-07 21:37:12 +00001195 if (isa<llvm::ConstantInt>(Order)) {
JF Bastiendda2cb12016-04-18 18:01:49 +00001196 auto ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
1197 // We should not ever get to a case where the ordering isn't a valid C ABI
1198 // value, but it's hard to enforce that in general.
1199 if (llvm::isValidAtomicOrderingCABI(ord))
1200 switch ((llvm::AtomicOrderingCABI)ord) {
1201 case llvm::AtomicOrderingCABI::relaxed:
1202 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001203 llvm::AtomicOrdering::Monotonic, Scope);
JF Bastiendda2cb12016-04-18 18:01:49 +00001204 break;
1205 case llvm::AtomicOrderingCABI::consume:
1206 case llvm::AtomicOrderingCABI::acquire:
1207 if (IsStore)
1208 break; // Avoid crashing on code with undefined behavior
1209 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001210 llvm::AtomicOrdering::Acquire, Scope);
JF Bastiendda2cb12016-04-18 18:01:49 +00001211 break;
1212 case llvm::AtomicOrderingCABI::release:
1213 if (IsLoad)
1214 break; // Avoid crashing on code with undefined behavior
1215 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001216 llvm::AtomicOrdering::Release, Scope);
JF Bastiendda2cb12016-04-18 18:01:49 +00001217 break;
1218 case llvm::AtomicOrderingCABI::acq_rel:
1219 if (IsLoad || IsStore)
1220 break; // Avoid crashing on code with undefined behavior
1221 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001222 llvm::AtomicOrdering::AcquireRelease, Scope);
JF Bastiendda2cb12016-04-18 18:01:49 +00001223 break;
1224 case llvm::AtomicOrderingCABI::seq_cst:
1225 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001226 llvm::AtomicOrdering::SequentiallyConsistent, Scope);
JF Bastiendda2cb12016-04-18 18:01:49 +00001227 break;
1228 }
David Majnemeree8d04d2014-12-12 08:16:09 +00001229 if (RValTy->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +00001230 return RValue::get(nullptr);
Tim Northovercc2a6e02015-11-09 19:56:35 +00001231
1232 return convertTempToRValue(
Yaxun Liu8ab5ab02017-10-17 14:19:29 +00001233 Builder.CreateBitCast(Dest, ConvertTypeForMem(RValTy)->getPointerTo(
1234 Dest.getAddressSpace())),
Tim Northovercc2a6e02015-11-09 19:56:35 +00001235 RValTy, E->getExprLoc());
John McCallfc207f22013-03-07 21:37:12 +00001236 }
1237
1238 // Long case, when Order isn't obviously constant.
1239
1240 // Create all the relevant BB's
Craig Topper8a13c412014-05-21 05:09:00 +00001241 llvm::BasicBlock *MonotonicBB = nullptr, *AcquireBB = nullptr,
1242 *ReleaseBB = nullptr, *AcqRelBB = nullptr,
1243 *SeqCstBB = nullptr;
John McCallfc207f22013-03-07 21:37:12 +00001244 MonotonicBB = createBasicBlock("monotonic", CurFn);
1245 if (!IsStore)
1246 AcquireBB = createBasicBlock("acquire", CurFn);
1247 if (!IsLoad)
1248 ReleaseBB = createBasicBlock("release", CurFn);
1249 if (!IsLoad && !IsStore)
1250 AcqRelBB = createBasicBlock("acqrel", CurFn);
1251 SeqCstBB = createBasicBlock("seqcst", CurFn);
1252 llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
1253
1254 // Create the switch for the split
1255 // MonotonicBB is arbitrarily chosen as the default case; in practice, this
1256 // doesn't matter unless someone is crazy enough to use something that
1257 // doesn't fold to a constant for the ordering.
1258 Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
1259 llvm::SwitchInst *SI = Builder.CreateSwitch(Order, MonotonicBB);
1260
1261 // Emit all the different atomics
1262 Builder.SetInsertPoint(MonotonicBB);
Yaxun Liu39195062017-08-04 18:16:31 +00001263 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001264 llvm::AtomicOrdering::Monotonic, Scope);
John McCallfc207f22013-03-07 21:37:12 +00001265 Builder.CreateBr(ContBB);
1266 if (!IsStore) {
1267 Builder.SetInsertPoint(AcquireBB);
Yaxun Liu39195062017-08-04 18:16:31 +00001268 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001269 llvm::AtomicOrdering::Acquire, Scope);
John McCallfc207f22013-03-07 21:37:12 +00001270 Builder.CreateBr(ContBB);
JF Bastiendda2cb12016-04-18 18:01:49 +00001271 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::consume),
Tim Northover514fc612014-03-13 19:25:52 +00001272 AcquireBB);
JF Bastiendda2cb12016-04-18 18:01:49 +00001273 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::acquire),
Tim Northover514fc612014-03-13 19:25:52 +00001274 AcquireBB);
John McCallfc207f22013-03-07 21:37:12 +00001275 }
1276 if (!IsLoad) {
1277 Builder.SetInsertPoint(ReleaseBB);
Yaxun Liu39195062017-08-04 18:16:31 +00001278 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001279 llvm::AtomicOrdering::Release, Scope);
John McCallfc207f22013-03-07 21:37:12 +00001280 Builder.CreateBr(ContBB);
JF Bastiendda2cb12016-04-18 18:01:49 +00001281 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::release),
Tim Northover514fc612014-03-13 19:25:52 +00001282 ReleaseBB);
John McCallfc207f22013-03-07 21:37:12 +00001283 }
1284 if (!IsLoad && !IsStore) {
1285 Builder.SetInsertPoint(AcqRelBB);
Yaxun Liu39195062017-08-04 18:16:31 +00001286 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001287 llvm::AtomicOrdering::AcquireRelease, Scope);
John McCallfc207f22013-03-07 21:37:12 +00001288 Builder.CreateBr(ContBB);
JF Bastiendda2cb12016-04-18 18:01:49 +00001289 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::acq_rel),
Tim Northover514fc612014-03-13 19:25:52 +00001290 AcqRelBB);
John McCallfc207f22013-03-07 21:37:12 +00001291 }
1292 Builder.SetInsertPoint(SeqCstBB);
Yaxun Liu39195062017-08-04 18:16:31 +00001293 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001294 llvm::AtomicOrdering::SequentiallyConsistent, Scope);
John McCallfc207f22013-03-07 21:37:12 +00001295 Builder.CreateBr(ContBB);
JF Bastiendda2cb12016-04-18 18:01:49 +00001296 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::seq_cst),
Tim Northover514fc612014-03-13 19:25:52 +00001297 SeqCstBB);
John McCallfc207f22013-03-07 21:37:12 +00001298
1299 // Cleanup and return
1300 Builder.SetInsertPoint(ContBB);
David Majnemeree8d04d2014-12-12 08:16:09 +00001301 if (RValTy->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +00001302 return RValue::get(nullptr);
Tim Northovercc2a6e02015-11-09 19:56:35 +00001303
1304 assert(Atomics.getValueSizeInBits() <= Atomics.getAtomicSizeInBits());
1305 return convertTempToRValue(
Yaxun Liu8ab5ab02017-10-17 14:19:29 +00001306 Builder.CreateBitCast(Dest, ConvertTypeForMem(RValTy)->getPointerTo(
1307 Dest.getAddressSpace())),
Tim Northovercc2a6e02015-11-09 19:56:35 +00001308 RValTy, E->getExprLoc());
John McCallfc207f22013-03-07 21:37:12 +00001309}
John McCalla8ec7eb2013-03-07 21:37:17 +00001310
John McCall7f416cc2015-09-08 08:05:57 +00001311Address AtomicInfo::emitCastToAtomicIntPointer(Address addr) const {
John McCalla8ec7eb2013-03-07 21:37:17 +00001312 unsigned addrspace =
John McCall7f416cc2015-09-08 08:05:57 +00001313 cast<llvm::PointerType>(addr.getPointer()->getType())->getAddressSpace();
John McCalla8ec7eb2013-03-07 21:37:17 +00001314 llvm::IntegerType *ty =
1315 llvm::IntegerType::get(CGF.getLLVMContext(), AtomicSizeInBits);
1316 return CGF.Builder.CreateBitCast(addr, ty->getPointerTo(addrspace));
1317}
1318
Tim Northovercc2a6e02015-11-09 19:56:35 +00001319Address AtomicInfo::convertToAtomicIntPointer(Address Addr) const {
1320 llvm::Type *Ty = Addr.getElementType();
1321 uint64_t SourceSizeInBits = CGF.CGM.getDataLayout().getTypeSizeInBits(Ty);
1322 if (SourceSizeInBits != AtomicSizeInBits) {
1323 Address Tmp = CreateTempAlloca();
1324 CGF.Builder.CreateMemCpy(Tmp, Addr,
1325 std::min(AtomicSizeInBits, SourceSizeInBits) / 8);
1326 Addr = Tmp;
1327 }
1328
1329 return emitCastToAtomicIntPointer(Addr);
1330}
1331
John McCall7f416cc2015-09-08 08:05:57 +00001332RValue AtomicInfo::convertAtomicTempToRValue(Address addr,
1333 AggValueSlot resultSlot,
1334 SourceLocation loc,
1335 bool asValue) const {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001336 if (LVal.isSimple()) {
1337 if (EvaluationKind == TEK_Aggregate)
1338 return resultSlot.asRValue();
John McCalla8ec7eb2013-03-07 21:37:17 +00001339
Alexey Bataevb57056f2015-01-22 06:17:56 +00001340 // Drill into the padding structure if we have one.
1341 if (hasPadding())
John McCall7f416cc2015-09-08 08:05:57 +00001342 addr = CGF.Builder.CreateStructGEP(addr, 0, CharUnits());
John McCalla8ec7eb2013-03-07 21:37:17 +00001343
Alexey Bataevb57056f2015-01-22 06:17:56 +00001344 // Otherwise, just convert the temporary to an r-value using the
1345 // normal conversion routine.
1346 return CGF.convertTempToRValue(addr, getValueType(), loc);
David Blaikie1ed728c2015-04-05 22:45:47 +00001347 }
John McCall7f416cc2015-09-08 08:05:57 +00001348 if (!asValue)
Alexey Bataevb8329262015-02-27 06:33:30 +00001349 // Get RValue from temp memory as atomic for non-simple lvalues
John McCall7f416cc2015-09-08 08:05:57 +00001350 return RValue::get(CGF.Builder.CreateLoad(addr));
David Blaikie1ed728c2015-04-05 22:45:47 +00001351 if (LVal.isBitField())
John McCall7f416cc2015-09-08 08:05:57 +00001352 return CGF.EmitLoadOfBitfieldLValue(
1353 LValue::MakeBitfield(addr, LVal.getBitFieldInfo(), LVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001354 LVal.getBaseInfo(), TBAAAccessInfo()), loc);
David Blaikie1ed728c2015-04-05 22:45:47 +00001355 if (LVal.isVectorElt())
John McCall7f416cc2015-09-08 08:05:57 +00001356 return CGF.EmitLoadOfLValue(
1357 LValue::MakeVectorElt(addr, LVal.getVectorIdx(), LVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001358 LVal.getBaseInfo(), TBAAAccessInfo()), loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001359 assert(LVal.isExtVectorElt());
1360 return CGF.EmitLoadOfExtVectorElementLValue(LValue::MakeExtVectorElt(
John McCall7f416cc2015-09-08 08:05:57 +00001361 addr, LVal.getExtVectorElts(), LVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001362 LVal.getBaseInfo(), TBAAAccessInfo()));
John McCalla8ec7eb2013-03-07 21:37:17 +00001363}
1364
Alexey Bataevb8329262015-02-27 06:33:30 +00001365RValue AtomicInfo::ConvertIntToValueOrAtomic(llvm::Value *IntVal,
1366 AggValueSlot ResultSlot,
1367 SourceLocation Loc,
1368 bool AsValue) const {
Alexey Bataev452d8e12014-12-15 05:25:25 +00001369 // Try not to in some easy cases.
1370 assert(IntVal->getType()->isIntegerTy() && "Expected integer value");
Alexey Bataevb8329262015-02-27 06:33:30 +00001371 if (getEvaluationKind() == TEK_Scalar &&
1372 (((!LVal.isBitField() ||
1373 LVal.getBitFieldInfo().Size == ValueSizeInBits) &&
1374 !hasPadding()) ||
1375 !AsValue)) {
1376 auto *ValTy = AsValue
1377 ? CGF.ConvertTypeForMem(ValueTy)
John McCall7f416cc2015-09-08 08:05:57 +00001378 : getAtomicAddress().getType()->getPointerElementType();
Alexey Bataev452d8e12014-12-15 05:25:25 +00001379 if (ValTy->isIntegerTy()) {
1380 assert(IntVal->getType() == ValTy && "Different integer types.");
David Majnemereeaec262015-02-14 02:18:14 +00001381 return RValue::get(CGF.EmitFromMemory(IntVal, ValueTy));
Alexey Bataev452d8e12014-12-15 05:25:25 +00001382 } else if (ValTy->isPointerTy())
1383 return RValue::get(CGF.Builder.CreateIntToPtr(IntVal, ValTy));
1384 else if (llvm::CastInst::isBitCastable(IntVal->getType(), ValTy))
1385 return RValue::get(CGF.Builder.CreateBitCast(IntVal, ValTy));
1386 }
1387
1388 // Create a temporary. This needs to be big enough to hold the
1389 // atomic integer.
John McCall7f416cc2015-09-08 08:05:57 +00001390 Address Temp = Address::invalid();
Alexey Bataev452d8e12014-12-15 05:25:25 +00001391 bool TempIsVolatile = false;
Alexey Bataevb8329262015-02-27 06:33:30 +00001392 if (AsValue && getEvaluationKind() == TEK_Aggregate) {
Alexey Bataev452d8e12014-12-15 05:25:25 +00001393 assert(!ResultSlot.isIgnored());
John McCall7f416cc2015-09-08 08:05:57 +00001394 Temp = ResultSlot.getAddress();
Alexey Bataev452d8e12014-12-15 05:25:25 +00001395 TempIsVolatile = ResultSlot.isVolatile();
1396 } else {
Alexey Bataevb8329262015-02-27 06:33:30 +00001397 Temp = CreateTempAlloca();
Alexey Bataev452d8e12014-12-15 05:25:25 +00001398 }
1399
1400 // Slam the integer into the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00001401 Address CastTemp = emitCastToAtomicIntPointer(Temp);
1402 CGF.Builder.CreateStore(IntVal, CastTemp)
Alexey Bataev452d8e12014-12-15 05:25:25 +00001403 ->setVolatile(TempIsVolatile);
1404
John McCall7f416cc2015-09-08 08:05:57 +00001405 return convertAtomicTempToRValue(Temp, ResultSlot, Loc, AsValue);
Alexey Bataevb8329262015-02-27 06:33:30 +00001406}
1407
1408void AtomicInfo::EmitAtomicLoadLibcall(llvm::Value *AddForLoaded,
1409 llvm::AtomicOrdering AO, bool) {
1410 // void __atomic_load(size_t size, void *mem, void *return, int order);
1411 CallArgList Args;
1412 Args.add(RValue::get(getAtomicSizeValue()), CGF.getContext().getSizeType());
John McCall7f416cc2015-09-08 08:05:57 +00001413 Args.add(RValue::get(CGF.EmitCastToVoidPtr(getAtomicPointer())),
Alexey Bataevb8329262015-02-27 06:33:30 +00001414 CGF.getContext().VoidPtrTy);
1415 Args.add(RValue::get(CGF.EmitCastToVoidPtr(AddForLoaded)),
1416 CGF.getContext().VoidPtrTy);
JF Bastiendda2cb12016-04-18 18:01:49 +00001417 Args.add(
1418 RValue::get(llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(AO))),
1419 CGF.getContext().IntTy);
Alexey Bataevb8329262015-02-27 06:33:30 +00001420 emitAtomicLibcall(CGF, "__atomic_load", CGF.getContext().VoidTy, Args);
1421}
1422
1423llvm::Value *AtomicInfo::EmitAtomicLoadOp(llvm::AtomicOrdering AO,
1424 bool IsVolatile) {
1425 // Okay, we're doing this natively.
John McCall7f416cc2015-09-08 08:05:57 +00001426 Address Addr = getAtomicAddressAsAtomicIntPointer();
Alexey Bataevb8329262015-02-27 06:33:30 +00001427 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Addr, "atomic-load");
1428 Load->setAtomic(AO);
1429
1430 // Other decoration.
Alexey Bataevb8329262015-02-27 06:33:30 +00001431 if (IsVolatile)
1432 Load->setVolatile(true);
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001433 CGF.CGM.DecorateInstructionWithTBAA(Load, LVal.getTBAAInfo());
Alexey Bataevb8329262015-02-27 06:33:30 +00001434 return Load;
Alexey Bataev452d8e12014-12-15 05:25:25 +00001435}
1436
David Majnemera5b195a2015-02-14 01:35:12 +00001437/// An LValue is a candidate for having its loads and stores be made atomic if
1438/// we are operating under /volatile:ms *and* the LValue itself is volatile and
1439/// performing such an operation can be performed without a libcall.
1440bool CodeGenFunction::LValueIsSuitableForInlineAtomic(LValue LV) {
John McCall7f416cc2015-09-08 08:05:57 +00001441 if (!CGM.getCodeGenOpts().MSVolatile) return false;
David Majnemera5b195a2015-02-14 01:35:12 +00001442 AtomicInfo AI(*this, LV);
1443 bool IsVolatile = LV.isVolatile() || hasVolatileMember(LV.getType());
1444 // An atomic is inline if we don't need to use a libcall.
1445 bool AtomicIsInline = !AI.shouldUseLibcall();
David Majnemerfc80b6e2016-01-22 16:36:44 +00001446 // MSVC doesn't seem to do this for types wider than a pointer.
David Majnemera38c9f12016-05-24 16:09:25 +00001447 if (getContext().getTypeSize(LV.getType()) >
David Majnemerfc80b6e2016-01-22 16:36:44 +00001448 getContext().getTypeSize(getContext().getIntPtrType()))
1449 return false;
David Majnemera38c9f12016-05-24 16:09:25 +00001450 return IsVolatile && AtomicIsInline;
David Majnemera5b195a2015-02-14 01:35:12 +00001451}
1452
1453RValue CodeGenFunction::EmitAtomicLoad(LValue LV, SourceLocation SL,
1454 AggValueSlot Slot) {
1455 llvm::AtomicOrdering AO;
1456 bool IsVolatile = LV.isVolatileQualified();
1457 if (LV.getType()->isAtomicType()) {
JF Bastien92f4ef12016-04-06 17:26:42 +00001458 AO = llvm::AtomicOrdering::SequentiallyConsistent;
David Majnemera5b195a2015-02-14 01:35:12 +00001459 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00001460 AO = llvm::AtomicOrdering::Acquire;
David Majnemera5b195a2015-02-14 01:35:12 +00001461 IsVolatile = true;
1462 }
1463 return EmitAtomicLoad(LV, SL, AO, IsVolatile, Slot);
1464}
1465
Alexey Bataevb8329262015-02-27 06:33:30 +00001466RValue AtomicInfo::EmitAtomicLoad(AggValueSlot ResultSlot, SourceLocation Loc,
1467 bool AsValue, llvm::AtomicOrdering AO,
1468 bool IsVolatile) {
1469 // Check whether we should use a library call.
1470 if (shouldUseLibcall()) {
John McCall7f416cc2015-09-08 08:05:57 +00001471 Address TempAddr = Address::invalid();
Alexey Bataevb8329262015-02-27 06:33:30 +00001472 if (LVal.isSimple() && !ResultSlot.isIgnored()) {
1473 assert(getEvaluationKind() == TEK_Aggregate);
John McCall7f416cc2015-09-08 08:05:57 +00001474 TempAddr = ResultSlot.getAddress();
Alexey Bataevb8329262015-02-27 06:33:30 +00001475 } else
1476 TempAddr = CreateTempAlloca();
1477
John McCall7f416cc2015-09-08 08:05:57 +00001478 EmitAtomicLoadLibcall(TempAddr.getPointer(), AO, IsVolatile);
Alexey Bataevb8329262015-02-27 06:33:30 +00001479
1480 // Okay, turn that back into the original value or whole atomic (for
1481 // non-simple lvalues) type.
John McCall7f416cc2015-09-08 08:05:57 +00001482 return convertAtomicTempToRValue(TempAddr, ResultSlot, Loc, AsValue);
Alexey Bataevb8329262015-02-27 06:33:30 +00001483 }
1484
1485 // Okay, we're doing this natively.
1486 auto *Load = EmitAtomicLoadOp(AO, IsVolatile);
1487
1488 // If we're ignoring an aggregate return, don't do anything.
1489 if (getEvaluationKind() == TEK_Aggregate && ResultSlot.isIgnored())
John McCall7f416cc2015-09-08 08:05:57 +00001490 return RValue::getAggregate(Address::invalid(), false);
Alexey Bataevb8329262015-02-27 06:33:30 +00001491
1492 // Okay, turn that back into the original value or atomic (for non-simple
1493 // lvalues) type.
1494 return ConvertIntToValueOrAtomic(Load, ResultSlot, Loc, AsValue);
1495}
1496
John McCalla8ec7eb2013-03-07 21:37:17 +00001497/// Emit a load from an l-value of atomic type. Note that the r-value
1498/// we produce is an r-value of the atomic *value* type.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001499RValue CodeGenFunction::EmitAtomicLoad(LValue src, SourceLocation loc,
David Majnemera5b195a2015-02-14 01:35:12 +00001500 llvm::AtomicOrdering AO, bool IsVolatile,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001501 AggValueSlot resultSlot) {
Alexey Bataevb8329262015-02-27 06:33:30 +00001502 AtomicInfo Atomics(*this, src);
1503 return Atomics.EmitAtomicLoad(resultSlot, loc, /*AsValue=*/true, AO,
1504 IsVolatile);
John McCalla8ec7eb2013-03-07 21:37:17 +00001505}
1506
John McCalla8ec7eb2013-03-07 21:37:17 +00001507/// Copy an r-value into memory as part of storing to an atomic type.
1508/// This needs to create a bit-pattern suitable for atomic operations.
Alexey Bataevb57056f2015-01-22 06:17:56 +00001509void AtomicInfo::emitCopyIntoMemory(RValue rvalue) const {
1510 assert(LVal.isSimple());
John McCalla8ec7eb2013-03-07 21:37:17 +00001511 // If we have an r-value, the rvalue should be of the atomic type,
1512 // which means that the caller is responsible for having zeroed
1513 // any padding. Just do an aggregate copy of that type.
1514 if (rvalue.isAggregate()) {
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001515 LValue Dest = CGF.MakeAddrLValue(getAtomicAddress(), getAtomicType());
1516 LValue Src = CGF.MakeAddrLValue(rvalue.getAggregateAddress(),
1517 getAtomicType());
1518 bool IsVolatile = rvalue.isVolatileQualified() ||
1519 LVal.isVolatileQualified();
Richard Smithe78fac52018-04-05 20:52:58 +00001520 CGF.EmitAggregateCopy(Dest, Src, getAtomicType(),
1521 AggValueSlot::DoesNotOverlap, IsVolatile);
John McCalla8ec7eb2013-03-07 21:37:17 +00001522 return;
1523 }
1524
1525 // Okay, otherwise we're copying stuff.
1526
1527 // Zero out the buffer if necessary.
Alexey Bataevb57056f2015-01-22 06:17:56 +00001528 emitMemSetZeroIfNecessary();
John McCalla8ec7eb2013-03-07 21:37:17 +00001529
1530 // Drill past the padding if present.
Alexey Bataevb57056f2015-01-22 06:17:56 +00001531 LValue TempLVal = projectValue();
John McCalla8ec7eb2013-03-07 21:37:17 +00001532
1533 // Okay, store the rvalue in.
1534 if (rvalue.isScalar()) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001535 CGF.EmitStoreOfScalar(rvalue.getScalarVal(), TempLVal, /*init*/ true);
John McCalla8ec7eb2013-03-07 21:37:17 +00001536 } else {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001537 CGF.EmitStoreOfComplex(rvalue.getComplexVal(), TempLVal, /*init*/ true);
John McCalla8ec7eb2013-03-07 21:37:17 +00001538 }
1539}
1540
1541
1542/// Materialize an r-value into memory for the purposes of storing it
1543/// to an atomic type.
John McCall7f416cc2015-09-08 08:05:57 +00001544Address AtomicInfo::materializeRValue(RValue rvalue) const {
John McCalla8ec7eb2013-03-07 21:37:17 +00001545 // Aggregate r-values are already in memory, and EmitAtomicStore
1546 // requires them to be values of the atomic type.
1547 if (rvalue.isAggregate())
John McCall7f416cc2015-09-08 08:05:57 +00001548 return rvalue.getAggregateAddress();
John McCalla8ec7eb2013-03-07 21:37:17 +00001549
1550 // Otherwise, make a temporary and materialize into it.
John McCall7f416cc2015-09-08 08:05:57 +00001551 LValue TempLV = CGF.MakeAddrLValue(CreateTempAlloca(), getAtomicType());
Alexey Bataevb8329262015-02-27 06:33:30 +00001552 AtomicInfo Atomics(CGF, TempLV);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001553 Atomics.emitCopyIntoMemory(rvalue);
Alexey Bataevb8329262015-02-27 06:33:30 +00001554 return TempLV.getAddress();
John McCalla8ec7eb2013-03-07 21:37:17 +00001555}
1556
Alexey Bataev452d8e12014-12-15 05:25:25 +00001557llvm::Value *AtomicInfo::convertRValueToInt(RValue RVal) const {
1558 // If we've got a scalar value of the right size, try to avoid going
1559 // through memory.
Alexey Bataevb8329262015-02-27 06:33:30 +00001560 if (RVal.isScalar() && (!hasPadding() || !LVal.isSimple())) {
Alexey Bataev452d8e12014-12-15 05:25:25 +00001561 llvm::Value *Value = RVal.getScalarVal();
1562 if (isa<llvm::IntegerType>(Value->getType()))
Alexey Bataevb4505a72015-03-30 05:20:59 +00001563 return CGF.EmitToMemory(Value, ValueTy);
Alexey Bataev452d8e12014-12-15 05:25:25 +00001564 else {
Alexey Bataevb8329262015-02-27 06:33:30 +00001565 llvm::IntegerType *InputIntTy = llvm::IntegerType::get(
1566 CGF.getLLVMContext(),
1567 LVal.isSimple() ? getValueSizeInBits() : getAtomicSizeInBits());
Alexey Bataev452d8e12014-12-15 05:25:25 +00001568 if (isa<llvm::PointerType>(Value->getType()))
1569 return CGF.Builder.CreatePtrToInt(Value, InputIntTy);
1570 else if (llvm::BitCastInst::isBitCastable(Value->getType(), InputIntTy))
1571 return CGF.Builder.CreateBitCast(Value, InputIntTy);
1572 }
1573 }
1574 // Otherwise, we need to go through memory.
1575 // Put the r-value in memory.
John McCall7f416cc2015-09-08 08:05:57 +00001576 Address Addr = materializeRValue(RVal);
Alexey Bataev452d8e12014-12-15 05:25:25 +00001577
1578 // Cast the temporary to the atomic int type and pull a value out.
1579 Addr = emitCastToAtomicIntPointer(Addr);
John McCall7f416cc2015-09-08 08:05:57 +00001580 return CGF.Builder.CreateLoad(Addr);
Alexey Bataev452d8e12014-12-15 05:25:25 +00001581}
1582
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001583std::pair<llvm::Value *, llvm::Value *> AtomicInfo::EmitAtomicCompareExchangeOp(
1584 llvm::Value *ExpectedVal, llvm::Value *DesiredVal,
1585 llvm::AtomicOrdering Success, llvm::AtomicOrdering Failure, bool IsWeak) {
Alexey Bataevb8329262015-02-27 06:33:30 +00001586 // Do the atomic store.
John McCall7f416cc2015-09-08 08:05:57 +00001587 Address Addr = getAtomicAddressAsAtomicIntPointer();
1588 auto *Inst = CGF.Builder.CreateAtomicCmpXchg(Addr.getPointer(),
1589 ExpectedVal, DesiredVal,
Alexey Bataevb4505a72015-03-30 05:20:59 +00001590 Success, Failure);
Alexey Bataevb8329262015-02-27 06:33:30 +00001591 // Other decoration.
1592 Inst->setVolatile(LVal.isVolatileQualified());
1593 Inst->setWeak(IsWeak);
1594
1595 // Okay, turn that back into the original value type.
1596 auto *PreviousVal = CGF.Builder.CreateExtractValue(Inst, /*Idxs=*/0);
1597 auto *SuccessFailureVal = CGF.Builder.CreateExtractValue(Inst, /*Idxs=*/1);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001598 return std::make_pair(PreviousVal, SuccessFailureVal);
Alexey Bataevb8329262015-02-27 06:33:30 +00001599}
1600
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001601llvm::Value *
1602AtomicInfo::EmitAtomicCompareExchangeLibcall(llvm::Value *ExpectedAddr,
1603 llvm::Value *DesiredAddr,
Alexey Bataevb8329262015-02-27 06:33:30 +00001604 llvm::AtomicOrdering Success,
1605 llvm::AtomicOrdering Failure) {
1606 // bool __atomic_compare_exchange(size_t size, void *obj, void *expected,
1607 // void *desired, int success, int failure);
1608 CallArgList Args;
1609 Args.add(RValue::get(getAtomicSizeValue()), CGF.getContext().getSizeType());
John McCall7f416cc2015-09-08 08:05:57 +00001610 Args.add(RValue::get(CGF.EmitCastToVoidPtr(getAtomicPointer())),
Alexey Bataevb8329262015-02-27 06:33:30 +00001611 CGF.getContext().VoidPtrTy);
1612 Args.add(RValue::get(CGF.EmitCastToVoidPtr(ExpectedAddr)),
1613 CGF.getContext().VoidPtrTy);
1614 Args.add(RValue::get(CGF.EmitCastToVoidPtr(DesiredAddr)),
1615 CGF.getContext().VoidPtrTy);
JF Bastiendda2cb12016-04-18 18:01:49 +00001616 Args.add(RValue::get(
1617 llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(Success))),
Alexey Bataevb8329262015-02-27 06:33:30 +00001618 CGF.getContext().IntTy);
JF Bastiendda2cb12016-04-18 18:01:49 +00001619 Args.add(RValue::get(
1620 llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(Failure))),
Alexey Bataevb8329262015-02-27 06:33:30 +00001621 CGF.getContext().IntTy);
1622 auto SuccessFailureRVal = emitAtomicLibcall(CGF, "__atomic_compare_exchange",
1623 CGF.getContext().BoolTy, Args);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001624
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001625 return SuccessFailureRVal.getScalarVal();
Alexey Bataevb8329262015-02-27 06:33:30 +00001626}
1627
Alexey Bataevb4505a72015-03-30 05:20:59 +00001628std::pair<RValue, llvm::Value *> AtomicInfo::EmitAtomicCompareExchange(
Alexey Bataevb8329262015-02-27 06:33:30 +00001629 RValue Expected, RValue Desired, llvm::AtomicOrdering Success,
1630 llvm::AtomicOrdering Failure, bool IsWeak) {
JF Bastiendd11ee72016-04-06 23:37:36 +00001631 if (isStrongerThan(Failure, Success))
1632 // Don't assert on undefined behavior "failure argument shall be no stronger
1633 // than the success argument".
Alexey Bataevb8329262015-02-27 06:33:30 +00001634 Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(Success);
1635
1636 // Check whether we should use a library call.
1637 if (shouldUseLibcall()) {
Alexey Bataevb8329262015-02-27 06:33:30 +00001638 // Produce a source address.
John McCall7f416cc2015-09-08 08:05:57 +00001639 Address ExpectedAddr = materializeRValue(Expected);
1640 Address DesiredAddr = materializeRValue(Desired);
1641 auto *Res = EmitAtomicCompareExchangeLibcall(ExpectedAddr.getPointer(),
1642 DesiredAddr.getPointer(),
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001643 Success, Failure);
1644 return std::make_pair(
John McCall7f416cc2015-09-08 08:05:57 +00001645 convertAtomicTempToRValue(ExpectedAddr, AggValueSlot::ignored(),
1646 SourceLocation(), /*AsValue=*/false),
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001647 Res);
Alexey Bataevb8329262015-02-27 06:33:30 +00001648 }
1649
1650 // If we've got a scalar value of the right size, try to avoid going
1651 // through memory.
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001652 auto *ExpectedVal = convertRValueToInt(Expected);
1653 auto *DesiredVal = convertRValueToInt(Desired);
1654 auto Res = EmitAtomicCompareExchangeOp(ExpectedVal, DesiredVal, Success,
1655 Failure, IsWeak);
1656 return std::make_pair(
1657 ConvertIntToValueOrAtomic(Res.first, AggValueSlot::ignored(),
1658 SourceLocation(), /*AsValue=*/false),
1659 Res.second);
1660}
1661
1662static void
1663EmitAtomicUpdateValue(CodeGenFunction &CGF, AtomicInfo &Atomics, RValue OldRVal,
1664 const llvm::function_ref<RValue(RValue)> &UpdateOp,
John McCall7f416cc2015-09-08 08:05:57 +00001665 Address DesiredAddr) {
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001666 RValue UpRVal;
1667 LValue AtomicLVal = Atomics.getAtomicLValue();
1668 LValue DesiredLVal;
1669 if (AtomicLVal.isSimple()) {
1670 UpRVal = OldRVal;
John McCall7f416cc2015-09-08 08:05:57 +00001671 DesiredLVal = CGF.MakeAddrLValue(DesiredAddr, AtomicLVal.getType());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001672 } else {
1673 // Build new lvalue for temp address
John McCall7f416cc2015-09-08 08:05:57 +00001674 Address Ptr = Atomics.materializeRValue(OldRVal);
1675 LValue UpdateLVal;
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001676 if (AtomicLVal.isBitField()) {
1677 UpdateLVal =
1678 LValue::MakeBitfield(Ptr, AtomicLVal.getBitFieldInfo(),
John McCall7f416cc2015-09-08 08:05:57 +00001679 AtomicLVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001680 AtomicLVal.getBaseInfo(),
1681 AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001682 DesiredLVal =
1683 LValue::MakeBitfield(DesiredAddr, AtomicLVal.getBitFieldInfo(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001684 AtomicLVal.getType(), AtomicLVal.getBaseInfo(),
1685 AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001686 } else if (AtomicLVal.isVectorElt()) {
1687 UpdateLVal = LValue::MakeVectorElt(Ptr, AtomicLVal.getVectorIdx(),
1688 AtomicLVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001689 AtomicLVal.getBaseInfo(),
1690 AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001691 DesiredLVal = LValue::MakeVectorElt(
1692 DesiredAddr, AtomicLVal.getVectorIdx(), AtomicLVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001693 AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001694 } else {
1695 assert(AtomicLVal.isExtVectorElt());
1696 UpdateLVal = LValue::MakeExtVectorElt(Ptr, AtomicLVal.getExtVectorElts(),
1697 AtomicLVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001698 AtomicLVal.getBaseInfo(),
1699 AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001700 DesiredLVal = LValue::MakeExtVectorElt(
1701 DesiredAddr, AtomicLVal.getExtVectorElts(), AtomicLVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001702 AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001703 }
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001704 UpRVal = CGF.EmitLoadOfLValue(UpdateLVal, SourceLocation());
1705 }
1706 // Store new value in the corresponding memory area
1707 RValue NewRVal = UpdateOp(UpRVal);
1708 if (NewRVal.isScalar()) {
1709 CGF.EmitStoreThroughLValue(NewRVal, DesiredLVal);
1710 } else {
1711 assert(NewRVal.isComplex());
1712 CGF.EmitStoreOfComplex(NewRVal.getComplexVal(), DesiredLVal,
1713 /*isInit=*/false);
1714 }
1715}
1716
1717void AtomicInfo::EmitAtomicUpdateLibcall(
1718 llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1719 bool IsVolatile) {
1720 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1721
John McCall7f416cc2015-09-08 08:05:57 +00001722 Address ExpectedAddr = CreateTempAlloca();
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001723
John McCall7f416cc2015-09-08 08:05:57 +00001724 EmitAtomicLoadLibcall(ExpectedAddr.getPointer(), AO, IsVolatile);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001725 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1726 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1727 CGF.EmitBlock(ContBB);
John McCall7f416cc2015-09-08 08:05:57 +00001728 Address DesiredAddr = CreateTempAlloca();
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001729 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
John McCall7f416cc2015-09-08 08:05:57 +00001730 requiresMemSetZero(getAtomicAddress().getElementType())) {
1731 auto *OldVal = CGF.Builder.CreateLoad(ExpectedAddr);
1732 CGF.Builder.CreateStore(OldVal, DesiredAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001733 }
John McCall7f416cc2015-09-08 08:05:57 +00001734 auto OldRVal = convertAtomicTempToRValue(ExpectedAddr,
1735 AggValueSlot::ignored(),
1736 SourceLocation(), /*AsValue=*/false);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001737 EmitAtomicUpdateValue(CGF, *this, OldRVal, UpdateOp, DesiredAddr);
1738 auto *Res =
John McCall7f416cc2015-09-08 08:05:57 +00001739 EmitAtomicCompareExchangeLibcall(ExpectedAddr.getPointer(),
1740 DesiredAddr.getPointer(),
1741 AO, Failure);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001742 CGF.Builder.CreateCondBr(Res, ExitBB, ContBB);
1743 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1744}
1745
1746void AtomicInfo::EmitAtomicUpdateOp(
1747 llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1748 bool IsVolatile) {
1749 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1750
1751 // Do the atomic load.
1752 auto *OldVal = EmitAtomicLoadOp(AO, IsVolatile);
1753 // For non-simple lvalues perform compare-and-swap procedure.
1754 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1755 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1756 auto *CurBB = CGF.Builder.GetInsertBlock();
1757 CGF.EmitBlock(ContBB);
1758 llvm::PHINode *PHI = CGF.Builder.CreatePHI(OldVal->getType(),
1759 /*NumReservedValues=*/2);
1760 PHI->addIncoming(OldVal, CurBB);
John McCall7f416cc2015-09-08 08:05:57 +00001761 Address NewAtomicAddr = CreateTempAlloca();
1762 Address NewAtomicIntAddr = emitCastToAtomicIntPointer(NewAtomicAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001763 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
John McCall7f416cc2015-09-08 08:05:57 +00001764 requiresMemSetZero(getAtomicAddress().getElementType())) {
1765 CGF.Builder.CreateStore(PHI, NewAtomicIntAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001766 }
1767 auto OldRVal = ConvertIntToValueOrAtomic(PHI, AggValueSlot::ignored(),
1768 SourceLocation(), /*AsValue=*/false);
1769 EmitAtomicUpdateValue(CGF, *this, OldRVal, UpdateOp, NewAtomicAddr);
John McCall7f416cc2015-09-08 08:05:57 +00001770 auto *DesiredVal = CGF.Builder.CreateLoad(NewAtomicIntAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001771 // Try to write new value using cmpxchg operation
1772 auto Res = EmitAtomicCompareExchangeOp(PHI, DesiredVal, AO, Failure);
1773 PHI->addIncoming(Res.first, CGF.Builder.GetInsertBlock());
1774 CGF.Builder.CreateCondBr(Res.second, ExitBB, ContBB);
1775 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1776}
1777
1778static void EmitAtomicUpdateValue(CodeGenFunction &CGF, AtomicInfo &Atomics,
John McCall7f416cc2015-09-08 08:05:57 +00001779 RValue UpdateRVal, Address DesiredAddr) {
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001780 LValue AtomicLVal = Atomics.getAtomicLValue();
1781 LValue DesiredLVal;
1782 // Build new lvalue for temp address
1783 if (AtomicLVal.isBitField()) {
1784 DesiredLVal =
1785 LValue::MakeBitfield(DesiredAddr, AtomicLVal.getBitFieldInfo(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001786 AtomicLVal.getType(), AtomicLVal.getBaseInfo(),
1787 AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001788 } else if (AtomicLVal.isVectorElt()) {
1789 DesiredLVal =
1790 LValue::MakeVectorElt(DesiredAddr, AtomicLVal.getVectorIdx(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001791 AtomicLVal.getType(), AtomicLVal.getBaseInfo(),
1792 AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001793 } else {
1794 assert(AtomicLVal.isExtVectorElt());
1795 DesiredLVal = LValue::MakeExtVectorElt(
1796 DesiredAddr, AtomicLVal.getExtVectorElts(), AtomicLVal.getType(),
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00001797 AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001798 }
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001799 // Store new value in the corresponding memory area
1800 assert(UpdateRVal.isScalar());
1801 CGF.EmitStoreThroughLValue(UpdateRVal, DesiredLVal);
1802}
1803
1804void AtomicInfo::EmitAtomicUpdateLibcall(llvm::AtomicOrdering AO,
1805 RValue UpdateRVal, bool IsVolatile) {
1806 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1807
John McCall7f416cc2015-09-08 08:05:57 +00001808 Address ExpectedAddr = CreateTempAlloca();
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001809
John McCall7f416cc2015-09-08 08:05:57 +00001810 EmitAtomicLoadLibcall(ExpectedAddr.getPointer(), AO, IsVolatile);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001811 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1812 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1813 CGF.EmitBlock(ContBB);
John McCall7f416cc2015-09-08 08:05:57 +00001814 Address DesiredAddr = CreateTempAlloca();
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001815 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
John McCall7f416cc2015-09-08 08:05:57 +00001816 requiresMemSetZero(getAtomicAddress().getElementType())) {
1817 auto *OldVal = CGF.Builder.CreateLoad(ExpectedAddr);
1818 CGF.Builder.CreateStore(OldVal, DesiredAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001819 }
1820 EmitAtomicUpdateValue(CGF, *this, UpdateRVal, DesiredAddr);
1821 auto *Res =
John McCall7f416cc2015-09-08 08:05:57 +00001822 EmitAtomicCompareExchangeLibcall(ExpectedAddr.getPointer(),
1823 DesiredAddr.getPointer(),
1824 AO, Failure);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001825 CGF.Builder.CreateCondBr(Res, ExitBB, ContBB);
1826 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1827}
1828
1829void AtomicInfo::EmitAtomicUpdateOp(llvm::AtomicOrdering AO, RValue UpdateRVal,
1830 bool IsVolatile) {
1831 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1832
1833 // Do the atomic load.
1834 auto *OldVal = EmitAtomicLoadOp(AO, IsVolatile);
1835 // For non-simple lvalues perform compare-and-swap procedure.
1836 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1837 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1838 auto *CurBB = CGF.Builder.GetInsertBlock();
1839 CGF.EmitBlock(ContBB);
1840 llvm::PHINode *PHI = CGF.Builder.CreatePHI(OldVal->getType(),
1841 /*NumReservedValues=*/2);
1842 PHI->addIncoming(OldVal, CurBB);
John McCall7f416cc2015-09-08 08:05:57 +00001843 Address NewAtomicAddr = CreateTempAlloca();
1844 Address NewAtomicIntAddr = emitCastToAtomicIntPointer(NewAtomicAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001845 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
John McCall7f416cc2015-09-08 08:05:57 +00001846 requiresMemSetZero(getAtomicAddress().getElementType())) {
1847 CGF.Builder.CreateStore(PHI, NewAtomicIntAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001848 }
1849 EmitAtomicUpdateValue(CGF, *this, UpdateRVal, NewAtomicAddr);
John McCall7f416cc2015-09-08 08:05:57 +00001850 auto *DesiredVal = CGF.Builder.CreateLoad(NewAtomicIntAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001851 // Try to write new value using cmpxchg operation
1852 auto Res = EmitAtomicCompareExchangeOp(PHI, DesiredVal, AO, Failure);
1853 PHI->addIncoming(Res.first, CGF.Builder.GetInsertBlock());
1854 CGF.Builder.CreateCondBr(Res.second, ExitBB, ContBB);
1855 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1856}
1857
1858void AtomicInfo::EmitAtomicUpdate(
1859 llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1860 bool IsVolatile) {
1861 if (shouldUseLibcall()) {
1862 EmitAtomicUpdateLibcall(AO, UpdateOp, IsVolatile);
1863 } else {
1864 EmitAtomicUpdateOp(AO, UpdateOp, IsVolatile);
1865 }
1866}
1867
1868void AtomicInfo::EmitAtomicUpdate(llvm::AtomicOrdering AO, RValue UpdateRVal,
1869 bool IsVolatile) {
1870 if (shouldUseLibcall()) {
1871 EmitAtomicUpdateLibcall(AO, UpdateRVal, IsVolatile);
1872 } else {
1873 EmitAtomicUpdateOp(AO, UpdateRVal, IsVolatile);
1874 }
Alexey Bataevb8329262015-02-27 06:33:30 +00001875}
1876
David Majnemera5b195a2015-02-14 01:35:12 +00001877void CodeGenFunction::EmitAtomicStore(RValue rvalue, LValue lvalue,
1878 bool isInit) {
1879 bool IsVolatile = lvalue.isVolatileQualified();
1880 llvm::AtomicOrdering AO;
1881 if (lvalue.getType()->isAtomicType()) {
JF Bastien92f4ef12016-04-06 17:26:42 +00001882 AO = llvm::AtomicOrdering::SequentiallyConsistent;
David Majnemera5b195a2015-02-14 01:35:12 +00001883 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00001884 AO = llvm::AtomicOrdering::Release;
David Majnemera5b195a2015-02-14 01:35:12 +00001885 IsVolatile = true;
1886 }
1887 return EmitAtomicStore(rvalue, lvalue, AO, IsVolatile, isInit);
1888}
1889
John McCalla8ec7eb2013-03-07 21:37:17 +00001890/// Emit a store to an l-value of atomic type.
1891///
1892/// Note that the r-value is expected to be an r-value *of the atomic
1893/// type*; this means that for aggregate r-values, it should include
1894/// storage for any padding that was necessary.
David Majnemera5b195a2015-02-14 01:35:12 +00001895void CodeGenFunction::EmitAtomicStore(RValue rvalue, LValue dest,
1896 llvm::AtomicOrdering AO, bool IsVolatile,
1897 bool isInit) {
John McCalla8ec7eb2013-03-07 21:37:17 +00001898 // If this is an aggregate r-value, it should agree in type except
1899 // maybe for address-space qualification.
1900 assert(!rvalue.isAggregate() ||
John McCall7f416cc2015-09-08 08:05:57 +00001901 rvalue.getAggregateAddress().getElementType()
1902 == dest.getAddress().getElementType());
John McCalla8ec7eb2013-03-07 21:37:17 +00001903
1904 AtomicInfo atomics(*this, dest);
Alexey Bataevb8329262015-02-27 06:33:30 +00001905 LValue LVal = atomics.getAtomicLValue();
John McCalla8ec7eb2013-03-07 21:37:17 +00001906
1907 // If this is an initialization, just put the value there normally.
Alexey Bataevb8329262015-02-27 06:33:30 +00001908 if (LVal.isSimple()) {
1909 if (isInit) {
1910 atomics.emitCopyIntoMemory(rvalue);
1911 return;
1912 }
1913
1914 // Check whether we should use a library call.
1915 if (atomics.shouldUseLibcall()) {
1916 // Produce a source address.
John McCall7f416cc2015-09-08 08:05:57 +00001917 Address srcAddr = atomics.materializeRValue(rvalue);
Alexey Bataevb8329262015-02-27 06:33:30 +00001918
1919 // void __atomic_store(size_t size, void *mem, void *val, int order)
1920 CallArgList args;
1921 args.add(RValue::get(atomics.getAtomicSizeValue()),
1922 getContext().getSizeType());
John McCall7f416cc2015-09-08 08:05:57 +00001923 args.add(RValue::get(EmitCastToVoidPtr(atomics.getAtomicPointer())),
Alexey Bataevb8329262015-02-27 06:33:30 +00001924 getContext().VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00001925 args.add(RValue::get(EmitCastToVoidPtr(srcAddr.getPointer())),
1926 getContext().VoidPtrTy);
JF Bastiendda2cb12016-04-18 18:01:49 +00001927 args.add(
1928 RValue::get(llvm::ConstantInt::get(IntTy, (int)llvm::toCABI(AO))),
1929 getContext().IntTy);
Alexey Bataevb8329262015-02-27 06:33:30 +00001930 emitAtomicLibcall(*this, "__atomic_store", getContext().VoidTy, args);
1931 return;
1932 }
1933
1934 // Okay, we're doing this natively.
1935 llvm::Value *intValue = atomics.convertRValueToInt(rvalue);
1936
1937 // Do the atomic store.
John McCall7f416cc2015-09-08 08:05:57 +00001938 Address addr =
Alexey Bataevb8329262015-02-27 06:33:30 +00001939 atomics.emitCastToAtomicIntPointer(atomics.getAtomicAddress());
1940 intValue = Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00001941 intValue, addr.getElementType(), /*isSigned=*/false);
Alexey Bataevb8329262015-02-27 06:33:30 +00001942 llvm::StoreInst *store = Builder.CreateStore(intValue, addr);
1943
1944 // Initializations don't need to be atomic.
1945 if (!isInit)
1946 store->setAtomic(AO);
1947
1948 // Other decoration.
Alexey Bataevb8329262015-02-27 06:33:30 +00001949 if (IsVolatile)
1950 store->setVolatile(true);
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001951 CGM.DecorateInstructionWithTBAA(store, dest.getTBAAInfo());
John McCalla8ec7eb2013-03-07 21:37:17 +00001952 return;
1953 }
1954
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001955 // Emit simple atomic update operation.
1956 atomics.EmitAtomicUpdate(AO, rvalue, IsVolatile);
John McCalla8ec7eb2013-03-07 21:37:17 +00001957}
1958
Alexey Bataev452d8e12014-12-15 05:25:25 +00001959/// Emit a compare-and-exchange op for atomic type.
1960///
Alexey Bataevb4505a72015-03-30 05:20:59 +00001961std::pair<RValue, llvm::Value *> CodeGenFunction::EmitAtomicCompareExchange(
Alexey Bataev452d8e12014-12-15 05:25:25 +00001962 LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
1963 llvm::AtomicOrdering Success, llvm::AtomicOrdering Failure, bool IsWeak,
1964 AggValueSlot Slot) {
1965 // If this is an aggregate r-value, it should agree in type except
1966 // maybe for address-space qualification.
1967 assert(!Expected.isAggregate() ||
John McCall7f416cc2015-09-08 08:05:57 +00001968 Expected.getAggregateAddress().getElementType() ==
1969 Obj.getAddress().getElementType());
Alexey Bataev452d8e12014-12-15 05:25:25 +00001970 assert(!Desired.isAggregate() ||
John McCall7f416cc2015-09-08 08:05:57 +00001971 Desired.getAggregateAddress().getElementType() ==
1972 Obj.getAddress().getElementType());
Alexey Bataev452d8e12014-12-15 05:25:25 +00001973 AtomicInfo Atomics(*this, Obj);
1974
Alexey Bataevb4505a72015-03-30 05:20:59 +00001975 return Atomics.EmitAtomicCompareExchange(Expected, Desired, Success, Failure,
1976 IsWeak);
1977}
1978
1979void CodeGenFunction::EmitAtomicUpdate(
1980 LValue LVal, llvm::AtomicOrdering AO,
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001981 const llvm::function_ref<RValue(RValue)> &UpdateOp, bool IsVolatile) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00001982 AtomicInfo Atomics(*this, LVal);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001983 Atomics.EmitAtomicUpdate(AO, UpdateOp, IsVolatile);
Alexey Bataev452d8e12014-12-15 05:25:25 +00001984}
1985
John McCalla8ec7eb2013-03-07 21:37:17 +00001986void CodeGenFunction::EmitAtomicInit(Expr *init, LValue dest) {
1987 AtomicInfo atomics(*this, dest);
1988
1989 switch (atomics.getEvaluationKind()) {
1990 case TEK_Scalar: {
1991 llvm::Value *value = EmitScalarExpr(init);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001992 atomics.emitCopyIntoMemory(RValue::get(value));
John McCalla8ec7eb2013-03-07 21:37:17 +00001993 return;
1994 }
1995
1996 case TEK_Complex: {
1997 ComplexPairTy value = EmitComplexExpr(init);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001998 atomics.emitCopyIntoMemory(RValue::getComplex(value));
John McCalla8ec7eb2013-03-07 21:37:17 +00001999 return;
2000 }
2001
2002 case TEK_Aggregate: {
Eli Friedmanbe4504d2013-07-11 01:32:21 +00002003 // Fix up the destination if the initializer isn't an expression
2004 // of atomic type.
2005 bool Zeroed = false;
John McCalla8ec7eb2013-03-07 21:37:17 +00002006 if (!init->getType()->isAtomicType()) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002007 Zeroed = atomics.emitMemSetZeroIfNecessary();
2008 dest = atomics.projectValue();
John McCalla8ec7eb2013-03-07 21:37:17 +00002009 }
2010
2011 // Evaluate the expression directly into the destination.
2012 AggValueSlot slot = AggValueSlot::forLValue(dest,
2013 AggValueSlot::IsNotDestructed,
2014 AggValueSlot::DoesNotNeedGCBarriers,
Eli Friedmanbe4504d2013-07-11 01:32:21 +00002015 AggValueSlot::IsNotAliased,
Richard Smithe78fac52018-04-05 20:52:58 +00002016 AggValueSlot::DoesNotOverlap,
Eli Friedmanbe4504d2013-07-11 01:32:21 +00002017 Zeroed ? AggValueSlot::IsZeroed :
2018 AggValueSlot::IsNotZeroed);
2019
John McCalla8ec7eb2013-03-07 21:37:17 +00002020 EmitAggExpr(init, slot);
2021 return;
2022 }
2023 }
2024 llvm_unreachable("bad evaluation kind");
2025}