]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/build/mod.rs
Auto merge of #102565 - jyn514:refactor-build-manifest, r=Mark-Simulacrum
[rust.git] / compiler / rustc_mir_build / src / build / mod.rs
1 pub(crate) use crate::build::expr::as_constant::lit_to_mir_constant;
2 use crate::build::expr::as_place::PlaceBuilder;
3 use crate::build::scope::DropKind;
4 use rustc_apfloat::ieee::{Double, Single};
5 use rustc_apfloat::Float;
6 use rustc_data_structures::fx::FxHashMap;
7 use rustc_data_structures::sorted_map::SortedIndexMultiMap;
8 use rustc_errors::ErrorGuaranteed;
9 use rustc_hir as hir;
10 use rustc_hir::def::DefKind;
11 use rustc_hir::def_id::{DefId, LocalDefId};
12 use rustc_hir::{GeneratorKind, Node};
13 use rustc_index::vec::{Idx, IndexVec};
14 use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
15 use rustc_middle::hir::place::PlaceBase as HirPlaceBase;
16 use rustc_middle::middle::region;
17 use rustc_middle::mir::interpret::ConstValue;
18 use rustc_middle::mir::interpret::Scalar;
19 use rustc_middle::mir::*;
20 use rustc_middle::thir::{
21     self, BindingMode, Expr, ExprId, LintLevel, LocalVarId, Param, ParamId, PatKind, Thir,
22 };
23 use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitable, TypeckResults};
24 use rustc_span::symbol::sym;
25 use rustc_span::Span;
26 use rustc_span::Symbol;
27 use rustc_target::spec::abi::Abi;
28
29 use super::lints;
30
31 pub(crate) fn mir_built<'tcx>(
32     tcx: TyCtxt<'tcx>,
33     def: ty::WithOptConstParam<LocalDefId>,
34 ) -> &'tcx rustc_data_structures::steal::Steal<Body<'tcx>> {
35     if let Some(def) = def.try_upgrade(tcx) {
36         return tcx.mir_built(def);
37     }
38
39     let mut body = mir_build(tcx, def);
40     if def.const_param_did.is_some() {
41         assert!(matches!(body.source.instance, ty::InstanceDef::Item(_)));
42         body.source = MirSource::from_instance(ty::InstanceDef::Item(def.to_global()));
43     }
44
45     tcx.alloc_steal_mir(body)
46 }
47
48 /// Construct the MIR for a given `DefId`.
49 fn mir_build(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> Body<'_> {
50     let body_owner_kind = tcx.hir().body_owner_kind(def.did);
51
52     // Ensure unsafeck and abstract const building is ran before we steal the THIR.
53     // We can't use `ensure()` for `thir_abstract_const` as it doesn't compute the query
54     // if inputs are green. This can cause ICEs when calling `thir_abstract_const` after
55     // THIR has been stolen if we haven't computed this query yet.
56     match def {
57         ty::WithOptConstParam { did, const_param_did: Some(const_param_did) } => {
58             tcx.ensure().thir_check_unsafety_for_const_arg((did, const_param_did));
59             drop(tcx.thir_abstract_const_of_const_arg((did, const_param_did)));
60         }
61         ty::WithOptConstParam { did, const_param_did: None } => {
62             tcx.ensure().thir_check_unsafety(did);
63             drop(tcx.thir_abstract_const(did));
64         }
65     }
66
67     let body = match tcx.thir_body(def) {
68         Err(error_reported) => construct_error(tcx, def.did, body_owner_kind, error_reported),
69         Ok((thir, expr)) => {
70             // We ran all queries that depended on THIR at the beginning
71             // of `mir_build`, so now we can steal it
72             let thir = thir.steal();
73
74             if body_owner_kind.is_fn_or_closure() {
75                 construct_fn(tcx, def, &thir, expr)
76             } else {
77                 construct_const(tcx, def, &thir, expr)
78             }
79         }
80     };
81
82     lints::check(tcx, &body);
83
84     // The borrow checker will replace all the regions here with its own
85     // inference variables. There's no point having non-erased regions here.
86     // The exception is `body.user_type_annotations`, which is used unmodified
87     // by borrow checking.
88     debug_assert!(
89         !(body.local_decls.has_free_regions()
90             || body.basic_blocks.has_free_regions()
91             || body.var_debug_info.has_free_regions()
92             || body.yield_ty().has_free_regions()),
93         "Unexpected free regions in MIR: {:?}",
94         body,
95     );
96
97     body
98 }
99
100 ///////////////////////////////////////////////////////////////////////////
101 // BuildMir -- walks a crate, looking for fn items and methods to build MIR from
102
103 #[derive(Debug, PartialEq, Eq)]
104 enum BlockFrame {
105     /// Evaluation is currently within a statement.
106     ///
107     /// Examples include:
108     /// 1. `EXPR;`
109     /// 2. `let _ = EXPR;`
110     /// 3. `let x = EXPR;`
111     Statement {
112         /// If true, then statement discards result from evaluating
113         /// the expression (such as examples 1 and 2 above).
114         ignores_expr_result: bool,
115     },
116
117     /// Evaluation is currently within the tail expression of a block.
118     ///
119     /// Example: `{ STMT_1; STMT_2; EXPR }`
120     TailExpr {
121         /// If true, then the surrounding context of the block ignores
122         /// the result of evaluating the block's tail expression.
123         ///
124         /// Example: `let _ = { STMT_1; EXPR };`
125         tail_result_is_ignored: bool,
126
127         /// `Span` of the tail expression.
128         span: Span,
129     },
130
131     /// Generic mark meaning that the block occurred as a subexpression
132     /// where the result might be used.
133     ///
134     /// Examples: `foo(EXPR)`, `match EXPR { ... }`
135     SubExpr,
136 }
137
138 impl BlockFrame {
139     fn is_tail_expr(&self) -> bool {
140         match *self {
141             BlockFrame::TailExpr { .. } => true,
142
143             BlockFrame::Statement { .. } | BlockFrame::SubExpr => false,
144         }
145     }
146     fn is_statement(&self) -> bool {
147         match *self {
148             BlockFrame::Statement { .. } => true,
149
150             BlockFrame::TailExpr { .. } | BlockFrame::SubExpr => false,
151         }
152     }
153 }
154
155 #[derive(Debug)]
156 struct BlockContext(Vec<BlockFrame>);
157
158 struct Builder<'a, 'tcx> {
159     tcx: TyCtxt<'tcx>,
160     infcx: InferCtxt<'tcx>,
161     typeck_results: &'tcx TypeckResults<'tcx>,
162     region_scope_tree: &'tcx region::ScopeTree,
163     param_env: ty::ParamEnv<'tcx>,
164
165     thir: &'a Thir<'tcx>,
166     cfg: CFG<'tcx>,
167
168     def_id: DefId,
169     hir_id: hir::HirId,
170     parent_module: DefId,
171     check_overflow: bool,
172     fn_span: Span,
173     arg_count: usize,
174     generator_kind: Option<GeneratorKind>,
175
176     /// The current set of scopes, updated as we traverse;
177     /// see the `scope` module for more details.
178     scopes: scope::Scopes<'tcx>,
179
180     /// The block-context: each time we build the code within an thir::Block,
181     /// we push a frame here tracking whether we are building a statement or
182     /// if we are pushing the tail expression of the block. This is used to
183     /// embed information in generated temps about whether they were created
184     /// for a block tail expression or not.
185     ///
186     /// It would be great if we could fold this into `self.scopes`
187     /// somehow, but right now I think that is very tightly tied to
188     /// the code generation in ways that we cannot (or should not)
189     /// start just throwing new entries onto that vector in order to
190     /// distinguish the context of EXPR1 from the context of EXPR2 in
191     /// `{ STMTS; EXPR1 } + EXPR2`.
192     block_context: BlockContext,
193
194     /// The current unsafe block in scope
195     in_scope_unsafe: Safety,
196
197     /// The vector of all scopes that we have created thus far;
198     /// we track this for debuginfo later.
199     source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
200     source_scope: SourceScope,
201
202     /// The guard-context: each time we build the guard expression for
203     /// a match arm, we push onto this stack, and then pop when we
204     /// finish building it.
205     guard_context: Vec<GuardFrame>,
206
207     /// Maps `HirId`s of variable bindings to the `Local`s created for them.
208     /// (A match binding can have two locals; the 2nd is for the arm's guard.)
209     var_indices: FxHashMap<LocalVarId, LocalsForNode>,
210     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
211     canonical_user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
212     upvars: CaptureMap<'tcx>,
213     unit_temp: Option<Place<'tcx>>,
214
215     var_debug_info: Vec<VarDebugInfo<'tcx>>,
216 }
217
218 type CaptureMap<'tcx> = SortedIndexMultiMap<usize, hir::HirId, Capture<'tcx>>;
219
220 #[derive(Debug)]
221 struct Capture<'tcx> {
222     captured_place: &'tcx ty::CapturedPlace<'tcx>,
223     use_place: Place<'tcx>,
224     mutability: Mutability,
225 }
226
227 impl<'a, 'tcx> Builder<'a, 'tcx> {
228     fn is_bound_var_in_guard(&self, id: LocalVarId) -> bool {
229         self.guard_context.iter().any(|frame| frame.locals.iter().any(|local| local.id == id))
230     }
231
232     fn var_local_id(&self, id: LocalVarId, for_guard: ForGuard) -> Local {
233         self.var_indices[&id].local_id(for_guard)
234     }
235 }
236
237 impl BlockContext {
238     fn new() -> Self {
239         BlockContext(vec![])
240     }
241     fn push(&mut self, bf: BlockFrame) {
242         self.0.push(bf);
243     }
244     fn pop(&mut self) -> Option<BlockFrame> {
245         self.0.pop()
246     }
247
248     /// Traverses the frames on the `BlockContext`, searching for either
249     /// the first block-tail expression frame with no intervening
250     /// statement frame.
251     ///
252     /// Notably, this skips over `SubExpr` frames; this method is
253     /// meant to be used in the context of understanding the
254     /// relationship of a temp (created within some complicated
255     /// expression) with its containing expression, and whether the
256     /// value of that *containing expression* (not the temp!) is
257     /// ignored.
258     fn currently_in_block_tail(&self) -> Option<BlockTailInfo> {
259         for bf in self.0.iter().rev() {
260             match bf {
261                 BlockFrame::SubExpr => continue,
262                 BlockFrame::Statement { .. } => break,
263                 &BlockFrame::TailExpr { tail_result_is_ignored, span } => {
264                     return Some(BlockTailInfo { tail_result_is_ignored, span });
265                 }
266             }
267         }
268
269         None
270     }
271
272     /// Looks at the topmost frame on the BlockContext and reports
273     /// whether its one that would discard a block tail result.
274     ///
275     /// Unlike `currently_within_ignored_tail_expression`, this does
276     /// *not* skip over `SubExpr` frames: here, we want to know
277     /// whether the block result itself is discarded.
278     fn currently_ignores_tail_results(&self) -> bool {
279         match self.0.last() {
280             // no context: conservatively assume result is read
281             None => false,
282
283             // sub-expression: block result feeds into some computation
284             Some(BlockFrame::SubExpr) => false,
285
286             // otherwise: use accumulated is_ignored state.
287             Some(
288                 BlockFrame::TailExpr { tail_result_is_ignored: ignored, .. }
289                 | BlockFrame::Statement { ignores_expr_result: ignored },
290             ) => *ignored,
291         }
292     }
293 }
294
295 #[derive(Debug)]
296 enum LocalsForNode {
297     /// In the usual case, a `HirId` for an identifier maps to at most
298     /// one `Local` declaration.
299     One(Local),
300
301     /// The exceptional case is identifiers in a match arm's pattern
302     /// that are referenced in a guard of that match arm. For these,
303     /// we have `2` Locals.
304     ///
305     /// * `for_arm_body` is the Local used in the arm body (which is
306     ///   just like the `One` case above),
307     ///
308     /// * `ref_for_guard` is the Local used in the arm's guard (which
309     ///   is a reference to a temp that is an alias of
310     ///   `for_arm_body`).
311     ForGuard { ref_for_guard: Local, for_arm_body: Local },
312 }
313
314 #[derive(Debug)]
315 struct GuardFrameLocal {
316     id: LocalVarId,
317 }
318
319 impl GuardFrameLocal {
320     fn new(id: LocalVarId, _binding_mode: BindingMode) -> Self {
321         GuardFrameLocal { id }
322     }
323 }
324
325 #[derive(Debug)]
326 struct GuardFrame {
327     /// These are the id's of names that are bound by patterns of the
328     /// arm of *this* guard.
329     ///
330     /// (Frames higher up the stack will have the id's bound in arms
331     /// further out, such as in a case like:
332     ///
333     /// match E1 {
334     ///      P1(id1) if (... (match E2 { P2(id2) if ... => B2 })) => B1,
335     /// }
336     ///
337     /// here, when building for FIXME.
338     locals: Vec<GuardFrameLocal>,
339 }
340
341 /// `ForGuard` indicates whether we are talking about:
342 ///   1. The variable for use outside of guard expressions, or
343 ///   2. The temp that holds reference to (1.), which is actually what the
344 ///      guard expressions see.
345 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
346 enum ForGuard {
347     RefWithinGuard,
348     OutsideGuard,
349 }
350
351 impl LocalsForNode {
352     fn local_id(&self, for_guard: ForGuard) -> Local {
353         match (self, for_guard) {
354             (&LocalsForNode::One(local_id), ForGuard::OutsideGuard)
355             | (
356                 &LocalsForNode::ForGuard { ref_for_guard: local_id, .. },
357                 ForGuard::RefWithinGuard,
358             )
359             | (&LocalsForNode::ForGuard { for_arm_body: local_id, .. }, ForGuard::OutsideGuard) => {
360                 local_id
361             }
362
363             (&LocalsForNode::One(_), ForGuard::RefWithinGuard) => {
364                 bug!("anything with one local should never be within a guard.")
365             }
366         }
367     }
368 }
369
370 struct CFG<'tcx> {
371     basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
372 }
373
374 rustc_index::newtype_index! {
375     struct ScopeId { .. }
376 }
377
378 #[derive(Debug)]
379 enum NeedsTemporary {
380     /// Use this variant when whatever you are converting with `as_operand`
381     /// is the last thing you are converting. This means that if we introduced
382     /// an intermediate temporary, we'd only read it immediately after, so we can
383     /// also avoid it.
384     No,
385     /// For all cases where you aren't sure or that are too expensive to compute
386     /// for now. It is always safe to fall back to this.
387     Maybe,
388 }
389
390 ///////////////////////////////////////////////////////////////////////////
391 /// The `BlockAnd` "monad" packages up the new basic block along with a
392 /// produced value (sometimes just unit, of course). The `unpack!`
393 /// macro (and methods below) makes working with `BlockAnd` much more
394 /// convenient.
395
396 #[must_use = "if you don't use one of these results, you're leaving a dangling edge"]
397 struct BlockAnd<T>(BasicBlock, T);
398
399 trait BlockAndExtension {
400     fn and<T>(self, v: T) -> BlockAnd<T>;
401     fn unit(self) -> BlockAnd<()>;
402 }
403
404 impl BlockAndExtension for BasicBlock {
405     fn and<T>(self, v: T) -> BlockAnd<T> {
406         BlockAnd(self, v)
407     }
408
409     fn unit(self) -> BlockAnd<()> {
410         BlockAnd(self, ())
411     }
412 }
413
414 /// Update a block pointer and return the value.
415 /// Use it like `let x = unpack!(block = self.foo(block, foo))`.
416 macro_rules! unpack {
417     ($x:ident = $c:expr) => {{
418         let BlockAnd(b, v) = $c;
419         $x = b;
420         v
421     }};
422
423     ($c:expr) => {{
424         let BlockAnd(b, ()) = $c;
425         b
426     }};
427 }
428
429 ///////////////////////////////////////////////////////////////////////////
430 /// the main entry point for building MIR for a function
431
432 fn construct_fn<'tcx>(
433     tcx: TyCtxt<'tcx>,
434     fn_def: ty::WithOptConstParam<LocalDefId>,
435     thir: &Thir<'tcx>,
436     expr: ExprId,
437 ) -> Body<'tcx> {
438     let span = tcx.def_span(fn_def.did);
439     let fn_id = tcx.hir().local_def_id_to_hir_id(fn_def.did);
440     let generator_kind = tcx.generator_kind(fn_def.did);
441
442     // Figure out what primary body this item has.
443     let body_id = tcx.hir().body_owned_by(fn_def.did);
444     let span_with_body = tcx.hir().span_with_body(fn_id);
445     let return_ty_span = tcx
446         .hir()
447         .fn_decl_by_hir_id(fn_id)
448         .unwrap_or_else(|| span_bug!(span, "can't build MIR for {:?}", fn_def.did))
449         .output
450         .span();
451
452     // fetch the fully liberated fn signature (that is, all bound
453     // types/lifetimes replaced)
454     let typeck_results = tcx.typeck_opt_const_arg(fn_def);
455     let fn_sig = typeck_results.liberated_fn_sigs()[fn_id];
456
457     let safety = match fn_sig.unsafety {
458         hir::Unsafety::Normal => Safety::Safe,
459         hir::Unsafety::Unsafe => Safety::FnUnsafe,
460     };
461
462     let mut abi = fn_sig.abi;
463     if let DefKind::Closure = tcx.def_kind(fn_def.did) {
464         // HACK(eddyb) Avoid having RustCall on closures,
465         // as it adds unnecessary (and wrong) auto-tupling.
466         abi = Abi::Rust;
467     }
468
469     let arguments = &thir.params;
470
471     let (yield_ty, return_ty) = if generator_kind.is_some() {
472         let gen_ty = arguments[thir::UPVAR_ENV_PARAM].ty;
473         let gen_sig = match gen_ty.kind() {
474             ty::Generator(_, gen_substs, ..) => gen_substs.as_generator().sig(),
475             _ => {
476                 span_bug!(span, "generator w/o generator type: {:?}", gen_ty)
477             }
478         };
479         (Some(gen_sig.yield_ty), gen_sig.return_ty)
480     } else {
481         (None, fn_sig.output())
482     };
483
484     let infcx = tcx.infer_ctxt().build();
485     let mut builder = Builder::new(
486         thir,
487         infcx,
488         fn_def,
489         fn_id,
490         span_with_body,
491         arguments.len(),
492         safety,
493         return_ty,
494         return_ty_span,
495         generator_kind,
496     );
497
498     let call_site_scope =
499         region::Scope { id: body_id.hir_id.local_id, data: region::ScopeData::CallSite };
500     let arg_scope =
501         region::Scope { id: body_id.hir_id.local_id, data: region::ScopeData::Arguments };
502     let source_info = builder.source_info(span);
503     let call_site_s = (call_site_scope, source_info);
504     unpack!(builder.in_scope(call_site_s, LintLevel::Inherited, |builder| {
505         let arg_scope_s = (arg_scope, source_info);
506         // Attribute epilogue to function's closing brace
507         let fn_end = span_with_body.shrink_to_hi();
508         let return_block =
509             unpack!(builder.in_breakable_scope(None, Place::return_place(), fn_end, |builder| {
510                 Some(builder.in_scope(arg_scope_s, LintLevel::Inherited, |builder| {
511                     builder.args_and_body(
512                         START_BLOCK,
513                         fn_def.did,
514                         arguments,
515                         arg_scope,
516                         &thir[expr],
517                     )
518                 }))
519             }));
520         let source_info = builder.source_info(fn_end);
521         builder.cfg.terminate(return_block, source_info, TerminatorKind::Return);
522         builder.build_drop_trees();
523         return_block.unit()
524     }));
525
526     let mut body = builder.finish();
527
528     body.spread_arg = if abi == Abi::RustCall {
529         // RustCall pseudo-ABI untuples the last argument.
530         Some(Local::new(arguments.len()))
531     } else {
532         None
533     };
534     if yield_ty.is_some() {
535         body.generator.as_mut().unwrap().yield_ty = yield_ty;
536     }
537     body
538 }
539
540 fn construct_const<'a, 'tcx>(
541     tcx: TyCtxt<'tcx>,
542     def: ty::WithOptConstParam<LocalDefId>,
543     thir: &'a Thir<'tcx>,
544     expr: ExprId,
545 ) -> Body<'tcx> {
546     let hir_id = tcx.hir().local_def_id_to_hir_id(def.did);
547
548     // Figure out what primary body this item has.
549     let (span, const_ty_span) = match tcx.hir().get(hir_id) {
550         Node::Item(hir::Item {
551             kind: hir::ItemKind::Static(ty, _, _) | hir::ItemKind::Const(ty, _),
552             span,
553             ..
554         })
555         | Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Const(ty, _), span, .. })
556         | Node::TraitItem(hir::TraitItem {
557             kind: hir::TraitItemKind::Const(ty, Some(_)),
558             span,
559             ..
560         }) => (*span, ty.span),
561         Node::AnonConst(_) => {
562             let span = tcx.def_span(def.did);
563             (span, span)
564         }
565         _ => span_bug!(tcx.def_span(def.did), "can't build MIR for {:?}", def.did),
566     };
567
568     // Get the revealed type of this const. This is *not* the adjusted
569     // type of its body, which may be a subtype of this type. For
570     // example:
571     //
572     // fn foo(_: &()) {}
573     // static X: fn(&'static ()) = foo;
574     //
575     // The adjusted type of the body of X is `for<'a> fn(&'a ())` which
576     // is not the same as the type of X. We need the type of the return
577     // place to be the type of the constant because NLL typeck will
578     // equate them.
579     let typeck_results = tcx.typeck_opt_const_arg(def);
580     let const_ty = typeck_results.node_type(hir_id);
581
582     let infcx = tcx.infer_ctxt().build();
583     let mut builder = Builder::new(
584         thir,
585         infcx,
586         def,
587         hir_id,
588         span,
589         0,
590         Safety::Safe,
591         const_ty,
592         const_ty_span,
593         None,
594     );
595
596     let mut block = START_BLOCK;
597     unpack!(block = builder.expr_into_dest(Place::return_place(), block, &thir[expr]));
598
599     let source_info = builder.source_info(span);
600     builder.cfg.terminate(block, source_info, TerminatorKind::Return);
601
602     builder.build_drop_trees();
603
604     builder.finish()
605 }
606
607 /// Construct MIR for an item that has had errors in type checking.
608 ///
609 /// This is required because we may still want to run MIR passes on an item
610 /// with type errors, but normal MIR construction can't handle that in general.
611 fn construct_error<'tcx>(
612     tcx: TyCtxt<'tcx>,
613     def: LocalDefId,
614     body_owner_kind: hir::BodyOwnerKind,
615     err: ErrorGuaranteed,
616 ) -> Body<'tcx> {
617     let span = tcx.def_span(def);
618     let hir_id = tcx.hir().local_def_id_to_hir_id(def);
619     let generator_kind = tcx.generator_kind(def);
620
621     let ty = tcx.ty_error();
622     let num_params = match body_owner_kind {
623         hir::BodyOwnerKind::Fn => tcx.fn_sig(def).inputs().skip_binder().len(),
624         hir::BodyOwnerKind::Closure => {
625             let ty = tcx.type_of(def);
626             match ty.kind() {
627                 ty::Closure(_, substs) => {
628                     1 + substs.as_closure().sig().inputs().skip_binder().len()
629                 }
630                 ty::Generator(..) => 2,
631                 _ => bug!("expected closure or generator, found {ty:?}"),
632             }
633         }
634         hir::BodyOwnerKind::Const => 0,
635         hir::BodyOwnerKind::Static(_) => 0,
636     };
637     let mut cfg = CFG { basic_blocks: IndexVec::new() };
638     let mut source_scopes = IndexVec::new();
639     let mut local_decls = IndexVec::from_elem_n(LocalDecl::new(ty, span), 1);
640
641     cfg.start_new_block();
642     source_scopes.push(SourceScopeData {
643         span,
644         parent_scope: None,
645         inlined: None,
646         inlined_parent_scope: None,
647         local_data: ClearCrossCrate::Set(SourceScopeLocalData {
648             lint_root: hir_id,
649             safety: Safety::Safe,
650         }),
651     });
652     let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
653
654     // Some MIR passes will expect the number of parameters to match the
655     // function declaration.
656     for _ in 0..num_params {
657         local_decls.push(LocalDecl::with_source_info(ty, source_info));
658     }
659     cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
660
661     let mut body = Body::new(
662         MirSource::item(def.to_def_id()),
663         cfg.basic_blocks,
664         source_scopes,
665         local_decls,
666         IndexVec::new(),
667         num_params,
668         vec![],
669         span,
670         generator_kind,
671         Some(err),
672     );
673     body.generator.as_mut().map(|gen| gen.yield_ty = Some(ty));
674     body
675 }
676
677 impl<'a, 'tcx> Builder<'a, 'tcx> {
678     fn new(
679         thir: &'a Thir<'tcx>,
680         infcx: InferCtxt<'tcx>,
681         def: ty::WithOptConstParam<LocalDefId>,
682         hir_id: hir::HirId,
683         span: Span,
684         arg_count: usize,
685         safety: Safety,
686         return_ty: Ty<'tcx>,
687         return_span: Span,
688         generator_kind: Option<GeneratorKind>,
689     ) -> Builder<'a, 'tcx> {
690         let tcx = infcx.tcx;
691         let attrs = tcx.hir().attrs(hir_id);
692         // Some functions always have overflow checks enabled,
693         // however, they may not get codegen'd, depending on
694         // the settings for the crate they are codegened in.
695         let mut check_overflow = tcx.sess.contains_name(attrs, sym::rustc_inherit_overflow_checks);
696         // Respect -C overflow-checks.
697         check_overflow |= tcx.sess.overflow_checks();
698         // Constants always need overflow checks.
699         check_overflow |= matches!(
700             tcx.hir().body_owner_kind(def.did),
701             hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_)
702         );
703
704         let lint_level = LintLevel::Explicit(hir_id);
705         let param_env = tcx.param_env(def.did);
706         let mut builder = Builder {
707             thir,
708             tcx,
709             infcx,
710             typeck_results: tcx.typeck_opt_const_arg(def),
711             region_scope_tree: tcx.region_scope_tree(def.did),
712             param_env,
713             def_id: def.did.to_def_id(),
714             hir_id,
715             parent_module: tcx.parent_module(hir_id).to_def_id(),
716             check_overflow,
717             cfg: CFG { basic_blocks: IndexVec::new() },
718             fn_span: span,
719             arg_count,
720             generator_kind,
721             scopes: scope::Scopes::new(),
722             block_context: BlockContext::new(),
723             source_scopes: IndexVec::new(),
724             source_scope: OUTERMOST_SOURCE_SCOPE,
725             guard_context: vec![],
726             in_scope_unsafe: safety,
727             local_decls: IndexVec::from_elem_n(LocalDecl::new(return_ty, return_span), 1),
728             canonical_user_type_annotations: IndexVec::new(),
729             upvars: CaptureMap::new(),
730             var_indices: Default::default(),
731             unit_temp: None,
732             var_debug_info: vec![],
733         };
734
735         assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
736         assert_eq!(
737             builder.new_source_scope(span, lint_level, Some(safety)),
738             OUTERMOST_SOURCE_SCOPE
739         );
740         builder.source_scopes[OUTERMOST_SOURCE_SCOPE].parent_scope = None;
741
742         builder
743     }
744
745     fn finish(self) -> Body<'tcx> {
746         for (index, block) in self.cfg.basic_blocks.iter().enumerate() {
747             if block.terminator.is_none() {
748                 span_bug!(self.fn_span, "no terminator on block {:?}", index);
749             }
750         }
751
752         Body::new(
753             MirSource::item(self.def_id),
754             self.cfg.basic_blocks,
755             self.source_scopes,
756             self.local_decls,
757             self.canonical_user_type_annotations,
758             self.arg_count,
759             self.var_debug_info,
760             self.fn_span,
761             self.generator_kind,
762             self.typeck_results.tainted_by_errors,
763         )
764     }
765
766     fn args_and_body(
767         &mut self,
768         mut block: BasicBlock,
769         fn_def_id: LocalDefId,
770         arguments: &IndexVec<ParamId, Param<'tcx>>,
771         argument_scope: region::Scope,
772         expr: &Expr<'tcx>,
773     ) -> BlockAnd<()> {
774         // Allocate locals for the function arguments
775         for param in arguments.iter() {
776             let source_info =
777                 SourceInfo::outermost(param.pat.as_ref().map_or(self.fn_span, |pat| pat.span));
778             let arg_local =
779                 self.local_decls.push(LocalDecl::with_source_info(param.ty, source_info));
780
781             // If this is a simple binding pattern, give debuginfo a nice name.
782             if let Some(ref pat) = param.pat && let Some(name) = pat.simple_ident() {
783                 self.var_debug_info.push(VarDebugInfo {
784                     name,
785                     source_info,
786                     value: VarDebugInfoContents::Place(arg_local.into()),
787                 });
788             }
789         }
790
791         let tcx = self.tcx;
792         let tcx_hir = tcx.hir();
793         let hir_typeck_results = self.typeck_results;
794
795         // In analyze_closure() in upvar.rs we gathered a list of upvars used by an
796         // indexed closure and we stored in a map called closure_min_captures in TypeckResults
797         // with the closure's DefId. Here, we run through that vec of UpvarIds for
798         // the given closure and use the necessary information to create upvar
799         // debuginfo and to fill `self.upvars`.
800         if hir_typeck_results.closure_min_captures.get(&fn_def_id).is_some() {
801             let mut closure_env_projs = vec![];
802             let mut closure_ty = self.local_decls[ty::CAPTURE_STRUCT_LOCAL].ty;
803             if let ty::Ref(_, ty, _) = closure_ty.kind() {
804                 closure_env_projs.push(ProjectionElem::Deref);
805                 closure_ty = *ty;
806             }
807             let upvar_substs = match closure_ty.kind() {
808                 ty::Closure(_, substs) => ty::UpvarSubsts::Closure(substs),
809                 ty::Generator(_, substs, _) => ty::UpvarSubsts::Generator(substs),
810                 _ => span_bug!(self.fn_span, "upvars with non-closure env ty {:?}", closure_ty),
811             };
812             let def_id = self.def_id.as_local().unwrap();
813             let capture_syms = tcx.symbols_for_closure_captures((def_id, fn_def_id));
814             let capture_tys = upvar_substs.upvar_tys();
815             let captures_with_tys = hir_typeck_results
816                 .closure_min_captures_flattened(fn_def_id)
817                 .zip(capture_tys.zip(capture_syms));
818
819             self.upvars = captures_with_tys
820                 .enumerate()
821                 .map(|(i, (captured_place, (ty, sym)))| {
822                     let capture = captured_place.info.capture_kind;
823                     let var_id = match captured_place.place.base {
824                         HirPlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
825                         _ => bug!("Expected an upvar"),
826                     };
827
828                     let mutability = captured_place.mutability;
829
830                     let mut projs = closure_env_projs.clone();
831                     projs.push(ProjectionElem::Field(Field::new(i), ty));
832                     match capture {
833                         ty::UpvarCapture::ByValue => {}
834                         ty::UpvarCapture::ByRef(..) => {
835                             projs.push(ProjectionElem::Deref);
836                         }
837                     };
838
839                     let use_place = Place {
840                         local: ty::CAPTURE_STRUCT_LOCAL,
841                         projection: tcx.intern_place_elems(&projs),
842                     };
843                     self.var_debug_info.push(VarDebugInfo {
844                         name: *sym,
845                         source_info: SourceInfo::outermost(tcx_hir.span(var_id)),
846                         value: VarDebugInfoContents::Place(use_place),
847                     });
848
849                     let capture = Capture { captured_place, use_place, mutability };
850                     (var_id, capture)
851                 })
852                 .collect();
853         }
854
855         let mut scope = None;
856         // Bind the argument patterns
857         for (index, param) in arguments.iter().enumerate() {
858             // Function arguments always get the first Local indices after the return place
859             let local = Local::new(index + 1);
860             let place = Place::from(local);
861
862             // Make sure we drop (parts of) the argument even when not matched on.
863             self.schedule_drop(
864                 param.pat.as_ref().map_or(expr.span, |pat| pat.span),
865                 argument_scope,
866                 local,
867                 DropKind::Value,
868             );
869
870             let Some(ref pat) = param.pat else {
871                 continue;
872             };
873             let original_source_scope = self.source_scope;
874             let span = pat.span;
875             if let Some(arg_hir_id) = param.hir_id {
876                 self.set_correct_source_scope_for_arg(arg_hir_id, original_source_scope, span);
877             }
878             match pat.kind {
879                 // Don't introduce extra copies for simple bindings
880                 PatKind::Binding {
881                     mutability,
882                     var,
883                     mode: BindingMode::ByValue,
884                     subpattern: None,
885                     ..
886                 } => {
887                     self.local_decls[local].mutability = mutability;
888                     self.local_decls[local].source_info.scope = self.source_scope;
889                     self.local_decls[local].local_info = if let Some(kind) = param.self_kind {
890                         Some(Box::new(LocalInfo::User(ClearCrossCrate::Set(
891                             BindingForm::ImplicitSelf(kind),
892                         ))))
893                     } else {
894                         let binding_mode = ty::BindingMode::BindByValue(mutability);
895                         Some(Box::new(LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
896                             VarBindingForm {
897                                 binding_mode,
898                                 opt_ty_info: param.ty_span,
899                                 opt_match_place: Some((None, span)),
900                                 pat_span: span,
901                             },
902                         )))))
903                     };
904                     self.var_indices.insert(var, LocalsForNode::One(local));
905                 }
906                 _ => {
907                     scope = self.declare_bindings(
908                         scope,
909                         expr.span,
910                         &pat,
911                         matches::ArmHasGuard(false),
912                         Some((Some(&place), span)),
913                     );
914                     let place_builder = PlaceBuilder::from(local);
915                     unpack!(block = self.place_into_pattern(block, &pat, place_builder, false));
916                 }
917             }
918             self.source_scope = original_source_scope;
919         }
920
921         // Enter the argument pattern bindings source scope, if it exists.
922         if let Some(source_scope) = scope {
923             self.source_scope = source_scope;
924         }
925
926         self.expr_into_dest(Place::return_place(), block, &expr)
927     }
928
929     fn set_correct_source_scope_for_arg(
930         &mut self,
931         arg_hir_id: hir::HirId,
932         original_source_scope: SourceScope,
933         pattern_span: Span,
934     ) {
935         let tcx = self.tcx;
936         let current_root = tcx.maybe_lint_level_root_bounded(arg_hir_id, self.hir_id);
937         let parent_root = tcx.maybe_lint_level_root_bounded(
938             self.source_scopes[original_source_scope]
939                 .local_data
940                 .as_ref()
941                 .assert_crate_local()
942                 .lint_root,
943             self.hir_id,
944         );
945         if current_root != parent_root {
946             self.source_scope =
947                 self.new_source_scope(pattern_span, LintLevel::Explicit(current_root), None);
948         }
949     }
950
951     fn get_unit_temp(&mut self) -> Place<'tcx> {
952         match self.unit_temp {
953             Some(tmp) => tmp,
954             None => {
955                 let ty = self.tcx.mk_unit();
956                 let fn_span = self.fn_span;
957                 let tmp = self.temp(ty, fn_span);
958                 self.unit_temp = Some(tmp);
959                 tmp
960             }
961         }
962     }
963 }
964
965 fn parse_float_into_constval<'tcx>(
966     num: Symbol,
967     float_ty: ty::FloatTy,
968     neg: bool,
969 ) -> Option<ConstValue<'tcx>> {
970     parse_float_into_scalar(num, float_ty, neg).map(ConstValue::Scalar)
971 }
972
973 pub(crate) fn parse_float_into_scalar(
974     num: Symbol,
975     float_ty: ty::FloatTy,
976     neg: bool,
977 ) -> Option<Scalar> {
978     let num = num.as_str();
979     match float_ty {
980         ty::FloatTy::F32 => {
981             let Ok(rust_f) = num.parse::<f32>() else { return None };
982             let mut f = num.parse::<Single>().unwrap_or_else(|e| {
983                 panic!("apfloat::ieee::Single failed to parse `{}`: {:?}", num, e)
984             });
985
986             assert!(
987                 u128::from(rust_f.to_bits()) == f.to_bits(),
988                 "apfloat::ieee::Single gave different result for `{}`: \
989                  {}({:#x}) vs Rust's {}({:#x})",
990                 rust_f,
991                 f,
992                 f.to_bits(),
993                 Single::from_bits(rust_f.to_bits().into()),
994                 rust_f.to_bits()
995             );
996
997             if neg {
998                 f = -f;
999             }
1000
1001             Some(Scalar::from_f32(f))
1002         }
1003         ty::FloatTy::F64 => {
1004             let Ok(rust_f) = num.parse::<f64>() else { return None };
1005             let mut f = num.parse::<Double>().unwrap_or_else(|e| {
1006                 panic!("apfloat::ieee::Double failed to parse `{}`: {:?}", num, e)
1007             });
1008
1009             assert!(
1010                 u128::from(rust_f.to_bits()) == f.to_bits(),
1011                 "apfloat::ieee::Double gave different result for `{}`: \
1012                  {}({:#x}) vs Rust's {}({:#x})",
1013                 rust_f,
1014                 f,
1015                 f.to_bits(),
1016                 Double::from_bits(rust_f.to_bits().into()),
1017                 rust_f.to_bits()
1018             );
1019
1020             if neg {
1021                 f = -f;
1022             }
1023
1024             Some(Scalar::from_f64(f))
1025         }
1026     }
1027 }
1028
1029 ///////////////////////////////////////////////////////////////////////////
1030 // Builder methods are broken up into modules, depending on what kind
1031 // of thing is being lowered. Note that they use the `unpack` macro
1032 // above extensively.
1033
1034 mod block;
1035 mod cfg;
1036 mod expr;
1037 mod matches;
1038 mod misc;
1039 mod scope;
1040
1041 pub(crate) use expr::category::Category as ExprCategory;