3 use rustc_middle::mir::interpret::ErrorHandled;
4 use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, TyAndLayout};
5 use rustc_middle::ty::{self, Instance, Ty, TypeFoldable, TypeVisitable};
6 use rustc_target::abi::call::{FnAbi, PassMode};
10 use rustc_index::bit_set::BitSet;
11 use rustc_index::vec::IndexVec;
13 use self::debuginfo::{FunctionDebugContext, PerLocalVarDebugInfo};
14 use self::place::PlaceRef;
15 use rustc_middle::mir::traversal;
17 use self::operand::{OperandRef, OperandValue};
19 // Used for tracking the state of generated basic blocks.
21 /// Nothing created yet.
27 /// Nothing created yet, and nothing should be.
31 /// Master context for codegenning from MIR.
32 pub struct FunctionCx<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> {
33 instance: Instance<'tcx>,
35 mir: &'tcx mir::Body<'tcx>,
37 debug_context: Option<FunctionDebugContext<Bx::DIScope, Bx::DILocation>>,
41 cx: &'a Bx::CodegenCx,
43 fn_abi: &'tcx FnAbi<'tcx, Ty<'tcx>>,
45 /// When unwinding is initiated, we have to store this personality
46 /// value somewhere so that we can load it and re-use it in the
47 /// resume instruction. The personality is (afaik) some kind of
48 /// value used for C++ unwinding, which must filter by type: we
49 /// don't really care about it very much. Anyway, this value
50 /// contains an alloca into which the personality is stored and
51 /// then later loaded when generating the DIVERGE_BLOCK.
52 personality_slot: Option<PlaceRef<'tcx, Bx::Value>>,
54 /// A backend `BasicBlock` for each MIR `BasicBlock`, created lazily
55 /// as-needed (e.g. RPO reaching it or another block branching to it).
56 // FIXME(eddyb) rename `llbbs` and other `ll`-prefixed things to use a
57 // more backend-agnostic prefix such as `cg` (i.e. this would be `cgbbs`).
58 cached_llbbs: IndexVec<mir::BasicBlock, CachedLlbb<Bx::BasicBlock>>,
60 /// The funclet status of each basic block
61 cleanup_kinds: IndexVec<mir::BasicBlock, analyze::CleanupKind>,
63 /// When targeting MSVC, this stores the cleanup info for each funclet BB.
64 /// This is initialized at the same time as the `landing_pads` entry for the
65 /// funclets' head block, i.e. when needed by an unwind / `cleanup_ret` edge.
66 funclets: IndexVec<mir::BasicBlock, Option<Bx::Funclet>>,
68 /// This stores the cached landing/cleanup pad block for a given BB.
69 // FIXME(eddyb) rename this to `eh_pads`.
70 landing_pads: IndexVec<mir::BasicBlock, Option<Bx::BasicBlock>>,
72 /// Cached unreachable block
73 unreachable_block: Option<Bx::BasicBlock>,
75 /// Cached double unwind guarding block
76 double_unwind_guard: Option<Bx::BasicBlock>,
78 /// The location where each MIR arg/var/tmp/ret is stored. This is
79 /// usually an `PlaceRef` representing an alloca, but not always:
80 /// sometimes we can skip the alloca and just store the value
81 /// directly using an `OperandRef`, which makes for tighter LLVM
82 /// IR. The conditions for using an `OperandRef` are as follows:
84 /// - the type of the local must be judged "immediate" by `is_llvm_immediate`
85 /// - the operand must never be referenced indirectly
86 /// - we should not take its address using the `&` operator
87 /// - nor should it appear in a place path like `tmp.a`
88 /// - the operand must be defined by an rvalue that can generate immediate
91 /// Avoiding allocs can also be important for certain intrinsics,
93 locals: IndexVec<mir::Local, LocalRef<'tcx, Bx::Value>>,
95 /// All `VarDebugInfo` from the MIR body, partitioned by `Local`.
96 /// This is `None` if no var`#[non_exhaustive]`iable debuginfo/names are needed.
97 per_local_var_debug_info:
98 Option<IndexVec<mir::Local, Vec<PerLocalVarDebugInfo<'tcx, Bx::DIVariable>>>>,
100 /// Caller location propagated if this function has `#[track_caller]`.
101 caller_location: Option<OperandRef<'tcx, Bx::Value>>,
104 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
105 pub fn monomorphize<T>(&self, value: T) -> T
107 T: Copy + TypeFoldable<'tcx>,
109 debug!("monomorphize: self.instance={:?}", self.instance);
110 self.instance.subst_mir_and_normalize_erasing_regions(
112 ty::ParamEnv::reveal_all(),
118 enum LocalRef<'tcx, V> {
119 Place(PlaceRef<'tcx, V>),
120 /// `UnsizedPlace(p)`: `p` itself is a thin pointer (indirect place).
121 /// `*p` is the fat pointer that references the actual unsized place.
122 /// Every time it is initialized, we have to reallocate the place
123 /// and update the fat pointer. That's the reason why it is indirect.
124 UnsizedPlace(PlaceRef<'tcx, V>),
125 Operand(Option<OperandRef<'tcx, V>>),
128 impl<'a, 'tcx, V: CodegenObject> LocalRef<'tcx, V> {
129 fn new_operand<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
131 layout: TyAndLayout<'tcx>,
132 ) -> LocalRef<'tcx, V> {
134 // Zero-size temporaries aren't always initialized, which
135 // doesn't matter because they don't contain data, but
136 // we need something in the operand.
137 LocalRef::Operand(Some(OperandRef::new_zst(bx, layout)))
139 LocalRef::Operand(None)
144 ///////////////////////////////////////////////////////////////////////////
146 #[instrument(level = "debug", skip(cx))]
147 pub fn codegen_mir<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
148 cx: &'a Bx::CodegenCx,
149 instance: Instance<'tcx>,
151 assert!(!instance.substs.needs_infer());
153 let llfn = cx.get_fn(instance);
155 let mir = cx.tcx().instance_mir(instance.def);
157 let fn_abi = cx.fn_abi_of_instance(instance, ty::List::empty());
158 debug!("fn_abi: {:?}", fn_abi);
160 let debug_context = cx.create_function_debug_context(instance, &fn_abi, llfn, &mir);
162 let start_llbb = Bx::append_block(cx, llfn, "start");
163 let mut start_bx = Bx::build(cx, start_llbb);
165 if mir.basic_blocks.iter().any(|bb| bb.is_cleanup) {
166 start_bx.set_personality_fn(cx.eh_personality());
169 let cleanup_kinds = analyze::cleanup_kinds(&mir);
170 let cached_llbbs: IndexVec<mir::BasicBlock, CachedLlbb<Bx::BasicBlock>> =
174 if bb == mir::START_BLOCK { CachedLlbb::Some(start_llbb) } else { CachedLlbb::None }
178 let mut fx = FunctionCx {
184 personality_slot: None,
186 unreachable_block: None,
187 double_unwind_guard: None,
189 landing_pads: IndexVec::from_elem(None, &mir.basic_blocks),
190 funclets: IndexVec::from_fn_n(|_| None, mir.basic_blocks.len()),
191 locals: IndexVec::new(),
193 per_local_var_debug_info: None,
194 caller_location: None,
197 fx.per_local_var_debug_info = fx.compute_per_local_var_debug_info(&mut start_bx);
199 // Evaluate all required consts; codegen later assumes that CTFE will never fail.
200 let mut all_consts_ok = true;
201 for const_ in &mir.required_consts {
202 if let Err(err) = fx.eval_mir_constant(const_) {
203 all_consts_ok = false;
205 // errored or at least linted
206 ErrorHandled::Reported(_) => {}
207 ErrorHandled::TooGeneric => {
208 span_bug!(const_.span, "codegen encountered polymorphic constant: {:?}", err)
214 // We leave the IR in some half-built state here, and rely on this code not even being
215 // submitted to LLVM once an error was raised.
219 let memory_locals = analyze::non_ssa_locals(&fx);
221 // Allocate variable and temp allocas
223 let args = arg_local_refs(&mut start_bx, &mut fx, &memory_locals);
225 let mut allocate_local = |local| {
226 let decl = &mir.local_decls[local];
227 let layout = start_bx.layout_of(fx.monomorphize(decl.ty));
228 assert!(!layout.ty.has_erasable_regions());
230 if local == mir::RETURN_PLACE && fx.fn_abi.ret.is_indirect() {
231 debug!("alloc: {:?} (return place) -> place", local);
232 let llretptr = start_bx.get_param(0);
233 return LocalRef::Place(PlaceRef::new_sized(llretptr, layout));
236 if memory_locals.contains(local) {
237 debug!("alloc: {:?} -> place", local);
238 if layout.is_unsized() {
239 LocalRef::UnsizedPlace(PlaceRef::alloca_unsized_indirect(&mut start_bx, layout))
241 LocalRef::Place(PlaceRef::alloca(&mut start_bx, layout))
244 debug!("alloc: {:?} -> operand", local);
245 LocalRef::new_operand(&mut start_bx, layout)
249 let retptr = allocate_local(mir::RETURN_PLACE);
251 .chain(args.into_iter())
252 .chain(mir.vars_and_temps_iter().map(allocate_local))
256 // Apply debuginfo to the newly allocated locals.
257 fx.debug_introduce_locals(&mut start_bx);
259 // Codegen the body of each block using reverse postorder
260 for (bb, _) in traversal::reverse_postorder(&mir) {
261 fx.codegen_block(bb);
265 /// Produces, for each argument, a `Value` pointing at the
266 /// argument's value. As arguments are places, these are always
268 fn arg_local_refs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
270 fx: &mut FunctionCx<'a, 'tcx, Bx>,
271 memory_locals: &BitSet<mir::Local>,
272 ) -> Vec<LocalRef<'tcx, Bx::Value>> {
275 let mut llarg_idx = fx.fn_abi.ret.is_indirect() as usize;
277 let mut num_untupled = None;
282 .map(|(arg_index, local)| {
283 let arg_decl = &mir.local_decls[local];
285 if Some(local) == mir.spread_arg {
286 // This argument (e.g., the last argument in the "rust-call" ABI)
287 // is a tuple that was spread at the ABI level and now we have
288 // to reconstruct it into a tuple local variable, from multiple
289 // individual LLVM function arguments.
291 let arg_ty = fx.monomorphize(arg_decl.ty);
292 let ty::Tuple(tupled_arg_tys) = arg_ty.kind() else {
293 bug!("spread argument isn't a tuple?!");
296 let place = PlaceRef::alloca(bx, bx.layout_of(arg_ty));
297 for i in 0..tupled_arg_tys.len() {
298 let arg = &fx.fn_abi.args[idx];
300 if let PassMode::Cast(_, true) = arg.mode {
303 let pr_field = place.project_field(bx, i);
304 bx.store_fn_arg(arg, &mut llarg_idx, pr_field);
308 num_untupled.replace(tupled_arg_tys.len()),
309 "Replaced existing num_tupled"
312 return LocalRef::Place(place);
315 if fx.fn_abi.c_variadic && arg_index == fx.fn_abi.args.len() {
316 let arg_ty = fx.monomorphize(arg_decl.ty);
318 let va_list = PlaceRef::alloca(bx, bx.layout_of(arg_ty));
319 bx.va_start(va_list.llval);
321 return LocalRef::Place(va_list);
324 let arg = &fx.fn_abi.args[idx];
326 if let PassMode::Cast(_, true) = arg.mode {
330 if !memory_locals.contains(local) {
331 // We don't have to cast or keep the argument in the alloca.
332 // FIXME(eddyb): We should figure out how to use llvm.dbg.value instead
333 // of putting everything in allocas just so we can use llvm.dbg.declare.
334 let local = |op| LocalRef::Operand(Some(op));
336 PassMode::Ignore => {
337 return local(OperandRef::new_zst(bx, arg.layout));
339 PassMode::Direct(_) => {
340 let llarg = bx.get_param(llarg_idx);
342 return local(OperandRef::from_immediate_or_packed_pair(
343 bx, llarg, arg.layout,
346 PassMode::Pair(..) => {
347 let (a, b) = (bx.get_param(llarg_idx), bx.get_param(llarg_idx + 1));
350 return local(OperandRef {
351 val: OperandValue::Pair(a, b),
359 if arg.is_sized_indirect() {
360 // Don't copy an indirect argument to an alloca, the caller
361 // already put it in a temporary alloca and gave it up.
363 let llarg = bx.get_param(llarg_idx);
365 LocalRef::Place(PlaceRef::new_sized(llarg, arg.layout))
366 } else if arg.is_unsized_indirect() {
367 // As the storage for the indirect argument lives during
368 // the whole function call, we just copy the fat pointer.
369 let llarg = bx.get_param(llarg_idx);
371 let llextra = bx.get_param(llarg_idx);
373 let indirect_operand = OperandValue::Pair(llarg, llextra);
375 let tmp = PlaceRef::alloca_unsized_indirect(bx, arg.layout);
376 indirect_operand.store(bx, tmp);
377 LocalRef::UnsizedPlace(tmp)
379 let tmp = PlaceRef::alloca(bx, arg.layout);
380 bx.store_fn_arg(arg, &mut llarg_idx, tmp);
384 .collect::<Vec<_>>();
386 if fx.instance.def.requires_caller_location(bx.tcx()) {
387 let mir_args = if let Some(num_untupled) = num_untupled {
388 // Subtract off the tupled argument that gets 'expanded'
389 args.len() - 1 + num_untupled
394 fx.fn_abi.args.len(),
396 "#[track_caller] instance {:?} must have 1 more argument in their ABI than in their MIR",
400 let arg = fx.fn_abi.args.last().unwrap();
402 PassMode::Direct(_) => (),
403 _ => bug!("caller location must be PassMode::Direct, found {:?}", arg.mode),
406 fx.caller_location = Some(OperandRef {
407 val: OperandValue::Immediate(bx.get_param(llarg_idx)),
418 pub mod coverageinfo;