Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(416)

Side by Side Diff: src/IceGlobalContext.h

Issue 870653002: Subzero: Initial implementation of multithreaded translation. (Closed) Base URL: https://chromium.googlesource.com/native_client/pnacl-subzero.git@master
Patch Set: Fix getErrorStatus() usage in BitcodeMunger Created 5 years, 11 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 //===- subzero/src/IceGlobalContext.h - Global context defs -----*- C++ -*-===// 1 //===- subzero/src/IceGlobalContext.h - Global context defs -----*- C++ -*-===//
2 // 2 //
3 // The Subzero Code Generator 3 // The Subzero Code Generator
4 // 4 //
5 // This file is distributed under the University of Illinois Open Source 5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details. 6 // License. See LICENSE.TXT for details.
7 // 7 //
8 //===----------------------------------------------------------------------===// 8 //===----------------------------------------------------------------------===//
9 // 9 //
10 // This file declares aspects of the compilation that persist across 10 // This file declares aspects of the compilation that persist across
11 // multiple functions. 11 // multiple functions.
12 // 12 //
13 //===----------------------------------------------------------------------===// 13 //===----------------------------------------------------------------------===//
14 14
15 #ifndef SUBZERO_SRC_ICEGLOBALCONTEXT_H 15 #ifndef SUBZERO_SRC_ICEGLOBALCONTEXT_H
16 #define SUBZERO_SRC_ICEGLOBALCONTEXT_H 16 #define SUBZERO_SRC_ICEGLOBALCONTEXT_H
17 17
18 #include <memory>
19 #include <mutex> 18 #include <mutex>
19 #include <queue>
20 #include <thread>
20 21
21 #include "IceDefs.h" 22 #include "IceDefs.h"
22 #include "IceClFlags.h" 23 #include "IceClFlags.h"
23 #include "IceIntrinsics.h" 24 #include "IceIntrinsics.h"
24 #include "IceRNG.h" 25 #include "IceRNG.h"
25 #include "IceTimerTree.h" 26 #include "IceTimerTree.h"
26 #include "IceTypes.h" 27 #include "IceTypes.h"
27 28
28 namespace Ice { 29 namespace Ice {
29 30
(...skipping 59 matching lines...) Expand 10 before | Expand all | Expand 10 after
89 class ThreadContext { 90 class ThreadContext {
90 ThreadContext(const ThreadContext &) = delete; 91 ThreadContext(const ThreadContext &) = delete;
91 ThreadContext &operator=(const ThreadContext &) = delete; 92 ThreadContext &operator=(const ThreadContext &) = delete;
92 93
93 public: 94 public:
94 ThreadContext() {} 95 ThreadContext() {}
95 CodeStats StatsFunction; 96 CodeStats StatsFunction;
96 std::vector<TimerStack> Timers; 97 std::vector<TimerStack> Timers;
97 }; 98 };
98 99
100 // CfgQueue is the translation work queue. It allows multiple
101 // producers and multiple consumers (though currently only a single
102 // producer is used). The producer adds entries using add(), and
103 // may block if the queue is "full" to control Cfg memory footprint.
104 // The producer uses end() to indicate that no more entries will be
105 // added. The consumer removes an item using get(), which will
106 // return nullptr if end() has been called and the queue is empty.
107 //
108 // The MaxSize ctor arg controls the maximum size the queue can grow
109 // to. The Sequential arg indicates purely sequential execution in
110 // which the single thread should never wait().
111 //
112 // Two condition variables are used in the implementation.
113 // GrewOrEnded signals waiting workers that the producer has changed
114 // the state of the queue. Shrunk signals a blocked producer that a
115 // consumer has changed the state of the queue.
116 class CfgQueue {
117 public:
118 CfgQueue(size_t MaxSize, bool Sequential)
119 : MaxSize(MaxSize), Sequential(Sequential), IsEnded(false) {}
120 void add(Cfg *Func) {
121 std::unique_lock<GlobalLockType> L(Lock);
122 // If the work queue is already "full", wait for a consumer to
123 // grab an element and shrink the queue.
124 while (!Sequential && WorkQueue.size() >= MaxSize) {
125 Shrunk.wait(L);
126 }
127 WorkQueue.push(Func);
128 L.unlock();
129 GrewOrEnded.notify_one();
130 }
131 Cfg *get() {
132 std::unique_lock<GlobalLockType> L(Lock);
133 while (!IsEnded || !WorkQueue.empty()) {
134 if (!WorkQueue.empty()) {
135 Cfg *Func = WorkQueue.front();
136 WorkQueue.pop();
137 L.unlock();
138 Shrunk.notify_one();
139 return Func;
140 }
141 // If the work queue is empty, and this is pure sequential
142 // execution, then return nullptr.
143 if (Sequential)
144 return nullptr;
145 GrewOrEnded.wait(L);
146 }
147 return nullptr;
148 }
149 void end() {
150 std::unique_lock<GlobalLockType> L(Lock);
151 IsEnded = true;
152 L.unlock();
153 GrewOrEnded.notify_all();
154 }
155
156 private:
157 std::queue<Cfg *> WorkQueue;
158 // Lock guards access to WorkQueue and IsEnded.
159 GlobalLockType Lock;
160 // GrewOrEnded is notified (by the producer) when something is
161 // added to the queue, in case consumers are waiting for a
162 // non-empty queue.
163 std::condition_variable GrewOrEnded;
164 // Shrunk is notified (by the consumer) when something is removed
165 // from the queue, in case the producer is waiting for the queue
166 // to drop below maximum capacity.
167 std::condition_variable Shrunk;
168 const size_t MaxSize;
169 const bool Sequential;
170 bool IsEnded;
JF 2015/01/23 17:22:43 I think it's worth reordering and aligning to cach
Jim Stichnoth 2015/01/23 21:54:02 Done. And added a TODO about considering std::arr
171 };
172
99 public: 173 public:
100 GlobalContext(Ostream *OsDump, Ostream *OsEmit, ELFStreamer *ELFStreamer, 174 GlobalContext(Ostream *OsDump, Ostream *OsEmit, ELFStreamer *ELFStreamer,
101 VerboseMask Mask, TargetArch Arch, OptLevel Opt, 175 VerboseMask Mask, TargetArch Arch, OptLevel Opt,
102 IceString TestPrefix, const ClFlags &Flags); 176 IceString TestPrefix, const ClFlags &Flags);
103 ~GlobalContext(); 177 ~GlobalContext();
104 178
105 // Returns true if any of the specified options in the verbose mask
106 // are set. If the argument is omitted, it checks if any verbose
107 // options at all are set.
108 VerboseMask getVerbose() const { return VMask; } 179 VerboseMask getVerbose() const { return VMask; }
109 bool isVerbose(VerboseMask Mask = IceV_All) const { return VMask & Mask; }
110 void setVerbose(VerboseMask Mask) { VMask = Mask; }
111 void addVerbose(VerboseMask Mask) { VMask |= Mask; }
112 void subVerbose(VerboseMask Mask) { VMask &= ~Mask; }
113 180
114 // The dump and emit streams need to be used by only one thread at a 181 // The dump and emit streams need to be used by only one thread at a
115 // time. This is done by exclusively reserving the streams via 182 // time. This is done by exclusively reserving the streams via
116 // lockStr() and unlockStr(). The OstreamLocker class can be used 183 // lockStr() and unlockStr(). The OstreamLocker class can be used
117 // to conveniently manage this. 184 // to conveniently manage this.
118 // 185 //
119 // The model is that a thread grabs the stream lock, then does an 186 // The model is that a thread grabs the stream lock, then does an
120 // arbitrary amount of work during which far-away callees may grab 187 // arbitrary amount of work during which far-away callees may grab
121 // the stream and do something with it, and finally the thread 188 // the stream and do something with it, and finally the thread
122 // releases the stream lock. This allows large chunks of output to 189 // releases the stream lock. This allows large chunks of output to
123 // be dumped or emitted without risking interleaving from multiple 190 // be dumped or emitted without risking interleaving from multiple
124 // threads. 191 // threads.
125 void lockStr() { StrLock.lock(); } 192 void lockStr() { StrLock.lock(); }
126 void unlockStr() { StrLock.unlock(); } 193 void unlockStr() { StrLock.unlock(); }
127 Ostream &getStrDump() { return *StrDump; } 194 Ostream &getStrDump() { return *StrDump; }
128 Ostream &getStrEmit() { return *StrEmit; } 195 Ostream &getStrEmit() { return *StrEmit; }
129 196
130 TargetArch getTargetArch() const { return Arch; } 197 TargetArch getTargetArch() const { return Arch; }
131 OptLevel getOptLevel() const { return Opt; } 198 OptLevel getOptLevel() const { return Opt; }
199 std::error_code getErrorStatus() const { return ErrorStatus; }
132 200
133 // When emitting assembly, we allow a string to be prepended to 201 // When emitting assembly, we allow a string to be prepended to
134 // names of translated functions. This makes it easier to create an 202 // names of translated functions. This makes it easier to create an
135 // execution test against a reference translator like llc, with both 203 // execution test against a reference translator like llc, with both
136 // translators using the same bitcode as input. 204 // translators using the same bitcode as input.
137 IceString getTestPrefix() const { return TestPrefix; } 205 IceString getTestPrefix() const { return TestPrefix; }
138 IceString mangleName(const IceString &Name) const; 206 IceString mangleName(const IceString &Name) const;
139 207
140 // Manage Constants. 208 // Manage Constants.
141 // getConstant*() functions are not const because they might add 209 // getConstant*() functions are not const because they might add
(...skipping 80 matching lines...) Expand 10 before | Expand all | Expand 10 after
222 290
223 TimerStackIdT newTimerStackID(const IceString &Name); 291 TimerStackIdT newTimerStackID(const IceString &Name);
224 TimerIdT getTimerID(TimerStackIdT StackID, const IceString &Name); 292 TimerIdT getTimerID(TimerStackIdT StackID, const IceString &Name);
225 void pushTimer(TimerIdT ID, TimerStackIdT StackID = TSK_Default); 293 void pushTimer(TimerIdT ID, TimerStackIdT StackID = TSK_Default);
226 void popTimer(TimerIdT ID, TimerStackIdT StackID = TSK_Default); 294 void popTimer(TimerIdT ID, TimerStackIdT StackID = TSK_Default);
227 void resetTimer(TimerStackIdT StackID); 295 void resetTimer(TimerStackIdT StackID);
228 void setTimerName(TimerStackIdT StackID, const IceString &NewName); 296 void setTimerName(TimerStackIdT StackID, const IceString &NewName);
229 void dumpTimers(TimerStackIdT StackID = TSK_Default, 297 void dumpTimers(TimerStackIdT StackID = TSK_Default,
230 bool DumpCumulative = true); 298 bool DumpCumulative = true);
231 299
300 // Adds a newly parsed and constructed function to the Cfg work
301 // queue. Notifies any idle workers that a new function is
302 // available for translating. May block if the work queue is too
303 // large, in order to control memory footprint.
304 void cfgQueueAdd(Cfg *Func) { CfgQ.add(Func); }
305 // Takes a Cfg from the work queue for translating. May block if
306 // the work queue is currently empty. Returns nullptr if there is
307 // no more work - the queue is empty and either end() has been
308 // called or the Sequential flag was set.
309 Cfg *cfgQueueGet() { return CfgQ.get(); }
310 // Notifies that no more work will be added to the work queue.
311 void cfgQueueEnd() { CfgQ.end(); }
312
313 void startWorkerThreads() {
314 size_t NumWorkers = getFlags().NumTranslationThreads;
315 for (size_t i = 0; i < NumWorkers; ++i) {
316 ThreadContext *WorkerTLS = new ThreadContext();
317 AllThreadContexts.push_back(WorkerTLS);
318 TranslationThreads.push_back(std::thread(
319 &GlobalContext::translateFunctionsWrapper, this, WorkerTLS));
320 }
321 if (NumWorkers) {
322 // TODO(stichnot): start a new thread for the emitter queue worker.
323 }
324 }
325
326 void waitForWorkerThreads() {
327 cfgQueueEnd();
328 // TODO(stichnot): call end() on the emitter work queue.
329 for (std::thread &Worker : TranslationThreads) {
330 Worker.join();
331 }
332 TranslationThreads.clear();
333 // TODO(stichnot): join the emitter thread.
334 }
335
336 // Translation thread startup routine.
337 void translateFunctionsWrapper(ThreadContext *MyTLS) {
338 TLS = MyTLS;
339 translateFunctions();
340 }
341 // Translate functions from the Cfg queue until the queue is empty.
342 void translateFunctions();
343
344 // Utility function to match a symbol name against a match string.
345 // This is used in a few cases where we want to take some action on
346 // a particular function or symbol based on a command-line argument,
347 // such as changing the verbose level for a particular function. An
348 // empty Match argument means match everything. Returns true if
349 // there is a match.
350 static bool matchSymbolName(const IceString &SymbolName,
351 const IceString &Match) {
352 return Match.empty() || Match == SymbolName;
353 }
354
232 private: 355 private:
233 // Try to make sure the mutexes are allocated on separate cache 356 // Try to make sure the mutexes are allocated on separate cache
234 // lines, assuming the maximum cache line size is 64. 357 // lines, assuming the maximum cache line size is 64.
235 const static size_t MaxCacheLineSize = 64; 358 const static size_t MaxCacheLineSize = 64;
236 alignas(MaxCacheLineSize) GlobalLockType AllocLock; 359 alignas(MaxCacheLineSize) GlobalLockType AllocLock;
237 alignas(MaxCacheLineSize) GlobalLockType ConstPoolLock; 360 alignas(MaxCacheLineSize) GlobalLockType ConstPoolLock;
238 alignas(MaxCacheLineSize) GlobalLockType StatsLock; 361 alignas(MaxCacheLineSize) GlobalLockType StatsLock;
239 alignas(MaxCacheLineSize) GlobalLockType TimerLock; 362 alignas(MaxCacheLineSize) GlobalLockType TimerLock;
240 363
241 // StrLock is a global lock on the dump and emit output streams. 364 // StrLock is a global lock on the dump and emit output streams.
242 typedef std::mutex StrLockType; 365 typedef std::mutex StrLockType;
243 StrLockType StrLock; 366 StrLockType StrLock;
244 367
245 Ostream *StrDump; // Stream for dumping / diagnostics 368 Ostream *StrDump; // Stream for dumping / diagnostics
246 Ostream *StrEmit; // Stream for code emission 369 Ostream *StrEmit; // Stream for code emission
247 370
248 ArenaAllocator<> Allocator; 371 ArenaAllocator<> Allocator;
249 VerboseMask VMask; 372 VerboseMask VMask;
250 std::unique_ptr<ConstantPool> ConstPool; 373 std::unique_ptr<ConstantPool> ConstPool;
251 Intrinsics IntrinsicsInfo; 374 Intrinsics IntrinsicsInfo;
252 const TargetArch Arch; 375 const TargetArch Arch;
253 const OptLevel Opt; 376 const OptLevel Opt;
254 const IceString TestPrefix; 377 const IceString TestPrefix;
255 const ClFlags &Flags; 378 const ClFlags &Flags;
256 RandomNumberGenerator RNG; 379 RandomNumberGenerator RNG;
257 std::unique_ptr<ELFObjectWriter> ObjectWriter; 380 std::unique_ptr<ELFObjectWriter> ObjectWriter;
258 CodeStats StatsCumulative; 381 CodeStats StatsCumulative;
259 std::vector<TimerStack> Timers; 382 std::vector<TimerStack> Timers;
383 CfgQueue CfgQ;
384 std::error_code ErrorStatus;
260 385
261 LockedPtr<ArenaAllocator<>> getAllocator() { 386 LockedPtr<ArenaAllocator<>> getAllocator() {
262 return LockedPtr<ArenaAllocator<>>(&Allocator, &AllocLock); 387 return LockedPtr<ArenaAllocator<>>(&Allocator, &AllocLock);
263 } 388 }
264 LockedPtr<ConstantPool> getConstPool() { 389 LockedPtr<ConstantPool> getConstPool() {
265 return LockedPtr<ConstantPool>(ConstPool.get(), &ConstPoolLock); 390 return LockedPtr<ConstantPool>(ConstPool.get(), &ConstPoolLock);
266 } 391 }
267 LockedPtr<CodeStats> getStatsCumulative() { 392 LockedPtr<CodeStats> getStatsCumulative() {
268 return LockedPtr<CodeStats>(&StatsCumulative, &StatsLock); 393 return LockedPtr<CodeStats>(&StatsCumulative, &StatsLock);
269 } 394 }
270 LockedPtr<std::vector<TimerStack>> getTimers() { 395 LockedPtr<std::vector<TimerStack>> getTimers() {
271 return LockedPtr<std::vector<TimerStack>>(&Timers, &TimerLock); 396 return LockedPtr<std::vector<TimerStack>>(&Timers, &TimerLock);
272 } 397 }
273 398
274 std::vector<ThreadContext *> AllThreadContexts; 399 std::vector<ThreadContext *> AllThreadContexts;
400 std::vector<std::thread> TranslationThreads;
275 // Each thread has its own TLS pointer which is also held in 401 // Each thread has its own TLS pointer which is also held in
276 // AllThreadContexts. 402 // AllThreadContexts.
277 thread_local static ThreadContext *TLS; 403 thread_local static ThreadContext *TLS;
278 404
279 // Private helpers for mangleName() 405 // Private helpers for mangleName()
280 typedef llvm::SmallVector<char, 32> ManglerVector; 406 typedef llvm::SmallVector<char, 32> ManglerVector;
281 void incrementSubstitutions(ManglerVector &OldName) const; 407 void incrementSubstitutions(ManglerVector &OldName) const;
282 }; 408 };
283 409
284 // Helper class to push and pop a timer marker. The constructor 410 // Helper class to push and pop a timer marker. The constructor
(...skipping 37 matching lines...) Expand 10 before | Expand all | Expand 10 after
322 explicit OstreamLocker(GlobalContext *Ctx) : Ctx(Ctx) { Ctx->lockStr(); } 448 explicit OstreamLocker(GlobalContext *Ctx) : Ctx(Ctx) { Ctx->lockStr(); }
323 ~OstreamLocker() { Ctx->unlockStr(); } 449 ~OstreamLocker() { Ctx->unlockStr(); }
324 450
325 private: 451 private:
326 GlobalContext *const Ctx; 452 GlobalContext *const Ctx;
327 }; 453 };
328 454
329 } // end of namespace Ice 455 } // end of namespace Ice
330 456
331 #endif // SUBZERO_SRC_ICEGLOBALCONTEXT_H 457 #endif // SUBZERO_SRC_ICEGLOBALCONTEXT_H
OLDNEW
« no previous file with comments | « src/IceDefs.h ('k') | src/IceGlobalContext.cpp » ('j') | src/IceGlobalContext.cpp » ('J')

Powered by Google App Engine
This is Rietveld 408576698