]> git.lizzy.rs Git - rust.git/blob - src/librustc_data_structures/sync.rs
Execute all parallel blocks even if they panic in a single-threaded compiler
[rust.git] / src / librustc_data_structures / sync.rs
1 //! This module defines types which are thread safe if cfg!(parallel_compiler) is true.
2 //!
3 //! `Lrc` is an alias of either Rc or Arc.
4 //!
5 //! `Lock` is a mutex.
6 //! It internally uses `parking_lot::Mutex` if cfg!(parallel_compiler) is true,
7 //! `RefCell` otherwise.
8 //!
9 //! `RwLock` is a read-write lock.
10 //! It internally uses `parking_lot::RwLock` if cfg!(parallel_compiler) is true,
11 //! `RefCell` otherwise.
12 //!
13 //! `MTLock` is a mutex which disappears if cfg!(parallel_compiler) is false.
14 //!
15 //! `MTRef` is a immutable reference if cfg!(parallel_compiler), and an mutable reference otherwise.
16 //!
17 //! `rustc_erase_owner!` erases a OwningRef owner into Erased or Erased + Send + Sync
18 //! depending on the value of cfg!(parallel_compiler).
19
20 use std::collections::HashMap;
21 use std::hash::{Hash, BuildHasher};
22 use std::marker::PhantomData;
23 use std::ops::{Deref, DerefMut};
24 use crate::owning_ref::{Erased, OwningRef};
25
26 pub fn serial_join<A, B, RA, RB>(oper_a: A, oper_b: B) -> (RA, RB)
27     where A: FnOnce() -> RA,
28           B: FnOnce() -> RB
29 {
30     (oper_a(), oper_b())
31 }
32
33 pub struct SerialScope;
34
35 impl SerialScope {
36     pub fn spawn<F>(&self, f: F)
37         where F: FnOnce(&SerialScope)
38     {
39         f(self)
40     }
41 }
42
43 pub fn serial_scope<F, R>(f: F) -> R
44     where F: FnOnce(&SerialScope) -> R
45 {
46     f(&SerialScope)
47 }
48
49 pub use std::sync::atomic::Ordering::SeqCst;
50 pub use std::sync::atomic::Ordering;
51
52 cfg_if! {
53     if #[cfg(not(parallel_compiler))] {
54         pub auto trait Send {}
55         pub auto trait Sync {}
56
57         impl<T: ?Sized> Send for T {}
58         impl<T: ?Sized> Sync for T {}
59
60         #[macro_export]
61         macro_rules! rustc_erase_owner {
62             ($v:expr) => {
63                 $v.erase_owner()
64             }
65         }
66
67         use std::ops::Add;
68         use std::panic::{resume_unwind, catch_unwind, AssertUnwindSafe};
69
70         #[derive(Debug)]
71         pub struct Atomic<T: Copy>(Cell<T>);
72
73         impl<T: Copy> Atomic<T> {
74             #[inline]
75             pub fn new(v: T) -> Self {
76                 Atomic(Cell::new(v))
77             }
78         }
79
80         impl<T: Copy + PartialEq> Atomic<T> {
81             pub fn into_inner(self) -> T {
82                 self.0.into_inner()
83             }
84
85             #[inline]
86             pub fn load(&self, _: Ordering) -> T {
87                 self.0.get()
88             }
89
90             #[inline]
91             pub fn store(&self, val: T, _: Ordering) {
92                 self.0.set(val)
93             }
94
95             pub fn swap(&self, val: T, _: Ordering) -> T {
96                 self.0.replace(val)
97             }
98
99             pub fn compare_exchange(&self,
100                                     current: T,
101                                     new: T,
102                                     _: Ordering,
103                                     _: Ordering)
104                                     -> Result<T, T> {
105                 let read = self.0.get();
106                 if read == current {
107                     self.0.set(new);
108                     Ok(read)
109                 } else {
110                     Err(read)
111                 }
112             }
113         }
114
115         impl<T: Add<Output=T> + Copy> Atomic<T> {
116             pub fn fetch_add(&self, val: T, _: Ordering) -> T {
117                 let old = self.0.get();
118                 self.0.set(old + val);
119                 old
120             }
121         }
122
123         pub type AtomicUsize = Atomic<usize>;
124         pub type AtomicBool = Atomic<bool>;
125         pub type AtomicU32 = Atomic<u32>;
126         pub type AtomicU64 = Atomic<u64>;
127
128         pub use self::serial_join as join;
129         pub use self::serial_scope as scope;
130
131         #[macro_export]
132         macro_rules! parallel {
133             ($($blocks:tt),*) => {
134                 let mut panic = None;
135                 $(
136                     if let Err(p) = ::std::panic::catch_unwind(
137                         ::std::panic::AssertUnwindSafe(|| $blocks)
138                     ) {
139                         if panic.is_none() {
140                             panic = Some(p);
141                         }
142                     }
143                 )*
144                 if let Some(panic) = panic {
145                     ::std::panic::resume_unwind(panic);
146                 }
147             }
148         }
149
150         pub use std::iter::Iterator as ParallelIterator;
151
152         pub fn par_iter<T: IntoIterator>(t: T) -> T::IntoIter {
153             t.into_iter()
154         }
155
156         pub fn par_for_each_in<T: IntoIterator>(
157             t: T,
158             for_each:
159                 impl Fn(<<T as IntoIterator>::IntoIter as Iterator>::Item) + Sync + Send
160         ) {
161             let mut panic = None;
162             t.into_iter().for_each(|i| {
163                 if let Err(p) = catch_unwind(AssertUnwindSafe(|| for_each(i))) {
164                     if panic.is_none() {
165                         panic = Some(p);
166                     }
167                 }
168             });
169             if let Some(panic) = panic {
170                 resume_unwind(panic);
171             }
172         }
173
174         pub type MetadataRef = OwningRef<Box<dyn Erased>, [u8]>;
175
176         pub use std::rc::Rc as Lrc;
177         pub use std::rc::Weak as Weak;
178         pub use std::cell::Ref as ReadGuard;
179         pub use std::cell::Ref as MappedReadGuard;
180         pub use std::cell::RefMut as WriteGuard;
181         pub use std::cell::RefMut as MappedWriteGuard;
182         pub use std::cell::RefMut as LockGuard;
183         pub use std::cell::RefMut as MappedLockGuard;
184
185         use std::cell::RefCell as InnerRwLock;
186         use std::cell::RefCell as InnerLock;
187
188         use std::cell::Cell;
189
190         #[derive(Debug)]
191         pub struct WorkerLocal<T>(OneThread<T>);
192
193         impl<T> WorkerLocal<T> {
194             /// Creates a new worker local where the `initial` closure computes the
195             /// value this worker local should take for each thread in the thread pool.
196             #[inline]
197             pub fn new<F: FnMut(usize) -> T>(mut f: F) -> WorkerLocal<T> {
198                 WorkerLocal(OneThread::new(f(0)))
199             }
200
201             /// Returns the worker-local value for each thread
202             #[inline]
203             pub fn into_inner(self) -> Vec<T> {
204                 vec![OneThread::into_inner(self.0)]
205             }
206         }
207
208         impl<T> Deref for WorkerLocal<T> {
209             type Target = T;
210
211             #[inline(always)]
212             fn deref(&self) -> &T {
213                 &*self.0
214             }
215         }
216
217         pub type MTRef<'a, T> = &'a mut T;
218
219         #[derive(Debug, Default)]
220         pub struct MTLock<T>(T);
221
222         impl<T> MTLock<T> {
223             #[inline(always)]
224             pub fn new(inner: T) -> Self {
225                 MTLock(inner)
226             }
227
228             #[inline(always)]
229             pub fn into_inner(self) -> T {
230                 self.0
231             }
232
233             #[inline(always)]
234             pub fn get_mut(&mut self) -> &mut T {
235                 &mut self.0
236             }
237
238             #[inline(always)]
239             pub fn lock(&self) -> &T {
240                 &self.0
241             }
242
243             #[inline(always)]
244             pub fn lock_mut(&mut self) -> &mut T {
245                 &mut self.0
246             }
247         }
248
249         // FIXME: Probably a bad idea (in the threaded case)
250         impl<T: Clone> Clone for MTLock<T> {
251             #[inline]
252             fn clone(&self) -> Self {
253                 MTLock(self.0.clone())
254             }
255         }
256     } else {
257         pub use std::marker::Send as Send;
258         pub use std::marker::Sync as Sync;
259
260         pub use parking_lot::RwLockReadGuard as ReadGuard;
261         pub use parking_lot::MappedRwLockReadGuard as MappedReadGuard;
262         pub use parking_lot::RwLockWriteGuard as WriteGuard;
263         pub use parking_lot::MappedRwLockWriteGuard as MappedWriteGuard;
264
265         pub use parking_lot::MutexGuard as LockGuard;
266         pub use parking_lot::MappedMutexGuard as MappedLockGuard;
267
268         pub use std::sync::atomic::{AtomicBool, AtomicUsize, AtomicU32, AtomicU64};
269
270         pub use std::sync::Arc as Lrc;
271         pub use std::sync::Weak as Weak;
272
273         pub type MTRef<'a, T> = &'a T;
274
275         #[derive(Debug, Default)]
276         pub struct MTLock<T>(Lock<T>);
277
278         impl<T> MTLock<T> {
279             #[inline(always)]
280             pub fn new(inner: T) -> Self {
281                 MTLock(Lock::new(inner))
282             }
283
284             #[inline(always)]
285             pub fn into_inner(self) -> T {
286                 self.0.into_inner()
287             }
288
289             #[inline(always)]
290             pub fn get_mut(&mut self) -> &mut T {
291                 self.0.get_mut()
292             }
293
294             #[inline(always)]
295             pub fn lock(&self) -> LockGuard<'_, T> {
296                 self.0.lock()
297             }
298
299             #[inline(always)]
300             pub fn lock_mut(&self) -> LockGuard<'_, T> {
301                 self.lock()
302             }
303         }
304
305         use parking_lot::Mutex as InnerLock;
306         use parking_lot::RwLock as InnerRwLock;
307
308         use std;
309         use std::thread;
310         pub use rayon::{join, scope};
311
312         #[macro_export]
313         macro_rules! parallel {
314             (impl $fblock:tt [$($c:tt,)*] [$block:tt $(, $rest:tt)*]) => {
315                 parallel!(impl $fblock [$block, $($c,)*] [$($rest),*])
316             };
317             (impl $fblock:tt [$($blocks:tt,)*] []) => {
318                 ::rustc_data_structures::sync::scope(|s| {
319                     $(
320                         s.spawn(|_| $blocks);
321                     )*
322                     $fblock;
323                 })
324             };
325             ($fblock:tt, $($blocks:tt),*) => {
326                 // Reverse the order of the blocks since Rayon executes them in reverse order
327                 // when using a single thread. This ensures the execution order matches that
328                 // of a single threaded rustc
329                 parallel!(impl $fblock [] [$($blocks),*]);
330             };
331         }
332
333         pub use rayon_core::WorkerLocal;
334
335         pub use rayon::iter::ParallelIterator;
336         use rayon::iter::IntoParallelIterator;
337
338         pub fn par_iter<T: IntoParallelIterator>(t: T) -> T::Iter {
339             t.into_par_iter()
340         }
341
342         pub fn par_for_each_in<T: IntoParallelIterator>(
343             t: T,
344             for_each: impl Fn(
345                 <<T as IntoParallelIterator>::Iter as ParallelIterator>::Item
346             ) + Sync + Send
347         ) {
348             t.into_par_iter().for_each(for_each)
349         }
350
351         pub type MetadataRef = OwningRef<Box<dyn Erased + Send + Sync>, [u8]>;
352
353         /// This makes locks panic if they are already held.
354         /// It is only useful when you are running in a single thread
355         const ERROR_CHECKING: bool = false;
356
357         #[macro_export]
358         macro_rules! rustc_erase_owner {
359             ($v:expr) => {{
360                 let v = $v;
361                 ::rustc_data_structures::sync::assert_send_val(&v);
362                 v.erase_send_sync_owner()
363             }}
364         }
365     }
366 }
367
368 pub fn assert_sync<T: ?Sized + Sync>() {}
369 pub fn assert_send<T: ?Sized + Send>() {}
370 pub fn assert_send_val<T: ?Sized + Send>(_t: &T) {}
371 pub fn assert_send_sync_val<T: ?Sized + Sync + Send>(_t: &T) {}
372
373 pub trait HashMapExt<K, V> {
374     /// Same as HashMap::insert, but it may panic if there's already an
375     /// entry for `key` with a value not equal to `value`
376     fn insert_same(&mut self, key: K, value: V);
377 }
378
379 impl<K: Eq + Hash, V: Eq, S: BuildHasher> HashMapExt<K, V> for HashMap<K, V, S> {
380     fn insert_same(&mut self, key: K, value: V) {
381         self.entry(key).and_modify(|old| assert!(*old == value)).or_insert(value);
382     }
383 }
384
385 /// A type whose inner value can be written once and then will stay read-only
386 // This contains a PhantomData<T> since this type conceptually owns a T outside the Mutex once
387 // initialized. This ensures that Once<T> is Sync only if T is. If we did not have PhantomData<T>
388 // we could send a &Once<Cell<bool>> to multiple threads and call `get` on it to get access
389 // to &Cell<bool> on those threads.
390 pub struct Once<T>(Lock<Option<T>>, PhantomData<T>);
391
392 impl<T> Once<T> {
393     /// Creates an Once value which is uninitialized
394     #[inline(always)]
395     pub fn new() -> Self {
396         Once(Lock::new(None), PhantomData)
397     }
398
399     /// Consumes the value and returns Some(T) if it was initialized
400     #[inline(always)]
401     pub fn into_inner(self) -> Option<T> {
402         self.0.into_inner()
403     }
404
405     /// Tries to initialize the inner value to `value`.
406     /// Returns `None` if the inner value was uninitialized and `value` was consumed setting it
407     /// otherwise if the inner value was already set it returns `value` back to the caller
408     #[inline]
409     pub fn try_set(&self, value: T) -> Option<T> {
410         let mut lock = self.0.lock();
411         if lock.is_some() {
412             return Some(value);
413         }
414         *lock = Some(value);
415         None
416     }
417
418     /// Tries to initialize the inner value to `value`.
419     /// Returns `None` if the inner value was uninitialized and `value` was consumed setting it
420     /// otherwise if the inner value was already set it asserts that `value` is equal to the inner
421     /// value and then returns `value` back to the caller
422     #[inline]
423     pub fn try_set_same(&self, value: T) -> Option<T> where T: Eq {
424         let mut lock = self.0.lock();
425         if let Some(ref inner) = *lock {
426             assert!(*inner == value);
427             return Some(value);
428         }
429         *lock = Some(value);
430         None
431     }
432
433     /// Tries to initialize the inner value to `value` and panics if it was already initialized
434     #[inline]
435     pub fn set(&self, value: T) {
436         assert!(self.try_set(value).is_none());
437     }
438
439     /// Tries to initialize the inner value by calling the closure while ensuring that no-one else
440     /// can access the value in the mean time by holding a lock for the duration of the closure.
441     /// If the value was already initialized the closure is not called and `false` is returned,
442     /// otherwise if the value from the closure initializes the inner value, `true` is returned
443     #[inline]
444     pub fn init_locking<F: FnOnce() -> T>(&self, f: F) -> bool {
445         let mut lock = self.0.lock();
446         if lock.is_some() {
447             return false;
448         }
449         *lock = Some(f());
450         true
451     }
452
453     /// Tries to initialize the inner value by calling the closure without ensuring that no-one
454     /// else can access it. This mean when this is called from multiple threads, multiple
455     /// closures may concurrently be computing a value which the inner value should take.
456     /// Only one of these closures are used to actually initialize the value.
457     /// If some other closure already set the value,
458     /// we return the value our closure computed wrapped in a `Option`.
459     /// If our closure set the value, `None` is returned.
460     /// If the value is already initialized, the closure is not called and `None` is returned.
461     #[inline]
462     pub fn init_nonlocking<F: FnOnce() -> T>(&self, f: F) -> Option<T> {
463         if self.0.lock().is_some() {
464             None
465         } else {
466             self.try_set(f())
467         }
468     }
469
470     /// Tries to initialize the inner value by calling the closure without ensuring that no-one
471     /// else can access it. This mean when this is called from multiple threads, multiple
472     /// closures may concurrently be computing a value which the inner value should take.
473     /// Only one of these closures are used to actually initialize the value.
474     /// If some other closure already set the value, we assert that it our closure computed
475     /// a value equal to the value already set and then
476     /// we return the value our closure computed wrapped in a `Option`.
477     /// If our closure set the value, `None` is returned.
478     /// If the value is already initialized, the closure is not called and `None` is returned.
479     #[inline]
480     pub fn init_nonlocking_same<F: FnOnce() -> T>(&self, f: F) -> Option<T> where T: Eq {
481         if self.0.lock().is_some() {
482             None
483         } else {
484             self.try_set_same(f())
485         }
486     }
487
488     /// Tries to get a reference to the inner value, returns `None` if it is not yet initialized
489     #[inline(always)]
490     pub fn try_get(&self) -> Option<&T> {
491         let lock = &*self.0.lock();
492         if let Some(ref inner) = *lock {
493             // This is safe since we won't mutate the inner value
494             unsafe { Some(&*(inner as *const T)) }
495         } else {
496             None
497         }
498     }
499
500     /// Gets reference to the inner value, panics if it is not yet initialized
501     #[inline(always)]
502     pub fn get(&self) -> &T {
503         self.try_get().expect("value was not set")
504     }
505
506     /// Gets reference to the inner value, panics if it is not yet initialized
507     #[inline(always)]
508     pub fn borrow(&self) -> &T {
509         self.get()
510     }
511 }
512
513 #[derive(Debug)]
514 pub struct Lock<T>(InnerLock<T>);
515
516 impl<T> Lock<T> {
517     #[inline(always)]
518     pub fn new(inner: T) -> Self {
519         Lock(InnerLock::new(inner))
520     }
521
522     #[inline(always)]
523     pub fn into_inner(self) -> T {
524         self.0.into_inner()
525     }
526
527     #[inline(always)]
528     pub fn get_mut(&mut self) -> &mut T {
529         self.0.get_mut()
530     }
531
532     #[cfg(parallel_compiler)]
533     #[inline(always)]
534     pub fn try_lock(&self) -> Option<LockGuard<'_, T>> {
535         self.0.try_lock()
536     }
537
538     #[cfg(not(parallel_compiler))]
539     #[inline(always)]
540     pub fn try_lock(&self) -> Option<LockGuard<'_, T>> {
541         self.0.try_borrow_mut().ok()
542     }
543
544     #[cfg(parallel_compiler)]
545     #[inline(always)]
546     pub fn lock(&self) -> LockGuard<'_, T> {
547         if ERROR_CHECKING {
548             self.0.try_lock().expect("lock was already held")
549         } else {
550             self.0.lock()
551         }
552     }
553
554     #[cfg(not(parallel_compiler))]
555     #[inline(always)]
556     pub fn lock(&self) -> LockGuard<'_, T> {
557         self.0.borrow_mut()
558     }
559
560     #[inline(always)]
561     pub fn with_lock<F: FnOnce(&mut T) -> R, R>(&self, f: F) -> R {
562         f(&mut *self.lock())
563     }
564
565     #[inline(always)]
566     pub fn borrow(&self) -> LockGuard<'_, T> {
567         self.lock()
568     }
569
570     #[inline(always)]
571     pub fn borrow_mut(&self) -> LockGuard<'_, T> {
572         self.lock()
573     }
574 }
575
576 impl<T: Default> Default for Lock<T> {
577     #[inline]
578     fn default() -> Self {
579         Lock::new(T::default())
580     }
581 }
582
583 // FIXME: Probably a bad idea
584 impl<T: Clone> Clone for Lock<T> {
585     #[inline]
586     fn clone(&self) -> Self {
587         Lock::new(self.borrow().clone())
588     }
589 }
590
591 #[derive(Debug)]
592 pub struct RwLock<T>(InnerRwLock<T>);
593
594 impl<T> RwLock<T> {
595     #[inline(always)]
596     pub fn new(inner: T) -> Self {
597         RwLock(InnerRwLock::new(inner))
598     }
599
600     #[inline(always)]
601     pub fn into_inner(self) -> T {
602         self.0.into_inner()
603     }
604
605     #[inline(always)]
606     pub fn get_mut(&mut self) -> &mut T {
607         self.0.get_mut()
608     }
609
610     #[cfg(not(parallel_compiler))]
611     #[inline(always)]
612     pub fn read(&self) -> ReadGuard<'_, T> {
613         self.0.borrow()
614     }
615
616     #[cfg(parallel_compiler)]
617     #[inline(always)]
618     pub fn read(&self) -> ReadGuard<'_, T> {
619         if ERROR_CHECKING {
620             self.0.try_read().expect("lock was already held")
621         } else {
622             self.0.read()
623         }
624     }
625
626     #[inline(always)]
627     pub fn with_read_lock<F: FnOnce(&T) -> R, R>(&self, f: F) -> R {
628         f(&*self.read())
629     }
630
631     #[cfg(not(parallel_compiler))]
632     #[inline(always)]
633     pub fn try_write(&self) -> Result<WriteGuard<'_, T>, ()> {
634         self.0.try_borrow_mut().map_err(|_| ())
635     }
636
637     #[cfg(parallel_compiler)]
638     #[inline(always)]
639     pub fn try_write(&self) -> Result<WriteGuard<'_, T>, ()> {
640         self.0.try_write().ok_or(())
641     }
642
643     #[cfg(not(parallel_compiler))]
644     #[inline(always)]
645     pub fn write(&self) -> WriteGuard<'_, T> {
646         self.0.borrow_mut()
647     }
648
649     #[cfg(parallel_compiler)]
650     #[inline(always)]
651     pub fn write(&self) -> WriteGuard<'_, T> {
652         if ERROR_CHECKING {
653             self.0.try_write().expect("lock was already held")
654         } else {
655             self.0.write()
656         }
657     }
658
659     #[inline(always)]
660     pub fn with_write_lock<F: FnOnce(&mut T) -> R, R>(&self, f: F) -> R {
661         f(&mut *self.write())
662     }
663
664     #[inline(always)]
665     pub fn borrow(&self) -> ReadGuard<'_, T> {
666         self.read()
667     }
668
669     #[inline(always)]
670     pub fn borrow_mut(&self) -> WriteGuard<'_, T> {
671         self.write()
672     }
673 }
674
675 // FIXME: Probably a bad idea
676 impl<T: Clone> Clone for RwLock<T> {
677     #[inline]
678     fn clone(&self) -> Self {
679         RwLock::new(self.borrow().clone())
680     }
681 }
682
683 /// A type which only allows its inner value to be used in one thread.
684 /// It will panic if it is used on multiple threads.
685 #[derive(Copy, Clone, Hash, Debug, Eq, PartialEq)]
686 pub struct OneThread<T> {
687     #[cfg(parallel_compiler)]
688     thread: thread::ThreadId,
689     inner: T,
690 }
691
692 #[cfg(parallel_compiler)]
693 unsafe impl<T> std::marker::Sync for OneThread<T> {}
694 #[cfg(parallel_compiler)]
695 unsafe impl<T> std::marker::Send for OneThread<T> {}
696
697 impl<T> OneThread<T> {
698     #[inline(always)]
699     fn check(&self) {
700         #[cfg(parallel_compiler)]
701         assert_eq!(thread::current().id(), self.thread);
702     }
703
704     #[inline(always)]
705     pub fn new(inner: T) -> Self {
706         OneThread {
707             #[cfg(parallel_compiler)]
708             thread: thread::current().id(),
709             inner,
710         }
711     }
712
713     #[inline(always)]
714     pub fn into_inner(value: Self) -> T {
715         value.check();
716         value.inner
717     }
718 }
719
720 impl<T> Deref for OneThread<T> {
721     type Target = T;
722
723     fn deref(&self) -> &T {
724         self.check();
725         &self.inner
726     }
727 }
728
729 impl<T> DerefMut for OneThread<T> {
730     fn deref_mut(&mut self) -> &mut T {
731         self.check();
732         &mut self.inner
733     }
734 }