Debian Codegraph @

gcc/rust/checks/errors/borrowck/rust-bir-builder-internal.h

raw
1 // Copyright (C) 2020-2025 Free Software Foundation, Inc.
2
3 // This file is part of GCC.
4
5 // GCC is free software; you can redistribute it and/or modify it under
6 // the terms of the GNU General Public License as published by the Free
7 // Software Foundation; either version 3, or (at your option) any later
8 // version.
9
10 // GCC is distributed in the hope that it will be useful, but WITHOUT ANY
11 // WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 // for more details.
14
15 // You should have received a copy of the GNU General Public License
16 // along with GCC; see the file COPYING3. If not see
17 // <http://www.gnu.org/licenses/>.
18
19 #ifndef RUST_BIR_BUILDER_INTERNAL_H
20 #define RUST_BIR_BUILDER_INTERNAL_H
21
22 #include "rust-bir-place.h"
23 #include "rust-hir-expr.h"
24 #include "rust-hir-item.h"
25 #include "rust-hir-type-check.h"
26 #include "rust-hir-visitor.h"
27 #include "rust-name-resolver.h"
28 #include "rust-bir.h"
29 #include "rust-bir-free-region.h"
30
31 namespace Rust {
32
33 namespace TyTy {
34
35 using Variance = VarianceAnalysis::Variance;
36
37 class RenumberCtx
38 {
39 Polonius::Origin next_region = 0;
40
41 public:
42 Polonius::Origin get_next_region () { return next_region++; }
43 };
44
45 } // namespace TyTy
46
47 namespace BIR {
48
49 /** Holds the context of BIR building so that it can be shared/passed between
50 * different builders. */
51 struct BuilderContext
52 {
53 struct LoopAndLabelCtx
54 {
55 bool is_loop; // Loop or labelled block
56 NodeId label; // UNKNOWN_NODEID if no label (loop)
57 PlaceId label_var; // For break with value.
58 BasicBlockId break_bb;
59 BasicBlockId continue_bb; // Only valid for loops
60 ScopeId continue_scope;
61 // Break scope is the parent of the `continue_scope`.
62
63 LoopAndLabelCtx (bool is_loop = false, NodeId label = UNKNOWN_NODEID,
64 PlaceId label_var = INVALID_PLACE,
65 BasicBlockId break_bb = INVALID_BB,
66 BasicBlockId continue_bb = INVALID_BB,
67 ScopeId continue_scope = INVALID_SCOPE)
68 : is_loop (is_loop), label (label), label_var (label_var),
69 break_bb (break_bb), continue_bb (continue_bb),
70 continue_scope (continue_scope)
71 {}
72 };
73
74 // External context.
75 Resolver::TypeCheckContext &tyctx;
76 Resolver::Resolver &resolver;
77
78 // BIR output
79 BasicBlocks basic_blocks;
80 BasicBlockId current_bb = ENTRY_BASIC_BLOCK;
81
82 /**
83 * Allocation and lookup of places (variables, temporaries, paths, and
84 * constants)
85 */
86 PlaceDB place_db;
87 RegionBinder region_binder{place_db.expose_next_free_region ()};
88
89 // Used for cleaner dump.
90 std::vector<PlaceId> arguments;
91 /**
92 * Since labels can be used to return values, we need to reserve a place for
93 * them. This map associates labels with their respective places.
94 */
95 std::unordered_map<NodeId, PlaceId> label_place_map;
96
97 /** Context for current situation (loop, label, etc.) */
98 std::vector<LoopAndLabelCtx> loop_and_label_stack;
99
100 FreeRegions fn_free_regions{{}};
101
102 public:
103 BuilderContext ()
104 : tyctx (*Resolver::TypeCheckContext::get ()),
105 resolver (*Resolver::Resolver::get ())
106 {
107 basic_blocks.emplace_back (); // StartBB
108 }
109
110 BasicBlock &get_current_bb () { return basic_blocks[current_bb]; }
111
112 const LoopAndLabelCtx &lookup_label (NodeId label)
113 {
114 auto label_match = [label] (const LoopAndLabelCtx &info) {
115 return info.label != UNKNOWN_NODEID && info.label == label;
116 };
117
118 auto found = std::find_if (loop_and_label_stack.rbegin (),
119 loop_and_label_stack.rend (), label_match);
120 rust_assert (found != loop_and_label_stack.rend ());
121 return *found;
122 }
123 };
124
125 /** Common infrastructure for building BIR from HIR. */
126 class AbstractBuilder
127 {
128 protected:
129 BuilderContext &ctx;
130
131 /**
132 * This emulates the return value of the visitor, to be able to use the
133 * current visitor infrastructure, where the return value is forced to be
134 * void.
135 */
136 PlaceId translated = INVALID_PLACE;
137
138 protected:
139 explicit AbstractBuilder (BuilderContext &ctx) : ctx (ctx) {}
140
141 PlaceId declare_variable (const Analysis::NodeMapping &node,
142 bool user_type_annotation = false)
143 {
144 return declare_variable (node, lookup_type (node.get_hirid ()),
145 user_type_annotation);
146 }
147
148 PlaceId declare_variable (const Analysis::NodeMapping &node,
149 TyTy::BaseType *ty,
150 bool user_type_annotation = false)
151 {
152 const NodeId nodeid = node.get_nodeid ();
153
154 // In debug mode, check that the variable is not already declared.
155 rust_assert (ctx.place_db.lookup_variable (nodeid) == INVALID_PLACE);
156
157 auto place_id = ctx.place_db.add_variable (nodeid, ty);
158
159 if (ctx.place_db.get_current_scope_id () != INVALID_SCOPE)
160 push_storage_live (place_id);
161
162 if (user_type_annotation)
163 push_user_type_ascription (place_id, ty);
164
165 return place_id;
166 }
167
168 void push_new_scope () { ctx.place_db.push_new_scope (); }
169
170 void pop_scope ()
171 {
172 auto &scope = ctx.place_db.get_current_scope ();
173 if (ctx.place_db.get_current_scope_id () != INVALID_SCOPE)
174 {
175 std::for_each (scope.locals.rbegin (), scope.locals.rend (),
176 [&] (PlaceId place) { push_storage_dead (place); });
177 }
178 ctx.place_db.pop_scope ();
179 }
180
181 bool intersection_empty (std::vector<PlaceId> &a, std::vector<PlaceId> &b)
182 {
183 for (auto &place : a)
184 {
185 if (std::find (b.begin (), b.end (), place) != b.end ())
186 return false;
187 }
188 return true;
189 }
190
191 void unwind_until (ScopeId final_scope)
192 {
193 auto current_scope_id = ctx.place_db.get_current_scope_id ();
194 while (current_scope_id != final_scope)
195 {
196 auto &scope = ctx.place_db.get_scope (current_scope_id);
197
198 // TODO: Perform stable toposort based on `borrowed_by`.
199
200 std::for_each (scope.locals.rbegin (), scope.locals.rend (),
201 [&] (PlaceId place) { push_storage_dead (place); });
202 current_scope_id = scope.parent;
203 }
204 }
205
206 FreeRegions bind_regions (std::vector<TyTy::Region> regions,
207 FreeRegions parent_free_regions)
208 {
209 FreeRegions free_regions;
210 for (auto &region : regions)
211 {
212 if (region.is_early_bound ())
213 {
214 free_regions.push_back (parent_free_regions[region.get_index ()]);
215 }
216 else if (region.is_static ())
217 {
218 free_regions.push_back (STATIC_FREE_REGION);
219 }
220 else if (region.is_anonymous ())
221 {
222 free_regions.push_back (ctx.place_db.get_next_free_region ());
223 }
224 else if (region.is_named ())
225 {
226 rust_unreachable (); // FIXME
227 }
228 else
229 {
230 rust_sorry_at (UNKNOWN_LOCATION, "Unimplemented");
231 rust_unreachable ();
232 }
233 }
234 return free_regions;
235 }
236
237 protected: // Helpers to add BIR statements
238 void push_assignment (PlaceId lhs, AbstractExpr *rhs, location_t location)
239 {
240 ctx.get_current_bb ().statements.push_back (
241 Statement::make_assignment (lhs, rhs, location));
242 translated = lhs;
243 }
244
245 void push_assignment (PlaceId lhs, PlaceId rhs, location_t location)
246 {
247 push_assignment (lhs, new Assignment (rhs), location);
248 }
249
250 void push_tmp_assignment (AbstractExpr *rhs, TyTy::BaseType *tyty,
251 location_t location)
252 {
253 PlaceId tmp = ctx.place_db.add_temporary (tyty);
254 push_storage_live (tmp);
255 push_assignment (tmp, rhs, location);
256 }
257
258 void push_tmp_assignment (PlaceId rhs, location_t location)
259 {
260 push_tmp_assignment (new Assignment (rhs), ctx.place_db[rhs].tyty,
261 location);
262 }
263
264 void push_switch (PlaceId switch_val, location_t location,
265 std::initializer_list<BasicBlockId> destinations = {})
266 {
267 auto copy = move_place (switch_val, location);
268 ctx.get_current_bb ().statements.push_back (Statement::make_switch (copy));
269 ctx.get_current_bb ().successors.insert (
270 ctx.get_current_bb ().successors.end (), destinations);
271 }
272
273 void push_goto (BasicBlockId bb)
274 {
275 ctx.get_current_bb ().statements.push_back (Statement::make_goto ());
276 if (bb != INVALID_BB) // INVALID_BB means the goto will be resolved later.
277 ctx.get_current_bb ().successors.push_back (bb);
278 }
279
280 void push_storage_live (PlaceId place)
281 {
282 ctx.get_current_bb ().statements.push_back (
283 Statement::make_storage_live (place));
284 }
285
286 void push_storage_dead (PlaceId place)
287 {
288 ctx.get_current_bb ().statements.push_back (
289 Statement::make_storage_dead (place));
290 }
291
292 void push_user_type_ascription (PlaceId place, TyTy::BaseType *ty)
293 {
294 ctx.get_current_bb ().statements.push_back (
295 Statement::make_user_type_ascription (place, ty));
296 }
297
298 void push_fake_read (PlaceId place)
299 {
300 ctx.get_current_bb ().statements.push_back (
301 Statement::make_fake_read (place));
302 }
303
304 void push_return (location_t location)
305 {
306 ctx.get_current_bb ().statements.push_back (
307 Statement::make_return (location));
308 }
309
310 PlaceId borrow_place (PlaceId place_id, TyTy::BaseType *ty,
311 location_t location)
312 {
313 auto mutability = ty->as<const TyTy::ReferenceType> ()->mutability ();
314 auto loan = ctx.place_db.add_loan ({mutability, place_id, location});
315 push_tmp_assignment (
316 new BorrowExpr (place_id, loan,
317 ctx.place_db.get_next_free_region ().value),
318 ty, location);
319 return translated;
320 }
321
322 PlaceId move_place (PlaceId arg, location_t location)
323 {
324 auto &place = ctx.place_db[arg];
325
326 if (place.is_constant ())
327 return arg;
328
329 if (place.tyty->is<TyTy::ReferenceType> ())
330 return reborrow_place (arg, location);
331
332 if (place.is_rvalue ())
333 return arg;
334
335 push_tmp_assignment (arg, location);
336 return translated;
337 }
338
339 PlaceId reborrow_place (PlaceId arg, location_t location)
340 {
341 auto ty = ctx.place_db[arg].tyty->as<TyTy::ReferenceType> ();
342 return borrow_place (ctx.place_db.lookup_or_add_path (Place::DEREF,
343 ty->get_base (), arg),
344 ty, location);
345 }
346
347 template <typename T>
348 void move_all (T &args, std::vector<location_t> locations)
349 {
350 rust_assert (args.size () == locations.size ());
351 std::transform (args.begin (), args.end (), locations.begin (),
352 args.begin (), [this] (PlaceId arg, location_t location) {
353 return move_place (arg, location);
354 });
355 }
356
357 protected: // CFG helpers
358 BasicBlockId new_bb ()
359 {
360 ctx.basic_blocks.emplace_back ();
361 return {ctx.basic_blocks.size () - 1};
362 }
363
364 BasicBlockId start_new_consecutive_bb ()
365 {
366 BasicBlockId bb = new_bb ();
367 if (!ctx.get_current_bb ().is_terminated ())
368 {
369 push_goto (bb);
370 }
371 else
372 {
373 add_jump_to (bb);
374 }
375 ctx.current_bb = bb;
376 return bb;
377 }
378
379 void add_jump (BasicBlockId from, BasicBlockId to)
380 {
381 ctx.basic_blocks[from].successors.emplace_back (to);
382 }
383
384 void add_jump_to (BasicBlockId bb) { add_jump (ctx.current_bb, bb); }
385
386 protected: // HIR resolution helpers
387 template <typename T>
388 WARN_UNUSED_RESULT TyTy::BaseType *lookup_type (T &hir_node) const
389 {
390 return lookup_type (hir_node.get_mappings ().get_hirid ());
391 }
392
393 WARN_UNUSED_RESULT TyTy::BaseType *lookup_type (HirId hirid) const
394 {
395 TyTy::BaseType *type = nullptr;
396 bool ok = ctx.tyctx.lookup_type (hirid, &type);
397 rust_assert (ok);
398 rust_assert (type != nullptr);
399 return type;
400 }
401
402 template <typename T> NodeId resolve_label (T &expr)
403 {
404 NodeId resolved_label;
405 bool ok
406 = ctx.resolver.lookup_resolved_label (expr.get_mappings ().get_nodeid (),
407 &resolved_label);
408 rust_assert (ok);
409 return resolved_label;
410 }
411
412 template <typename T> PlaceId resolve_variable (T &variable)
413 {
414 NodeId variable_id;
415 bool ok = ctx.resolver.lookup_resolved_name (
416 variable.get_mappings ().get_nodeid (), &variable_id);
417 rust_assert (ok);
418 return ctx.place_db.lookup_variable (variable_id);
419 }
420
421 template <typename T>
422 PlaceId resolve_variable_or_fn (T &variable, TyTy::BaseType *ty)
423 {
424 ty = (ty) ? ty : lookup_type (variable);
425 // Unlike variables,
426 // functions do not have to be declared in PlaceDB before use.
427 NodeId variable_id;
428 bool ok = ctx.resolver.lookup_resolved_name (
429 variable.get_mappings ().get_nodeid (), &variable_id);
430 rust_assert (ok);
431 if (ty->is<TyTy::FnType> ())
432 return ctx.place_db.get_constant (ty);
433 else
434 return ctx.place_db.lookup_or_add_variable (variable_id, ty);
435 }
436
437 protected: // Implicit conversions.
438 /**
439 * Performs implicit coercions on the `translated` place defined for a
440 * coercion site.
441 *
442 * Reference: https://doc.rust-lang.org/reference/type-coercions.html
443 *
444 * The only coercion relevant to BIR is the autoderef. All other coercions
445 * will be taken in account because the type is extracted from each node and
446 * not derived from operations in HIR/BIR. The borrowck does not care about
447 * type transitions. Lifetimes are not coerced, rather new are created with
448 * defined bounds to the original ones.
449 */
450 void coercion_site (PlaceId &place, TyTy::BaseType *expected_ty)
451 {
452 auto count_ref_levels = [] (TyTy::BaseType *ty) {
453 size_t count = 0;
454 while (auto r = ty->try_as<TyTy::ReferenceType> ())
455 {
456 ty = r->get_base ();
457 count++;
458 }
459 return count;
460 };
461
462 auto actual_ty = ctx.place_db[place].tyty;
463
464 auto deref_count
465 = count_ref_levels (actual_ty) - count_ref_levels (expected_ty);
466
467 for (size_t i = 0; i < deref_count; ++i)
468 {
469 actual_ty = actual_ty->as<TyTy::ReferenceType> ()->get_base ();
470 place
471 = ctx.place_db.lookup_or_add_path (Place::DEREF, actual_ty, place);
472 }
473 }
474
475 /** Dereferences the `translated` place until it is at most one reference
476 * and return the base type. */
477 TyTy::BaseType *autoderef (PlaceId &place)
478 {
479 auto ty = ctx.place_db[place].tyty;
480 while (auto ref_ty = ty->try_as<TyTy::ReferenceType> ())
481 {
482 ty = ref_ty->get_base ();
483 place = ctx.place_db.lookup_or_add_path (Place::DEREF, ty, place);
484 }
485 return ty;
486 }
487
488 void autoref ()
489 {
490 if (ctx.place_db[translated].tyty->get_kind () != TyTy::REF)
491 {
492 // FIXME: not sure how to fetch correct location for this
493 // this function is unused yet, so can ignore for now
494 auto ty = ctx.place_db[translated].tyty;
495 translated
496 = borrow_place (translated,
497 new TyTy::ReferenceType (ty->get_ref (),
498 TyTy::TyVar (ty->get_ref ()),
499 Mutability::Imm),
500 UNKNOWN_LOCATION);
501 }
502 }
503 };
504
505 class AbstractExprBuilder : public AbstractBuilder,
506 public HIR::HIRExpressionVisitor
507 {
508 protected:
509 /**
510 * Optional place for the result of the evaluated expression.
511 * Valid if value is not `INVALID_PLACE`.
512 * Used when return place must be created by caller (return for if-else).
513 */
514 PlaceId expr_return_place = INVALID_PLACE;
515
516 protected:
517 explicit AbstractExprBuilder (BuilderContext &ctx,
518 PlaceId expr_return_place = INVALID_PLACE)
519 : AbstractBuilder (ctx), expr_return_place (expr_return_place)
520 {}
521
522 /**
523 * Wrapper that provides return value based API inside a visitor which has
524 * to use global state to pass the data around.
525 * @param dst_place Place to assign the produced value to, optionally
526 * allocated by the caller.
527 * */
528 PlaceId visit_expr (HIR::Expr &expr, PlaceId dst_place = INVALID_PLACE)
529 {
530 // Save to support proper recursion.
531 auto saved = expr_return_place;
532 expr_return_place = dst_place;
533 translated = INVALID_PLACE;
534 expr.accept_vis (*this);
535 expr_return_place = saved;
536 auto result = translated;
537 translated = INVALID_PLACE;
538 return result;
539 }
540
541 /**
542 * Create a return value of a subexpression, which produces an expression.
543 * Use `return_place` for subexpression that only produce a place (look it
544 * up) to avoid needless assignments.
545 *
546 * @param can_panic mark that expression can panic to insert jump to
547 * cleanup.
548 */
549 void return_expr (AbstractExpr *expr, TyTy::BaseType *ty, location_t location,
550 bool can_panic = false)
551 {
552 if (expr_return_place != INVALID_PLACE)
553 {
554 push_assignment (expr_return_place, expr, location);
555 }
556 else
557 {
558 push_tmp_assignment (expr, ty, location);
559 }
560
561 if (can_panic)
562 {
563 start_new_consecutive_bb ();
564 }
565
566 if (ty->is<TyTy::ReferenceType> ()
567 || ctx.place_db[translated].is_constant ())
568 {
569 push_fake_read (translated);
570 }
571 }
572
573 /** Mark place to be a result of processed subexpression. */
574 void return_place (PlaceId place, location_t location, bool can_panic = false)
575 {
576 if (expr_return_place != INVALID_PLACE)
577 {
578 // Return place is already allocated, no need to defer assignment.
579 push_assignment (expr_return_place, place, location);
580 }
581 else
582 {
583 translated = place;
584 }
585
586 if (can_panic)
587 {
588 start_new_consecutive_bb ();
589 }
590
591 if (ctx.place_db[place].is_constant ())
592 {
593 push_fake_read (translated);
594 }
595 }
596
597 /** Explicitly return a unit value. Expression produces no value. */
598 void return_unit (HIR::Expr &expr)
599 {
600 translated = ctx.place_db.get_constant (lookup_type (expr));
601 }
602
603 PlaceId return_borrowed (PlaceId place_id, TyTy::BaseType *ty,
604 location_t location)
605 {
606 // TODO: deduplicate with borrow_place
607 auto loan = ctx.place_db.add_loan (
608 {ty->as<const TyTy::ReferenceType> ()->mutability (), place_id,
609 location});
610 return_expr (new BorrowExpr (place_id, loan,
611 ctx.place_db.get_next_free_region ().value),
612 ty, location);
613 return translated;
614 }
615
616 PlaceId take_or_create_return_place (TyTy::BaseType *type)
617 {
618 PlaceId result = INVALID_PLACE;
619 if (expr_return_place != INVALID_PLACE)
620 {
621 result = expr_return_place;
622 expr_return_place = INVALID_PLACE;
623 }
624 else
625 {
626 result = ctx.place_db.add_temporary (type);
627 push_storage_live (result);
628 }
629 return result;
630 }
631 };
632
633 /**
634 * Helper to convert a pointer to an optional. Maps nullptr to nullopt.
635 * Optionals are mainly used here to provide monadic operations (map) over
636 * possibly null pointers.
637 */
638 template <typename T>
639 tl::optional<T>
640 optional_from_ptr (T ptr)
641 {
642 if (ptr != nullptr)
643 return {ptr};
644 else
645 return tl::nullopt;
646 }
647
648 } // namespace BIR
649 } // namespace Rust
650
651 #endif // RUST_BIR_BUILDER_INTERNAL_H