1
Fork 0

Auto merge of #132277 - workingjubilee:rollup-5e6q6e4, r=workingjubilee

Rollup of 9 pull requests

Successful merges:

 - #130259 (Lower AST node id only once)
 - #131441 (Add a new trait `proc_macro::ToTokens`)
 - #132247 (stable_mir: Directly use types from rustc_abi)
 - #132249 (compiler: Add rustc_abi dependence to the compiler)
 - #132255 (Add `LayoutData::is_uninhabited` and use it)
 - #132258 ([rustdoc] Unify variant struct fields margins with struct fields)
 - #132260 (cg_llvm: Use a type-safe helper to cast `&str` and `&[u8]` to `*const c_char`)
 - #132261 (refactor: cleaner check to return None)
 - #132271 (Updating Fuchsia platform-support documentation)

r? `@ghost`
`@rustbot` modify labels: rollup
This commit is contained in:
bors 2024-10-29 07:32:45 +00:00
commit 2df8dbb1b3
81 changed files with 750 additions and 341 deletions

View file

@ -3621,6 +3621,7 @@ version = "0.0.0"
dependencies = [ dependencies = [
"annotate-snippets 0.11.4", "annotate-snippets 0.11.4",
"derive_setters", "derive_setters",
"rustc_abi",
"rustc_ast", "rustc_ast",
"rustc_ast_pretty", "rustc_ast_pretty",
"rustc_data_structures", "rustc_data_structures",
@ -3718,6 +3719,7 @@ name = "rustc_hir_analysis"
version = "0.0.0" version = "0.0.0"
dependencies = [ dependencies = [
"itertools", "itertools",
"rustc_abi",
"rustc_arena", "rustc_arena",
"rustc_ast", "rustc_ast",
"rustc_attr", "rustc_attr",
@ -3906,6 +3908,7 @@ dependencies = [
name = "rustc_lint" name = "rustc_lint"
version = "0.0.0" version = "0.0.0"
dependencies = [ dependencies = [
"rustc_abi",
"rustc_ast", "rustc_ast",
"rustc_ast_pretty", "rustc_ast_pretty",
"rustc_attr", "rustc_attr",
@ -3980,6 +3983,7 @@ dependencies = [
"bitflags 2.6.0", "bitflags 2.6.0",
"libloading", "libloading",
"odht", "odht",
"rustc_abi",
"rustc_ast", "rustc_ast",
"rustc_attr", "rustc_attr",
"rustc_data_structures", "rustc_data_structures",
@ -4074,6 +4078,7 @@ version = "0.0.0"
dependencies = [ dependencies = [
"polonius-engine", "polonius-engine",
"regex", "regex",
"rustc_abi",
"rustc_ast", "rustc_ast",
"rustc_data_structures", "rustc_data_structures",
"rustc_errors", "rustc_errors",
@ -4095,6 +4100,7 @@ version = "0.0.0"
dependencies = [ dependencies = [
"either", "either",
"itertools", "itertools",
"rustc_abi",
"rustc_arena", "rustc_arena",
"rustc_ast", "rustc_ast",
"rustc_attr", "rustc_attr",
@ -4187,6 +4193,7 @@ dependencies = [
name = "rustc_passes" name = "rustc_passes"
version = "0.0.0" version = "0.0.0"
dependencies = [ dependencies = [
"rustc_abi",
"rustc_ast", "rustc_ast",
"rustc_ast_pretty", "rustc_ast_pretty",
"rustc_attr", "rustc_attr",
@ -4213,6 +4220,7 @@ name = "rustc_pattern_analysis"
version = "0.0.0" version = "0.0.0"
dependencies = [ dependencies = [
"rustc-hash 2.0.0", "rustc-hash 2.0.0",
"rustc_abi",
"rustc_apfloat", "rustc_apfloat",
"rustc_arena", "rustc_arena",
"rustc_data_structures", "rustc_data_structures",
@ -4352,6 +4360,7 @@ dependencies = [
"bitflags 2.6.0", "bitflags 2.6.0",
"getopts", "getopts",
"libc", "libc",
"rustc_abi",
"rustc_ast", "rustc_ast",
"rustc_data_structures", "rustc_data_structures",
"rustc_errors", "rustc_errors",
@ -4415,6 +4424,7 @@ version = "0.0.0"
dependencies = [ dependencies = [
"punycode", "punycode",
"rustc-demangle", "rustc-demangle",
"rustc_abi",
"rustc_data_structures", "rustc_data_structures",
"rustc_errors", "rustc_errors",
"rustc_hir", "rustc_hir",

View file

@ -28,7 +28,7 @@ where
VariantIdx: Idx, VariantIdx: Idx,
F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug, F: Deref<Target = &'a LayoutData<FieldIdx, VariantIdx>> + fmt::Debug,
{ {
let uninhabited = fields.iter().any(|f| f.abi.is_uninhabited()); let uninhabited = fields.iter().any(|f| f.is_uninhabited());
// We cannot ignore alignment; that might lead us to entirely discard a variant and // We cannot ignore alignment; that might lead us to entirely discard a variant and
// produce an enum that is less aligned than it should be! // produce an enum that is less aligned than it should be!
let is_1zst = fields.iter().all(|f| f.is_1zst()); let is_1zst = fields.iter().all(|f| f.is_1zst());
@ -681,7 +681,7 @@ impl<Cx: HasDataLayout> LayoutCalculator<Cx> {
let discr_type = repr.discr_type(); let discr_type = repr.discr_type();
let bits = Integer::from_attr(dl, discr_type).size().bits(); let bits = Integer::from_attr(dl, discr_type).size().bits();
for (i, mut val) in discriminants { for (i, mut val) in discriminants {
if !repr.c() && variants[i].iter().any(|f| f.abi.is_uninhabited()) { if !repr.c() && variants[i].iter().any(|f| f.is_uninhabited()) {
continue; continue;
} }
if discr_type.is_signed() { if discr_type.is_signed() {

View file

@ -1652,6 +1652,11 @@ impl<FieldIdx: Idx, VariantIdx: Idx> LayoutData<FieldIdx, VariantIdx> {
} }
} }
/// Returns `true` if this is an uninhabited type
pub fn is_uninhabited(&self) -> bool {
self.abi.is_uninhabited()
}
pub fn scalar<C: HasDataLayout>(cx: &C, scalar: Scalar) -> Self { pub fn scalar<C: HasDataLayout>(cx: &C, scalar: Scalar) -> Self {
let largest_niche = Niche::from_scalar(cx, Size::ZERO, scalar); let largest_niche = Niche::from_scalar(cx, Size::ZERO, scalar);
let size = scalar.size(cx); let size = scalar.size(cx);

View file

@ -10,17 +10,18 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
b: &Block, b: &Block,
targeted_by_break: bool, targeted_by_break: bool,
) -> &'hir hir::Block<'hir> { ) -> &'hir hir::Block<'hir> {
self.arena.alloc(self.lower_block_noalloc(b, targeted_by_break)) let hir_id = self.lower_node_id(b.id);
self.arena.alloc(self.lower_block_noalloc(hir_id, b, targeted_by_break))
} }
pub(super) fn lower_block_noalloc( pub(super) fn lower_block_noalloc(
&mut self, &mut self,
hir_id: hir::HirId,
b: &Block, b: &Block,
targeted_by_break: bool, targeted_by_break: bool,
) -> hir::Block<'hir> { ) -> hir::Block<'hir> {
let (stmts, expr) = self.lower_stmts(&b.stmts); let (stmts, expr) = self.lower_stmts(&b.stmts);
let rules = self.lower_block_check_mode(&b.rules); let rules = self.lower_block_check_mode(&b.rules);
let hir_id = self.lower_node_id(b.id);
hir::Block { hir_id, stmts, expr, rules, span: self.lower_span(b.span), targeted_by_break } hir::Block { hir_id, stmts, expr, rules, span: self.lower_span(b.span), targeted_by_break }
} }

View file

@ -259,10 +259,11 @@ impl<'hir> LoweringContext<'_, 'hir> {
self_param_id: pat_node_id, self_param_id: pat_node_id,
}; };
self_resolver.visit_block(block); self_resolver.visit_block(block);
// Target expr needs to lower `self` path.
this.ident_and_label_to_local_id.insert(pat_node_id, param.pat.hir_id.local_id);
this.lower_target_expr(&block) this.lower_target_expr(&block)
} else { } else {
let pat_hir_id = this.lower_node_id(pat_node_id); this.generate_arg(param.pat.hir_id, span)
this.generate_arg(pat_hir_id, span)
}; };
args.push(arg); args.push(arg);
} }

View file

@ -70,8 +70,8 @@ impl<'hir> LoweringContext<'_, 'hir> {
_ => (), _ => (),
} }
let hir_id = self.lower_node_id(e.id); let expr_hir_id = self.lower_node_id(e.id);
self.lower_attrs(hir_id, &e.attrs); self.lower_attrs(expr_hir_id, &e.attrs);
let kind = match &e.kind { let kind = match &e.kind {
ExprKind::Array(exprs) => hir::ExprKind::Array(self.lower_exprs(exprs)), ExprKind::Array(exprs) => hir::ExprKind::Array(self.lower_exprs(exprs)),
@ -175,18 +175,25 @@ impl<'hir> LoweringContext<'_, 'hir> {
ExprKind::If(cond, then, else_opt) => { ExprKind::If(cond, then, else_opt) => {
self.lower_expr_if(cond, then, else_opt.as_deref()) self.lower_expr_if(cond, then, else_opt.as_deref())
} }
ExprKind::While(cond, body, opt_label) => self.with_loop_scope(e.id, |this| { ExprKind::While(cond, body, opt_label) => {
let span = this.mark_span_with_reason(DesugaringKind::WhileLoop, e.span, None); self.with_loop_scope(expr_hir_id, |this| {
this.lower_expr_while_in_loop_scope(span, cond, body, *opt_label) let span =
}), this.mark_span_with_reason(DesugaringKind::WhileLoop, e.span, None);
ExprKind::Loop(body, opt_label, span) => self.with_loop_scope(e.id, |this| { let opt_label = this.lower_label(*opt_label, e.id, expr_hir_id);
hir::ExprKind::Loop( this.lower_expr_while_in_loop_scope(span, cond, body, opt_label)
this.lower_block(body, false), })
this.lower_label(*opt_label), }
hir::LoopSource::Loop, ExprKind::Loop(body, opt_label, span) => {
this.lower_span(*span), self.with_loop_scope(expr_hir_id, |this| {
) let opt_label = this.lower_label(*opt_label, e.id, expr_hir_id);
}), hir::ExprKind::Loop(
this.lower_block(body, false),
opt_label,
hir::LoopSource::Loop,
this.lower_span(*span),
)
})
}
ExprKind::TryBlock(body) => self.lower_expr_try_block(body), ExprKind::TryBlock(body) => self.lower_expr_try_block(body),
ExprKind::Match(expr, arms, kind) => hir::ExprKind::Match( ExprKind::Match(expr, arms, kind) => hir::ExprKind::Match(
self.lower_expr(expr), self.lower_expr(expr),
@ -212,7 +219,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
binder, binder,
*capture_clause, *capture_clause,
e.id, e.id,
hir_id, expr_hir_id,
*coroutine_kind, *coroutine_kind,
fn_decl, fn_decl,
body, body,
@ -223,7 +230,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
binder, binder,
*capture_clause, *capture_clause,
e.id, e.id,
hir_id, expr_hir_id,
*constness, *constness,
*movability, *movability,
fn_decl, fn_decl,
@ -250,8 +257,16 @@ impl<'hir> LoweringContext<'_, 'hir> {
) )
} }
ExprKind::Block(blk, opt_label) => { ExprKind::Block(blk, opt_label) => {
let opt_label = self.lower_label(*opt_label); // Different from loops, label of block resolves to block id rather than
hir::ExprKind::Block(self.lower_block(blk, opt_label.is_some()), opt_label) // expr node id.
let block_hir_id = self.lower_node_id(blk.id);
let opt_label = self.lower_label(*opt_label, blk.id, block_hir_id);
let hir_block = self.arena.alloc(self.lower_block_noalloc(
block_hir_id,
blk,
opt_label.is_some(),
));
hir::ExprKind::Block(hir_block, opt_label)
} }
ExprKind::Assign(el, er, span) => self.lower_expr_assign(el, er, *span, e.span), ExprKind::Assign(el, er, span) => self.lower_expr_assign(el, er, *span, e.span),
ExprKind::AssignOp(op, el, er) => hir::ExprKind::AssignOp( ExprKind::AssignOp(op, el, er) => hir::ExprKind::AssignOp(
@ -354,7 +369,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
ExprKind::MacCall(_) => panic!("{:?} shouldn't exist here", e.span), ExprKind::MacCall(_) => panic!("{:?} shouldn't exist here", e.span),
}; };
hir::Expr { hir_id, kind, span: self.lower_span(e.span) } hir::Expr { hir_id: expr_hir_id, kind, span: self.lower_span(e.span) }
}) })
} }
@ -504,7 +519,6 @@ impl<'hir> LoweringContext<'_, 'hir> {
let if_expr = self.expr(span, if_kind); let if_expr = self.expr(span, if_kind);
let block = self.block_expr(self.arena.alloc(if_expr)); let block = self.block_expr(self.arena.alloc(if_expr));
let span = self.lower_span(span.with_hi(cond.span.hi())); let span = self.lower_span(span.with_hi(cond.span.hi()));
let opt_label = self.lower_label(opt_label);
hir::ExprKind::Loop(block, opt_label, hir::LoopSource::While, span) hir::ExprKind::Loop(block, opt_label, hir::LoopSource::While, span)
} }
@ -512,8 +526,9 @@ impl<'hir> LoweringContext<'_, 'hir> {
/// `try { <stmts>; }` into `{ <stmts>; ::std::ops::Try::from_output(()) }` /// `try { <stmts>; }` into `{ <stmts>; ::std::ops::Try::from_output(()) }`
/// and save the block id to use it as a break target for desugaring of the `?` operator. /// and save the block id to use it as a break target for desugaring of the `?` operator.
fn lower_expr_try_block(&mut self, body: &Block) -> hir::ExprKind<'hir> { fn lower_expr_try_block(&mut self, body: &Block) -> hir::ExprKind<'hir> {
self.with_catch_scope(body.id, |this| { let body_hir_id = self.lower_node_id(body.id);
let mut block = this.lower_block_noalloc(body, true); self.with_catch_scope(body_hir_id, |this| {
let mut block = this.lower_block_noalloc(body_hir_id, body, true);
// Final expression of the block (if present) or `()` with span at the end of block // Final expression of the block (if present) or `()` with span at the end of block
let (try_span, tail_expr) = if let Some(expr) = block.expr.take() { let (try_span, tail_expr) = if let Some(expr) = block.expr.take() {
@ -869,7 +884,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
let x_expr = self.expr_ident(gen_future_span, x_ident, x_pat_hid); let x_expr = self.expr_ident(gen_future_span, x_ident, x_pat_hid);
let ready_field = self.single_pat_field(gen_future_span, x_pat); let ready_field = self.single_pat_field(gen_future_span, x_pat);
let ready_pat = self.pat_lang_item_variant(span, hir::LangItem::PollReady, ready_field); let ready_pat = self.pat_lang_item_variant(span, hir::LangItem::PollReady, ready_field);
let break_x = self.with_loop_scope(loop_node_id, move |this| { let break_x = self.with_loop_scope(loop_hir_id, move |this| {
let expr_break = let expr_break =
hir::ExprKind::Break(this.lower_loop_destination(None), Some(x_expr)); hir::ExprKind::Break(this.lower_loop_destination(None), Some(x_expr));
this.arena.alloc(this.expr(gen_future_span, expr_break)) this.arena.alloc(this.expr(gen_future_span, expr_break))
@ -1101,8 +1116,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
hir::CoroutineSource::Closure, hir::CoroutineSource::Closure,
); );
let hir_id = this.lower_node_id(coroutine_kind.closure_id()); this.maybe_forward_track_caller(body.span, closure_hir_id, expr.hir_id);
this.maybe_forward_track_caller(body.span, closure_hir_id, hir_id);
(parameters, expr) (parameters, expr)
}); });
@ -1465,8 +1479,16 @@ impl<'hir> LoweringContext<'_, 'hir> {
) )
} }
fn lower_label(&self, opt_label: Option<Label>) -> Option<Label> { // Record labelled expr's HirId so that we can retrieve it in `lower_jump_destination` without
// lowering node id again.
fn lower_label(
&mut self,
opt_label: Option<Label>,
dest_id: NodeId,
dest_hir_id: hir::HirId,
) -> Option<Label> {
let label = opt_label?; let label = opt_label?;
self.ident_and_label_to_local_id.insert(dest_id, dest_hir_id.local_id);
Some(Label { ident: self.lower_ident(label.ident) }) Some(Label { ident: self.lower_ident(label.ident) })
} }
@ -1474,17 +1496,20 @@ impl<'hir> LoweringContext<'_, 'hir> {
let target_id = match destination { let target_id = match destination {
Some((id, _)) => { Some((id, _)) => {
if let Some(loop_id) = self.resolver.get_label_res(id) { if let Some(loop_id) = self.resolver.get_label_res(id) {
Ok(self.lower_node_id(loop_id)) let local_id = self.ident_and_label_to_local_id[&loop_id];
let loop_hir_id = HirId { owner: self.current_hir_id_owner, local_id };
Ok(loop_hir_id)
} else { } else {
Err(hir::LoopIdError::UnresolvedLabel) Err(hir::LoopIdError::UnresolvedLabel)
} }
} }
None => self None => {
.loop_scope self.loop_scope.map(|id| Ok(id)).unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
.map(|id| Ok(self.lower_node_id(id))) }
.unwrap_or(Err(hir::LoopIdError::OutsideLoopScope)),
}; };
let label = self.lower_label(destination.map(|(_, label)| label)); let label = destination
.map(|(_, label)| label)
.map(|label| Label { ident: self.lower_ident(label.ident) });
hir::Destination { label, target_id } hir::Destination { label, target_id }
} }
@ -1499,14 +1524,14 @@ impl<'hir> LoweringContext<'_, 'hir> {
} }
} }
fn with_catch_scope<T>(&mut self, catch_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T { fn with_catch_scope<T>(&mut self, catch_id: hir::HirId, f: impl FnOnce(&mut Self) -> T) -> T {
let old_scope = self.catch_scope.replace(catch_id); let old_scope = self.catch_scope.replace(catch_id);
let result = f(self); let result = f(self);
self.catch_scope = old_scope; self.catch_scope = old_scope;
result result
} }
fn with_loop_scope<T>(&mut self, loop_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T { fn with_loop_scope<T>(&mut self, loop_id: hir::HirId, f: impl FnOnce(&mut Self) -> T) -> T {
// We're no longer in the base loop's condition; we're in another loop. // We're no longer in the base loop's condition; we're in another loop.
let was_in_loop_condition = self.is_in_loop_condition; let was_in_loop_condition = self.is_in_loop_condition;
self.is_in_loop_condition = false; self.is_in_loop_condition = false;
@ -1658,9 +1683,13 @@ impl<'hir> LoweringContext<'_, 'hir> {
let head_span = self.mark_span_with_reason(DesugaringKind::ForLoop, head.span, None); let head_span = self.mark_span_with_reason(DesugaringKind::ForLoop, head.span, None);
let pat_span = self.mark_span_with_reason(DesugaringKind::ForLoop, pat.span, None); let pat_span = self.mark_span_with_reason(DesugaringKind::ForLoop, pat.span, None);
let loop_hir_id = self.lower_node_id(e.id);
let label = self.lower_label(opt_label, e.id, loop_hir_id);
// `None => break` // `None => break`
let none_arm = { let none_arm = {
let break_expr = self.with_loop_scope(e.id, |this| this.expr_break_alloc(for_span)); let break_expr =
self.with_loop_scope(loop_hir_id, |this| this.expr_break_alloc(for_span));
let pat = self.pat_none(for_span); let pat = self.pat_none(for_span);
self.arm(pat, break_expr) self.arm(pat, break_expr)
}; };
@ -1668,7 +1697,8 @@ impl<'hir> LoweringContext<'_, 'hir> {
// Some(<pat>) => <body>, // Some(<pat>) => <body>,
let some_arm = { let some_arm = {
let some_pat = self.pat_some(pat_span, pat); let some_pat = self.pat_some(pat_span, pat);
let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false)); let body_block =
self.with_loop_scope(loop_hir_id, |this| this.lower_block(body, false));
let body_expr = self.arena.alloc(self.expr_block(body_block)); let body_expr = self.arena.alloc(self.expr_block(body_block));
self.arm(some_pat, body_expr) self.arm(some_pat, body_expr)
}; };
@ -1722,12 +1752,11 @@ impl<'hir> LoweringContext<'_, 'hir> {
// `[opt_ident]: loop { ... }` // `[opt_ident]: loop { ... }`
let kind = hir::ExprKind::Loop( let kind = hir::ExprKind::Loop(
loop_block, loop_block,
self.lower_label(opt_label), label,
hir::LoopSource::ForLoop, hir::LoopSource::ForLoop,
self.lower_span(for_span.with_hi(head.span.hi())), self.lower_span(for_span.with_hi(head.span.hi())),
); );
let loop_expr = let loop_expr = self.arena.alloc(hir::Expr { hir_id: loop_hir_id, kind, span: for_span });
self.arena.alloc(hir::Expr { hir_id: self.lower_node_id(e.id), kind, span: for_span });
// `mut iter => { ... }` // `mut iter => { ... }`
let iter_arm = self.arm(iter_pat, loop_expr); let iter_arm = self.arm(iter_pat, loop_expr);
@ -1867,8 +1896,8 @@ impl<'hir> LoweringContext<'_, 'hir> {
self.arena.alloc(residual_expr), self.arena.alloc(residual_expr),
unstable_span, unstable_span,
); );
let ret_expr = if let Some(catch_node) = self.catch_scope { let ret_expr = if let Some(catch_id) = self.catch_scope {
let target_id = Ok(self.lower_node_id(catch_node)); let target_id = Ok(catch_id);
self.arena.alloc(self.expr( self.arena.alloc(self.expr(
try_span, try_span,
hir::ExprKind::Break( hir::ExprKind::Break(
@ -1922,8 +1951,8 @@ impl<'hir> LoweringContext<'_, 'hir> {
yeeted_span, yeeted_span,
); );
if let Some(catch_node) = self.catch_scope { if let Some(catch_id) = self.catch_scope {
let target_id = Ok(self.lower_node_id(catch_node)); let target_id = Ok(catch_id);
hir::ExprKind::Break(hir::Destination { label: None, target_id }, Some(from_yeet_expr)) hir::ExprKind::Break(hir::Destination { label: None, target_id }, Some(from_yeet_expr))
} else { } else {
hir::ExprKind::Ret(Some(from_yeet_expr)) hir::ExprKind::Ret(Some(from_yeet_expr))

View file

@ -154,7 +154,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
fn lower_item(&mut self, i: &Item) -> &'hir hir::Item<'hir> { fn lower_item(&mut self, i: &Item) -> &'hir hir::Item<'hir> {
let mut ident = i.ident; let mut ident = i.ident;
let vis_span = self.lower_span(i.vis.span); let vis_span = self.lower_span(i.vis.span);
let hir_id = self.lower_node_id(i.id); let hir_id = hir::HirId::make_owner(self.current_hir_id_owner.def_id);
let attrs = self.lower_attrs(hir_id, &i.attrs); let attrs = self.lower_attrs(hir_id, &i.attrs);
let kind = self.lower_item_kind(i.span, i.id, hir_id, &mut ident, attrs, vis_span, &i.kind); let kind = self.lower_item_kind(i.span, i.id, hir_id, &mut ident, attrs, vis_span, &i.kind);
let item = hir::Item { let item = hir::Item {
@ -604,7 +604,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
} }
fn lower_foreign_item(&mut self, i: &ForeignItem) -> &'hir hir::ForeignItem<'hir> { fn lower_foreign_item(&mut self, i: &ForeignItem) -> &'hir hir::ForeignItem<'hir> {
let hir_id = self.lower_node_id(i.id); let hir_id = hir::HirId::make_owner(self.current_hir_id_owner.def_id);
let owner_id = hir_id.expect_owner(); let owner_id = hir_id.expect_owner();
self.lower_attrs(hir_id, &i.attrs); self.lower_attrs(hir_id, &i.attrs);
let item = hir::ForeignItem { let item = hir::ForeignItem {
@ -728,7 +728,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
} }
fn lower_trait_item(&mut self, i: &AssocItem) -> &'hir hir::TraitItem<'hir> { fn lower_trait_item(&mut self, i: &AssocItem) -> &'hir hir::TraitItem<'hir> {
let hir_id = self.lower_node_id(i.id); let hir_id = hir::HirId::make_owner(self.current_hir_id_owner.def_id);
self.lower_attrs(hir_id, &i.attrs); self.lower_attrs(hir_id, &i.attrs);
let trait_item_def_id = hir_id.expect_owner(); let trait_item_def_id = hir_id.expect_owner();
@ -858,7 +858,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
// Since `default impl` is not yet implemented, this is always true in impls. // Since `default impl` is not yet implemented, this is always true in impls.
let has_value = true; let has_value = true;
let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value); let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value);
let hir_id = self.lower_node_id(i.id); let hir_id = hir::HirId::make_owner(self.current_hir_id_owner.def_id);
self.lower_attrs(hir_id, &i.attrs); self.lower_attrs(hir_id, &i.attrs);
let (generics, kind) = match &i.kind { let (generics, kind) = match &i.kind {
@ -1086,7 +1086,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
); );
// FIXME(async_fn_track_caller): Can this be moved above? // FIXME(async_fn_track_caller): Can this be moved above?
let hir_id = this.lower_node_id(coroutine_kind.closure_id()); let hir_id = expr.hir_id;
this.maybe_forward_track_caller(body.span, fn_id, hir_id); this.maybe_forward_track_caller(body.span, fn_id, hir_id);
(parameters, expr) (parameters, expr)

View file

@ -40,8 +40,6 @@
#![warn(unreachable_pub)] #![warn(unreachable_pub)]
// tidy-alphabetical-end // tidy-alphabetical-end
use std::collections::hash_map::Entry;
use rustc_ast::node_id::NodeMap; use rustc_ast::node_id::NodeMap;
use rustc_ast::ptr::P; use rustc_ast::ptr::P;
use rustc_ast::{self as ast, *}; use rustc_ast::{self as ast, *};
@ -115,8 +113,8 @@ struct LoweringContext<'a, 'hir> {
/// outside of an `async fn`. /// outside of an `async fn`.
current_item: Option<Span>, current_item: Option<Span>,
catch_scope: Option<NodeId>, catch_scope: Option<HirId>,
loop_scope: Option<NodeId>, loop_scope: Option<HirId>,
is_in_loop_condition: bool, is_in_loop_condition: bool,
is_in_trait_impl: bool, is_in_trait_impl: bool,
is_in_dyn_type: bool, is_in_dyn_type: bool,
@ -140,7 +138,10 @@ struct LoweringContext<'a, 'hir> {
impl_trait_defs: Vec<hir::GenericParam<'hir>>, impl_trait_defs: Vec<hir::GenericParam<'hir>>,
impl_trait_bounds: Vec<hir::WherePredicate<'hir>>, impl_trait_bounds: Vec<hir::WherePredicate<'hir>>,
/// NodeIds that are lowered inside the current HIR owner. /// NodeIds of pattern identifiers and labelled nodes that are lowered inside the current HIR owner.
ident_and_label_to_local_id: NodeMap<hir::ItemLocalId>,
/// NodeIds that are lowered inside the current HIR owner. Only used for duplicate lowering check.
#[cfg(debug_assertions)]
node_id_to_local_id: NodeMap<hir::ItemLocalId>, node_id_to_local_id: NodeMap<hir::ItemLocalId>,
allow_try_trait: Lrc<[Symbol]>, allow_try_trait: Lrc<[Symbol]>,
@ -171,6 +172,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
current_hir_id_owner: hir::CRATE_OWNER_ID, current_hir_id_owner: hir::CRATE_OWNER_ID,
current_def_id_parent: CRATE_DEF_ID, current_def_id_parent: CRATE_DEF_ID,
item_local_id_counter: hir::ItemLocalId::ZERO, item_local_id_counter: hir::ItemLocalId::ZERO,
ident_and_label_to_local_id: Default::default(),
#[cfg(debug_assertions)]
node_id_to_local_id: Default::default(), node_id_to_local_id: Default::default(),
trait_map: Default::default(), trait_map: Default::default(),
@ -588,7 +591,11 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
let current_attrs = std::mem::take(&mut self.attrs); let current_attrs = std::mem::take(&mut self.attrs);
let current_bodies = std::mem::take(&mut self.bodies); let current_bodies = std::mem::take(&mut self.bodies);
let current_node_ids = std::mem::take(&mut self.node_id_to_local_id); let current_ident_and_label_to_local_id =
std::mem::take(&mut self.ident_and_label_to_local_id);
#[cfg(debug_assertions)]
let current_node_id_to_local_id = std::mem::take(&mut self.node_id_to_local_id);
let current_trait_map = std::mem::take(&mut self.trait_map); let current_trait_map = std::mem::take(&mut self.trait_map);
let current_owner = let current_owner =
std::mem::replace(&mut self.current_hir_id_owner, hir::OwnerId { def_id }); std::mem::replace(&mut self.current_hir_id_owner, hir::OwnerId { def_id });
@ -602,8 +609,11 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
// and the caller to refer to some of the subdefinitions' nodes' `LocalDefId`s. // and the caller to refer to some of the subdefinitions' nodes' `LocalDefId`s.
// Always allocate the first `HirId` for the owner itself. // Always allocate the first `HirId` for the owner itself.
let _old = self.node_id_to_local_id.insert(owner, hir::ItemLocalId::ZERO); #[cfg(debug_assertions)]
debug_assert_eq!(_old, None); {
let _old = self.node_id_to_local_id.insert(owner, hir::ItemLocalId::ZERO);
debug_assert_eq!(_old, None);
}
let item = self.with_def_id_parent(def_id, f); let item = self.with_def_id_parent(def_id, f);
debug_assert_eq!(def_id, item.def_id().def_id); debug_assert_eq!(def_id, item.def_id().def_id);
@ -614,7 +624,12 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
self.attrs = current_attrs; self.attrs = current_attrs;
self.bodies = current_bodies; self.bodies = current_bodies;
self.node_id_to_local_id = current_node_ids; self.ident_and_label_to_local_id = current_ident_and_label_to_local_id;
#[cfg(debug_assertions)]
{
self.node_id_to_local_id = current_node_id_to_local_id;
}
self.trait_map = current_trait_map; self.trait_map = current_trait_map;
self.current_hir_id_owner = current_owner; self.current_hir_id_owner = current_owner;
self.item_local_id_counter = current_local_counter; self.item_local_id_counter = current_local_counter;
@ -680,39 +695,37 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
self.arena.alloc(hir::OwnerInfo { nodes, parenting, attrs, trait_map }) self.arena.alloc(hir::OwnerInfo { nodes, parenting, attrs, trait_map })
} }
/// This method allocates a new `HirId` for the given `NodeId` and stores it in /// This method allocates a new `HirId` for the given `NodeId`.
/// the `LoweringContext`'s `NodeId => HirId` map.
/// Take care not to call this method if the resulting `HirId` is then not /// Take care not to call this method if the resulting `HirId` is then not
/// actually used in the HIR, as that would trigger an assertion in the /// actually used in the HIR, as that would trigger an assertion in the
/// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped
/// properly. Calling the method twice with the same `NodeId` is fine though. /// properly. Calling the method twice with the same `NodeId` is also forbidden.
#[instrument(level = "debug", skip(self), ret)] #[instrument(level = "debug", skip(self), ret)]
fn lower_node_id(&mut self, ast_node_id: NodeId) -> HirId { fn lower_node_id(&mut self, ast_node_id: NodeId) -> HirId {
assert_ne!(ast_node_id, DUMMY_NODE_ID); assert_ne!(ast_node_id, DUMMY_NODE_ID);
match self.node_id_to_local_id.entry(ast_node_id) { let owner = self.current_hir_id_owner;
Entry::Occupied(o) => HirId { owner: self.current_hir_id_owner, local_id: *o.get() }, let local_id = self.item_local_id_counter;
Entry::Vacant(v) => { assert_ne!(local_id, hir::ItemLocalId::ZERO);
// Generate a new `HirId`. self.item_local_id_counter.increment_by(1);
let owner = self.current_hir_id_owner; let hir_id = HirId { owner, local_id };
let local_id = self.item_local_id_counter;
let hir_id = HirId { owner, local_id };
v.insert(local_id); if let Some(def_id) = self.opt_local_def_id(ast_node_id) {
self.item_local_id_counter.increment_by(1); self.children.push((def_id, hir::MaybeOwner::NonOwner(hir_id)));
assert_ne!(local_id, hir::ItemLocalId::ZERO);
if let Some(def_id) = self.opt_local_def_id(ast_node_id) {
self.children.push((def_id, hir::MaybeOwner::NonOwner(hir_id)));
}
if let Some(traits) = self.resolver.trait_map.remove(&ast_node_id) {
self.trait_map.insert(hir_id.local_id, traits.into_boxed_slice());
}
hir_id
}
} }
if let Some(traits) = self.resolver.trait_map.remove(&ast_node_id) {
self.trait_map.insert(hir_id.local_id, traits.into_boxed_slice());
}
// Check whether the same `NodeId` is lowered more than once.
#[cfg(debug_assertions)]
{
let old = self.node_id_to_local_id.insert(ast_node_id, local_id);
assert_eq!(old, None);
}
hir_id
} }
/// Generate a new `HirId` without a backing `NodeId`. /// Generate a new `HirId` without a backing `NodeId`.
@ -729,7 +742,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
fn lower_res(&mut self, res: Res<NodeId>) -> Res { fn lower_res(&mut self, res: Res<NodeId>) -> Res {
let res: Result<Res, ()> = res.apply_id(|id| { let res: Result<Res, ()> = res.apply_id(|id| {
let owner = self.current_hir_id_owner; let owner = self.current_hir_id_owner;
let local_id = self.node_id_to_local_id.get(&id).copied().ok_or(())?; let local_id = self.ident_and_label_to_local_id.get(&id).copied().ok_or(())?;
Ok(HirId { owner, local_id }) Ok(HirId { owner, local_id })
}); });
trace!(?res); trace!(?res);

View file

@ -21,13 +21,20 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
fn lower_pat_mut(&mut self, mut pattern: &Pat) -> hir::Pat<'hir> { fn lower_pat_mut(&mut self, mut pattern: &Pat) -> hir::Pat<'hir> {
ensure_sufficient_stack(|| { ensure_sufficient_stack(|| {
// loop here to avoid recursion // loop here to avoid recursion
let pat_hir_id = self.lower_node_id(pattern.id);
let node = loop { let node = loop {
match &pattern.kind { match &pattern.kind {
PatKind::Wild => break hir::PatKind::Wild, PatKind::Wild => break hir::PatKind::Wild,
PatKind::Never => break hir::PatKind::Never, PatKind::Never => break hir::PatKind::Never,
PatKind::Ident(binding_mode, ident, sub) => { PatKind::Ident(binding_mode, ident, sub) => {
let lower_sub = |this: &mut Self| sub.as_ref().map(|s| this.lower_pat(s)); let lower_sub = |this: &mut Self| sub.as_ref().map(|s| this.lower_pat(s));
break self.lower_pat_ident(pattern, *binding_mode, *ident, lower_sub); break self.lower_pat_ident(
pattern,
*binding_mode,
*ident,
pat_hir_id,
lower_sub,
);
} }
PatKind::Lit(e) => { PatKind::Lit(e) => {
break hir::PatKind::Lit(self.lower_expr_within_pat(e, false)); break hir::PatKind::Lit(self.lower_expr_within_pat(e, false));
@ -119,7 +126,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
} }
}; };
self.pat_with_node_id_of(pattern, node) self.pat_with_node_id_of(pattern, node, pat_hir_id)
}) })
} }
@ -187,10 +194,12 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
let mut prev_rest_span = None; let mut prev_rest_span = None;
// Lowers `$bm $ident @ ..` to `$bm $ident @ _`. // Lowers `$bm $ident @ ..` to `$bm $ident @ _`.
let lower_rest_sub = |this: &mut Self, pat, &ann, &ident, sub| { let lower_rest_sub = |this: &mut Self, pat: &Pat, &ann, &ident, sub: &Pat| {
let lower_sub = |this: &mut Self| Some(this.pat_wild_with_node_id_of(sub)); let sub_hir_id = this.lower_node_id(sub.id);
let node = this.lower_pat_ident(pat, ann, ident, lower_sub); let lower_sub = |this: &mut Self| Some(this.pat_wild_with_node_id_of(sub, sub_hir_id));
this.pat_with_node_id_of(pat, node) let pat_hir_id = this.lower_node_id(pat.id);
let node = this.lower_pat_ident(pat, ann, ident, pat_hir_id, lower_sub);
this.pat_with_node_id_of(pat, node, pat_hir_id)
}; };
let mut iter = pats.iter(); let mut iter = pats.iter();
@ -200,7 +209,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
// Found a sub-slice pattern `..`. Record, lower it to `_`, and stop here. // Found a sub-slice pattern `..`. Record, lower it to `_`, and stop here.
PatKind::Rest => { PatKind::Rest => {
prev_rest_span = Some(pat.span); prev_rest_span = Some(pat.span);
slice = Some(self.pat_wild_with_node_id_of(pat)); let hir_id = self.lower_node_id(pat.id);
slice = Some(self.pat_wild_with_node_id_of(pat, hir_id));
break; break;
} }
// Found a sub-slice pattern `$binding_mode $ident @ ..`. // Found a sub-slice pattern `$binding_mode $ident @ ..`.
@ -248,19 +258,35 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
p: &Pat, p: &Pat,
annotation: BindingMode, annotation: BindingMode,
ident: Ident, ident: Ident,
hir_id: hir::HirId,
lower_sub: impl FnOnce(&mut Self) -> Option<&'hir hir::Pat<'hir>>, lower_sub: impl FnOnce(&mut Self) -> Option<&'hir hir::Pat<'hir>>,
) -> hir::PatKind<'hir> { ) -> hir::PatKind<'hir> {
match self.resolver.get_partial_res(p.id).map(|d| d.expect_full_res()) { match self.resolver.get_partial_res(p.id).map(|d| d.expect_full_res()) {
// `None` can occur in body-less function signatures // `None` can occur in body-less function signatures
res @ (None | Some(Res::Local(_))) => { res @ (None | Some(Res::Local(_))) => {
let canonical_id = match res { let binding_id = match res {
Some(Res::Local(id)) => id, Some(Res::Local(id)) => {
_ => p.id, // In `Or` patterns like `VariantA(s) | VariantB(s, _)`, multiple identifier patterns
// will be resolved to the same `Res::Local`. Thus they just share a single
// `HirId`.
if id == p.id {
self.ident_and_label_to_local_id.insert(id, hir_id.local_id);
hir_id
} else {
hir::HirId {
owner: self.current_hir_id_owner,
local_id: self.ident_and_label_to_local_id[&id],
}
}
}
_ => {
self.ident_and_label_to_local_id.insert(p.id, hir_id.local_id);
hir_id
}
}; };
hir::PatKind::Binding( hir::PatKind::Binding(
annotation, annotation,
self.lower_node_id(canonical_id), binding_id,
self.lower_ident(ident), self.lower_ident(ident),
lower_sub(self), lower_sub(self),
) )
@ -280,18 +306,18 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
} }
} }
fn pat_wild_with_node_id_of(&mut self, p: &Pat) -> &'hir hir::Pat<'hir> { fn pat_wild_with_node_id_of(&mut self, p: &Pat, hir_id: hir::HirId) -> &'hir hir::Pat<'hir> {
self.arena.alloc(self.pat_with_node_id_of(p, hir::PatKind::Wild)) self.arena.alloc(self.pat_with_node_id_of(p, hir::PatKind::Wild, hir_id))
} }
/// Construct a `Pat` with the `HirId` of `p.id` lowered. /// Construct a `Pat` with the `HirId` of `p.id` already lowered.
fn pat_with_node_id_of(&mut self, p: &Pat, kind: hir::PatKind<'hir>) -> hir::Pat<'hir> { fn pat_with_node_id_of(
hir::Pat { &mut self,
hir_id: self.lower_node_id(p.id), p: &Pat,
kind, kind: hir::PatKind<'hir>,
span: self.lower_span(p.span), hir_id: hir::HirId,
default_binding_modes: true, ) -> hir::Pat<'hir> {
} hir::Pat { hir_id, kind, span: self.lower_span(p.span), default_binding_modes: true }
} }
/// Emit a friendly error for extra `..` patterns in a tuple/tuple struct/slice pattern. /// Emit a friendly error for extra `..` patterns in a tuple/tuple struct/slice pattern.

View file

@ -415,7 +415,7 @@ impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> {
instance: Option<ty::Instance<'tcx>>, instance: Option<ty::Instance<'tcx>>,
) { ) {
let mut func_attrs = SmallVec::<[_; 3]>::new(); let mut func_attrs = SmallVec::<[_; 3]>::new();
if self.ret.layout.abi.is_uninhabited() { if self.ret.layout.is_uninhabited() {
func_attrs.push(llvm::AttributeKind::NoReturn.create_attr(cx.llcx)); func_attrs.push(llvm::AttributeKind::NoReturn.create_attr(cx.llcx));
} }
if !self.can_unwind { if !self.can_unwind {
@ -532,7 +532,7 @@ impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> {
fn apply_attrs_callsite(&self, bx: &mut Builder<'_, 'll, 'tcx>, callsite: &'ll Value) { fn apply_attrs_callsite(&self, bx: &mut Builder<'_, 'll, 'tcx>, callsite: &'ll Value) {
let mut func_attrs = SmallVec::<[_; 2]>::new(); let mut func_attrs = SmallVec::<[_; 2]>::new();
if self.ret.layout.abi.is_uninhabited() { if self.ret.layout.is_uninhabited() {
func_attrs.push(llvm::AttributeKind::NoReturn.create_attr(bx.cx.llcx)); func_attrs.push(llvm::AttributeKind::NoReturn.create_attr(bx.cx.llcx));
} }
if !self.can_unwind { if !self.can_unwind {

View file

@ -7,6 +7,7 @@ use rustc_middle::bug;
use rustc_middle::ty::TyCtxt; use rustc_middle::ty::TyCtxt;
use rustc_session::config::{DebugInfo, OomStrategy}; use rustc_session::config::{DebugInfo, OomStrategy};
use crate::common::AsCCharPtr;
use crate::llvm::{self, Context, False, Module, True, Type}; use crate::llvm::{self, Context, False, Module, True, Type};
use crate::{ModuleLlvm, attributes, debuginfo}; use crate::{ModuleLlvm, attributes, debuginfo};
@ -76,14 +77,14 @@ pub(crate) unsafe fn codegen(
unsafe { unsafe {
// __rust_alloc_error_handler_should_panic // __rust_alloc_error_handler_should_panic
let name = OomStrategy::SYMBOL; let name = OomStrategy::SYMBOL;
let ll_g = llvm::LLVMRustGetOrInsertGlobal(llmod, name.as_ptr().cast(), name.len(), i8); let ll_g = llvm::LLVMRustGetOrInsertGlobal(llmod, name.as_c_char_ptr(), name.len(), i8);
llvm::set_visibility(ll_g, llvm::Visibility::from_generic(tcx.sess.default_visibility())); llvm::set_visibility(ll_g, llvm::Visibility::from_generic(tcx.sess.default_visibility()));
let val = tcx.sess.opts.unstable_opts.oom.should_panic(); let val = tcx.sess.opts.unstable_opts.oom.should_panic();
let llval = llvm::LLVMConstInt(i8, val as u64, False); let llval = llvm::LLVMConstInt(i8, val as u64, False);
llvm::LLVMSetInitializer(ll_g, llval); llvm::LLVMSetInitializer(ll_g, llval);
let name = NO_ALLOC_SHIM_IS_UNSTABLE; let name = NO_ALLOC_SHIM_IS_UNSTABLE;
let ll_g = llvm::LLVMRustGetOrInsertGlobal(llmod, name.as_ptr().cast(), name.len(), i8); let ll_g = llvm::LLVMRustGetOrInsertGlobal(llmod, name.as_c_char_ptr(), name.len(), i8);
llvm::set_visibility(ll_g, llvm::Visibility::from_generic(tcx.sess.default_visibility())); llvm::set_visibility(ll_g, llvm::Visibility::from_generic(tcx.sess.default_visibility()));
let llval = llvm::LLVMConstInt(i8, 0, False); let llval = llvm::LLVMConstInt(i8, 0, False);
llvm::LLVMSetInitializer(ll_g, llval); llvm::LLVMSetInitializer(ll_g, llval);
@ -115,7 +116,7 @@ fn create_wrapper_function(
); );
let llfn = llvm::LLVMRustGetOrInsertFunction( let llfn = llvm::LLVMRustGetOrInsertFunction(
llmod, llmod,
from_name.as_ptr().cast(), from_name.as_c_char_ptr(),
from_name.len(), from_name.len(),
ty, ty,
); );
@ -137,7 +138,7 @@ fn create_wrapper_function(
} }
let callee = let callee =
llvm::LLVMRustGetOrInsertFunction(llmod, to_name.as_ptr().cast(), to_name.len(), ty); llvm::LLVMRustGetOrInsertFunction(llmod, to_name.as_c_char_ptr(), to_name.len(), ty);
if let Some(no_return) = no_return { if let Some(no_return) = no_return {
// -> ! DIFlagNoReturn // -> ! DIFlagNoReturn
attributes::apply_to_llfn(callee, llvm::AttributePlace::Function, &[no_return]); attributes::apply_to_llfn(callee, llvm::AttributePlace::Function, &[no_return]);

View file

@ -15,7 +15,7 @@ use smallvec::SmallVec;
use tracing::debug; use tracing::debug;
use crate::builder::Builder; use crate::builder::Builder;
use crate::common::Funclet; use crate::common::{AsCCharPtr, Funclet};
use crate::context::CodegenCx; use crate::context::CodegenCx;
use crate::type_::Type; use crate::type_::Type;
use crate::type_of::LayoutLlvmExt; use crate::type_of::LayoutLlvmExt;
@ -420,7 +420,7 @@ impl<'tcx> AsmCodegenMethods<'tcx> for CodegenCx<'_, 'tcx> {
unsafe { unsafe {
llvm::LLVMAppendModuleInlineAsm( llvm::LLVMAppendModuleInlineAsm(
self.llmod, self.llmod,
template_str.as_ptr().cast(), template_str.as_c_char_ptr(),
template_str.len(), template_str.len(),
); );
} }
@ -458,14 +458,14 @@ pub(crate) fn inline_asm_call<'ll>(
let fty = bx.cx.type_func(&argtys, output); let fty = bx.cx.type_func(&argtys, output);
unsafe { unsafe {
// Ask LLVM to verify that the constraints are well-formed. // Ask LLVM to verify that the constraints are well-formed.
let constraints_ok = llvm::LLVMRustInlineAsmVerify(fty, cons.as_ptr().cast(), cons.len()); let constraints_ok = llvm::LLVMRustInlineAsmVerify(fty, cons.as_c_char_ptr(), cons.len());
debug!("constraint verification result: {:?}", constraints_ok); debug!("constraint verification result: {:?}", constraints_ok);
if constraints_ok { if constraints_ok {
let v = llvm::LLVMRustInlineAsm( let v = llvm::LLVMRustInlineAsm(
fty, fty,
asm.as_ptr().cast(), asm.as_c_char_ptr(),
asm.len(), asm.len(),
cons.as_ptr().cast(), cons.as_c_char_ptr(),
cons.len(), cons.len(),
volatile, volatile,
alignstack, alignstack,

View file

@ -25,6 +25,7 @@ use tracing::{debug, info};
use crate::back::write::{ use crate::back::write::{
self, CodegenDiagnosticsStage, DiagnosticHandlers, bitcode_section_name, save_temp_bitcode, self, CodegenDiagnosticsStage, DiagnosticHandlers, bitcode_section_name, save_temp_bitcode,
}; };
use crate::common::AsCCharPtr;
use crate::errors::{ use crate::errors::{
DynamicLinkingWithLTO, LlvmError, LtoBitcodeFromRlib, LtoDisallowed, LtoDylib, LtoProcMacro, DynamicLinkingWithLTO, LlvmError, LtoBitcodeFromRlib, LtoDisallowed, LtoDylib, LtoProcMacro,
}; };
@ -604,7 +605,7 @@ pub(crate) fn run_pass_manager(
unsafe { unsafe {
if !llvm::LLVMRustHasModuleFlag( if !llvm::LLVMRustHasModuleFlag(
module.module_llvm.llmod(), module.module_llvm.llmod(),
"LTOPostLink".as_ptr().cast(), "LTOPostLink".as_c_char_ptr(),
11, 11,
) { ) {
llvm::LLVMRustAddModuleFlagU32( llvm::LLVMRustAddModuleFlagU32(

View file

@ -34,6 +34,7 @@ use crate::back::owned_target_machine::OwnedTargetMachine;
use crate::back::profiling::{ use crate::back::profiling::{
LlvmSelfProfiler, selfprofile_after_pass_callback, selfprofile_before_pass_callback, LlvmSelfProfiler, selfprofile_after_pass_callback, selfprofile_before_pass_callback,
}; };
use crate::common::AsCCharPtr;
use crate::errors::{ use crate::errors::{
CopyBitcode, FromLlvmDiag, FromLlvmOptimizationDiag, LlvmError, UnknownCompression, CopyBitcode, FromLlvmDiag, FromLlvmOptimizationDiag, LlvmError, UnknownCompression,
WithLlvmError, WriteBytecode, WithLlvmError, WriteBytecode,
@ -596,9 +597,9 @@ pub(crate) unsafe fn llvm_optimize(
llvm_selfprofiler, llvm_selfprofiler,
selfprofile_before_pass_callback, selfprofile_before_pass_callback,
selfprofile_after_pass_callback, selfprofile_after_pass_callback,
extra_passes.as_ptr().cast(), extra_passes.as_c_char_ptr(),
extra_passes.len(), extra_passes.len(),
llvm_plugins.as_ptr().cast(), llvm_plugins.as_c_char_ptr(),
llvm_plugins.len(), llvm_plugins.len(),
) )
}; };
@ -1042,7 +1043,7 @@ unsafe fn embed_bitcode(
llvm::LLVMSetInitializer(llglobal, llconst); llvm::LLVMSetInitializer(llglobal, llconst);
let section = bitcode_section_name(cgcx); let section = bitcode_section_name(cgcx);
llvm::LLVMSetSection(llglobal, section.as_ptr().cast()); llvm::LLVMSetSection(llglobal, section.as_c_char_ptr());
llvm::set_linkage(llglobal, llvm::Linkage::PrivateLinkage); llvm::set_linkage(llglobal, llvm::Linkage::PrivateLinkage);
llvm::LLVMSetGlobalConstant(llglobal, llvm::True); llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
@ -1066,9 +1067,9 @@ unsafe fn embed_bitcode(
// We need custom section flags, so emit module-level inline assembly. // We need custom section flags, so emit module-level inline assembly.
let section_flags = if cgcx.is_pe_coff { "n" } else { "e" }; let section_flags = if cgcx.is_pe_coff { "n" } else { "e" };
let asm = create_section_with_flags_asm(".llvmbc", section_flags, bitcode); let asm = create_section_with_flags_asm(".llvmbc", section_flags, bitcode);
llvm::LLVMAppendModuleInlineAsm(llmod, asm.as_ptr().cast(), asm.len()); llvm::LLVMAppendModuleInlineAsm(llmod, asm.as_c_char_ptr(), asm.len());
let asm = create_section_with_flags_asm(".llvmcmd", section_flags, cmdline.as_bytes()); let asm = create_section_with_flags_asm(".llvmcmd", section_flags, cmdline.as_bytes());
llvm::LLVMAppendModuleInlineAsm(llmod, asm.as_ptr().cast(), asm.len()); llvm::LLVMAppendModuleInlineAsm(llmod, asm.as_c_char_ptr(), asm.len());
} }
} }
} }

View file

@ -392,3 +392,21 @@ pub(crate) fn get_dllimport<'tcx>(
tcx.native_library(id) tcx.native_library(id)
.and_then(|lib| lib.dll_imports.iter().find(|di| di.name.as_str() == name)) .and_then(|lib| lib.dll_imports.iter().find(|di| di.name.as_str() == name))
} }
/// Extension trait for explicit casts to `*const c_char`.
pub(crate) trait AsCCharPtr {
/// Equivalent to `self.as_ptr().cast()`, but only casts to `*const c_char`.
fn as_c_char_ptr(&self) -> *const c_char;
}
impl AsCCharPtr for str {
fn as_c_char_ptr(&self) -> *const c_char {
self.as_ptr().cast()
}
}
impl AsCCharPtr for [u8] {
fn as_c_char_ptr(&self) -> *const c_char {
self.as_ptr().cast()
}
}

View file

@ -19,7 +19,7 @@ use rustc_target::abi::{
}; };
use tracing::{debug, instrument, trace}; use tracing::{debug, instrument, trace};
use crate::common::CodegenCx; use crate::common::{AsCCharPtr, CodegenCx};
use crate::errors::{ use crate::errors::{
InvalidMinimumAlignmentNotPowerOfTwo, InvalidMinimumAlignmentTooLarge, SymbolAlreadyDefined, InvalidMinimumAlignmentNotPowerOfTwo, InvalidMinimumAlignmentTooLarge, SymbolAlreadyDefined,
}; };
@ -400,7 +400,7 @@ impl<'ll> CodegenCx<'ll, '_> {
let new_g = llvm::LLVMRustGetOrInsertGlobal( let new_g = llvm::LLVMRustGetOrInsertGlobal(
self.llmod, self.llmod,
name.as_ptr().cast(), name.as_c_char_ptr(),
name.len(), name.len(),
val_llty, val_llty,
); );
@ -451,7 +451,7 @@ impl<'ll> CodegenCx<'ll, '_> {
if let Some(section) = attrs.link_section { if let Some(section) = attrs.link_section {
let section = llvm::LLVMMDStringInContext2( let section = llvm::LLVMMDStringInContext2(
self.llcx, self.llcx,
section.as_str().as_ptr().cast(), section.as_str().as_c_char_ptr(),
section.as_str().len(), section.as_str().len(),
); );
assert!(alloc.provenance().ptrs().is_empty()); assert!(alloc.provenance().ptrs().is_empty());
@ -462,7 +462,7 @@ impl<'ll> CodegenCx<'ll, '_> {
let bytes = let bytes =
alloc.inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len()); alloc.inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len());
let alloc = let alloc =
llvm::LLVMMDStringInContext2(self.llcx, bytes.as_ptr().cast(), bytes.len()); llvm::LLVMMDStringInContext2(self.llcx, bytes.as_c_char_ptr(), bytes.len());
let data = [section, alloc]; let data = [section, alloc];
let meta = llvm::LLVMMDNodeInContext2(self.llcx, data.as_ptr(), data.len()); let meta = llvm::LLVMMDNodeInContext2(self.llcx, data.as_ptr(), data.len());
let val = llvm::LLVMMetadataAsValue(self.llcx, meta); let val = llvm::LLVMMetadataAsValue(self.llcx, meta);

View file

@ -29,6 +29,7 @@ use smallvec::SmallVec;
use crate::back::write::to_llvm_code_model; use crate::back::write::to_llvm_code_model;
use crate::callee::get_fn; use crate::callee::get_fn;
use crate::common::AsCCharPtr;
use crate::debuginfo::metadata::apply_vcall_visibility_metadata; use crate::debuginfo::metadata::apply_vcall_visibility_metadata;
use crate::llvm::{Metadata, MetadataType}; use crate::llvm::{Metadata, MetadataType};
use crate::type_::Type; use crate::type_::Type;
@ -231,7 +232,7 @@ pub(crate) unsafe fn create_module<'ll>(
// If we're normalizing integers with CFI, ensure LLVM generated functions do the same. // If we're normalizing integers with CFI, ensure LLVM generated functions do the same.
// See https://github.com/llvm/llvm-project/pull/104826 // See https://github.com/llvm/llvm-project/pull/104826
if sess.is_sanitizer_cfi_normalize_integers_enabled() { if sess.is_sanitizer_cfi_normalize_integers_enabled() {
let cfi_normalize_integers = c"cfi-normalize-integers".as_ptr().cast(); let cfi_normalize_integers = c"cfi-normalize-integers".as_ptr();
unsafe { unsafe {
llvm::LLVMRustAddModuleFlagU32( llvm::LLVMRustAddModuleFlagU32(
llmod, llmod,
@ -268,7 +269,7 @@ pub(crate) unsafe fn create_module<'ll>(
let pfe = let pfe =
PatchableFunctionEntry::from_config(sess.opts.unstable_opts.patchable_function_entry); PatchableFunctionEntry::from_config(sess.opts.unstable_opts.patchable_function_entry);
if pfe.prefix() > 0 { if pfe.prefix() > 0 {
let kcfi_offset = c"kcfi-offset".as_ptr().cast(); let kcfi_offset = c"kcfi-offset".as_ptr();
unsafe { unsafe {
llvm::LLVMRustAddModuleFlagU32( llvm::LLVMRustAddModuleFlagU32(
llmod, llmod,
@ -429,7 +430,7 @@ pub(crate) unsafe fn create_module<'ll>(
let name_metadata = unsafe { let name_metadata = unsafe {
llvm::LLVMMDStringInContext2( llvm::LLVMMDStringInContext2(
llcx, llcx,
rustc_producer.as_ptr().cast(), rustc_producer.as_c_char_ptr(),
rustc_producer.as_bytes().len(), rustc_producer.as_bytes().len(),
) )
}; };
@ -453,7 +454,7 @@ pub(crate) unsafe fn create_module<'ll>(
llmod, llmod,
llvm::LLVMModFlagBehavior::Error, llvm::LLVMModFlagBehavior::Error,
c"target-abi".as_ptr(), c"target-abi".as_ptr(),
llvm_abiname.as_ptr().cast(), llvm_abiname.as_c_char_ptr(),
llvm_abiname.len(), llvm_abiname.len(),
); );
} }
@ -474,7 +475,7 @@ pub(crate) unsafe fn create_module<'ll>(
// We already checked this during option parsing // We already checked this during option parsing
_ => unreachable!(), _ => unreachable!(),
}; };
unsafe { llvm::LLVMRustAddModuleFlagU32(llmod, behavior, key.as_ptr().cast(), *value) } unsafe { llvm::LLVMRustAddModuleFlagU32(llmod, behavior, key.as_c_char_ptr(), *value) }
} }
llmod llmod

View file

@ -14,7 +14,7 @@ use rustc_target::abi::Size;
use tracing::{debug, instrument}; use tracing::{debug, instrument};
use crate::builder::Builder; use crate::builder::Builder;
use crate::common::CodegenCx; use crate::common::{AsCCharPtr, CodegenCx};
use crate::coverageinfo::map_data::FunctionCoverageCollector; use crate::coverageinfo::map_data::FunctionCoverageCollector;
use crate::llvm; use crate::llvm;
@ -236,7 +236,7 @@ fn create_pgo_func_name_var<'ll, 'tcx>(
unsafe { unsafe {
llvm::LLVMRustCoverageCreatePGOFuncNameVar( llvm::LLVMRustCoverageCreatePGOFuncNameVar(
llfn, llfn,
mangled_fn_name.as_ptr().cast(), mangled_fn_name.as_c_char_ptr(),
mangled_fn_name.len(), mangled_fn_name.len(),
) )
} }
@ -248,7 +248,7 @@ pub(crate) fn write_filenames_section_to_buffer<'a>(
) { ) {
let (pointers, lengths) = filenames let (pointers, lengths) = filenames
.into_iter() .into_iter()
.map(|s: &str| (s.as_ptr().cast(), s.len())) .map(|s: &str| (s.as_c_char_ptr(), s.len()))
.unzip::<_, _, Vec<_>, Vec<_>>(); .unzip::<_, _, Vec<_>, Vec<_>>();
unsafe { unsafe {
@ -291,7 +291,7 @@ pub(crate) fn write_mapping_to_buffer(
} }
pub(crate) fn hash_bytes(bytes: &[u8]) -> u64 { pub(crate) fn hash_bytes(bytes: &[u8]) -> u64 {
unsafe { llvm::LLVMRustCoverageHashByteArray(bytes.as_ptr().cast(), bytes.len()) } unsafe { llvm::LLVMRustCoverageHashByteArray(bytes.as_c_char_ptr(), bytes.len()) }
} }
pub(crate) fn mapping_version() -> u32 { pub(crate) fn mapping_version() -> u32 {

View file

@ -32,7 +32,7 @@ use super::type_names::{compute_debuginfo_type_name, compute_debuginfo_vtable_na
use super::utils::{ use super::utils::{
DIB, create_DIArray, debug_context, get_namespace_for_item, is_node_local_to_unit, DIB, create_DIArray, debug_context, get_namespace_for_item, is_node_local_to_unit,
}; };
use crate::common::CodegenCx; use crate::common::{AsCCharPtr, CodegenCx};
use crate::debuginfo::metadata::type_map::build_type_with_children; use crate::debuginfo::metadata::type_map::build_type_with_children;
use crate::debuginfo::utils::{WidePtrKind, wide_pointer_kind}; use crate::debuginfo::utils::{WidePtrKind, wide_pointer_kind};
use crate::llvm::debuginfo::{ use crate::llvm::debuginfo::{
@ -190,7 +190,7 @@ fn build_pointer_or_reference_di_node<'ll, 'tcx>(
data_layout.pointer_size.bits(), data_layout.pointer_size.bits(),
data_layout.pointer_align.abi.bits() as u32, data_layout.pointer_align.abi.bits() as u32,
0, // Ignore DWARF address space. 0, // Ignore DWARF address space.
ptr_type_debuginfo_name.as_ptr().cast(), ptr_type_debuginfo_name.as_c_char_ptr(),
ptr_type_debuginfo_name.len(), ptr_type_debuginfo_name.len(),
) )
}; };
@ -348,7 +348,7 @@ fn build_subroutine_type_di_node<'ll, 'tcx>(
size, size,
align, align,
0, // Ignore DWARF address space. 0, // Ignore DWARF address space.
name.as_ptr().cast(), name.as_c_char_ptr(),
name.len(), name.len(),
) )
}; };
@ -518,7 +518,7 @@ fn recursion_marker_type_di_node<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>) -> &'ll D
let name = "<recur_type>"; let name = "<recur_type>";
llvm::LLVMRustDIBuilderCreateBasicType( llvm::LLVMRustDIBuilderCreateBasicType(
DIB(cx), DIB(cx),
name.as_ptr().cast(), name.as_c_char_ptr(),
name.len(), name.len(),
cx.tcx.data_layout.pointer_size.bits(), cx.tcx.data_layout.pointer_size.bits(),
DW_ATE_unsigned, DW_ATE_unsigned,
@ -640,14 +640,14 @@ pub(crate) fn file_metadata<'ll>(cx: &CodegenCx<'ll, '_>, source_file: &SourceFi
unsafe { unsafe {
llvm::LLVMRustDIBuilderCreateFile( llvm::LLVMRustDIBuilderCreateFile(
DIB(cx), DIB(cx),
file_name.as_ptr().cast(), file_name.as_c_char_ptr(),
file_name.len(), file_name.len(),
directory.as_ptr().cast(), directory.as_c_char_ptr(),
directory.len(), directory.len(),
hash_kind, hash_kind,
hash_value.as_ptr().cast(), hash_value.as_c_char_ptr(),
hash_value.len(), hash_value.len(),
source.map_or(ptr::null(), |x| x.as_ptr().cast()), source.map_or(ptr::null(), |x| x.as_c_char_ptr()),
source.map_or(0, |x| x.len()), source.map_or(0, |x| x.len()),
) )
} }
@ -662,12 +662,12 @@ fn unknown_file_metadata<'ll>(cx: &CodegenCx<'ll, '_>) -> &'ll DIFile {
llvm::LLVMRustDIBuilderCreateFile( llvm::LLVMRustDIBuilderCreateFile(
DIB(cx), DIB(cx),
file_name.as_ptr().cast(), file_name.as_c_char_ptr(),
file_name.len(), file_name.len(),
directory.as_ptr().cast(), directory.as_c_char_ptr(),
directory.len(), directory.len(),
llvm::ChecksumKind::None, llvm::ChecksumKind::None,
hash_value.as_ptr().cast(), hash_value.as_c_char_ptr(),
hash_value.len(), hash_value.len(),
ptr::null(), ptr::null(),
0, 0,
@ -788,7 +788,7 @@ fn build_basic_type_di_node<'ll, 'tcx>(
let ty_di_node = unsafe { let ty_di_node = unsafe {
llvm::LLVMRustDIBuilderCreateBasicType( llvm::LLVMRustDIBuilderCreateBasicType(
DIB(cx), DIB(cx),
name.as_ptr().cast(), name.as_c_char_ptr(),
name.len(), name.len(),
cx.size_of(t).bits(), cx.size_of(t).bits(),
encoding, encoding,
@ -810,7 +810,7 @@ fn build_basic_type_di_node<'ll, 'tcx>(
llvm::LLVMRustDIBuilderCreateTypedef( llvm::LLVMRustDIBuilderCreateTypedef(
DIB(cx), DIB(cx),
ty_di_node, ty_di_node,
typedef_name.as_ptr().cast(), typedef_name.as_c_char_ptr(),
typedef_name.len(), typedef_name.len(),
unknown_file_metadata(cx), unknown_file_metadata(cx),
0, 0,
@ -861,7 +861,7 @@ fn build_param_type_di_node<'ll, 'tcx>(
di_node: unsafe { di_node: unsafe {
llvm::LLVMRustDIBuilderCreateBasicType( llvm::LLVMRustDIBuilderCreateBasicType(
DIB(cx), DIB(cx),
name.as_ptr().cast(), name.as_c_char_ptr(),
name.len(), name.len(),
Size::ZERO.bits(), Size::ZERO.bits(),
DW_ATE_unsigned, DW_ATE_unsigned,
@ -948,9 +948,9 @@ pub(crate) fn build_compile_unit_di_node<'ll, 'tcx>(
unsafe { unsafe {
let compile_unit_file = llvm::LLVMRustDIBuilderCreateFile( let compile_unit_file = llvm::LLVMRustDIBuilderCreateFile(
debug_context.builder, debug_context.builder,
name_in_debuginfo.as_ptr().cast(), name_in_debuginfo.as_c_char_ptr(),
name_in_debuginfo.len(), name_in_debuginfo.len(),
work_dir.as_ptr().cast(), work_dir.as_c_char_ptr(),
work_dir.len(), work_dir.len(),
llvm::ChecksumKind::None, llvm::ChecksumKind::None,
ptr::null(), ptr::null(),
@ -963,7 +963,7 @@ pub(crate) fn build_compile_unit_di_node<'ll, 'tcx>(
debug_context.builder, debug_context.builder,
DW_LANG_RUST, DW_LANG_RUST,
compile_unit_file, compile_unit_file,
producer.as_ptr().cast(), producer.as_c_char_ptr(),
producer.len(), producer.len(),
tcx.sess.opts.optimize != config::OptLevel::No, tcx.sess.opts.optimize != config::OptLevel::No,
c"".as_ptr(), c"".as_ptr(),
@ -971,7 +971,7 @@ pub(crate) fn build_compile_unit_di_node<'ll, 'tcx>(
// NB: this doesn't actually have any perceptible effect, it seems. LLVM will instead // NB: this doesn't actually have any perceptible effect, it seems. LLVM will instead
// put the path supplied to `MCSplitDwarfFile` into the debug info of the final // put the path supplied to `MCSplitDwarfFile` into the debug info of the final
// output(s). // output(s).
split_name.as_ptr().cast(), split_name.as_c_char_ptr(),
split_name.len(), split_name.len(),
kind, kind,
0, 0,
@ -1022,7 +1022,7 @@ fn build_field_di_node<'ll, 'tcx>(
llvm::LLVMRustDIBuilderCreateMemberType( llvm::LLVMRustDIBuilderCreateMemberType(
DIB(cx), DIB(cx),
owner, owner,
name.as_ptr().cast(), name.as_c_char_ptr(),
name.len(), name.len(),
unknown_file_metadata(cx), unknown_file_metadata(cx),
UNKNOWN_LINE_NUMBER, UNKNOWN_LINE_NUMBER,
@ -1306,7 +1306,7 @@ fn build_generic_type_param_di_nodes<'ll, 'tcx>(
llvm::LLVMRustDIBuilderCreateTemplateTypeParameter( llvm::LLVMRustDIBuilderCreateTemplateTypeParameter(
DIB(cx), DIB(cx),
None, None,
name.as_ptr().cast(), name.as_c_char_ptr(),
name.len(), name.len(),
actual_type_di_node, actual_type_di_node,
) )
@ -1382,9 +1382,9 @@ pub(crate) fn build_global_var_di_node<'ll>(
llvm::LLVMRustDIBuilderCreateStaticVariable( llvm::LLVMRustDIBuilderCreateStaticVariable(
DIB(cx), DIB(cx),
Some(var_scope), Some(var_scope),
var_name.as_ptr().cast(), var_name.as_c_char_ptr(),
var_name.len(), var_name.len(),
linkage_name.as_ptr().cast(), linkage_name.as_c_char_ptr(),
linkage_name.len(), linkage_name.len(),
file_metadata, file_metadata,
line_number, line_number,
@ -1602,9 +1602,9 @@ pub(crate) fn create_vtable_di_node<'ll, 'tcx>(
llvm::LLVMRustDIBuilderCreateStaticVariable( llvm::LLVMRustDIBuilderCreateStaticVariable(
DIB(cx), DIB(cx),
NO_SCOPE_METADATA, NO_SCOPE_METADATA,
vtable_name.as_ptr().cast(), vtable_name.as_c_char_ptr(),
vtable_name.len(), vtable_name.len(),
linkage_name.as_ptr().cast(), linkage_name.as_c_char_ptr(),
linkage_name.len(), linkage_name.len(),
unknown_file_metadata(cx), unknown_file_metadata(cx),
UNKNOWN_LINE_NUMBER, UNKNOWN_LINE_NUMBER,

View file

@ -11,7 +11,7 @@ use rustc_middle::ty::{self, AdtDef, CoroutineArgs, CoroutineArgsExt, Ty};
use rustc_target::abi::{Align, Endian, Size, TagEncoding, VariantIdx, Variants}; use rustc_target::abi::{Align, Endian, Size, TagEncoding, VariantIdx, Variants};
use smallvec::smallvec; use smallvec::smallvec;
use crate::common::CodegenCx; use crate::common::{AsCCharPtr, CodegenCx};
use crate::debuginfo::metadata::enums::DiscrResult; use crate::debuginfo::metadata::enums::DiscrResult;
use crate::debuginfo::metadata::type_map::{self, Stub, UniqueTypeId}; use crate::debuginfo::metadata::type_map::{self, Stub, UniqueTypeId};
use crate::debuginfo::metadata::{ use crate::debuginfo::metadata::{
@ -359,7 +359,7 @@ fn build_single_variant_union_fields<'ll, 'tcx>(
llvm::LLVMRustDIBuilderCreateStaticMemberType( llvm::LLVMRustDIBuilderCreateStaticMemberType(
DIB(cx), DIB(cx),
enum_type_di_node, enum_type_di_node,
TAG_FIELD_NAME.as_ptr().cast(), TAG_FIELD_NAME.as_c_char_ptr(),
TAG_FIELD_NAME.len(), TAG_FIELD_NAME.len(),
unknown_file_metadata(cx), unknown_file_metadata(cx),
UNKNOWN_LINE_NUMBER, UNKNOWN_LINE_NUMBER,
@ -537,7 +537,7 @@ fn build_variant_struct_wrapper_type_di_node<'ll, 'tcx>(
llvm::LLVMRustDIBuilderCreateStaticMemberType( llvm::LLVMRustDIBuilderCreateStaticMemberType(
DIB(cx), DIB(cx),
wrapper_struct_type_di_node, wrapper_struct_type_di_node,
name.as_ptr().cast(), name.as_c_char_ptr(),
name.len(), name.len(),
unknown_file_metadata(cx), unknown_file_metadata(cx),
UNKNOWN_LINE_NUMBER, UNKNOWN_LINE_NUMBER,
@ -785,7 +785,7 @@ fn build_union_fields_for_direct_tag_enum_or_coroutine<'ll, 'tcx>(
llvm::LLVMRustDIBuilderCreateMemberType( llvm::LLVMRustDIBuilderCreateMemberType(
DIB(cx), DIB(cx),
enum_type_di_node, enum_type_di_node,
field_name.as_ptr().cast(), field_name.as_c_char_ptr(),
field_name.len(), field_name.len(),
file_di_node, file_di_node,
line_number, line_number,

View file

@ -13,7 +13,7 @@ use rustc_target::abi::{FieldIdx, TagEncoding, VariantIdx, Variants};
use super::type_map::{DINodeCreationResult, UniqueTypeId}; use super::type_map::{DINodeCreationResult, UniqueTypeId};
use super::{SmallVec, size_and_align_of}; use super::{SmallVec, size_and_align_of};
use crate::common::CodegenCx; use crate::common::{AsCCharPtr, CodegenCx};
use crate::debuginfo::metadata::type_map::{self, Stub}; use crate::debuginfo::metadata::type_map::{self, Stub};
use crate::debuginfo::metadata::{ use crate::debuginfo::metadata::{
UNKNOWN_LINE_NUMBER, build_field_di_node, build_generic_type_param_di_nodes, type_di_node, UNKNOWN_LINE_NUMBER, build_field_di_node, build_generic_type_param_di_nodes, type_di_node,
@ -106,7 +106,7 @@ fn build_enumeration_type_di_node<'ll, 'tcx>(
let value = [value as u64, (value >> 64) as u64]; let value = [value as u64, (value >> 64) as u64];
Some(llvm::LLVMRustDIBuilderCreateEnumerator( Some(llvm::LLVMRustDIBuilderCreateEnumerator(
DIB(cx), DIB(cx),
name.as_ptr().cast(), name.as_c_char_ptr(),
name.len(), name.len(),
value.as_ptr(), value.as_ptr(),
size.bits() as libc::c_uint, size.bits() as libc::c_uint,
@ -119,7 +119,7 @@ fn build_enumeration_type_di_node<'ll, 'tcx>(
llvm::LLVMRustDIBuilderCreateEnumerationType( llvm::LLVMRustDIBuilderCreateEnumerationType(
DIB(cx), DIB(cx),
containing_scope, containing_scope,
type_name.as_ptr().cast(), type_name.as_c_char_ptr(),
type_name.len(), type_name.len(),
unknown_file_metadata(cx), unknown_file_metadata(cx),
UNKNOWN_LINE_NUMBER, UNKNOWN_LINE_NUMBER,

View file

@ -10,7 +10,7 @@ use rustc_middle::ty::{self};
use rustc_target::abi::{Size, TagEncoding, VariantIdx, Variants}; use rustc_target::abi::{Size, TagEncoding, VariantIdx, Variants};
use smallvec::smallvec; use smallvec::smallvec;
use crate::common::CodegenCx; use crate::common::{AsCCharPtr, CodegenCx};
use crate::debuginfo::metadata::type_map::{self, Stub, StubInfo, UniqueTypeId}; use crate::debuginfo::metadata::type_map::{self, Stub, StubInfo, UniqueTypeId};
use crate::debuginfo::metadata::{ use crate::debuginfo::metadata::{
DINodeCreationResult, NO_GENERICS, SmallVec, UNKNOWN_LINE_NUMBER, file_metadata, DINodeCreationResult, NO_GENERICS, SmallVec, UNKNOWN_LINE_NUMBER, file_metadata,
@ -244,7 +244,7 @@ fn build_enum_variant_part_di_node<'ll, 'tcx>(
llvm::LLVMRustDIBuilderCreateVariantPart( llvm::LLVMRustDIBuilderCreateVariantPart(
DIB(cx), DIB(cx),
enum_type_di_node, enum_type_di_node,
variant_part_name.as_ptr().cast(), variant_part_name.as_c_char_ptr(),
variant_part_name.len(), variant_part_name.len(),
unknown_file_metadata(cx), unknown_file_metadata(cx),
UNKNOWN_LINE_NUMBER, UNKNOWN_LINE_NUMBER,
@ -253,7 +253,7 @@ fn build_enum_variant_part_di_node<'ll, 'tcx>(
DIFlags::FlagZero, DIFlags::FlagZero,
tag_member_di_node, tag_member_di_node,
create_DIArray(DIB(cx), &[]), create_DIArray(DIB(cx), &[]),
variant_part_unique_type_id_str.as_ptr().cast(), variant_part_unique_type_id_str.as_c_char_ptr(),
variant_part_unique_type_id_str.len(), variant_part_unique_type_id_str.len(),
) )
}, },
@ -327,7 +327,7 @@ fn build_discr_member_di_node<'ll, 'tcx>(
Some(llvm::LLVMRustDIBuilderCreateMemberType( Some(llvm::LLVMRustDIBuilderCreateMemberType(
DIB(cx), DIB(cx),
containing_scope, containing_scope,
tag_name.as_ptr().cast(), tag_name.as_c_char_ptr(),
tag_name.len(), tag_name.len(),
unknown_file_metadata(cx), unknown_file_metadata(cx),
UNKNOWN_LINE_NUMBER, UNKNOWN_LINE_NUMBER,
@ -399,7 +399,7 @@ fn build_enum_variant_member_di_node<'ll, 'tcx>(
llvm::LLVMRustDIBuilderCreateVariantMemberType( llvm::LLVMRustDIBuilderCreateVariantMemberType(
DIB(cx), DIB(cx),
variant_part_di_node, variant_part_di_node,
variant_member_info.variant_name.as_ptr().cast(), variant_member_info.variant_name.as_c_char_ptr(),
variant_member_info.variant_name.len(), variant_member_info.variant_name.len(),
file_di_node, file_di_node,
line_number, line_number,

View file

@ -9,7 +9,7 @@ use rustc_middle::ty::{ParamEnv, PolyExistentialTraitRef, Ty, TyCtxt};
use rustc_target::abi::{Align, Size, VariantIdx}; use rustc_target::abi::{Align, Size, VariantIdx};
use super::{SmallVec, UNKNOWN_LINE_NUMBER, unknown_file_metadata}; use super::{SmallVec, UNKNOWN_LINE_NUMBER, unknown_file_metadata};
use crate::common::CodegenCx; use crate::common::{AsCCharPtr, CodegenCx};
use crate::debuginfo::utils::{DIB, create_DIArray, debug_context}; use crate::debuginfo::utils::{DIB, create_DIArray, debug_context};
use crate::llvm::debuginfo::{DIFlags, DIScope, DIType}; use crate::llvm::debuginfo::{DIFlags, DIScope, DIType};
use crate::llvm::{self}; use crate::llvm::{self};
@ -191,7 +191,7 @@ pub(super) fn stub<'ll, 'tcx>(
llvm::LLVMRustDIBuilderCreateStructType( llvm::LLVMRustDIBuilderCreateStructType(
DIB(cx), DIB(cx),
containing_scope, containing_scope,
name.as_ptr().cast(), name.as_c_char_ptr(),
name.len(), name.len(),
unknown_file_metadata(cx), unknown_file_metadata(cx),
UNKNOWN_LINE_NUMBER, UNKNOWN_LINE_NUMBER,
@ -202,7 +202,7 @@ pub(super) fn stub<'ll, 'tcx>(
empty_array, empty_array,
0, 0,
vtable_holder, vtable_holder,
unique_type_id_str.as_ptr().cast(), unique_type_id_str.as_c_char_ptr(),
unique_type_id_str.len(), unique_type_id_str.len(),
) )
} }
@ -211,7 +211,7 @@ pub(super) fn stub<'ll, 'tcx>(
llvm::LLVMRustDIBuilderCreateUnionType( llvm::LLVMRustDIBuilderCreateUnionType(
DIB(cx), DIB(cx),
containing_scope, containing_scope,
name.as_ptr().cast(), name.as_c_char_ptr(),
name.len(), name.len(),
unknown_file_metadata(cx), unknown_file_metadata(cx),
UNKNOWN_LINE_NUMBER, UNKNOWN_LINE_NUMBER,
@ -220,7 +220,7 @@ pub(super) fn stub<'ll, 'tcx>(
flags, flags,
Some(empty_array), Some(empty_array),
0, 0,
unique_type_id_str.as_ptr().cast(), unique_type_id_str.as_c_char_ptr(),
unique_type_id_str.len(), unique_type_id_str.len(),
) )
}, },

View file

@ -31,7 +31,7 @@ use self::namespace::mangled_name_of_instance;
use self::utils::{DIB, create_DIArray, is_node_local_to_unit}; use self::utils::{DIB, create_DIArray, is_node_local_to_unit};
use crate::abi::FnAbi; use crate::abi::FnAbi;
use crate::builder::Builder; use crate::builder::Builder;
use crate::common::CodegenCx; use crate::common::{AsCCharPtr, CodegenCx};
use crate::llvm; use crate::llvm;
use crate::llvm::debuginfo::{ use crate::llvm::debuginfo::{
DIArray, DIBuilder, DIFile, DIFlags, DILexicalBlock, DILocation, DISPFlags, DIScope, DIType, DIArray, DIBuilder, DIFile, DIFlags, DILexicalBlock, DILocation, DISPFlags, DIScope, DIType,
@ -364,7 +364,7 @@ impl<'ll, 'tcx> DebugInfoCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> {
let mut flags = DIFlags::FlagPrototyped; let mut flags = DIFlags::FlagPrototyped;
if fn_abi.ret.layout.abi.is_uninhabited() { if fn_abi.ret.layout.is_uninhabited() {
flags |= DIFlags::FlagNoReturn; flags |= DIFlags::FlagNoReturn;
} }
@ -389,9 +389,9 @@ impl<'ll, 'tcx> DebugInfoCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> {
llvm::LLVMRustDIBuilderCreateMethod( llvm::LLVMRustDIBuilderCreateMethod(
DIB(self), DIB(self),
containing_scope, containing_scope,
name.as_ptr().cast(), name.as_c_char_ptr(),
name.len(), name.len(),
linkage_name.as_ptr().cast(), linkage_name.as_c_char_ptr(),
linkage_name.len(), linkage_name.len(),
file_metadata, file_metadata,
loc.line, loc.line,
@ -406,9 +406,9 @@ impl<'ll, 'tcx> DebugInfoCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> {
llvm::LLVMRustDIBuilderCreateFunction( llvm::LLVMRustDIBuilderCreateFunction(
DIB(self), DIB(self),
containing_scope, containing_scope,
name.as_ptr().cast(), name.as_c_char_ptr(),
name.len(), name.len(),
linkage_name.as_ptr().cast(), linkage_name.as_c_char_ptr(),
linkage_name.len(), linkage_name.len(),
file_metadata, file_metadata,
loc.line, loc.line,
@ -494,7 +494,7 @@ impl<'ll, 'tcx> DebugInfoCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> {
Some(llvm::LLVMRustDIBuilderCreateTemplateTypeParameter( Some(llvm::LLVMRustDIBuilderCreateTemplateTypeParameter(
DIB(cx), DIB(cx),
None, None,
name.as_ptr().cast(), name.as_c_char_ptr(),
name.len(), name.len(),
actual_type_metadata, actual_type_metadata,
)) ))
@ -635,7 +635,7 @@ impl<'ll, 'tcx> DebugInfoCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> {
DIB(self), DIB(self),
dwarf_tag, dwarf_tag,
scope_metadata, scope_metadata,
name.as_ptr().cast(), name.as_c_char_ptr(),
name.len(), name.len(),
file_metadata, file_metadata,
loc.line, loc.line,

View file

@ -5,7 +5,7 @@ use rustc_hir::def_id::DefId;
use rustc_middle::ty::{self, Instance}; use rustc_middle::ty::{self, Instance};
use super::utils::{DIB, debug_context}; use super::utils::{DIB, debug_context};
use crate::common::CodegenCx; use crate::common::{AsCCharPtr, CodegenCx};
use crate::llvm; use crate::llvm;
use crate::llvm::debuginfo::DIScope; use crate::llvm::debuginfo::DIScope;
@ -36,7 +36,7 @@ pub(crate) fn item_namespace<'ll>(cx: &CodegenCx<'ll, '_>, def_id: DefId) -> &'l
llvm::LLVMRustDIBuilderCreateNameSpace( llvm::LLVMRustDIBuilderCreateNameSpace(
DIB(cx), DIB(cx),
parent_scope, parent_scope,
namespace_name_string.as_ptr().cast(), namespace_name_string.as_c_char_ptr(),
namespace_name_string.len(), namespace_name_string.len(),
false, // ExportSymbols (only relevant for C++ anonymous namespaces) false, // ExportSymbols (only relevant for C++ anonymous namespaces)
) )

View file

@ -20,6 +20,7 @@ use smallvec::SmallVec;
use tracing::debug; use tracing::debug;
use crate::abi::{FnAbi, FnAbiLlvmExt}; use crate::abi::{FnAbi, FnAbiLlvmExt};
use crate::common::AsCCharPtr;
use crate::context::CodegenCx; use crate::context::CodegenCx;
use crate::llvm::AttributePlace::Function; use crate::llvm::AttributePlace::Function;
use crate::llvm::Visibility; use crate::llvm::Visibility;
@ -41,7 +42,7 @@ fn declare_raw_fn<'ll>(
) -> &'ll Value { ) -> &'ll Value {
debug!("declare_raw_fn(name={:?}, ty={:?})", name, ty); debug!("declare_raw_fn(name={:?}, ty={:?})", name, ty);
let llfn = unsafe { let llfn = unsafe {
llvm::LLVMRustGetOrInsertFunction(cx.llmod, name.as_ptr().cast(), name.len(), ty) llvm::LLVMRustGetOrInsertFunction(cx.llmod, name.as_c_char_ptr(), name.len(), ty)
}; };
llvm::SetFunctionCallConv(llfn, callconv); llvm::SetFunctionCallConv(llfn, callconv);
@ -68,7 +69,7 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> {
/// return its Value instead. /// return its Value instead.
pub(crate) fn declare_global(&self, name: &str, ty: &'ll Type) -> &'ll Value { pub(crate) fn declare_global(&self, name: &str, ty: &'ll Type) -> &'ll Value {
debug!("declare_global(name={:?})", name); debug!("declare_global(name={:?})", name);
unsafe { llvm::LLVMRustGetOrInsertGlobal(self.llmod, name.as_ptr().cast(), name.len(), ty) } unsafe { llvm::LLVMRustGetOrInsertGlobal(self.llmod, name.as_c_char_ptr(), name.len(), ty) }
} }
/// Declare a C ABI function. /// Declare a C ABI function.
@ -209,7 +210,7 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> {
/// Gets declared value by name. /// Gets declared value by name.
pub(crate) fn get_declared_value(&self, name: &str) -> Option<&'ll Value> { pub(crate) fn get_declared_value(&self, name: &str) -> Option<&'ll Value> {
debug!("get_declared_value(name={:?})", name); debug!("get_declared_value(name={:?})", name);
unsafe { llvm::LLVMRustGetNamedValue(self.llmod, name.as_ptr().cast(), name.len()) } unsafe { llvm::LLVMRustGetNamedValue(self.llmod, name.as_c_char_ptr(), name.len()) }
} }
/// Gets defined or externally defined (AvailableExternally linkage) value by /// Gets defined or externally defined (AvailableExternally linkage) value by

View file

@ -17,13 +17,13 @@ pub use self::IntPredicate::*;
pub use self::Linkage::*; pub use self::Linkage::*;
pub use self::MetadataType::*; pub use self::MetadataType::*;
pub use self::RealPredicate::*; pub use self::RealPredicate::*;
pub use self::ffi::*;
use crate::common::AsCCharPtr;
pub mod archive_ro; pub mod archive_ro;
pub mod diagnostic; pub mod diagnostic;
mod ffi; mod ffi;
pub use self::ffi::*;
impl LLVMRustResult { impl LLVMRustResult {
pub fn into_result(self) -> Result<(), ()> { pub fn into_result(self) -> Result<(), ()> {
match self { match self {
@ -53,9 +53,9 @@ pub fn CreateAttrStringValue<'ll>(llcx: &'ll Context, attr: &str, value: &str) -
unsafe { unsafe {
LLVMCreateStringAttribute( LLVMCreateStringAttribute(
llcx, llcx,
attr.as_ptr().cast(), attr.as_c_char_ptr(),
attr.len().try_into().unwrap(), attr.len().try_into().unwrap(),
value.as_ptr().cast(), value.as_c_char_ptr(),
value.len().try_into().unwrap(), value.len().try_into().unwrap(),
) )
} }
@ -65,7 +65,7 @@ pub fn CreateAttrString<'ll>(llcx: &'ll Context, attr: &str) -> &'ll Attribute {
unsafe { unsafe {
LLVMCreateStringAttribute( LLVMCreateStringAttribute(
llcx, llcx,
attr.as_ptr().cast(), attr.as_c_char_ptr(),
attr.len().try_into().unwrap(), attr.len().try_into().unwrap(),
std::ptr::null(), std::ptr::null(),
0, 0,
@ -294,7 +294,7 @@ pub fn get_value_name(value: &Value) -> &[u8] {
/// Safe wrapper for `LLVMSetValueName2` from a byte slice /// Safe wrapper for `LLVMSetValueName2` from a byte slice
pub fn set_value_name(value: &Value, name: &[u8]) { pub fn set_value_name(value: &Value, name: &[u8]) {
unsafe { unsafe {
let data = name.as_ptr().cast(); let data = name.as_c_char_ptr();
LLVMSetValueName2(value, data, name.len()); LLVMSetValueName2(value, data, name.len());
} }
} }

View file

@ -698,12 +698,9 @@ fn backend_feature_name<'a>(sess: &Session, s: &'a str) -> Option<&'a str> {
let feature = s let feature = s
.strip_prefix(&['+', '-'][..]) .strip_prefix(&['+', '-'][..])
.unwrap_or_else(|| sess.dcx().emit_fatal(InvalidTargetFeaturePrefix { feature: s })); .unwrap_or_else(|| sess.dcx().emit_fatal(InvalidTargetFeaturePrefix { feature: s }));
if s.is_empty() {
return None;
}
// Rustc-specific feature requests like `+crt-static` or `-crt-static` // Rustc-specific feature requests like `+crt-static` or `-crt-static`
// are not passed down to LLVM. // are not passed down to LLVM.
if RUSTC_SPECIFIC_FEATURES.contains(&feature) { if s.is_empty() || RUSTC_SPECIFIC_FEATURES.contains(&feature) {
return None; return None;
} }
Some(feature) Some(feature)

View file

@ -438,7 +438,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
_ => bug!("C-variadic function must have a `VaList` place"), _ => bug!("C-variadic function must have a `VaList` place"),
} }
} }
if self.fn_abi.ret.layout.abi.is_uninhabited() { if self.fn_abi.ret.layout.is_uninhabited() {
// Functions with uninhabited return values are marked `noreturn`, // Functions with uninhabited return values are marked `noreturn`,
// so we should make sure that we never actually do. // so we should make sure that we never actually do.
// We play it safe by using a well-defined `abort`, but we could go for immediate UB // We play it safe by using a well-defined `abort`, but we could go for immediate UB
@ -774,7 +774,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
Some(if do_panic { Some(if do_panic {
let msg_str = with_no_visible_paths!({ let msg_str = with_no_visible_paths!({
with_no_trimmed_paths!({ with_no_trimmed_paths!({
if layout.abi.is_uninhabited() { if layout.is_uninhabited() {
// Use this error even for the other intrinsics as it is more precise. // Use this error even for the other intrinsics as it is more precise.
format!("attempted to instantiate uninhabited type `{ty}`") format!("attempted to instantiate uninhabited type `{ty}`")
} else if requirement == ValidityRequirement::Zero { } else if requirement == ValidityRequirement::Zero {

View file

@ -55,7 +55,7 @@ impl<V: CodegenObject> PlaceValue<V> {
/// Creates a `PlaceRef` to this location with the given type. /// Creates a `PlaceRef` to this location with the given type.
pub fn with_type<'tcx>(self, layout: TyAndLayout<'tcx>) -> PlaceRef<'tcx, V> { pub fn with_type<'tcx>(self, layout: TyAndLayout<'tcx>) -> PlaceRef<'tcx, V> {
assert!( assert!(
layout.is_unsized() || layout.abi.is_uninhabited() || self.llextra.is_none(), layout.is_unsized() || layout.is_uninhabited() || self.llextra.is_none(),
"Had pointer metadata {:?} for sized type {layout:?}", "Had pointer metadata {:?} for sized type {layout:?}",
self.llextra, self.llextra,
); );
@ -239,7 +239,7 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> {
let dl = &bx.tcx().data_layout; let dl = &bx.tcx().data_layout;
let cast_to_layout = bx.cx().layout_of(cast_to); let cast_to_layout = bx.cx().layout_of(cast_to);
let cast_to = bx.cx().immediate_backend_type(cast_to_layout); let cast_to = bx.cx().immediate_backend_type(cast_to_layout);
if self.layout.abi.is_uninhabited() { if self.layout.is_uninhabited() {
return bx.cx().const_poison(cast_to); return bx.cx().const_poison(cast_to);
} }
let (tag_scalar, tag_encoding, tag_field) = match self.layout.variants { let (tag_scalar, tag_encoding, tag_field) = match self.layout.variants {
@ -358,7 +358,7 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> {
bx: &mut Bx, bx: &mut Bx,
variant_index: VariantIdx, variant_index: VariantIdx,
) { ) {
if self.layout.for_variant(bx.cx(), variant_index).abi.is_uninhabited() { if self.layout.for_variant(bx.cx(), variant_index).is_uninhabited() {
// We play it safe by using a well-defined `abort`, but we could go for immediate UB // We play it safe by using a well-defined `abort`, but we could go for immediate UB
// if that turns out to be helpful. // if that turns out to be helpful.
bx.abort(); bx.abort();

View file

@ -203,10 +203,10 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
) -> Option<OperandValue<Bx::Value>> { ) -> Option<OperandValue<Bx::Value>> {
// Check for transmutes that are always UB. // Check for transmutes that are always UB.
if operand.layout.size != cast.size if operand.layout.size != cast.size
|| operand.layout.abi.is_uninhabited() || operand.layout.is_uninhabited()
|| cast.abi.is_uninhabited() || cast.is_uninhabited()
{ {
if !operand.layout.abi.is_uninhabited() { if !operand.layout.is_uninhabited() {
// Since this is known statically and the input could have existed // Since this is known statically and the input could have existed
// without already having hit UB, might as well trap for it. // without already having hit UB, might as well trap for it.
bx.abort(); bx.abort();
@ -555,7 +555,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
assert!(bx.cx().is_backend_immediate(cast)); assert!(bx.cx().is_backend_immediate(cast));
let to_backend_ty = bx.cx().immediate_backend_type(cast); let to_backend_ty = bx.cx().immediate_backend_type(cast);
if operand.layout.abi.is_uninhabited() { if operand.layout.is_uninhabited() {
let val = OperandValue::Immediate(bx.cx().const_poison(to_backend_ty)); let val = OperandValue::Immediate(bx.cx().const_poison(to_backend_ty));
return OperandRef { val, layout: cast }; return OperandRef { val, layout: cast };
} }

View file

@ -395,7 +395,7 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> {
#[inline(always)] #[inline(always)]
fn enforce_validity(ecx: &InterpCx<'tcx, Self>, layout: TyAndLayout<'tcx>) -> bool { fn enforce_validity(ecx: &InterpCx<'tcx, Self>, layout: TyAndLayout<'tcx>) -> bool {
ecx.tcx.sess.opts.unstable_opts.extra_const_ub_checks || layout.abi.is_uninhabited() ecx.tcx.sess.opts.unstable_opts.extra_const_ub_checks || layout.is_uninhabited()
} }
fn load_mir( fn load_mir(

View file

@ -27,7 +27,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
// discriminant, so we cannot do anything here. // discriminant, so we cannot do anything here.
// When evaluating we will always error before even getting here, but ConstProp 'executes' // When evaluating we will always error before even getting here, but ConstProp 'executes'
// dead code, so we cannot ICE here. // dead code, so we cannot ICE here.
if dest.layout().for_variant(self, variant_index).abi.is_uninhabited() { if dest.layout().for_variant(self, variant_index).is_uninhabited() {
throw_ub!(UninhabitedEnumVariantWritten(variant_index)) throw_ub!(UninhabitedEnumVariantWritten(variant_index))
} }
@ -86,7 +86,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
// For consistency with `write_discriminant`, and to make sure that // For consistency with `write_discriminant`, and to make sure that
// `project_downcast` cannot fail due to strange layouts, we declare immediate UB // `project_downcast` cannot fail due to strange layouts, we declare immediate UB
// for uninhabited variants. // for uninhabited variants.
if op.layout().for_variant(self, index).abi.is_uninhabited() { if op.layout().for_variant(self, index).is_uninhabited() {
throw_ub!(UninhabitedEnumVariantRead(index)) throw_ub!(UninhabitedEnumVariantRead(index))
} }
} }
@ -203,7 +203,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
// Reading the discriminant of an uninhabited variant is UB. This is the basis for the // Reading the discriminant of an uninhabited variant is UB. This is the basis for the
// `uninhabited_enum_branching` MIR pass. It also ensures consistency with // `uninhabited_enum_branching` MIR pass. It also ensures consistency with
// `write_discriminant`. // `write_discriminant`.
if op.layout().for_variant(self, index).abi.is_uninhabited() { if op.layout().for_variant(self, index).is_uninhabited() {
throw_ub!(UninhabitedEnumVariantRead(index)) throw_ub!(UninhabitedEnumVariantRead(index))
} }
interp_ok(index) interp_ok(index)

View file

@ -364,7 +364,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
let msg = match requirement { let msg = match requirement {
// For *all* intrinsics we first check `is_uninhabited` to give a more specific // For *all* intrinsics we first check `is_uninhabited` to give a more specific
// error message. // error message.
_ if layout.abi.is_uninhabited() => format!( _ if layout.is_uninhabited() => format!(
"aborted execution: attempted to instantiate uninhabited type `{ty}`" "aborted execution: attempted to instantiate uninhabited type `{ty}`"
), ),
ValidityRequirement::Inhabited => bug!("handled earlier"), ValidityRequirement::Inhabited => bug!("handled earlier"),

View file

@ -315,7 +315,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
let ptr = left.to_scalar().to_pointer(self)?; let ptr = left.to_scalar().to_pointer(self)?;
let pointee_ty = left.layout.ty.builtin_deref(true).unwrap(); let pointee_ty = left.layout.ty.builtin_deref(true).unwrap();
let pointee_layout = self.layout_of(pointee_ty)?; let pointee_layout = self.layout_of(pointee_ty)?;
assert!(pointee_layout.abi.is_sized()); assert!(pointee_layout.is_sized());
// The size always fits in `i64` as it can be at most `isize::MAX`. // The size always fits in `i64` as it can be at most `isize::MAX`.
let pointee_size = i64::try_from(pointee_layout.size.bytes()).unwrap(); let pointee_size = i64::try_from(pointee_layout.size.bytes()).unwrap();
@ -518,14 +518,14 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
interp_ok(match null_op { interp_ok(match null_op {
SizeOf => { SizeOf => {
if !layout.abi.is_sized() { if !layout.is_sized() {
span_bug!(self.cur_span(), "unsized type for `NullaryOp::SizeOf`"); span_bug!(self.cur_span(), "unsized type for `NullaryOp::SizeOf`");
} }
let val = layout.size.bytes(); let val = layout.size.bytes();
ImmTy::from_uint(val, usize_layout()) ImmTy::from_uint(val, usize_layout())
} }
AlignOf => { AlignOf => {
if !layout.abi.is_sized() { if !layout.is_sized() {
span_bug!(self.cur_span(), "unsized type for `NullaryOp::AlignOf`"); span_bug!(self.cur_span(), "unsized type for `NullaryOp::AlignOf`");
} }
let val = layout.align.abi.bytes(); let val = layout.align.abi.bytes();

View file

@ -542,7 +542,7 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> {
throw_validation_failure!(self.path, NullPtr { ptr_kind }) throw_validation_failure!(self.path, NullPtr { ptr_kind })
} }
// Do not allow references to uninhabited types. // Do not allow references to uninhabited types.
if place.layout.abi.is_uninhabited() { if place.layout.is_uninhabited() {
let ty = place.layout.ty; let ty = place.layout.ty;
throw_validation_failure!(self.path, PtrToUninhabited { ptr_kind, ty }) throw_validation_failure!(self.path, PtrToUninhabited { ptr_kind, ty })
} }
@ -867,7 +867,7 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> {
/// Add the entire given place to the "data" range of this visit. /// Add the entire given place to the "data" range of this visit.
fn add_data_range_place(&mut self, place: &PlaceTy<'tcx, M::Provenance>) { fn add_data_range_place(&mut self, place: &PlaceTy<'tcx, M::Provenance>) {
// Only sized places can be added this way. // Only sized places can be added this way.
debug_assert!(place.layout.abi.is_sized()); debug_assert!(place.layout.is_sized());
if let Some(data_bytes) = self.data_bytes.as_mut() { if let Some(data_bytes) = self.data_bytes.as_mut() {
let offset = Self::data_range_offset(self.ecx, place); let offset = Self::data_range_offset(self.ecx, place);
data_bytes.add_range(offset, place.layout.size); data_bytes.add_range(offset, place.layout.size);
@ -945,7 +945,7 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> {
layout: TyAndLayout<'tcx>, layout: TyAndLayout<'tcx>,
) -> Cow<'e, RangeSet> { ) -> Cow<'e, RangeSet> {
assert!(layout.ty.is_union()); assert!(layout.ty.is_union());
assert!(layout.abi.is_sized(), "there are no unsized unions"); assert!(layout.is_sized(), "there are no unsized unions");
let layout_cx = LayoutCx::new(*ecx.tcx, ecx.param_env); let layout_cx = LayoutCx::new(*ecx.tcx, ecx.param_env);
return M::cached_union_data_range(ecx, layout.ty, || { return M::cached_union_data_range(ecx, layout.ty, || {
let mut out = RangeSet(Vec::new()); let mut out = RangeSet(Vec::new());

View file

@ -29,7 +29,7 @@ pub fn check_validity_requirement<'tcx>(
// There is nothing strict or lax about inhabitedness. // There is nothing strict or lax about inhabitedness.
if kind == ValidityRequirement::Inhabited { if kind == ValidityRequirement::Inhabited {
return Ok(!layout.abi.is_uninhabited()); return Ok(!layout.is_uninhabited());
} }
let layout_cx = LayoutCx::new(tcx, param_env_and_ty.param_env); let layout_cx = LayoutCx::new(tcx, param_env_and_ty.param_env);

View file

@ -7,6 +7,7 @@ edition = "2021"
# tidy-alphabetical-start # tidy-alphabetical-start
annotate-snippets = "0.11" annotate-snippets = "0.11"
derive_setters = "0.1.6" derive_setters = "0.1.6"
rustc_abi = { path = "../rustc_abi" }
rustc_ast = { path = "../rustc_ast" } rustc_ast = { path = "../rustc_ast" }
rustc_ast_pretty = { path = "../rustc_ast_pretty" } rustc_ast_pretty = { path = "../rustc_ast_pretty" }
rustc_data_structures = { path = "../rustc_data_structures" } rustc_data_structures = { path = "../rustc_data_structures" }

View file

@ -5,12 +5,12 @@ use std::num::ParseIntError;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::process::ExitStatus; use std::process::ExitStatus;
use rustc_abi::TargetDataLayoutErrors;
use rustc_ast_pretty::pprust; use rustc_ast_pretty::pprust;
use rustc_macros::Subdiagnostic; use rustc_macros::Subdiagnostic;
use rustc_span::Span; use rustc_span::Span;
use rustc_span::edition::Edition; use rustc_span::edition::Edition;
use rustc_span::symbol::{Ident, MacroRulesNormalizedIdent, Symbol}; use rustc_span::symbol::{Ident, MacroRulesNormalizedIdent, Symbol};
use rustc_target::abi::TargetDataLayoutErrors;
use rustc_target::spec::{PanicStrategy, SplitDebuginfo, StackProtector, TargetTriple}; use rustc_target::spec::{PanicStrategy, SplitDebuginfo, StackProtector, TargetTriple};
use rustc_type_ir::{ClosureKind, FloatTy}; use rustc_type_ir::{ClosureKind, FloatTy};
use {rustc_ast as ast, rustc_hir as hir}; use {rustc_ast as ast, rustc_hir as hir};

View file

@ -10,6 +10,7 @@ doctest = false
[dependencies] [dependencies]
# tidy-alphabetical-start # tidy-alphabetical-start
itertools = "0.12" itertools = "0.12"
rustc_abi = { path = "../rustc_abi" }
rustc_arena = { path = "../rustc_arena" } rustc_arena = { path = "../rustc_arena" }
rustc_ast = { path = "../rustc_ast" } rustc_ast = { path = "../rustc_ast" }
rustc_attr = { path = "../rustc_attr" } rustc_attr = { path = "../rustc_attr" }

View file

@ -1,6 +1,7 @@
use std::cell::LazyCell; use std::cell::LazyCell;
use std::ops::ControlFlow; use std::ops::ControlFlow;
use rustc_abi::FieldIdx;
use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_data_structures::unord::{UnordMap, UnordSet};
use rustc_errors::MultiSpan; use rustc_errors::MultiSpan;
use rustc_errors::codes::*; use rustc_errors::codes::*;
@ -23,7 +24,6 @@ use rustc_middle::ty::{
TypeVisitableExt, TypeVisitableExt,
}; };
use rustc_session::lint::builtin::UNINHABITED_STATIC; use rustc_session::lint::builtin::UNINHABITED_STATIC;
use rustc_target::abi::FieldIdx;
use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
use rustc_trait_selection::error_reporting::traits::on_unimplemented::OnUnimplementedDirective; use rustc_trait_selection::error_reporting::traits::on_unimplemented::OnUnimplementedDirective;
use rustc_trait_selection::traits; use rustc_trait_selection::traits;
@ -172,7 +172,7 @@ fn check_static_inhabited(tcx: TyCtxt<'_>, def_id: LocalDefId) {
return; return;
} }
}; };
if layout.abi.is_uninhabited() { if layout.is_uninhabited() {
tcx.node_span_lint( tcx.node_span_lint(
UNINHABITED_STATIC, UNINHABITED_STATIC,
tcx.local_def_id_to_hir_id(def_id), tcx.local_def_id_to_hir_id(def_id),

View file

@ -1,5 +1,6 @@
use std::assert_matches::debug_assert_matches; use std::assert_matches::debug_assert_matches;
use rustc_abi::FieldIdx;
use rustc_ast::InlineAsmTemplatePiece; use rustc_ast::InlineAsmTemplatePiece;
use rustc_data_structures::fx::FxIndexSet; use rustc_data_structures::fx::FxIndexSet;
use rustc_hir::{self as hir, LangItem}; use rustc_hir::{self as hir, LangItem};
@ -8,7 +9,6 @@ use rustc_middle::ty::{self, FloatTy, IntTy, Ty, TyCtxt, TypeVisitableExt, UintT
use rustc_session::lint; use rustc_session::lint;
use rustc_span::Symbol; use rustc_span::Symbol;
use rustc_span::def_id::LocalDefId; use rustc_span::def_id::LocalDefId;
use rustc_target::abi::FieldIdx;
use rustc_target::asm::{ use rustc_target::asm::{
InlineAsmReg, InlineAsmRegClass, InlineAsmRegOrRegClass, InlineAsmType, ModifierInfo, InlineAsmReg, InlineAsmRegClass, InlineAsmRegOrRegClass, InlineAsmType, ModifierInfo,
}; };

View file

@ -74,6 +74,7 @@ pub mod wfcheck;
use std::num::NonZero; use std::num::NonZero;
pub use check::{check_abi, check_abi_fn_ptr}; pub use check::{check_abi, check_abi_fn_ptr};
use rustc_abi::VariantIdx;
use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
use rustc_errors::{Diag, ErrorGuaranteed, pluralize, struct_span_code_err}; use rustc_errors::{Diag, ErrorGuaranteed, pluralize, struct_span_code_err};
use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::def_id::{DefId, LocalDefId};
@ -90,7 +91,6 @@ use rustc_session::parse::feature_err;
use rustc_span::def_id::CRATE_DEF_ID; use rustc_span::def_id::CRATE_DEF_ID;
use rustc_span::symbol::{Ident, kw, sym}; use rustc_span::symbol::{Ident, kw, sym};
use rustc_span::{BytePos, DUMMY_SP, Span, Symbol}; use rustc_span::{BytePos, DUMMY_SP, Span, Symbol};
use rustc_target::abi::VariantIdx;
use rustc_target::spec::abi::Abi; use rustc_target::spec::abi::Abi;
use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
use rustc_trait_selection::error_reporting::infer::ObligationCauseExt as _; use rustc_trait_selection::error_reporting::infer::ObligationCauseExt as _;

View file

@ -5,6 +5,7 @@ edition = "2021"
[dependencies] [dependencies]
# tidy-alphabetical-start # tidy-alphabetical-start
rustc_abi = { path = "../rustc_abi" }
rustc_ast = { path = "../rustc_ast" } rustc_ast = { path = "../rustc_ast" }
rustc_ast_pretty = { path = "../rustc_ast_pretty" } rustc_ast_pretty = { path = "../rustc_ast_pretty" }
rustc_attr = { path = "../rustc_attr" } rustc_attr = { path = "../rustc_attr" }

View file

@ -11,7 +11,6 @@ use rustc_data_structures::sync;
use rustc_data_structures::unord::UnordMap; use rustc_data_structures::unord::UnordMap;
use rustc_errors::{Diag, LintDiagnostic, MultiSpan}; use rustc_errors::{Diag, LintDiagnostic, MultiSpan};
use rustc_feature::Features; use rustc_feature::Features;
use rustc_hir as hir;
use rustc_hir::def::Res; use rustc_hir::def::Res;
use rustc_hir::def_id::{CrateNum, DefId}; use rustc_hir::def_id::{CrateNum, DefId};
use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData}; use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData};
@ -27,8 +26,8 @@ use rustc_session::{LintStoreMarker, Session};
use rustc_span::Span; use rustc_span::Span;
use rustc_span::edit_distance::find_best_match_for_names; use rustc_span::edit_distance::find_best_match_for_names;
use rustc_span::symbol::{Ident, Symbol, sym}; use rustc_span::symbol::{Ident, Symbol, sym};
use rustc_target::abi;
use tracing::debug; use tracing::debug;
use {rustc_abi as abi, rustc_hir as hir};
use self::TargetLint::*; use self::TargetLint::*;
use crate::levels::LintLevelsBuilder; use crate::levels::LintLevelsBuilder;

View file

@ -1,3 +1,4 @@
use rustc_abi::FIRST_VARIANT;
use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_data_structures::stack::ensure_sufficient_stack;
use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_data_structures::unord::{UnordMap, UnordSet};
use rustc_hir as hir; use rustc_hir as hir;
@ -6,7 +7,6 @@ use rustc_middle::query::Providers;
use rustc_middle::ty::{self, AdtDef, Instance, Ty, TyCtxt}; use rustc_middle::ty::{self, AdtDef, Instance, Ty, TyCtxt};
use rustc_session::declare_lint; use rustc_session::declare_lint;
use rustc_span::{Span, Symbol, sym}; use rustc_span::{Span, Symbol, sym};
use rustc_target::abi::FIRST_VARIANT;
use tracing::{debug, instrument}; use tracing::{debug, instrument};
use crate::lints::{BuiltinClashingExtern, BuiltinClashingExternSub}; use crate::lints::{BuiltinClashingExtern, BuiltinClashingExternSub};

View file

@ -1,8 +1,8 @@
use hir::{ExprKind, Node, is_range_literal}; use hir::{ExprKind, Node, is_range_literal};
use rustc_abi::{Integer, Size};
use rustc_middle::ty::Ty; use rustc_middle::ty::Ty;
use rustc_middle::ty::layout::IntegerExt; use rustc_middle::ty::layout::IntegerExt;
use rustc_middle::{bug, ty}; use rustc_middle::{bug, ty};
use rustc_target::abi::{Integer, Size};
use {rustc_ast as ast, rustc_attr as attr, rustc_hir as hir}; use {rustc_ast as ast, rustc_attr as attr, rustc_hir as hir};
use crate::LateContext; use crate::LateContext;

View file

@ -8,6 +8,7 @@ edition = "2021"
bitflags = "2.4.1" bitflags = "2.4.1"
libloading = "0.8.0" libloading = "0.8.0"
odht = { version = "0.3.1", features = ["nightly"] } odht = { version = "0.3.1", features = ["nightly"] }
rustc_abi = { path = "../rustc_abi" }
rustc_ast = { path = "../rustc_ast" } rustc_ast = { path = "../rustc_ast" }
rustc_attr = { path = "../rustc_attr" } rustc_attr = { path = "../rustc_attr" }
rustc_data_structures = { path = "../rustc_data_structures" } rustc_data_structures = { path = "../rustc_data_structures" }

View file

@ -6,6 +6,7 @@ use decoder::{DecodeContext, Metadata};
use def_path_hash_map::DefPathHashMapRef; use def_path_hash_map::DefPathHashMapRef;
use encoder::EncodeContext; use encoder::EncodeContext;
pub use encoder::{EncodedMetadata, encode_metadata, rendered_const}; pub use encoder::{EncodedMetadata, encode_metadata, rendered_const};
use rustc_abi::{FieldIdx, VariantIdx};
use rustc_ast::expand::StrippedCfgItem; use rustc_ast::expand::StrippedCfgItem;
use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::svh::Svh; use rustc_data_structures::svh::Svh;
@ -37,7 +38,6 @@ use rustc_span::edition::Edition;
use rustc_span::hygiene::{ExpnIndex, MacroKind, SyntaxContextData}; use rustc_span::hygiene::{ExpnIndex, MacroKind, SyntaxContextData};
use rustc_span::symbol::{Ident, Symbol}; use rustc_span::symbol::{Ident, Symbol};
use rustc_span::{self, ExpnData, ExpnHash, ExpnId, Span}; use rustc_span::{self, ExpnData, ExpnHash, ExpnId, Span};
use rustc_target::abi::{FieldIdx, VariantIdx};
use rustc_target::spec::{PanicStrategy, TargetTriple}; use rustc_target::spec::{PanicStrategy, TargetTriple};
use table::TableBuilder; use table::TableBuilder;
use {rustc_ast as ast, rustc_attr as attr, rustc_hir as hir}; use {rustc_ast as ast, rustc_attr as attr, rustc_hir as hir};

View file

@ -346,7 +346,7 @@ impl<'tcx> SizeSkeleton<'tcx> {
// First try computing a static layout. // First try computing a static layout.
let err = match tcx.layout_of(param_env.and(ty)) { let err = match tcx.layout_of(param_env.and(ty)) {
Ok(layout) => { Ok(layout) => {
if layout.abi.is_sized() { if layout.is_sized() {
return Ok(SizeSkeleton::Known(layout.size, Some(layout.align.abi))); return Ok(SizeSkeleton::Known(layout.size, Some(layout.align.abi)));
} else { } else {
// Just to be safe, don't claim a known layout for unsized types. // Just to be safe, don't claim a known layout for unsized types.

View file

@ -7,6 +7,7 @@ edition = "2021"
# tidy-alphabetical-start # tidy-alphabetical-start
polonius-engine = "0.13.0" polonius-engine = "0.13.0"
regex = "1" regex = "1"
rustc_abi = { path = "../rustc_abi" }
rustc_ast = { path = "../rustc_ast" } rustc_ast = { path = "../rustc_ast" }
rustc_data_structures = { path = "../rustc_data_structures" } rustc_data_structures = { path = "../rustc_data_structures" }
rustc_errors = { path = "../rustc_errors" } rustc_errors = { path = "../rustc_errors" }

View file

@ -1,5 +1,5 @@
use rustc_abi::VariantIdx;
use rustc_middle::mir::{self, Body, Location, Terminator, TerminatorKind}; use rustc_middle::mir::{self, Body, Location, Terminator, TerminatorKind};
use rustc_target::abi::VariantIdx;
use tracing::debug; use tracing::debug;
use super::move_paths::{InitKind, LookupResult, MoveData, MovePathIndex}; use super::move_paths::{InitKind, LookupResult, MoveData, MovePathIndex};

View file

@ -1,5 +1,6 @@
use std::{fmt, iter}; use std::{fmt, iter};
use rustc_abi::{FIRST_VARIANT, FieldIdx, VariantIdx};
use rustc_hir::lang_items::LangItem; use rustc_hir::lang_items::LangItem;
use rustc_index::Idx; use rustc_index::Idx;
use rustc_middle::mir::patch::MirPatch; use rustc_middle::mir::patch::MirPatch;
@ -10,7 +11,6 @@ use rustc_middle::ty::util::IntTypeExt;
use rustc_middle::ty::{self, GenericArgsRef, Ty, TyCtxt}; use rustc_middle::ty::{self, GenericArgsRef, Ty, TyCtxt};
use rustc_span::DUMMY_SP; use rustc_span::DUMMY_SP;
use rustc_span::source_map::Spanned; use rustc_span::source_map::Spanned;
use rustc_target::abi::{FIRST_VARIANT, FieldIdx, VariantIdx};
use tracing::{debug, instrument}; use tracing::{debug, instrument};
/// The value of an inserted drop flag. /// The value of an inserted drop flag.

View file

@ -36,6 +36,7 @@ use std::assert_matches::assert_matches;
use std::fmt::{Debug, Formatter}; use std::fmt::{Debug, Formatter};
use std::ops::Range; use std::ops::Range;
use rustc_abi::{FieldIdx, VariantIdx};
use rustc_data_structures::captures::Captures; use rustc_data_structures::captures::Captures;
use rustc_data_structures::fx::{FxHashMap, FxIndexSet, StdEntry}; use rustc_data_structures::fx::{FxHashMap, FxIndexSet, StdEntry};
use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_data_structures::stack::ensure_sufficient_stack;
@ -46,7 +47,6 @@ use rustc_middle::mir::tcx::PlaceTy;
use rustc_middle::mir::visit::{MutatingUseContext, PlaceContext, Visitor}; use rustc_middle::mir::visit::{MutatingUseContext, PlaceContext, Visitor};
use rustc_middle::mir::*; use rustc_middle::mir::*;
use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_target::abi::{FieldIdx, VariantIdx};
use tracing::debug; use tracing::debug;
use crate::fmt::DebugWithContext; use crate::fmt::DebugWithContext;

View file

@ -7,6 +7,7 @@ edition = "2021"
# tidy-alphabetical-start # tidy-alphabetical-start
either = "1" either = "1"
itertools = "0.12" itertools = "0.12"
rustc_abi = { path = "../rustc_abi" }
rustc_arena = { path = "../rustc_arena" } rustc_arena = { path = "../rustc_arena" }
rustc_ast = { path = "../rustc_ast" } rustc_ast = { path = "../rustc_ast" }
rustc_attr = { path = "../rustc_attr" } rustc_attr = { path = "../rustc_attr" }

View file

@ -1,5 +1,6 @@
//! A pass that eliminates branches on uninhabited or unreachable enum variants. //! A pass that eliminates branches on uninhabited or unreachable enum variants.
use rustc_abi::Variants;
use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::fx::FxHashSet;
use rustc_middle::bug; use rustc_middle::bug;
use rustc_middle::mir::patch::MirPatch; use rustc_middle::mir::patch::MirPatch;
@ -9,7 +10,6 @@ use rustc_middle::mir::{
}; };
use rustc_middle::ty::layout::TyAndLayout; use rustc_middle::ty::layout::TyAndLayout;
use rustc_middle::ty::{Ty, TyCtxt}; use rustc_middle::ty::{Ty, TyCtxt};
use rustc_target::abi::{Abi, Variants};
use tracing::trace; use tracing::trace;
pub(super) struct UnreachableEnumBranching; pub(super) struct UnreachableEnumBranching;
@ -65,7 +65,7 @@ fn variant_discriminants<'tcx>(
Variants::Multiple { variants, .. } => variants Variants::Multiple { variants, .. } => variants
.iter_enumerated() .iter_enumerated()
.filter_map(|(idx, layout)| { .filter_map(|(idx, layout)| {
(layout.abi != Abi::Uninhabited) (!layout.is_uninhabited())
.then(|| ty.discriminant_for_variant(tcx, idx).unwrap().val) .then(|| ty.discriminant_for_variant(tcx, idx).unwrap().val)
}) })
.collect(), .collect(),

View file

@ -5,6 +5,7 @@ edition = "2021"
[dependencies] [dependencies]
# tidy-alphabetical-start # tidy-alphabetical-start
rustc_abi = { path = "../rustc_abi" }
rustc_ast = { path = "../rustc_ast" } rustc_ast = { path = "../rustc_ast" }
rustc_ast_pretty = { path = "../rustc_ast_pretty" } rustc_ast_pretty = { path = "../rustc_ast_pretty" }
rustc_attr = { path = "../rustc_attr" } rustc_attr = { path = "../rustc_attr" }

View file

@ -7,6 +7,7 @@ use std::mem;
use hir::ItemKind; use hir::ItemKind;
use hir::def_id::{LocalDefIdMap, LocalDefIdSet}; use hir::def_id::{LocalDefIdMap, LocalDefIdSet};
use rustc_abi::FieldIdx;
use rustc_data_structures::unord::UnordSet; use rustc_data_structures::unord::UnordSet;
use rustc_errors::MultiSpan; use rustc_errors::MultiSpan;
use rustc_hir as hir; use rustc_hir as hir;
@ -22,7 +23,6 @@ use rustc_middle::{bug, span_bug};
use rustc_session::lint; use rustc_session::lint;
use rustc_session::lint::builtin::DEAD_CODE; use rustc_session::lint::builtin::DEAD_CODE;
use rustc_span::symbol::{Symbol, sym}; use rustc_span::symbol::{Symbol, sym};
use rustc_target::abi::FieldIdx;
use crate::errors::{ use crate::errors::{
ChangeFields, IgnoredDerivedImpls, MultipleDeadCodes, ParentInfo, UselessAssignment, ChangeFields, IgnoredDerivedImpls, MultipleDeadCodes, ParentInfo, UselessAssignment,

View file

@ -1,3 +1,4 @@
use rustc_abi::{HasDataLayout, TargetDataLayout};
use rustc_ast::Attribute; use rustc_ast::Attribute;
use rustc_hir::def::DefKind; use rustc_hir::def::DefKind;
use rustc_hir::def_id::LocalDefId; use rustc_hir::def_id::LocalDefId;
@ -7,7 +8,6 @@ use rustc_middle::ty::{self, ParamEnv, Ty, TyCtxt};
use rustc_span::Span; use rustc_span::Span;
use rustc_span::source_map::Spanned; use rustc_span::source_map::Spanned;
use rustc_span::symbol::sym; use rustc_span::symbol::sym;
use rustc_target::abi::{HasDataLayout, TargetDataLayout};
use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
use rustc_trait_selection::infer::TyCtxtInferExt; use rustc_trait_selection::infer::TyCtxtInferExt;
use rustc_trait_selection::traits; use rustc_trait_selection::traits;

View file

@ -6,6 +6,8 @@ edition = "2021"
[dependencies] [dependencies]
# tidy-alphabetical-start # tidy-alphabetical-start
rustc-hash = "2.0.0" rustc-hash = "2.0.0"
rustc_abi = { path = "../rustc_abi", optional = true }
rustc_apfloat = "0.2.0" rustc_apfloat = "0.2.0"
rustc_arena = { path = "../rustc_arena", optional = true } rustc_arena = { path = "../rustc_arena", optional = true }
rustc_data_structures = { path = "../rustc_data_structures", optional = true } rustc_data_structures = { path = "../rustc_data_structures", optional = true }
@ -29,6 +31,7 @@ tracing-tree = "0.3.0"
[features] [features]
default = ["rustc"] default = ["rustc"]
rustc = [ rustc = [
"dep:rustc_abi",
"dep:rustc_arena", "dep:rustc_arena",
"dep:rustc_data_structures", "dep:rustc_data_structures",
"dep:rustc_errors", "dep:rustc_errors",

View file

@ -1,6 +1,7 @@
use std::fmt; use std::fmt;
use std::iter::once; use std::iter::once;
use rustc_abi::{FIRST_VARIANT, FieldIdx, Integer, VariantIdx};
use rustc_arena::DroplessArena; use rustc_arena::DroplessArena;
use rustc_hir::HirId; use rustc_hir::HirId;
use rustc_hir::def_id::DefId; use rustc_hir::def_id::DefId;
@ -15,7 +16,6 @@ use rustc_middle::ty::{
use rustc_middle::{bug, span_bug}; use rustc_middle::{bug, span_bug};
use rustc_session::lint; use rustc_session::lint;
use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span}; use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span};
use rustc_target::abi::{FIRST_VARIANT, FieldIdx, Integer, VariantIdx};
use crate::constructor::Constructor::*; use crate::constructor::Constructor::*;
use crate::constructor::{ use crate::constructor::{

View file

@ -11,10 +11,10 @@
use std::fmt; use std::fmt;
use rustc_abi::{FieldIdx, VariantIdx};
use rustc_middle::bug; use rustc_middle::bug;
use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt}; use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt};
use rustc_span::sym; use rustc_span::sym;
use rustc_target::abi::{FieldIdx, VariantIdx};
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub(crate) struct FieldPat { pub(crate) struct FieldPat {

View file

@ -7,6 +7,7 @@ edition = "2021"
# tidy-alphabetical-start # tidy-alphabetical-start
bitflags = "2.4.1" bitflags = "2.4.1"
getopts = "0.2" getopts = "0.2"
rustc_abi = { path = "../rustc_abi" }
rustc_ast = { path = "../rustc_ast" } rustc_ast = { path = "../rustc_ast" }
rustc_data_structures = { path = "../rustc_data_structures" } rustc_data_structures = { path = "../rustc_data_structures" }
rustc_errors = { path = "../rustc_errors" } rustc_errors = { path = "../rustc_errors" }

View file

@ -1,10 +1,10 @@
use std::cmp; use std::cmp;
use rustc_abi::{Align, Size};
use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_data_structures::sync::Lock; use rustc_data_structures::sync::Lock;
use rustc_span::Symbol; use rustc_span::Symbol;
use rustc_span::def_id::DefId; use rustc_span::def_id::DefId;
use rustc_target::abi::{Align, Size};
#[derive(Clone, PartialEq, Eq, Hash, Debug)] #[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct VariantInfo { pub struct VariantInfo {

View file

@ -23,12 +23,12 @@
use std::hash::Hash; use std::hash::Hash;
use std::iter; use std::iter;
use rustc_abi::Align;
use rustc_ast::ast; use rustc_ast::ast;
use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet}; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
use rustc_lint_defs::BuiltinLintDiag; use rustc_lint_defs::BuiltinLintDiag;
use rustc_lint_defs::builtin::EXPLICIT_BUILTIN_CFGS_IN_FLAGS; use rustc_lint_defs::builtin::EXPLICIT_BUILTIN_CFGS_IN_FLAGS;
use rustc_span::symbol::{Symbol, sym}; use rustc_span::symbol::{Symbol, sym};
use rustc_target::abi::Align;
use rustc_target::spec::{PanicStrategy, RelocModel, SanitizerSet, TARGETS, Target, TargetTriple}; use rustc_target::spec::{PanicStrategy, RelocModel, SanitizerSet, TARGETS, Target, TargetTriple};
use crate::Session; use crate::Session;

View file

@ -170,7 +170,7 @@ impl<'tcx> Tables<'tcx> {
stable_mir::mir::mono::StaticDef(self.create_def_id(did)) stable_mir::mir::mono::StaticDef(self.create_def_id(did))
} }
pub(crate) fn layout_id(&mut self, layout: rustc_target::abi::Layout<'tcx>) -> Layout { pub(crate) fn layout_id(&mut self, layout: rustc_abi::Layout<'tcx>) -> Layout {
self.layouts.create_or_fetch(layout) self.layouts.create_or_fetch(layout)
} }
} }

View file

@ -1,3 +1,4 @@
use rustc_abi::{Align, Size};
use rustc_middle::mir::ConstValue; use rustc_middle::mir::ConstValue;
use rustc_middle::mir::interpret::{AllocRange, Pointer, alloc_range}; use rustc_middle::mir::interpret::{AllocRange, Pointer, alloc_range};
use stable_mir::Error; use stable_mir::Error;
@ -7,7 +8,7 @@ use stable_mir::ty::{Allocation, ProvenanceMap};
use crate::rustc_smir::{Stable, Tables}; use crate::rustc_smir::{Stable, Tables};
/// Creates new empty `Allocation` from given `Align`. /// Creates new empty `Allocation` from given `Align`.
fn new_empty_allocation(align: rustc_target::abi::Align) -> Allocation { fn new_empty_allocation(align: Align) -> Allocation {
Allocation { Allocation {
bytes: Vec::new(), bytes: Vec::new(),
provenance: ProvenanceMap { ptrs: Vec::new() }, provenance: ProvenanceMap { ptrs: Vec::new() },
@ -45,7 +46,7 @@ pub(crate) fn try_new_allocation<'tcx>(
.align; .align;
let mut allocation = rustc_middle::mir::interpret::Allocation::uninit(size, align.abi); let mut allocation = rustc_middle::mir::interpret::Allocation::uninit(size, align.abi);
allocation allocation
.write_scalar(&tables.tcx, alloc_range(rustc_target::abi::Size::ZERO, size), scalar) .write_scalar(&tables.tcx, alloc_range(Size::ZERO, size), scalar)
.map_err(|e| e.stable(tables))?; .map_err(|e| e.stable(tables))?;
allocation.stable(tables) allocation.stable(tables)
} }
@ -59,7 +60,7 @@ pub(crate) fn try_new_allocation<'tcx>(
} }
ConstValue::Slice { data, meta } => { ConstValue::Slice { data, meta } => {
let alloc_id = tables.tcx.reserve_and_set_memory_alloc(data); let alloc_id = tables.tcx.reserve_and_set_memory_alloc(data);
let ptr = Pointer::new(alloc_id.into(), rustc_target::abi::Size::ZERO); let ptr = Pointer::new(alloc_id.into(), Size::ZERO);
let scalar_ptr = rustc_middle::mir::interpret::Scalar::from_pointer(ptr, &tables.tcx); let scalar_ptr = rustc_middle::mir::interpret::Scalar::from_pointer(ptr, &tables.tcx);
let scalar_meta = let scalar_meta =
rustc_middle::mir::interpret::Scalar::from_target_usize(meta, &tables.tcx); rustc_middle::mir::interpret::Scalar::from_target_usize(meta, &tables.tcx);
@ -72,7 +73,7 @@ pub(crate) fn try_new_allocation<'tcx>(
allocation allocation
.write_scalar( .write_scalar(
&tables.tcx, &tables.tcx,
alloc_range(rustc_target::abi::Size::ZERO, tables.tcx.data_layout.pointer_size), alloc_range(Size::ZERO, tables.tcx.data_layout.pointer_size),
scalar_ptr, scalar_ptr,
) )
.map_err(|e| e.stable(tables))?; .map_err(|e| e.stable(tables))?;
@ -112,10 +113,7 @@ pub(super) fn allocation_filter<'tcx>(
.map(Some) .map(Some)
.collect(); .collect();
for (i, b) in bytes.iter_mut().enumerate() { for (i, b) in bytes.iter_mut().enumerate() {
if !alloc if !alloc.init_mask().get(Size::from_bytes(i + alloc_range.start.bytes_usize())) {
.init_mask()
.get(rustc_target::abi::Size::from_bytes(i + alloc_range.start.bytes_usize()))
{
*b = None; *b = None;
} }
} }

View file

@ -1,9 +1,9 @@
//! Conversion of internal Rust compiler `rustc_target::abi` and `rustc_abi` items to stable ones. //! Conversion of internal Rust compiler `rustc_target` and `rustc_abi` items to stable ones.
#![allow(rustc::usage_of_qualified_ty)] #![allow(rustc::usage_of_qualified_ty)]
use rustc_middle::ty; use rustc_middle::ty;
use rustc_target::abi::call::Conv; use rustc_target::callconv::{self, Conv};
use stable_mir::abi::{ use stable_mir::abi::{
AddressSpace, ArgAbi, CallConvention, FieldsShape, FloatLength, FnAbi, IntegerLength, Layout, AddressSpace, ArgAbi, CallConvention, FieldsShape, FloatLength, FnAbi, IntegerLength, Layout,
LayoutShape, PassMode, Primitive, Scalar, TagEncoding, TyAndLayout, ValueAbi, VariantsShape, LayoutShape, PassMode, Primitive, Scalar, TagEncoding, TyAndLayout, ValueAbi, VariantsShape,
@ -15,7 +15,7 @@ use stable_mir::ty::{Align, IndexedVal, VariantIdx};
use crate::rustc_smir::{Stable, Tables}; use crate::rustc_smir::{Stable, Tables};
impl<'tcx> Stable<'tcx> for rustc_target::abi::VariantIdx { impl<'tcx> Stable<'tcx> for rustc_abi::VariantIdx {
type T = VariantIdx; type T = VariantIdx;
fn stable(&self, _: &mut Tables<'_>) -> Self::T { fn stable(&self, _: &mut Tables<'_>) -> Self::T {
VariantIdx::to_val(self.as_usize()) VariantIdx::to_val(self.as_usize())
@ -33,7 +33,7 @@ impl<'tcx> Stable<'tcx> for rustc_abi::Endian {
} }
} }
impl<'tcx> Stable<'tcx> for rustc_target::abi::TyAndLayout<'tcx, ty::Ty<'tcx>> { impl<'tcx> Stable<'tcx> for rustc_abi::TyAndLayout<'tcx, ty::Ty<'tcx>> {
type T = TyAndLayout; type T = TyAndLayout;
fn stable(&self, tables: &mut Tables<'_>) -> Self::T { fn stable(&self, tables: &mut Tables<'_>) -> Self::T {
@ -41,7 +41,7 @@ impl<'tcx> Stable<'tcx> for rustc_target::abi::TyAndLayout<'tcx, ty::Ty<'tcx>> {
} }
} }
impl<'tcx> Stable<'tcx> for rustc_target::abi::Layout<'tcx> { impl<'tcx> Stable<'tcx> for rustc_abi::Layout<'tcx> {
type T = Layout; type T = Layout;
fn stable(&self, tables: &mut Tables<'_>) -> Self::T { fn stable(&self, tables: &mut Tables<'_>) -> Self::T {
@ -49,9 +49,7 @@ impl<'tcx> Stable<'tcx> for rustc_target::abi::Layout<'tcx> {
} }
} }
impl<'tcx> Stable<'tcx> impl<'tcx> Stable<'tcx> for rustc_abi::LayoutData<rustc_abi::FieldIdx, rustc_abi::VariantIdx> {
for rustc_abi::LayoutData<rustc_target::abi::FieldIdx, rustc_target::abi::VariantIdx>
{
type T = LayoutShape; type T = LayoutShape;
fn stable(&self, tables: &mut Tables<'_>) -> Self::T { fn stable(&self, tables: &mut Tables<'_>) -> Self::T {
@ -65,7 +63,7 @@ impl<'tcx> Stable<'tcx>
} }
} }
impl<'tcx> Stable<'tcx> for rustc_target::abi::call::FnAbi<'tcx, ty::Ty<'tcx>> { impl<'tcx> Stable<'tcx> for callconv::FnAbi<'tcx, ty::Ty<'tcx>> {
type T = FnAbi; type T = FnAbi;
fn stable(&self, tables: &mut Tables<'_>) -> Self::T { fn stable(&self, tables: &mut Tables<'_>) -> Self::T {
@ -81,7 +79,7 @@ impl<'tcx> Stable<'tcx> for rustc_target::abi::call::FnAbi<'tcx, ty::Ty<'tcx>> {
} }
} }
impl<'tcx> Stable<'tcx> for rustc_target::abi::call::ArgAbi<'tcx, ty::Ty<'tcx>> { impl<'tcx> Stable<'tcx> for callconv::ArgAbi<'tcx, ty::Ty<'tcx>> {
type T = ArgAbi; type T = ArgAbi;
fn stable(&self, tables: &mut Tables<'_>) -> Self::T { fn stable(&self, tables: &mut Tables<'_>) -> Self::T {
@ -93,7 +91,7 @@ impl<'tcx> Stable<'tcx> for rustc_target::abi::call::ArgAbi<'tcx, ty::Ty<'tcx>>
} }
} }
impl<'tcx> Stable<'tcx> for rustc_target::abi::call::Conv { impl<'tcx> Stable<'tcx> for callconv::Conv {
type T = CallConvention; type T = CallConvention;
fn stable(&self, _tables: &mut Tables<'_>) -> Self::T { fn stable(&self, _tables: &mut Tables<'_>) -> Self::T {
@ -122,31 +120,29 @@ impl<'tcx> Stable<'tcx> for rustc_target::abi::call::Conv {
} }
} }
impl<'tcx> Stable<'tcx> for rustc_target::abi::call::PassMode { impl<'tcx> Stable<'tcx> for callconv::PassMode {
type T = PassMode; type T = PassMode;
fn stable(&self, _tables: &mut Tables<'_>) -> Self::T { fn stable(&self, _tables: &mut Tables<'_>) -> Self::T {
match self { match self {
rustc_target::abi::call::PassMode::Ignore => PassMode::Ignore, callconv::PassMode::Ignore => PassMode::Ignore,
rustc_target::abi::call::PassMode::Direct(attr) => PassMode::Direct(opaque(attr)), callconv::PassMode::Direct(attr) => PassMode::Direct(opaque(attr)),
rustc_target::abi::call::PassMode::Pair(first, second) => { callconv::PassMode::Pair(first, second) => {
PassMode::Pair(opaque(first), opaque(second)) PassMode::Pair(opaque(first), opaque(second))
} }
rustc_target::abi::call::PassMode::Cast { pad_i32, cast } => { callconv::PassMode::Cast { pad_i32, cast } => {
PassMode::Cast { pad_i32: *pad_i32, cast: opaque(cast) } PassMode::Cast { pad_i32: *pad_i32, cast: opaque(cast) }
} }
rustc_target::abi::call::PassMode::Indirect { attrs, meta_attrs, on_stack } => { callconv::PassMode::Indirect { attrs, meta_attrs, on_stack } => PassMode::Indirect {
PassMode::Indirect { attrs: opaque(attrs),
attrs: opaque(attrs), meta_attrs: opaque(meta_attrs),
meta_attrs: opaque(meta_attrs), on_stack: *on_stack,
on_stack: *on_stack, },
}
}
} }
} }
} }
impl<'tcx> Stable<'tcx> for rustc_abi::FieldsShape<rustc_target::abi::FieldIdx> { impl<'tcx> Stable<'tcx> for rustc_abi::FieldsShape<rustc_abi::FieldIdx> {
type T = FieldsShape; type T = FieldsShape;
fn stable(&self, tables: &mut Tables<'_>) -> Self::T { fn stable(&self, tables: &mut Tables<'_>) -> Self::T {
@ -163,9 +159,7 @@ impl<'tcx> Stable<'tcx> for rustc_abi::FieldsShape<rustc_target::abi::FieldIdx>
} }
} }
impl<'tcx> Stable<'tcx> impl<'tcx> Stable<'tcx> for rustc_abi::Variants<rustc_abi::FieldIdx, rustc_abi::VariantIdx> {
for rustc_abi::Variants<rustc_target::abi::FieldIdx, rustc_target::abi::VariantIdx>
{
type T = VariantsShape; type T = VariantsShape;
fn stable(&self, tables: &mut Tables<'_>) -> Self::T { fn stable(&self, tables: &mut Tables<'_>) -> Self::T {
@ -185,7 +179,7 @@ impl<'tcx> Stable<'tcx>
} }
} }
impl<'tcx> Stable<'tcx> for rustc_abi::TagEncoding<rustc_target::abi::VariantIdx> { impl<'tcx> Stable<'tcx> for rustc_abi::TagEncoding<rustc_abi::VariantIdx> {
type T = TagEncoding; type T = TagEncoding;
fn stable(&self, tables: &mut Tables<'_>) -> Self::T { fn stable(&self, tables: &mut Tables<'_>) -> Self::T {

View file

@ -691,11 +691,7 @@ impl<'tcx> Stable<'tcx> for mir::interpret::Allocation {
type T = stable_mir::ty::Allocation; type T = stable_mir::ty::Allocation;
fn stable(&self, tables: &mut Tables<'_>) -> Self::T { fn stable(&self, tables: &mut Tables<'_>) -> Self::T {
alloc::allocation_filter( alloc::allocation_filter(self, alloc_range(rustc_abi::Size::ZERO, self.size()), tables)
self,
alloc_range(rustc_target::abi::Size::ZERO, self.size()),
tables,
)
} }
} }

View file

@ -36,7 +36,7 @@ pub struct Tables<'tcx> {
pub(crate) instances: IndexMap<ty::Instance<'tcx>, InstanceDef>, pub(crate) instances: IndexMap<ty::Instance<'tcx>, InstanceDef>,
pub(crate) ty_consts: IndexMap<ty::Const<'tcx>, TyConstId>, pub(crate) ty_consts: IndexMap<ty::Const<'tcx>, TyConstId>,
pub(crate) mir_consts: IndexMap<mir::Const<'tcx>, MirConstId>, pub(crate) mir_consts: IndexMap<mir::Const<'tcx>, MirConstId>,
pub(crate) layouts: IndexMap<rustc_target::abi::Layout<'tcx>, Layout>, pub(crate) layouts: IndexMap<rustc_abi::Layout<'tcx>, Layout>,
} }
impl<'tcx> Tables<'tcx> { impl<'tcx> Tables<'tcx> {

View file

@ -7,6 +7,8 @@ edition = "2021"
# tidy-alphabetical-start # tidy-alphabetical-start
punycode = "0.4.0" punycode = "0.4.0"
rustc-demangle = "0.1.21" rustc-demangle = "0.1.21"
rustc_abi = { path = "../rustc_abi" }
rustc_data_structures = { path = "../rustc_data_structures" } rustc_data_structures = { path = "../rustc_data_structures" }
rustc_errors = { path = "../rustc_errors" } rustc_errors = { path = "../rustc_errors" }
rustc_hir = { path = "../rustc_hir" } rustc_hir = { path = "../rustc_hir" }

View file

@ -2,6 +2,7 @@ use std::fmt::Write;
use std::iter; use std::iter;
use std::ops::Range; use std::ops::Range;
use rustc_abi::Integer;
use rustc_data_structures::base_n::ToBaseN; use rustc_data_structures::base_n::ToBaseN;
use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::intern::Interned; use rustc_data_structures::intern::Interned;
@ -17,7 +18,6 @@ use rustc_middle::ty::{
TyCtxt, TypeVisitable, TypeVisitableExt, UintTy, TyCtxt, TypeVisitable, TypeVisitableExt, UintTy,
}; };
use rustc_span::symbol::kw; use rustc_span::symbol::kw;
use rustc_target::abi::Integer;
use rustc_target::spec::abi::Abi; use rustc_target::spec::abi::Abi;
pub(super) fn mangle<'tcx>( pub(super) fn mangle<'tcx>(

View file

@ -339,9 +339,7 @@ pub(crate) mod rustc {
// 2. enums that delegate their layout to a variant // 2. enums that delegate their layout to a variant
// 3. enums with multiple variants // 3. enums with multiple variants
match layout.variants() { match layout.variants() {
Variants::Single { .. } Variants::Single { .. } if layout.is_uninhabited() && layout.size == Size::ZERO => {
if layout.abi.is_uninhabited() && layout.size == Size::ZERO =>
{
// The layout representation of uninhabited, ZST enums is // The layout representation of uninhabited, ZST enums is
// defined to be like that of the `!` type, as opposed of a // defined to be like that of the `!` type, as opposed of a
// typical enum. Consequently, they cannot be descended into // typical enum. Consequently, they cannot be descended into

View file

@ -10,7 +10,7 @@ pub(super) fn partially_check_layout<'tcx>(cx: &LayoutCx<'tcx>, layout: &TyAndLa
// Type-level uninhabitedness should always imply ABI uninhabitedness. // Type-level uninhabitedness should always imply ABI uninhabitedness.
if layout.ty.is_privately_uninhabited(tcx, cx.param_env) { if layout.ty.is_privately_uninhabited(tcx, cx.param_env) {
assert!(layout.abi.is_uninhabited()); assert!(layout.is_uninhabited());
} }
if layout.size.bytes() % layout.align.abi.bytes() != 0 { if layout.size.bytes() % layout.align.abi.bytes() != 0 {
@ -262,9 +262,7 @@ pub(super) fn partially_check_layout<'tcx>(cx: &LayoutCx<'tcx>, layout: &TyAndLa
) )
} }
// Skip empty variants. // Skip empty variants.
if variant.size == Size::ZERO if variant.size == Size::ZERO || variant.fields.count() == 0 || variant.is_uninhabited()
|| variant.fields.count() == 0
|| variant.abi.is_uninhabited()
{ {
// These are never actually accessed anyway, so we can skip the coherence check // These are never actually accessed anyway, so we can skip the coherence check
// for them. They also fail that check, since they have // for them. They also fail that check, since they have

View file

@ -32,6 +32,7 @@
#![feature(restricted_std)] #![feature(restricted_std)]
#![feature(rustc_attrs)] #![feature(rustc_attrs)]
#![feature(min_specialization)] #![feature(min_specialization)]
#![feature(extend_one)]
#![recursion_limit = "256"] #![recursion_limit = "256"]
#![allow(internal_features)] #![allow(internal_features)]
#![deny(ffi_unwind_calls)] #![deny(ffi_unwind_calls)]
@ -43,6 +44,7 @@ pub mod bridge;
mod diagnostic; mod diagnostic;
mod escape; mod escape;
mod to_tokens;
use std::ffi::CStr; use std::ffi::CStr;
use std::ops::{Range, RangeBounds}; use std::ops::{Range, RangeBounds};
@ -52,6 +54,8 @@ use std::{error, fmt};
#[unstable(feature = "proc_macro_diagnostic", issue = "54140")] #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
pub use diagnostic::{Diagnostic, Level, MultiSpan}; pub use diagnostic::{Diagnostic, Level, MultiSpan};
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
pub use to_tokens::ToTokens;
use crate::escape::{EscapeOptions, escape_bytes}; use crate::escape::{EscapeOptions, escape_bytes};

View file

@ -0,0 +1,310 @@
use std::borrow::Cow;
use std::ffi::{CStr, CString};
use std::rc::Rc;
use crate::{ConcatTreesHelper, Group, Ident, Literal, Punct, Span, TokenStream, TokenTree};
/// Types that can be interpolated inside a [`quote!`] invocation.
///
/// [`quote!`]: crate::quote!
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
pub trait ToTokens {
/// Write `self` to the given `TokenStream`.
///
/// # Example
///
/// Example implementation for a struct representing Rust paths like
/// `std::cmp::PartialEq`:
///
/// ```
/// #![feature(proc_macro_totokens)]
///
/// use std::iter;
/// use proc_macro::{Spacing, Punct, TokenStream, TokenTree, ToTokens};
///
/// pub struct Path {
/// pub global: bool,
/// pub segments: Vec<PathSegment>,
/// }
///
/// impl ToTokens for Path {
/// fn to_tokens(&self, tokens: &mut TokenStream) {
/// for (i, segment) in self.segments.iter().enumerate() {
/// if i > 0 || self.global {
/// // Double colon `::`
/// tokens.extend(iter::once(TokenTree::from(Punct::new(':', Spacing::Joint))));
/// tokens.extend(iter::once(TokenTree::from(Punct::new(':', Spacing::Alone))));
/// }
/// segment.to_tokens(tokens);
/// }
/// }
/// }
/// #
/// # pub struct PathSegment;
/// #
/// # impl ToTokens for PathSegment {
/// # fn to_tokens(&self, tokens: &mut TokenStream) {
/// # unimplemented!()
/// # }
/// # }
/// ```
fn to_tokens(&self, tokens: &mut TokenStream);
/// Convert `self` directly into a `TokenStream` object.
///
/// This method is implicitly implemented using `to_tokens`, and acts as a
/// convenience method for consumers of the `ToTokens` trait.
fn to_token_stream(&self) -> TokenStream {
let mut tokens = TokenStream::new();
self.to_tokens(&mut tokens);
tokens
}
/// Convert `self` directly into a `TokenStream` object.
///
/// This method is implicitly implemented using `to_tokens`, and acts as a
/// convenience method for consumers of the `ToTokens` trait.
fn into_token_stream(self) -> TokenStream
where
Self: Sized,
{
self.to_token_stream()
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl ToTokens for TokenTree {
fn to_tokens(&self, tokens: &mut TokenStream) {
tokens.extend_one(self.clone());
}
fn into_token_stream(self) -> TokenStream {
let mut builder = ConcatTreesHelper::new(1);
builder.push(self);
builder.build()
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl ToTokens for TokenStream {
fn to_tokens(&self, tokens: &mut TokenStream) {
tokens.extend(self.clone());
}
fn into_token_stream(self) -> TokenStream {
self
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl ToTokens for Literal {
fn to_tokens(&self, tokens: &mut TokenStream) {
tokens.extend_one(TokenTree::from(self.clone()));
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl ToTokens for Ident {
fn to_tokens(&self, tokens: &mut TokenStream) {
tokens.extend_one(TokenTree::from(self.clone()));
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl ToTokens for Punct {
fn to_tokens(&self, tokens: &mut TokenStream) {
tokens.extend_one(TokenTree::from(self.clone()));
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl ToTokens for Group {
fn to_tokens(&self, tokens: &mut TokenStream) {
tokens.extend_one(TokenTree::from(self.clone()));
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl<T: ToTokens + ?Sized> ToTokens for &T {
fn to_tokens(&self, tokens: &mut TokenStream) {
(**self).to_tokens(tokens)
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl<T: ToTokens + ?Sized> ToTokens for &mut T {
fn to_tokens(&self, tokens: &mut TokenStream) {
(**self).to_tokens(tokens)
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl<T: ToTokens + ?Sized> ToTokens for Box<T> {
fn to_tokens(&self, tokens: &mut TokenStream) {
(**self).to_tokens(tokens)
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl<T: ToTokens + ?Sized> ToTokens for Rc<T> {
fn to_tokens(&self, tokens: &mut TokenStream) {
(**self).to_tokens(tokens)
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl<T: ToTokens + ToOwned + ?Sized> ToTokens for Cow<'_, T> {
fn to_tokens(&self, tokens: &mut TokenStream) {
(**self).to_tokens(tokens)
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl<T: ToTokens> ToTokens for Option<T> {
fn to_tokens(&self, tokens: &mut TokenStream) {
if let Some(t) = self {
t.to_tokens(tokens);
}
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl ToTokens for u8 {
fn to_tokens(&self, tokens: &mut TokenStream) {
Literal::u8_suffixed(*self).to_tokens(tokens)
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl ToTokens for u16 {
fn to_tokens(&self, tokens: &mut TokenStream) {
Literal::u16_suffixed(*self).to_tokens(tokens)
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl ToTokens for u32 {
fn to_tokens(&self, tokens: &mut TokenStream) {
Literal::u32_suffixed(*self).to_tokens(tokens)
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl ToTokens for u64 {
fn to_tokens(&self, tokens: &mut TokenStream) {
Literal::u64_suffixed(*self).to_tokens(tokens)
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl ToTokens for u128 {
fn to_tokens(&self, tokens: &mut TokenStream) {
Literal::u128_suffixed(*self).to_tokens(tokens)
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl ToTokens for i8 {
fn to_tokens(&self, tokens: &mut TokenStream) {
Literal::i8_suffixed(*self).to_tokens(tokens)
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl ToTokens for i16 {
fn to_tokens(&self, tokens: &mut TokenStream) {
Literal::i16_suffixed(*self).to_tokens(tokens)
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl ToTokens for i32 {
fn to_tokens(&self, tokens: &mut TokenStream) {
Literal::i32_suffixed(*self).to_tokens(tokens)
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl ToTokens for i64 {
fn to_tokens(&self, tokens: &mut TokenStream) {
Literal::i64_suffixed(*self).to_tokens(tokens)
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl ToTokens for i128 {
fn to_tokens(&self, tokens: &mut TokenStream) {
Literal::i128_suffixed(*self).to_tokens(tokens)
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl ToTokens for f32 {
fn to_tokens(&self, tokens: &mut TokenStream) {
Literal::f32_suffixed(*self).to_tokens(tokens)
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl ToTokens for f64 {
fn to_tokens(&self, tokens: &mut TokenStream) {
Literal::f64_suffixed(*self).to_tokens(tokens)
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl ToTokens for usize {
fn to_tokens(&self, tokens: &mut TokenStream) {
Literal::usize_suffixed(*self).to_tokens(tokens)
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl ToTokens for isize {
fn to_tokens(&self, tokens: &mut TokenStream) {
Literal::isize_suffixed(*self).to_tokens(tokens)
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl ToTokens for bool {
fn to_tokens(&self, tokens: &mut TokenStream) {
let word = if *self { "true" } else { "false" };
Ident::new(word, Span::call_site()).to_tokens(tokens)
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl ToTokens for char {
fn to_tokens(&self, tokens: &mut TokenStream) {
Literal::character(*self).to_tokens(tokens)
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl ToTokens for str {
fn to_tokens(&self, tokens: &mut TokenStream) {
Literal::string(self).to_tokens(tokens)
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl ToTokens for String {
fn to_tokens(&self, tokens: &mut TokenStream) {
Literal::string(self).to_tokens(tokens)
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl ToTokens for CStr {
fn to_tokens(&self, tokens: &mut TokenStream) {
Literal::c_string(self).to_tokens(tokens)
}
}
#[unstable(feature = "proc_macro_totokens", issue = "130977")]
impl ToTokens for CString {
fn to_tokens(&self, tokens: &mut TokenStream) {
Literal::c_string(self).to_tokens(tokens)
}
}

View file

@ -525,14 +525,6 @@ ${SDK_PATH}/tools/${ARCH}/ffx repository publish \
pkg/repo pkg/repo
``` ```
Then we can add the repository to `ffx`'s package server as `hello-fuchsia` using:
```sh
${SDK_PATH}/tools/${ARCH}/ffx repository add-from-pm \
--repository hello-fuchsia \
pkg/repo
```
## Running a Fuchsia component on an emulator ## Running a Fuchsia component on an emulator
At this point, we are ready to run our Fuchsia At this point, we are ready to run our Fuchsia
@ -590,7 +582,8 @@ Now, start a package repository server to serve our
package to the emulator: package to the emulator:
```sh ```sh
${SDK_PATH}/tools/${ARCH}/ffx repository server start ${SDK_PATH}/tools/${ARCH}/ffx repository server start \
--background --repository hello-fuchsia --repo-path pkg-repo
``` ```
Once the repository server is up and running, register it with the target Fuchsia system running in the emulator: Once the repository server is up and running, register it with the target Fuchsia system running in the emulator:

View file

@ -60,8 +60,8 @@ pub(crate) fn document_type_layout<'a, 'cx: 'a>(
span_bug!(tcx.def_span(ty_def_id), "not an adt") span_bug!(tcx.def_span(ty_def_id), "not an adt")
}; };
let name = adt.variant(variant_idx).name; let name = adt.variant(variant_idx).name;
let is_unsized = variant_layout.abi.is_unsized(); let is_unsized = variant_layout.is_unsized();
let is_uninhabited = variant_layout.abi.is_uninhabited(); let is_uninhabited = variant_layout.is_uninhabited();
let size = variant_layout.size.bytes() - tag_size; let size = variant_layout.size.bytes() - tag_size;
let type_layout_size = TypeLayoutSize { is_unsized, is_uninhabited, size }; let type_layout_size = TypeLayoutSize { is_unsized, is_uninhabited, size };
(name, type_layout_size) (name, type_layout_size)
@ -72,8 +72,8 @@ pub(crate) fn document_type_layout<'a, 'cx: 'a>(
}; };
let type_layout_size = tcx.layout_of(param_env.and(ty)).map(|layout| { let type_layout_size = tcx.layout_of(param_env.and(ty)).map(|layout| {
let is_unsized = layout.abi.is_unsized(); let is_unsized = layout.is_unsized();
let is_uninhabited = layout.abi.is_uninhabited(); let is_uninhabited = layout.is_uninhabited();
let size = layout.size.bytes(); let size = layout.size.bytes();
TypeLayoutSize { is_unsized, is_uninhabited, size } TypeLayoutSize { is_unsized, is_uninhabited, size }
}); });

View file

@ -230,7 +230,7 @@ h4.code-header {
padding: 0; padding: 0;
white-space: pre-wrap; white-space: pre-wrap;
} }
.structfield { .structfield, .sub-variant-field {
margin: 0.6em 0; margin: 0.6em 0;
} }

View file

@ -1,6 +1,7 @@
// This test checks that fields are displayed as expected (one by line) and they are surrounded // This test checks that fields are displayed as expected (one by line) and they are surrounded
// by margins. // by margins.
store-value: (margin, "9.6px")
define-function: ( define-function: (
"check-fields", "check-fields",
[path, selector_1, selector_2], [path, selector_1, selector_2],
@ -12,8 +13,8 @@ define-function: (
// Check the margins. // Check the margins.
assert-css: (".structfield.section-header", { assert-css: (".structfield.section-header", {
"margin-top": "9.6px", "margin-top": |margin|,
"margin-bottom": "9.6px", "margin-bottom": |margin|,
"margin-left": "0px", "margin-left": "0px",
"margin-right": "0px", "margin-right": "0px",
}, ALL) }, ALL)
@ -41,9 +42,9 @@ store-position: ("#variant\.B\.field\.b", {"y": b_y})
assert: |a_y| < |b_y| assert: |a_y| < |b_y|
// Check the margins. // Check the margins.
assert-css: (".sub-variant-field .section-header", { assert-css: (".sub-variant-field", {
"margin-top": "0px", "margin-top": |margin|,
"margin-bottom": "0px", "margin-bottom": |margin|,
"margin-left": "0px", "margin-left": "24px",
"margin-right": "0px", "margin-right": "0px",
}, ALL) }, ALL)

View file

@ -41,7 +41,7 @@ body:
Block { Block {
targeted_by_break: false targeted_by_break: false
span: $DIR/thir-tree-match.rs:15:32: 21:2 (#0) span: $DIR/thir-tree-match.rs:15:32: 21:2 (#0)
region_scope: Node(25) region_scope: Node(3)
safety_mode: Safe safety_mode: Safe
stmts: [] stmts: []
expr: expr:
@ -51,8 +51,8 @@ body:
span: $DIR/thir-tree-match.rs:16:5: 20:6 (#0) span: $DIR/thir-tree-match.rs:16:5: 20:6 (#0)
kind: kind:
Scope { Scope {
region_scope: Node(3) region_scope: Node(4)
lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).3)) lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).4))
value: value:
Expr { Expr {
ty: bool ty: bool
@ -67,8 +67,8 @@ body:
span: $DIR/thir-tree-match.rs:16:11: 16:14 (#0) span: $DIR/thir-tree-match.rs:16:11: 16:14 (#0)
kind: kind:
Scope { Scope {
region_scope: Node(4) region_scope: Node(5)
lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).4)) lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).5))
value: value:
Expr { Expr {
ty: Foo ty: Foo
@ -123,16 +123,16 @@ body:
body: body:
Expr { Expr {
ty: bool ty: bool
temp_lifetime: Some(Node(12)) temp_lifetime: Some(Node(13))
span: $DIR/thir-tree-match.rs:17:36: 17:40 (#0) span: $DIR/thir-tree-match.rs:17:36: 17:40 (#0)
kind: kind:
Scope { Scope {
region_scope: Node(13) region_scope: Node(14)
lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).13)) lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).14))
value: value:
Expr { Expr {
ty: bool ty: bool
temp_lifetime: Some(Node(12)) temp_lifetime: Some(Node(13))
span: $DIR/thir-tree-match.rs:17:36: 17:40 (#0) span: $DIR/thir-tree-match.rs:17:36: 17:40 (#0)
kind: kind:
Literal( lit: Spanned { node: Bool(true), span: $DIR/thir-tree-match.rs:17:36: 17:40 (#0) }, neg: false) Literal( lit: Spanned { node: Bool(true), span: $DIR/thir-tree-match.rs:17:36: 17:40 (#0) }, neg: false)
@ -140,8 +140,8 @@ body:
} }
} }
} }
lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).12)) lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).13))
scope: Node(12) scope: Node(13)
span: $DIR/thir-tree-match.rs:17:9: 17:40 (#0) span: $DIR/thir-tree-match.rs:17:9: 17:40 (#0)
} }
Arm { Arm {
@ -175,16 +175,16 @@ body:
body: body:
Expr { Expr {
ty: bool ty: bool
temp_lifetime: Some(Node(18)) temp_lifetime: Some(Node(19))
span: $DIR/thir-tree-match.rs:18:27: 18:32 (#0) span: $DIR/thir-tree-match.rs:18:27: 18:32 (#0)
kind: kind:
Scope { Scope {
region_scope: Node(19) region_scope: Node(20)
lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).19)) lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).20))
value: value:
Expr { Expr {
ty: bool ty: bool
temp_lifetime: Some(Node(18)) temp_lifetime: Some(Node(19))
span: $DIR/thir-tree-match.rs:18:27: 18:32 (#0) span: $DIR/thir-tree-match.rs:18:27: 18:32 (#0)
kind: kind:
Literal( lit: Spanned { node: Bool(false), span: $DIR/thir-tree-match.rs:18:27: 18:32 (#0) }, neg: false) Literal( lit: Spanned { node: Bool(false), span: $DIR/thir-tree-match.rs:18:27: 18:32 (#0) }, neg: false)
@ -192,8 +192,8 @@ body:
} }
} }
} }
lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).18)) lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).19))
scope: Node(18) scope: Node(19)
span: $DIR/thir-tree-match.rs:18:9: 18:32 (#0) span: $DIR/thir-tree-match.rs:18:9: 18:32 (#0)
} }
Arm { Arm {
@ -219,16 +219,16 @@ body:
body: body:
Expr { Expr {
ty: bool ty: bool
temp_lifetime: Some(Node(23)) temp_lifetime: Some(Node(24))
span: $DIR/thir-tree-match.rs:19:24: 19:28 (#0) span: $DIR/thir-tree-match.rs:19:24: 19:28 (#0)
kind: kind:
Scope { Scope {
region_scope: Node(24) region_scope: Node(25)
lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).24)) lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).25))
value: value:
Expr { Expr {
ty: bool ty: bool
temp_lifetime: Some(Node(23)) temp_lifetime: Some(Node(24))
span: $DIR/thir-tree-match.rs:19:24: 19:28 (#0) span: $DIR/thir-tree-match.rs:19:24: 19:28 (#0)
kind: kind:
Literal( lit: Spanned { node: Bool(true), span: $DIR/thir-tree-match.rs:19:24: 19:28 (#0) }, neg: false) Literal( lit: Spanned { node: Bool(true), span: $DIR/thir-tree-match.rs:19:24: 19:28 (#0) }, neg: false)
@ -236,8 +236,8 @@ body:
} }
} }
} }
lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).23)) lint_level: Explicit(HirId(DefId(0:16 ~ thir_tree_match[fcf8]::has_match).24))
scope: Node(23) scope: Node(24)
span: $DIR/thir-tree-match.rs:19:9: 19:28 (#0) span: $DIR/thir-tree-match.rs:19:9: 19:28 (#0)
} }
] ]