Skip to content

Rollup of 4 pull requests #113821

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 10 commits into from
Closed
24 changes: 14 additions & 10 deletions compiler/rustc_ast_lowering/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1619,13 +1619,15 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
debug!(?hir_bounds);

let lifetime_mapping = if in_trait {
self.arena.alloc_from_iter(
collected_lifetime_mapping
.iter()
.map(|(lifetime, def_id)| (**lifetime, *def_id)),
Some(
&*self.arena.alloc_from_iter(
collected_lifetime_mapping
.iter()
.map(|(lifetime, def_id)| (**lifetime, *def_id)),
),
)
} else {
&mut []
None
};

let opaque_ty_item = hir::OpaqueTy {
Expand Down Expand Up @@ -2090,13 +2092,15 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
debug!("lower_async_fn_ret_ty: generic_params={:#?}", generic_params);

let lifetime_mapping = if in_trait {
self.arena.alloc_from_iter(
collected_lifetime_mapping
.iter()
.map(|(lifetime, def_id)| (**lifetime, *def_id)),
Some(
&*self.arena.alloc_from_iter(
collected_lifetime_mapping
.iter()
.map(|(lifetime, def_id)| (**lifetime, *def_id)),
),
)
} else {
&mut []
None
};

let opaque_ty_item = hir::OpaqueTy {
Expand Down
4 changes: 4 additions & 0 deletions compiler/rustc_codegen_llvm/src/attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,10 @@ pub fn from_fn_attrs<'ll, 'tcx>(
to_add.extend(probestack_attr(cx));
to_add.extend(stackprotector_attr(cx));

if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NO_BUILTINS) {
to_add.push(llvm::CreateAttrString(cx.llcx, "no-builtins"));
}

if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
to_add.push(AttributeKind::Cold.create_attr(cx.llcx));
}
Expand Down
10 changes: 9 additions & 1 deletion compiler/rustc_codegen_ssa/src/codegen_attrs.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use rustc_ast::{ast, MetaItemKind, NestedMetaItem};
use rustc_ast::{ast, attr, MetaItemKind, NestedMetaItem};
use rustc_attr::{list_contains_name, InlineAttr, InstructionSetAttr, OptimizeAttr};
use rustc_errors::struct_span_err;
use rustc_hir as hir;
Expand Down Expand Up @@ -60,6 +60,14 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
}

// When `no_builtins` is applied at the crate level, we should add the
// `no-builtins` attribute to each function to ensure it takes effect in LTO.
let crate_attrs = tcx.hir().attrs(rustc_hir::CRATE_HIR_ID);
let no_builtins = attr::contains_name(crate_attrs, sym::no_builtins);
if no_builtins {
codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_BUILTINS;
}

let supported_target_features = tcx.supported_target_features(LOCAL_CRATE);

let mut inline_span = None;
Expand Down
17 changes: 13 additions & 4 deletions compiler/rustc_hir/src/hir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2664,10 +2664,19 @@ pub struct OpaqueTy<'hir> {
pub generics: &'hir Generics<'hir>,
pub bounds: GenericBounds<'hir>,
pub origin: OpaqueTyOrigin,
// Opaques have duplicated lifetimes, this mapping connects the original lifetime with the copy
// so we can later generate bidirectional outlives predicates to enforce that these lifetimes
// stay in sync.
pub lifetime_mapping: &'hir [(Lifetime, LocalDefId)],
/// Return-position impl traits (and async futures) must "reify" any late-bound
/// lifetimes that are captured from the function signature they originate from.
///
/// This is done by generating a new early-bound lifetime parameter local to the
/// opaque which is substituted in the function signature with the late-bound
/// lifetime.
///
/// This mapping associated a captured lifetime (first parameter) with the new
/// early-bound lifetime that was generated for the opaque.
pub lifetime_mapping: Option<&'hir [(Lifetime, LocalDefId)]>,
/// Whether the opaque is a return-position impl trait (or async future)
/// originating from a trait method. This makes it so that the opaque is
/// lowered as an associated type.
pub in_trait: bool,
}

Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_analysis/src/collect/predicates_of.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen
let opaque_ty_id = tcx.hir().local_def_id_to_hir_id(opaque_def_id.expect_local());
let opaque_ty_node = tcx.hir().get(opaque_ty_id);
let Node::Item(&Item {
kind: ItemKind::OpaqueTy(OpaqueTy { lifetime_mapping, .. }),
kind: ItemKind::OpaqueTy(OpaqueTy { lifetime_mapping: Some(lifetime_mapping), .. }),
..
}) = opaque_ty_node
else {
Expand Down
8 changes: 4 additions & 4 deletions compiler/rustc_lint/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -956,11 +956,11 @@ pub trait LintContext: Sized {
db.span_note(glob_reexport_span, format!("the name `{}` in the {} namespace is supposed to be publicly re-exported here", name, namespace));
db.span_note(private_item_span, "but the private item here shadows it".to_owned());
}
BuiltinLintDiagnostics::UnusedQualifications { path_span, unqualified_path } => {
BuiltinLintDiagnostics::UnusedQualifications { removal_span } => {
db.span_suggestion_verbose(
path_span,
"replace it with the unqualified path",
unqualified_path,
removal_span,
"remove the unnecessary path segments",
"",
Applicability::MachineApplicable
);
}
Expand Down
6 changes: 2 additions & 4 deletions compiler/rustc_lint_defs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -551,10 +551,8 @@ pub enum BuiltinLintDiagnostics {
private_item_span: Span,
},
UnusedQualifications {
/// The span of the unnecessarily-qualified path.
path_span: Span,
/// The replacement unqualified path.
unqualified_path: Ident,
/// The span of the unnecessarily-qualified path to remove.
removal_span: Span,
},
}

Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_middle/src/middle/codegen_fn_attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ bitflags! {
const REALLOCATOR = 1 << 18;
/// `#[rustc_allocator_zeroed]`: a hint to LLVM that the function only allocates zeroed memory.
const ALLOCATOR_ZEROED = 1 << 19;
/// `#[no_builtins]`: indicates that disable implicit builtin knowledge of functions for the function.
const NO_BUILTINS = 1 << 20;
}
}

Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_resolve/src/late.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3911,8 +3911,9 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> {
&& path[0].ident.name != kw::PathRoot
&& path[0].ident.name != kw::DollarCrate
{
let last_segment = *path.last().unwrap();
let unqualified_result = {
match self.resolve_path(&[*path.last().unwrap()], Some(ns), None) {
match self.resolve_path(&[last_segment], Some(ns), None) {
PathResult::NonModule(path_res) => path_res.expect_full_res(),
PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
module.res().unwrap()
Expand All @@ -3928,8 +3929,7 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> {
finalize.path_span,
"unnecessary qualification",
lint::BuiltinLintDiagnostics::UnusedQualifications {
path_span: finalize.path_span,
unqualified_path: path.last().unwrap().ident
removal_span: finalize.path_span.until(last_segment.ident.span),
}
)
}
Expand Down
19 changes: 16 additions & 3 deletions src/librustdoc/clean/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,19 @@ pub(crate) fn clean_doc_module<'tcx>(doc: &DocModule<'tcx>, cx: &mut DocContext<
}
v
}));
items.extend(doc.inlined_foreigns.iter().flat_map(|((_, renamed), (res, local_import_id))| {
let Some(def_id) = res.opt_def_id() else { return Vec::new() };
let name = renamed.unwrap_or_else(|| cx.tcx.item_name(def_id));
let import = cx.tcx.hir().expect_item(*local_import_id);
match import.kind {
hir::ItemKind::Use(path, kind) => {
let hir::UsePath { segments, span, .. } = *path;
let path = hir::Path { segments, res: *res, span };
clean_use_statement_inner(import, name, &path, kind, cx, &mut Default::default())
}
_ => unreachable!(),
}
}));
items.extend(doc.items.values().flat_map(|(item, renamed, _)| {
// Now we actually lower the imports, skipping everything else.
if let hir::ItemKind::Use(path, hir::UseKind::Glob) = item.kind {
Expand Down Expand Up @@ -2652,9 +2665,6 @@ fn clean_use_statement<'tcx>(
let mut items = Vec::new();
let hir::UsePath { segments, ref res, span } = *path;
for &res in res {
if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = res {
continue;
}
let path = hir::Path { segments, res, span };
items.append(&mut clean_use_statement_inner(import, name, &path, kind, cx, inlined_names));
}
Expand All @@ -2669,6 +2679,9 @@ fn clean_use_statement_inner<'tcx>(
cx: &mut DocContext<'tcx>,
inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
) -> Vec<Item> {
if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = path.res {
return Vec::new();
}
// We need this comparison because some imports (for std types for example)
// are "inserted" as well but directly by the compiler and they should not be
// taken into account.
Expand Down
39 changes: 25 additions & 14 deletions src/librustdoc/visit_ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ pub(crate) struct Module<'hir> {
(LocalDefId, Option<Symbol>),
(&'hir hir::Item<'hir>, Option<Symbol>, Option<LocalDefId>),
>,
/// Same as for `items`.
pub(crate) inlined_foreigns: FxIndexMap<(DefId, Option<Symbol>), (Res, LocalDefId)>,
pub(crate) foreigns: Vec<(&'hir hir::ForeignItem<'hir>, Option<Symbol>)>,
}

Expand All @@ -54,6 +56,7 @@ impl Module<'_> {
import_id,
mods: Vec::new(),
items: FxIndexMap::default(),
inlined_foreigns: FxIndexMap::default(),
foreigns: Vec::new(),
}
}
Expand Down Expand Up @@ -272,21 +275,30 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
return false;
}

// For cross-crate impl inlining we need to know whether items are
// reachable in documentation -- a previously unreachable item can be
// made reachable by cross-crate inlining which we're checking here.
// (this is done here because we need to know this upfront).
if !ori_res_did.is_local() && !is_no_inline {
crate::visit_lib::lib_embargo_visit_item(self.cx, ori_res_did);
return false;
}

let is_hidden = !document_hidden && tcx.is_doc_hidden(ori_res_did);
let Some(res_did) = ori_res_did.as_local() else {
return false;
// For cross-crate impl inlining we need to know whether items are
// reachable in documentation -- a previously unreachable item can be
// made reachable by cross-crate inlining which we're checking here.
// (this is done here because we need to know this upfront).
crate::visit_lib::lib_embargo_visit_item(self.cx, ori_res_did);
if is_hidden {
return false;
}
// We store inlined foreign items otherwise, it'd mean that the `use` item would be kept
// around. It's not a problem unless this `use` imports both a local AND a foreign item.
// If a local item is inlined, its `use` is not supposed to still be around in `clean`,
// which would make appear the `use` in the generated documentation like the local item
// was not inlined even though it actually was.
self.modules
.last_mut()
.unwrap()
.inlined_foreigns
.insert((ori_res_did, renamed), (res, def_id));
return true;
};

let is_private = !self.cx.cache.effective_visibilities.is_directly_public(tcx, ori_res_did);
let is_hidden = !document_hidden && tcx.is_doc_hidden(ori_res_did);
let item = tcx.hir().get_by_def_id(res_did);

if !please_inline {
Expand Down Expand Up @@ -314,7 +326,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
return false;
}

let inlined = match tcx.hir().get_by_def_id(res_did) {
let inlined = match item {
// Bang macros are handled a bit on their because of how they are handled by the
// compiler. If they have `#[doc(hidden)]` and the re-export doesn't have
// `#[doc(inline)]`, then we don't inline it.
Expand Down Expand Up @@ -346,7 +358,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
};
self.view_item_stack.remove(&res_did);
if inlined {
self.cx.cache.inlined_items.insert(res_did.to_def_id());
self.cx.cache.inlined_items.insert(ori_res_did);
}
inlined
}
Expand Down Expand Up @@ -483,7 +495,6 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
continue;
}
}

self.add_to_current_mod(item, renamed, import_id);
}
}
Expand Down
23 changes: 23 additions & 0 deletions tests/codegen/no_builtins-at-crate.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// compile-flags: -C opt-level=1

#![no_builtins]
#![crate_type = "lib"]

// CHECK: define void @__aeabi_memcpy
// CHECK-SAME: #0
#[no_mangle]
pub unsafe extern "C" fn __aeabi_memcpy(dest: *mut u8, src: *const u8, size: usize) {
// CHECK: call
// CHECK-SAME: @memcpy(
memcpy(dest, src, size);
}

// CHECK: declare
// CHECK-SAME: @memcpy
// CHECK-SAME: #0
extern "C" {
pub fn memcpy(dest: *mut u8, src: *const u8, n: usize) -> *mut u8;
}

// CHECK: attributes #0
// CHECK-SAME: "no-builtins"
9 changes: 9 additions & 0 deletions tests/run-make/no-builtins-attribute/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
include ../tools.mk

# We want to check if `no-builtins` is also added to the function declarations in the used crate.

all:
$(RUSTC) no_builtins.rs --emit=link
$(RUSTC) main.rs --emit=llvm-ir

cat "$(TMPDIR)"/main.ll | "$(LLVM_FILECHECK)" filecheck.main.txt
5 changes: 5 additions & 0 deletions tests/run-make/no-builtins-attribute/filecheck.main.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
CHECK: declare void @foo()
CHECK-SAME: #[[ATTR_3:[0-9]+]]

CHECK: attributes #[[ATTR_3]]
CHECK-SAME: no-builtins
10 changes: 10 additions & 0 deletions tests/run-make/no-builtins-attribute/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
extern crate no_builtins;

#[no_mangle]
fn call_foo() {
no_builtins::foo();
}

fn main() {
call_foo();
}
5 changes: 5 additions & 0 deletions tests/run-make/no-builtins-attribute/no_builtins.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#![crate_type = "lib"]
#![no_builtins]

#[no_mangle]
pub fn foo() {}
25 changes: 25 additions & 0 deletions tests/rustdoc/issue-105735-overlapping-reexport-2.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// Regression test to ensure that both `AtomicU8` items are displayed but not the re-export.

#![crate_name = "foo"]
#![no_std]

// @has 'foo/index.html'
// @has - '//*[@class="item-name"]/a[@class="type"]' 'AtomicU8'
// @has - '//*[@class="item-name"]/a[@class="constant"]' 'AtomicU8'
// We also ensure we don't have another item displayed.
// @count - '//*[@id="main-content"]/*[@class="small-section-header"]' 2
// @has - '//*[@id="main-content"]/*[@class="small-section-header"]' 'Type Definitions'
// @has - '//*[@id="main-content"]/*[@class="small-section-header"]' 'Constants'

mod other {
pub type AtomicU8 = ();
}

mod thing {
pub use crate::other::AtomicU8;

#[allow(non_upper_case_globals)]
pub const AtomicU8: () = ();
}

pub use crate::thing::AtomicU8;
21 changes: 21 additions & 0 deletions tests/rustdoc/issue-105735-overlapping-reexport.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Regression test to ensure that both `AtomicU8` items are displayed but not the re-export.

#![crate_name = "foo"]
#![no_std]

// @has 'foo/index.html'
// @has - '//*[@class="item-name"]/a[@class="struct"]' 'AtomicU8'
// @has - '//*[@class="item-name"]/a[@class="constant"]' 'AtomicU8'
// We also ensure we don't have another item displayed.
// @count - '//*[@id="main-content"]/*[@class="small-section-header"]' 2
// @has - '//*[@id="main-content"]/*[@class="small-section-header"]' 'Structs'
// @has - '//*[@id="main-content"]/*[@class="small-section-header"]' 'Constants'

mod thing {
pub use core::sync::atomic::AtomicU8;

#[allow(non_upper_case_globals)]
pub const AtomicU8: () = ();
}

pub use crate::thing::AtomicU8;
Loading