Short live Q_CONSTINIT!

It expands to the first available of

- constinit (C++20)
- [[clang::require_constant_initialization]] (Clang)
- __constinit (GCC >= 10)

Use it around the code (on and near static QBasicAtomic; this patch
makes no attempt to find all statics in qtbase).

[ChangeLog][QtCore][QtGlobal] Added macro Q_CONSTINIT.

Fixes: QTBUG-100484
Change-Id: I11e0363a7acb3464476859d12ec7f94319d82be7
Reviewed-by: Thiago Macieira <thiago.macieira@intel.com>
Reviewed-by: Qt CI Bot <qt_ci_bot@qt-project.org>
This commit is contained in:
Marc Mutz 2022-01-31 17:19:06 +01:00
parent edb64351cd
commit 80b6bcc385
30 changed files with 121 additions and 84 deletions

View File

@ -289,7 +289,7 @@ void QPropertyAnimation::updateState(QAbstractAnimation::State newState,
QPropertyAnimation *animToStop = nullptr;
{
static QBasicMutex mutex;
Q_CONSTINIT static QBasicMutex mutex;
auto locker = qt_unique_lock(mutex);
typedef QPair<QObject *, QByteArray> QPropertyAnimationPair;
typedef QHash<QPropertyAnimationPair, QPropertyAnimation*> QPropertyAnimationHash;

View File

@ -404,7 +404,7 @@ QBindable<QEasingCurve> QVariantAnimation::bindableEasingCurve()
typedef QList<QVariantAnimation::Interpolator> QInterpolatorVector;
Q_GLOBAL_STATIC(QInterpolatorVector, registeredInterpolators)
static QBasicMutex registeredInterpolatorsMutex;
Q_CONSTINIT static QBasicMutex registeredInterpolatorsMutex;
/*!
\fn template <typename T> void qRegisterAnimationInterpolator(QVariant (*func)(const T &from, const T &to, qreal progress))

View File

@ -3344,7 +3344,7 @@ Q_CORE_EXPORT Q_DECL_CONST_FUNCTION unsigned int qt_int_sqrt(unsigned int n)
// In the C runtime on all platforms access to the environment is not thread-safe. We
// add thread-safety for the Qt wrappers.
static QBasicMutex environmentMutex;
Q_CONSTINIT static QBasicMutex environmentMutex;
/*
Wraps tzset(), which accesses the environment, so should only be called while
@ -4114,6 +4114,33 @@ bool qunsetenv(const char *varName)
\sa Q_LIKELY()
*/
/*!
\macro Q_CONSTINIT
\relates <QtGlobal>
\since 6.4
\brief Enforces constant initialization when supported by the compiler.
If the compiler supports the C++20 \c{constinit} keyword, Clang's
\c{[[clang::require_constant_initialization]]} or GCC's \c{__constinit},
then this macro expands to the first one of these that is available,
otherwise it expands to nothing.
Variables marked as \c{constinit} cause a compile-error if their
initialization would have to be performed at runtime.
For constants, you can use \c{constexpr} since C++11, but \c{constexpr}
makes variables \c{const}, too, whereas \c{constinit} ensures constant
initialization, but doesn't make the variable \c{const}:
\table
\header \li Keyword \li Added \li immutable \li constant-initialized
\row \li \c{const} \li C++98 \li yes \li not required
\row \li \c{constexpr} \li C++11 \li yes \li required
\row \li \c{constinit} \li C++20 \li no \li required
\endtable
*/
/*!
\macro QT_POINTER_SIZE
\relates <QtGlobal>

View File

@ -1165,6 +1165,16 @@ constexpr std::underlying_type_t<Enum> qToUnderlying(Enum e) noexcept
#define Q_IMPLICIT
#endif
#ifdef __cpp_constinit
# define Q_CONSTINIT constinit
#elif defined(__has_cpp_attribute) && __has_cpp_attribute(clang::require_constant_initialization)
# define Q_CONSTINIT [[clang::require_constant_initialization]]
#elif defined(Q_CC_GNU) && Q_CC_GNU >= 1000
# define Q_CONSTINIT __constinit
#else
# define Q_CONSTINIT
#endif
template <typename T> inline T *qGetPtrHelper(T *ptr) noexcept { return ptr; }
template <typename Ptr> inline auto qGetPtrHelper(Ptr &ptr) noexcept -> decltype(ptr.get())
{ static_assert(noexcept(ptr.get()), "Smart d pointers for Q_DECLARE_PRIVATE must have noexcept get()"); return ptr.get(); }

View File

@ -63,7 +63,7 @@ template <typename QGS> union Holder
using PlainType = std::remove_cv_t<Type>;
static constexpr bool ConstructionIsNoexcept = noexcept(QGS::innerFunction(nullptr));
static inline QBasicAtomicInteger<qint8> guard = { QtGlobalStatic::Uninitialized };
Q_CONSTINIT static inline QBasicAtomicInteger<qint8> guard = { QtGlobalStatic::Uninitialized };
// union's sole member
PlainType storage;
@ -144,7 +144,7 @@ protected:
new (pointer) QGS_Type ARGS; \
} \
}; } \
static QGlobalStatic<QtGlobalStatic::Holder<Q_QGS_ ## NAME>> NAME; \
Q_CONSTINIT static QGlobalStatic<QtGlobalStatic::Holder<Q_QGS_ ## NAME>> NAME; \
QT_WARNING_POP
/**/

View File

@ -1096,7 +1096,7 @@ struct QMessagePattern
Q_DECLARE_TYPEINFO(QMessagePattern::BacktraceParams, Q_RELOCATABLE_TYPE);
#endif
QBasicMutex QMessagePattern::mutex;
Q_CONSTINIT QBasicMutex QMessagePattern::mutex;
QMessagePattern::QMessagePattern()
{
@ -1750,7 +1750,7 @@ static bool android_default_message_handler(QtMsgType type,
static void win_outputDebugString_helper(const QString &message)
{
const qsizetype maxOutputStringLength = 32766;
static QBasicMutex m;
Q_CONSTINIT static QBasicMutex m;
auto locker = qt_unique_lock(m);
// fast path: Avoid string copies if one output is enough
if (message.length() <= maxOutputStringLength) {
@ -1827,7 +1827,7 @@ static void stderr_message_handler(QtMsgType type, const QMessageLogContext &con
#ifdef Q_OS_WASM
// Prevent thread cross-talk, which causes Emscripten to log
// non-valid UTF-8. FIXME: remove once we upgrade to emsdk > 2.0.30
static QBasicMutex m;
Q_CONSTINIT static QBasicMutex m;
auto locker = qt_unique_lock(m);
#endif

View File

@ -58,7 +58,7 @@ using namespace Qt::StringLiterals;
static const char env_override[] = "QT_NO_BUILTIN_SELECTORS";
Q_GLOBAL_STATIC(QFileSelectorSharedData, sharedData);
static QBasicMutex sharedDataMutex;
Q_CONSTINIT static QBasicMutex sharedDataMutex;
QFileSelectorPrivate::QFileSelectorPrivate()
: QObjectPrivate()

View File

@ -424,7 +424,7 @@ static QString resolveExecutable(const QString &program)
{
// CFBundle is not reentrant, since CFBundleCreate might return a reference
// to a cached bundle object. Protect the bundle calls with a mutex lock.
static QBasicMutex cfbundleMutex;
Q_CONSTINIT static QBasicMutex cfbundleMutex;
const auto locker = qt_scoped_lock(cfbundleMutex);
QCFType<CFBundleRef> bundle = CFBundleCreate(0, url);
// 'executableURL' can be either relative or absolute ...

View File

@ -132,7 +132,7 @@ Q_GLOBAL_STATIC(ConfFileCache, unusedCacheFunc)
Q_GLOBAL_STATIC(PathHash, pathHashFunc)
Q_GLOBAL_STATIC(CustomFormatVector, customFormatVectorFunc)
static QBasicMutex settingsGlobalMutex;
Q_CONSTINIT static QBasicMutex settingsGlobalMutex;
static QSettings::Format globalDefaultFormat = QSettings::NativeFormat;

View File

@ -265,8 +265,8 @@ typedef QList<QtStartUpFunction> QStartUpFuncList;
Q_GLOBAL_STATIC(QStartUpFuncList, preRList)
typedef QList<QtCleanUpFunction> QVFuncList;
Q_GLOBAL_STATIC(QVFuncList, postRList)
static QBasicMutex globalRoutinesMutex;
static bool preRoutinesCalled = false;
Q_CONSTINIT static QBasicMutex globalRoutinesMutex;
Q_CONSTINIT static bool preRoutinesCalled = false;
/*!
\internal

View File

@ -296,7 +296,7 @@ QEventDispatcherGlibPrivate::QEventDispatcherGlibPrivate(GMainContext *context)
{
#if GLIB_MAJOR_VERSION == 2 && GLIB_MINOR_VERSION < 32
if (qEnvironmentVariableIsEmpty("QT_NO_THREADED_GLIB")) {
static QBasicMutex mutex;
Q_CONSTINIT static QBasicMutex mutex;
QMutexLocker locker(&mutex);
if (!g_thread_supported())
g_thread_init(NULL);

View File

@ -149,7 +149,7 @@ static int *queuedConnectionTypes(const QArgumentType *argumentTypes, int argc)
return types.release();
}
static QBasicMutex _q_ObjectMutexPool[131];
Q_CONSTINIT static QBasicMutex _q_ObjectMutexPool[131];
/**
* \internal

View File

@ -354,9 +354,9 @@ private:
LibraryMap libraryMap;
};
static QBasicMutex qt_library_mutex;
static QLibraryStore *qt_library_data = nullptr;
static bool qt_library_data_once;
Q_CONSTINIT static QBasicMutex qt_library_mutex;
Q_CONSTINIT static QLibraryStore *qt_library_data = nullptr;
Q_CONSTINIT static bool qt_library_data_once;
QLibraryStore::~QLibraryStore()
{

View File

@ -792,7 +792,7 @@ static const QLocaleData *systemData()
one thread.
*/
{
static QBasicMutex systemDataMutex;
Q_CONSTINIT static QBasicMutex systemDataMutex;
systemDataMutex.lock();
if (systemLocaleData.m_language_id == 0)
updateSystemPrivate();

View File

@ -501,8 +501,8 @@ QThreadPool::~QThreadPool()
*/
QThreadPool *QThreadPool::globalInstance()
{
static QPointer<QThreadPool> theInstance;
static QBasicMutex theMutex;
Q_CONSTINIT static QPointer<QThreadPool> theInstance;
Q_CONSTINIT static QBasicMutex theMutex;
const QMutexLocker locker(&theMutex);
if (theInstance.isNull() && !QCoreApplication::closingDown())

View File

@ -68,7 +68,7 @@ void qtsDebug(const char *fmt, ...)
# define DEBUG_MSG if (false)qDebug
#endif
static QBasicMutex destructorsMutex;
Q_CONSTINIT static QBasicMutex destructorsMutex;
typedef QList<void (*)(void *)> DestructorMap;
Q_GLOBAL_STATIC(DestructorMap, destructors)

View File

@ -67,7 +67,7 @@ QT_BEGIN_NAMESPACE
using namespace Qt::StringLiterals;
#if QT_CONFIG(icu)
static QBasicMutex s_icu_mutex;
Q_CONSTINIT static QBasicMutex s_icu_mutex;
#endif
/*

View File

@ -79,8 +79,8 @@ bool qdbus_loadLibDBus()
return false;
#endif
static bool triedToLoadLibrary = false;
static QBasicMutex mutex;
Q_CONSTINIT static bool triedToLoadLibrary = false;
Q_CONSTINIT static QBasicMutex mutex;
const auto locker = qt_scoped_lock(mutex);
QLibrary *&lib = qdbus_libdbus;

View File

@ -1991,14 +1991,14 @@ public:
#if defined(QT_NO_DEBUG)
// when in a release build, we default these to off.
// this means that we only affect code that explicitly enables the warning.
static int mainThreadWarningAmount = -1;
static int otherThreadWarningAmount = -1;
Q_CONSTINIT static int mainThreadWarningAmount = -1;
Q_CONSTINIT static int otherThreadWarningAmount = -1;
#else
static int mainThreadWarningAmount = 200;
static int otherThreadWarningAmount = 500;
Q_CONSTINIT static int mainThreadWarningAmount = 200;
Q_CONSTINIT static int otherThreadWarningAmount = 500;
#endif
static bool initializedAmounts = false;
static QBasicMutex initializeMutex;
Q_CONSTINIT static bool initializedAmounts = false;
Q_CONSTINIT static QBasicMutex initializeMutex;
auto locker = qt_unique_lock(initializeMutex);
if (!initializedAmounts) {

View File

@ -144,8 +144,8 @@ static int registerComplexDBusType(const QByteArray &typeName)
{}
};
static QBasicMutex mutex;
static struct Hash : QHash<QByteArray, QMetaType>
Q_CONSTINIT static QBasicMutex mutex;
Q_CONSTINIT static struct Hash : QHash<QByteArray, QMetaType>
{
~Hash()
{

View File

@ -186,7 +186,7 @@ static QImageIOHandler *createReadHandlerHelper(QIODevice *device,
QByteArray suffix;
#ifndef QT_NO_IMAGEFORMATPLUGIN
static QBasicMutex mutex;
Q_CONSTINIT static QBasicMutex mutex;
const auto locker = qt_scoped_lock(mutex);
typedef QMultiMap<int, QString> PluginKeyMap;

View File

@ -145,79 +145,79 @@ QT_BEGIN_NAMESPACE
Q_CORE_EXPORT void qt_call_post_routines();
Q_GUI_EXPORT bool qt_is_tty_app = false;
Qt::MouseButtons QGuiApplicationPrivate::mouse_buttons = Qt::NoButton;
Qt::KeyboardModifiers QGuiApplicationPrivate::modifier_buttons = Qt::NoModifier;
Q_CONSTINIT Qt::MouseButtons QGuiApplicationPrivate::mouse_buttons = Qt::NoButton;
Q_CONSTINIT Qt::KeyboardModifiers QGuiApplicationPrivate::modifier_buttons = Qt::NoModifier;
QGuiApplicationPrivate::QLastCursorPosition QGuiApplicationPrivate::lastCursorPosition;
Q_CONSTINIT QGuiApplicationPrivate::QLastCursorPosition QGuiApplicationPrivate::lastCursorPosition;
QWindow *QGuiApplicationPrivate::currentMouseWindow = nullptr;
Q_CONSTINIT QWindow *QGuiApplicationPrivate::currentMouseWindow = nullptr;
QString QGuiApplicationPrivate::styleOverride;
Q_CONSTINIT QString QGuiApplicationPrivate::styleOverride;
Qt::ApplicationState QGuiApplicationPrivate::applicationState = Qt::ApplicationInactive;
Q_CONSTINIT Qt::ApplicationState QGuiApplicationPrivate::applicationState = Qt::ApplicationInactive;
Qt::HighDpiScaleFactorRoundingPolicy QGuiApplicationPrivate::highDpiScaleFactorRoundingPolicy =
Q_CONSTINIT Qt::HighDpiScaleFactorRoundingPolicy QGuiApplicationPrivate::highDpiScaleFactorRoundingPolicy =
Qt::HighDpiScaleFactorRoundingPolicy::PassThrough;
QPointer<QWindow> QGuiApplicationPrivate::currentDragWindow;
Q_CONSTINIT QPointer<QWindow> QGuiApplicationPrivate::currentDragWindow;
QList<QGuiApplicationPrivate::TabletPointData> QGuiApplicationPrivate::tabletDevicePoints; // TODO remove
Q_CONSTINIT QList<QGuiApplicationPrivate::TabletPointData> QGuiApplicationPrivate::tabletDevicePoints; // TODO remove
QPlatformIntegration *QGuiApplicationPrivate::platform_integration = nullptr;
QPlatformTheme *QGuiApplicationPrivate::platform_theme = nullptr;
Q_CONSTINIT QPlatformIntegration *QGuiApplicationPrivate::platform_integration = nullptr;
Q_CONSTINIT QPlatformTheme *QGuiApplicationPrivate::platform_theme = nullptr;
QList<QObject *> QGuiApplicationPrivate::generic_plugin_list;
Q_CONSTINIT QList<QObject *> QGuiApplicationPrivate::generic_plugin_list;
enum ApplicationResourceFlags
{
ApplicationFontExplicitlySet = 0x2
};
static unsigned applicationResourceFlags = 0;
Q_CONSTINIT static unsigned applicationResourceFlags = 0;
QIcon *QGuiApplicationPrivate::app_icon = nullptr;
Q_CONSTINIT QIcon *QGuiApplicationPrivate::app_icon = nullptr;
QString *QGuiApplicationPrivate::platform_name = nullptr;
QString *QGuiApplicationPrivate::displayName = nullptr;
QString *QGuiApplicationPrivate::desktopFileName = nullptr;
Q_CONSTINIT QString *QGuiApplicationPrivate::platform_name = nullptr;
Q_CONSTINIT QString *QGuiApplicationPrivate::displayName = nullptr;
Q_CONSTINIT QString *QGuiApplicationPrivate::desktopFileName = nullptr;
QPalette *QGuiApplicationPrivate::app_pal = nullptr; // default application palette
Q_CONSTINIT QPalette *QGuiApplicationPrivate::app_pal = nullptr; // default application palette
Qt::MouseButton QGuiApplicationPrivate::mousePressButton = Qt::NoButton;
Q_CONSTINIT Qt::MouseButton QGuiApplicationPrivate::mousePressButton = Qt::NoButton;
static int mouseDoubleClickDistance = 0;
static int touchDoubleTapDistance = 0;
Q_CONSTINIT static int mouseDoubleClickDistance = 0;
Q_CONSTINIT static int touchDoubleTapDistance = 0;
QWindow *QGuiApplicationPrivate::currentMousePressWindow = nullptr;
Q_CONSTINIT QWindow *QGuiApplicationPrivate::currentMousePressWindow = nullptr;
static Qt::LayoutDirection layout_direction = Qt::LayoutDirectionAuto;
static Qt::LayoutDirection effective_layout_direction = Qt::LeftToRight;
static bool force_reverse = false;
Q_CONSTINIT static Qt::LayoutDirection layout_direction = Qt::LayoutDirectionAuto;
Q_CONSTINIT static Qt::LayoutDirection effective_layout_direction = Qt::LeftToRight;
Q_CONSTINIT static bool force_reverse = false;
QGuiApplicationPrivate *QGuiApplicationPrivate::self = nullptr;
int QGuiApplicationPrivate::m_fakeMouseSourcePointId = -1;
Q_CONSTINIT QGuiApplicationPrivate *QGuiApplicationPrivate::self = nullptr;
Q_CONSTINIT int QGuiApplicationPrivate::m_fakeMouseSourcePointId = -1;
#ifndef QT_NO_CLIPBOARD
QClipboard *QGuiApplicationPrivate::qt_clipboard = nullptr;
Q_CONSTINIT QClipboard *QGuiApplicationPrivate::qt_clipboard = nullptr;
#endif
QList<QScreen *> QGuiApplicationPrivate::screen_list;
Q_CONSTINIT QList<QScreen *> QGuiApplicationPrivate::screen_list;
QWindowList QGuiApplicationPrivate::window_list;
QWindow *QGuiApplicationPrivate::focus_window = nullptr;
Q_CONSTINIT QWindowList QGuiApplicationPrivate::window_list;
Q_CONSTINIT QWindow *QGuiApplicationPrivate::focus_window = nullptr;
static QBasicMutex applicationFontMutex;
QFont *QGuiApplicationPrivate::app_font = nullptr;
QStyleHints *QGuiApplicationPrivate::styleHints = nullptr;
bool QGuiApplicationPrivate::obey_desktop_settings = true;
Q_CONSTINIT static QBasicMutex applicationFontMutex;
Q_CONSTINIT QFont *QGuiApplicationPrivate::app_font = nullptr;
Q_CONSTINIT QStyleHints *QGuiApplicationPrivate::styleHints = nullptr;
Q_CONSTINIT bool QGuiApplicationPrivate::obey_desktop_settings = true;
QInputDeviceManager *QGuiApplicationPrivate::m_inputDeviceManager = nullptr;
Q_CONSTINIT QInputDeviceManager *QGuiApplicationPrivate::m_inputDeviceManager = nullptr;
qreal QGuiApplicationPrivate::m_maxDevicePixelRatio = 0.0;
Q_CONSTINIT qreal QGuiApplicationPrivate::m_maxDevicePixelRatio = 0.0;
static qreal fontSmoothingGamma = 1.7;
Q_CONSTINIT static qreal fontSmoothingGamma = 1.7;
bool QGuiApplicationPrivate::quitOnLastWindowClosed = true;
Q_CONSTINIT bool QGuiApplicationPrivate::quitOnLastWindowClosed = true;
extern void qRegisterGuiVariant();
#if QT_CONFIG(animation)

View File

@ -264,7 +264,7 @@ QString QInputDevice::seatName() const
using InputDevicesList = QList<const QInputDevice *>;
Q_GLOBAL_STATIC(InputDevicesList, deviceList)
static QBasicMutex devicesMutex;
Q_CONSTINIT static QBasicMutex devicesMutex;
/*!
Returns a list of all registered input devices (keyboards and pointing devices).

View File

@ -54,7 +54,7 @@
QT_BEGIN_NAMESPACE
QBasicMutex QColorSpacePrivate::s_lutWriteLock;
Q_CONSTINIT QBasicMutex QColorSpacePrivate::s_lutWriteLock;
static QAtomicPointer<QColorSpacePrivate> s_predefinedColorspacePrivates[QColorSpace::ProPhotoRgb] = {};
static void cleanupPredefinedColorspaces()

View File

@ -1714,7 +1714,7 @@ QNetworkRequest QNetworkAccessManagerPrivate::prepareMultipart(const QNetworkReq
*/
void QNetworkAccessManagerPrivate::ensureBackendPluginsLoaded()
{
static QBasicMutex mutex;
Q_CONSTINIT static QBasicMutex mutex;
std::unique_lock locker(mutex);
if (!loader())
return;

View File

@ -1574,7 +1574,7 @@ static PSecurityFunctionTableW pSecurityFunctionTable = nullptr;
static bool q_SSPI_library_load()
{
static QBasicMutex mutex;
Q_CONSTINIT static QBasicMutex mutex;
QMutexLocker l(&mutex);
if (pSecurityFunctionTable == nullptr)

View File

@ -124,7 +124,7 @@ bool QNetworkInformationPrivate::initializeList()
return false;
if (!dataHolder())
return false;
static QBasicMutex mutex;
Q_CONSTINIT static QBasicMutex mutex;
QMutexLocker initLocker(&mutex);
#if QT_CONFIG(library)

View File

@ -91,7 +91,7 @@ public:
if (!loader())
return false;
static QBasicMutex mutex;
Q_CONSTINIT static QBasicMutex mutex;
const QMutexLocker locker(&mutex);
if (backends.size())
return true;

View File

@ -47,8 +47,8 @@
QT_BEGIN_NAMESPACE
static QBasicMutex qAppExiting;
static bool dispatcherOwnerDestructing = false;
Q_CONSTINIT static QBasicMutex qAppExiting;
Q_CONSTINIT static bool dispatcherOwnerDestructing = false;
/*!
\class QXcbEventQueue

View File

@ -868,9 +868,9 @@ static LoadedOpenSsl loadOpenSsl()
}
#endif
static QBasicMutex symbolResolveMutex;
static QBasicAtomicInt symbolsResolved = Q_BASIC_ATOMIC_INITIALIZER(false);
static bool triedToResolveSymbols = false;
Q_CONSTINIT static QBasicMutex symbolResolveMutex;
Q_CONSTINIT static QBasicAtomicInt symbolsResolved = Q_BASIC_ATOMIC_INITIALIZER(false);
Q_CONSTINIT static bool triedToResolveSymbols = false;
bool q_resolveOpenSslSymbols()
{