1 //===-- Atomic.cpp - Atomic Operations --------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements atomic operations.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Support/Atomic.h"
15 #include "llvm/Config/llvm-config.h"
25 #if defined(__GNUC__) || (defined(__IBMCPP__) && __IBMCPP__ >= 1210)
29 void sys::MemoryFence() {
30 #if LLVM_HAS_ATOMICS == 0
33 # if defined(GNU_ATOMICS)
35 # elif defined(_MSC_VER)
38 # error No memory fence implementation for your platform!
43 sys::cas_flag sys::CompareAndSwap(volatile sys::cas_flag* ptr,
44 sys::cas_flag new_value,
45 sys::cas_flag old_value) {
46 #if LLVM_HAS_ATOMICS == 0
47 sys::cas_flag result = *ptr;
48 if (result == old_value)
51 #elif defined(GNU_ATOMICS)
52 return __sync_val_compare_and_swap(ptr, old_value, new_value);
53 #elif defined(_MSC_VER)
54 return InterlockedCompareExchange(ptr, new_value, old_value);
56 # error No compare-and-swap implementation for your platform!
60 sys::cas_flag sys::AtomicIncrement(volatile sys::cas_flag* ptr) {
61 #if LLVM_HAS_ATOMICS == 0
64 #elif defined(GNU_ATOMICS)
65 return __sync_add_and_fetch(ptr, 1);
66 #elif defined(_MSC_VER)
67 return InterlockedIncrement(ptr);
69 # error No atomic increment implementation for your platform!
73 sys::cas_flag sys::AtomicDecrement(volatile sys::cas_flag* ptr) {
74 #if LLVM_HAS_ATOMICS == 0
77 #elif defined(GNU_ATOMICS)
78 return __sync_sub_and_fetch(ptr, 1);
79 #elif defined(_MSC_VER)
80 return InterlockedDecrement(ptr);
82 # error No atomic decrement implementation for your platform!
86 sys::cas_flag sys::AtomicAdd(volatile sys::cas_flag* ptr, sys::cas_flag val) {
87 #if LLVM_HAS_ATOMICS == 0
90 #elif defined(GNU_ATOMICS)
91 return __sync_add_and_fetch(ptr, val);
92 #elif defined(_MSC_VER)
93 return InterlockedExchangeAdd(ptr, val) + val;
95 # error No atomic add implementation for your platform!
99 sys::cas_flag sys::AtomicMul(volatile sys::cas_flag* ptr, sys::cas_flag val) {
100 sys::cas_flag original, result;
103 result = original * val;
104 } while (sys::CompareAndSwap(ptr, result, original) != original);
109 sys::cas_flag sys::AtomicDiv(volatile sys::cas_flag* ptr, sys::cas_flag val) {
110 sys::cas_flag original, result;
113 result = original / val;
114 } while (sys::CompareAndSwap(ptr, result, original) != original);