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
use borrow_check::borrow_set::BorrowSet;
use borrow_check::location::{LocationIndex, LocationTable};
use borrow_check::nll::facts::AllFactsExt;
use borrow_check::nll::type_check::MirTypeckRegionConstraints;
use dataflow::indexes::BorrowIndex;
use dataflow::move_paths::MoveData;
use dataflow::FlowAtLocation;
use dataflow::MaybeInitializedPlaces;
use rustc::hir::def_id::DefId;
use rustc::infer::InferCtxt;
use rustc::mir::{ClosureOutlivesSubject, ClosureRegionRequirements, Mir};
use rustc::ty::{self, RegionKind, RegionVid};
use rustc::util::nodemap::FxHashMap;
use std::collections::BTreeSet;
use std::fmt::Debug;
use std::env;
use std::io;
use std::path::PathBuf;
use std::rc::Rc;
use std::str::FromStr;
use transform::MirSource;
use util::liveness::{LivenessResults, LocalSet};
use self::mir_util::PassWhere;
use polonius_engine::{Algorithm, Output};
use util as mir_util;
use util::pretty::{self, ALIGN};
mod constraint_generation;
pub mod explain_borrow;
mod facts;
mod invalidation;
crate mod region_infer;
mod renumber;
crate mod type_check;
mod universal_regions;
use self::facts::AllFacts;
use self::region_infer::RegionInferenceContext;
use self::universal_regions::UniversalRegions;
pub(in borrow_check) fn replace_regions_in_mir<'cx, 'gcx, 'tcx>(
infcx: &InferCtxt<'cx, 'gcx, 'tcx>,
def_id: DefId,
param_env: ty::ParamEnv<'tcx>,
mir: &mut Mir<'tcx>,
) -> UniversalRegions<'tcx> {
debug!("replace_regions_in_mir(def_id={:?})", def_id);
let universal_regions = UniversalRegions::new(infcx, def_id, param_env);
renumber::renumber_mir(infcx, mir);
let source = MirSource::item(def_id);
mir_util::dump_mir(infcx.tcx, None, "renumber", &0, source, mir, |_, _| Ok(()));
universal_regions
}
pub(in borrow_check) fn compute_regions<'cx, 'gcx, 'tcx>(
infcx: &InferCtxt<'cx, 'gcx, 'tcx>,
def_id: DefId,
universal_regions: UniversalRegions<'tcx>,
mir: &Mir<'tcx>,
location_table: &LocationTable,
param_env: ty::ParamEnv<'gcx>,
flow_inits: &mut FlowAtLocation<MaybeInitializedPlaces<'cx, 'gcx, 'tcx>>,
move_data: &MoveData<'tcx>,
borrow_set: &BorrowSet<'tcx>,
) -> (
RegionInferenceContext<'tcx>,
Option<Rc<Output<RegionVid, BorrowIndex, LocationIndex>>>,
Option<ClosureRegionRequirements<'gcx>>,
) {
let mut all_facts = if infcx.tcx.sess.opts.debugging_opts.nll_facts
|| infcx.tcx.sess.opts.debugging_opts.polonius
{
Some(AllFacts::default())
} else {
None
};
let liveness = &LivenessResults::compute(mir);
let constraint_sets = type_check::type_check(
infcx,
param_env,
mir,
def_id,
&universal_regions,
location_table,
&liveness,
&mut all_facts,
flow_inits,
move_data,
);
if let Some(all_facts) = &mut all_facts {
all_facts
.universal_region
.extend(universal_regions.universal_regions());
}
let var_origins = infcx.take_region_var_origins();
let MirTypeckRegionConstraints {
liveness_set,
outlives_constraints,
type_tests,
} = constraint_sets;
let mut regioncx = RegionInferenceContext::new(
var_origins,
universal_regions,
mir,
outlives_constraints,
type_tests,
);
constraint_generation::generate_constraints(
infcx,
&mut regioncx,
&mut all_facts,
location_table,
&mir,
borrow_set,
&liveness_set,
);
invalidation::generate_invalidates(
infcx,
&mut all_facts,
location_table,
&mir,
def_id,
borrow_set,
);
let polonius_output = all_facts.and_then(|all_facts| {
if infcx.tcx.sess.opts.debugging_opts.nll_facts {
let def_path = infcx.tcx.hir.def_path(def_id);
let dir_path =
PathBuf::from("nll-facts").join(def_path.to_filename_friendly_no_crate());
all_facts.write_to_dir(dir_path, location_table).unwrap();
}
if infcx.tcx.sess.opts.debugging_opts.polonius {
let algorithm = env::var("POLONIUS_ALGORITHM")
.unwrap_or(String::from("DatafrogOpt"));
let algorithm = Algorithm::from_str(&algorithm).unwrap();
debug!("compute_regions: using polonius algorithm {:?}", algorithm);
Some(Rc::new(Output::compute(
&all_facts,
algorithm,
false,
)))
} else {
None
}
});
let closure_region_requirements = regioncx.solve(infcx, &mir, def_id);
dump_mir_results(
infcx,
liveness,
MirSource::item(def_id),
&mir,
®ioncx,
&closure_region_requirements,
);
dump_annotation(infcx, &mir, def_id, ®ioncx, &closure_region_requirements);
(regioncx, polonius_output, closure_region_requirements)
}
fn dump_mir_results<'a, 'gcx, 'tcx>(
infcx: &InferCtxt<'a, 'gcx, 'tcx>,
liveness: &LivenessResults,
source: MirSource,
mir: &Mir<'tcx>,
regioncx: &RegionInferenceContext,
closure_region_requirements: &Option<ClosureRegionRequirements>,
) {
if !mir_util::dump_enabled(infcx.tcx, "nll", source) {
return;
}
let regular_liveness_per_location: FxHashMap<_, _> = mir
.basic_blocks()
.indices()
.flat_map(|bb| {
let mut results = vec![];
liveness
.regular
.simulate_block(&mir, bb, |location, local_set| {
results.push((location, local_set.clone()));
});
results
})
.collect();
let drop_liveness_per_location: FxHashMap<_, _> = mir
.basic_blocks()
.indices()
.flat_map(|bb| {
let mut results = vec![];
liveness
.drop
.simulate_block(&mir, bb, |location, local_set| {
results.push((location, local_set.clone()));
});
results
})
.collect();
mir_util::dump_mir(
infcx.tcx,
None,
"nll",
&0,
source,
mir,
|pass_where, out| {
match pass_where {
PassWhere::BeforeCFG => {
regioncx.dump_mir(out)?;
if let Some(closure_region_requirements) = closure_region_requirements {
writeln!(out, "|")?;
writeln!(out, "| Free Region Constraints")?;
for_each_region_constraint(closure_region_requirements, &mut |msg| {
writeln!(out, "| {}", msg)
})?;
}
}
PassWhere::BeforeBlock(bb) => {
let s = live_variable_set(&liveness.regular.ins[bb], &liveness.drop.ins[bb]);
writeln!(out, " | Live variables on entry to {:?}: {}", bb, s)?;
}
PassWhere::BeforeLocation(location) => {
let s = live_variable_set(
®ular_liveness_per_location[&location],
&drop_liveness_per_location[&location],
);
writeln!(
out,
"{:ALIGN$} | Live variables on entry to {:?}: {}",
"",
location,
s,
ALIGN = ALIGN
)?;
}
PassWhere::AfterLocation(_) | PassWhere::AfterCFG => {}
}
Ok(())
},
);
let _: io::Result<()> = do catch {
let mut file =
pretty::create_dump_file(infcx.tcx, "regioncx.dot", None, "nll", &0, source)?;
regioncx.dump_graphviz(&mut file)?;
};
}
fn dump_annotation<'a, 'gcx, 'tcx>(
infcx: &InferCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
mir_def_id: DefId,
regioncx: &RegionInferenceContext,
closure_region_requirements: &Option<ClosureRegionRequirements>,
) {
let tcx = infcx.tcx;
let base_def_id = tcx.closure_base_def_id(mir_def_id);
if !tcx.has_attr(base_def_id, "rustc_regions") {
return;
}
if let Some(closure_region_requirements) = closure_region_requirements {
let mut err = tcx
.sess
.diagnostic()
.span_note_diag(mir.span, "External requirements");
regioncx.annotate(&mut err);
err.note(&format!(
"number of external vids: {}",
closure_region_requirements.num_external_vids
));
for_each_region_constraint(closure_region_requirements, &mut |msg| {
err.note(msg);
Ok(())
}).unwrap();
err.emit();
} else {
let mut err = tcx
.sess
.diagnostic()
.span_note_diag(mir.span, "No external requirements");
regioncx.annotate(&mut err);
err.emit();
}
}
fn for_each_region_constraint(
closure_region_requirements: &ClosureRegionRequirements,
with_msg: &mut dyn FnMut(&str) -> io::Result<()>,
) -> io::Result<()> {
for req in &closure_region_requirements.outlives_requirements {
let subject: &dyn Debug = match &req.subject {
ClosureOutlivesSubject::Region(subject) => subject,
ClosureOutlivesSubject::Ty(ty) => ty,
};
with_msg(&format!(
"where {:?}: {:?}",
subject, req.outlived_free_region,
))?;
}
Ok(())
}
pub trait ToRegionVid {
fn to_region_vid(self) -> RegionVid;
}
impl<'tcx> ToRegionVid for &'tcx RegionKind {
fn to_region_vid(self) -> RegionVid {
if let ty::ReVar(vid) = self {
*vid
} else {
bug!("region is not an ReVar: {:?}", self)
}
}
}
impl ToRegionVid for RegionVid {
fn to_region_vid(self) -> RegionVid {
self
}
}
fn live_variable_set(regular: &LocalSet, drops: &LocalSet) -> String {
let all_locals: BTreeSet<_> = regular.iter().chain(drops.iter()).collect();
let mut string = String::new();
for local in all_locals {
string.push_str(&format!("{:?}", local));
if !regular.contains(&local) {
assert!(drops.contains(&local));
string.push_str(" (drop)");
}
string.push_str(", ");
}
let len = if string.is_empty() {
0
} else {
string.len() - 2
};
format!("[{}]", &string[..len])
}