diff --git a/lld/MachO/Writer.cpp b/lld/MachO/Writer.cpp --- a/lld/MachO/Writer.cpp +++ b/lld/MachO/Writer.cpp @@ -1130,11 +1130,10 @@ createLoadCommands(); finalizeAddresses(); threadPool.async([&] { - if (LLVM_ENABLE_THREADS && config->timeTraceEnabled) - timeTraceProfilerInitialize(config->timeTraceGranularity, "writeMapFile"); + TimeTraceProfilerThreadScope profilerScope( + LLVM_ENABLE_THREADS && config->timeTraceEnabled, + config->timeTraceGranularity, "writeMapFile"); writeMapFile(); - if (LLVM_ENABLE_THREADS && config->timeTraceEnabled) - timeTraceProfilerFinishThread(); }); finalizeLinkEditSegment(); writeOutputFile(); diff --git a/llvm/include/llvm/Support/TimeProfiler.h b/llvm/include/llvm/Support/TimeProfiler.h --- a/llvm/include/llvm/Support/TimeProfiler.h +++ b/llvm/include/llvm/Support/TimeProfiler.h @@ -31,6 +31,32 @@ /// Finish a time trace profiler running on a worker thread. void timeTraceProfilerFinishThread(); +/// Initialize and clean up the profiler on a worker thread using RAII. +struct TimeTraceProfilerThreadScope { + TimeTraceProfilerThreadScope() = delete; + TimeTraceProfilerThreadScope(const TimeTraceProfilerThreadScope &) = delete; + TimeTraceProfilerThreadScope & + operator=(const TimeTraceProfilerThreadScope &) = delete; + TimeTraceProfilerThreadScope(TimeTraceProfilerThreadScope &&) = delete; + TimeTraceProfilerThreadScope & + operator=(TimeTraceProfilerThreadScope &&) = delete; + + TimeTraceProfilerThreadScope(bool Enable, unsigned TimeTraceGranularity, + StringRef ProcName) + : Enable(Enable) { + if (Enable) + timeTraceProfilerInitialize(TimeTraceGranularity, ProcName); + } + + ~TimeTraceProfilerThreadScope() { + if (Enable) + timeTraceProfilerFinishThread(); + } + +private: + bool Enable; +}; + /// Is the time trace profiler enabled, i.e. initialized? inline bool timeTraceProfilerEnabled() { return getTimeTraceProfilerInstance() != nullptr; diff --git a/llvm/lib/LTO/LTO.cpp b/llvm/lib/LTO/LTO.cpp --- a/llvm/lib/LTO/LTO.cpp +++ b/llvm/lib/LTO/LTO.cpp @@ -1267,9 +1267,9 @@ &ResolvedODR, const GVSummaryMapTy &DefinedGlobals, MapVector &ModuleMap) { - if (LLVM_ENABLE_THREADS && Conf.TimeTraceEnabled) - timeTraceProfilerInitialize(Conf.TimeTraceGranularity, - "thin backend"); + TimeTraceProfilerThreadScope profilerScope( + LLVM_ENABLE_THREADS && Conf.TimeTraceEnabled, + Conf.TimeTraceGranularity, "thin backend"); Error E = runThinLTOBackendThread( AddStream, Cache, Task, BM, CombinedIndex, ImportList, ExportList, ResolvedODR, DefinedGlobals, ModuleMap); @@ -1280,8 +1280,6 @@ else Err = std::move(E); } - if (LLVM_ENABLE_THREADS && Conf.TimeTraceEnabled) - timeTraceProfilerFinishThread(); }, BM, std::ref(CombinedIndex), std::ref(ImportList), std::ref(ExportList), std::ref(ResolvedODR), std::ref(DefinedGlobals), std::ref(ModuleMap));