]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_ssa/src/mir/mod.rs
Merge commit 'b7f3f7f6082679da2da9a0b3faf1b5adef3afd3b' into clippyup
[rust.git] / compiler / rustc_codegen_ssa / src / mir / mod.rs
1 use crate::traits::*;
2 use rustc_errors::ErrorReported;
3 use rustc_middle::mir;
4 use rustc_middle::mir::interpret::ErrorHandled;
5 use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, TyAndLayout};
6 use rustc_middle::ty::{self, Instance, Ty, TypeFoldable};
7 use rustc_target::abi::call::{FnAbi, PassMode};
8
9 use std::iter;
10
11 use rustc_index::bit_set::BitSet;
12 use rustc_index::vec::IndexVec;
13
14 use self::debuginfo::{FunctionDebugContext, PerLocalVarDebugInfo};
15 use self::place::PlaceRef;
16 use rustc_middle::mir::traversal;
17
18 use self::operand::{OperandRef, OperandValue};
19
20 /// Master context for codegenning from MIR.
21 pub struct FunctionCx<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> {
22     instance: Instance<'tcx>,
23
24     mir: &'tcx mir::Body<'tcx>,
25
26     debug_context: Option<FunctionDebugContext<Bx::DIScope, Bx::DILocation>>,
27
28     llfn: Bx::Function,
29
30     cx: &'a Bx::CodegenCx,
31
32     fn_abi: &'tcx FnAbi<'tcx, Ty<'tcx>>,
33
34     /// When unwinding is initiated, we have to store this personality
35     /// value somewhere so that we can load it and re-use it in the
36     /// resume instruction. The personality is (afaik) some kind of
37     /// value used for C++ unwinding, which must filter by type: we
38     /// don't really care about it very much. Anyway, this value
39     /// contains an alloca into which the personality is stored and
40     /// then later loaded when generating the DIVERGE_BLOCK.
41     personality_slot: Option<PlaceRef<'tcx, Bx::Value>>,
42
43     /// A backend `BasicBlock` for each MIR `BasicBlock`, created lazily
44     /// as-needed (e.g. RPO reaching it or another block branching to it).
45     // FIXME(eddyb) rename `llbbs` and other `ll`-prefixed things to use a
46     // more backend-agnostic prefix such as `cg` (i.e. this would be `cgbbs`).
47     cached_llbbs: IndexVec<mir::BasicBlock, Option<Bx::BasicBlock>>,
48
49     /// The funclet status of each basic block
50     cleanup_kinds: IndexVec<mir::BasicBlock, analyze::CleanupKind>,
51
52     /// When targeting MSVC, this stores the cleanup info for each funclet BB.
53     /// This is initialized at the same time as the `landing_pads` entry for the
54     /// funclets' head block, i.e. when needed by an unwind / `cleanup_ret` edge.
55     funclets: IndexVec<mir::BasicBlock, Option<Bx::Funclet>>,
56
57     /// This stores the cached landing/cleanup pad block for a given BB.
58     // FIXME(eddyb) rename this to `eh_pads`.
59     landing_pads: IndexVec<mir::BasicBlock, Option<Bx::BasicBlock>>,
60
61     /// Cached unreachable block
62     unreachable_block: Option<Bx::BasicBlock>,
63
64     /// The location where each MIR arg/var/tmp/ret is stored. This is
65     /// usually an `PlaceRef` representing an alloca, but not always:
66     /// sometimes we can skip the alloca and just store the value
67     /// directly using an `OperandRef`, which makes for tighter LLVM
68     /// IR. The conditions for using an `OperandRef` are as follows:
69     ///
70     /// - the type of the local must be judged "immediate" by `is_llvm_immediate`
71     /// - the operand must never be referenced indirectly
72     ///     - we should not take its address using the `&` operator
73     ///     - nor should it appear in a place path like `tmp.a`
74     /// - the operand must be defined by an rvalue that can generate immediate
75     ///   values
76     ///
77     /// Avoiding allocs can also be important for certain intrinsics,
78     /// notably `expect`.
79     locals: IndexVec<mir::Local, LocalRef<'tcx, Bx::Value>>,
80
81     /// All `VarDebugInfo` from the MIR body, partitioned by `Local`.
82     /// This is `None` if no var`#[non_exhaustive]`iable debuginfo/names are needed.
83     per_local_var_debug_info:
84         Option<IndexVec<mir::Local, Vec<PerLocalVarDebugInfo<'tcx, Bx::DIVariable>>>>,
85
86     /// Caller location propagated if this function has `#[track_caller]`.
87     caller_location: Option<OperandRef<'tcx, Bx::Value>>,
88 }
89
90 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
91     pub fn monomorphize<T>(&self, value: T) -> T
92     where
93         T: Copy + TypeFoldable<'tcx>,
94     {
95         debug!("monomorphize: self.instance={:?}", self.instance);
96         self.instance.subst_mir_and_normalize_erasing_regions(
97             self.cx.tcx(),
98             ty::ParamEnv::reveal_all(),
99             value,
100         )
101     }
102 }
103
104 enum LocalRef<'tcx, V> {
105     Place(PlaceRef<'tcx, V>),
106     /// `UnsizedPlace(p)`: `p` itself is a thin pointer (indirect place).
107     /// `*p` is the fat pointer that references the actual unsized place.
108     /// Every time it is initialized, we have to reallocate the place
109     /// and update the fat pointer. That's the reason why it is indirect.
110     UnsizedPlace(PlaceRef<'tcx, V>),
111     Operand(Option<OperandRef<'tcx, V>>),
112 }
113
114 impl<'a, 'tcx, V: CodegenObject> LocalRef<'tcx, V> {
115     fn new_operand<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
116         bx: &mut Bx,
117         layout: TyAndLayout<'tcx>,
118     ) -> LocalRef<'tcx, V> {
119         if layout.is_zst() {
120             // Zero-size temporaries aren't always initialized, which
121             // doesn't matter because they don't contain data, but
122             // we need something in the operand.
123             LocalRef::Operand(Some(OperandRef::new_zst(bx, layout)))
124         } else {
125             LocalRef::Operand(None)
126         }
127     }
128 }
129
130 ///////////////////////////////////////////////////////////////////////////
131
132 #[instrument(level = "debug", skip(cx))]
133 pub fn codegen_mir<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
134     cx: &'a Bx::CodegenCx,
135     instance: Instance<'tcx>,
136 ) {
137     assert!(!instance.substs.needs_infer());
138
139     let llfn = cx.get_fn(instance);
140
141     let mir = cx.tcx().instance_mir(instance.def);
142
143     let fn_abi = cx.fn_abi_of_instance(instance, ty::List::empty());
144     debug!("fn_abi: {:?}", fn_abi);
145
146     let debug_context = cx.create_function_debug_context(instance, &fn_abi, llfn, &mir);
147
148     let start_llbb = Bx::append_block(cx, llfn, "start");
149     let mut bx = Bx::build(cx, start_llbb);
150
151     if mir.basic_blocks().iter().any(|bb| bb.is_cleanup) {
152         bx.set_personality_fn(cx.eh_personality());
153     }
154
155     let cleanup_kinds = analyze::cleanup_kinds(&mir);
156     let cached_llbbs: IndexVec<mir::BasicBlock, Option<Bx::BasicBlock>> = mir
157         .basic_blocks()
158         .indices()
159         .map(|bb| if bb == mir::START_BLOCK { Some(start_llbb) } else { None })
160         .collect();
161
162     let mut fx = FunctionCx {
163         instance,
164         mir,
165         llfn,
166         fn_abi,
167         cx,
168         personality_slot: None,
169         cached_llbbs,
170         unreachable_block: None,
171         cleanup_kinds,
172         landing_pads: IndexVec::from_elem(None, mir.basic_blocks()),
173         funclets: IndexVec::from_fn_n(|_| None, mir.basic_blocks().len()),
174         locals: IndexVec::new(),
175         debug_context,
176         per_local_var_debug_info: None,
177         caller_location: None,
178     };
179
180     fx.per_local_var_debug_info = fx.compute_per_local_var_debug_info(&mut bx);
181
182     // Evaluate all required consts; codegen later assumes that CTFE will never fail.
183     let mut all_consts_ok = true;
184     for const_ in &mir.required_consts {
185         if let Err(err) = fx.eval_mir_constant(const_) {
186             all_consts_ok = false;
187             match err {
188                 // errored or at least linted
189                 ErrorHandled::Reported(ErrorReported) | ErrorHandled::Linted => {}
190                 ErrorHandled::TooGeneric => {
191                     span_bug!(const_.span, "codgen encountered polymorphic constant: {:?}", err)
192                 }
193             }
194         }
195     }
196     if !all_consts_ok {
197         // We leave the IR in some half-built state here, and rely on this code not even being
198         // submitted to LLVM once an error was raised.
199         return;
200     }
201
202     let memory_locals = analyze::non_ssa_locals(&fx);
203
204     // Allocate variable and temp allocas
205     fx.locals = {
206         let args = arg_local_refs(&mut bx, &mut fx, &memory_locals);
207
208         let mut allocate_local = |local| {
209             let decl = &mir.local_decls[local];
210             let layout = bx.layout_of(fx.monomorphize(decl.ty));
211             assert!(!layout.ty.has_erasable_regions(cx.tcx()));
212
213             if local == mir::RETURN_PLACE && fx.fn_abi.ret.is_indirect() {
214                 debug!("alloc: {:?} (return place) -> place", local);
215                 let llretptr = bx.get_param(0);
216                 return LocalRef::Place(PlaceRef::new_sized(llretptr, layout));
217             }
218
219             if memory_locals.contains(local) {
220                 debug!("alloc: {:?} -> place", local);
221                 if layout.is_unsized() {
222                     LocalRef::UnsizedPlace(PlaceRef::alloca_unsized_indirect(&mut bx, layout))
223                 } else {
224                     LocalRef::Place(PlaceRef::alloca(&mut bx, layout))
225                 }
226             } else {
227                 debug!("alloc: {:?} -> operand", local);
228                 LocalRef::new_operand(&mut bx, layout)
229             }
230         };
231
232         let retptr = allocate_local(mir::RETURN_PLACE);
233         iter::once(retptr)
234             .chain(args.into_iter())
235             .chain(mir.vars_and_temps_iter().map(allocate_local))
236             .collect()
237     };
238
239     // Apply debuginfo to the newly allocated locals.
240     fx.debug_introduce_locals(&mut bx);
241
242     // Codegen the body of each block using reverse postorder
243     // FIXME(eddyb) reuse RPO iterator between `analysis` and this.
244     for (bb, _) in traversal::reverse_postorder(&mir) {
245         fx.codegen_block(bb);
246     }
247 }
248
249 /// Produces, for each argument, a `Value` pointing at the
250 /// argument's value. As arguments are places, these are always
251 /// indirect.
252 fn arg_local_refs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
253     bx: &mut Bx,
254     fx: &mut FunctionCx<'a, 'tcx, Bx>,
255     memory_locals: &BitSet<mir::Local>,
256 ) -> Vec<LocalRef<'tcx, Bx::Value>> {
257     let mir = fx.mir;
258     let mut idx = 0;
259     let mut llarg_idx = fx.fn_abi.ret.is_indirect() as usize;
260
261     let mut num_untupled = None;
262
263     let args = mir
264         .args_iter()
265         .enumerate()
266         .map(|(arg_index, local)| {
267             let arg_decl = &mir.local_decls[local];
268
269             if Some(local) == mir.spread_arg {
270                 // This argument (e.g., the last argument in the "rust-call" ABI)
271                 // is a tuple that was spread at the ABI level and now we have
272                 // to reconstruct it into a tuple local variable, from multiple
273                 // individual LLVM function arguments.
274
275                 let arg_ty = fx.monomorphize(arg_decl.ty);
276                 let tupled_arg_tys = match arg_ty.kind() {
277                     ty::Tuple(tys) => tys,
278                     _ => bug!("spread argument isn't a tuple?!"),
279                 };
280
281                 let place = PlaceRef::alloca(bx, bx.layout_of(arg_ty));
282                 for i in 0..tupled_arg_tys.len() {
283                     let arg = &fx.fn_abi.args[idx];
284                     idx += 1;
285                     if arg.pad.is_some() {
286                         llarg_idx += 1;
287                     }
288                     let pr_field = place.project_field(bx, i);
289                     bx.store_fn_arg(arg, &mut llarg_idx, pr_field);
290                 }
291                 assert_eq!(
292                     None,
293                     num_untupled.replace(tupled_arg_tys.len()),
294                     "Replaced existing num_tupled"
295                 );
296
297                 return LocalRef::Place(place);
298             }
299
300             if fx.fn_abi.c_variadic && arg_index == fx.fn_abi.args.len() {
301                 let arg_ty = fx.monomorphize(arg_decl.ty);
302
303                 let va_list = PlaceRef::alloca(bx, bx.layout_of(arg_ty));
304                 bx.va_start(va_list.llval);
305
306                 return LocalRef::Place(va_list);
307             }
308
309             let arg = &fx.fn_abi.args[idx];
310             idx += 1;
311             if arg.pad.is_some() {
312                 llarg_idx += 1;
313             }
314
315             if !memory_locals.contains(local) {
316                 // We don't have to cast or keep the argument in the alloca.
317                 // FIXME(eddyb): We should figure out how to use llvm.dbg.value instead
318                 // of putting everything in allocas just so we can use llvm.dbg.declare.
319                 let local = |op| LocalRef::Operand(Some(op));
320                 match arg.mode {
321                     PassMode::Ignore => {
322                         return local(OperandRef::new_zst(bx, arg.layout));
323                     }
324                     PassMode::Direct(_) => {
325                         let llarg = bx.get_param(llarg_idx);
326                         llarg_idx += 1;
327                         return local(OperandRef::from_immediate_or_packed_pair(
328                             bx, llarg, arg.layout,
329                         ));
330                     }
331                     PassMode::Pair(..) => {
332                         let (a, b) = (bx.get_param(llarg_idx), bx.get_param(llarg_idx + 1));
333                         llarg_idx += 2;
334
335                         return local(OperandRef {
336                             val: OperandValue::Pair(a, b),
337                             layout: arg.layout,
338                         });
339                     }
340                     _ => {}
341                 }
342             }
343
344             if arg.is_sized_indirect() {
345                 // Don't copy an indirect argument to an alloca, the caller
346                 // already put it in a temporary alloca and gave it up.
347                 // FIXME: lifetimes
348                 let llarg = bx.get_param(llarg_idx);
349                 llarg_idx += 1;
350                 LocalRef::Place(PlaceRef::new_sized(llarg, arg.layout))
351             } else if arg.is_unsized_indirect() {
352                 // As the storage for the indirect argument lives during
353                 // the whole function call, we just copy the fat pointer.
354                 let llarg = bx.get_param(llarg_idx);
355                 llarg_idx += 1;
356                 let llextra = bx.get_param(llarg_idx);
357                 llarg_idx += 1;
358                 let indirect_operand = OperandValue::Pair(llarg, llextra);
359
360                 let tmp = PlaceRef::alloca_unsized_indirect(bx, arg.layout);
361                 indirect_operand.store(bx, tmp);
362                 LocalRef::UnsizedPlace(tmp)
363             } else {
364                 let tmp = PlaceRef::alloca(bx, arg.layout);
365                 bx.store_fn_arg(arg, &mut llarg_idx, tmp);
366                 LocalRef::Place(tmp)
367             }
368         })
369         .collect::<Vec<_>>();
370
371     if fx.instance.def.requires_caller_location(bx.tcx()) {
372         let mir_args = if let Some(num_untupled) = num_untupled {
373             // Subtract off the tupled argument that gets 'expanded'
374             args.len() - 1 + num_untupled
375         } else {
376             args.len()
377         };
378         assert_eq!(
379             fx.fn_abi.args.len(),
380             mir_args + 1,
381             "#[track_caller] instance {:?} must have 1 more argument in their ABI than in their MIR",
382             fx.instance
383         );
384
385         let arg = fx.fn_abi.args.last().unwrap();
386         match arg.mode {
387             PassMode::Direct(_) => (),
388             _ => bug!("caller location must be PassMode::Direct, found {:?}", arg.mode),
389         }
390
391         fx.caller_location = Some(OperandRef {
392             val: OperandValue::Immediate(bx.get_param(llarg_idx)),
393             layout: arg.layout,
394         });
395     }
396
397     args
398 }
399
400 mod analyze;
401 mod block;
402 pub mod constant;
403 pub mod coverageinfo;
404 pub mod debuginfo;
405 mod intrinsic;
406 pub mod operand;
407 pub mod place;
408 mod rvalue;
409 mod statement;