blob: 030c944ffeb1ea60d2d9fbe09af055654e3ec828 [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"
Yaxun Liu30d652a2017-08-15 16:02:49 +000021#include "llvm/ADT/DenseMap.h"
John McCallfc207f22013-03-07 21:37:12 +000022#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/Intrinsics.h"
John McCalla8ec7eb2013-03-07 21:37:17 +000024#include "llvm/IR/Operator.h"
John McCallfc207f22013-03-07 21:37:12 +000025
26using namespace clang;
27using namespace CodeGen;
28
John McCalla8ec7eb2013-03-07 21:37:17 +000029namespace {
30 class AtomicInfo {
31 CodeGenFunction &CGF;
32 QualType AtomicTy;
33 QualType ValueTy;
34 uint64_t AtomicSizeInBits;
35 uint64_t ValueSizeInBits;
36 CharUnits AtomicAlign;
37 CharUnits ValueAlign;
38 CharUnits LValueAlign;
39 TypeEvaluationKind EvaluationKind;
40 bool UseLibcall;
Alexey Bataevb57056f2015-01-22 06:17:56 +000041 LValue LVal;
42 CGBitFieldInfo BFI;
John McCalla8ec7eb2013-03-07 21:37:17 +000043 public:
Alexey Bataevb57056f2015-01-22 06:17:56 +000044 AtomicInfo(CodeGenFunction &CGF, LValue &lvalue)
45 : CGF(CGF), AtomicSizeInBits(0), ValueSizeInBits(0),
46 EvaluationKind(TEK_Scalar), UseLibcall(true) {
47 assert(!lvalue.isGlobalReg());
John McCalla8ec7eb2013-03-07 21:37:17 +000048 ASTContext &C = CGF.getContext();
Alexey Bataevb57056f2015-01-22 06:17:56 +000049 if (lvalue.isSimple()) {
50 AtomicTy = lvalue.getType();
51 if (auto *ATy = AtomicTy->getAs<AtomicType>())
52 ValueTy = ATy->getValueType();
53 else
54 ValueTy = AtomicTy;
55 EvaluationKind = CGF.getEvaluationKind(ValueTy);
John McCalla8ec7eb2013-03-07 21:37:17 +000056
Alexey Bataevb57056f2015-01-22 06:17:56 +000057 uint64_t ValueAlignInBits;
58 uint64_t AtomicAlignInBits;
59 TypeInfo ValueTI = C.getTypeInfo(ValueTy);
60 ValueSizeInBits = ValueTI.Width;
61 ValueAlignInBits = ValueTI.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +000062
Alexey Bataevb57056f2015-01-22 06:17:56 +000063 TypeInfo AtomicTI = C.getTypeInfo(AtomicTy);
64 AtomicSizeInBits = AtomicTI.Width;
65 AtomicAlignInBits = AtomicTI.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +000066
Alexey Bataevb57056f2015-01-22 06:17:56 +000067 assert(ValueSizeInBits <= AtomicSizeInBits);
68 assert(ValueAlignInBits <= AtomicAlignInBits);
John McCalla8ec7eb2013-03-07 21:37:17 +000069
Alexey Bataevb57056f2015-01-22 06:17:56 +000070 AtomicAlign = C.toCharUnitsFromBits(AtomicAlignInBits);
71 ValueAlign = C.toCharUnitsFromBits(ValueAlignInBits);
72 if (lvalue.getAlignment().isZero())
73 lvalue.setAlignment(AtomicAlign);
John McCalla8ec7eb2013-03-07 21:37:17 +000074
Alexey Bataevb57056f2015-01-22 06:17:56 +000075 LVal = lvalue;
76 } else if (lvalue.isBitField()) {
Alexey Bataevb8329262015-02-27 06:33:30 +000077 ValueTy = lvalue.getType();
78 ValueSizeInBits = C.getTypeSize(ValueTy);
Alexey Bataevb57056f2015-01-22 06:17:56 +000079 auto &OrigBFI = lvalue.getBitFieldInfo();
80 auto Offset = OrigBFI.Offset % C.toBits(lvalue.getAlignment());
81 AtomicSizeInBits = C.toBits(
82 C.toCharUnitsFromBits(Offset + OrigBFI.Size + C.getCharWidth() - 1)
Rui Ueyama83aa9792016-01-14 21:00:27 +000083 .alignTo(lvalue.getAlignment()));
John McCall7f416cc2015-09-08 08:05:57 +000084 auto VoidPtrAddr = CGF.EmitCastToVoidPtr(lvalue.getBitFieldPointer());
Alexey Bataevb57056f2015-01-22 06:17:56 +000085 auto OffsetInChars =
86 (C.toCharUnitsFromBits(OrigBFI.Offset) / lvalue.getAlignment()) *
87 lvalue.getAlignment();
88 VoidPtrAddr = CGF.Builder.CreateConstGEP1_64(
89 VoidPtrAddr, OffsetInChars.getQuantity());
90 auto Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
91 VoidPtrAddr,
92 CGF.Builder.getIntNTy(AtomicSizeInBits)->getPointerTo(),
93 "atomic_bitfield_base");
94 BFI = OrigBFI;
95 BFI.Offset = Offset;
96 BFI.StorageSize = AtomicSizeInBits;
Ulrich Weigand03ce2a12015-07-10 17:30:00 +000097 BFI.StorageOffset += OffsetInChars;
John McCall7f416cc2015-09-08 08:05:57 +000098 LVal = LValue::MakeBitfield(Address(Addr, lvalue.getAlignment()),
99 BFI, lvalue.getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000100 lvalue.getBaseInfo());
Ivan A. Kosarevc12b48e2017-10-03 11:31:42 +0000101 LVal.setTBAAInfo(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. Kosarevafc074c2017-10-05 11:05:43 +0000208 LVal.getBaseInfo(), LVal.getTBAAAccessType());
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;
577 // Fall through.
578 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;
586 // Fall through.
587 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;
605 // Fall through.
606 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;
614 // Fall through.
615 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;
623 // Fall through.
624 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
632 // Fall through.
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
755 CharUnits sizeChars, alignChars;
756 std::tie(sizeChars, alignChars) = getContext().getTypeInfoInChars(AtomicTy);
757 uint64_t Size = sizeChars.getQuantity();
758 unsigned MaxInlineWidthInBits = getTarget().getMaxAtomicInlineWidth();
759 bool UseLibcall = ((Ptr.getAlignment() % sizeChars) != 0 ||
760 getContext().toBits(sizeChars) > MaxInlineWidthInBits);
John McCallfc207f22013-03-07 21:37:12 +0000761
Yaxun Liu39195062017-08-04 18:16:31 +0000762 if (E->getOp() == AtomicExpr::AO__c11_atomic_init ||
763 E->getOp() == AtomicExpr::AO__opencl_atomic_init) {
John McCall7f416cc2015-09-08 08:05:57 +0000764 LValue lvalue = MakeAddrLValue(Ptr, AtomicTy);
John McCalla8ec7eb2013-03-07 21:37:17 +0000765 EmitAtomicInit(E->getVal1(), lvalue);
Craig Topper8a13c412014-05-21 05:09:00 +0000766 return RValue::get(nullptr);
John McCallfc207f22013-03-07 21:37:12 +0000767 }
768
Craig Topper8a13c412014-05-21 05:09:00 +0000769 llvm::Value *Order = EmitScalarExpr(E->getOrder());
Yaxun Liu30d652a2017-08-15 16:02:49 +0000770 llvm::Value *Scope =
771 E->getScopeModel() ? EmitScalarExpr(E->getScope()) : nullptr;
John McCallfc207f22013-03-07 21:37:12 +0000772
773 switch (E->getOp()) {
774 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +0000775 case AtomicExpr::AO__opencl_atomic_init:
James Y Knight81167fb2015-08-05 16:57:36 +0000776 llvm_unreachable("Already handled above with EmitAtomicInit!");
John McCallfc207f22013-03-07 21:37:12 +0000777
778 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +0000779 case AtomicExpr::AO__opencl_atomic_load:
John McCallfc207f22013-03-07 21:37:12 +0000780 case AtomicExpr::AO__atomic_load_n:
781 break;
782
783 case AtomicExpr::AO__atomic_load:
John McCall7f416cc2015-09-08 08:05:57 +0000784 Dest = EmitPointerWithAlignment(E->getVal1());
John McCallfc207f22013-03-07 21:37:12 +0000785 break;
786
787 case AtomicExpr::AO__atomic_store:
John McCall7f416cc2015-09-08 08:05:57 +0000788 Val1 = EmitPointerWithAlignment(E->getVal1());
John McCallfc207f22013-03-07 21:37:12 +0000789 break;
790
791 case AtomicExpr::AO__atomic_exchange:
John McCall7f416cc2015-09-08 08:05:57 +0000792 Val1 = EmitPointerWithAlignment(E->getVal1());
793 Dest = EmitPointerWithAlignment(E->getVal2());
John McCallfc207f22013-03-07 21:37:12 +0000794 break;
795
796 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
797 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +0000798 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
799 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
John McCallfc207f22013-03-07 21:37:12 +0000800 case AtomicExpr::AO__atomic_compare_exchange_n:
801 case AtomicExpr::AO__atomic_compare_exchange:
John McCall7f416cc2015-09-08 08:05:57 +0000802 Val1 = EmitPointerWithAlignment(E->getVal1());
John McCallfc207f22013-03-07 21:37:12 +0000803 if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange)
John McCall7f416cc2015-09-08 08:05:57 +0000804 Val2 = EmitPointerWithAlignment(E->getVal2());
John McCallfc207f22013-03-07 21:37:12 +0000805 else
806 Val2 = EmitValToTemp(*this, E->getVal2());
807 OrderFail = EmitScalarExpr(E->getOrderFail());
Yaxun Liu39195062017-08-04 18:16:31 +0000808 if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange_n ||
809 E->getOp() == AtomicExpr::AO__atomic_compare_exchange)
Tim Northovercadbbe12014-06-13 19:43:04 +0000810 IsWeak = EmitScalarExpr(E->getWeak());
John McCallfc207f22013-03-07 21:37:12 +0000811 break;
812
813 case AtomicExpr::AO__c11_atomic_fetch_add:
814 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +0000815 case AtomicExpr::AO__opencl_atomic_fetch_add:
816 case AtomicExpr::AO__opencl_atomic_fetch_sub:
John McCallfc207f22013-03-07 21:37:12 +0000817 if (MemTy->isPointerType()) {
818 // For pointer arithmetic, we're required to do a bit of math:
819 // adding 1 to an int* is not the same as adding 1 to a uintptr_t.
820 // ... but only for the C11 builtins. The GNU builtins expect the
821 // user to multiply by sizeof(T).
822 QualType Val1Ty = E->getVal1()->getType();
823 llvm::Value *Val1Scalar = EmitScalarExpr(E->getVal1());
824 CharUnits PointeeIncAmt =
825 getContext().getTypeSizeInChars(MemTy->getPointeeType());
826 Val1Scalar = Builder.CreateMul(Val1Scalar, CGM.getSize(PointeeIncAmt));
John McCall7f416cc2015-09-08 08:05:57 +0000827 auto Temp = CreateMemTemp(Val1Ty, ".atomictmp");
828 Val1 = Temp;
829 EmitStoreOfScalar(Val1Scalar, MakeAddrLValue(Temp, Val1Ty));
John McCallfc207f22013-03-07 21:37:12 +0000830 break;
831 }
832 // Fall through.
833 case AtomicExpr::AO__atomic_fetch_add:
834 case AtomicExpr::AO__atomic_fetch_sub:
835 case AtomicExpr::AO__atomic_add_fetch:
836 case AtomicExpr::AO__atomic_sub_fetch:
837 case AtomicExpr::AO__c11_atomic_store:
838 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +0000839 case AtomicExpr::AO__opencl_atomic_store:
840 case AtomicExpr::AO__opencl_atomic_exchange:
John McCallfc207f22013-03-07 21:37:12 +0000841 case AtomicExpr::AO__atomic_store_n:
842 case AtomicExpr::AO__atomic_exchange_n:
843 case AtomicExpr::AO__c11_atomic_fetch_and:
844 case AtomicExpr::AO__c11_atomic_fetch_or:
845 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +0000846 case AtomicExpr::AO__opencl_atomic_fetch_and:
847 case AtomicExpr::AO__opencl_atomic_fetch_or:
848 case AtomicExpr::AO__opencl_atomic_fetch_xor:
849 case AtomicExpr::AO__opencl_atomic_fetch_min:
850 case AtomicExpr::AO__opencl_atomic_fetch_max:
John McCallfc207f22013-03-07 21:37:12 +0000851 case AtomicExpr::AO__atomic_fetch_and:
852 case AtomicExpr::AO__atomic_fetch_or:
853 case AtomicExpr::AO__atomic_fetch_xor:
854 case AtomicExpr::AO__atomic_fetch_nand:
855 case AtomicExpr::AO__atomic_and_fetch:
856 case AtomicExpr::AO__atomic_or_fetch:
857 case AtomicExpr::AO__atomic_xor_fetch:
858 case AtomicExpr::AO__atomic_nand_fetch:
859 Val1 = EmitValToTemp(*this, E->getVal1());
860 break;
861 }
862
David Majnemeree8d04d2014-12-12 08:16:09 +0000863 QualType RValTy = E->getType().getUnqualifiedType();
864
Tim Northovercc2a6e02015-11-09 19:56:35 +0000865 // The inlined atomics only function on iN types, where N is a power of 2. We
866 // need to make sure (via temporaries if necessary) that all incoming values
867 // are compatible.
868 LValue AtomicVal = MakeAddrLValue(Ptr, AtomicTy);
869 AtomicInfo Atomics(*this, AtomicVal);
870
871 Ptr = Atomics.emitCastToAtomicIntPointer(Ptr);
872 if (Val1.isValid()) Val1 = Atomics.convertToAtomicIntPointer(Val1);
873 if (Val2.isValid()) Val2 = Atomics.convertToAtomicIntPointer(Val2);
874 if (Dest.isValid())
875 Dest = Atomics.emitCastToAtomicIntPointer(Dest);
876 else if (E->isCmpXChg())
877 Dest = CreateMemTemp(RValTy, "cmpxchg.bool");
878 else if (!RValTy->isVoidType())
879 Dest = Atomics.emitCastToAtomicIntPointer(Atomics.CreateTempAlloca());
John McCallfc207f22013-03-07 21:37:12 +0000880
881 // Use a library call. See: http://gcc.gnu.org/wiki/Atomic/GCCMM/LIbrary .
882 if (UseLibcall) {
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000883 bool UseOptimizedLibcall = false;
884 switch (E->getOp()) {
James Y Knight81167fb2015-08-05 16:57:36 +0000885 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +0000886 case AtomicExpr::AO__opencl_atomic_init:
James Y Knight81167fb2015-08-05 16:57:36 +0000887 llvm_unreachable("Already handled above with EmitAtomicInit!");
888
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000889 case AtomicExpr::AO__c11_atomic_fetch_add:
Yaxun Liu39195062017-08-04 18:16:31 +0000890 case AtomicExpr::AO__opencl_atomic_fetch_add:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000891 case AtomicExpr::AO__atomic_fetch_add:
892 case AtomicExpr::AO__c11_atomic_fetch_and:
Yaxun Liu39195062017-08-04 18:16:31 +0000893 case AtomicExpr::AO__opencl_atomic_fetch_and:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000894 case AtomicExpr::AO__atomic_fetch_and:
895 case AtomicExpr::AO__c11_atomic_fetch_or:
Yaxun Liu39195062017-08-04 18:16:31 +0000896 case AtomicExpr::AO__opencl_atomic_fetch_or:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000897 case AtomicExpr::AO__atomic_fetch_or:
James Y Knight81167fb2015-08-05 16:57:36 +0000898 case AtomicExpr::AO__atomic_fetch_nand:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000899 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +0000900 case AtomicExpr::AO__opencl_atomic_fetch_sub:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000901 case AtomicExpr::AO__atomic_fetch_sub:
902 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +0000903 case AtomicExpr::AO__opencl_atomic_fetch_xor:
904 case AtomicExpr::AO__opencl_atomic_fetch_min:
905 case AtomicExpr::AO__opencl_atomic_fetch_max:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000906 case AtomicExpr::AO__atomic_fetch_xor:
James Y Knight81167fb2015-08-05 16:57:36 +0000907 case AtomicExpr::AO__atomic_add_fetch:
908 case AtomicExpr::AO__atomic_and_fetch:
909 case AtomicExpr::AO__atomic_nand_fetch:
910 case AtomicExpr::AO__atomic_or_fetch:
911 case AtomicExpr::AO__atomic_sub_fetch:
912 case AtomicExpr::AO__atomic_xor_fetch:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000913 // For these, only library calls for certain sizes exist.
914 UseOptimizedLibcall = true;
915 break;
James Y Knight81167fb2015-08-05 16:57:36 +0000916
917 case AtomicExpr::AO__c11_atomic_load:
918 case AtomicExpr::AO__c11_atomic_store:
919 case AtomicExpr::AO__c11_atomic_exchange:
920 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
921 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
Yaxun Liu39195062017-08-04 18:16:31 +0000922 case AtomicExpr::AO__opencl_atomic_load:
923 case AtomicExpr::AO__opencl_atomic_store:
924 case AtomicExpr::AO__opencl_atomic_exchange:
925 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
926 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
James Y Knight81167fb2015-08-05 16:57:36 +0000927 case AtomicExpr::AO__atomic_load_n:
928 case AtomicExpr::AO__atomic_load:
929 case AtomicExpr::AO__atomic_store_n:
930 case AtomicExpr::AO__atomic_store:
931 case AtomicExpr::AO__atomic_exchange_n:
932 case AtomicExpr::AO__atomic_exchange:
933 case AtomicExpr::AO__atomic_compare_exchange_n:
934 case AtomicExpr::AO__atomic_compare_exchange:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000935 // Only use optimized library calls for sizes for which they exist.
936 if (Size == 1 || Size == 2 || Size == 4 || Size == 8)
937 UseOptimizedLibcall = true;
938 break;
939 }
John McCallfc207f22013-03-07 21:37:12 +0000940
John McCallfc207f22013-03-07 21:37:12 +0000941 CallArgList Args;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000942 if (!UseOptimizedLibcall) {
943 // For non-optimized library calls, the size is the first parameter
944 Args.add(RValue::get(llvm::ConstantInt::get(SizeTy, Size)),
945 getContext().getSizeType());
946 }
947 // Atomic address is the first or second parameter
Yaxun Liu39195062017-08-04 18:16:31 +0000948 // The OpenCL atomic library functions only accept pointer arguments to
949 // generic address space.
950 auto CastToGenericAddrSpace = [&](llvm::Value *V, QualType PT) {
951 if (!E->isOpenCL())
952 return V;
953 auto AS = PT->getAs<PointerType>()->getPointeeType().getAddressSpace();
954 if (AS == LangAS::opencl_generic)
955 return V;
956 auto DestAS = getContext().getTargetAddressSpace(LangAS::opencl_generic);
957 auto T = V->getType();
958 auto *DestType = T->getPointerElementType()->getPointerTo(DestAS);
959
960 return getTargetHooks().performAddrSpaceCast(
961 *this, V, AS, LangAS::opencl_generic, DestType, false);
962 };
963
964 Args.add(RValue::get(CastToGenericAddrSpace(
965 EmitCastToVoidPtr(Ptr.getPointer()), E->getPtr()->getType())),
John McCall7f416cc2015-09-08 08:05:57 +0000966 getContext().VoidPtrTy);
John McCallfc207f22013-03-07 21:37:12 +0000967
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000968 std::string LibCallName;
Logan Chien74798a32014-03-26 17:35:01 +0000969 QualType LoweredMemTy =
970 MemTy->isPointerType() ? getContext().getIntPtrType() : MemTy;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000971 QualType RetTy;
972 bool HaveRetTy = false;
James Y Knight7aefb5b2015-11-12 18:37:29 +0000973 llvm::Instruction::BinaryOps PostOp = (llvm::Instruction::BinaryOps)0;
John McCallfc207f22013-03-07 21:37:12 +0000974 switch (E->getOp()) {
James Y Knight81167fb2015-08-05 16:57:36 +0000975 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +0000976 case AtomicExpr::AO__opencl_atomic_init:
James Y Knight81167fb2015-08-05 16:57:36 +0000977 llvm_unreachable("Already handled!");
978
John McCallfc207f22013-03-07 21:37:12 +0000979 // There is only one libcall for compare an exchange, because there is no
980 // optimisation benefit possible from a libcall version of a weak compare
981 // and exchange.
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000982 // bool __atomic_compare_exchange(size_t size, void *mem, void *expected,
John McCallfc207f22013-03-07 21:37:12 +0000983 // void *desired, int success, int failure)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000984 // bool __atomic_compare_exchange_N(T *mem, T *expected, T desired,
985 // int success, int failure)
John McCallfc207f22013-03-07 21:37:12 +0000986 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
987 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
Yaxun Liu39195062017-08-04 18:16:31 +0000988 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
989 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
John McCallfc207f22013-03-07 21:37:12 +0000990 case AtomicExpr::AO__atomic_compare_exchange:
991 case AtomicExpr::AO__atomic_compare_exchange_n:
992 LibCallName = "__atomic_compare_exchange";
993 RetTy = getContext().BoolTy;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000994 HaveRetTy = true;
Yaxun Liu39195062017-08-04 18:16:31 +0000995 Args.add(
996 RValue::get(CastToGenericAddrSpace(
997 EmitCastToVoidPtr(Val1.getPointer()), E->getVal1()->getType())),
998 getContext().VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +0000999 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val2.getPointer(),
1000 MemTy, E->getExprLoc(), sizeChars);
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001001 Args.add(RValue::get(Order), getContext().IntTy);
John McCallfc207f22013-03-07 21:37:12 +00001002 Order = OrderFail;
1003 break;
1004 // void __atomic_exchange(size_t size, void *mem, void *val, void *return,
1005 // int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001006 // T __atomic_exchange_N(T *mem, T val, int order)
John McCallfc207f22013-03-07 21:37:12 +00001007 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00001008 case AtomicExpr::AO__opencl_atomic_exchange:
John McCallfc207f22013-03-07 21:37:12 +00001009 case AtomicExpr::AO__atomic_exchange_n:
1010 case AtomicExpr::AO__atomic_exchange:
1011 LibCallName = "__atomic_exchange";
John McCall7f416cc2015-09-08 08:05:57 +00001012 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1013 MemTy, E->getExprLoc(), sizeChars);
John McCallfc207f22013-03-07 21:37:12 +00001014 break;
1015 // void __atomic_store(size_t size, void *mem, void *val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001016 // void __atomic_store_N(T *mem, T val, int order)
John McCallfc207f22013-03-07 21:37:12 +00001017 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00001018 case AtomicExpr::AO__opencl_atomic_store:
John McCallfc207f22013-03-07 21:37:12 +00001019 case AtomicExpr::AO__atomic_store:
1020 case AtomicExpr::AO__atomic_store_n:
1021 LibCallName = "__atomic_store";
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001022 RetTy = getContext().VoidTy;
1023 HaveRetTy = true;
John McCall7f416cc2015-09-08 08:05:57 +00001024 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1025 MemTy, E->getExprLoc(), sizeChars);
John McCallfc207f22013-03-07 21:37:12 +00001026 break;
1027 // void __atomic_load(size_t size, void *mem, void *return, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001028 // T __atomic_load_N(T *mem, int order)
John McCallfc207f22013-03-07 21:37:12 +00001029 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00001030 case AtomicExpr::AO__opencl_atomic_load:
John McCallfc207f22013-03-07 21:37:12 +00001031 case AtomicExpr::AO__atomic_load:
1032 case AtomicExpr::AO__atomic_load_n:
1033 LibCallName = "__atomic_load";
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001034 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +00001035 // T __atomic_add_fetch_N(T *mem, T val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001036 // T __atomic_fetch_add_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +00001037 case AtomicExpr::AO__atomic_add_fetch:
1038 PostOp = llvm::Instruction::Add;
1039 // Fall through.
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001040 case AtomicExpr::AO__c11_atomic_fetch_add:
Yaxun Liu39195062017-08-04 18:16:31 +00001041 case AtomicExpr::AO__opencl_atomic_fetch_add:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001042 case AtomicExpr::AO__atomic_fetch_add:
1043 LibCallName = "__atomic_fetch_add";
John McCall7f416cc2015-09-08 08:05:57 +00001044 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1045 LoweredMemTy, E->getExprLoc(), sizeChars);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001046 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +00001047 // T __atomic_and_fetch_N(T *mem, T val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001048 // T __atomic_fetch_and_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +00001049 case AtomicExpr::AO__atomic_and_fetch:
1050 PostOp = llvm::Instruction::And;
1051 // Fall through.
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001052 case AtomicExpr::AO__c11_atomic_fetch_and:
Yaxun Liu39195062017-08-04 18:16:31 +00001053 case AtomicExpr::AO__opencl_atomic_fetch_and:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001054 case AtomicExpr::AO__atomic_fetch_and:
1055 LibCallName = "__atomic_fetch_and";
John McCall7f416cc2015-09-08 08:05:57 +00001056 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1057 MemTy, E->getExprLoc(), sizeChars);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001058 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +00001059 // T __atomic_or_fetch_N(T *mem, T val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001060 // T __atomic_fetch_or_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +00001061 case AtomicExpr::AO__atomic_or_fetch:
1062 PostOp = llvm::Instruction::Or;
1063 // Fall through.
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001064 case AtomicExpr::AO__c11_atomic_fetch_or:
Yaxun Liu39195062017-08-04 18:16:31 +00001065 case AtomicExpr::AO__opencl_atomic_fetch_or:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001066 case AtomicExpr::AO__atomic_fetch_or:
1067 LibCallName = "__atomic_fetch_or";
John McCall7f416cc2015-09-08 08:05:57 +00001068 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1069 MemTy, E->getExprLoc(), sizeChars);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001070 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +00001071 // T __atomic_sub_fetch_N(T *mem, T val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001072 // T __atomic_fetch_sub_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +00001073 case AtomicExpr::AO__atomic_sub_fetch:
1074 PostOp = llvm::Instruction::Sub;
1075 // Fall through.
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001076 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00001077 case AtomicExpr::AO__opencl_atomic_fetch_sub:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001078 case AtomicExpr::AO__atomic_fetch_sub:
1079 LibCallName = "__atomic_fetch_sub";
John McCall7f416cc2015-09-08 08:05:57 +00001080 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1081 LoweredMemTy, E->getExprLoc(), sizeChars);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001082 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +00001083 // T __atomic_xor_fetch_N(T *mem, T val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001084 // T __atomic_fetch_xor_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +00001085 case AtomicExpr::AO__atomic_xor_fetch:
1086 PostOp = llvm::Instruction::Xor;
1087 // Fall through.
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001088 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00001089 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001090 case AtomicExpr::AO__atomic_fetch_xor:
1091 LibCallName = "__atomic_fetch_xor";
John McCall7f416cc2015-09-08 08:05:57 +00001092 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1093 MemTy, E->getExprLoc(), sizeChars);
John McCallfc207f22013-03-07 21:37:12 +00001094 break;
Yaxun Liu39195062017-08-04 18:16:31 +00001095 case AtomicExpr::AO__opencl_atomic_fetch_min:
1096 LibCallName = E->getValueType()->isSignedIntegerType()
1097 ? "__atomic_fetch_min"
1098 : "__atomic_fetch_umin";
1099 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1100 LoweredMemTy, E->getExprLoc(), sizeChars);
1101 break;
1102 case AtomicExpr::AO__opencl_atomic_fetch_max:
1103 LibCallName = E->getValueType()->isSignedIntegerType()
1104 ? "__atomic_fetch_max"
1105 : "__atomic_fetch_umax";
1106 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1107 LoweredMemTy, E->getExprLoc(), sizeChars);
1108 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +00001109 // T __atomic_nand_fetch_N(T *mem, T val, int order)
James Y Knight81167fb2015-08-05 16:57:36 +00001110 // T __atomic_fetch_nand_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +00001111 case AtomicExpr::AO__atomic_nand_fetch:
1112 PostOp = llvm::Instruction::And; // the NOT is special cased below
1113 // Fall through.
James Y Knight81167fb2015-08-05 16:57:36 +00001114 case AtomicExpr::AO__atomic_fetch_nand:
1115 LibCallName = "__atomic_fetch_nand";
John McCall7f416cc2015-09-08 08:05:57 +00001116 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1117 MemTy, E->getExprLoc(), sizeChars);
James Y Knight81167fb2015-08-05 16:57:36 +00001118 break;
John McCallfc207f22013-03-07 21:37:12 +00001119 }
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001120
Yaxun Liu39195062017-08-04 18:16:31 +00001121 if (E->isOpenCL()) {
1122 LibCallName = std::string("__opencl") +
1123 StringRef(LibCallName).drop_front(1).str();
1124
1125 }
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001126 // Optimized functions have the size in their name.
1127 if (UseOptimizedLibcall)
1128 LibCallName += "_" + llvm::utostr(Size);
1129 // By default, assume we return a value of the atomic type.
1130 if (!HaveRetTy) {
1131 if (UseOptimizedLibcall) {
1132 // Value is returned directly.
David Majnemer0392cf82014-08-29 07:27:49 +00001133 // The function returns an appropriately sized integer type.
1134 RetTy = getContext().getIntTypeForBitwidth(
1135 getContext().toBits(sizeChars), /*Signed=*/false);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001136 } else {
1137 // Value is returned through parameter before the order.
1138 RetTy = getContext().VoidTy;
John McCall7f416cc2015-09-08 08:05:57 +00001139 Args.add(RValue::get(EmitCastToVoidPtr(Dest.getPointer())),
1140 getContext().VoidPtrTy);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +00001141 }
1142 }
John McCallfc207f22013-03-07 21:37:12 +00001143 // order is always the last parameter
1144 Args.add(RValue::get(Order),
1145 getContext().IntTy);
Yaxun Liu39195062017-08-04 18:16:31 +00001146 if (E->isOpenCL())
1147 Args.add(RValue::get(Scope), getContext().IntTy);
John McCallfc207f22013-03-07 21:37:12 +00001148
James Y Knight7aefb5b2015-11-12 18:37:29 +00001149 // PostOp is only needed for the atomic_*_fetch operations, and
1150 // thus is only needed for and implemented in the
1151 // UseOptimizedLibcall codepath.
1152 assert(UseOptimizedLibcall || !PostOp);
1153
David Majnemer659be552014-11-25 23:44:32 +00001154 RValue Res = emitAtomicLibcall(*this, LibCallName, RetTy, Args);
1155 // The value is returned directly from the libcall.
Tim Northovercc2a6e02015-11-09 19:56:35 +00001156 if (E->isCmpXChg())
David Majnemer659be552014-11-25 23:44:32 +00001157 return Res;
Tim Northovercc2a6e02015-11-09 19:56:35 +00001158
1159 // The value is returned directly for optimized libcalls but the expr
1160 // provided an out-param.
1161 if (UseOptimizedLibcall && Res.getScalarVal()) {
David Majnemer659be552014-11-25 23:44:32 +00001162 llvm::Value *ResVal = Res.getScalarVal();
James Y Knight7aefb5b2015-11-12 18:37:29 +00001163 if (PostOp) {
1164 llvm::Value *LoadVal1 = Args[1].RV.getScalarVal();
1165 ResVal = Builder.CreateBinOp(PostOp, ResVal, LoadVal1);
1166 }
1167 if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch)
1168 ResVal = Builder.CreateNot(ResVal);
1169
Tim Northovercc2a6e02015-11-09 19:56:35 +00001170 Builder.CreateStore(
1171 ResVal,
1172 Builder.CreateBitCast(Dest, ResVal->getType()->getPointerTo()));
David Majnemer659be552014-11-25 23:44:32 +00001173 }
Tim Northovercc2a6e02015-11-09 19:56:35 +00001174
1175 if (RValTy->isVoidType())
1176 return RValue::get(nullptr);
1177
1178 return convertTempToRValue(
1179 Builder.CreateBitCast(Dest, ConvertTypeForMem(RValTy)->getPointerTo()),
1180 RValTy, E->getExprLoc());
John McCallfc207f22013-03-07 21:37:12 +00001181 }
1182
1183 bool IsStore = E->getOp() == AtomicExpr::AO__c11_atomic_store ||
Yaxun Liu39195062017-08-04 18:16:31 +00001184 E->getOp() == AtomicExpr::AO__opencl_atomic_store ||
John McCallfc207f22013-03-07 21:37:12 +00001185 E->getOp() == AtomicExpr::AO__atomic_store ||
1186 E->getOp() == AtomicExpr::AO__atomic_store_n;
1187 bool IsLoad = E->getOp() == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00001188 E->getOp() == AtomicExpr::AO__opencl_atomic_load ||
John McCallfc207f22013-03-07 21:37:12 +00001189 E->getOp() == AtomicExpr::AO__atomic_load ||
1190 E->getOp() == AtomicExpr::AO__atomic_load_n;
1191
John McCallfc207f22013-03-07 21:37:12 +00001192 if (isa<llvm::ConstantInt>(Order)) {
JF Bastiendda2cb12016-04-18 18:01:49 +00001193 auto ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
1194 // We should not ever get to a case where the ordering isn't a valid C ABI
1195 // value, but it's hard to enforce that in general.
1196 if (llvm::isValidAtomicOrderingCABI(ord))
1197 switch ((llvm::AtomicOrderingCABI)ord) {
1198 case llvm::AtomicOrderingCABI::relaxed:
1199 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001200 llvm::AtomicOrdering::Monotonic, Scope);
JF Bastiendda2cb12016-04-18 18:01:49 +00001201 break;
1202 case llvm::AtomicOrderingCABI::consume:
1203 case llvm::AtomicOrderingCABI::acquire:
1204 if (IsStore)
1205 break; // Avoid crashing on code with undefined behavior
1206 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001207 llvm::AtomicOrdering::Acquire, Scope);
JF Bastiendda2cb12016-04-18 18:01:49 +00001208 break;
1209 case llvm::AtomicOrderingCABI::release:
1210 if (IsLoad)
1211 break; // Avoid crashing on code with undefined behavior
1212 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001213 llvm::AtomicOrdering::Release, Scope);
JF Bastiendda2cb12016-04-18 18:01:49 +00001214 break;
1215 case llvm::AtomicOrderingCABI::acq_rel:
1216 if (IsLoad || IsStore)
1217 break; // Avoid crashing on code with undefined behavior
1218 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001219 llvm::AtomicOrdering::AcquireRelease, Scope);
JF Bastiendda2cb12016-04-18 18:01:49 +00001220 break;
1221 case llvm::AtomicOrderingCABI::seq_cst:
1222 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001223 llvm::AtomicOrdering::SequentiallyConsistent, Scope);
JF Bastiendda2cb12016-04-18 18:01:49 +00001224 break;
1225 }
David Majnemeree8d04d2014-12-12 08:16:09 +00001226 if (RValTy->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +00001227 return RValue::get(nullptr);
Tim Northovercc2a6e02015-11-09 19:56:35 +00001228
1229 return convertTempToRValue(
1230 Builder.CreateBitCast(Dest, ConvertTypeForMem(RValTy)->getPointerTo()),
1231 RValTy, E->getExprLoc());
John McCallfc207f22013-03-07 21:37:12 +00001232 }
1233
1234 // Long case, when Order isn't obviously constant.
1235
1236 // Create all the relevant BB's
Craig Topper8a13c412014-05-21 05:09:00 +00001237 llvm::BasicBlock *MonotonicBB = nullptr, *AcquireBB = nullptr,
1238 *ReleaseBB = nullptr, *AcqRelBB = nullptr,
1239 *SeqCstBB = nullptr;
John McCallfc207f22013-03-07 21:37:12 +00001240 MonotonicBB = createBasicBlock("monotonic", CurFn);
1241 if (!IsStore)
1242 AcquireBB = createBasicBlock("acquire", CurFn);
1243 if (!IsLoad)
1244 ReleaseBB = createBasicBlock("release", CurFn);
1245 if (!IsLoad && !IsStore)
1246 AcqRelBB = createBasicBlock("acqrel", CurFn);
1247 SeqCstBB = createBasicBlock("seqcst", CurFn);
1248 llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
1249
1250 // Create the switch for the split
1251 // MonotonicBB is arbitrarily chosen as the default case; in practice, this
1252 // doesn't matter unless someone is crazy enough to use something that
1253 // doesn't fold to a constant for the ordering.
1254 Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
1255 llvm::SwitchInst *SI = Builder.CreateSwitch(Order, MonotonicBB);
1256
1257 // Emit all the different atomics
1258 Builder.SetInsertPoint(MonotonicBB);
Yaxun Liu39195062017-08-04 18:16:31 +00001259 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001260 llvm::AtomicOrdering::Monotonic, Scope);
John McCallfc207f22013-03-07 21:37:12 +00001261 Builder.CreateBr(ContBB);
1262 if (!IsStore) {
1263 Builder.SetInsertPoint(AcquireBB);
Yaxun Liu39195062017-08-04 18:16:31 +00001264 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001265 llvm::AtomicOrdering::Acquire, Scope);
John McCallfc207f22013-03-07 21:37:12 +00001266 Builder.CreateBr(ContBB);
JF Bastiendda2cb12016-04-18 18:01:49 +00001267 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::consume),
Tim Northover514fc612014-03-13 19:25:52 +00001268 AcquireBB);
JF Bastiendda2cb12016-04-18 18:01:49 +00001269 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::acquire),
Tim Northover514fc612014-03-13 19:25:52 +00001270 AcquireBB);
John McCallfc207f22013-03-07 21:37:12 +00001271 }
1272 if (!IsLoad) {
1273 Builder.SetInsertPoint(ReleaseBB);
Yaxun Liu39195062017-08-04 18:16:31 +00001274 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001275 llvm::AtomicOrdering::Release, Scope);
John McCallfc207f22013-03-07 21:37:12 +00001276 Builder.CreateBr(ContBB);
JF Bastiendda2cb12016-04-18 18:01:49 +00001277 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::release),
Tim Northover514fc612014-03-13 19:25:52 +00001278 ReleaseBB);
John McCallfc207f22013-03-07 21:37:12 +00001279 }
1280 if (!IsLoad && !IsStore) {
1281 Builder.SetInsertPoint(AcqRelBB);
Yaxun Liu39195062017-08-04 18:16:31 +00001282 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001283 llvm::AtomicOrdering::AcquireRelease, Scope);
John McCallfc207f22013-03-07 21:37:12 +00001284 Builder.CreateBr(ContBB);
JF Bastiendda2cb12016-04-18 18:01:49 +00001285 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::acq_rel),
Tim Northover514fc612014-03-13 19:25:52 +00001286 AcqRelBB);
John McCallfc207f22013-03-07 21:37:12 +00001287 }
1288 Builder.SetInsertPoint(SeqCstBB);
Yaxun Liu39195062017-08-04 18:16:31 +00001289 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
Yaxun Liu30d652a2017-08-15 16:02:49 +00001290 llvm::AtomicOrdering::SequentiallyConsistent, Scope);
John McCallfc207f22013-03-07 21:37:12 +00001291 Builder.CreateBr(ContBB);
JF Bastiendda2cb12016-04-18 18:01:49 +00001292 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::seq_cst),
Tim Northover514fc612014-03-13 19:25:52 +00001293 SeqCstBB);
John McCallfc207f22013-03-07 21:37:12 +00001294
1295 // Cleanup and return
1296 Builder.SetInsertPoint(ContBB);
David Majnemeree8d04d2014-12-12 08:16:09 +00001297 if (RValTy->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +00001298 return RValue::get(nullptr);
Tim Northovercc2a6e02015-11-09 19:56:35 +00001299
1300 assert(Atomics.getValueSizeInBits() <= Atomics.getAtomicSizeInBits());
1301 return convertTempToRValue(
1302 Builder.CreateBitCast(Dest, ConvertTypeForMem(RValTy)->getPointerTo()),
1303 RValTy, E->getExprLoc());
John McCallfc207f22013-03-07 21:37:12 +00001304}
John McCalla8ec7eb2013-03-07 21:37:17 +00001305
John McCall7f416cc2015-09-08 08:05:57 +00001306Address AtomicInfo::emitCastToAtomicIntPointer(Address addr) const {
John McCalla8ec7eb2013-03-07 21:37:17 +00001307 unsigned addrspace =
John McCall7f416cc2015-09-08 08:05:57 +00001308 cast<llvm::PointerType>(addr.getPointer()->getType())->getAddressSpace();
John McCalla8ec7eb2013-03-07 21:37:17 +00001309 llvm::IntegerType *ty =
1310 llvm::IntegerType::get(CGF.getLLVMContext(), AtomicSizeInBits);
1311 return CGF.Builder.CreateBitCast(addr, ty->getPointerTo(addrspace));
1312}
1313
Tim Northovercc2a6e02015-11-09 19:56:35 +00001314Address AtomicInfo::convertToAtomicIntPointer(Address Addr) const {
1315 llvm::Type *Ty = Addr.getElementType();
1316 uint64_t SourceSizeInBits = CGF.CGM.getDataLayout().getTypeSizeInBits(Ty);
1317 if (SourceSizeInBits != AtomicSizeInBits) {
1318 Address Tmp = CreateTempAlloca();
1319 CGF.Builder.CreateMemCpy(Tmp, Addr,
1320 std::min(AtomicSizeInBits, SourceSizeInBits) / 8);
1321 Addr = Tmp;
1322 }
1323
1324 return emitCastToAtomicIntPointer(Addr);
1325}
1326
John McCall7f416cc2015-09-08 08:05:57 +00001327RValue AtomicInfo::convertAtomicTempToRValue(Address addr,
1328 AggValueSlot resultSlot,
1329 SourceLocation loc,
1330 bool asValue) const {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001331 if (LVal.isSimple()) {
1332 if (EvaluationKind == TEK_Aggregate)
1333 return resultSlot.asRValue();
John McCalla8ec7eb2013-03-07 21:37:17 +00001334
Alexey Bataevb57056f2015-01-22 06:17:56 +00001335 // Drill into the padding structure if we have one.
1336 if (hasPadding())
John McCall7f416cc2015-09-08 08:05:57 +00001337 addr = CGF.Builder.CreateStructGEP(addr, 0, CharUnits());
John McCalla8ec7eb2013-03-07 21:37:17 +00001338
Alexey Bataevb57056f2015-01-22 06:17:56 +00001339 // Otherwise, just convert the temporary to an r-value using the
1340 // normal conversion routine.
1341 return CGF.convertTempToRValue(addr, getValueType(), loc);
David Blaikie1ed728c2015-04-05 22:45:47 +00001342 }
John McCall7f416cc2015-09-08 08:05:57 +00001343 if (!asValue)
Alexey Bataevb8329262015-02-27 06:33:30 +00001344 // Get RValue from temp memory as atomic for non-simple lvalues
John McCall7f416cc2015-09-08 08:05:57 +00001345 return RValue::get(CGF.Builder.CreateLoad(addr));
David Blaikie1ed728c2015-04-05 22:45:47 +00001346 if (LVal.isBitField())
John McCall7f416cc2015-09-08 08:05:57 +00001347 return CGF.EmitLoadOfBitfieldLValue(
1348 LValue::MakeBitfield(addr, LVal.getBitFieldInfo(), LVal.getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001349 LVal.getBaseInfo()), loc);
David Blaikie1ed728c2015-04-05 22:45:47 +00001350 if (LVal.isVectorElt())
John McCall7f416cc2015-09-08 08:05:57 +00001351 return CGF.EmitLoadOfLValue(
1352 LValue::MakeVectorElt(addr, LVal.getVectorIdx(), LVal.getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001353 LVal.getBaseInfo()), loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001354 assert(LVal.isExtVectorElt());
1355 return CGF.EmitLoadOfExtVectorElementLValue(LValue::MakeExtVectorElt(
John McCall7f416cc2015-09-08 08:05:57 +00001356 addr, LVal.getExtVectorElts(), LVal.getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001357 LVal.getBaseInfo()));
John McCalla8ec7eb2013-03-07 21:37:17 +00001358}
1359
Alexey Bataevb8329262015-02-27 06:33:30 +00001360RValue AtomicInfo::ConvertIntToValueOrAtomic(llvm::Value *IntVal,
1361 AggValueSlot ResultSlot,
1362 SourceLocation Loc,
1363 bool AsValue) const {
Alexey Bataev452d8e12014-12-15 05:25:25 +00001364 // Try not to in some easy cases.
1365 assert(IntVal->getType()->isIntegerTy() && "Expected integer value");
Alexey Bataevb8329262015-02-27 06:33:30 +00001366 if (getEvaluationKind() == TEK_Scalar &&
1367 (((!LVal.isBitField() ||
1368 LVal.getBitFieldInfo().Size == ValueSizeInBits) &&
1369 !hasPadding()) ||
1370 !AsValue)) {
1371 auto *ValTy = AsValue
1372 ? CGF.ConvertTypeForMem(ValueTy)
John McCall7f416cc2015-09-08 08:05:57 +00001373 : getAtomicAddress().getType()->getPointerElementType();
Alexey Bataev452d8e12014-12-15 05:25:25 +00001374 if (ValTy->isIntegerTy()) {
1375 assert(IntVal->getType() == ValTy && "Different integer types.");
David Majnemereeaec262015-02-14 02:18:14 +00001376 return RValue::get(CGF.EmitFromMemory(IntVal, ValueTy));
Alexey Bataev452d8e12014-12-15 05:25:25 +00001377 } else if (ValTy->isPointerTy())
1378 return RValue::get(CGF.Builder.CreateIntToPtr(IntVal, ValTy));
1379 else if (llvm::CastInst::isBitCastable(IntVal->getType(), ValTy))
1380 return RValue::get(CGF.Builder.CreateBitCast(IntVal, ValTy));
1381 }
1382
1383 // Create a temporary. This needs to be big enough to hold the
1384 // atomic integer.
John McCall7f416cc2015-09-08 08:05:57 +00001385 Address Temp = Address::invalid();
Alexey Bataev452d8e12014-12-15 05:25:25 +00001386 bool TempIsVolatile = false;
Alexey Bataevb8329262015-02-27 06:33:30 +00001387 if (AsValue && getEvaluationKind() == TEK_Aggregate) {
Alexey Bataev452d8e12014-12-15 05:25:25 +00001388 assert(!ResultSlot.isIgnored());
John McCall7f416cc2015-09-08 08:05:57 +00001389 Temp = ResultSlot.getAddress();
Alexey Bataev452d8e12014-12-15 05:25:25 +00001390 TempIsVolatile = ResultSlot.isVolatile();
1391 } else {
Alexey Bataevb8329262015-02-27 06:33:30 +00001392 Temp = CreateTempAlloca();
Alexey Bataev452d8e12014-12-15 05:25:25 +00001393 }
1394
1395 // Slam the integer into the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00001396 Address CastTemp = emitCastToAtomicIntPointer(Temp);
1397 CGF.Builder.CreateStore(IntVal, CastTemp)
Alexey Bataev452d8e12014-12-15 05:25:25 +00001398 ->setVolatile(TempIsVolatile);
1399
John McCall7f416cc2015-09-08 08:05:57 +00001400 return convertAtomicTempToRValue(Temp, ResultSlot, Loc, AsValue);
Alexey Bataevb8329262015-02-27 06:33:30 +00001401}
1402
1403void AtomicInfo::EmitAtomicLoadLibcall(llvm::Value *AddForLoaded,
1404 llvm::AtomicOrdering AO, bool) {
1405 // void __atomic_load(size_t size, void *mem, void *return, int order);
1406 CallArgList Args;
1407 Args.add(RValue::get(getAtomicSizeValue()), CGF.getContext().getSizeType());
John McCall7f416cc2015-09-08 08:05:57 +00001408 Args.add(RValue::get(CGF.EmitCastToVoidPtr(getAtomicPointer())),
Alexey Bataevb8329262015-02-27 06:33:30 +00001409 CGF.getContext().VoidPtrTy);
1410 Args.add(RValue::get(CGF.EmitCastToVoidPtr(AddForLoaded)),
1411 CGF.getContext().VoidPtrTy);
JF Bastiendda2cb12016-04-18 18:01:49 +00001412 Args.add(
1413 RValue::get(llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(AO))),
1414 CGF.getContext().IntTy);
Alexey Bataevb8329262015-02-27 06:33:30 +00001415 emitAtomicLibcall(CGF, "__atomic_load", CGF.getContext().VoidTy, Args);
1416}
1417
1418llvm::Value *AtomicInfo::EmitAtomicLoadOp(llvm::AtomicOrdering AO,
1419 bool IsVolatile) {
1420 // Okay, we're doing this natively.
John McCall7f416cc2015-09-08 08:05:57 +00001421 Address Addr = getAtomicAddressAsAtomicIntPointer();
Alexey Bataevb8329262015-02-27 06:33:30 +00001422 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Addr, "atomic-load");
1423 Load->setAtomic(AO);
1424
1425 // Other decoration.
Alexey Bataevb8329262015-02-27 06:33:30 +00001426 if (IsVolatile)
1427 Load->setVolatile(true);
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +00001428 TBAAAccessInfo TBAAInfo(LVal.getTBAAAccessType());
1429 CGF.CGM.DecorateInstructionWithTBAA(Load, TBAAInfo);
Alexey Bataevb8329262015-02-27 06:33:30 +00001430 return Load;
Alexey Bataev452d8e12014-12-15 05:25:25 +00001431}
1432
David Majnemera5b195a2015-02-14 01:35:12 +00001433/// An LValue is a candidate for having its loads and stores be made atomic if
1434/// we are operating under /volatile:ms *and* the LValue itself is volatile and
1435/// performing such an operation can be performed without a libcall.
1436bool CodeGenFunction::LValueIsSuitableForInlineAtomic(LValue LV) {
John McCall7f416cc2015-09-08 08:05:57 +00001437 if (!CGM.getCodeGenOpts().MSVolatile) return false;
David Majnemera5b195a2015-02-14 01:35:12 +00001438 AtomicInfo AI(*this, LV);
1439 bool IsVolatile = LV.isVolatile() || hasVolatileMember(LV.getType());
1440 // An atomic is inline if we don't need to use a libcall.
1441 bool AtomicIsInline = !AI.shouldUseLibcall();
David Majnemerfc80b6e2016-01-22 16:36:44 +00001442 // MSVC doesn't seem to do this for types wider than a pointer.
David Majnemera38c9f12016-05-24 16:09:25 +00001443 if (getContext().getTypeSize(LV.getType()) >
David Majnemerfc80b6e2016-01-22 16:36:44 +00001444 getContext().getTypeSize(getContext().getIntPtrType()))
1445 return false;
David Majnemera38c9f12016-05-24 16:09:25 +00001446 return IsVolatile && AtomicIsInline;
David Majnemera5b195a2015-02-14 01:35:12 +00001447}
1448
1449RValue CodeGenFunction::EmitAtomicLoad(LValue LV, SourceLocation SL,
1450 AggValueSlot Slot) {
1451 llvm::AtomicOrdering AO;
1452 bool IsVolatile = LV.isVolatileQualified();
1453 if (LV.getType()->isAtomicType()) {
JF Bastien92f4ef12016-04-06 17:26:42 +00001454 AO = llvm::AtomicOrdering::SequentiallyConsistent;
David Majnemera5b195a2015-02-14 01:35:12 +00001455 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00001456 AO = llvm::AtomicOrdering::Acquire;
David Majnemera5b195a2015-02-14 01:35:12 +00001457 IsVolatile = true;
1458 }
1459 return EmitAtomicLoad(LV, SL, AO, IsVolatile, Slot);
1460}
1461
Alexey Bataevb8329262015-02-27 06:33:30 +00001462RValue AtomicInfo::EmitAtomicLoad(AggValueSlot ResultSlot, SourceLocation Loc,
1463 bool AsValue, llvm::AtomicOrdering AO,
1464 bool IsVolatile) {
1465 // Check whether we should use a library call.
1466 if (shouldUseLibcall()) {
John McCall7f416cc2015-09-08 08:05:57 +00001467 Address TempAddr = Address::invalid();
Alexey Bataevb8329262015-02-27 06:33:30 +00001468 if (LVal.isSimple() && !ResultSlot.isIgnored()) {
1469 assert(getEvaluationKind() == TEK_Aggregate);
John McCall7f416cc2015-09-08 08:05:57 +00001470 TempAddr = ResultSlot.getAddress();
Alexey Bataevb8329262015-02-27 06:33:30 +00001471 } else
1472 TempAddr = CreateTempAlloca();
1473
John McCall7f416cc2015-09-08 08:05:57 +00001474 EmitAtomicLoadLibcall(TempAddr.getPointer(), AO, IsVolatile);
Alexey Bataevb8329262015-02-27 06:33:30 +00001475
1476 // Okay, turn that back into the original value or whole atomic (for
1477 // non-simple lvalues) type.
John McCall7f416cc2015-09-08 08:05:57 +00001478 return convertAtomicTempToRValue(TempAddr, ResultSlot, Loc, AsValue);
Alexey Bataevb8329262015-02-27 06:33:30 +00001479 }
1480
1481 // Okay, we're doing this natively.
1482 auto *Load = EmitAtomicLoadOp(AO, IsVolatile);
1483
1484 // If we're ignoring an aggregate return, don't do anything.
1485 if (getEvaluationKind() == TEK_Aggregate && ResultSlot.isIgnored())
John McCall7f416cc2015-09-08 08:05:57 +00001486 return RValue::getAggregate(Address::invalid(), false);
Alexey Bataevb8329262015-02-27 06:33:30 +00001487
1488 // Okay, turn that back into the original value or atomic (for non-simple
1489 // lvalues) type.
1490 return ConvertIntToValueOrAtomic(Load, ResultSlot, Loc, AsValue);
1491}
1492
John McCalla8ec7eb2013-03-07 21:37:17 +00001493/// Emit a load from an l-value of atomic type. Note that the r-value
1494/// we produce is an r-value of the atomic *value* type.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001495RValue CodeGenFunction::EmitAtomicLoad(LValue src, SourceLocation loc,
David Majnemera5b195a2015-02-14 01:35:12 +00001496 llvm::AtomicOrdering AO, bool IsVolatile,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001497 AggValueSlot resultSlot) {
Alexey Bataevb8329262015-02-27 06:33:30 +00001498 AtomicInfo Atomics(*this, src);
1499 return Atomics.EmitAtomicLoad(resultSlot, loc, /*AsValue=*/true, AO,
1500 IsVolatile);
John McCalla8ec7eb2013-03-07 21:37:17 +00001501}
1502
John McCalla8ec7eb2013-03-07 21:37:17 +00001503/// Copy an r-value into memory as part of storing to an atomic type.
1504/// This needs to create a bit-pattern suitable for atomic operations.
Alexey Bataevb57056f2015-01-22 06:17:56 +00001505void AtomicInfo::emitCopyIntoMemory(RValue rvalue) const {
1506 assert(LVal.isSimple());
John McCalla8ec7eb2013-03-07 21:37:17 +00001507 // If we have an r-value, the rvalue should be of the atomic type,
1508 // which means that the caller is responsible for having zeroed
1509 // any padding. Just do an aggregate copy of that type.
1510 if (rvalue.isAggregate()) {
Alexey Bataevb8329262015-02-27 06:33:30 +00001511 CGF.EmitAggregateCopy(getAtomicAddress(),
John McCall7f416cc2015-09-08 08:05:57 +00001512 rvalue.getAggregateAddress(),
John McCalla8ec7eb2013-03-07 21:37:17 +00001513 getAtomicType(),
1514 (rvalue.isVolatileQualified()
John McCall7f416cc2015-09-08 08:05:57 +00001515 || LVal.isVolatileQualified()));
John McCalla8ec7eb2013-03-07 21:37:17 +00001516 return;
1517 }
1518
1519 // Okay, otherwise we're copying stuff.
1520
1521 // Zero out the buffer if necessary.
Alexey Bataevb57056f2015-01-22 06:17:56 +00001522 emitMemSetZeroIfNecessary();
John McCalla8ec7eb2013-03-07 21:37:17 +00001523
1524 // Drill past the padding if present.
Alexey Bataevb57056f2015-01-22 06:17:56 +00001525 LValue TempLVal = projectValue();
John McCalla8ec7eb2013-03-07 21:37:17 +00001526
1527 // Okay, store the rvalue in.
1528 if (rvalue.isScalar()) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001529 CGF.EmitStoreOfScalar(rvalue.getScalarVal(), TempLVal, /*init*/ true);
John McCalla8ec7eb2013-03-07 21:37:17 +00001530 } else {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001531 CGF.EmitStoreOfComplex(rvalue.getComplexVal(), TempLVal, /*init*/ true);
John McCalla8ec7eb2013-03-07 21:37:17 +00001532 }
1533}
1534
1535
1536/// Materialize an r-value into memory for the purposes of storing it
1537/// to an atomic type.
John McCall7f416cc2015-09-08 08:05:57 +00001538Address AtomicInfo::materializeRValue(RValue rvalue) const {
John McCalla8ec7eb2013-03-07 21:37:17 +00001539 // Aggregate r-values are already in memory, and EmitAtomicStore
1540 // requires them to be values of the atomic type.
1541 if (rvalue.isAggregate())
John McCall7f416cc2015-09-08 08:05:57 +00001542 return rvalue.getAggregateAddress();
John McCalla8ec7eb2013-03-07 21:37:17 +00001543
1544 // Otherwise, make a temporary and materialize into it.
John McCall7f416cc2015-09-08 08:05:57 +00001545 LValue TempLV = CGF.MakeAddrLValue(CreateTempAlloca(), getAtomicType());
Alexey Bataevb8329262015-02-27 06:33:30 +00001546 AtomicInfo Atomics(CGF, TempLV);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001547 Atomics.emitCopyIntoMemory(rvalue);
Alexey Bataevb8329262015-02-27 06:33:30 +00001548 return TempLV.getAddress();
John McCalla8ec7eb2013-03-07 21:37:17 +00001549}
1550
Alexey Bataev452d8e12014-12-15 05:25:25 +00001551llvm::Value *AtomicInfo::convertRValueToInt(RValue RVal) const {
1552 // If we've got a scalar value of the right size, try to avoid going
1553 // through memory.
Alexey Bataevb8329262015-02-27 06:33:30 +00001554 if (RVal.isScalar() && (!hasPadding() || !LVal.isSimple())) {
Alexey Bataev452d8e12014-12-15 05:25:25 +00001555 llvm::Value *Value = RVal.getScalarVal();
1556 if (isa<llvm::IntegerType>(Value->getType()))
Alexey Bataevb4505a72015-03-30 05:20:59 +00001557 return CGF.EmitToMemory(Value, ValueTy);
Alexey Bataev452d8e12014-12-15 05:25:25 +00001558 else {
Alexey Bataevb8329262015-02-27 06:33:30 +00001559 llvm::IntegerType *InputIntTy = llvm::IntegerType::get(
1560 CGF.getLLVMContext(),
1561 LVal.isSimple() ? getValueSizeInBits() : getAtomicSizeInBits());
Alexey Bataev452d8e12014-12-15 05:25:25 +00001562 if (isa<llvm::PointerType>(Value->getType()))
1563 return CGF.Builder.CreatePtrToInt(Value, InputIntTy);
1564 else if (llvm::BitCastInst::isBitCastable(Value->getType(), InputIntTy))
1565 return CGF.Builder.CreateBitCast(Value, InputIntTy);
1566 }
1567 }
1568 // Otherwise, we need to go through memory.
1569 // Put the r-value in memory.
John McCall7f416cc2015-09-08 08:05:57 +00001570 Address Addr = materializeRValue(RVal);
Alexey Bataev452d8e12014-12-15 05:25:25 +00001571
1572 // Cast the temporary to the atomic int type and pull a value out.
1573 Addr = emitCastToAtomicIntPointer(Addr);
John McCall7f416cc2015-09-08 08:05:57 +00001574 return CGF.Builder.CreateLoad(Addr);
Alexey Bataev452d8e12014-12-15 05:25:25 +00001575}
1576
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001577std::pair<llvm::Value *, llvm::Value *> AtomicInfo::EmitAtomicCompareExchangeOp(
1578 llvm::Value *ExpectedVal, llvm::Value *DesiredVal,
1579 llvm::AtomicOrdering Success, llvm::AtomicOrdering Failure, bool IsWeak) {
Alexey Bataevb8329262015-02-27 06:33:30 +00001580 // Do the atomic store.
John McCall7f416cc2015-09-08 08:05:57 +00001581 Address Addr = getAtomicAddressAsAtomicIntPointer();
1582 auto *Inst = CGF.Builder.CreateAtomicCmpXchg(Addr.getPointer(),
1583 ExpectedVal, DesiredVal,
Alexey Bataevb4505a72015-03-30 05:20:59 +00001584 Success, Failure);
Alexey Bataevb8329262015-02-27 06:33:30 +00001585 // Other decoration.
1586 Inst->setVolatile(LVal.isVolatileQualified());
1587 Inst->setWeak(IsWeak);
1588
1589 // Okay, turn that back into the original value type.
1590 auto *PreviousVal = CGF.Builder.CreateExtractValue(Inst, /*Idxs=*/0);
1591 auto *SuccessFailureVal = CGF.Builder.CreateExtractValue(Inst, /*Idxs=*/1);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001592 return std::make_pair(PreviousVal, SuccessFailureVal);
Alexey Bataevb8329262015-02-27 06:33:30 +00001593}
1594
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001595llvm::Value *
1596AtomicInfo::EmitAtomicCompareExchangeLibcall(llvm::Value *ExpectedAddr,
1597 llvm::Value *DesiredAddr,
Alexey Bataevb8329262015-02-27 06:33:30 +00001598 llvm::AtomicOrdering Success,
1599 llvm::AtomicOrdering Failure) {
1600 // bool __atomic_compare_exchange(size_t size, void *obj, void *expected,
1601 // void *desired, int success, int failure);
1602 CallArgList Args;
1603 Args.add(RValue::get(getAtomicSizeValue()), CGF.getContext().getSizeType());
John McCall7f416cc2015-09-08 08:05:57 +00001604 Args.add(RValue::get(CGF.EmitCastToVoidPtr(getAtomicPointer())),
Alexey Bataevb8329262015-02-27 06:33:30 +00001605 CGF.getContext().VoidPtrTy);
1606 Args.add(RValue::get(CGF.EmitCastToVoidPtr(ExpectedAddr)),
1607 CGF.getContext().VoidPtrTy);
1608 Args.add(RValue::get(CGF.EmitCastToVoidPtr(DesiredAddr)),
1609 CGF.getContext().VoidPtrTy);
JF Bastiendda2cb12016-04-18 18:01:49 +00001610 Args.add(RValue::get(
1611 llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(Success))),
Alexey Bataevb8329262015-02-27 06:33:30 +00001612 CGF.getContext().IntTy);
JF Bastiendda2cb12016-04-18 18:01:49 +00001613 Args.add(RValue::get(
1614 llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(Failure))),
Alexey Bataevb8329262015-02-27 06:33:30 +00001615 CGF.getContext().IntTy);
1616 auto SuccessFailureRVal = emitAtomicLibcall(CGF, "__atomic_compare_exchange",
1617 CGF.getContext().BoolTy, Args);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001618
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001619 return SuccessFailureRVal.getScalarVal();
Alexey Bataevb8329262015-02-27 06:33:30 +00001620}
1621
Alexey Bataevb4505a72015-03-30 05:20:59 +00001622std::pair<RValue, llvm::Value *> AtomicInfo::EmitAtomicCompareExchange(
Alexey Bataevb8329262015-02-27 06:33:30 +00001623 RValue Expected, RValue Desired, llvm::AtomicOrdering Success,
1624 llvm::AtomicOrdering Failure, bool IsWeak) {
JF Bastiendd11ee72016-04-06 23:37:36 +00001625 if (isStrongerThan(Failure, Success))
1626 // Don't assert on undefined behavior "failure argument shall be no stronger
1627 // than the success argument".
Alexey Bataevb8329262015-02-27 06:33:30 +00001628 Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(Success);
1629
1630 // Check whether we should use a library call.
1631 if (shouldUseLibcall()) {
Alexey Bataevb8329262015-02-27 06:33:30 +00001632 // Produce a source address.
John McCall7f416cc2015-09-08 08:05:57 +00001633 Address ExpectedAddr = materializeRValue(Expected);
1634 Address DesiredAddr = materializeRValue(Desired);
1635 auto *Res = EmitAtomicCompareExchangeLibcall(ExpectedAddr.getPointer(),
1636 DesiredAddr.getPointer(),
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001637 Success, Failure);
1638 return std::make_pair(
John McCall7f416cc2015-09-08 08:05:57 +00001639 convertAtomicTempToRValue(ExpectedAddr, AggValueSlot::ignored(),
1640 SourceLocation(), /*AsValue=*/false),
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001641 Res);
Alexey Bataevb8329262015-02-27 06:33:30 +00001642 }
1643
1644 // If we've got a scalar value of the right size, try to avoid going
1645 // through memory.
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001646 auto *ExpectedVal = convertRValueToInt(Expected);
1647 auto *DesiredVal = convertRValueToInt(Desired);
1648 auto Res = EmitAtomicCompareExchangeOp(ExpectedVal, DesiredVal, Success,
1649 Failure, IsWeak);
1650 return std::make_pair(
1651 ConvertIntToValueOrAtomic(Res.first, AggValueSlot::ignored(),
1652 SourceLocation(), /*AsValue=*/false),
1653 Res.second);
1654}
1655
1656static void
1657EmitAtomicUpdateValue(CodeGenFunction &CGF, AtomicInfo &Atomics, RValue OldRVal,
1658 const llvm::function_ref<RValue(RValue)> &UpdateOp,
John McCall7f416cc2015-09-08 08:05:57 +00001659 Address DesiredAddr) {
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001660 RValue UpRVal;
1661 LValue AtomicLVal = Atomics.getAtomicLValue();
1662 LValue DesiredLVal;
1663 if (AtomicLVal.isSimple()) {
1664 UpRVal = OldRVal;
John McCall7f416cc2015-09-08 08:05:57 +00001665 DesiredLVal = CGF.MakeAddrLValue(DesiredAddr, AtomicLVal.getType());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001666 } else {
1667 // Build new lvalue for temp address
John McCall7f416cc2015-09-08 08:05:57 +00001668 Address Ptr = Atomics.materializeRValue(OldRVal);
1669 LValue UpdateLVal;
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001670 if (AtomicLVal.isBitField()) {
1671 UpdateLVal =
1672 LValue::MakeBitfield(Ptr, AtomicLVal.getBitFieldInfo(),
John McCall7f416cc2015-09-08 08:05:57 +00001673 AtomicLVal.getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001674 AtomicLVal.getBaseInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001675 DesiredLVal =
1676 LValue::MakeBitfield(DesiredAddr, AtomicLVal.getBitFieldInfo(),
John McCall7f416cc2015-09-08 08:05:57 +00001677 AtomicLVal.getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001678 AtomicLVal.getBaseInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001679 } else if (AtomicLVal.isVectorElt()) {
1680 UpdateLVal = LValue::MakeVectorElt(Ptr, AtomicLVal.getVectorIdx(),
1681 AtomicLVal.getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001682 AtomicLVal.getBaseInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001683 DesiredLVal = LValue::MakeVectorElt(
1684 DesiredAddr, AtomicLVal.getVectorIdx(), AtomicLVal.getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001685 AtomicLVal.getBaseInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001686 } else {
1687 assert(AtomicLVal.isExtVectorElt());
1688 UpdateLVal = LValue::MakeExtVectorElt(Ptr, AtomicLVal.getExtVectorElts(),
1689 AtomicLVal.getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001690 AtomicLVal.getBaseInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001691 DesiredLVal = LValue::MakeExtVectorElt(
1692 DesiredAddr, AtomicLVal.getExtVectorElts(), AtomicLVal.getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001693 AtomicLVal.getBaseInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001694 }
Ivan A. Kosarevc12b48e2017-10-03 11:31:42 +00001695 UpdateLVal.setTBAAInfo(AtomicLVal.getTBAAInfo());
1696 DesiredLVal.setTBAAInfo(AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001697 UpRVal = CGF.EmitLoadOfLValue(UpdateLVal, SourceLocation());
1698 }
1699 // Store new value in the corresponding memory area
1700 RValue NewRVal = UpdateOp(UpRVal);
1701 if (NewRVal.isScalar()) {
1702 CGF.EmitStoreThroughLValue(NewRVal, DesiredLVal);
1703 } else {
1704 assert(NewRVal.isComplex());
1705 CGF.EmitStoreOfComplex(NewRVal.getComplexVal(), DesiredLVal,
1706 /*isInit=*/false);
1707 }
1708}
1709
1710void AtomicInfo::EmitAtomicUpdateLibcall(
1711 llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1712 bool IsVolatile) {
1713 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1714
John McCall7f416cc2015-09-08 08:05:57 +00001715 Address ExpectedAddr = CreateTempAlloca();
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001716
John McCall7f416cc2015-09-08 08:05:57 +00001717 EmitAtomicLoadLibcall(ExpectedAddr.getPointer(), AO, IsVolatile);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001718 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1719 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1720 CGF.EmitBlock(ContBB);
John McCall7f416cc2015-09-08 08:05:57 +00001721 Address DesiredAddr = CreateTempAlloca();
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001722 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
John McCall7f416cc2015-09-08 08:05:57 +00001723 requiresMemSetZero(getAtomicAddress().getElementType())) {
1724 auto *OldVal = CGF.Builder.CreateLoad(ExpectedAddr);
1725 CGF.Builder.CreateStore(OldVal, DesiredAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001726 }
John McCall7f416cc2015-09-08 08:05:57 +00001727 auto OldRVal = convertAtomicTempToRValue(ExpectedAddr,
1728 AggValueSlot::ignored(),
1729 SourceLocation(), /*AsValue=*/false);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001730 EmitAtomicUpdateValue(CGF, *this, OldRVal, UpdateOp, DesiredAddr);
1731 auto *Res =
John McCall7f416cc2015-09-08 08:05:57 +00001732 EmitAtomicCompareExchangeLibcall(ExpectedAddr.getPointer(),
1733 DesiredAddr.getPointer(),
1734 AO, Failure);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001735 CGF.Builder.CreateCondBr(Res, ExitBB, ContBB);
1736 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1737}
1738
1739void AtomicInfo::EmitAtomicUpdateOp(
1740 llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1741 bool IsVolatile) {
1742 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1743
1744 // Do the atomic load.
1745 auto *OldVal = EmitAtomicLoadOp(AO, IsVolatile);
1746 // For non-simple lvalues perform compare-and-swap procedure.
1747 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1748 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1749 auto *CurBB = CGF.Builder.GetInsertBlock();
1750 CGF.EmitBlock(ContBB);
1751 llvm::PHINode *PHI = CGF.Builder.CreatePHI(OldVal->getType(),
1752 /*NumReservedValues=*/2);
1753 PHI->addIncoming(OldVal, CurBB);
John McCall7f416cc2015-09-08 08:05:57 +00001754 Address NewAtomicAddr = CreateTempAlloca();
1755 Address NewAtomicIntAddr = emitCastToAtomicIntPointer(NewAtomicAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001756 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
John McCall7f416cc2015-09-08 08:05:57 +00001757 requiresMemSetZero(getAtomicAddress().getElementType())) {
1758 CGF.Builder.CreateStore(PHI, NewAtomicIntAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001759 }
1760 auto OldRVal = ConvertIntToValueOrAtomic(PHI, AggValueSlot::ignored(),
1761 SourceLocation(), /*AsValue=*/false);
1762 EmitAtomicUpdateValue(CGF, *this, OldRVal, UpdateOp, NewAtomicAddr);
John McCall7f416cc2015-09-08 08:05:57 +00001763 auto *DesiredVal = CGF.Builder.CreateLoad(NewAtomicIntAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001764 // Try to write new value using cmpxchg operation
1765 auto Res = EmitAtomicCompareExchangeOp(PHI, DesiredVal, AO, Failure);
1766 PHI->addIncoming(Res.first, CGF.Builder.GetInsertBlock());
1767 CGF.Builder.CreateCondBr(Res.second, ExitBB, ContBB);
1768 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1769}
1770
1771static void EmitAtomicUpdateValue(CodeGenFunction &CGF, AtomicInfo &Atomics,
John McCall7f416cc2015-09-08 08:05:57 +00001772 RValue UpdateRVal, Address DesiredAddr) {
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001773 LValue AtomicLVal = Atomics.getAtomicLValue();
1774 LValue DesiredLVal;
1775 // Build new lvalue for temp address
1776 if (AtomicLVal.isBitField()) {
1777 DesiredLVal =
1778 LValue::MakeBitfield(DesiredAddr, AtomicLVal.getBitFieldInfo(),
John McCall7f416cc2015-09-08 08:05:57 +00001779 AtomicLVal.getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001780 AtomicLVal.getBaseInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001781 } else if (AtomicLVal.isVectorElt()) {
1782 DesiredLVal =
1783 LValue::MakeVectorElt(DesiredAddr, AtomicLVal.getVectorIdx(),
John McCall7f416cc2015-09-08 08:05:57 +00001784 AtomicLVal.getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001785 AtomicLVal.getBaseInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001786 } else {
1787 assert(AtomicLVal.isExtVectorElt());
1788 DesiredLVal = LValue::MakeExtVectorElt(
1789 DesiredAddr, AtomicLVal.getExtVectorElts(), AtomicLVal.getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001790 AtomicLVal.getBaseInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001791 }
Ivan A. Kosarevc12b48e2017-10-03 11:31:42 +00001792 DesiredLVal.setTBAAInfo(AtomicLVal.getTBAAInfo());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001793 // Store new value in the corresponding memory area
1794 assert(UpdateRVal.isScalar());
1795 CGF.EmitStoreThroughLValue(UpdateRVal, DesiredLVal);
1796}
1797
1798void AtomicInfo::EmitAtomicUpdateLibcall(llvm::AtomicOrdering AO,
1799 RValue UpdateRVal, bool IsVolatile) {
1800 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1801
John McCall7f416cc2015-09-08 08:05:57 +00001802 Address ExpectedAddr = CreateTempAlloca();
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001803
John McCall7f416cc2015-09-08 08:05:57 +00001804 EmitAtomicLoadLibcall(ExpectedAddr.getPointer(), AO, IsVolatile);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001805 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1806 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1807 CGF.EmitBlock(ContBB);
John McCall7f416cc2015-09-08 08:05:57 +00001808 Address DesiredAddr = CreateTempAlloca();
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001809 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
John McCall7f416cc2015-09-08 08:05:57 +00001810 requiresMemSetZero(getAtomicAddress().getElementType())) {
1811 auto *OldVal = CGF.Builder.CreateLoad(ExpectedAddr);
1812 CGF.Builder.CreateStore(OldVal, DesiredAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001813 }
1814 EmitAtomicUpdateValue(CGF, *this, UpdateRVal, DesiredAddr);
1815 auto *Res =
John McCall7f416cc2015-09-08 08:05:57 +00001816 EmitAtomicCompareExchangeLibcall(ExpectedAddr.getPointer(),
1817 DesiredAddr.getPointer(),
1818 AO, Failure);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001819 CGF.Builder.CreateCondBr(Res, ExitBB, ContBB);
1820 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1821}
1822
1823void AtomicInfo::EmitAtomicUpdateOp(llvm::AtomicOrdering AO, RValue UpdateRVal,
1824 bool IsVolatile) {
1825 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1826
1827 // Do the atomic load.
1828 auto *OldVal = EmitAtomicLoadOp(AO, IsVolatile);
1829 // For non-simple lvalues perform compare-and-swap procedure.
1830 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1831 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1832 auto *CurBB = CGF.Builder.GetInsertBlock();
1833 CGF.EmitBlock(ContBB);
1834 llvm::PHINode *PHI = CGF.Builder.CreatePHI(OldVal->getType(),
1835 /*NumReservedValues=*/2);
1836 PHI->addIncoming(OldVal, CurBB);
John McCall7f416cc2015-09-08 08:05:57 +00001837 Address NewAtomicAddr = CreateTempAlloca();
1838 Address NewAtomicIntAddr = emitCastToAtomicIntPointer(NewAtomicAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001839 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
John McCall7f416cc2015-09-08 08:05:57 +00001840 requiresMemSetZero(getAtomicAddress().getElementType())) {
1841 CGF.Builder.CreateStore(PHI, NewAtomicIntAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001842 }
1843 EmitAtomicUpdateValue(CGF, *this, UpdateRVal, NewAtomicAddr);
John McCall7f416cc2015-09-08 08:05:57 +00001844 auto *DesiredVal = CGF.Builder.CreateLoad(NewAtomicIntAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001845 // Try to write new value using cmpxchg operation
1846 auto Res = EmitAtomicCompareExchangeOp(PHI, DesiredVal, AO, Failure);
1847 PHI->addIncoming(Res.first, CGF.Builder.GetInsertBlock());
1848 CGF.Builder.CreateCondBr(Res.second, ExitBB, ContBB);
1849 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1850}
1851
1852void AtomicInfo::EmitAtomicUpdate(
1853 llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1854 bool IsVolatile) {
1855 if (shouldUseLibcall()) {
1856 EmitAtomicUpdateLibcall(AO, UpdateOp, IsVolatile);
1857 } else {
1858 EmitAtomicUpdateOp(AO, UpdateOp, IsVolatile);
1859 }
1860}
1861
1862void AtomicInfo::EmitAtomicUpdate(llvm::AtomicOrdering AO, RValue UpdateRVal,
1863 bool IsVolatile) {
1864 if (shouldUseLibcall()) {
1865 EmitAtomicUpdateLibcall(AO, UpdateRVal, IsVolatile);
1866 } else {
1867 EmitAtomicUpdateOp(AO, UpdateRVal, IsVolatile);
1868 }
Alexey Bataevb8329262015-02-27 06:33:30 +00001869}
1870
David Majnemera5b195a2015-02-14 01:35:12 +00001871void CodeGenFunction::EmitAtomicStore(RValue rvalue, LValue lvalue,
1872 bool isInit) {
1873 bool IsVolatile = lvalue.isVolatileQualified();
1874 llvm::AtomicOrdering AO;
1875 if (lvalue.getType()->isAtomicType()) {
JF Bastien92f4ef12016-04-06 17:26:42 +00001876 AO = llvm::AtomicOrdering::SequentiallyConsistent;
David Majnemera5b195a2015-02-14 01:35:12 +00001877 } else {
JF Bastien92f4ef12016-04-06 17:26:42 +00001878 AO = llvm::AtomicOrdering::Release;
David Majnemera5b195a2015-02-14 01:35:12 +00001879 IsVolatile = true;
1880 }
1881 return EmitAtomicStore(rvalue, lvalue, AO, IsVolatile, isInit);
1882}
1883
John McCalla8ec7eb2013-03-07 21:37:17 +00001884/// Emit a store to an l-value of atomic type.
1885///
1886/// Note that the r-value is expected to be an r-value *of the atomic
1887/// type*; this means that for aggregate r-values, it should include
1888/// storage for any padding that was necessary.
David Majnemera5b195a2015-02-14 01:35:12 +00001889void CodeGenFunction::EmitAtomicStore(RValue rvalue, LValue dest,
1890 llvm::AtomicOrdering AO, bool IsVolatile,
1891 bool isInit) {
John McCalla8ec7eb2013-03-07 21:37:17 +00001892 // If this is an aggregate r-value, it should agree in type except
1893 // maybe for address-space qualification.
1894 assert(!rvalue.isAggregate() ||
John McCall7f416cc2015-09-08 08:05:57 +00001895 rvalue.getAggregateAddress().getElementType()
1896 == dest.getAddress().getElementType());
John McCalla8ec7eb2013-03-07 21:37:17 +00001897
1898 AtomicInfo atomics(*this, dest);
Alexey Bataevb8329262015-02-27 06:33:30 +00001899 LValue LVal = atomics.getAtomicLValue();
John McCalla8ec7eb2013-03-07 21:37:17 +00001900
1901 // If this is an initialization, just put the value there normally.
Alexey Bataevb8329262015-02-27 06:33:30 +00001902 if (LVal.isSimple()) {
1903 if (isInit) {
1904 atomics.emitCopyIntoMemory(rvalue);
1905 return;
1906 }
1907
1908 // Check whether we should use a library call.
1909 if (atomics.shouldUseLibcall()) {
1910 // Produce a source address.
John McCall7f416cc2015-09-08 08:05:57 +00001911 Address srcAddr = atomics.materializeRValue(rvalue);
Alexey Bataevb8329262015-02-27 06:33:30 +00001912
1913 // void __atomic_store(size_t size, void *mem, void *val, int order)
1914 CallArgList args;
1915 args.add(RValue::get(atomics.getAtomicSizeValue()),
1916 getContext().getSizeType());
John McCall7f416cc2015-09-08 08:05:57 +00001917 args.add(RValue::get(EmitCastToVoidPtr(atomics.getAtomicPointer())),
Alexey Bataevb8329262015-02-27 06:33:30 +00001918 getContext().VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00001919 args.add(RValue::get(EmitCastToVoidPtr(srcAddr.getPointer())),
1920 getContext().VoidPtrTy);
JF Bastiendda2cb12016-04-18 18:01:49 +00001921 args.add(
1922 RValue::get(llvm::ConstantInt::get(IntTy, (int)llvm::toCABI(AO))),
1923 getContext().IntTy);
Alexey Bataevb8329262015-02-27 06:33:30 +00001924 emitAtomicLibcall(*this, "__atomic_store", getContext().VoidTy, args);
1925 return;
1926 }
1927
1928 // Okay, we're doing this natively.
1929 llvm::Value *intValue = atomics.convertRValueToInt(rvalue);
1930
1931 // Do the atomic store.
John McCall7f416cc2015-09-08 08:05:57 +00001932 Address addr =
Alexey Bataevb8329262015-02-27 06:33:30 +00001933 atomics.emitCastToAtomicIntPointer(atomics.getAtomicAddress());
1934 intValue = Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00001935 intValue, addr.getElementType(), /*isSigned=*/false);
Alexey Bataevb8329262015-02-27 06:33:30 +00001936 llvm::StoreInst *store = Builder.CreateStore(intValue, addr);
1937
1938 // Initializations don't need to be atomic.
1939 if (!isInit)
1940 store->setAtomic(AO);
1941
1942 // Other decoration.
Alexey Bataevb8329262015-02-27 06:33:30 +00001943 if (IsVolatile)
1944 store->setVolatile(true);
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +00001945 TBAAAccessInfo TBAAInfo(dest.getTBAAAccessType());
1946 CGM.DecorateInstructionWithTBAA(store, TBAAInfo);
John McCalla8ec7eb2013-03-07 21:37:17 +00001947 return;
1948 }
1949
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001950 // Emit simple atomic update operation.
1951 atomics.EmitAtomicUpdate(AO, rvalue, IsVolatile);
John McCalla8ec7eb2013-03-07 21:37:17 +00001952}
1953
Alexey Bataev452d8e12014-12-15 05:25:25 +00001954/// Emit a compare-and-exchange op for atomic type.
1955///
Alexey Bataevb4505a72015-03-30 05:20:59 +00001956std::pair<RValue, llvm::Value *> CodeGenFunction::EmitAtomicCompareExchange(
Alexey Bataev452d8e12014-12-15 05:25:25 +00001957 LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
1958 llvm::AtomicOrdering Success, llvm::AtomicOrdering Failure, bool IsWeak,
1959 AggValueSlot Slot) {
1960 // If this is an aggregate r-value, it should agree in type except
1961 // maybe for address-space qualification.
1962 assert(!Expected.isAggregate() ||
John McCall7f416cc2015-09-08 08:05:57 +00001963 Expected.getAggregateAddress().getElementType() ==
1964 Obj.getAddress().getElementType());
Alexey Bataev452d8e12014-12-15 05:25:25 +00001965 assert(!Desired.isAggregate() ||
John McCall7f416cc2015-09-08 08:05:57 +00001966 Desired.getAggregateAddress().getElementType() ==
1967 Obj.getAddress().getElementType());
Alexey Bataev452d8e12014-12-15 05:25:25 +00001968 AtomicInfo Atomics(*this, Obj);
1969
Alexey Bataevb4505a72015-03-30 05:20:59 +00001970 return Atomics.EmitAtomicCompareExchange(Expected, Desired, Success, Failure,
1971 IsWeak);
1972}
1973
1974void CodeGenFunction::EmitAtomicUpdate(
1975 LValue LVal, llvm::AtomicOrdering AO,
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001976 const llvm::function_ref<RValue(RValue)> &UpdateOp, bool IsVolatile) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00001977 AtomicInfo Atomics(*this, LVal);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001978 Atomics.EmitAtomicUpdate(AO, UpdateOp, IsVolatile);
Alexey Bataev452d8e12014-12-15 05:25:25 +00001979}
1980
John McCalla8ec7eb2013-03-07 21:37:17 +00001981void CodeGenFunction::EmitAtomicInit(Expr *init, LValue dest) {
1982 AtomicInfo atomics(*this, dest);
1983
1984 switch (atomics.getEvaluationKind()) {
1985 case TEK_Scalar: {
1986 llvm::Value *value = EmitScalarExpr(init);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001987 atomics.emitCopyIntoMemory(RValue::get(value));
John McCalla8ec7eb2013-03-07 21:37:17 +00001988 return;
1989 }
1990
1991 case TEK_Complex: {
1992 ComplexPairTy value = EmitComplexExpr(init);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001993 atomics.emitCopyIntoMemory(RValue::getComplex(value));
John McCalla8ec7eb2013-03-07 21:37:17 +00001994 return;
1995 }
1996
1997 case TEK_Aggregate: {
Eli Friedmanbe4504d2013-07-11 01:32:21 +00001998 // Fix up the destination if the initializer isn't an expression
1999 // of atomic type.
2000 bool Zeroed = false;
John McCalla8ec7eb2013-03-07 21:37:17 +00002001 if (!init->getType()->isAtomicType()) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00002002 Zeroed = atomics.emitMemSetZeroIfNecessary();
2003 dest = atomics.projectValue();
John McCalla8ec7eb2013-03-07 21:37:17 +00002004 }
2005
2006 // Evaluate the expression directly into the destination.
2007 AggValueSlot slot = AggValueSlot::forLValue(dest,
2008 AggValueSlot::IsNotDestructed,
2009 AggValueSlot::DoesNotNeedGCBarriers,
Eli Friedmanbe4504d2013-07-11 01:32:21 +00002010 AggValueSlot::IsNotAliased,
2011 Zeroed ? AggValueSlot::IsZeroed :
2012 AggValueSlot::IsNotZeroed);
2013
John McCalla8ec7eb2013-03-07 21:37:17 +00002014 EmitAggExpr(init, slot);
2015 return;
2016 }
2017 }
2018 llvm_unreachable("bad evaluation kind");
2019}