]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_ssa/mir/mod.rs
Auto merge of #68975 - Dylan-DPC:rollup-jzab8oh, r=Dylan-DPC
[rust.git] / src / librustc_codegen_ssa / mir / mod.rs
1 use crate::base;
2 use crate::traits::*;
3 use rustc::mir;
4 use rustc::ty::layout::{FnAbiExt, HasTyCtxt, TyLayout};
5 use rustc::ty::{self, Instance, Ty, TypeFoldable};
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::analyze::CleanupKind;
14 use self::debuginfo::{FunctionDebugContext, PerLocalVarDebugInfo};
15 use self::place::PlaceRef;
16 use rustc::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: mir::ReadOnlyBodyAndCache<'tcx, 'tcx>,
25
26     debug_context: Option<FunctionDebugContext<Bx::DIScope>>,
27
28     llfn: Bx::Function,
29
30     cx: &'a Bx::CodegenCx,
31
32     fn_abi: 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 `Block` for each MIR `BasicBlock`
44     blocks: IndexVec<mir::BasicBlock, Bx::BasicBlock>,
45
46     /// The funclet status of each basic block
47     cleanup_kinds: IndexVec<mir::BasicBlock, analyze::CleanupKind>,
48
49     /// When targeting MSVC, this stores the cleanup info for each funclet
50     /// BB. This is initialized as we compute the funclets' head block in RPO.
51     funclets: IndexVec<mir::BasicBlock, Option<Bx::Funclet>>,
52
53     /// This stores the landing-pad block for a given BB, computed lazily on GNU
54     /// and eagerly on MSVC.
55     landing_pads: IndexVec<mir::BasicBlock, Option<Bx::BasicBlock>>,
56
57     /// Cached unreachable block
58     unreachable_block: Option<Bx::BasicBlock>,
59
60     /// The location where each MIR arg/var/tmp/ret is stored. This is
61     /// usually an `PlaceRef` representing an alloca, but not always:
62     /// sometimes we can skip the alloca and just store the value
63     /// directly using an `OperandRef`, which makes for tighter LLVM
64     /// IR. The conditions for using an `OperandRef` are as follows:
65     ///
66     /// - the type of the local must be judged "immediate" by `is_llvm_immediate`
67     /// - the operand must never be referenced indirectly
68     ///     - we should not take its address using the `&` operator
69     ///     - nor should it appear in a place path like `tmp.a`
70     /// - the operand must be defined by an rvalue that can generate immediate
71     ///   values
72     ///
73     /// Avoiding allocs can also be important for certain intrinsics,
74     /// notably `expect`.
75     locals: IndexVec<mir::Local, LocalRef<'tcx, Bx::Value>>,
76
77     /// All `VarDebugInfo` from the MIR body, partitioned by `Local`.
78     /// This is `None` if no var`#[non_exhaustive]`iable debuginfo/names are needed.
79     per_local_var_debug_info:
80         Option<IndexVec<mir::Local, Vec<PerLocalVarDebugInfo<'tcx, Bx::DIVariable>>>>,
81
82     /// Caller location propagated if this function has `#[track_caller]`.
83     caller_location: Option<OperandRef<'tcx, Bx::Value>>,
84 }
85
86 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
87     pub fn monomorphize<T>(&self, value: &T) -> T
88     where
89         T: TypeFoldable<'tcx>,
90     {
91         self.cx.tcx().subst_and_normalize_erasing_regions(
92             self.instance.substs,
93             ty::ParamEnv::reveal_all(),
94             value,
95         )
96     }
97 }
98
99 enum LocalRef<'tcx, V> {
100     Place(PlaceRef<'tcx, V>),
101     /// `UnsizedPlace(p)`: `p` itself is a thin pointer (indirect place).
102     /// `*p` is the fat pointer that references the actual unsized place.
103     /// Every time it is initialized, we have to reallocate the place
104     /// and update the fat pointer. That's the reason why it is indirect.
105     UnsizedPlace(PlaceRef<'tcx, V>),
106     Operand(Option<OperandRef<'tcx, V>>),
107 }
108
109 impl<'a, 'tcx, V: CodegenObject> LocalRef<'tcx, V> {
110     fn new_operand<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
111         bx: &mut Bx,
112         layout: TyLayout<'tcx>,
113     ) -> LocalRef<'tcx, V> {
114         if layout.is_zst() {
115             // Zero-size temporaries aren't always initialized, which
116             // doesn't matter because they don't contain data, but
117             // we need something in the operand.
118             LocalRef::Operand(Some(OperandRef::new_zst(bx, layout)))
119         } else {
120             LocalRef::Operand(None)
121         }
122     }
123 }
124
125 ///////////////////////////////////////////////////////////////////////////
126
127 pub fn codegen_mir<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
128     cx: &'a Bx::CodegenCx,
129     instance: Instance<'tcx>,
130 ) {
131     assert!(!instance.substs.needs_infer());
132
133     let llfn = cx.get_fn(instance);
134
135     let mir = cx.tcx().instance_mir(instance.def);
136
137     let fn_abi = FnAbi::of_instance(cx, instance, &[]);
138     debug!("fn_abi: {:?}", fn_abi);
139
140     let debug_context = cx.create_function_debug_context(instance, &fn_abi, llfn, &mir);
141
142     let mut bx = Bx::new_block(cx, llfn, "start");
143
144     if mir.basic_blocks().iter().any(|bb| bb.is_cleanup) {
145         bx.set_personality_fn(cx.eh_personality());
146     }
147
148     bx.sideeffect();
149
150     let cleanup_kinds = analyze::cleanup_kinds(&mir);
151     // Allocate a `Block` for every basic block, except
152     // the start block, if nothing loops back to it.
153     let reentrant_start_block = !mir.predecessors_for(mir::START_BLOCK).is_empty();
154     let block_bxs: IndexVec<mir::BasicBlock, Bx::BasicBlock> = mir
155         .basic_blocks()
156         .indices()
157         .map(|bb| {
158             if bb == mir::START_BLOCK && !reentrant_start_block {
159                 bx.llbb()
160             } else {
161                 bx.build_sibling_block(&format!("{:?}", bb)).llbb()
162             }
163         })
164         .collect();
165
166     let (landing_pads, funclets) = create_funclets(&mir, &mut bx, &cleanup_kinds, &block_bxs);
167     let mir_body: &mir::Body<'_> = *mir;
168     let mut fx = FunctionCx {
169         instance,
170         mir,
171         llfn,
172         fn_abi,
173         cx,
174         personality_slot: None,
175         blocks: block_bxs,
176         unreachable_block: None,
177         cleanup_kinds,
178         landing_pads,
179         funclets,
180         locals: IndexVec::new(),
181         debug_context,
182         per_local_var_debug_info: None,
183         caller_location: None,
184     };
185
186     fx.per_local_var_debug_info = fx.compute_per_local_var_debug_info();
187
188     let memory_locals = analyze::non_ssa_locals(&fx);
189
190     // Allocate variable and temp allocas
191     fx.locals = {
192         let args = arg_local_refs(&mut bx, &mut fx, &memory_locals);
193
194         let mut allocate_local = |local| {
195             let decl = &mir_body.local_decls[local];
196             let layout = bx.layout_of(fx.monomorphize(&decl.ty));
197             assert!(!layout.ty.has_erasable_regions());
198
199             if local == mir::RETURN_PLACE && fx.fn_abi.ret.is_indirect() {
200                 debug!("alloc: {:?} (return place) -> place", local);
201                 let llretptr = bx.get_param(0);
202                 return LocalRef::Place(PlaceRef::new_sized(llretptr, layout));
203             }
204
205             if memory_locals.contains(local) {
206                 debug!("alloc: {:?} -> place", local);
207                 if layout.is_unsized() {
208                     LocalRef::UnsizedPlace(PlaceRef::alloca_unsized_indirect(&mut bx, layout))
209                 } else {
210                     LocalRef::Place(PlaceRef::alloca(&mut bx, layout))
211                 }
212             } else {
213                 debug!("alloc: {:?} -> operand", local);
214                 LocalRef::new_operand(&mut bx, layout)
215             }
216         };
217
218         let retptr = allocate_local(mir::RETURN_PLACE);
219         iter::once(retptr)
220             .chain(args.into_iter())
221             .chain(mir_body.vars_and_temps_iter().map(allocate_local))
222             .collect()
223     };
224
225     // Apply debuginfo to the newly allocated locals.
226     fx.debug_introduce_locals(&mut bx);
227
228     // Branch to the START block, if it's not the entry block.
229     if reentrant_start_block {
230         bx.br(fx.blocks[mir::START_BLOCK]);
231     }
232
233     let rpo = traversal::reverse_postorder(&mir_body);
234     let mut visited = BitSet::new_empty(mir_body.basic_blocks().len());
235
236     // Codegen the body of each block using reverse postorder
237     for (bb, _) in rpo {
238         visited.insert(bb.index());
239         fx.codegen_block(bb);
240     }
241
242     // Remove blocks that haven't been visited, or have no
243     // predecessors.
244     for bb in mir_body.basic_blocks().indices() {
245         // Unreachable block
246         if !visited.contains(bb.index()) {
247             debug!("codegen_mir: block {:?} was not visited", bb);
248             unsafe {
249                 bx.delete_basic_block(fx.blocks[bb]);
250             }
251         }
252     }
253 }
254
255 fn create_funclets<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
256     mir: &'tcx mir::Body<'tcx>,
257     bx: &mut Bx,
258     cleanup_kinds: &IndexVec<mir::BasicBlock, CleanupKind>,
259     block_bxs: &IndexVec<mir::BasicBlock, Bx::BasicBlock>,
260 ) -> (
261     IndexVec<mir::BasicBlock, Option<Bx::BasicBlock>>,
262     IndexVec<mir::BasicBlock, Option<Bx::Funclet>>,
263 ) {
264     block_bxs
265         .iter_enumerated()
266         .zip(cleanup_kinds)
267         .map(|((bb, &llbb), cleanup_kind)| {
268             match *cleanup_kind {
269                 CleanupKind::Funclet if base::wants_msvc_seh(bx.sess()) => {}
270                 _ => return (None, None),
271             }
272
273             let funclet;
274             let ret_llbb;
275             match mir[bb].terminator.as_ref().map(|t| &t.kind) {
276                 // This is a basic block that we're aborting the program for,
277                 // notably in an `extern` function. These basic blocks are inserted
278                 // so that we assert that `extern` functions do indeed not panic,
279                 // and if they do we abort the process.
280                 //
281                 // On MSVC these are tricky though (where we're doing funclets). If
282                 // we were to do a cleanuppad (like below) the normal functions like
283                 // `longjmp` would trigger the abort logic, terminating the
284                 // program. Instead we insert the equivalent of `catch(...)` for C++
285                 // which magically doesn't trigger when `longjmp` files over this
286                 // frame.
287                 //
288                 // Lots more discussion can be found on #48251 but this codegen is
289                 // modeled after clang's for:
290                 //
291                 //      try {
292                 //          foo();
293                 //      } catch (...) {
294                 //          bar();
295                 //      }
296                 Some(&mir::TerminatorKind::Abort) => {
297                     let mut cs_bx = bx.build_sibling_block(&format!("cs_funclet{:?}", bb));
298                     let mut cp_bx = bx.build_sibling_block(&format!("cp_funclet{:?}", bb));
299                     ret_llbb = cs_bx.llbb();
300
301                     let cs = cs_bx.catch_switch(None, None, 1);
302                     cs_bx.add_handler(cs, cp_bx.llbb());
303
304                     // The "null" here is actually a RTTI type descriptor for the
305                     // C++ personality function, but `catch (...)` has no type so
306                     // it's null. The 64 here is actually a bitfield which
307                     // represents that this is a catch-all block.
308                     let null = bx.const_null(bx.type_i8p());
309                     let sixty_four = bx.const_i32(64);
310                     funclet = cp_bx.catch_pad(cs, &[null, sixty_four, null]);
311                     cp_bx.br(llbb);
312                 }
313                 _ => {
314                     let mut cleanup_bx = bx.build_sibling_block(&format!("funclet_{:?}", bb));
315                     ret_llbb = cleanup_bx.llbb();
316                     funclet = cleanup_bx.cleanup_pad(None, &[]);
317                     cleanup_bx.br(llbb);
318                 }
319             };
320
321             (Some(ret_llbb), Some(funclet))
322         })
323         .unzip()
324 }
325
326 /// Produces, for each argument, a `Value` pointing at the
327 /// argument's value. As arguments are places, these are always
328 /// indirect.
329 fn arg_local_refs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
330     bx: &mut Bx,
331     fx: &mut FunctionCx<'a, 'tcx, Bx>,
332     memory_locals: &BitSet<mir::Local>,
333 ) -> Vec<LocalRef<'tcx, Bx::Value>> {
334     let mir = fx.mir;
335     let mut idx = 0;
336     let mut llarg_idx = fx.fn_abi.ret.is_indirect() as usize;
337
338     let args = mir
339         .args_iter()
340         .enumerate()
341         .map(|(arg_index, local)| {
342             let arg_decl = &mir.local_decls[local];
343
344             if Some(local) == mir.spread_arg {
345                 // This argument (e.g., the last argument in the "rust-call" ABI)
346                 // is a tuple that was spread at the ABI level and now we have
347                 // to reconstruct it into a tuple local variable, from multiple
348                 // individual LLVM function arguments.
349
350                 let arg_ty = fx.monomorphize(&arg_decl.ty);
351                 let tupled_arg_tys = match arg_ty.kind {
352                     ty::Tuple(ref tys) => tys,
353                     _ => bug!("spread argument isn't a tuple?!"),
354                 };
355
356                 let place = PlaceRef::alloca(bx, bx.layout_of(arg_ty));
357                 for i in 0..tupled_arg_tys.len() {
358                     let arg = &fx.fn_abi.args[idx];
359                     idx += 1;
360                     if arg.pad.is_some() {
361                         llarg_idx += 1;
362                     }
363                     let pr_field = place.project_field(bx, i);
364                     bx.store_fn_arg(arg, &mut llarg_idx, pr_field);
365                 }
366
367                 return LocalRef::Place(place);
368             }
369
370             if fx.fn_abi.c_variadic && arg_index == fx.fn_abi.args.len() {
371                 let arg_ty = fx.monomorphize(&arg_decl.ty);
372
373                 let va_list = PlaceRef::alloca(bx, bx.layout_of(arg_ty));
374                 bx.va_start(va_list.llval);
375
376                 return LocalRef::Place(va_list);
377             }
378
379             let arg = &fx.fn_abi.args[idx];
380             idx += 1;
381             if arg.pad.is_some() {
382                 llarg_idx += 1;
383             }
384
385             if !memory_locals.contains(local) {
386                 // We don't have to cast or keep the argument in the alloca.
387                 // FIXME(eddyb): We should figure out how to use llvm.dbg.value instead
388                 // of putting everything in allocas just so we can use llvm.dbg.declare.
389                 let local = |op| LocalRef::Operand(Some(op));
390                 match arg.mode {
391                     PassMode::Ignore => {
392                         return local(OperandRef::new_zst(bx, arg.layout));
393                     }
394                     PassMode::Direct(_) => {
395                         let llarg = bx.get_param(llarg_idx);
396                         llarg_idx += 1;
397                         return local(OperandRef::from_immediate_or_packed_pair(
398                             bx, llarg, arg.layout,
399                         ));
400                     }
401                     PassMode::Pair(..) => {
402                         let (a, b) = (bx.get_param(llarg_idx), bx.get_param(llarg_idx + 1));
403                         llarg_idx += 2;
404
405                         return local(OperandRef {
406                             val: OperandValue::Pair(a, b),
407                             layout: arg.layout,
408                         });
409                     }
410                     _ => {}
411                 }
412             }
413
414             if arg.is_sized_indirect() {
415                 // Don't copy an indirect argument to an alloca, the caller
416                 // already put it in a temporary alloca and gave it up.
417                 // FIXME: lifetimes
418                 let llarg = bx.get_param(llarg_idx);
419                 llarg_idx += 1;
420                 LocalRef::Place(PlaceRef::new_sized(llarg, arg.layout))
421             } else if arg.is_unsized_indirect() {
422                 // As the storage for the indirect argument lives during
423                 // the whole function call, we just copy the fat pointer.
424                 let llarg = bx.get_param(llarg_idx);
425                 llarg_idx += 1;
426                 let llextra = bx.get_param(llarg_idx);
427                 llarg_idx += 1;
428                 let indirect_operand = OperandValue::Pair(llarg, llextra);
429
430                 let tmp = PlaceRef::alloca_unsized_indirect(bx, arg.layout);
431                 indirect_operand.store(bx, tmp);
432                 LocalRef::UnsizedPlace(tmp)
433             } else {
434                 let tmp = PlaceRef::alloca(bx, arg.layout);
435                 bx.store_fn_arg(arg, &mut llarg_idx, tmp);
436                 LocalRef::Place(tmp)
437             }
438         })
439         .collect::<Vec<_>>();
440
441     if fx.instance.def.requires_caller_location(bx.tcx()) {
442         assert_eq!(
443             fx.fn_abi.args.len(),
444             args.len() + 1,
445             "#[track_caller] fn's must have 1 more argument in their ABI than in their MIR",
446         );
447
448         let arg = fx.fn_abi.args.last().unwrap();
449         match arg.mode {
450             PassMode::Direct(_) => (),
451             _ => bug!("caller location must be PassMode::Direct, found {:?}", arg.mode),
452         }
453
454         fx.caller_location = Some(OperandRef {
455             val: OperandValue::Immediate(bx.get_param(llarg_idx)),
456             layout: arg.layout,
457         });
458     }
459
460     args
461 }
462
463 mod analyze;
464 mod block;
465 pub mod constant;
466 pub mod debuginfo;
467 pub mod operand;
468 pub mod place;
469 mod rvalue;
470 mod statement;