Skip to content

Commit d68c327

Browse files
committed
Auto merge of #131958 - Zalathar:rollup-gkuk3n1, r=Zalathar
Rollup of 4 pull requests Successful merges: - #131876 (compiler: Use LLVM's Comdat support) - #131941 (compiletest: disambiguate html-tidy from rust tidy tool) - #131942 (compiler: Adopt rust-analyzer impls for `LayoutCalculatorError`) - #131945 (rustdoc: Clean up footnote handling) r? `@ghost` `@rustbot` modify labels: rollup
2 parents 54791ef + 456821b commit d68c327

File tree

13 files changed

+189
-113
lines changed

13 files changed

+189
-113
lines changed

compiler/rustc_abi/src/layout.rs

+26-1
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ enum NicheBias {
3939
End,
4040
}
4141

42-
#[derive(Copy, Clone, Debug)]
42+
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
4343
pub enum LayoutCalculatorError<F> {
4444
/// An unsized type was found in a location where a sized type was expected.
4545
///
@@ -56,6 +56,31 @@ pub enum LayoutCalculatorError<F> {
5656
EmptyUnion,
5757
}
5858

59+
impl<F> LayoutCalculatorError<F> {
60+
pub fn without_payload(&self) -> LayoutCalculatorError<()> {
61+
match self {
62+
LayoutCalculatorError::UnexpectedUnsized(_) => {
63+
LayoutCalculatorError::UnexpectedUnsized(())
64+
}
65+
LayoutCalculatorError::SizeOverflow => LayoutCalculatorError::SizeOverflow,
66+
LayoutCalculatorError::EmptyUnion => LayoutCalculatorError::EmptyUnion,
67+
}
68+
}
69+
70+
/// Format an untranslated diagnostic for this type
71+
///
72+
/// Intended for use by rust-analyzer, as neither it nor `rustc_abi` depend on fluent infra.
73+
pub fn fallback_fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74+
f.write_str(match self {
75+
LayoutCalculatorError::UnexpectedUnsized(_) => {
76+
"an unsized type was found where a sized type was expected"
77+
}
78+
LayoutCalculatorError::SizeOverflow => "size overflow",
79+
LayoutCalculatorError::EmptyUnion => "type is a union with no fields",
80+
})
81+
}
82+
}
83+
5984
type LayoutCalculatorResult<FieldIdx, VariantIdx, F> =
6085
Result<LayoutS<FieldIdx, VariantIdx>, LayoutCalculatorError<F>>;
6186

compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ pub(crate) fn finalize(cx: &CodegenCx<'_, '_>) {
132132
.collect::<Vec<_>>();
133133
let initializer = cx.const_array(cx.type_ptr(), &name_globals);
134134

135-
let array = llvm::add_global(cx.llmod, cx.val_ty(initializer), "__llvm_coverage_names");
135+
let array = llvm::add_global(cx.llmod, cx.val_ty(initializer), c"__llvm_coverage_names");
136136
llvm::set_global_constant(array, true);
137137
llvm::set_linkage(array, llvm::Linkage::InternalLinkage);
138138
llvm::set_initializer(array, initializer);

compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs

+10-5
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use std::cell::RefCell;
2+
use std::ffi::CString;
23

34
use libc::c_uint;
45
use rustc_codegen_ssa::traits::{
@@ -12,6 +13,7 @@ use rustc_middle::mir::coverage::CoverageKind;
1213
use rustc_middle::ty::Instance;
1314
use rustc_middle::ty::layout::HasTyCtxt;
1415
use rustc_target::abi::{Align, Size};
16+
use rustc_target::spec::HasTargetSpec;
1517
use tracing::{debug, instrument};
1618

1719
use crate::builder::Builder;
@@ -284,10 +286,10 @@ pub(crate) fn save_cov_data_to_mod<'ll, 'tcx>(
284286
cx: &CodegenCx<'ll, 'tcx>,
285287
cov_data_val: &'ll llvm::Value,
286288
) {
287-
let covmap_var_name = llvm::build_string(|s| unsafe {
289+
let covmap_var_name = CString::new(llvm::build_byte_buffer(|s| unsafe {
288290
llvm::LLVMRustCoverageWriteMappingVarNameToString(s);
289-
})
290-
.expect("Rust Coverage Mapping var name failed UTF-8 conversion");
291+
}))
292+
.unwrap();
291293
debug!("covmap var name: {:?}", covmap_var_name);
292294

293295
let covmap_section_name = llvm::build_string(|s| unsafe {
@@ -322,7 +324,8 @@ pub(crate) fn save_func_record_to_mod<'ll, 'tcx>(
322324
// of descriptions play distinct roles in LLVM IR; therefore, assign them different names (by
323325
// appending "u" to the end of the function record var name, to prevent `linkonce_odr` merging.
324326
let func_record_var_name =
325-
format!("__covrec_{:X}{}", func_name_hash, if is_used { "u" } else { "" });
327+
CString::new(format!("__covrec_{:X}{}", func_name_hash, if is_used { "u" } else { "" }))
328+
.unwrap();
326329
debug!("function record var name: {:?}", func_record_var_name);
327330
debug!("function record section name: {:?}", covfun_section_name);
328331

@@ -334,7 +337,9 @@ pub(crate) fn save_func_record_to_mod<'ll, 'tcx>(
334337
llvm::set_section(llglobal, covfun_section_name);
335338
// LLVM's coverage mapping format specifies 8-byte alignment for items in this section.
336339
llvm::set_alignment(llglobal, Align::EIGHT);
337-
llvm::set_comdat(cx.llmod, llglobal, &func_record_var_name);
340+
if cx.target_spec().supports_comdat() {
341+
llvm::set_comdat(cx.llmod, llglobal, &func_record_var_name);
342+
}
338343
cx.add_used_global(llglobal);
339344
}
340345

compiler/rustc_codegen_llvm/src/intrinsic.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -787,7 +787,9 @@ fn codegen_msvc_try<'ll>(
787787
let tydesc = bx.declare_global("__rust_panic_type_info", bx.val_ty(type_info));
788788
unsafe {
789789
llvm::LLVMRustSetLinkage(tydesc, llvm::Linkage::LinkOnceODRLinkage);
790-
llvm::SetUniqueComdat(bx.llmod, tydesc);
790+
if bx.cx.tcx.sess.target.supports_comdat() {
791+
llvm::SetUniqueComdat(bx.llmod, tydesc);
792+
}
791793
llvm::LLVMSetInitializer(tydesc, type_info);
792794
}
793795

compiler/rustc_codegen_llvm/src/llvm/ffi.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -646,6 +646,7 @@ unsafe extern "C" {
646646
pub type Attribute;
647647
pub type Metadata;
648648
pub type BasicBlock;
649+
pub type Comdat;
649650
}
650651
#[repr(C)]
651652
pub struct Builder<'a>(InvariantOpaque<'a>);
@@ -1490,6 +1491,9 @@ unsafe extern "C" {
14901491
pub fn LLVMSetUnnamedAddress(Global: &Value, UnnamedAddr: UnnamedAddr);
14911492

14921493
pub fn LLVMIsAConstantInt(value_ref: &Value) -> Option<&ConstantInt>;
1494+
1495+
pub fn LLVMGetOrInsertComdat(M: &Module, Name: *const c_char) -> &Comdat;
1496+
pub fn LLVMSetComdat(V: &Value, C: &Comdat);
14931497
}
14941498

14951499
#[link(name = "llvm-wrapper", kind = "static")]
@@ -2320,7 +2324,6 @@ unsafe extern "C" {
23202324

23212325
pub fn LLVMRustPositionBuilderAtStart<'a>(B: &Builder<'a>, BB: &'a BasicBlock);
23222326

2323-
pub fn LLVMRustSetComdat<'a>(M: &'a Module, V: &'a Value, Name: *const c_char, NameLen: size_t);
23242327
pub fn LLVMRustSetModulePICLevel(M: &Module);
23252328
pub fn LLVMRustSetModulePIELevel(M: &Module);
23262329
pub fn LLVMRustSetModuleCodeModel(M: &Module, Model: CodeModel);

compiler/rustc_codegen_llvm/src/llvm/mod.rs

+12-8
Original file line numberDiff line numberDiff line change
@@ -178,10 +178,10 @@ pub fn SetFunctionCallConv(fn_: &Value, cc: CallConv) {
178178
// function.
179179
// For more details on COMDAT sections see e.g., https://www.airs.com/blog/archives/52
180180
pub fn SetUniqueComdat(llmod: &Module, val: &Value) {
181-
unsafe {
182-
let name = get_value_name(val);
183-
LLVMRustSetComdat(llmod, val, name.as_ptr().cast(), name.len());
184-
}
181+
let name_buf = get_value_name(val).to_vec();
182+
let name =
183+
CString::from_vec_with_nul(name_buf).or_else(|buf| CString::new(buf.into_bytes())).unwrap();
184+
set_comdat(llmod, val, &name);
185185
}
186186

187187
pub fn SetUnnamedAddress(global: &Value, unnamed: UnnamedAddr) {
@@ -217,8 +217,7 @@ pub fn set_section(llglobal: &Value, section_name: &str) {
217217
}
218218
}
219219

220-
pub fn add_global<'a>(llmod: &'a Module, ty: &'a Type, name: &str) -> &'a Value {
221-
let name_cstr = CString::new(name).expect("unexpected CString error");
220+
pub fn add_global<'a>(llmod: &'a Module, ty: &'a Type, name_cstr: &CStr) -> &'a Value {
222221
unsafe { LLVMAddGlobal(llmod, ty, name_cstr.as_ptr()) }
223222
}
224223

@@ -252,9 +251,14 @@ pub fn set_alignment(llglobal: &Value, align: Align) {
252251
}
253252
}
254253

255-
pub fn set_comdat(llmod: &Module, llglobal: &Value, name: &str) {
254+
/// Get the `name`d comdat from `llmod` and assign it to `llglobal`.
255+
///
256+
/// Inserts the comdat into `llmod` if it does not exist.
257+
/// It is an error to call this if the target does not support comdat.
258+
pub fn set_comdat(llmod: &Module, llglobal: &Value, name: &CStr) {
256259
unsafe {
257-
LLVMRustSetComdat(llmod, llglobal, name.as_ptr().cast(), name.len());
260+
let comdat = LLVMGetOrInsertComdat(llmod, name.as_ptr());
261+
LLVMSetComdat(llglobal, comdat);
258262
}
259263
}
260264

compiler/rustc_codegen_llvm/src/mono_item.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,9 @@ impl<'tcx> PreDefineCodegenMethods<'tcx> for CodegenCx<'_, 'tcx> {
6464
unsafe { llvm::LLVMRustSetLinkage(lldecl, base::linkage_to_llvm(linkage)) };
6565
let attrs = self.tcx.codegen_fn_attrs(instance.def_id());
6666
base::set_link_section(lldecl, attrs);
67-
if linkage == Linkage::LinkOnceODR || linkage == Linkage::WeakODR {
67+
if (linkage == Linkage::LinkOnceODR || linkage == Linkage::WeakODR)
68+
&& self.tcx.sess.target.supports_comdat()
69+
{
6870
llvm::SetUniqueComdat(self.llmod, lldecl);
6971
}
7072

compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp

-10
Original file line numberDiff line numberDiff line change
@@ -1658,16 +1658,6 @@ extern "C" void LLVMRustPositionBuilderAtStart(LLVMBuilderRef B,
16581658
unwrap(B)->SetInsertPoint(unwrap(BB), Point);
16591659
}
16601660

1661-
extern "C" void LLVMRustSetComdat(LLVMModuleRef M, LLVMValueRef V,
1662-
const char *Name, size_t NameLen) {
1663-
Triple TargetTriple = Triple(unwrap(M)->getTargetTriple());
1664-
GlobalObject *GV = unwrap<GlobalObject>(V);
1665-
if (TargetTriple.supportsCOMDAT()) {
1666-
StringRef NameRef(Name, NameLen);
1667-
GV->setComdat(unwrap(M)->getOrInsertComdat(NameRef));
1668-
}
1669-
}
1670-
16711661
enum class LLVMRustLinkage {
16721662
ExternalLinkage = 0,
16731663
AvailableExternallyLinkage = 1,

compiler/rustc_target/src/spec/mod.rs

+7
Original file line numberDiff line numberDiff line change
@@ -2514,6 +2514,13 @@ fn add_link_args(link_args: &mut LinkArgs, flavor: LinkerFlavor, args: &[&'stati
25142514
add_link_args_iter(link_args, flavor, args.iter().copied().map(Cow::Borrowed))
25152515
}
25162516

2517+
impl TargetOptions {
2518+
pub fn supports_comdat(&self) -> bool {
2519+
// XCOFF and MachO don't support COMDAT.
2520+
!self.is_like_aix && !self.is_like_osx
2521+
}
2522+
}
2523+
25172524
impl TargetOptions {
25182525
fn link_args(flavor: LinkerFlavor, args: &[&'static str]) -> LinkArgs {
25192526
let mut link_args = LinkArgs::new();

src/librustdoc/html/markdown.rs

+5-79
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ use std::sync::OnceLock;
3737
use pulldown_cmark::{
3838
BrokenLink, CodeBlockKind, CowStr, Event, LinkType, Options, Parser, Tag, TagEnd, html,
3939
};
40-
use rustc_data_structures::fx::{FxHashMap, FxIndexMap};
40+
use rustc_data_structures::fx::FxHashMap;
4141
use rustc_errors::{Diag, DiagMessage};
4242
use rustc_hir::def_id::LocalDefId;
4343
use rustc_middle::ty::TyCtxt;
@@ -57,6 +57,7 @@ use crate::html::length_limit::HtmlWithLimit;
5757
use crate::html::render::small_url_encode;
5858
use crate::html::toc::{Toc, TocBuilder};
5959

60+
mod footnotes;
6061
#[cfg(test)]
6162
mod tests;
6263

@@ -646,81 +647,6 @@ impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
646647
}
647648
}
648649

649-
/// Moves all footnote definitions to the end and add back links to the
650-
/// references.
651-
struct Footnotes<'a, I> {
652-
inner: I,
653-
footnotes: FxIndexMap<String, (Vec<Event<'a>>, u16)>,
654-
}
655-
656-
impl<'a, I> Footnotes<'a, I> {
657-
fn new(iter: I) -> Self {
658-
Footnotes { inner: iter, footnotes: FxIndexMap::default() }
659-
}
660-
661-
fn get_entry(&mut self, key: &str) -> &mut (Vec<Event<'a>>, u16) {
662-
let new_id = self.footnotes.len() + 1;
663-
let key = key.to_owned();
664-
self.footnotes.entry(key).or_insert((Vec::new(), new_id as u16))
665-
}
666-
}
667-
668-
impl<'a, I: Iterator<Item = SpannedEvent<'a>>> Iterator for Footnotes<'a, I> {
669-
type Item = SpannedEvent<'a>;
670-
671-
fn next(&mut self) -> Option<Self::Item> {
672-
loop {
673-
match self.inner.next() {
674-
Some((Event::FootnoteReference(ref reference), range)) => {
675-
let entry = self.get_entry(reference);
676-
let reference = format!(
677-
"<sup id=\"fnref{0}\"><a href=\"#fn{0}\">{0}</a></sup>",
678-
(*entry).1
679-
);
680-
return Some((Event::Html(reference.into()), range));
681-
}
682-
Some((Event::Start(Tag::FootnoteDefinition(def)), _)) => {
683-
let mut content = Vec::new();
684-
for (event, _) in &mut self.inner {
685-
if let Event::End(TagEnd::FootnoteDefinition) = event {
686-
break;
687-
}
688-
content.push(event);
689-
}
690-
let entry = self.get_entry(&def);
691-
(*entry).0 = content;
692-
}
693-
Some(e) => return Some(e),
694-
None => {
695-
if !self.footnotes.is_empty() {
696-
let mut v: Vec<_> = self.footnotes.drain(..).map(|(_, x)| x).collect();
697-
v.sort_by(|a, b| a.1.cmp(&b.1));
698-
let mut ret = String::from("<div class=\"footnotes\"><hr><ol>");
699-
for (mut content, id) in v {
700-
write!(ret, "<li id=\"fn{id}\">").unwrap();
701-
let mut is_paragraph = false;
702-
if let Some(&Event::End(TagEnd::Paragraph)) = content.last() {
703-
content.pop();
704-
is_paragraph = true;
705-
}
706-
html::push_html(&mut ret, content.into_iter());
707-
write!(ret, "&nbsp;<a href=\"#fnref{id}\">↩</a>").unwrap();
708-
if is_paragraph {
709-
ret.push_str("</p>");
710-
}
711-
ret.push_str("</li>");
712-
}
713-
ret.push_str("</ol></div>");
714-
return Some((Event::Html(ret.into()), 0..0));
715-
} else {
716-
return None;
717-
}
718-
}
719-
}
720-
}
721-
}
722-
}
723-
724650
/// A newtype that represents a relative line number in Markdown.
725651
///
726652
/// In other words, this represents an offset from the first line of Markdown
@@ -1408,7 +1334,7 @@ impl Markdown<'_> {
14081334
let mut s = String::with_capacity(md.len() * 3 / 2);
14091335

14101336
let p = HeadingLinks::new(p, None, ids, heading_offset);
1411-
let p = Footnotes::new(p);
1337+
let p = footnotes::Footnotes::new(p);
14121338
let p = LinkReplacer::new(p.map(|(ev, _)| ev), links);
14131339
let p = TableWrapper::new(p);
14141340
let p = CodeBlocks::new(p, codes, edition, playground);
@@ -1443,7 +1369,7 @@ impl MarkdownWithToc<'_> {
14431369

14441370
{
14451371
let p = HeadingLinks::new(p, Some(&mut toc), ids, HeadingOffset::H1);
1446-
let p = Footnotes::new(p);
1372+
let p = footnotes::Footnotes::new(p);
14471373
let p = TableWrapper::new(p.map(|(ev, _)| ev));
14481374
let p = CodeBlocks::new(p, codes, edition, playground);
14491375
html::push_html(&mut s, p);
@@ -1476,7 +1402,7 @@ impl MarkdownItemInfo<'_> {
14761402
let mut s = String::with_capacity(md.len() * 3 / 2);
14771403

14781404
let p = HeadingLinks::new(p, None, ids, HeadingOffset::H1);
1479-
let p = Footnotes::new(p);
1405+
let p = footnotes::Footnotes::new(p);
14801406
let p = TableWrapper::new(p.map(|(ev, _)| ev));
14811407
let p = p.filter(|event| {
14821408
!matches!(event, Event::Start(Tag::Paragraph) | Event::End(TagEnd::Paragraph))

0 commit comments

Comments
 (0)