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 /// Master context for codegenning from MIR.
20 pub struct FunctionCx<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> {
21 instance: Instance<'tcx>,
23 mir: &'tcx mir::Body<'tcx>,
25 debug_context: Option<FunctionDebugContext<Bx::DIScope, Bx::DILocation>>,
29 cx: &'a Bx::CodegenCx,
31 fn_abi: &'tcx FnAbi<'tcx, Ty<'tcx>>,
33 /// When unwinding is initiated, we have to store this personality
34 /// value somewhere so that we can load it and re-use it in the
35 /// resume instruction. The personality is (afaik) some kind of
36 /// value used for C++ unwinding, which must filter by type: we
37 /// don't really care about it very much. Anyway, this value
38 /// contains an alloca into which the personality is stored and
39 /// then later loaded when generating the DIVERGE_BLOCK.
40 personality_slot: Option<PlaceRef<'tcx, Bx::Value>>,
42 /// A backend `BasicBlock` for each MIR `BasicBlock`, created lazily
43 /// as-needed (e.g. RPO reaching it or another block branching to it).
44 // FIXME(eddyb) rename `llbbs` and other `ll`-prefixed things to use a
45 // more backend-agnostic prefix such as `cg` (i.e. this would be `cgbbs`).
46 cached_llbbs: IndexVec<mir::BasicBlock, Option<Bx::BasicBlock>>,
48 /// The funclet status of each basic block
49 cleanup_kinds: IndexVec<mir::BasicBlock, analyze::CleanupKind>,
51 /// When targeting MSVC, this stores the cleanup info for each funclet BB.
52 /// This is initialized at the same time as the `landing_pads` entry for the
53 /// funclets' head block, i.e. when needed by an unwind / `cleanup_ret` edge.
54 funclets: IndexVec<mir::BasicBlock, Option<Bx::Funclet>>,
56 /// This stores the cached landing/cleanup pad block for a given BB.
57 // FIXME(eddyb) rename this to `eh_pads`.
58 landing_pads: IndexVec<mir::BasicBlock, Option<Bx::BasicBlock>>,
60 /// Cached unreachable block
61 unreachable_block: Option<Bx::BasicBlock>,
63 /// Cached double unwind guarding block
64 double_unwind_guard: Option<Bx::BasicBlock>,
66 /// The location where each MIR arg/var/tmp/ret is stored. This is
67 /// usually an `PlaceRef` representing an alloca, but not always:
68 /// sometimes we can skip the alloca and just store the value
69 /// directly using an `OperandRef`, which makes for tighter LLVM
70 /// IR. The conditions for using an `OperandRef` are as follows:
72 /// - the type of the local must be judged "immediate" by `is_llvm_immediate`
73 /// - the operand must never be referenced indirectly
74 /// - we should not take its address using the `&` operator
75 /// - nor should it appear in a place path like `tmp.a`
76 /// - the operand must be defined by an rvalue that can generate immediate
79 /// Avoiding allocs can also be important for certain intrinsics,
81 locals: IndexVec<mir::Local, LocalRef<'tcx, Bx::Value>>,
83 /// All `VarDebugInfo` from the MIR body, partitioned by `Local`.
84 /// This is `None` if no var`#[non_exhaustive]`iable debuginfo/names are needed.
85 per_local_var_debug_info:
86 Option<IndexVec<mir::Local, Vec<PerLocalVarDebugInfo<'tcx, Bx::DIVariable>>>>,
88 /// Caller location propagated if this function has `#[track_caller]`.
89 caller_location: Option<OperandRef<'tcx, Bx::Value>>,
92 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
93 pub fn monomorphize<T>(&self, value: T) -> T
95 T: Copy + TypeFoldable<'tcx>,
97 debug!("monomorphize: self.instance={:?}", self.instance);
98 self.instance.subst_mir_and_normalize_erasing_regions(
100 ty::ParamEnv::reveal_all(),
106 enum LocalRef<'tcx, V> {
107 Place(PlaceRef<'tcx, V>),
108 /// `UnsizedPlace(p)`: `p` itself is a thin pointer (indirect place).
109 /// `*p` is the fat pointer that references the actual unsized place.
110 /// Every time it is initialized, we have to reallocate the place
111 /// and update the fat pointer. That's the reason why it is indirect.
112 UnsizedPlace(PlaceRef<'tcx, V>),
113 Operand(Option<OperandRef<'tcx, V>>),
116 impl<'a, 'tcx, V: CodegenObject> LocalRef<'tcx, V> {
117 fn new_operand<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
119 layout: TyAndLayout<'tcx>,
120 ) -> LocalRef<'tcx, V> {
122 // Zero-size temporaries aren't always initialized, which
123 // doesn't matter because they don't contain data, but
124 // we need something in the operand.
125 LocalRef::Operand(Some(OperandRef::new_zst(bx, layout)))
127 LocalRef::Operand(None)
132 ///////////////////////////////////////////////////////////////////////////
134 #[instrument(level = "debug", skip(cx))]
135 pub fn codegen_mir<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
136 cx: &'a Bx::CodegenCx,
137 instance: Instance<'tcx>,
139 assert!(!instance.substs.needs_infer());
141 let llfn = cx.get_fn(instance);
143 let mir = cx.tcx().instance_mir(instance.def);
145 let fn_abi = cx.fn_abi_of_instance(instance, ty::List::empty());
146 debug!("fn_abi: {:?}", fn_abi);
148 let debug_context = cx.create_function_debug_context(instance, &fn_abi, llfn, &mir);
150 let start_llbb = Bx::append_block(cx, llfn, "start");
151 let mut bx = Bx::build(cx, start_llbb);
153 if mir.basic_blocks.iter().any(|bb| bb.is_cleanup) {
154 bx.set_personality_fn(cx.eh_personality());
157 let cleanup_kinds = analyze::cleanup_kinds(&mir);
158 let cached_llbbs: IndexVec<mir::BasicBlock, Option<Bx::BasicBlock>> = mir
161 .map(|bb| if bb == mir::START_BLOCK { Some(start_llbb) } else { None })
164 let mut fx = FunctionCx {
170 personality_slot: None,
172 unreachable_block: None,
173 double_unwind_guard: None,
175 landing_pads: IndexVec::from_elem(None, &mir.basic_blocks),
176 funclets: IndexVec::from_fn_n(|_| None, mir.basic_blocks.len()),
177 locals: IndexVec::new(),
179 per_local_var_debug_info: None,
180 caller_location: None,
183 fx.per_local_var_debug_info = fx.compute_per_local_var_debug_info(&mut bx);
185 // Evaluate all required consts; codegen later assumes that CTFE will never fail.
186 let mut all_consts_ok = true;
187 for const_ in &mir.required_consts {
188 if let Err(err) = fx.eval_mir_constant(const_) {
189 all_consts_ok = false;
191 // errored or at least linted
192 ErrorHandled::Reported(_) | ErrorHandled::Linted => {}
193 ErrorHandled::TooGeneric => {
194 span_bug!(const_.span, "codegen encountered polymorphic constant: {:?}", err)
200 // We leave the IR in some half-built state here, and rely on this code not even being
201 // submitted to LLVM once an error was raised.
205 let memory_locals = analyze::non_ssa_locals(&fx);
207 // Allocate variable and temp allocas
209 let args = arg_local_refs(&mut bx, &mut fx, &memory_locals);
211 let mut allocate_local = |local| {
212 let decl = &mir.local_decls[local];
213 let layout = bx.layout_of(fx.monomorphize(decl.ty));
214 assert!(!layout.ty.has_erasable_regions());
216 if local == mir::RETURN_PLACE && fx.fn_abi.ret.is_indirect() {
217 debug!("alloc: {:?} (return place) -> place", local);
218 let llretptr = bx.get_param(0);
219 return LocalRef::Place(PlaceRef::new_sized(llretptr, layout));
222 if memory_locals.contains(local) {
223 debug!("alloc: {:?} -> place", local);
224 if layout.is_unsized() {
225 LocalRef::UnsizedPlace(PlaceRef::alloca_unsized_indirect(&mut bx, layout))
227 LocalRef::Place(PlaceRef::alloca(&mut bx, layout))
230 debug!("alloc: {:?} -> operand", local);
231 LocalRef::new_operand(&mut bx, layout)
235 let retptr = allocate_local(mir::RETURN_PLACE);
237 .chain(args.into_iter())
238 .chain(mir.vars_and_temps_iter().map(allocate_local))
242 // Apply debuginfo to the newly allocated locals.
243 fx.debug_introduce_locals(&mut bx);
245 // Codegen the body of each block using reverse postorder
246 for (bb, _) in traversal::reverse_postorder(&mir) {
247 fx.codegen_block(bb);
251 /// Produces, for each argument, a `Value` pointing at the
252 /// argument's value. As arguments are places, these are always
254 fn arg_local_refs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
256 fx: &mut FunctionCx<'a, 'tcx, Bx>,
257 memory_locals: &BitSet<mir::Local>,
258 ) -> Vec<LocalRef<'tcx, Bx::Value>> {
261 let mut llarg_idx = fx.fn_abi.ret.is_indirect() as usize;
263 let mut num_untupled = None;
268 .map(|(arg_index, local)| {
269 let arg_decl = &mir.local_decls[local];
271 if Some(local) == mir.spread_arg {
272 // This argument (e.g., the last argument in the "rust-call" ABI)
273 // is a tuple that was spread at the ABI level and now we have
274 // to reconstruct it into a tuple local variable, from multiple
275 // individual LLVM function arguments.
277 let arg_ty = fx.monomorphize(arg_decl.ty);
278 let ty::Tuple(tupled_arg_tys) = arg_ty.kind() else {
279 bug!("spread argument isn't a tuple?!");
282 let place = PlaceRef::alloca(bx, bx.layout_of(arg_ty));
283 for i in 0..tupled_arg_tys.len() {
284 let arg = &fx.fn_abi.args[idx];
286 if let PassMode::Cast(_, true) = arg.mode {
289 let pr_field = place.project_field(bx, i);
290 bx.store_fn_arg(arg, &mut llarg_idx, pr_field);
294 num_untupled.replace(tupled_arg_tys.len()),
295 "Replaced existing num_tupled"
298 return LocalRef::Place(place);
301 if fx.fn_abi.c_variadic && arg_index == fx.fn_abi.args.len() {
302 let arg_ty = fx.monomorphize(arg_decl.ty);
304 let va_list = PlaceRef::alloca(bx, bx.layout_of(arg_ty));
305 bx.va_start(va_list.llval);
307 return LocalRef::Place(va_list);
310 let arg = &fx.fn_abi.args[idx];
312 if let PassMode::Cast(_, true) = arg.mode {
316 if !memory_locals.contains(local) {
317 // We don't have to cast or keep the argument in the alloca.
318 // FIXME(eddyb): We should figure out how to use llvm.dbg.value instead
319 // of putting everything in allocas just so we can use llvm.dbg.declare.
320 let local = |op| LocalRef::Operand(Some(op));
322 PassMode::Ignore => {
323 return local(OperandRef::new_zst(bx, arg.layout));
325 PassMode::Direct(_) => {
326 let llarg = bx.get_param(llarg_idx);
328 return local(OperandRef::from_immediate_or_packed_pair(
329 bx, llarg, arg.layout,
332 PassMode::Pair(..) => {
333 let (a, b) = (bx.get_param(llarg_idx), bx.get_param(llarg_idx + 1));
336 return local(OperandRef {
337 val: OperandValue::Pair(a, b),
345 if arg.is_sized_indirect() {
346 // Don't copy an indirect argument to an alloca, the caller
347 // already put it in a temporary alloca and gave it up.
349 let llarg = bx.get_param(llarg_idx);
351 LocalRef::Place(PlaceRef::new_sized(llarg, arg.layout))
352 } else if arg.is_unsized_indirect() {
353 // As the storage for the indirect argument lives during
354 // the whole function call, we just copy the fat pointer.
355 let llarg = bx.get_param(llarg_idx);
357 let llextra = bx.get_param(llarg_idx);
359 let indirect_operand = OperandValue::Pair(llarg, llextra);
361 let tmp = PlaceRef::alloca_unsized_indirect(bx, arg.layout);
362 indirect_operand.store(bx, tmp);
363 LocalRef::UnsizedPlace(tmp)
365 let tmp = PlaceRef::alloca(bx, arg.layout);
366 bx.store_fn_arg(arg, &mut llarg_idx, tmp);
370 .collect::<Vec<_>>();
372 if fx.instance.def.requires_caller_location(bx.tcx()) {
373 let mir_args = if let Some(num_untupled) = num_untupled {
374 // Subtract off the tupled argument that gets 'expanded'
375 args.len() - 1 + num_untupled
380 fx.fn_abi.args.len(),
382 "#[track_caller] instance {:?} must have 1 more argument in their ABI than in their MIR",
386 let arg = fx.fn_abi.args.last().unwrap();
388 PassMode::Direct(_) => (),
389 _ => bug!("caller location must be PassMode::Direct, found {:?}", arg.mode),
392 fx.caller_location = Some(OperandRef {
393 val: OperandValue::Immediate(bx.get_param(llarg_idx)),
404 pub mod coverageinfo;