Skip to content

Commit 6717106

Browse files
Aatchmichaelwoerister
authored andcommitted
Drive function item translation from collector
Functions and method are declared ahead-of-time, including generic ones. Closures are not considered trans items anymore, instead they are translated on demands.
1 parent 891c2a0 commit 6717106

File tree

6 files changed

+211
-175
lines changed

6 files changed

+211
-175
lines changed

src/librustc_trans/base.rs

Lines changed: 90 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@ use debuginfo::{self, DebugLoc, ToDebugLoc};
7575
use declare;
7676
use expr;
7777
use glue;
78+
use inline;
7879
use machine;
7980
use machine::{llalign_of_min, llsize_of, llsize_of_real};
8081
use meth;
@@ -1948,6 +1949,49 @@ pub fn trans_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
19481949
closure::ClosureEnv::NotClosure);
19491950
}
19501951

1952+
pub fn trans_instance<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, instance: Instance<'tcx>) {
1953+
let instance = inline::maybe_inline_instance(ccx, instance);
1954+
1955+
let fn_node_id = ccx.tcx().map.as_local_node_id(instance.def).unwrap();
1956+
1957+
let _s = StatRecorder::new(ccx, ccx.tcx().node_path_str(fn_node_id));
1958+
debug!("trans_instance(instance={:?})", instance);
1959+
let _icx = push_ctxt("trans_instance");
1960+
1961+
let item = ccx.tcx().map.find(fn_node_id).unwrap();
1962+
1963+
let fn_ty = ccx.tcx().lookup_item_type(instance.def).ty;
1964+
let fn_ty = ccx.tcx().erase_regions(&fn_ty);
1965+
let fn_ty = monomorphize::apply_param_substs(ccx.tcx(), instance.substs, &fn_ty);
1966+
1967+
let sig = ccx.tcx().erase_late_bound_regions(fn_ty.fn_sig());
1968+
let sig = ccx.tcx().normalize_associated_type(&sig);
1969+
let abi = fn_ty.fn_abi();
1970+
1971+
let lldecl = match ccx.instances().borrow().get(&instance) {
1972+
Some(&val) => val,
1973+
None => bug!("Instance `{:?}` not already declared", instance)
1974+
};
1975+
1976+
match item {
1977+
hir_map::NodeItem(&hir::Item {
1978+
node: hir::ItemFn(ref decl, _, _, _, _, ref body), ..
1979+
}) |
1980+
hir_map::NodeTraitItem(&hir::TraitItem {
1981+
node: hir::MethodTraitItem(
1982+
hir::MethodSig { ref decl, .. }, Some(ref body)), ..
1983+
}) |
1984+
hir_map::NodeImplItem(&hir::ImplItem {
1985+
node: hir::ImplItemKind::Method(
1986+
hir::MethodSig { ref decl, .. }, ref body), ..
1987+
}) => {
1988+
trans_closure(ccx, decl, body, lldecl, instance,
1989+
fn_node_id, &sig, abi, closure::ClosureEnv::NotClosure);
1990+
}
1991+
_ => bug!("Instance is a {:?}?", item)
1992+
}
1993+
}
1994+
19511995
pub fn trans_named_tuple_constructor<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
19521996
ctor_ty: Ty<'tcx>,
19531997
disr: Disr,
@@ -2267,79 +2311,33 @@ pub fn trans_item(ccx: &CrateContext, item: &hir::Item) {
22672311
let _icx = push_ctxt("trans_item");
22682312

22692313
let tcx = ccx.tcx();
2270-
let from_external = ccx.external_srcs().borrow().contains_key(&item.id);
2271-
22722314
match item.node {
2273-
hir::ItemFn(ref decl, _, _, _, ref generics, ref body) => {
2274-
if !generics.is_type_parameterized() {
2275-
let trans_everywhere = attr::requests_inline(&item.attrs);
2276-
// Ignore `trans_everywhere` for cross-crate inlined items
2277-
// (`from_external`). `trans_item` will be called once for each
2278-
// compilation unit that references the item, so it will still get
2279-
// translated everywhere it's needed.
2280-
for (ref ccx, is_origin) in ccx.maybe_iter(!from_external && trans_everywhere) {
2281-
let def_id = tcx.map.local_def_id(item.id);
2282-
let empty_substs = ccx.empty_substs_for_def_id(def_id);
2283-
let llfn = Callee::def(ccx, def_id, empty_substs).reify(ccx).val;
2284-
trans_fn(ccx, &decl, &body, llfn, empty_substs, item.id);
2285-
set_link_section(ccx, llfn, &item.attrs);
2286-
update_linkage(ccx,
2287-
llfn,
2288-
Some(item.id),
2289-
if is_origin {
2290-
OriginalTranslation
2291-
} else {
2292-
InlinedCopy
2293-
});
2294-
2295-
if is_entry_fn(ccx.sess(), item.id) {
2296-
create_entry_wrapper(ccx, item.span, llfn);
2297-
// check for the #[rustc_error] annotation, which forces an
2298-
// error in trans. This is used to write compile-fail tests
2299-
// that actually test that compilation succeeds without
2300-
// reporting an error.
2301-
if tcx.has_attr(def_id, "rustc_error") {
2302-
tcx.sess.span_fatal(item.span, "compilation successful");
2303-
}
2304-
}
2315+
hir::ItemFn(_, _, _, _, _, _) => {
2316+
let def_id = tcx.map.local_def_id(item.id);
2317+
// check for the #[rustc_error] annotation, which forces an
2318+
// error in trans. This is used to write compile-fail tests
2319+
// that actually test that compilation succeeds without
2320+
// reporting an error.
2321+
if is_entry_fn(ccx.sess(), item.id) {
2322+
let empty_substs = ccx.empty_substs_for_def_id(def_id);
2323+
let llfn = Callee::def(ccx, def_id, empty_substs).reify(ccx).val;
2324+
create_entry_wrapper(ccx, item.span, llfn);
2325+
if tcx.has_attr(def_id, "rustc_error") {
2326+
tcx.sess.span_fatal(item.span, "compilation successful");
23052327
}
23062328
}
2307-
}
2308-
hir::ItemImpl(_, _, ref generics, _, _, ref impl_items) => {
2309-
// Both here and below with generic methods, be sure to recurse and look for
2310-
// items that we need to translate.
2311-
if !generics.ty_params.is_empty() {
2312-
return;
2313-
}
23142329

2315-
for impl_item in impl_items {
2316-
if let hir::ImplItemKind::Method(ref sig, ref body) = impl_item.node {
2317-
if sig.generics.ty_params.is_empty() {
2318-
let trans_everywhere = attr::requests_inline(&impl_item.attrs);
2319-
for (ref ccx, is_origin) in ccx.maybe_iter(trans_everywhere) {
2320-
let def_id = tcx.map.local_def_id(impl_item.id);
2321-
let empty_substs = ccx.empty_substs_for_def_id(def_id);
2322-
let llfn = Callee::def(ccx, def_id, empty_substs).reify(ccx).val;
2323-
trans_fn(ccx, &sig.decl, body, llfn, empty_substs, impl_item.id);
2324-
update_linkage(ccx, llfn, Some(impl_item.id),
2325-
if is_origin {
2326-
OriginalTranslation
2327-
} else {
2328-
InlinedCopy
2329-
});
2330-
}
2331-
}
2332-
}
2333-
}
2330+
// Function is actually translated in trans_instance
23342331
}
23352332
hir::ItemEnum(ref enum_definition, ref gens) => {
23362333
if gens.ty_params.is_empty() {
23372334
// sizes only make sense for non-generic types
23382335
enum_variant_size_lint(ccx, enum_definition, item.span, item.id);
23392336
}
23402337
}
2338+
hir::ItemImpl(..) |
23412339
hir::ItemStatic(..) => {
2342-
// Don't do anything here. Translation of statics has been moved to
2340+
// Don't do anything here. Translation has been moved to
23432341
// being "collector-driven".
23442342
}
23452343
_ => {}
@@ -2482,16 +2480,16 @@ fn internalize_symbols(cx: &CrateContextList, reachable: &HashSet<&str>) {
24822480
let linkage = llvm::LLVMGetLinkage(val);
24832481
// We only care about external declarations (not definitions)
24842482
// and available_externally definitions.
2485-
if !(linkage == llvm::ExternalLinkage as c_uint &&
2486-
llvm::LLVMIsDeclaration(val) != 0) &&
2487-
!(linkage == llvm::AvailableExternallyLinkage as c_uint) {
2488-
continue;
2483+
let is_available_externally = linkage == llvm::AvailableExternallyLinkage as c_uint;
2484+
let is_decl = llvm::LLVMIsDeclaration(val) != 0;
2485+
2486+
if is_decl || is_available_externally {
2487+
let name = CStr::from_ptr(llvm::LLVMGetValueName(val))
2488+
.to_bytes()
2489+
.to_vec();
2490+
declared.insert(name);
24892491
}
24902492

2491-
let name = CStr::from_ptr(llvm::LLVMGetValueName(val))
2492-
.to_bytes()
2493-
.to_vec();
2494-
declared.insert(name);
24952493
}
24962494
}
24972495

@@ -2501,21 +2499,27 @@ fn internalize_symbols(cx: &CrateContextList, reachable: &HashSet<&str>) {
25012499
for ccx in cx.iter() {
25022500
for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
25032501
let linkage = llvm::LLVMGetLinkage(val);
2502+
2503+
let is_external = linkage == llvm::ExternalLinkage as c_uint;
2504+
let is_weak_odr = linkage == llvm::WeakODRLinkage as c_uint;
2505+
let is_decl = llvm::LLVMIsDeclaration(val) != 0;
2506+
25042507
// We only care about external definitions.
2505-
if !((linkage == llvm::ExternalLinkage as c_uint ||
2506-
linkage == llvm::WeakODRLinkage as c_uint) &&
2507-
llvm::LLVMIsDeclaration(val) == 0) {
2508-
continue;
2509-
}
2508+
if (is_external || is_weak_odr) && !is_decl {
2509+
2510+
let name = CStr::from_ptr(llvm::LLVMGetValueName(val))
2511+
.to_bytes()
2512+
.to_vec();
2513+
2514+
let is_declared = declared.contains(&name);
2515+
let reachable = reachable.contains(str::from_utf8(&name).unwrap());
2516+
2517+
if !is_declared && !reachable {
2518+
llvm::SetLinkage(val, llvm::InternalLinkage);
2519+
llvm::SetDLLStorageClass(val, llvm::DefaultStorageClass);
2520+
llvm::UnsetComdat(val);
2521+
}
25102522

2511-
let name = CStr::from_ptr(llvm::LLVMGetValueName(val))
2512-
.to_bytes()
2513-
.to_vec();
2514-
if !declared.contains(&name) &&
2515-
!reachable.contains(str::from_utf8(&name).unwrap()) {
2516-
llvm::SetLinkage(val, llvm::InternalLinkage);
2517-
llvm::SetDLLStorageClass(val, llvm::DefaultStorageClass);
2518-
llvm::UnsetComdat(val);
25192523
}
25202524
}
25212525
}
@@ -2744,6 +2748,9 @@ pub fn trans_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
27442748
span_bug!(item.span, "Mismatch between hir::Item type and TransItem type")
27452749
}
27462750
}
2751+
TransItem::Fn(instance) => {
2752+
trans_instance(&ccx, instance);
2753+
}
27472754
_ => { }
27482755
}
27492756
}
@@ -2980,7 +2987,7 @@ fn collect_and_partition_translation_items<'a, 'tcx>(scx: &SharedCrateContext<'a
29802987
let mut item_keys: Vec<_> = items
29812988
.iter()
29822989
.map(|i| {
2983-
let mut output = i.to_string(scx.tcx());
2990+
let mut output = i.to_string(scx);
29842991
output.push_str(" @@");
29852992
let mut empty = Vec::new();
29862993
let mut cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);

src/librustc_trans/closure.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
use arena::TypedArena;
1212
use back::symbol_names;
13-
use llvm::{ValueRef, get_param, get_params};
13+
use llvm::{self, ValueRef, get_param, get_params};
1414
use rustc::hir::def_id::DefId;
1515
use abi::{Abi, FnType};
1616
use adt;
@@ -167,7 +167,7 @@ fn get_or_create_closure_declaration<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
167167
variadic: false
168168
})
169169
}));
170-
let llfn = declare::define_internal_fn(ccx, &symbol, function_type);
170+
let llfn = declare::declare_fn(ccx, &symbol, function_type);
171171

172172
// set an inline hint for all closures
173173
attributes::inline(llfn, attributes::InlineAttr::Hint);
@@ -211,6 +211,7 @@ pub fn trans_closure_expr<'a, 'tcx>(dest: Dest<'a, 'tcx>,
211211
id, closure_def_id, closure_substs);
212212

213213
let llfn = get_or_create_closure_declaration(ccx, closure_def_id, closure_substs);
214+
llvm::SetLinkage(llfn, llvm::WeakODRLinkage);
214215

215216
// Get the type of this closure. Use the current `param_substs` as
216217
// the closure substitutions. This makes sense because the closure
@@ -377,7 +378,7 @@ fn trans_fn_once_adapter_shim<'a, 'tcx>(
377378
// Create the by-value helper.
378379
let function_name =
379380
symbol_names::internal_name_from_type_and_suffix(ccx, llonce_fn_ty, "once_shim");
380-
let lloncefn = declare::define_internal_fn(ccx, &function_name, llonce_fn_ty);
381+
let lloncefn = declare::declare_fn(ccx, &function_name, llonce_fn_ty);
381382
attributes::set_frame_pointer_elimination(ccx, lloncefn);
382383

383384
let (block_arena, fcx): (TypedArena<_>, FunctionContext);

src/librustc_trans/collector.rs

Lines changed: 26 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -325,7 +325,7 @@ fn collect_items_rec<'a, 'tcx: 'a>(scx: &SharedCrateContext<'a, 'tcx>,
325325
// We've been here already, no need to search again.
326326
return;
327327
}
328-
debug!("BEGIN collect_items_rec({})", starting_point.to_string(scx.tcx()));
328+
debug!("BEGIN collect_items_rec({})", starting_point.to_string(scx));
329329

330330
let mut neighbors = Vec::new();
331331
let recursion_depth_reset;
@@ -396,7 +396,7 @@ fn collect_items_rec<'a, 'tcx: 'a>(scx: &SharedCrateContext<'a, 'tcx>,
396396
recursion_depths.insert(def_id, depth);
397397
}
398398

399-
debug!("END collect_items_rec({})", starting_point.to_string(scx.tcx()));
399+
debug!("END collect_items_rec({})", starting_point.to_string(scx));
400400
}
401401

402402
fn record_inlining_canditates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
@@ -456,12 +456,25 @@ impl<'a, 'tcx> MirVisitor<'tcx> for MirNeighborCollector<'a, 'tcx> {
456456
match *rvalue {
457457
mir::Rvalue::Aggregate(mir::AggregateKind::Closure(def_id,
458458
ref substs), _) => {
459-
assert!(can_have_local_instance(self.scx.tcx(), def_id));
460-
let trans_item = create_fn_trans_item(self.scx.tcx(),
461-
def_id,
462-
substs.func_substs,
463-
self.param_substs);
464-
self.output.push(trans_item);
459+
let mir = errors::expect(self.scx.sess().diagnostic(), self.scx.get_mir(def_id),
460+
|| format!("Could not find MIR for closure: {:?}", def_id));
461+
462+
let concrete_substs = monomorphize::apply_param_substs(self.scx.tcx(),
463+
self.param_substs,
464+
&substs.func_substs);
465+
let concrete_substs = self.scx.tcx().erase_regions(&concrete_substs);
466+
467+
let mut visitor = MirNeighborCollector {
468+
scx: self.scx,
469+
mir: &mir,
470+
output: self.output,
471+
param_substs: concrete_substs
472+
};
473+
474+
visitor.visit_mir(&mir);
475+
for promoted in &mir.promoted {
476+
visitor.visit_mir(promoted);
477+
}
465478
}
466479
// When doing an cast from a regular pointer to a fat pointer, we
467480
// have to instantiate all methods of the trait being cast to, so we
@@ -1107,9 +1120,8 @@ impl<'b, 'a, 'v> hir_visit::Visitor<'v> for RootCollector<'b, 'a, 'v> {
11071120
self.scx.tcx().map.local_def_id(item.id)));
11081121
self.output.push(TransItem::Static(item.id));
11091122
}
1110-
hir::ItemFn(_, _, constness, _, ref generics, _) => {
1111-
if !generics.is_type_parameterized() &&
1112-
constness == hir::Constness::NotConst {
1123+
hir::ItemFn(_, _, _, _, ref generics, _) => {
1124+
if !generics.is_type_parameterized() {
11131125
let def_id = self.scx.tcx().map.local_def_id(item.id);
11141126

11151127
debug!("RootCollector: ItemFn({})",
@@ -1129,9 +1141,8 @@ impl<'b, 'a, 'v> hir_visit::Visitor<'v> for RootCollector<'b, 'a, 'v> {
11291141
match ii.node {
11301142
hir::ImplItemKind::Method(hir::MethodSig {
11311143
ref generics,
1132-
constness,
11331144
..
1134-
}, _) if constness == hir::Constness::NotConst => {
1145+
}, _) => {
11351146
let hir_map = &self.scx.tcx().map;
11361147
let parent_node_id = hir_map.get_parent_node(ii.id);
11371148
let is_impl_generic = match hir_map.expect_item(parent_node_id) {
@@ -1260,7 +1271,7 @@ pub fn print_collection_results<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>) {
12601271
let mut item_keys = FnvHashMap();
12611272

12621273
for (item, item_state) in trans_items.iter() {
1263-
let k = item.to_string(scx.tcx());
1274+
let k = item.to_string(scx);
12641275

12651276
if item_keys.contains_key(&k) {
12661277
let prev: (TransItem, TransItemState) = item_keys[&k];
@@ -1288,7 +1299,7 @@ pub fn print_collection_results<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>) {
12881299
let mut generated = FnvHashSet();
12891300

12901301
for (item, item_state) in trans_items.iter() {
1291-
let item_key = item.to_string(scx.tcx());
1302+
let item_key = item.to_string(scx);
12921303

12931304
match *item_state {
12941305
TransItemState::PredictedAndGenerated => {

0 commit comments

Comments
 (0)