]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_ssa/src/mir/mod.rs
Rollup merge of #106153 - GuillaumeGomez:search-tabs-headers, r=notriddle
[rust.git] / compiler / rustc_codegen_ssa / src / mir / mod.rs
1 use crate::traits::*;
2 use rustc_middle::mir;
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};
7
8 use std::iter;
9
10 use rustc_index::bit_set::BitSet;
11 use rustc_index::vec::IndexVec;
12
13 use self::debuginfo::{FunctionDebugContext, PerLocalVarDebugInfo};
14 use self::place::PlaceRef;
15 use rustc_middle::mir::traversal;
16
17 use self::operand::{OperandRef, OperandValue};
18
19 // Used for tracking the state of generated basic blocks.
20 enum CachedLlbb<T> {
21     /// Nothing created yet.
22     None,
23
24     /// Has been created.
25     Some(T),
26
27     /// Nothing created yet, and nothing should be.
28     Skip,
29 }
30
31 /// Master context for codegenning from MIR.
32 pub struct FunctionCx<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> {
33     instance: Instance<'tcx>,
34
35     mir: &'tcx mir::Body<'tcx>,
36
37     debug_context: Option<FunctionDebugContext<Bx::DIScope, Bx::DILocation>>,
38
39     llfn: Bx::Function,
40
41     cx: &'a Bx::CodegenCx,
42
43     fn_abi: &'tcx FnAbi<'tcx, Ty<'tcx>>,
44
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>>,
53
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>>,
59
60     /// The funclet status of each basic block
61     cleanup_kinds: IndexVec<mir::BasicBlock, analyze::CleanupKind>,
62
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>>,
67
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>>,
71
72     /// Cached unreachable block
73     unreachable_block: Option<Bx::BasicBlock>,
74
75     /// Cached double unwind guarding block
76     double_unwind_guard: Option<Bx::BasicBlock>,
77
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:
83     ///
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
89     ///   values
90     ///
91     /// Avoiding allocs can also be important for certain intrinsics,
92     /// notably `expect`.
93     locals: IndexVec<mir::Local, LocalRef<'tcx, Bx::Value>>,
94
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>>>>,
99
100     /// Caller location propagated if this function has `#[track_caller]`.
101     caller_location: Option<OperandRef<'tcx, Bx::Value>>,
102 }
103
104 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
105     pub fn monomorphize<T>(&self, value: T) -> T
106     where
107         T: Copy + TypeFoldable<'tcx>,
108     {
109         debug!("monomorphize: self.instance={:?}", self.instance);
110         self.instance.subst_mir_and_normalize_erasing_regions(
111             self.cx.tcx(),
112             ty::ParamEnv::reveal_all(),
113             value,
114         )
115     }
116 }
117
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>>),
126 }
127
128 impl<'a, 'tcx, V: CodegenObject> LocalRef<'tcx, V> {
129     fn new_operand<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
130         bx: &mut Bx,
131         layout: TyAndLayout<'tcx>,
132     ) -> LocalRef<'tcx, V> {
133         if layout.is_zst() {
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)))
138         } else {
139             LocalRef::Operand(None)
140         }
141     }
142 }
143
144 ///////////////////////////////////////////////////////////////////////////
145
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>,
150 ) {
151     assert!(!instance.substs.needs_infer());
152
153     let llfn = cx.get_fn(instance);
154
155     let mir = cx.tcx().instance_mir(instance.def);
156
157     let fn_abi = cx.fn_abi_of_instance(instance, ty::List::empty());
158     debug!("fn_abi: {:?}", fn_abi);
159
160     let debug_context = cx.create_function_debug_context(instance, &fn_abi, llfn, &mir);
161
162     let start_llbb = Bx::append_block(cx, llfn, "start");
163     let mut start_bx = Bx::build(cx, start_llbb);
164
165     if mir.basic_blocks.iter().any(|bb| bb.is_cleanup) {
166         start_bx.set_personality_fn(cx.eh_personality());
167     }
168
169     let cleanup_kinds = analyze::cleanup_kinds(&mir);
170     let cached_llbbs: IndexVec<mir::BasicBlock, CachedLlbb<Bx::BasicBlock>> =
171         mir.basic_blocks
172             .indices()
173             .map(|bb| {
174                 if bb == mir::START_BLOCK { CachedLlbb::Some(start_llbb) } else { CachedLlbb::None }
175             })
176             .collect();
177
178     let mut fx = FunctionCx {
179         instance,
180         mir,
181         llfn,
182         fn_abi,
183         cx,
184         personality_slot: None,
185         cached_llbbs,
186         unreachable_block: None,
187         double_unwind_guard: None,
188         cleanup_kinds,
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(),
192         debug_context,
193         per_local_var_debug_info: None,
194         caller_location: None,
195     };
196
197     fx.per_local_var_debug_info = fx.compute_per_local_var_debug_info(&mut start_bx);
198
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;
204             match err {
205                 // errored or at least linted
206                 ErrorHandled::Reported(_) => {}
207                 ErrorHandled::TooGeneric => {
208                     span_bug!(const_.span, "codegen encountered polymorphic constant: {:?}", err)
209                 }
210             }
211         }
212     }
213     if !all_consts_ok {
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.
216         return;
217     }
218
219     let memory_locals = analyze::non_ssa_locals(&fx);
220
221     // Allocate variable and temp allocas
222     fx.locals = {
223         let args = arg_local_refs(&mut start_bx, &mut fx, &memory_locals);
224
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());
229
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));
234             }
235
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))
240                 } else {
241                     LocalRef::Place(PlaceRef::alloca(&mut start_bx, layout))
242                 }
243             } else {
244                 debug!("alloc: {:?} -> operand", local);
245                 LocalRef::new_operand(&mut start_bx, layout)
246             }
247         };
248
249         let retptr = allocate_local(mir::RETURN_PLACE);
250         iter::once(retptr)
251             .chain(args.into_iter())
252             .chain(mir.vars_and_temps_iter().map(allocate_local))
253             .collect()
254     };
255
256     // Apply debuginfo to the newly allocated locals.
257     fx.debug_introduce_locals(&mut start_bx);
258
259     // Codegen the body of each block using reverse postorder
260     for (bb, _) in traversal::reverse_postorder(&mir) {
261         fx.codegen_block(bb);
262     }
263 }
264
265 /// Produces, for each argument, a `Value` pointing at the
266 /// argument's value. As arguments are places, these are always
267 /// indirect.
268 fn arg_local_refs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
269     bx: &mut Bx,
270     fx: &mut FunctionCx<'a, 'tcx, Bx>,
271     memory_locals: &BitSet<mir::Local>,
272 ) -> Vec<LocalRef<'tcx, Bx::Value>> {
273     let mir = fx.mir;
274     let mut idx = 0;
275     let mut llarg_idx = fx.fn_abi.ret.is_indirect() as usize;
276
277     let mut num_untupled = None;
278
279     let args = mir
280         .args_iter()
281         .enumerate()
282         .map(|(arg_index, local)| {
283             let arg_decl = &mir.local_decls[local];
284
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.
290
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?!");
294                 };
295
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];
299                     idx += 1;
300                     if let PassMode::Cast(_, true) = arg.mode {
301                         llarg_idx += 1;
302                     }
303                     let pr_field = place.project_field(bx, i);
304                     bx.store_fn_arg(arg, &mut llarg_idx, pr_field);
305                 }
306                 assert_eq!(
307                     None,
308                     num_untupled.replace(tupled_arg_tys.len()),
309                     "Replaced existing num_tupled"
310                 );
311
312                 return LocalRef::Place(place);
313             }
314
315             if fx.fn_abi.c_variadic && arg_index == fx.fn_abi.args.len() {
316                 let arg_ty = fx.monomorphize(arg_decl.ty);
317
318                 let va_list = PlaceRef::alloca(bx, bx.layout_of(arg_ty));
319                 bx.va_start(va_list.llval);
320
321                 return LocalRef::Place(va_list);
322             }
323
324             let arg = &fx.fn_abi.args[idx];
325             idx += 1;
326             if let PassMode::Cast(_, true) = arg.mode {
327                 llarg_idx += 1;
328             }
329
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));
335                 match arg.mode {
336                     PassMode::Ignore => {
337                         return local(OperandRef::new_zst(bx, arg.layout));
338                     }
339                     PassMode::Direct(_) => {
340                         let llarg = bx.get_param(llarg_idx);
341                         llarg_idx += 1;
342                         return local(OperandRef::from_immediate_or_packed_pair(
343                             bx, llarg, arg.layout,
344                         ));
345                     }
346                     PassMode::Pair(..) => {
347                         let (a, b) = (bx.get_param(llarg_idx), bx.get_param(llarg_idx + 1));
348                         llarg_idx += 2;
349
350                         return local(OperandRef {
351                             val: OperandValue::Pair(a, b),
352                             layout: arg.layout,
353                         });
354                     }
355                     _ => {}
356                 }
357             }
358
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.
362                 // FIXME: lifetimes
363                 let llarg = bx.get_param(llarg_idx);
364                 llarg_idx += 1;
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);
370                 llarg_idx += 1;
371                 let llextra = bx.get_param(llarg_idx);
372                 llarg_idx += 1;
373                 let indirect_operand = OperandValue::Pair(llarg, llextra);
374
375                 let tmp = PlaceRef::alloca_unsized_indirect(bx, arg.layout);
376                 indirect_operand.store(bx, tmp);
377                 LocalRef::UnsizedPlace(tmp)
378             } else {
379                 let tmp = PlaceRef::alloca(bx, arg.layout);
380                 bx.store_fn_arg(arg, &mut llarg_idx, tmp);
381                 LocalRef::Place(tmp)
382             }
383         })
384         .collect::<Vec<_>>();
385
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
390         } else {
391             args.len()
392         };
393         assert_eq!(
394             fx.fn_abi.args.len(),
395             mir_args + 1,
396             "#[track_caller] instance {:?} must have 1 more argument in their ABI than in their MIR",
397             fx.instance
398         );
399
400         let arg = fx.fn_abi.args.last().unwrap();
401         match arg.mode {
402             PassMode::Direct(_) => (),
403             _ => bug!("caller location must be PassMode::Direct, found {:?}", arg.mode),
404         }
405
406         fx.caller_location = Some(OperandRef {
407             val: OperandValue::Immediate(bx.get_param(llarg_idx)),
408             layout: arg.layout,
409         });
410     }
411
412     args
413 }
414
415 mod analyze;
416 mod block;
417 pub mod constant;
418 pub mod coverageinfo;
419 pub mod debuginfo;
420 mod intrinsic;
421 pub mod operand;
422 pub mod place;
423 mod rvalue;
424 mod statement;