blob: 4e52c3630c772731c26c08dc667405fe592ec6da [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
14#include "CodeGenFunction.h"
15#include "CGCall.h"
Alexey Bataevb57056f2015-01-22 06:17:56 +000016#include "CGRecordLayout.h"
John McCallfc207f22013-03-07 21:37:12 +000017#include "CodeGenModule.h"
18#include "clang/AST/ASTContext.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000019#include "clang/CodeGen/CGFunctionInfo.h"
Ed Schoutenc7e82bd2013-05-31 19:27:59 +000020#include "llvm/ADT/StringExtras.h"
John McCallfc207f22013-03-07 21:37:12 +000021#include "llvm/IR/DataLayout.h"
22#include "llvm/IR/Intrinsics.h"
John McCalla8ec7eb2013-03-07 21:37:17 +000023#include "llvm/IR/Operator.h"
John McCallfc207f22013-03-07 21:37:12 +000024
25using namespace clang;
26using namespace CodeGen;
27
John McCalla8ec7eb2013-03-07 21:37:17 +000028namespace {
29 class AtomicInfo {
30 CodeGenFunction &CGF;
31 QualType AtomicTy;
32 QualType ValueTy;
33 uint64_t AtomicSizeInBits;
34 uint64_t ValueSizeInBits;
35 CharUnits AtomicAlign;
36 CharUnits ValueAlign;
37 CharUnits LValueAlign;
38 TypeEvaluationKind EvaluationKind;
39 bool UseLibcall;
Alexey Bataevb57056f2015-01-22 06:17:56 +000040 LValue LVal;
41 CGBitFieldInfo BFI;
John McCalla8ec7eb2013-03-07 21:37:17 +000042 public:
Alexey Bataevb57056f2015-01-22 06:17:56 +000043 AtomicInfo(CodeGenFunction &CGF, LValue &lvalue)
44 : CGF(CGF), AtomicSizeInBits(0), ValueSizeInBits(0),
45 EvaluationKind(TEK_Scalar), UseLibcall(true) {
46 assert(!lvalue.isGlobalReg());
John McCalla8ec7eb2013-03-07 21:37:17 +000047 ASTContext &C = CGF.getContext();
Alexey Bataevb57056f2015-01-22 06:17:56 +000048 if (lvalue.isSimple()) {
49 AtomicTy = lvalue.getType();
50 if (auto *ATy = AtomicTy->getAs<AtomicType>())
51 ValueTy = ATy->getValueType();
52 else
53 ValueTy = AtomicTy;
54 EvaluationKind = CGF.getEvaluationKind(ValueTy);
John McCalla8ec7eb2013-03-07 21:37:17 +000055
Alexey Bataevb57056f2015-01-22 06:17:56 +000056 uint64_t ValueAlignInBits;
57 uint64_t AtomicAlignInBits;
58 TypeInfo ValueTI = C.getTypeInfo(ValueTy);
59 ValueSizeInBits = ValueTI.Width;
60 ValueAlignInBits = ValueTI.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +000061
Alexey Bataevb57056f2015-01-22 06:17:56 +000062 TypeInfo AtomicTI = C.getTypeInfo(AtomicTy);
63 AtomicSizeInBits = AtomicTI.Width;
64 AtomicAlignInBits = AtomicTI.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +000065
Alexey Bataevb57056f2015-01-22 06:17:56 +000066 assert(ValueSizeInBits <= AtomicSizeInBits);
67 assert(ValueAlignInBits <= AtomicAlignInBits);
John McCalla8ec7eb2013-03-07 21:37:17 +000068
Alexey Bataevb57056f2015-01-22 06:17:56 +000069 AtomicAlign = C.toCharUnitsFromBits(AtomicAlignInBits);
70 ValueAlign = C.toCharUnitsFromBits(ValueAlignInBits);
71 if (lvalue.getAlignment().isZero())
72 lvalue.setAlignment(AtomicAlign);
John McCalla8ec7eb2013-03-07 21:37:17 +000073
Alexey Bataevb57056f2015-01-22 06:17:56 +000074 LVal = lvalue;
75 } else if (lvalue.isBitField()) {
Alexey Bataevb8329262015-02-27 06:33:30 +000076 ValueTy = lvalue.getType();
77 ValueSizeInBits = C.getTypeSize(ValueTy);
Alexey Bataevb57056f2015-01-22 06:17:56 +000078 auto &OrigBFI = lvalue.getBitFieldInfo();
79 auto Offset = OrigBFI.Offset % C.toBits(lvalue.getAlignment());
80 AtomicSizeInBits = C.toBits(
81 C.toCharUnitsFromBits(Offset + OrigBFI.Size + C.getCharWidth() - 1)
Rui Ueyama83aa9792016-01-14 21:00:27 +000082 .alignTo(lvalue.getAlignment()));
John McCall7f416cc2015-09-08 08:05:57 +000083 auto VoidPtrAddr = CGF.EmitCastToVoidPtr(lvalue.getBitFieldPointer());
Alexey Bataevb57056f2015-01-22 06:17:56 +000084 auto OffsetInChars =
85 (C.toCharUnitsFromBits(OrigBFI.Offset) / lvalue.getAlignment()) *
86 lvalue.getAlignment();
87 VoidPtrAddr = CGF.Builder.CreateConstGEP1_64(
88 VoidPtrAddr, OffsetInChars.getQuantity());
89 auto Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
90 VoidPtrAddr,
91 CGF.Builder.getIntNTy(AtomicSizeInBits)->getPointerTo(),
92 "atomic_bitfield_base");
93 BFI = OrigBFI;
94 BFI.Offset = Offset;
95 BFI.StorageSize = AtomicSizeInBits;
Ulrich Weigand03ce2a12015-07-10 17:30:00 +000096 BFI.StorageOffset += OffsetInChars;
John McCall7f416cc2015-09-08 08:05:57 +000097 LVal = LValue::MakeBitfield(Address(Addr, lvalue.getAlignment()),
98 BFI, lvalue.getType(),
99 lvalue.getAlignmentSource());
Alexey Bataevb8329262015-02-27 06:33:30 +0000100 LVal.setTBAAInfo(lvalue.getTBAAInfo());
101 AtomicTy = C.getIntTypeForBitwidth(AtomicSizeInBits, OrigBFI.IsSigned);
102 if (AtomicTy.isNull()) {
103 llvm::APInt Size(
104 /*numBits=*/32,
105 C.toCharUnitsFromBits(AtomicSizeInBits).getQuantity());
106 AtomicTy = C.getConstantArrayType(C.CharTy, Size, ArrayType::Normal,
107 /*IndexTypeQuals=*/0);
108 }
109 AtomicAlign = ValueAlign = lvalue.getAlignment();
Alexey Bataevb57056f2015-01-22 06:17:56 +0000110 } else if (lvalue.isVectorElt()) {
Alexey Bataevb8329262015-02-27 06:33:30 +0000111 ValueTy = lvalue.getType()->getAs<VectorType>()->getElementType();
112 ValueSizeInBits = C.getTypeSize(ValueTy);
113 AtomicTy = lvalue.getType();
114 AtomicSizeInBits = C.getTypeSize(AtomicTy);
115 AtomicAlign = ValueAlign = lvalue.getAlignment();
Alexey Bataevb57056f2015-01-22 06:17:56 +0000116 LVal = lvalue;
117 } else {
118 assert(lvalue.isExtVectorElt());
Alexey Bataevb8329262015-02-27 06:33:30 +0000119 ValueTy = lvalue.getType();
120 ValueSizeInBits = C.getTypeSize(ValueTy);
121 AtomicTy = ValueTy = CGF.getContext().getExtVectorType(
John McCall7f416cc2015-09-08 08:05:57 +0000122 lvalue.getType(), lvalue.getExtVectorAddress()
123 .getElementType()->getVectorNumElements());
Alexey Bataevb8329262015-02-27 06:33:30 +0000124 AtomicSizeInBits = C.getTypeSize(AtomicTy);
125 AtomicAlign = ValueAlign = lvalue.getAlignment();
Alexey Bataevb57056f2015-01-22 06:17:56 +0000126 LVal = lvalue;
127 }
Alexey Bataev452d8e12014-12-15 05:25:25 +0000128 UseLibcall = !C.getTargetInfo().hasBuiltinAtomic(
129 AtomicSizeInBits, C.toBits(lvalue.getAlignment()));
John McCalla8ec7eb2013-03-07 21:37:17 +0000130 }
131
132 QualType getAtomicType() const { return AtomicTy; }
133 QualType getValueType() const { return ValueTy; }
134 CharUnits getAtomicAlignment() const { return AtomicAlign; }
135 CharUnits getValueAlignment() const { return ValueAlign; }
136 uint64_t getAtomicSizeInBits() const { return AtomicSizeInBits; }
Alexey Bataev452d8e12014-12-15 05:25:25 +0000137 uint64_t getValueSizeInBits() const { return ValueSizeInBits; }
John McCalla8ec7eb2013-03-07 21:37:17 +0000138 TypeEvaluationKind getEvaluationKind() const { return EvaluationKind; }
139 bool shouldUseLibcall() const { return UseLibcall; }
Alexey Bataevb57056f2015-01-22 06:17:56 +0000140 const LValue &getAtomicLValue() const { return LVal; }
John McCall7f416cc2015-09-08 08:05:57 +0000141 llvm::Value *getAtomicPointer() const {
Alexey Bataevb8329262015-02-27 06:33:30 +0000142 if (LVal.isSimple())
John McCall7f416cc2015-09-08 08:05:57 +0000143 return LVal.getPointer();
Alexey Bataevb8329262015-02-27 06:33:30 +0000144 else if (LVal.isBitField())
John McCall7f416cc2015-09-08 08:05:57 +0000145 return LVal.getBitFieldPointer();
Alexey Bataevb8329262015-02-27 06:33:30 +0000146 else if (LVal.isVectorElt())
John McCall7f416cc2015-09-08 08:05:57 +0000147 return LVal.getVectorPointer();
Alexey Bataevb8329262015-02-27 06:33:30 +0000148 assert(LVal.isExtVectorElt());
John McCall7f416cc2015-09-08 08:05:57 +0000149 return LVal.getExtVectorPointer();
150 }
151 Address getAtomicAddress() const {
152 return Address(getAtomicPointer(), getAtomicAlignment());
153 }
154
155 Address getAtomicAddressAsAtomicIntPointer() const {
156 return emitCastToAtomicIntPointer(getAtomicAddress());
Alexey Bataevb8329262015-02-27 06:33:30 +0000157 }
John McCalla8ec7eb2013-03-07 21:37:17 +0000158
159 /// Is the atomic size larger than the underlying value type?
160 ///
161 /// Note that the absence of padding does not mean that atomic
162 /// objects are completely interchangeable with non-atomic
163 /// objects: we might have promoted the alignment of a type
164 /// without making it bigger.
165 bool hasPadding() const {
166 return (ValueSizeInBits != AtomicSizeInBits);
167 }
168
Alexey Bataevb57056f2015-01-22 06:17:56 +0000169 bool emitMemSetZeroIfNecessary() const;
John McCalla8ec7eb2013-03-07 21:37:17 +0000170
171 llvm::Value *getAtomicSizeValue() const {
172 CharUnits size = CGF.getContext().toCharUnitsFromBits(AtomicSizeInBits);
173 return CGF.CGM.getSize(size);
174 }
175
Tim Northovercc2a6e02015-11-09 19:56:35 +0000176 /// Cast the given pointer to an integer pointer suitable for atomic
177 /// operations if the source.
178 Address emitCastToAtomicIntPointer(Address Addr) const;
179
180 /// If Addr is compatible with the iN that will be used for an atomic
181 /// operation, bitcast it. Otherwise, create a temporary that is suitable
182 /// and copy the value across.
183 Address convertToAtomicIntPointer(Address Addr) const;
John McCalla8ec7eb2013-03-07 21:37:17 +0000184
185 /// Turn an atomic-layout object into an r-value.
John McCall7f416cc2015-09-08 08:05:57 +0000186 RValue convertAtomicTempToRValue(Address addr, AggValueSlot resultSlot,
187 SourceLocation loc, bool AsValue) const;
John McCalla8ec7eb2013-03-07 21:37:17 +0000188
Alexey Bataev452d8e12014-12-15 05:25:25 +0000189 /// \brief Converts a rvalue to integer value.
190 llvm::Value *convertRValueToInt(RValue RVal) const;
191
Alexey Bataevb8329262015-02-27 06:33:30 +0000192 RValue ConvertIntToValueOrAtomic(llvm::Value *IntVal,
193 AggValueSlot ResultSlot,
194 SourceLocation Loc, bool AsValue) const;
Alexey Bataev452d8e12014-12-15 05:25:25 +0000195
John McCalla8ec7eb2013-03-07 21:37:17 +0000196 /// Copy an atomic r-value into atomic-layout memory.
Alexey Bataevb57056f2015-01-22 06:17:56 +0000197 void emitCopyIntoMemory(RValue rvalue) const;
John McCalla8ec7eb2013-03-07 21:37:17 +0000198
199 /// Project an l-value down to the value field.
Alexey Bataevb57056f2015-01-22 06:17:56 +0000200 LValue projectValue() const {
201 assert(LVal.isSimple());
John McCall7f416cc2015-09-08 08:05:57 +0000202 Address addr = getAtomicAddress();
John McCalla8ec7eb2013-03-07 21:37:17 +0000203 if (hasPadding())
John McCall7f416cc2015-09-08 08:05:57 +0000204 addr = CGF.Builder.CreateStructGEP(addr, 0, CharUnits());
John McCalla8ec7eb2013-03-07 21:37:17 +0000205
John McCall7f416cc2015-09-08 08:05:57 +0000206 return LValue::MakeAddr(addr, getValueType(), CGF.getContext(),
207 LVal.getAlignmentSource(), LVal.getTBAAInfo());
John McCalla8ec7eb2013-03-07 21:37:17 +0000208 }
209
Alexey Bataevb8329262015-02-27 06:33:30 +0000210 /// \brief Emits atomic load.
211 /// \returns Loaded value.
212 RValue EmitAtomicLoad(AggValueSlot ResultSlot, SourceLocation Loc,
213 bool AsValue, llvm::AtomicOrdering AO,
214 bool IsVolatile);
215
216 /// \brief Emits atomic compare-and-exchange sequence.
217 /// \param Expected Expected value.
218 /// \param Desired Desired value.
219 /// \param Success Atomic ordering for success operation.
220 /// \param Failure Atomic ordering for failed operation.
221 /// \param IsWeak true if atomic operation is weak, false otherwise.
222 /// \returns Pair of values: previous value from storage (value type) and
223 /// boolean flag (i1 type) with true if success and false otherwise.
Alexey Bataevb4505a72015-03-30 05:20:59 +0000224 std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange(
Alexey Bataevb8329262015-02-27 06:33:30 +0000225 RValue Expected, RValue Desired,
226 llvm::AtomicOrdering Success = llvm::SequentiallyConsistent,
227 llvm::AtomicOrdering Failure = llvm::SequentiallyConsistent,
228 bool IsWeak = false);
229
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000230 /// \brief Emits atomic update.
NAKAMURA Takumid16af5d2015-05-15 13:47:52 +0000231 /// \param AO Atomic ordering.
232 /// \param UpdateOp Update operation for the current lvalue.
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000233 void EmitAtomicUpdate(llvm::AtomicOrdering AO,
234 const llvm::function_ref<RValue(RValue)> &UpdateOp,
235 bool IsVolatile);
236 /// \brief Emits atomic update.
NAKAMURA Takumid16af5d2015-05-15 13:47:52 +0000237 /// \param AO Atomic ordering.
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000238 void EmitAtomicUpdate(llvm::AtomicOrdering AO, RValue UpdateRVal,
239 bool IsVolatile);
240
John McCalla8ec7eb2013-03-07 21:37:17 +0000241 /// Materialize an atomic r-value in atomic-layout memory.
John McCall7f416cc2015-09-08 08:05:57 +0000242 Address materializeRValue(RValue rvalue) const;
John McCalla8ec7eb2013-03-07 21:37:17 +0000243
Alexey Bataevb8329262015-02-27 06:33:30 +0000244 /// \brief Translates LLVM atomic ordering to GNU atomic ordering for
245 /// libcalls.
246 static AtomicExpr::AtomicOrderingKind
247 translateAtomicOrdering(const llvm::AtomicOrdering AO);
248
Tim Northovercc2a6e02015-11-09 19:56:35 +0000249 /// \brief Creates temp alloca for intermediate operations on atomic value.
250 Address CreateTempAlloca() const;
John McCalla8ec7eb2013-03-07 21:37:17 +0000251 private:
252 bool requiresMemSetZero(llvm::Type *type) const;
Alexey Bataevb8329262015-02-27 06:33:30 +0000253
Alexey Bataevb8329262015-02-27 06:33:30 +0000254
255 /// \brief Emits atomic load as a libcall.
256 void EmitAtomicLoadLibcall(llvm::Value *AddForLoaded,
257 llvm::AtomicOrdering AO, bool IsVolatile);
258 /// \brief Emits atomic load as LLVM instruction.
259 llvm::Value *EmitAtomicLoadOp(llvm::AtomicOrdering AO, bool IsVolatile);
260 /// \brief Emits atomic compare-and-exchange op as a libcall.
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000261 llvm::Value *EmitAtomicCompareExchangeLibcall(
262 llvm::Value *ExpectedAddr, llvm::Value *DesiredAddr,
Alexey Bataevb8329262015-02-27 06:33:30 +0000263 llvm::AtomicOrdering Success = llvm::SequentiallyConsistent,
264 llvm::AtomicOrdering Failure = llvm::SequentiallyConsistent);
265 /// \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,
Alexey Bataevb8329262015-02-27 06:33:30 +0000268 llvm::AtomicOrdering Success = llvm::SequentiallyConsistent,
269 llvm::AtomicOrdering Failure = llvm::SequentiallyConsistent,
270 bool IsWeak = false);
Alexey Bataevf0ab5532015-05-15 08:36:34 +0000271 /// \brief Emit atomic update as libcalls.
272 void
273 EmitAtomicUpdateLibcall(llvm::AtomicOrdering AO,
274 const llvm::function_ref<RValue(RValue)> &UpdateOp,
275 bool IsVolatile);
276 /// \brief Emit atomic update as LLVM instructions.
277 void EmitAtomicUpdateOp(llvm::AtomicOrdering AO,
278 const llvm::function_ref<RValue(RValue)> &UpdateOp,
279 bool IsVolatile);
280 /// \brief Emit atomic update as libcalls.
281 void EmitAtomicUpdateLibcall(llvm::AtomicOrdering AO, RValue UpdateRVal,
282 bool IsVolatile);
283 /// \brief Emit atomic update as LLVM instructions.
284 void EmitAtomicUpdateOp(llvm::AtomicOrdering AO, RValue UpdateRal,
285 bool IsVolatile);
John McCalla8ec7eb2013-03-07 21:37:17 +0000286 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000287}
John McCalla8ec7eb2013-03-07 21:37:17 +0000288
Alexey Bataevb8329262015-02-27 06:33:30 +0000289AtomicExpr::AtomicOrderingKind
290AtomicInfo::translateAtomicOrdering(const llvm::AtomicOrdering AO) {
291 switch (AO) {
292 case llvm::Unordered:
293 case llvm::NotAtomic:
294 case llvm::Monotonic:
295 return AtomicExpr::AO_ABI_memory_order_relaxed;
296 case llvm::Acquire:
297 return AtomicExpr::AO_ABI_memory_order_acquire;
298 case llvm::Release:
299 return AtomicExpr::AO_ABI_memory_order_release;
300 case llvm::AcquireRelease:
301 return AtomicExpr::AO_ABI_memory_order_acq_rel;
302 case llvm::SequentiallyConsistent:
303 return AtomicExpr::AO_ABI_memory_order_seq_cst;
304 }
Aaron Ballman152ad172015-02-27 13:55:58 +0000305 llvm_unreachable("Unhandled AtomicOrdering");
Alexey Bataevb8329262015-02-27 06:33:30 +0000306}
307
John McCall7f416cc2015-09-08 08:05:57 +0000308Address AtomicInfo::CreateTempAlloca() const {
309 Address TempAlloca = CGF.CreateMemTemp(
Alexey Bataevb8329262015-02-27 06:33:30 +0000310 (LVal.isBitField() && ValueSizeInBits > AtomicSizeInBits) ? ValueTy
311 : AtomicTy,
John McCall7f416cc2015-09-08 08:05:57 +0000312 getAtomicAlignment(),
Alexey Bataevb8329262015-02-27 06:33:30 +0000313 "atomic-temp");
Alexey Bataevb8329262015-02-27 06:33:30 +0000314 // Cast to pointer to value type for bitfields.
315 if (LVal.isBitField())
316 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +0000317 TempAlloca, getAtomicAddress().getType());
Alexey Bataevb8329262015-02-27 06:33:30 +0000318 return TempAlloca;
319}
320
John McCalla8ec7eb2013-03-07 21:37:17 +0000321static RValue emitAtomicLibcall(CodeGenFunction &CGF,
322 StringRef fnName,
323 QualType resultType,
324 CallArgList &args) {
325 const CGFunctionInfo &fnInfo =
326 CGF.CGM.getTypes().arrangeFreeFunctionCall(resultType, args,
327 FunctionType::ExtInfo(), RequiredArgs::All);
328 llvm::FunctionType *fnTy = CGF.CGM.getTypes().GetFunctionType(fnInfo);
329 llvm::Constant *fn = CGF.CGM.CreateRuntimeFunction(fnTy, fnName);
330 return CGF.EmitCall(fnInfo, fn, ReturnValueSlot(), args);
331}
332
333/// Does a store of the given IR type modify the full expected width?
334static bool isFullSizeType(CodeGenModule &CGM, llvm::Type *type,
335 uint64_t expectedSize) {
336 return (CGM.getDataLayout().getTypeStoreSize(type) * 8 == expectedSize);
337}
338
339/// Does the atomic type require memsetting to zero before initialization?
340///
341/// The IR type is provided as a way of making certain queries faster.
342bool AtomicInfo::requiresMemSetZero(llvm::Type *type) const {
343 // If the atomic type has size padding, we definitely need a memset.
344 if (hasPadding()) return true;
345
346 // Otherwise, do some simple heuristics to try to avoid it:
347 switch (getEvaluationKind()) {
348 // For scalars and complexes, check whether the store size of the
349 // type uses the full size.
350 case TEK_Scalar:
351 return !isFullSizeType(CGF.CGM, type, AtomicSizeInBits);
352 case TEK_Complex:
353 return !isFullSizeType(CGF.CGM, type->getStructElementType(0),
354 AtomicSizeInBits / 2);
355
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000356 // Padding in structs has an undefined bit pattern. User beware.
John McCalla8ec7eb2013-03-07 21:37:17 +0000357 case TEK_Aggregate:
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000358 return false;
John McCalla8ec7eb2013-03-07 21:37:17 +0000359 }
360 llvm_unreachable("bad evaluation kind");
361}
362
Alexey Bataevb57056f2015-01-22 06:17:56 +0000363bool AtomicInfo::emitMemSetZeroIfNecessary() const {
364 assert(LVal.isSimple());
John McCall7f416cc2015-09-08 08:05:57 +0000365 llvm::Value *addr = LVal.getPointer();
John McCalla8ec7eb2013-03-07 21:37:17 +0000366 if (!requiresMemSetZero(addr->getType()->getPointerElementType()))
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000367 return false;
John McCalla8ec7eb2013-03-07 21:37:17 +0000368
Alexey Bataevb8329262015-02-27 06:33:30 +0000369 CGF.Builder.CreateMemSet(
370 addr, llvm::ConstantInt::get(CGF.Int8Ty, 0),
371 CGF.getContext().toCharUnitsFromBits(AtomicSizeInBits).getQuantity(),
372 LVal.getAlignment().getQuantity());
Eli Friedmanbe4504d2013-07-11 01:32:21 +0000373 return true;
John McCalla8ec7eb2013-03-07 21:37:17 +0000374}
375
Tim Northovercadbbe12014-06-13 19:43:04 +0000376static void emitAtomicCmpXchg(CodeGenFunction &CGF, AtomicExpr *E, bool IsWeak,
John McCall7f416cc2015-09-08 08:05:57 +0000377 Address Dest, Address Ptr,
378 Address Val1, Address Val2,
379 uint64_t Size,
Tim Northover9c177222014-03-13 19:25:48 +0000380 llvm::AtomicOrdering SuccessOrder,
381 llvm::AtomicOrdering FailureOrder) {
382 // Note that cmpxchg doesn't support weak cmpxchg, at least at the moment.
John McCall7f416cc2015-09-08 08:05:57 +0000383 llvm::Value *Expected = CGF.Builder.CreateLoad(Val1);
384 llvm::Value *Desired = CGF.Builder.CreateLoad(Val2);
Tim Northover9c177222014-03-13 19:25:48 +0000385
Tim Northoverb49b04b2014-06-13 14:24:59 +0000386 llvm::AtomicCmpXchgInst *Pair = CGF.Builder.CreateAtomicCmpXchg(
John McCall7f416cc2015-09-08 08:05:57 +0000387 Ptr.getPointer(), Expected, Desired, SuccessOrder, FailureOrder);
Tim Northoverb49b04b2014-06-13 14:24:59 +0000388 Pair->setVolatile(E->isVolatile());
Tim Northovercadbbe12014-06-13 19:43:04 +0000389 Pair->setWeak(IsWeak);
Tim Northover9c177222014-03-13 19:25:48 +0000390
391 // Cmp holds the result of the compare-exchange operation: true on success,
392 // false on failure.
Tim Northoverb49b04b2014-06-13 14:24:59 +0000393 llvm::Value *Old = CGF.Builder.CreateExtractValue(Pair, 0);
394 llvm::Value *Cmp = CGF.Builder.CreateExtractValue(Pair, 1);
Tim Northover9c177222014-03-13 19:25:48 +0000395
396 // This basic block is used to hold the store instruction if the operation
397 // failed.
398 llvm::BasicBlock *StoreExpectedBB =
399 CGF.createBasicBlock("cmpxchg.store_expected", CGF.CurFn);
400
401 // This basic block is the exit point of the operation, we should end up
402 // here regardless of whether or not the operation succeeded.
403 llvm::BasicBlock *ContinueBB =
404 CGF.createBasicBlock("cmpxchg.continue", CGF.CurFn);
405
406 // Update Expected if Expected isn't equal to Old, otherwise branch to the
407 // exit point.
408 CGF.Builder.CreateCondBr(Cmp, ContinueBB, StoreExpectedBB);
409
410 CGF.Builder.SetInsertPoint(StoreExpectedBB);
411 // Update the memory at Expected with Old's value.
John McCall7f416cc2015-09-08 08:05:57 +0000412 CGF.Builder.CreateStore(Old, Val1);
Tim Northover9c177222014-03-13 19:25:48 +0000413 // Finally, branch to the exit point.
414 CGF.Builder.CreateBr(ContinueBB);
415
416 CGF.Builder.SetInsertPoint(ContinueBB);
417 // Update the memory at Dest with Cmp's value.
418 CGF.EmitStoreOfScalar(Cmp, CGF.MakeAddrLValue(Dest, E->getType()));
Tim Northover9c177222014-03-13 19:25:48 +0000419}
420
421/// Given an ordering required on success, emit all possible cmpxchg
422/// instructions to cope with the provided (but possibly only dynamically known)
423/// FailureOrder.
424static void emitAtomicCmpXchgFailureSet(CodeGenFunction &CGF, AtomicExpr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000425 bool IsWeak, Address Dest,
426 Address Ptr, Address Val1,
427 Address Val2,
Tim Northover9c177222014-03-13 19:25:48 +0000428 llvm::Value *FailureOrderVal,
John McCall7f416cc2015-09-08 08:05:57 +0000429 uint64_t Size,
Tim Northover9c177222014-03-13 19:25:48 +0000430 llvm::AtomicOrdering SuccessOrder) {
431 llvm::AtomicOrdering FailureOrder;
432 if (llvm::ConstantInt *FO = dyn_cast<llvm::ConstantInt>(FailureOrderVal)) {
433 switch (FO->getSExtValue()) {
434 default:
435 FailureOrder = llvm::Monotonic;
436 break;
437 case AtomicExpr::AO_ABI_memory_order_consume:
438 case AtomicExpr::AO_ABI_memory_order_acquire:
439 FailureOrder = llvm::Acquire;
440 break;
441 case AtomicExpr::AO_ABI_memory_order_seq_cst:
442 FailureOrder = llvm::SequentiallyConsistent;
443 break;
444 }
445 if (FailureOrder >= SuccessOrder) {
446 // Don't assert on undefined behaviour.
447 FailureOrder =
448 llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrder);
449 }
John McCall7f416cc2015-09-08 08:05:57 +0000450 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, Size,
Tim Northovercadbbe12014-06-13 19:43:04 +0000451 SuccessOrder, FailureOrder);
Tim Northover9c177222014-03-13 19:25:48 +0000452 return;
453 }
454
455 // Create all the relevant BB's
Craig Topper8a13c412014-05-21 05:09:00 +0000456 llvm::BasicBlock *MonotonicBB = nullptr, *AcquireBB = nullptr,
457 *SeqCstBB = nullptr;
Tim Northover9c177222014-03-13 19:25:48 +0000458 MonotonicBB = CGF.createBasicBlock("monotonic_fail", CGF.CurFn);
459 if (SuccessOrder != llvm::Monotonic && SuccessOrder != llvm::Release)
460 AcquireBB = CGF.createBasicBlock("acquire_fail", CGF.CurFn);
461 if (SuccessOrder == llvm::SequentiallyConsistent)
462 SeqCstBB = CGF.createBasicBlock("seqcst_fail", CGF.CurFn);
463
464 llvm::BasicBlock *ContBB = CGF.createBasicBlock("atomic.continue", CGF.CurFn);
465
466 llvm::SwitchInst *SI = CGF.Builder.CreateSwitch(FailureOrderVal, MonotonicBB);
467
468 // Emit all the different atomics
469
470 // MonotonicBB is arbitrarily chosen as the default case; in practice, this
471 // doesn't matter unless someone is crazy enough to use something that
472 // doesn't fold to a constant for the ordering.
473 CGF.Builder.SetInsertPoint(MonotonicBB);
Tim Northovercadbbe12014-06-13 19:43:04 +0000474 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2,
John McCall7f416cc2015-09-08 08:05:57 +0000475 Size, SuccessOrder, llvm::Monotonic);
Tim Northover9c177222014-03-13 19:25:48 +0000476 CGF.Builder.CreateBr(ContBB);
477
478 if (AcquireBB) {
479 CGF.Builder.SetInsertPoint(AcquireBB);
Tim Northovercadbbe12014-06-13 19:43:04 +0000480 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2,
John McCall7f416cc2015-09-08 08:05:57 +0000481 Size, SuccessOrder, llvm::Acquire);
Tim Northover9c177222014-03-13 19:25:48 +0000482 CGF.Builder.CreateBr(ContBB);
483 SI->addCase(CGF.Builder.getInt32(AtomicExpr::AO_ABI_memory_order_consume),
484 AcquireBB);
485 SI->addCase(CGF.Builder.getInt32(AtomicExpr::AO_ABI_memory_order_acquire),
486 AcquireBB);
487 }
488 if (SeqCstBB) {
489 CGF.Builder.SetInsertPoint(SeqCstBB);
Tim Northovercadbbe12014-06-13 19:43:04 +0000490 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2,
John McCall7f416cc2015-09-08 08:05:57 +0000491 Size, SuccessOrder, llvm::SequentiallyConsistent);
Tim Northover9c177222014-03-13 19:25:48 +0000492 CGF.Builder.CreateBr(ContBB);
493 SI->addCase(CGF.Builder.getInt32(AtomicExpr::AO_ABI_memory_order_seq_cst),
494 SeqCstBB);
495 }
496
497 CGF.Builder.SetInsertPoint(ContBB);
498}
499
John McCall7f416cc2015-09-08 08:05:57 +0000500static void EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *E, Address Dest,
501 Address Ptr, Address Val1, Address Val2,
Tim Northovercadbbe12014-06-13 19:43:04 +0000502 llvm::Value *IsWeak, llvm::Value *FailureOrder,
John McCall7f416cc2015-09-08 08:05:57 +0000503 uint64_t Size, llvm::AtomicOrdering Order) {
John McCallfc207f22013-03-07 21:37:12 +0000504 llvm::AtomicRMWInst::BinOp Op = llvm::AtomicRMWInst::Add;
505 llvm::Instruction::BinaryOps PostOp = (llvm::Instruction::BinaryOps)0;
506
507 switch (E->getOp()) {
508 case AtomicExpr::AO__c11_atomic_init:
509 llvm_unreachable("Already handled!");
510
511 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
Tim Northovercadbbe12014-06-13 19:43:04 +0000512 emitAtomicCmpXchgFailureSet(CGF, E, false, Dest, Ptr, Val1, Val2,
John McCall7f416cc2015-09-08 08:05:57 +0000513 FailureOrder, Size, Order);
John McCallfc207f22013-03-07 21:37:12 +0000514 return;
Tim Northovercadbbe12014-06-13 19:43:04 +0000515 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
516 emitAtomicCmpXchgFailureSet(CGF, E, true, Dest, Ptr, Val1, Val2,
John McCall7f416cc2015-09-08 08:05:57 +0000517 FailureOrder, Size, Order);
Tim Northovercadbbe12014-06-13 19:43:04 +0000518 return;
519 case AtomicExpr::AO__atomic_compare_exchange:
520 case AtomicExpr::AO__atomic_compare_exchange_n: {
521 if (llvm::ConstantInt *IsWeakC = dyn_cast<llvm::ConstantInt>(IsWeak)) {
522 emitAtomicCmpXchgFailureSet(CGF, E, IsWeakC->getZExtValue(), Dest, Ptr,
John McCall7f416cc2015-09-08 08:05:57 +0000523 Val1, Val2, FailureOrder, Size, Order);
Tim Northovercadbbe12014-06-13 19:43:04 +0000524 } else {
525 // Create all the relevant BB's
526 llvm::BasicBlock *StrongBB =
527 CGF.createBasicBlock("cmpxchg.strong", CGF.CurFn);
528 llvm::BasicBlock *WeakBB = CGF.createBasicBlock("cmxchg.weak", CGF.CurFn);
529 llvm::BasicBlock *ContBB =
530 CGF.createBasicBlock("cmpxchg.continue", CGF.CurFn);
531
532 llvm::SwitchInst *SI = CGF.Builder.CreateSwitch(IsWeak, WeakBB);
533 SI->addCase(CGF.Builder.getInt1(false), StrongBB);
534
535 CGF.Builder.SetInsertPoint(StrongBB);
536 emitAtomicCmpXchgFailureSet(CGF, E, false, Dest, Ptr, Val1, Val2,
John McCall7f416cc2015-09-08 08:05:57 +0000537 FailureOrder, Size, Order);
Tim Northovercadbbe12014-06-13 19:43:04 +0000538 CGF.Builder.CreateBr(ContBB);
539
540 CGF.Builder.SetInsertPoint(WeakBB);
541 emitAtomicCmpXchgFailureSet(CGF, E, true, Dest, Ptr, Val1, Val2,
John McCall7f416cc2015-09-08 08:05:57 +0000542 FailureOrder, Size, Order);
Tim Northovercadbbe12014-06-13 19:43:04 +0000543 CGF.Builder.CreateBr(ContBB);
544
545 CGF.Builder.SetInsertPoint(ContBB);
546 }
547 return;
548 }
John McCallfc207f22013-03-07 21:37:12 +0000549 case AtomicExpr::AO__c11_atomic_load:
550 case AtomicExpr::AO__atomic_load_n:
551 case AtomicExpr::AO__atomic_load: {
552 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Ptr);
553 Load->setAtomic(Order);
John McCallfc207f22013-03-07 21:37:12 +0000554 Load->setVolatile(E->isVolatile());
John McCall7f416cc2015-09-08 08:05:57 +0000555 CGF.Builder.CreateStore(Load, Dest);
John McCallfc207f22013-03-07 21:37:12 +0000556 return;
557 }
558
559 case AtomicExpr::AO__c11_atomic_store:
560 case AtomicExpr::AO__atomic_store:
561 case AtomicExpr::AO__atomic_store_n: {
John McCall7f416cc2015-09-08 08:05:57 +0000562 llvm::Value *LoadVal1 = CGF.Builder.CreateLoad(Val1);
John McCallfc207f22013-03-07 21:37:12 +0000563 llvm::StoreInst *Store = CGF.Builder.CreateStore(LoadVal1, Ptr);
564 Store->setAtomic(Order);
John McCallfc207f22013-03-07 21:37:12 +0000565 Store->setVolatile(E->isVolatile());
566 return;
567 }
568
569 case AtomicExpr::AO__c11_atomic_exchange:
570 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:
579 case AtomicExpr::AO__atomic_fetch_add:
580 Op = llvm::AtomicRMWInst::Add;
581 break;
582
583 case AtomicExpr::AO__atomic_sub_fetch:
584 PostOp = llvm::Instruction::Sub;
585 // Fall through.
586 case AtomicExpr::AO__c11_atomic_fetch_sub:
587 case AtomicExpr::AO__atomic_fetch_sub:
588 Op = llvm::AtomicRMWInst::Sub;
589 break;
590
591 case AtomicExpr::AO__atomic_and_fetch:
592 PostOp = llvm::Instruction::And;
593 // Fall through.
594 case AtomicExpr::AO__c11_atomic_fetch_and:
595 case AtomicExpr::AO__atomic_fetch_and:
596 Op = llvm::AtomicRMWInst::And;
597 break;
598
599 case AtomicExpr::AO__atomic_or_fetch:
600 PostOp = llvm::Instruction::Or;
601 // Fall through.
602 case AtomicExpr::AO__c11_atomic_fetch_or:
603 case AtomicExpr::AO__atomic_fetch_or:
604 Op = llvm::AtomicRMWInst::Or;
605 break;
606
607 case AtomicExpr::AO__atomic_xor_fetch:
608 PostOp = llvm::Instruction::Xor;
609 // Fall through.
610 case AtomicExpr::AO__c11_atomic_fetch_xor:
611 case AtomicExpr::AO__atomic_fetch_xor:
612 Op = llvm::AtomicRMWInst::Xor;
613 break;
614
615 case AtomicExpr::AO__atomic_nand_fetch:
James Y Knight7aefb5b2015-11-12 18:37:29 +0000616 PostOp = llvm::Instruction::And; // the NOT is special cased below
617 // Fall through.
John McCallfc207f22013-03-07 21:37:12 +0000618 case AtomicExpr::AO__atomic_fetch_nand:
619 Op = llvm::AtomicRMWInst::Nand;
620 break;
621 }
622
John McCall7f416cc2015-09-08 08:05:57 +0000623 llvm::Value *LoadVal1 = CGF.Builder.CreateLoad(Val1);
John McCallfc207f22013-03-07 21:37:12 +0000624 llvm::AtomicRMWInst *RMWI =
John McCall7f416cc2015-09-08 08:05:57 +0000625 CGF.Builder.CreateAtomicRMW(Op, Ptr.getPointer(), LoadVal1, Order);
John McCallfc207f22013-03-07 21:37:12 +0000626 RMWI->setVolatile(E->isVolatile());
627
628 // For __atomic_*_fetch operations, perform the operation again to
629 // determine the value which was written.
630 llvm::Value *Result = RMWI;
631 if (PostOp)
632 Result = CGF.Builder.CreateBinOp(PostOp, RMWI, LoadVal1);
633 if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch)
634 Result = CGF.Builder.CreateNot(Result);
John McCall7f416cc2015-09-08 08:05:57 +0000635 CGF.Builder.CreateStore(Result, Dest);
John McCallfc207f22013-03-07 21:37:12 +0000636}
637
638// This function emits any expression (scalar, complex, or aggregate)
639// into a temporary alloca.
John McCall7f416cc2015-09-08 08:05:57 +0000640static Address
John McCallfc207f22013-03-07 21:37:12 +0000641EmitValToTemp(CodeGenFunction &CGF, Expr *E) {
John McCall7f416cc2015-09-08 08:05:57 +0000642 Address DeclPtr = CGF.CreateMemTemp(E->getType(), ".atomictmp");
John McCallfc207f22013-03-07 21:37:12 +0000643 CGF.EmitAnyExprToMem(E, DeclPtr, E->getType().getQualifiers(),
644 /*Init*/ true);
645 return DeclPtr;
646}
647
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000648static void
649AddDirectArgument(CodeGenFunction &CGF, CallArgList &Args,
Nick Lewycky2d84e842013-10-02 02:29:49 +0000650 bool UseOptimizedLibcall, llvm::Value *Val, QualType ValTy,
David Majnemer0392cf82014-08-29 07:27:49 +0000651 SourceLocation Loc, CharUnits SizeInChars) {
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000652 if (UseOptimizedLibcall) {
653 // Load value and pass it to the function directly.
John McCall7f416cc2015-09-08 08:05:57 +0000654 CharUnits Align = CGF.getContext().getTypeAlignInChars(ValTy);
David Majnemer0392cf82014-08-29 07:27:49 +0000655 int64_t SizeInBits = CGF.getContext().toBits(SizeInChars);
656 ValTy =
657 CGF.getContext().getIntTypeForBitwidth(SizeInBits, /*Signed=*/false);
658 llvm::Type *IPtrTy = llvm::IntegerType::get(CGF.getLLVMContext(),
659 SizeInBits)->getPointerTo();
John McCall7f416cc2015-09-08 08:05:57 +0000660 Address Ptr = Address(CGF.Builder.CreateBitCast(Val, IPtrTy), Align);
661 Val = CGF.EmitLoadOfScalar(Ptr, false,
662 CGF.getContext().getPointerType(ValTy),
David Majnemer0392cf82014-08-29 07:27:49 +0000663 Loc);
664 // Coerce the value into an appropriately sized integer type.
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000665 Args.add(RValue::get(Val), ValTy);
666 } else {
667 // Non-optimized functions always take a reference.
668 Args.add(RValue::get(CGF.EmitCastToVoidPtr(Val)),
669 CGF.getContext().VoidPtrTy);
670 }
671}
672
Tim Northovercc2a6e02015-11-09 19:56:35 +0000673RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E) {
John McCallfc207f22013-03-07 21:37:12 +0000674 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
675 QualType MemTy = AtomicTy;
676 if (const AtomicType *AT = AtomicTy->getAs<AtomicType>())
677 MemTy = AT->getValueType();
John McCall7f416cc2015-09-08 08:05:57 +0000678 CharUnits sizeChars, alignChars;
679 std::tie(sizeChars, alignChars) = getContext().getTypeInfoInChars(AtomicTy);
John McCallfc207f22013-03-07 21:37:12 +0000680 uint64_t Size = sizeChars.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +0000681 unsigned MaxInlineWidthInBits = getTarget().getMaxAtomicInlineWidth();
682 bool UseLibcall = (sizeChars != alignChars ||
John McCallfc207f22013-03-07 21:37:12 +0000683 getContext().toBits(sizeChars) > MaxInlineWidthInBits);
684
John McCall7f416cc2015-09-08 08:05:57 +0000685 llvm::Value *IsWeak = nullptr, *OrderFail = nullptr;
686
687 Address Val1 = Address::invalid();
688 Address Val2 = Address::invalid();
Tim Northovercc2a6e02015-11-09 19:56:35 +0000689 Address Dest = Address::invalid();
John McCall7f416cc2015-09-08 08:05:57 +0000690 Address Ptr(EmitScalarExpr(E->getPtr()), alignChars);
John McCallfc207f22013-03-07 21:37:12 +0000691
692 if (E->getOp() == AtomicExpr::AO__c11_atomic_init) {
John McCall7f416cc2015-09-08 08:05:57 +0000693 LValue lvalue = MakeAddrLValue(Ptr, AtomicTy);
John McCalla8ec7eb2013-03-07 21:37:17 +0000694 EmitAtomicInit(E->getVal1(), lvalue);
Craig Topper8a13c412014-05-21 05:09:00 +0000695 return RValue::get(nullptr);
John McCallfc207f22013-03-07 21:37:12 +0000696 }
697
Craig Topper8a13c412014-05-21 05:09:00 +0000698 llvm::Value *Order = EmitScalarExpr(E->getOrder());
John McCallfc207f22013-03-07 21:37:12 +0000699
700 switch (E->getOp()) {
701 case AtomicExpr::AO__c11_atomic_init:
James Y Knight81167fb2015-08-05 16:57:36 +0000702 llvm_unreachable("Already handled above with EmitAtomicInit!");
John McCallfc207f22013-03-07 21:37:12 +0000703
704 case AtomicExpr::AO__c11_atomic_load:
705 case AtomicExpr::AO__atomic_load_n:
706 break;
707
708 case AtomicExpr::AO__atomic_load:
John McCall7f416cc2015-09-08 08:05:57 +0000709 Dest = EmitPointerWithAlignment(E->getVal1());
John McCallfc207f22013-03-07 21:37:12 +0000710 break;
711
712 case AtomicExpr::AO__atomic_store:
John McCall7f416cc2015-09-08 08:05:57 +0000713 Val1 = EmitPointerWithAlignment(E->getVal1());
John McCallfc207f22013-03-07 21:37:12 +0000714 break;
715
716 case AtomicExpr::AO__atomic_exchange:
John McCall7f416cc2015-09-08 08:05:57 +0000717 Val1 = EmitPointerWithAlignment(E->getVal1());
718 Dest = EmitPointerWithAlignment(E->getVal2());
John McCallfc207f22013-03-07 21:37:12 +0000719 break;
720
721 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
722 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
723 case AtomicExpr::AO__atomic_compare_exchange_n:
724 case AtomicExpr::AO__atomic_compare_exchange:
John McCall7f416cc2015-09-08 08:05:57 +0000725 Val1 = EmitPointerWithAlignment(E->getVal1());
John McCallfc207f22013-03-07 21:37:12 +0000726 if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange)
John McCall7f416cc2015-09-08 08:05:57 +0000727 Val2 = EmitPointerWithAlignment(E->getVal2());
John McCallfc207f22013-03-07 21:37:12 +0000728 else
729 Val2 = EmitValToTemp(*this, E->getVal2());
730 OrderFail = EmitScalarExpr(E->getOrderFail());
John McCallfc207f22013-03-07 21:37:12 +0000731 if (E->getNumSubExprs() == 6)
Tim Northovercadbbe12014-06-13 19:43:04 +0000732 IsWeak = EmitScalarExpr(E->getWeak());
John McCallfc207f22013-03-07 21:37:12 +0000733 break;
734
735 case AtomicExpr::AO__c11_atomic_fetch_add:
736 case AtomicExpr::AO__c11_atomic_fetch_sub:
737 if (MemTy->isPointerType()) {
738 // For pointer arithmetic, we're required to do a bit of math:
739 // adding 1 to an int* is not the same as adding 1 to a uintptr_t.
740 // ... but only for the C11 builtins. The GNU builtins expect the
741 // user to multiply by sizeof(T).
742 QualType Val1Ty = E->getVal1()->getType();
743 llvm::Value *Val1Scalar = EmitScalarExpr(E->getVal1());
744 CharUnits PointeeIncAmt =
745 getContext().getTypeSizeInChars(MemTy->getPointeeType());
746 Val1Scalar = Builder.CreateMul(Val1Scalar, CGM.getSize(PointeeIncAmt));
John McCall7f416cc2015-09-08 08:05:57 +0000747 auto Temp = CreateMemTemp(Val1Ty, ".atomictmp");
748 Val1 = Temp;
749 EmitStoreOfScalar(Val1Scalar, MakeAddrLValue(Temp, Val1Ty));
John McCallfc207f22013-03-07 21:37:12 +0000750 break;
751 }
752 // Fall through.
753 case AtomicExpr::AO__atomic_fetch_add:
754 case AtomicExpr::AO__atomic_fetch_sub:
755 case AtomicExpr::AO__atomic_add_fetch:
756 case AtomicExpr::AO__atomic_sub_fetch:
757 case AtomicExpr::AO__c11_atomic_store:
758 case AtomicExpr::AO__c11_atomic_exchange:
759 case AtomicExpr::AO__atomic_store_n:
760 case AtomicExpr::AO__atomic_exchange_n:
761 case AtomicExpr::AO__c11_atomic_fetch_and:
762 case AtomicExpr::AO__c11_atomic_fetch_or:
763 case AtomicExpr::AO__c11_atomic_fetch_xor:
764 case AtomicExpr::AO__atomic_fetch_and:
765 case AtomicExpr::AO__atomic_fetch_or:
766 case AtomicExpr::AO__atomic_fetch_xor:
767 case AtomicExpr::AO__atomic_fetch_nand:
768 case AtomicExpr::AO__atomic_and_fetch:
769 case AtomicExpr::AO__atomic_or_fetch:
770 case AtomicExpr::AO__atomic_xor_fetch:
771 case AtomicExpr::AO__atomic_nand_fetch:
772 Val1 = EmitValToTemp(*this, E->getVal1());
773 break;
774 }
775
David Majnemeree8d04d2014-12-12 08:16:09 +0000776 QualType RValTy = E->getType().getUnqualifiedType();
777
Tim Northovercc2a6e02015-11-09 19:56:35 +0000778 // The inlined atomics only function on iN types, where N is a power of 2. We
779 // need to make sure (via temporaries if necessary) that all incoming values
780 // are compatible.
781 LValue AtomicVal = MakeAddrLValue(Ptr, AtomicTy);
782 AtomicInfo Atomics(*this, AtomicVal);
783
784 Ptr = Atomics.emitCastToAtomicIntPointer(Ptr);
785 if (Val1.isValid()) Val1 = Atomics.convertToAtomicIntPointer(Val1);
786 if (Val2.isValid()) Val2 = Atomics.convertToAtomicIntPointer(Val2);
787 if (Dest.isValid())
788 Dest = Atomics.emitCastToAtomicIntPointer(Dest);
789 else if (E->isCmpXChg())
790 Dest = CreateMemTemp(RValTy, "cmpxchg.bool");
791 else if (!RValTy->isVoidType())
792 Dest = Atomics.emitCastToAtomicIntPointer(Atomics.CreateTempAlloca());
John McCallfc207f22013-03-07 21:37:12 +0000793
794 // Use a library call. See: http://gcc.gnu.org/wiki/Atomic/GCCMM/LIbrary .
795 if (UseLibcall) {
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000796 bool UseOptimizedLibcall = false;
797 switch (E->getOp()) {
James Y Knight81167fb2015-08-05 16:57:36 +0000798 case AtomicExpr::AO__c11_atomic_init:
799 llvm_unreachable("Already handled above with EmitAtomicInit!");
800
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000801 case AtomicExpr::AO__c11_atomic_fetch_add:
802 case AtomicExpr::AO__atomic_fetch_add:
803 case AtomicExpr::AO__c11_atomic_fetch_and:
804 case AtomicExpr::AO__atomic_fetch_and:
805 case AtomicExpr::AO__c11_atomic_fetch_or:
806 case AtomicExpr::AO__atomic_fetch_or:
James Y Knight81167fb2015-08-05 16:57:36 +0000807 case AtomicExpr::AO__atomic_fetch_nand:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000808 case AtomicExpr::AO__c11_atomic_fetch_sub:
809 case AtomicExpr::AO__atomic_fetch_sub:
810 case AtomicExpr::AO__c11_atomic_fetch_xor:
811 case AtomicExpr::AO__atomic_fetch_xor:
James Y Knight81167fb2015-08-05 16:57:36 +0000812 case AtomicExpr::AO__atomic_add_fetch:
813 case AtomicExpr::AO__atomic_and_fetch:
814 case AtomicExpr::AO__atomic_nand_fetch:
815 case AtomicExpr::AO__atomic_or_fetch:
816 case AtomicExpr::AO__atomic_sub_fetch:
817 case AtomicExpr::AO__atomic_xor_fetch:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000818 // For these, only library calls for certain sizes exist.
819 UseOptimizedLibcall = true;
820 break;
James Y Knight81167fb2015-08-05 16:57:36 +0000821
822 case AtomicExpr::AO__c11_atomic_load:
823 case AtomicExpr::AO__c11_atomic_store:
824 case AtomicExpr::AO__c11_atomic_exchange:
825 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
826 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
827 case AtomicExpr::AO__atomic_load_n:
828 case AtomicExpr::AO__atomic_load:
829 case AtomicExpr::AO__atomic_store_n:
830 case AtomicExpr::AO__atomic_store:
831 case AtomicExpr::AO__atomic_exchange_n:
832 case AtomicExpr::AO__atomic_exchange:
833 case AtomicExpr::AO__atomic_compare_exchange_n:
834 case AtomicExpr::AO__atomic_compare_exchange:
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000835 // Only use optimized library calls for sizes for which they exist.
836 if (Size == 1 || Size == 2 || Size == 4 || Size == 8)
837 UseOptimizedLibcall = true;
838 break;
839 }
John McCallfc207f22013-03-07 21:37:12 +0000840
John McCallfc207f22013-03-07 21:37:12 +0000841 CallArgList Args;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000842 if (!UseOptimizedLibcall) {
843 // For non-optimized library calls, the size is the first parameter
844 Args.add(RValue::get(llvm::ConstantInt::get(SizeTy, Size)),
845 getContext().getSizeType());
846 }
847 // Atomic address is the first or second parameter
John McCall7f416cc2015-09-08 08:05:57 +0000848 Args.add(RValue::get(EmitCastToVoidPtr(Ptr.getPointer())),
849 getContext().VoidPtrTy);
John McCallfc207f22013-03-07 21:37:12 +0000850
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000851 std::string LibCallName;
Logan Chien74798a32014-03-26 17:35:01 +0000852 QualType LoweredMemTy =
853 MemTy->isPointerType() ? getContext().getIntPtrType() : MemTy;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000854 QualType RetTy;
855 bool HaveRetTy = false;
James Y Knight7aefb5b2015-11-12 18:37:29 +0000856 llvm::Instruction::BinaryOps PostOp = (llvm::Instruction::BinaryOps)0;
John McCallfc207f22013-03-07 21:37:12 +0000857 switch (E->getOp()) {
James Y Knight81167fb2015-08-05 16:57:36 +0000858 case AtomicExpr::AO__c11_atomic_init:
859 llvm_unreachable("Already handled!");
860
John McCallfc207f22013-03-07 21:37:12 +0000861 // There is only one libcall for compare an exchange, because there is no
862 // optimisation benefit possible from a libcall version of a weak compare
863 // and exchange.
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000864 // bool __atomic_compare_exchange(size_t size, void *mem, void *expected,
John McCallfc207f22013-03-07 21:37:12 +0000865 // void *desired, int success, int failure)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000866 // bool __atomic_compare_exchange_N(T *mem, T *expected, T desired,
867 // int success, int failure)
John McCallfc207f22013-03-07 21:37:12 +0000868 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
869 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
870 case AtomicExpr::AO__atomic_compare_exchange:
871 case AtomicExpr::AO__atomic_compare_exchange_n:
872 LibCallName = "__atomic_compare_exchange";
873 RetTy = getContext().BoolTy;
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000874 HaveRetTy = true;
John McCall7f416cc2015-09-08 08:05:57 +0000875 Args.add(RValue::get(EmitCastToVoidPtr(Val1.getPointer())),
876 getContext().VoidPtrTy);
877 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val2.getPointer(),
878 MemTy, E->getExprLoc(), sizeChars);
Nick Lewycky5fa40c32013-10-01 21:51:38 +0000879 Args.add(RValue::get(Order), getContext().IntTy);
John McCallfc207f22013-03-07 21:37:12 +0000880 Order = OrderFail;
881 break;
882 // void __atomic_exchange(size_t size, void *mem, void *val, void *return,
883 // int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000884 // T __atomic_exchange_N(T *mem, T val, int order)
John McCallfc207f22013-03-07 21:37:12 +0000885 case AtomicExpr::AO__c11_atomic_exchange:
886 case AtomicExpr::AO__atomic_exchange_n:
887 case AtomicExpr::AO__atomic_exchange:
888 LibCallName = "__atomic_exchange";
John McCall7f416cc2015-09-08 08:05:57 +0000889 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
890 MemTy, E->getExprLoc(), sizeChars);
John McCallfc207f22013-03-07 21:37:12 +0000891 break;
892 // void __atomic_store(size_t size, void *mem, void *val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000893 // void __atomic_store_N(T *mem, T val, int order)
John McCallfc207f22013-03-07 21:37:12 +0000894 case AtomicExpr::AO__c11_atomic_store:
895 case AtomicExpr::AO__atomic_store:
896 case AtomicExpr::AO__atomic_store_n:
897 LibCallName = "__atomic_store";
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000898 RetTy = getContext().VoidTy;
899 HaveRetTy = true;
John McCall7f416cc2015-09-08 08:05:57 +0000900 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
901 MemTy, E->getExprLoc(), sizeChars);
John McCallfc207f22013-03-07 21:37:12 +0000902 break;
903 // void __atomic_load(size_t size, void *mem, void *return, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000904 // T __atomic_load_N(T *mem, int order)
John McCallfc207f22013-03-07 21:37:12 +0000905 case AtomicExpr::AO__c11_atomic_load:
906 case AtomicExpr::AO__atomic_load:
907 case AtomicExpr::AO__atomic_load_n:
908 LibCallName = "__atomic_load";
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000909 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +0000910 // T __atomic_add_fetch_N(T *mem, T val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000911 // T __atomic_fetch_add_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +0000912 case AtomicExpr::AO__atomic_add_fetch:
913 PostOp = llvm::Instruction::Add;
914 // Fall through.
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000915 case AtomicExpr::AO__c11_atomic_fetch_add:
916 case AtomicExpr::AO__atomic_fetch_add:
917 LibCallName = "__atomic_fetch_add";
John McCall7f416cc2015-09-08 08:05:57 +0000918 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
919 LoweredMemTy, E->getExprLoc(), sizeChars);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000920 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +0000921 // T __atomic_and_fetch_N(T *mem, T val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000922 // T __atomic_fetch_and_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +0000923 case AtomicExpr::AO__atomic_and_fetch:
924 PostOp = llvm::Instruction::And;
925 // Fall through.
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000926 case AtomicExpr::AO__c11_atomic_fetch_and:
927 case AtomicExpr::AO__atomic_fetch_and:
928 LibCallName = "__atomic_fetch_and";
John McCall7f416cc2015-09-08 08:05:57 +0000929 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
930 MemTy, E->getExprLoc(), sizeChars);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000931 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +0000932 // T __atomic_or_fetch_N(T *mem, T val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000933 // T __atomic_fetch_or_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +0000934 case AtomicExpr::AO__atomic_or_fetch:
935 PostOp = llvm::Instruction::Or;
936 // Fall through.
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000937 case AtomicExpr::AO__c11_atomic_fetch_or:
938 case AtomicExpr::AO__atomic_fetch_or:
939 LibCallName = "__atomic_fetch_or";
John McCall7f416cc2015-09-08 08:05:57 +0000940 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
941 MemTy, E->getExprLoc(), sizeChars);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000942 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +0000943 // T __atomic_sub_fetch_N(T *mem, T val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000944 // T __atomic_fetch_sub_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +0000945 case AtomicExpr::AO__atomic_sub_fetch:
946 PostOp = llvm::Instruction::Sub;
947 // Fall through.
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000948 case AtomicExpr::AO__c11_atomic_fetch_sub:
949 case AtomicExpr::AO__atomic_fetch_sub:
950 LibCallName = "__atomic_fetch_sub";
John McCall7f416cc2015-09-08 08:05:57 +0000951 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
952 LoweredMemTy, E->getExprLoc(), sizeChars);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000953 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +0000954 // T __atomic_xor_fetch_N(T *mem, T val, int order)
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000955 // T __atomic_fetch_xor_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +0000956 case AtomicExpr::AO__atomic_xor_fetch:
957 PostOp = llvm::Instruction::Xor;
958 // Fall through.
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000959 case AtomicExpr::AO__c11_atomic_fetch_xor:
960 case AtomicExpr::AO__atomic_fetch_xor:
961 LibCallName = "__atomic_fetch_xor";
John McCall7f416cc2015-09-08 08:05:57 +0000962 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
963 MemTy, E->getExprLoc(), sizeChars);
John McCallfc207f22013-03-07 21:37:12 +0000964 break;
James Y Knight7aefb5b2015-11-12 18:37:29 +0000965 // T __atomic_nand_fetch_N(T *mem, T val, int order)
James Y Knight81167fb2015-08-05 16:57:36 +0000966 // T __atomic_fetch_nand_N(T *mem, T val, int order)
James Y Knight7aefb5b2015-11-12 18:37:29 +0000967 case AtomicExpr::AO__atomic_nand_fetch:
968 PostOp = llvm::Instruction::And; // the NOT is special cased below
969 // Fall through.
James Y Knight81167fb2015-08-05 16:57:36 +0000970 case AtomicExpr::AO__atomic_fetch_nand:
971 LibCallName = "__atomic_fetch_nand";
John McCall7f416cc2015-09-08 08:05:57 +0000972 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
973 MemTy, E->getExprLoc(), sizeChars);
James Y Knight81167fb2015-08-05 16:57:36 +0000974 break;
John McCallfc207f22013-03-07 21:37:12 +0000975 }
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000976
977 // Optimized functions have the size in their name.
978 if (UseOptimizedLibcall)
979 LibCallName += "_" + llvm::utostr(Size);
980 // By default, assume we return a value of the atomic type.
981 if (!HaveRetTy) {
982 if (UseOptimizedLibcall) {
983 // Value is returned directly.
David Majnemer0392cf82014-08-29 07:27:49 +0000984 // The function returns an appropriately sized integer type.
985 RetTy = getContext().getIntTypeForBitwidth(
986 getContext().toBits(sizeChars), /*Signed=*/false);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000987 } else {
988 // Value is returned through parameter before the order.
989 RetTy = getContext().VoidTy;
John McCall7f416cc2015-09-08 08:05:57 +0000990 Args.add(RValue::get(EmitCastToVoidPtr(Dest.getPointer())),
991 getContext().VoidPtrTy);
Ed Schoutenc7e82bd2013-05-31 19:27:59 +0000992 }
993 }
John McCallfc207f22013-03-07 21:37:12 +0000994 // order is always the last parameter
995 Args.add(RValue::get(Order),
996 getContext().IntTy);
997
James Y Knight7aefb5b2015-11-12 18:37:29 +0000998 // PostOp is only needed for the atomic_*_fetch operations, and
999 // thus is only needed for and implemented in the
1000 // UseOptimizedLibcall codepath.
1001 assert(UseOptimizedLibcall || !PostOp);
1002
David Majnemer659be552014-11-25 23:44:32 +00001003 RValue Res = emitAtomicLibcall(*this, LibCallName, RetTy, Args);
1004 // The value is returned directly from the libcall.
Tim Northovercc2a6e02015-11-09 19:56:35 +00001005 if (E->isCmpXChg())
David Majnemer659be552014-11-25 23:44:32 +00001006 return Res;
Tim Northovercc2a6e02015-11-09 19:56:35 +00001007
1008 // The value is returned directly for optimized libcalls but the expr
1009 // provided an out-param.
1010 if (UseOptimizedLibcall && Res.getScalarVal()) {
David Majnemer659be552014-11-25 23:44:32 +00001011 llvm::Value *ResVal = Res.getScalarVal();
James Y Knight7aefb5b2015-11-12 18:37:29 +00001012 if (PostOp) {
1013 llvm::Value *LoadVal1 = Args[1].RV.getScalarVal();
1014 ResVal = Builder.CreateBinOp(PostOp, ResVal, LoadVal1);
1015 }
1016 if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch)
1017 ResVal = Builder.CreateNot(ResVal);
1018
Tim Northovercc2a6e02015-11-09 19:56:35 +00001019 Builder.CreateStore(
1020 ResVal,
1021 Builder.CreateBitCast(Dest, ResVal->getType()->getPointerTo()));
David Majnemer659be552014-11-25 23:44:32 +00001022 }
Tim Northovercc2a6e02015-11-09 19:56:35 +00001023
1024 if (RValTy->isVoidType())
1025 return RValue::get(nullptr);
1026
1027 return convertTempToRValue(
1028 Builder.CreateBitCast(Dest, ConvertTypeForMem(RValTy)->getPointerTo()),
1029 RValTy, E->getExprLoc());
John McCallfc207f22013-03-07 21:37:12 +00001030 }
1031
1032 bool IsStore = E->getOp() == AtomicExpr::AO__c11_atomic_store ||
1033 E->getOp() == AtomicExpr::AO__atomic_store ||
1034 E->getOp() == AtomicExpr::AO__atomic_store_n;
1035 bool IsLoad = E->getOp() == AtomicExpr::AO__c11_atomic_load ||
1036 E->getOp() == AtomicExpr::AO__atomic_load ||
1037 E->getOp() == AtomicExpr::AO__atomic_load_n;
1038
John McCallfc207f22013-03-07 21:37:12 +00001039 if (isa<llvm::ConstantInt>(Order)) {
1040 int ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
1041 switch (ord) {
Tim Northovere94a34c2014-03-11 10:49:14 +00001042 case AtomicExpr::AO_ABI_memory_order_relaxed:
Tim Northovercadbbe12014-06-13 19:43:04 +00001043 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail,
John McCall7f416cc2015-09-08 08:05:57 +00001044 Size, llvm::Monotonic);
John McCallfc207f22013-03-07 21:37:12 +00001045 break;
Tim Northovere94a34c2014-03-11 10:49:14 +00001046 case AtomicExpr::AO_ABI_memory_order_consume:
1047 case AtomicExpr::AO_ABI_memory_order_acquire:
John McCallfc207f22013-03-07 21:37:12 +00001048 if (IsStore)
1049 break; // Avoid crashing on code with undefined behavior
Tim Northovercadbbe12014-06-13 19:43:04 +00001050 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail,
John McCall7f416cc2015-09-08 08:05:57 +00001051 Size, llvm::Acquire);
John McCallfc207f22013-03-07 21:37:12 +00001052 break;
Tim Northovere94a34c2014-03-11 10:49:14 +00001053 case AtomicExpr::AO_ABI_memory_order_release:
John McCallfc207f22013-03-07 21:37:12 +00001054 if (IsLoad)
1055 break; // Avoid crashing on code with undefined behavior
Tim Northovercadbbe12014-06-13 19:43:04 +00001056 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail,
John McCall7f416cc2015-09-08 08:05:57 +00001057 Size, llvm::Release);
John McCallfc207f22013-03-07 21:37:12 +00001058 break;
Tim Northovere94a34c2014-03-11 10:49:14 +00001059 case AtomicExpr::AO_ABI_memory_order_acq_rel:
John McCallfc207f22013-03-07 21:37:12 +00001060 if (IsLoad || IsStore)
1061 break; // Avoid crashing on code with undefined behavior
Tim Northovercadbbe12014-06-13 19:43:04 +00001062 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail,
John McCall7f416cc2015-09-08 08:05:57 +00001063 Size, llvm::AcquireRelease);
John McCallfc207f22013-03-07 21:37:12 +00001064 break;
Tim Northovere94a34c2014-03-11 10:49:14 +00001065 case AtomicExpr::AO_ABI_memory_order_seq_cst:
Tim Northovercadbbe12014-06-13 19:43:04 +00001066 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail,
John McCall7f416cc2015-09-08 08:05:57 +00001067 Size, llvm::SequentiallyConsistent);
John McCallfc207f22013-03-07 21:37:12 +00001068 break;
1069 default: // invalid order
1070 // We should not ever get here normally, but it's hard to
1071 // enforce that in general.
1072 break;
1073 }
David Majnemeree8d04d2014-12-12 08:16:09 +00001074 if (RValTy->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +00001075 return RValue::get(nullptr);
Tim Northovercc2a6e02015-11-09 19:56:35 +00001076
1077 return convertTempToRValue(
1078 Builder.CreateBitCast(Dest, ConvertTypeForMem(RValTy)->getPointerTo()),
1079 RValTy, E->getExprLoc());
John McCallfc207f22013-03-07 21:37:12 +00001080 }
1081
1082 // Long case, when Order isn't obviously constant.
1083
1084 // Create all the relevant BB's
Craig Topper8a13c412014-05-21 05:09:00 +00001085 llvm::BasicBlock *MonotonicBB = nullptr, *AcquireBB = nullptr,
1086 *ReleaseBB = nullptr, *AcqRelBB = nullptr,
1087 *SeqCstBB = nullptr;
John McCallfc207f22013-03-07 21:37:12 +00001088 MonotonicBB = createBasicBlock("monotonic", CurFn);
1089 if (!IsStore)
1090 AcquireBB = createBasicBlock("acquire", CurFn);
1091 if (!IsLoad)
1092 ReleaseBB = createBasicBlock("release", CurFn);
1093 if (!IsLoad && !IsStore)
1094 AcqRelBB = createBasicBlock("acqrel", CurFn);
1095 SeqCstBB = createBasicBlock("seqcst", CurFn);
1096 llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
1097
1098 // Create the switch for the split
1099 // MonotonicBB is arbitrarily chosen as the default case; in practice, this
1100 // doesn't matter unless someone is crazy enough to use something that
1101 // doesn't fold to a constant for the ordering.
1102 Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
1103 llvm::SwitchInst *SI = Builder.CreateSwitch(Order, MonotonicBB);
1104
1105 // Emit all the different atomics
1106 Builder.SetInsertPoint(MonotonicBB);
Tim Northovercadbbe12014-06-13 19:43:04 +00001107 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail,
John McCall7f416cc2015-09-08 08:05:57 +00001108 Size, llvm::Monotonic);
John McCallfc207f22013-03-07 21:37:12 +00001109 Builder.CreateBr(ContBB);
1110 if (!IsStore) {
1111 Builder.SetInsertPoint(AcquireBB);
Tim Northovercadbbe12014-06-13 19:43:04 +00001112 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail,
John McCall7f416cc2015-09-08 08:05:57 +00001113 Size, llvm::Acquire);
John McCallfc207f22013-03-07 21:37:12 +00001114 Builder.CreateBr(ContBB);
Tim Northover514fc612014-03-13 19:25:52 +00001115 SI->addCase(Builder.getInt32(AtomicExpr::AO_ABI_memory_order_consume),
1116 AcquireBB);
1117 SI->addCase(Builder.getInt32(AtomicExpr::AO_ABI_memory_order_acquire),
1118 AcquireBB);
John McCallfc207f22013-03-07 21:37:12 +00001119 }
1120 if (!IsLoad) {
1121 Builder.SetInsertPoint(ReleaseBB);
Tim Northovercadbbe12014-06-13 19:43:04 +00001122 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail,
John McCall7f416cc2015-09-08 08:05:57 +00001123 Size, llvm::Release);
John McCallfc207f22013-03-07 21:37:12 +00001124 Builder.CreateBr(ContBB);
Tim Northover514fc612014-03-13 19:25:52 +00001125 SI->addCase(Builder.getInt32(AtomicExpr::AO_ABI_memory_order_release),
1126 ReleaseBB);
John McCallfc207f22013-03-07 21:37:12 +00001127 }
1128 if (!IsLoad && !IsStore) {
1129 Builder.SetInsertPoint(AcqRelBB);
Tim Northovercadbbe12014-06-13 19:43:04 +00001130 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail,
John McCall7f416cc2015-09-08 08:05:57 +00001131 Size, llvm::AcquireRelease);
John McCallfc207f22013-03-07 21:37:12 +00001132 Builder.CreateBr(ContBB);
Tim Northover514fc612014-03-13 19:25:52 +00001133 SI->addCase(Builder.getInt32(AtomicExpr::AO_ABI_memory_order_acq_rel),
1134 AcqRelBB);
John McCallfc207f22013-03-07 21:37:12 +00001135 }
1136 Builder.SetInsertPoint(SeqCstBB);
Tim Northovercadbbe12014-06-13 19:43:04 +00001137 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail,
John McCall7f416cc2015-09-08 08:05:57 +00001138 Size, llvm::SequentiallyConsistent);
John McCallfc207f22013-03-07 21:37:12 +00001139 Builder.CreateBr(ContBB);
Tim Northover514fc612014-03-13 19:25:52 +00001140 SI->addCase(Builder.getInt32(AtomicExpr::AO_ABI_memory_order_seq_cst),
1141 SeqCstBB);
John McCallfc207f22013-03-07 21:37:12 +00001142
1143 // Cleanup and return
1144 Builder.SetInsertPoint(ContBB);
David Majnemeree8d04d2014-12-12 08:16:09 +00001145 if (RValTy->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +00001146 return RValue::get(nullptr);
Tim Northovercc2a6e02015-11-09 19:56:35 +00001147
1148 assert(Atomics.getValueSizeInBits() <= Atomics.getAtomicSizeInBits());
1149 return convertTempToRValue(
1150 Builder.CreateBitCast(Dest, ConvertTypeForMem(RValTy)->getPointerTo()),
1151 RValTy, E->getExprLoc());
John McCallfc207f22013-03-07 21:37:12 +00001152}
John McCalla8ec7eb2013-03-07 21:37:17 +00001153
John McCall7f416cc2015-09-08 08:05:57 +00001154Address AtomicInfo::emitCastToAtomicIntPointer(Address addr) const {
John McCalla8ec7eb2013-03-07 21:37:17 +00001155 unsigned addrspace =
John McCall7f416cc2015-09-08 08:05:57 +00001156 cast<llvm::PointerType>(addr.getPointer()->getType())->getAddressSpace();
John McCalla8ec7eb2013-03-07 21:37:17 +00001157 llvm::IntegerType *ty =
1158 llvm::IntegerType::get(CGF.getLLVMContext(), AtomicSizeInBits);
1159 return CGF.Builder.CreateBitCast(addr, ty->getPointerTo(addrspace));
1160}
1161
Tim Northovercc2a6e02015-11-09 19:56:35 +00001162Address AtomicInfo::convertToAtomicIntPointer(Address Addr) const {
1163 llvm::Type *Ty = Addr.getElementType();
1164 uint64_t SourceSizeInBits = CGF.CGM.getDataLayout().getTypeSizeInBits(Ty);
1165 if (SourceSizeInBits != AtomicSizeInBits) {
1166 Address Tmp = CreateTempAlloca();
1167 CGF.Builder.CreateMemCpy(Tmp, Addr,
1168 std::min(AtomicSizeInBits, SourceSizeInBits) / 8);
1169 Addr = Tmp;
1170 }
1171
1172 return emitCastToAtomicIntPointer(Addr);
1173}
1174
John McCall7f416cc2015-09-08 08:05:57 +00001175RValue AtomicInfo::convertAtomicTempToRValue(Address addr,
1176 AggValueSlot resultSlot,
1177 SourceLocation loc,
1178 bool asValue) const {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001179 if (LVal.isSimple()) {
1180 if (EvaluationKind == TEK_Aggregate)
1181 return resultSlot.asRValue();
John McCalla8ec7eb2013-03-07 21:37:17 +00001182
Alexey Bataevb57056f2015-01-22 06:17:56 +00001183 // Drill into the padding structure if we have one.
1184 if (hasPadding())
John McCall7f416cc2015-09-08 08:05:57 +00001185 addr = CGF.Builder.CreateStructGEP(addr, 0, CharUnits());
John McCalla8ec7eb2013-03-07 21:37:17 +00001186
Alexey Bataevb57056f2015-01-22 06:17:56 +00001187 // Otherwise, just convert the temporary to an r-value using the
1188 // normal conversion routine.
1189 return CGF.convertTempToRValue(addr, getValueType(), loc);
David Blaikie1ed728c2015-04-05 22:45:47 +00001190 }
John McCall7f416cc2015-09-08 08:05:57 +00001191 if (!asValue)
Alexey Bataevb8329262015-02-27 06:33:30 +00001192 // Get RValue from temp memory as atomic for non-simple lvalues
John McCall7f416cc2015-09-08 08:05:57 +00001193 return RValue::get(CGF.Builder.CreateLoad(addr));
David Blaikie1ed728c2015-04-05 22:45:47 +00001194 if (LVal.isBitField())
John McCall7f416cc2015-09-08 08:05:57 +00001195 return CGF.EmitLoadOfBitfieldLValue(
1196 LValue::MakeBitfield(addr, LVal.getBitFieldInfo(), LVal.getType(),
1197 LVal.getAlignmentSource()));
David Blaikie1ed728c2015-04-05 22:45:47 +00001198 if (LVal.isVectorElt())
John McCall7f416cc2015-09-08 08:05:57 +00001199 return CGF.EmitLoadOfLValue(
1200 LValue::MakeVectorElt(addr, LVal.getVectorIdx(), LVal.getType(),
1201 LVal.getAlignmentSource()), loc);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001202 assert(LVal.isExtVectorElt());
1203 return CGF.EmitLoadOfExtVectorElementLValue(LValue::MakeExtVectorElt(
John McCall7f416cc2015-09-08 08:05:57 +00001204 addr, LVal.getExtVectorElts(), LVal.getType(),
1205 LVal.getAlignmentSource()));
John McCalla8ec7eb2013-03-07 21:37:17 +00001206}
1207
Alexey Bataevb8329262015-02-27 06:33:30 +00001208RValue AtomicInfo::ConvertIntToValueOrAtomic(llvm::Value *IntVal,
1209 AggValueSlot ResultSlot,
1210 SourceLocation Loc,
1211 bool AsValue) const {
Alexey Bataev452d8e12014-12-15 05:25:25 +00001212 // Try not to in some easy cases.
1213 assert(IntVal->getType()->isIntegerTy() && "Expected integer value");
Alexey Bataevb8329262015-02-27 06:33:30 +00001214 if (getEvaluationKind() == TEK_Scalar &&
1215 (((!LVal.isBitField() ||
1216 LVal.getBitFieldInfo().Size == ValueSizeInBits) &&
1217 !hasPadding()) ||
1218 !AsValue)) {
1219 auto *ValTy = AsValue
1220 ? CGF.ConvertTypeForMem(ValueTy)
John McCall7f416cc2015-09-08 08:05:57 +00001221 : getAtomicAddress().getType()->getPointerElementType();
Alexey Bataev452d8e12014-12-15 05:25:25 +00001222 if (ValTy->isIntegerTy()) {
1223 assert(IntVal->getType() == ValTy && "Different integer types.");
David Majnemereeaec262015-02-14 02:18:14 +00001224 return RValue::get(CGF.EmitFromMemory(IntVal, ValueTy));
Alexey Bataev452d8e12014-12-15 05:25:25 +00001225 } else if (ValTy->isPointerTy())
1226 return RValue::get(CGF.Builder.CreateIntToPtr(IntVal, ValTy));
1227 else if (llvm::CastInst::isBitCastable(IntVal->getType(), ValTy))
1228 return RValue::get(CGF.Builder.CreateBitCast(IntVal, ValTy));
1229 }
1230
1231 // Create a temporary. This needs to be big enough to hold the
1232 // atomic integer.
John McCall7f416cc2015-09-08 08:05:57 +00001233 Address Temp = Address::invalid();
Alexey Bataev452d8e12014-12-15 05:25:25 +00001234 bool TempIsVolatile = false;
Alexey Bataevb8329262015-02-27 06:33:30 +00001235 if (AsValue && getEvaluationKind() == TEK_Aggregate) {
Alexey Bataev452d8e12014-12-15 05:25:25 +00001236 assert(!ResultSlot.isIgnored());
John McCall7f416cc2015-09-08 08:05:57 +00001237 Temp = ResultSlot.getAddress();
Alexey Bataev452d8e12014-12-15 05:25:25 +00001238 TempIsVolatile = ResultSlot.isVolatile();
1239 } else {
Alexey Bataevb8329262015-02-27 06:33:30 +00001240 Temp = CreateTempAlloca();
Alexey Bataev452d8e12014-12-15 05:25:25 +00001241 }
1242
1243 // Slam the integer into the temporary.
John McCall7f416cc2015-09-08 08:05:57 +00001244 Address CastTemp = emitCastToAtomicIntPointer(Temp);
1245 CGF.Builder.CreateStore(IntVal, CastTemp)
Alexey Bataev452d8e12014-12-15 05:25:25 +00001246 ->setVolatile(TempIsVolatile);
1247
John McCall7f416cc2015-09-08 08:05:57 +00001248 return convertAtomicTempToRValue(Temp, ResultSlot, Loc, AsValue);
Alexey Bataevb8329262015-02-27 06:33:30 +00001249}
1250
1251void AtomicInfo::EmitAtomicLoadLibcall(llvm::Value *AddForLoaded,
1252 llvm::AtomicOrdering AO, bool) {
1253 // void __atomic_load(size_t size, void *mem, void *return, int order);
1254 CallArgList Args;
1255 Args.add(RValue::get(getAtomicSizeValue()), CGF.getContext().getSizeType());
John McCall7f416cc2015-09-08 08:05:57 +00001256 Args.add(RValue::get(CGF.EmitCastToVoidPtr(getAtomicPointer())),
Alexey Bataevb8329262015-02-27 06:33:30 +00001257 CGF.getContext().VoidPtrTy);
1258 Args.add(RValue::get(CGF.EmitCastToVoidPtr(AddForLoaded)),
1259 CGF.getContext().VoidPtrTy);
1260 Args.add(RValue::get(
1261 llvm::ConstantInt::get(CGF.IntTy, translateAtomicOrdering(AO))),
1262 CGF.getContext().IntTy);
1263 emitAtomicLibcall(CGF, "__atomic_load", CGF.getContext().VoidTy, Args);
1264}
1265
1266llvm::Value *AtomicInfo::EmitAtomicLoadOp(llvm::AtomicOrdering AO,
1267 bool IsVolatile) {
1268 // Okay, we're doing this natively.
John McCall7f416cc2015-09-08 08:05:57 +00001269 Address Addr = getAtomicAddressAsAtomicIntPointer();
Alexey Bataevb8329262015-02-27 06:33:30 +00001270 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Addr, "atomic-load");
1271 Load->setAtomic(AO);
1272
1273 // Other decoration.
Alexey Bataevb8329262015-02-27 06:33:30 +00001274 if (IsVolatile)
1275 Load->setVolatile(true);
1276 if (LVal.getTBAAInfo())
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001277 CGF.CGM.DecorateInstructionWithTBAA(Load, LVal.getTBAAInfo());
Alexey Bataevb8329262015-02-27 06:33:30 +00001278 return Load;
Alexey Bataev452d8e12014-12-15 05:25:25 +00001279}
1280
David Majnemera5b195a2015-02-14 01:35:12 +00001281/// An LValue is a candidate for having its loads and stores be made atomic if
1282/// we are operating under /volatile:ms *and* the LValue itself is volatile and
1283/// performing such an operation can be performed without a libcall.
1284bool CodeGenFunction::LValueIsSuitableForInlineAtomic(LValue LV) {
John McCall7f416cc2015-09-08 08:05:57 +00001285 if (!CGM.getCodeGenOpts().MSVolatile) return false;
David Majnemera5b195a2015-02-14 01:35:12 +00001286 AtomicInfo AI(*this, LV);
1287 bool IsVolatile = LV.isVolatile() || hasVolatileMember(LV.getType());
1288 // An atomic is inline if we don't need to use a libcall.
1289 bool AtomicIsInline = !AI.shouldUseLibcall();
John McCall7f416cc2015-09-08 08:05:57 +00001290 return IsVolatile && AtomicIsInline;
David Majnemera5b195a2015-02-14 01:35:12 +00001291}
1292
1293/// An type is a candidate for having its loads and stores be made atomic if
1294/// we are operating under /volatile:ms *and* we know the access is volatile and
1295/// performing such an operation can be performed without a libcall.
1296bool CodeGenFunction::typeIsSuitableForInlineAtomic(QualType Ty,
1297 bool IsVolatile) const {
David Majnemerfc80b6e2016-01-22 16:36:44 +00001298 // The operation must be volatile for us to make it atomic.
1299 if (!IsVolatile)
1300 return false;
1301 // The -fms-volatile flag must be passed for us to adopt this behavior.
1302 if (!CGM.getCodeGenOpts().MSVolatile)
1303 return false;
1304
David Majnemera5b195a2015-02-14 01:35:12 +00001305 // An atomic is inline if we don't need to use a libcall (e.g. it is builtin).
David Majnemerfc80b6e2016-01-22 16:36:44 +00001306 if (!getContext().getTargetInfo().hasBuiltinAtomic(
1307 getContext().getTypeSize(Ty), getContext().getTypeAlign(Ty)))
1308 return false;
1309
1310 // MSVC doesn't seem to do this for types wider than a pointer.
1311 if (getContext().getTypeSize(Ty) >
1312 getContext().getTypeSize(getContext().getIntPtrType()))
1313 return false;
1314 return true;
David Majnemera5b195a2015-02-14 01:35:12 +00001315}
1316
1317RValue CodeGenFunction::EmitAtomicLoad(LValue LV, SourceLocation SL,
1318 AggValueSlot Slot) {
1319 llvm::AtomicOrdering AO;
1320 bool IsVolatile = LV.isVolatileQualified();
1321 if (LV.getType()->isAtomicType()) {
1322 AO = llvm::SequentiallyConsistent;
1323 } else {
1324 AO = llvm::Acquire;
1325 IsVolatile = true;
1326 }
1327 return EmitAtomicLoad(LV, SL, AO, IsVolatile, Slot);
1328}
1329
Alexey Bataevb8329262015-02-27 06:33:30 +00001330RValue AtomicInfo::EmitAtomicLoad(AggValueSlot ResultSlot, SourceLocation Loc,
1331 bool AsValue, llvm::AtomicOrdering AO,
1332 bool IsVolatile) {
1333 // Check whether we should use a library call.
1334 if (shouldUseLibcall()) {
John McCall7f416cc2015-09-08 08:05:57 +00001335 Address TempAddr = Address::invalid();
Alexey Bataevb8329262015-02-27 06:33:30 +00001336 if (LVal.isSimple() && !ResultSlot.isIgnored()) {
1337 assert(getEvaluationKind() == TEK_Aggregate);
John McCall7f416cc2015-09-08 08:05:57 +00001338 TempAddr = ResultSlot.getAddress();
Alexey Bataevb8329262015-02-27 06:33:30 +00001339 } else
1340 TempAddr = CreateTempAlloca();
1341
John McCall7f416cc2015-09-08 08:05:57 +00001342 EmitAtomicLoadLibcall(TempAddr.getPointer(), AO, IsVolatile);
Alexey Bataevb8329262015-02-27 06:33:30 +00001343
1344 // Okay, turn that back into the original value or whole atomic (for
1345 // non-simple lvalues) type.
John McCall7f416cc2015-09-08 08:05:57 +00001346 return convertAtomicTempToRValue(TempAddr, ResultSlot, Loc, AsValue);
Alexey Bataevb8329262015-02-27 06:33:30 +00001347 }
1348
1349 // Okay, we're doing this natively.
1350 auto *Load = EmitAtomicLoadOp(AO, IsVolatile);
1351
1352 // If we're ignoring an aggregate return, don't do anything.
1353 if (getEvaluationKind() == TEK_Aggregate && ResultSlot.isIgnored())
John McCall7f416cc2015-09-08 08:05:57 +00001354 return RValue::getAggregate(Address::invalid(), false);
Alexey Bataevb8329262015-02-27 06:33:30 +00001355
1356 // Okay, turn that back into the original value or atomic (for non-simple
1357 // lvalues) type.
1358 return ConvertIntToValueOrAtomic(Load, ResultSlot, Loc, AsValue);
1359}
1360
John McCalla8ec7eb2013-03-07 21:37:17 +00001361/// Emit a load from an l-value of atomic type. Note that the r-value
1362/// we produce is an r-value of the atomic *value* type.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001363RValue CodeGenFunction::EmitAtomicLoad(LValue src, SourceLocation loc,
David Majnemera5b195a2015-02-14 01:35:12 +00001364 llvm::AtomicOrdering AO, bool IsVolatile,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001365 AggValueSlot resultSlot) {
Alexey Bataevb8329262015-02-27 06:33:30 +00001366 AtomicInfo Atomics(*this, src);
1367 return Atomics.EmitAtomicLoad(resultSlot, loc, /*AsValue=*/true, AO,
1368 IsVolatile);
John McCalla8ec7eb2013-03-07 21:37:17 +00001369}
1370
John McCalla8ec7eb2013-03-07 21:37:17 +00001371/// Copy an r-value into memory as part of storing to an atomic type.
1372/// This needs to create a bit-pattern suitable for atomic operations.
Alexey Bataevb57056f2015-01-22 06:17:56 +00001373void AtomicInfo::emitCopyIntoMemory(RValue rvalue) const {
1374 assert(LVal.isSimple());
John McCalla8ec7eb2013-03-07 21:37:17 +00001375 // If we have an r-value, the rvalue should be of the atomic type,
1376 // which means that the caller is responsible for having zeroed
1377 // any padding. Just do an aggregate copy of that type.
1378 if (rvalue.isAggregate()) {
Alexey Bataevb8329262015-02-27 06:33:30 +00001379 CGF.EmitAggregateCopy(getAtomicAddress(),
John McCall7f416cc2015-09-08 08:05:57 +00001380 rvalue.getAggregateAddress(),
John McCalla8ec7eb2013-03-07 21:37:17 +00001381 getAtomicType(),
1382 (rvalue.isVolatileQualified()
John McCall7f416cc2015-09-08 08:05:57 +00001383 || LVal.isVolatileQualified()));
John McCalla8ec7eb2013-03-07 21:37:17 +00001384 return;
1385 }
1386
1387 // Okay, otherwise we're copying stuff.
1388
1389 // Zero out the buffer if necessary.
Alexey Bataevb57056f2015-01-22 06:17:56 +00001390 emitMemSetZeroIfNecessary();
John McCalla8ec7eb2013-03-07 21:37:17 +00001391
1392 // Drill past the padding if present.
Alexey Bataevb57056f2015-01-22 06:17:56 +00001393 LValue TempLVal = projectValue();
John McCalla8ec7eb2013-03-07 21:37:17 +00001394
1395 // Okay, store the rvalue in.
1396 if (rvalue.isScalar()) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001397 CGF.EmitStoreOfScalar(rvalue.getScalarVal(), TempLVal, /*init*/ true);
John McCalla8ec7eb2013-03-07 21:37:17 +00001398 } else {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001399 CGF.EmitStoreOfComplex(rvalue.getComplexVal(), TempLVal, /*init*/ true);
John McCalla8ec7eb2013-03-07 21:37:17 +00001400 }
1401}
1402
1403
1404/// Materialize an r-value into memory for the purposes of storing it
1405/// to an atomic type.
John McCall7f416cc2015-09-08 08:05:57 +00001406Address AtomicInfo::materializeRValue(RValue rvalue) const {
John McCalla8ec7eb2013-03-07 21:37:17 +00001407 // Aggregate r-values are already in memory, and EmitAtomicStore
1408 // requires them to be values of the atomic type.
1409 if (rvalue.isAggregate())
John McCall7f416cc2015-09-08 08:05:57 +00001410 return rvalue.getAggregateAddress();
John McCalla8ec7eb2013-03-07 21:37:17 +00001411
1412 // Otherwise, make a temporary and materialize into it.
John McCall7f416cc2015-09-08 08:05:57 +00001413 LValue TempLV = CGF.MakeAddrLValue(CreateTempAlloca(), getAtomicType());
Alexey Bataevb8329262015-02-27 06:33:30 +00001414 AtomicInfo Atomics(CGF, TempLV);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001415 Atomics.emitCopyIntoMemory(rvalue);
Alexey Bataevb8329262015-02-27 06:33:30 +00001416 return TempLV.getAddress();
John McCalla8ec7eb2013-03-07 21:37:17 +00001417}
1418
Alexey Bataev452d8e12014-12-15 05:25:25 +00001419llvm::Value *AtomicInfo::convertRValueToInt(RValue RVal) const {
1420 // If we've got a scalar value of the right size, try to avoid going
1421 // through memory.
Alexey Bataevb8329262015-02-27 06:33:30 +00001422 if (RVal.isScalar() && (!hasPadding() || !LVal.isSimple())) {
Alexey Bataev452d8e12014-12-15 05:25:25 +00001423 llvm::Value *Value = RVal.getScalarVal();
1424 if (isa<llvm::IntegerType>(Value->getType()))
Alexey Bataevb4505a72015-03-30 05:20:59 +00001425 return CGF.EmitToMemory(Value, ValueTy);
Alexey Bataev452d8e12014-12-15 05:25:25 +00001426 else {
Alexey Bataevb8329262015-02-27 06:33:30 +00001427 llvm::IntegerType *InputIntTy = llvm::IntegerType::get(
1428 CGF.getLLVMContext(),
1429 LVal.isSimple() ? getValueSizeInBits() : getAtomicSizeInBits());
Alexey Bataev452d8e12014-12-15 05:25:25 +00001430 if (isa<llvm::PointerType>(Value->getType()))
1431 return CGF.Builder.CreatePtrToInt(Value, InputIntTy);
1432 else if (llvm::BitCastInst::isBitCastable(Value->getType(), InputIntTy))
1433 return CGF.Builder.CreateBitCast(Value, InputIntTy);
1434 }
1435 }
1436 // Otherwise, we need to go through memory.
1437 // Put the r-value in memory.
John McCall7f416cc2015-09-08 08:05:57 +00001438 Address Addr = materializeRValue(RVal);
Alexey Bataev452d8e12014-12-15 05:25:25 +00001439
1440 // Cast the temporary to the atomic int type and pull a value out.
1441 Addr = emitCastToAtomicIntPointer(Addr);
John McCall7f416cc2015-09-08 08:05:57 +00001442 return CGF.Builder.CreateLoad(Addr);
Alexey Bataev452d8e12014-12-15 05:25:25 +00001443}
1444
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001445std::pair<llvm::Value *, llvm::Value *> AtomicInfo::EmitAtomicCompareExchangeOp(
1446 llvm::Value *ExpectedVal, llvm::Value *DesiredVal,
1447 llvm::AtomicOrdering Success, llvm::AtomicOrdering Failure, bool IsWeak) {
Alexey Bataevb8329262015-02-27 06:33:30 +00001448 // Do the atomic store.
John McCall7f416cc2015-09-08 08:05:57 +00001449 Address Addr = getAtomicAddressAsAtomicIntPointer();
1450 auto *Inst = CGF.Builder.CreateAtomicCmpXchg(Addr.getPointer(),
1451 ExpectedVal, DesiredVal,
Alexey Bataevb4505a72015-03-30 05:20:59 +00001452 Success, Failure);
Alexey Bataevb8329262015-02-27 06:33:30 +00001453 // Other decoration.
1454 Inst->setVolatile(LVal.isVolatileQualified());
1455 Inst->setWeak(IsWeak);
1456
1457 // Okay, turn that back into the original value type.
1458 auto *PreviousVal = CGF.Builder.CreateExtractValue(Inst, /*Idxs=*/0);
1459 auto *SuccessFailureVal = CGF.Builder.CreateExtractValue(Inst, /*Idxs=*/1);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001460 return std::make_pair(PreviousVal, SuccessFailureVal);
Alexey Bataevb8329262015-02-27 06:33:30 +00001461}
1462
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001463llvm::Value *
1464AtomicInfo::EmitAtomicCompareExchangeLibcall(llvm::Value *ExpectedAddr,
1465 llvm::Value *DesiredAddr,
Alexey Bataevb8329262015-02-27 06:33:30 +00001466 llvm::AtomicOrdering Success,
1467 llvm::AtomicOrdering Failure) {
1468 // bool __atomic_compare_exchange(size_t size, void *obj, void *expected,
1469 // void *desired, int success, int failure);
1470 CallArgList Args;
1471 Args.add(RValue::get(getAtomicSizeValue()), CGF.getContext().getSizeType());
John McCall7f416cc2015-09-08 08:05:57 +00001472 Args.add(RValue::get(CGF.EmitCastToVoidPtr(getAtomicPointer())),
Alexey Bataevb8329262015-02-27 06:33:30 +00001473 CGF.getContext().VoidPtrTy);
1474 Args.add(RValue::get(CGF.EmitCastToVoidPtr(ExpectedAddr)),
1475 CGF.getContext().VoidPtrTy);
1476 Args.add(RValue::get(CGF.EmitCastToVoidPtr(DesiredAddr)),
1477 CGF.getContext().VoidPtrTy);
1478 Args.add(RValue::get(llvm::ConstantInt::get(
1479 CGF.IntTy, translateAtomicOrdering(Success))),
1480 CGF.getContext().IntTy);
1481 Args.add(RValue::get(llvm::ConstantInt::get(
1482 CGF.IntTy, translateAtomicOrdering(Failure))),
1483 CGF.getContext().IntTy);
1484 auto SuccessFailureRVal = emitAtomicLibcall(CGF, "__atomic_compare_exchange",
1485 CGF.getContext().BoolTy, Args);
Alexey Bataevb4505a72015-03-30 05:20:59 +00001486
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001487 return SuccessFailureRVal.getScalarVal();
Alexey Bataevb8329262015-02-27 06:33:30 +00001488}
1489
Alexey Bataevb4505a72015-03-30 05:20:59 +00001490std::pair<RValue, llvm::Value *> AtomicInfo::EmitAtomicCompareExchange(
Alexey Bataevb8329262015-02-27 06:33:30 +00001491 RValue Expected, RValue Desired, llvm::AtomicOrdering Success,
1492 llvm::AtomicOrdering Failure, bool IsWeak) {
1493 if (Failure >= Success)
1494 // Don't assert on undefined behavior.
1495 Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(Success);
1496
1497 // Check whether we should use a library call.
1498 if (shouldUseLibcall()) {
Alexey Bataevb8329262015-02-27 06:33:30 +00001499 // Produce a source address.
John McCall7f416cc2015-09-08 08:05:57 +00001500 Address ExpectedAddr = materializeRValue(Expected);
1501 Address DesiredAddr = materializeRValue(Desired);
1502 auto *Res = EmitAtomicCompareExchangeLibcall(ExpectedAddr.getPointer(),
1503 DesiredAddr.getPointer(),
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001504 Success, Failure);
1505 return std::make_pair(
John McCall7f416cc2015-09-08 08:05:57 +00001506 convertAtomicTempToRValue(ExpectedAddr, AggValueSlot::ignored(),
1507 SourceLocation(), /*AsValue=*/false),
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001508 Res);
Alexey Bataevb8329262015-02-27 06:33:30 +00001509 }
1510
1511 // If we've got a scalar value of the right size, try to avoid going
1512 // through memory.
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001513 auto *ExpectedVal = convertRValueToInt(Expected);
1514 auto *DesiredVal = convertRValueToInt(Desired);
1515 auto Res = EmitAtomicCompareExchangeOp(ExpectedVal, DesiredVal, Success,
1516 Failure, IsWeak);
1517 return std::make_pair(
1518 ConvertIntToValueOrAtomic(Res.first, AggValueSlot::ignored(),
1519 SourceLocation(), /*AsValue=*/false),
1520 Res.second);
1521}
1522
1523static void
1524EmitAtomicUpdateValue(CodeGenFunction &CGF, AtomicInfo &Atomics, RValue OldRVal,
1525 const llvm::function_ref<RValue(RValue)> &UpdateOp,
John McCall7f416cc2015-09-08 08:05:57 +00001526 Address DesiredAddr) {
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001527 RValue UpRVal;
1528 LValue AtomicLVal = Atomics.getAtomicLValue();
1529 LValue DesiredLVal;
1530 if (AtomicLVal.isSimple()) {
1531 UpRVal = OldRVal;
John McCall7f416cc2015-09-08 08:05:57 +00001532 DesiredLVal = CGF.MakeAddrLValue(DesiredAddr, AtomicLVal.getType());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001533 } else {
1534 // Build new lvalue for temp address
John McCall7f416cc2015-09-08 08:05:57 +00001535 Address Ptr = Atomics.materializeRValue(OldRVal);
1536 LValue UpdateLVal;
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001537 if (AtomicLVal.isBitField()) {
1538 UpdateLVal =
1539 LValue::MakeBitfield(Ptr, AtomicLVal.getBitFieldInfo(),
John McCall7f416cc2015-09-08 08:05:57 +00001540 AtomicLVal.getType(),
1541 AtomicLVal.getAlignmentSource());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001542 DesiredLVal =
1543 LValue::MakeBitfield(DesiredAddr, AtomicLVal.getBitFieldInfo(),
John McCall7f416cc2015-09-08 08:05:57 +00001544 AtomicLVal.getType(),
1545 AtomicLVal.getAlignmentSource());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001546 } else if (AtomicLVal.isVectorElt()) {
1547 UpdateLVal = LValue::MakeVectorElt(Ptr, AtomicLVal.getVectorIdx(),
1548 AtomicLVal.getType(),
John McCall7f416cc2015-09-08 08:05:57 +00001549 AtomicLVal.getAlignmentSource());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001550 DesiredLVal = LValue::MakeVectorElt(
1551 DesiredAddr, AtomicLVal.getVectorIdx(), AtomicLVal.getType(),
John McCall7f416cc2015-09-08 08:05:57 +00001552 AtomicLVal.getAlignmentSource());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001553 } else {
1554 assert(AtomicLVal.isExtVectorElt());
1555 UpdateLVal = LValue::MakeExtVectorElt(Ptr, AtomicLVal.getExtVectorElts(),
1556 AtomicLVal.getType(),
John McCall7f416cc2015-09-08 08:05:57 +00001557 AtomicLVal.getAlignmentSource());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001558 DesiredLVal = LValue::MakeExtVectorElt(
1559 DesiredAddr, AtomicLVal.getExtVectorElts(), AtomicLVal.getType(),
John McCall7f416cc2015-09-08 08:05:57 +00001560 AtomicLVal.getAlignmentSource());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001561 }
1562 UpdateLVal.setTBAAInfo(AtomicLVal.getTBAAInfo());
1563 DesiredLVal.setTBAAInfo(AtomicLVal.getTBAAInfo());
1564 UpRVal = CGF.EmitLoadOfLValue(UpdateLVal, SourceLocation());
1565 }
1566 // Store new value in the corresponding memory area
1567 RValue NewRVal = UpdateOp(UpRVal);
1568 if (NewRVal.isScalar()) {
1569 CGF.EmitStoreThroughLValue(NewRVal, DesiredLVal);
1570 } else {
1571 assert(NewRVal.isComplex());
1572 CGF.EmitStoreOfComplex(NewRVal.getComplexVal(), DesiredLVal,
1573 /*isInit=*/false);
1574 }
1575}
1576
1577void AtomicInfo::EmitAtomicUpdateLibcall(
1578 llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1579 bool IsVolatile) {
1580 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1581
John McCall7f416cc2015-09-08 08:05:57 +00001582 Address ExpectedAddr = CreateTempAlloca();
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001583
John McCall7f416cc2015-09-08 08:05:57 +00001584 EmitAtomicLoadLibcall(ExpectedAddr.getPointer(), AO, IsVolatile);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001585 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1586 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1587 CGF.EmitBlock(ContBB);
John McCall7f416cc2015-09-08 08:05:57 +00001588 Address DesiredAddr = CreateTempAlloca();
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001589 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
John McCall7f416cc2015-09-08 08:05:57 +00001590 requiresMemSetZero(getAtomicAddress().getElementType())) {
1591 auto *OldVal = CGF.Builder.CreateLoad(ExpectedAddr);
1592 CGF.Builder.CreateStore(OldVal, DesiredAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001593 }
John McCall7f416cc2015-09-08 08:05:57 +00001594 auto OldRVal = convertAtomicTempToRValue(ExpectedAddr,
1595 AggValueSlot::ignored(),
1596 SourceLocation(), /*AsValue=*/false);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001597 EmitAtomicUpdateValue(CGF, *this, OldRVal, UpdateOp, DesiredAddr);
1598 auto *Res =
John McCall7f416cc2015-09-08 08:05:57 +00001599 EmitAtomicCompareExchangeLibcall(ExpectedAddr.getPointer(),
1600 DesiredAddr.getPointer(),
1601 AO, Failure);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001602 CGF.Builder.CreateCondBr(Res, ExitBB, ContBB);
1603 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1604}
1605
1606void AtomicInfo::EmitAtomicUpdateOp(
1607 llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1608 bool IsVolatile) {
1609 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1610
1611 // Do the atomic load.
1612 auto *OldVal = EmitAtomicLoadOp(AO, IsVolatile);
1613 // For non-simple lvalues perform compare-and-swap procedure.
1614 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1615 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1616 auto *CurBB = CGF.Builder.GetInsertBlock();
1617 CGF.EmitBlock(ContBB);
1618 llvm::PHINode *PHI = CGF.Builder.CreatePHI(OldVal->getType(),
1619 /*NumReservedValues=*/2);
1620 PHI->addIncoming(OldVal, CurBB);
John McCall7f416cc2015-09-08 08:05:57 +00001621 Address NewAtomicAddr = CreateTempAlloca();
1622 Address NewAtomicIntAddr = emitCastToAtomicIntPointer(NewAtomicAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001623 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
John McCall7f416cc2015-09-08 08:05:57 +00001624 requiresMemSetZero(getAtomicAddress().getElementType())) {
1625 CGF.Builder.CreateStore(PHI, NewAtomicIntAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001626 }
1627 auto OldRVal = ConvertIntToValueOrAtomic(PHI, AggValueSlot::ignored(),
1628 SourceLocation(), /*AsValue=*/false);
1629 EmitAtomicUpdateValue(CGF, *this, OldRVal, UpdateOp, NewAtomicAddr);
John McCall7f416cc2015-09-08 08:05:57 +00001630 auto *DesiredVal = CGF.Builder.CreateLoad(NewAtomicIntAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001631 // Try to write new value using cmpxchg operation
1632 auto Res = EmitAtomicCompareExchangeOp(PHI, DesiredVal, AO, Failure);
1633 PHI->addIncoming(Res.first, CGF.Builder.GetInsertBlock());
1634 CGF.Builder.CreateCondBr(Res.second, ExitBB, ContBB);
1635 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1636}
1637
1638static void EmitAtomicUpdateValue(CodeGenFunction &CGF, AtomicInfo &Atomics,
John McCall7f416cc2015-09-08 08:05:57 +00001639 RValue UpdateRVal, Address DesiredAddr) {
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001640 LValue AtomicLVal = Atomics.getAtomicLValue();
1641 LValue DesiredLVal;
1642 // Build new lvalue for temp address
1643 if (AtomicLVal.isBitField()) {
1644 DesiredLVal =
1645 LValue::MakeBitfield(DesiredAddr, AtomicLVal.getBitFieldInfo(),
John McCall7f416cc2015-09-08 08:05:57 +00001646 AtomicLVal.getType(),
1647 AtomicLVal.getAlignmentSource());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001648 } else if (AtomicLVal.isVectorElt()) {
1649 DesiredLVal =
1650 LValue::MakeVectorElt(DesiredAddr, AtomicLVal.getVectorIdx(),
John McCall7f416cc2015-09-08 08:05:57 +00001651 AtomicLVal.getType(),
1652 AtomicLVal.getAlignmentSource());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001653 } else {
1654 assert(AtomicLVal.isExtVectorElt());
1655 DesiredLVal = LValue::MakeExtVectorElt(
1656 DesiredAddr, AtomicLVal.getExtVectorElts(), AtomicLVal.getType(),
John McCall7f416cc2015-09-08 08:05:57 +00001657 AtomicLVal.getAlignmentSource());
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001658 }
1659 DesiredLVal.setTBAAInfo(AtomicLVal.getTBAAInfo());
1660 // Store new value in the corresponding memory area
1661 assert(UpdateRVal.isScalar());
1662 CGF.EmitStoreThroughLValue(UpdateRVal, DesiredLVal);
1663}
1664
1665void AtomicInfo::EmitAtomicUpdateLibcall(llvm::AtomicOrdering AO,
1666 RValue UpdateRVal, bool IsVolatile) {
1667 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1668
John McCall7f416cc2015-09-08 08:05:57 +00001669 Address ExpectedAddr = CreateTempAlloca();
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001670
John McCall7f416cc2015-09-08 08:05:57 +00001671 EmitAtomicLoadLibcall(ExpectedAddr.getPointer(), AO, IsVolatile);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001672 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1673 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1674 CGF.EmitBlock(ContBB);
John McCall7f416cc2015-09-08 08:05:57 +00001675 Address DesiredAddr = CreateTempAlloca();
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001676 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
John McCall7f416cc2015-09-08 08:05:57 +00001677 requiresMemSetZero(getAtomicAddress().getElementType())) {
1678 auto *OldVal = CGF.Builder.CreateLoad(ExpectedAddr);
1679 CGF.Builder.CreateStore(OldVal, DesiredAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001680 }
1681 EmitAtomicUpdateValue(CGF, *this, UpdateRVal, DesiredAddr);
1682 auto *Res =
John McCall7f416cc2015-09-08 08:05:57 +00001683 EmitAtomicCompareExchangeLibcall(ExpectedAddr.getPointer(),
1684 DesiredAddr.getPointer(),
1685 AO, Failure);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001686 CGF.Builder.CreateCondBr(Res, ExitBB, ContBB);
1687 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1688}
1689
1690void AtomicInfo::EmitAtomicUpdateOp(llvm::AtomicOrdering AO, RValue UpdateRVal,
1691 bool IsVolatile) {
1692 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1693
1694 // Do the atomic load.
1695 auto *OldVal = EmitAtomicLoadOp(AO, IsVolatile);
1696 // For non-simple lvalues perform compare-and-swap procedure.
1697 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1698 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1699 auto *CurBB = CGF.Builder.GetInsertBlock();
1700 CGF.EmitBlock(ContBB);
1701 llvm::PHINode *PHI = CGF.Builder.CreatePHI(OldVal->getType(),
1702 /*NumReservedValues=*/2);
1703 PHI->addIncoming(OldVal, CurBB);
John McCall7f416cc2015-09-08 08:05:57 +00001704 Address NewAtomicAddr = CreateTempAlloca();
1705 Address NewAtomicIntAddr = emitCastToAtomicIntPointer(NewAtomicAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001706 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
John McCall7f416cc2015-09-08 08:05:57 +00001707 requiresMemSetZero(getAtomicAddress().getElementType())) {
1708 CGF.Builder.CreateStore(PHI, NewAtomicIntAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001709 }
1710 EmitAtomicUpdateValue(CGF, *this, UpdateRVal, NewAtomicAddr);
John McCall7f416cc2015-09-08 08:05:57 +00001711 auto *DesiredVal = CGF.Builder.CreateLoad(NewAtomicIntAddr);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001712 // Try to write new value using cmpxchg operation
1713 auto Res = EmitAtomicCompareExchangeOp(PHI, DesiredVal, AO, Failure);
1714 PHI->addIncoming(Res.first, CGF.Builder.GetInsertBlock());
1715 CGF.Builder.CreateCondBr(Res.second, ExitBB, ContBB);
1716 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1717}
1718
1719void AtomicInfo::EmitAtomicUpdate(
1720 llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1721 bool IsVolatile) {
1722 if (shouldUseLibcall()) {
1723 EmitAtomicUpdateLibcall(AO, UpdateOp, IsVolatile);
1724 } else {
1725 EmitAtomicUpdateOp(AO, UpdateOp, IsVolatile);
1726 }
1727}
1728
1729void AtomicInfo::EmitAtomicUpdate(llvm::AtomicOrdering AO, RValue UpdateRVal,
1730 bool IsVolatile) {
1731 if (shouldUseLibcall()) {
1732 EmitAtomicUpdateLibcall(AO, UpdateRVal, IsVolatile);
1733 } else {
1734 EmitAtomicUpdateOp(AO, UpdateRVal, IsVolatile);
1735 }
Alexey Bataevb8329262015-02-27 06:33:30 +00001736}
1737
David Majnemera5b195a2015-02-14 01:35:12 +00001738void CodeGenFunction::EmitAtomicStore(RValue rvalue, LValue lvalue,
1739 bool isInit) {
1740 bool IsVolatile = lvalue.isVolatileQualified();
1741 llvm::AtomicOrdering AO;
1742 if (lvalue.getType()->isAtomicType()) {
1743 AO = llvm::SequentiallyConsistent;
1744 } else {
1745 AO = llvm::Release;
1746 IsVolatile = true;
1747 }
1748 return EmitAtomicStore(rvalue, lvalue, AO, IsVolatile, isInit);
1749}
1750
John McCalla8ec7eb2013-03-07 21:37:17 +00001751/// Emit a store to an l-value of atomic type.
1752///
1753/// Note that the r-value is expected to be an r-value *of the atomic
1754/// type*; this means that for aggregate r-values, it should include
1755/// storage for any padding that was necessary.
David Majnemera5b195a2015-02-14 01:35:12 +00001756void CodeGenFunction::EmitAtomicStore(RValue rvalue, LValue dest,
1757 llvm::AtomicOrdering AO, bool IsVolatile,
1758 bool isInit) {
John McCalla8ec7eb2013-03-07 21:37:17 +00001759 // If this is an aggregate r-value, it should agree in type except
1760 // maybe for address-space qualification.
1761 assert(!rvalue.isAggregate() ||
John McCall7f416cc2015-09-08 08:05:57 +00001762 rvalue.getAggregateAddress().getElementType()
1763 == dest.getAddress().getElementType());
John McCalla8ec7eb2013-03-07 21:37:17 +00001764
1765 AtomicInfo atomics(*this, dest);
Alexey Bataevb8329262015-02-27 06:33:30 +00001766 LValue LVal = atomics.getAtomicLValue();
John McCalla8ec7eb2013-03-07 21:37:17 +00001767
1768 // If this is an initialization, just put the value there normally.
Alexey Bataevb8329262015-02-27 06:33:30 +00001769 if (LVal.isSimple()) {
1770 if (isInit) {
1771 atomics.emitCopyIntoMemory(rvalue);
1772 return;
1773 }
1774
1775 // Check whether we should use a library call.
1776 if (atomics.shouldUseLibcall()) {
1777 // Produce a source address.
John McCall7f416cc2015-09-08 08:05:57 +00001778 Address srcAddr = atomics.materializeRValue(rvalue);
Alexey Bataevb8329262015-02-27 06:33:30 +00001779
1780 // void __atomic_store(size_t size, void *mem, void *val, int order)
1781 CallArgList args;
1782 args.add(RValue::get(atomics.getAtomicSizeValue()),
1783 getContext().getSizeType());
John McCall7f416cc2015-09-08 08:05:57 +00001784 args.add(RValue::get(EmitCastToVoidPtr(atomics.getAtomicPointer())),
Alexey Bataevb8329262015-02-27 06:33:30 +00001785 getContext().VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +00001786 args.add(RValue::get(EmitCastToVoidPtr(srcAddr.getPointer())),
1787 getContext().VoidPtrTy);
Alexey Bataevb8329262015-02-27 06:33:30 +00001788 args.add(RValue::get(llvm::ConstantInt::get(
1789 IntTy, AtomicInfo::translateAtomicOrdering(AO))),
1790 getContext().IntTy);
1791 emitAtomicLibcall(*this, "__atomic_store", getContext().VoidTy, args);
1792 return;
1793 }
1794
1795 // Okay, we're doing this natively.
1796 llvm::Value *intValue = atomics.convertRValueToInt(rvalue);
1797
1798 // Do the atomic store.
John McCall7f416cc2015-09-08 08:05:57 +00001799 Address addr =
Alexey Bataevb8329262015-02-27 06:33:30 +00001800 atomics.emitCastToAtomicIntPointer(atomics.getAtomicAddress());
1801 intValue = Builder.CreateIntCast(
John McCall7f416cc2015-09-08 08:05:57 +00001802 intValue, addr.getElementType(), /*isSigned=*/false);
Alexey Bataevb8329262015-02-27 06:33:30 +00001803 llvm::StoreInst *store = Builder.CreateStore(intValue, addr);
1804
1805 // Initializations don't need to be atomic.
1806 if (!isInit)
1807 store->setAtomic(AO);
1808
1809 // Other decoration.
Alexey Bataevb8329262015-02-27 06:33:30 +00001810 if (IsVolatile)
1811 store->setVolatile(true);
1812 if (dest.getTBAAInfo())
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001813 CGM.DecorateInstructionWithTBAA(store, dest.getTBAAInfo());
John McCalla8ec7eb2013-03-07 21:37:17 +00001814 return;
1815 }
1816
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001817 // Emit simple atomic update operation.
1818 atomics.EmitAtomicUpdate(AO, rvalue, IsVolatile);
John McCalla8ec7eb2013-03-07 21:37:17 +00001819}
1820
Alexey Bataev452d8e12014-12-15 05:25:25 +00001821/// Emit a compare-and-exchange op for atomic type.
1822///
Alexey Bataevb4505a72015-03-30 05:20:59 +00001823std::pair<RValue, llvm::Value *> CodeGenFunction::EmitAtomicCompareExchange(
Alexey Bataev452d8e12014-12-15 05:25:25 +00001824 LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
1825 llvm::AtomicOrdering Success, llvm::AtomicOrdering Failure, bool IsWeak,
1826 AggValueSlot Slot) {
1827 // If this is an aggregate r-value, it should agree in type except
1828 // maybe for address-space qualification.
1829 assert(!Expected.isAggregate() ||
John McCall7f416cc2015-09-08 08:05:57 +00001830 Expected.getAggregateAddress().getElementType() ==
1831 Obj.getAddress().getElementType());
Alexey Bataev452d8e12014-12-15 05:25:25 +00001832 assert(!Desired.isAggregate() ||
John McCall7f416cc2015-09-08 08:05:57 +00001833 Desired.getAggregateAddress().getElementType() ==
1834 Obj.getAddress().getElementType());
Alexey Bataev452d8e12014-12-15 05:25:25 +00001835 AtomicInfo Atomics(*this, Obj);
1836
Alexey Bataevb4505a72015-03-30 05:20:59 +00001837 return Atomics.EmitAtomicCompareExchange(Expected, Desired, Success, Failure,
1838 IsWeak);
1839}
1840
1841void CodeGenFunction::EmitAtomicUpdate(
1842 LValue LVal, llvm::AtomicOrdering AO,
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001843 const llvm::function_ref<RValue(RValue)> &UpdateOp, bool IsVolatile) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00001844 AtomicInfo Atomics(*this, LVal);
Alexey Bataevf0ab5532015-05-15 08:36:34 +00001845 Atomics.EmitAtomicUpdate(AO, UpdateOp, IsVolatile);
Alexey Bataev452d8e12014-12-15 05:25:25 +00001846}
1847
John McCalla8ec7eb2013-03-07 21:37:17 +00001848void CodeGenFunction::EmitAtomicInit(Expr *init, LValue dest) {
1849 AtomicInfo atomics(*this, dest);
1850
1851 switch (atomics.getEvaluationKind()) {
1852 case TEK_Scalar: {
1853 llvm::Value *value = EmitScalarExpr(init);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001854 atomics.emitCopyIntoMemory(RValue::get(value));
John McCalla8ec7eb2013-03-07 21:37:17 +00001855 return;
1856 }
1857
1858 case TEK_Complex: {
1859 ComplexPairTy value = EmitComplexExpr(init);
Alexey Bataevb57056f2015-01-22 06:17:56 +00001860 atomics.emitCopyIntoMemory(RValue::getComplex(value));
John McCalla8ec7eb2013-03-07 21:37:17 +00001861 return;
1862 }
1863
1864 case TEK_Aggregate: {
Eli Friedmanbe4504d2013-07-11 01:32:21 +00001865 // Fix up the destination if the initializer isn't an expression
1866 // of atomic type.
1867 bool Zeroed = false;
John McCalla8ec7eb2013-03-07 21:37:17 +00001868 if (!init->getType()->isAtomicType()) {
Alexey Bataevb57056f2015-01-22 06:17:56 +00001869 Zeroed = atomics.emitMemSetZeroIfNecessary();
1870 dest = atomics.projectValue();
John McCalla8ec7eb2013-03-07 21:37:17 +00001871 }
1872
1873 // Evaluate the expression directly into the destination.
1874 AggValueSlot slot = AggValueSlot::forLValue(dest,
1875 AggValueSlot::IsNotDestructed,
1876 AggValueSlot::DoesNotNeedGCBarriers,
Eli Friedmanbe4504d2013-07-11 01:32:21 +00001877 AggValueSlot::IsNotAliased,
1878 Zeroed ? AggValueSlot::IsZeroed :
1879 AggValueSlot::IsNotZeroed);
1880
John McCalla8ec7eb2013-03-07 21:37:17 +00001881 EmitAggExpr(init, slot);
1882 return;
1883 }
1884 }
1885 llvm_unreachable("bad evaluation kind");
1886}