rust/compiler/rustc_const_eval/src/util/alignment.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

68 lines
1.8 KiB
Rust
Raw Normal View History

2020-03-29 14:41:09 +00:00
use rustc_middle::mir::*;
use rustc_middle::ty::{self, TyCtxt};
use rustc_target::abi::Align;
2019-02-08 13:53:55 +00:00
/// Returns `true` if this place is allowed to be less aligned
/// than its containing struct (because it is within a packed
/// struct).
pub fn is_disaligned<'tcx, L>(
2019-06-13 21:48:52 +00:00
tcx: TyCtxt<'tcx>,
local_decls: &L,
param_env: ty::ParamEnv<'tcx>,
place: Place<'tcx>,
) -> bool
where
L: HasLocalDecls<'tcx>,
{
debug!("is_disaligned({:?})", place);
let Some(pack) = is_within_packed(tcx, local_decls, place) else {
debug!("is_disaligned({:?}) - not within packed", place);
return false;
};
let ty = place.ty(local_decls, tcx).ty;
match tcx.layout_of(param_env.and(ty)) {
Ok(layout) if layout.align.abi <= pack => {
// If the packed alignment is greater or equal to the field alignment, the type won't be
// further disaligned.
debug!(
"is_disaligned({:?}) - align = {}, packed = {}; not disaligned",
place,
layout.align.abi.bytes(),
pack.bytes()
);
false
}
_ => {
debug!("is_disaligned({:?}) - true", place);
true
}
}
}
fn is_within_packed<'tcx, L>(
tcx: TyCtxt<'tcx>,
local_decls: &L,
place: Place<'tcx>,
) -> Option<Align>
where
L: HasLocalDecls<'tcx>,
{
for (place_base, elem) in place.iter_projections().rev() {
match elem {
// encountered a Deref, which is ABI-aligned
ProjectionElem::Deref => break,
ProjectionElem::Field(..) => {
let ty = place_base.ty(local_decls, tcx).ty;
2020-08-02 22:49:11 +00:00
match ty.kind() {
ty::Adt(def, _) => return def.repr().pack,
_ => {}
}
}
_ => {}
}
}
None
}