1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
use collector::InliningMap;
use common;
use context::SharedCrateContext;
use llvm;
use rustc::dep_graph::{DepNode, WorkProductId};
use rustc::hir::def_id::DefId;
use rustc::hir::map::DefPathData;
use rustc::session::config::NUMBERED_CODEGEN_UNIT_MARKER;
use rustc::ty::TyCtxt;
use rustc::ty::item_path::characteristic_def_id_of_type;
use rustc_incremental::IchHasher;
use std::cmp::Ordering;
use std::hash::Hash;
use std::sync::Arc;
use symbol_map::SymbolMap;
use syntax::ast::NodeId;
use syntax::symbol::{Symbol, InternedString};
use trans_item::{TransItem, InstantiationMode};
use util::nodemap::{FxHashMap, FxHashSet};
pub enum PartitioningStrategy {
PerModule,
FixedUnitCount(usize)
}
pub struct CodegenUnit<'tcx> {
name: InternedString,
items: FxHashMap<TransItem<'tcx>, llvm::Linkage>,
}
impl<'tcx> CodegenUnit<'tcx> {
pub fn new(name: InternedString,
items: FxHashMap<TransItem<'tcx>, llvm::Linkage>)
-> Self {
CodegenUnit {
name: name,
items: items,
}
}
pub fn empty(name: InternedString) -> Self {
Self::new(name, FxHashMap())
}
pub fn contains_item(&self, item: &TransItem<'tcx>) -> bool {
self.items.contains_key(item)
}
pub fn name(&self) -> &str {
&self.name
}
pub fn items(&self) -> &FxHashMap<TransItem<'tcx>, llvm::Linkage> {
&self.items
}
pub fn work_product_id(&self) -> Arc<WorkProductId> {
Arc::new(WorkProductId(self.name().to_string()))
}
pub fn work_product_dep_node(&self) -> DepNode<DefId> {
DepNode::WorkProduct(self.work_product_id())
}
pub fn compute_symbol_name_hash(&self,
scx: &SharedCrateContext,
symbol_map: &SymbolMap) -> u64 {
let mut state = IchHasher::new();
let exported_symbols = scx.exported_symbols();
let all_items = self.items_in_deterministic_order(scx.tcx(), symbol_map);
for (item, _) in all_items {
let symbol_name = symbol_map.get(item).unwrap();
symbol_name.len().hash(&mut state);
symbol_name.hash(&mut state);
let exported = match item {
TransItem::Fn(ref instance) => {
let node_id = scx.tcx().hir.as_local_node_id(instance.def);
node_id.map(|node_id| exported_symbols.contains(&node_id))
.unwrap_or(false)
}
TransItem::Static(node_id) => {
exported_symbols.contains(&node_id)
}
TransItem::DropGlue(..) => false,
};
exported.hash(&mut state);
}
state.finish().to_smaller_hash()
}
pub fn items_in_deterministic_order(&self,
tcx: TyCtxt,
symbol_map: &SymbolMap)
-> Vec<(TransItem<'tcx>, llvm::Linkage)> {
let mut items: Vec<(TransItem<'tcx>, llvm::Linkage)> =
self.items.iter().map(|(item, linkage)| (*item, *linkage)).collect();
items.sort_by(|&(trans_item1, _), &(trans_item2, _)| {
let node_id1 = local_node_id(tcx, trans_item1);
let node_id2 = local_node_id(tcx, trans_item2);
match (node_id1, node_id2) {
(None, None) => {
let symbol_name1 = symbol_map.get(trans_item1).unwrap();
let symbol_name2 = symbol_map.get(trans_item2).unwrap();
symbol_name1.cmp(symbol_name2)
}
(None, Some(_)) => Ordering::Less,
(Some(_), None) => Ordering::Greater,
(Some(node_id1), Some(node_id2)) => {
let ordering = node_id1.cmp(&node_id2);
if ordering != Ordering::Equal {
return ordering;
}
let symbol_name1 = symbol_map.get(trans_item1).unwrap();
let symbol_name2 = symbol_map.get(trans_item2).unwrap();
symbol_name1.cmp(symbol_name2)
}
}
});
return items;
fn local_node_id(tcx: TyCtxt, trans_item: TransItem) -> Option<NodeId> {
match trans_item {
TransItem::Fn(instance) => {
tcx.hir.as_local_node_id(instance.def)
}
TransItem::Static(node_id) => Some(node_id),
TransItem::DropGlue(_) => None,
}
}
}
}
const FALLBACK_CODEGEN_UNIT: &'static str = "__rustc_fallback_codegen_unit";
pub fn partition<'a, 'tcx, I>(scx: &SharedCrateContext<'a, 'tcx>,
trans_items: I,
strategy: PartitioningStrategy,
inlining_map: &InliningMap<'tcx>)
-> Vec<CodegenUnit<'tcx>>
where I: Iterator<Item = TransItem<'tcx>>
{
let tcx = scx.tcx();
let mut initial_partitioning = place_root_translation_items(scx,
trans_items);
debug_dump(scx, "INITIAL PARTITONING:", initial_partitioning.codegen_units.iter());
if let PartitioningStrategy::FixedUnitCount(count) = strategy {
merge_codegen_units(&mut initial_partitioning, count, &tcx.crate_name.as_str());
debug_dump(scx, "POST MERGING:", initial_partitioning.codegen_units.iter());
}
let post_inlining = place_inlined_translation_items(initial_partitioning,
inlining_map);
debug_dump(scx, "POST INLINING:", post_inlining.0.iter());
let mut result = post_inlining.0;
result.sort_by(|cgu1, cgu2| {
(&cgu1.name[..]).cmp(&cgu2.name[..])
});
result
}
struct PreInliningPartitioning<'tcx> {
codegen_units: Vec<CodegenUnit<'tcx>>,
roots: FxHashSet<TransItem<'tcx>>,
}
struct PostInliningPartitioning<'tcx>(Vec<CodegenUnit<'tcx>>);
fn place_root_translation_items<'a, 'tcx, I>(scx: &SharedCrateContext<'a, 'tcx>,
trans_items: I)
-> PreInliningPartitioning<'tcx>
where I: Iterator<Item = TransItem<'tcx>>
{
let tcx = scx.tcx();
let mut roots = FxHashSet();
let mut codegen_units = FxHashMap();
let is_incremental_build = tcx.sess.opts.incremental.is_some();
for trans_item in trans_items {
let is_root = trans_item.instantiation_mode(tcx) == InstantiationMode::GloballyShared;
if is_root {
let characteristic_def_id = characteristic_def_id_of_trans_item(scx, trans_item);
let is_volatile = is_incremental_build &&
trans_item.is_generic_fn();
let codegen_unit_name = match characteristic_def_id {
Some(def_id) => compute_codegen_unit_name(tcx, def_id, is_volatile),
None => Symbol::intern(FALLBACK_CODEGEN_UNIT).as_str(),
};
let make_codegen_unit = || {
CodegenUnit::empty(codegen_unit_name.clone())
};
let mut codegen_unit = codegen_units.entry(codegen_unit_name.clone())
.or_insert_with(make_codegen_unit);
let linkage = match trans_item.explicit_linkage(tcx) {
Some(explicit_linkage) => explicit_linkage,
None => {
match trans_item {
TransItem::Fn(..) |
TransItem::Static(..) => llvm::ExternalLinkage,
TransItem::DropGlue(..) => unreachable!(),
}
}
};
codegen_unit.items.insert(trans_item, linkage);
roots.insert(trans_item);
}
}
if codegen_units.is_empty() {
let codegen_unit_name = Symbol::intern(FALLBACK_CODEGEN_UNIT).as_str();
codegen_units.entry(codegen_unit_name.clone())
.or_insert_with(|| CodegenUnit::empty(codegen_unit_name.clone()));
}
PreInliningPartitioning {
codegen_units: codegen_units.into_iter()
.map(|(_, codegen_unit)| codegen_unit)
.collect(),
roots: roots,
}
}
fn merge_codegen_units<'tcx>(initial_partitioning: &mut PreInliningPartitioning<'tcx>,
target_cgu_count: usize,
crate_name: &str) {
assert!(target_cgu_count >= 1);
let codegen_units = &mut initial_partitioning.codegen_units;
while codegen_units.len() > target_cgu_count {
codegen_units.sort_by_key(|cgu| -(cgu.items.len() as i64));
let smallest = codegen_units.pop().unwrap();
let second_smallest = codegen_units.last_mut().unwrap();
for (k, v) in smallest.items.into_iter() {
second_smallest.items.insert(k, v);
}
}
for (index, cgu) in codegen_units.iter_mut().enumerate() {
cgu.name = numbered_codegen_unit_name(crate_name, index);
}
while codegen_units.len() < target_cgu_count {
let index = codegen_units.len();
codegen_units.push(
CodegenUnit::empty(numbered_codegen_unit_name(crate_name, index)));
}
}
fn place_inlined_translation_items<'tcx>(initial_partitioning: PreInliningPartitioning<'tcx>,
inlining_map: &InliningMap<'tcx>)
-> PostInliningPartitioning<'tcx> {
let mut new_partitioning = Vec::new();
for codegen_unit in &initial_partitioning.codegen_units[..] {
let mut reachable = FxHashSet();
for root in codegen_unit.items.keys() {
follow_inlining(*root, inlining_map, &mut reachable);
}
let mut new_codegen_unit =
CodegenUnit::empty(codegen_unit.name.clone());
for trans_item in reachable {
if let Some(linkage) = codegen_unit.items.get(&trans_item) {
new_codegen_unit.items.insert(trans_item, *linkage);
} else {
if initial_partitioning.roots.contains(&trans_item) {
bug!("GloballyShared trans-item inlined into other CGU: \
{:?}", trans_item);
}
new_codegen_unit.items.insert(trans_item, llvm::InternalLinkage);
}
}
new_partitioning.push(new_codegen_unit);
}
return PostInliningPartitioning(new_partitioning);
fn follow_inlining<'tcx>(trans_item: TransItem<'tcx>,
inlining_map: &InliningMap<'tcx>,
visited: &mut FxHashSet<TransItem<'tcx>>) {
if !visited.insert(trans_item) {
return;
}
inlining_map.with_inlining_candidates(trans_item, |target| {
follow_inlining(target, inlining_map, visited);
});
}
}
fn characteristic_def_id_of_trans_item<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>,
trans_item: TransItem<'tcx>)
-> Option<DefId> {
let tcx = scx.tcx();
match trans_item {
TransItem::Fn(instance) => {
if tcx.trait_of_item(instance.def).is_some() {
let self_ty = instance.substs.type_at(0);
return characteristic_def_id_of_type(self_ty).or(Some(instance.def));
}
if let Some(impl_def_id) = tcx.impl_of_method(instance.def) {
let impl_self_ty = common::def_ty(scx, impl_def_id, instance.substs);
if let Some(def_id) = characteristic_def_id_of_type(impl_self_ty) {
return Some(def_id);
}
}
Some(instance.def)
}
TransItem::DropGlue(dg) => characteristic_def_id_of_type(dg.ty()),
TransItem::Static(node_id) => Some(tcx.hir.local_def_id(node_id)),
}
}
fn compute_codegen_unit_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
def_id: DefId,
volatile: bool)
-> InternedString {
let mut mod_path = String::with_capacity(64);
let def_path = tcx.def_path(def_id);
mod_path.push_str(&tcx.crate_name(def_path.krate).as_str());
for part in tcx.def_path(def_id)
.data
.iter()
.take_while(|part| {
match part.data {
DefPathData::Module(..) => true,
_ => false,
}
}) {
mod_path.push_str("-");
mod_path.push_str(&part.data.as_interned_str());
}
if volatile {
mod_path.push_str(".volatile");
}
return Symbol::intern(&mod_path[..]).as_str();
}
fn numbered_codegen_unit_name(crate_name: &str, index: usize) -> InternedString {
Symbol::intern(&format!("{}{}{}", crate_name, NUMBERED_CODEGEN_UNIT_MARKER, index)).as_str()
}
fn debug_dump<'a, 'b, 'tcx, I>(scx: &SharedCrateContext<'a, 'tcx>,
label: &str,
cgus: I)
where I: Iterator<Item=&'b CodegenUnit<'tcx>>,
'tcx: 'a + 'b
{
if cfg!(debug_assertions) {
debug!("{}", label);
for cgu in cgus {
let symbol_map = SymbolMap::build(scx, cgu.items
.iter()
.map(|(&trans_item, _)| trans_item));
debug!("CodegenUnit {}:", cgu.name);
for (trans_item, linkage) in &cgu.items {
let symbol_name = symbol_map.get_or_compute(scx, *trans_item);
let symbol_hash_start = symbol_name.rfind('h');
let symbol_hash = symbol_hash_start.map(|i| &symbol_name[i ..])
.unwrap_or("<no hash>");
debug!(" - {} [{:?}] [{}]",
trans_item.to_string(scx.tcx()),
linkage,
symbol_hash);
}
debug!("");
}
}
}