File: HandleMigrate.cpp

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (939 lines) | stat: -rw-r--r-- 35,082 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// A clang tool for the migration of Handle<T> to DirectHandle<T>.
// This is only useful for the V8 code base.

#include <clang/AST/ASTContext.h>
#include <clang/ASTMatchers/ASTMatchFinder.h>
#include <clang/ASTMatchers/ASTMatchers.h>
#include <clang/Frontend/FrontendActions.h>
#include <clang/Tooling/CommonOptionsParser.h>
#include <clang/Tooling/Refactoring.h>
#include <clang/Tooling/Tooling.h>
#include <llvm/Support/CommandLine.h>

#include <optional>
#include <regex>
#include <string>
#include <unordered_map>
#include <vector>

using namespace clang;
using namespace clang::tooling;
using namespace clang::ast_matchers;

// Command line options.

static llvm::cl::OptionCategory my_tool_category(
    "Handle migration tool options");
static llvm::cl::extrahelp common_help(CommonOptionsParser::HelpMessage);

constexpr int kVerboseNone = 0;
constexpr int kVerboseReportInterestingHandleUse = 1;
constexpr int kVerboseReportInterestingFunctionCall = 1;
constexpr int kVerboseReportImplicitHandleConversion = 2;
constexpr int kVerboseReportHandleDereference = 2;
constexpr int kVerboseReportInterestingHandleDecl = 3;
constexpr int kVerboseReportInterestingFunctions = 4;
constexpr int kVerboseWhereAreWe = 90;

static llvm::cl::opt<int> VERBOSE("verbose",
                                  llvm::cl::desc("Set verbosity level"),
                                  llvm::cl::value_desc("level"),
                                  llvm::cl::init(kVerboseNone),
                                  llvm::cl::cat(my_tool_category));

static llvm::cl::alias alias_for_VERBOSE("v",
                                         llvm::cl::desc("Alias for --verbose"),
                                         llvm::cl::aliasopt(VERBOSE),
                                         llvm::cl::cat(my_tool_category));

static llvm::cl::extrahelp verbosity_help(
    "Verbosity levels:\n"
    "\t0:\tquiet\n"
    "\t1:\tinteresting handle uses and function calls\n"
    "\t2:\timplicit handle conversions and dereferences\n"
    "\t3:\tinteresting handle declarations\n"
    "\t4:\tinteresting function declarations\n"
    "\t90:\ttrack AST source location\n"
    "\n");

static llvm::cl::opt<bool> only_in_main_file(
    "local",
    llvm::cl::desc("Process only declarations in main file(s), default false"),
    llvm::cl::init(false),
    llvm::cl::cat(my_tool_category));

// Boilerplate. (Using clang::ast_matchers naming convention for these.)
// ----------------------------------------------------------------------------

TypeMatcher relaxType(TypeMatcher t) {
  return anyOf(t, pointerType(pointee(t)), referenceType(pointee(t)));
}

StatementMatcher constructorWithOneArgument(StatementMatcher argument) {
  return cxxConstructExpr(argumentCountIs(1),
                          hasArgument(0, ignoringImplicit(argument)));
}

auto handleDecl = cxxRecordDecl(isSameOrDerivedFrom("::v8::internal::Handle"),
                                isTemplateInstantiation());
auto directHandleDecl =
    cxxRecordDecl(isSameOrDerivedFrom("::v8::internal::DirectHandle"),
                  isTemplateInstantiation());
TypeMatcher handleType = relaxType(hasDeclaration(handleDecl));
TypeMatcher directHandleType = relaxType(hasDeclaration(directHandleDecl));

// Database for storing interesting variables, functions, etc.
// ----------------------------------------------------------------------------

template <typename NodeType>
struct ASTNodeHash {
  size_t operator()(const NodeType* x) const {
    return x->getLocation().getHashValue();
  }
};

template <typename NodeType>
struct ASTNodeEquals {
  bool operator()(const NodeType* x, const NodeType* y) const {
    return x->getLocation() == y->getLocation();
  }
};

class InterestingFunction;

// A database with possibly interesting declarations of type Handle<T>.
class InterestingHandle {
 public:
  InterestingHandle(const InterestingHandle&) = delete;
  InterestingHandle(InterestingHandle&&) = default;

  static InterestingHandle* Insert(const VarDecl* decl, bool is_definition) {
    assert(decl != nullptr);
    auto it = interesting_.find(decl);
    if (it == interesting_.end()) {
      auto p =
          interesting_.emplace(decl, InterestingHandle{decl, is_definition});
      it = p.first;
    }
    return &it->second;
  }

  static InterestingHandle* Lookup(const VarDecl* decl) {
    assert(decl != nullptr);
    auto it = interesting_.find(decl);
    if (it == interesting_.end()) {
      return nullptr;
    }
    return &it->second;
  }

  void Print(const SourceManager& source_manager) const {
    llvm::outs() << "    location: ";
    location_.print(llvm::outs(), source_manager);
    llvm::outs() << "\n";
    llvm::outs() << "    type: " << type_ << "\n";
  }

  void AddDependent(InterestingHandle* h) {
    // Marks `h` as a dependent of `this`: `this` is the parameter of a
    // function definition and `h` is the corresponding parameter of some
    // declaration of the same function.
    // 1. `this` is a definition and therefore must not be dependent to any
    // other definition.
    assert(dependent_to_ == nullptr);
    // 2. `h` must not be dependent to any other definition.
    assert(h->dependent_to_ == nullptr);
    // 3. `h` is in a declaration and therefore it must not have dependents.
    assert(h->list_of_dependent_.empty());
    list_of_dependent_.push_back(h);
    h->dependent_to_ = this;
  }

  void AddAsParameter(InterestingFunction* f) {
    if (function_ != nullptr && function_ != f) {
      llvm::outs()
          << "Warning: adding as a parameter to a different function\n";
    }
    function_ = f;
  }

  bool CanMigrate() const;
  Replacement GetReplacement() const { return replacement_.value(); }

  // This method registers a usage of an interesting variable. The first
  // parameter corresponds to the AST node where the variable is used,
  // whereas the second parameter advises if migration should be possible.
  // We want to disallow migration if a variable is used (at least once) in a
  // context where a `Handle<T>` is really required. When the AST is traversed
  // and a node with a variable usage is visited, the matcher callbacks will be
  // invoked consecutively for that node, in the order that they were added to
  // the match finder. These callbacks, independently from one another, may
  // invoke this method to advise whether migration should be possible.
  // Migration is prevented when this method is called for a variable's use for
  // the first time with migrate = false. If it has previously been called for
  // the same variable use with migrate = true, then migration is not prevented.
  // Evidently, the order in which the matcher callbacks are added to the finder
  // is very important. See the comment before `HandleUseVisitor` for a detailed
  // example.
  void RegisterUsage(const DeclRefExpr* use, bool migrate) {
    if (dependent_to_ != nullptr) {
      llvm::outs() << "Warning: use of handle that is marked as dependent\n";
    }
    if (use != previous_use_ && !migrate) {
      replacement_.reset();
    }
    previous_use_ = use;
  }

 private:
  InterestingHandle(const VarDecl* decl, bool is_definition)
      : is_definition_(is_definition),
        type_(decl->getType().getAsString()),
        location_(decl->getLocation()) {
    // If this is not a definition, bail out, otherwise let's be optimistic and
    // generate the replacement for migration!
    if (!is_definition_) {
      return;
    }

    // We get the |replacement_range| in a bit clumsy way, because clang docs
    // for QualifiedTypeLoc explicitly say that these objects "intentionally
    // do not provide source location for type qualifiers".
    const auto& source_manager = decl->getASTContext().getSourceManager();
    const auto& options = decl->getASTContext().getLangOpts();
    auto first_token_loc = source_manager.getSpellingLoc(decl->getBeginLoc());
    auto last_token_loc =
        source_manager.getSpellingLoc(decl->getTypeSpecEndLoc());
    auto end_loc =
        Lexer::getLocForEndOfToken(last_token_loc, 0, source_manager, options);
    auto range = CharSourceRange::getCharRange(first_token_loc, end_loc);

    auto original_text =
        Lexer::getSourceText(range, source_manager, options).str();
    std::regex re_handle("\\bHandle<");
    auto replacement_text =
        std::regex_replace(original_text, re_handle, "DirectHandle<");

    if (original_text != replacement_text) {
      replacement_.emplace(source_manager, range, replacement_text);
    }
  }

  bool is_definition_;
  std::string type_;
  SourceLocation location_;
  std::optional<Replacement> replacement_;
  const DeclRefExpr* previous_use_ = nullptr;

  // For parameters, this points to the corresponding function.
  InterestingFunction* function_ = nullptr;
  // For parameters of a function declaration, this points to the
  // corresponding parameter of the function definition.
  InterestingHandle* dependent_to_ = nullptr;
  // For parameters of a function definition, this contains a list
  // of all the corresponding parameters of function declarations (if any).
  std::vector<InterestingHandle*> list_of_dependent_;

  using Container = std::unordered_map<const VarDecl*,
                                       InterestingHandle,
                                       ASTNodeHash<VarDecl>,
                                       ASTNodeEquals<VarDecl>>;
  static Container interesting_;
};

InterestingHandle::Container InterestingHandle::interesting_;

// A database with all interesting functions.
class InterestingFunction {
 public:
  InterestingFunction(const InterestingFunction&) = delete;
  InterestingFunction(InterestingFunction&&) = default;

  static InterestingFunction* Insert(const FunctionDecl* decl) {
    assert(decl != nullptr);
    auto it = interesting_.find(decl);
    if (it == interesting_.end()) {
      auto p = interesting_.emplace(decl, InterestingFunction{decl});
      it = p.first;
    }
    return &it->second;
  }

  static InterestingFunction* Lookup(const FunctionDecl* decl) {
    assert(decl != nullptr);
    auto it = interesting_.find(decl);
    if (it == interesting_.end()) {
      return nullptr;
    }
    return &it->second;
  }

  void AddOrCheckParameter(const ParmVarDecl* param, InterestingHandle* p) {
    unsigned i = param->getFunctionScopeIndex();
    if (i >= parameters_.size()) {
      llvm::outs() << "Warning: parameter " << i
                   << " does not exist, there are only " << parameters_.size()
                   << " parameters\n";
      return;
    }
    if (parameters_[i] == nullptr) {
      parameters_[i] = p;
      p->AddAsParameter(this);
    } else if (parameters_[i] != p) {
      const auto& source_manager = param->getASTContext().getSourceManager();
      llvm::outs() << "Warning: parameter " << i << " has already been added\n";
      llvm::outs() << "  previous:\n";
      parameters_[i]->Print(source_manager);
      llvm::outs() << "  current:\n";
      p->Print(source_manager);
    }
  }

  void AddLocalVariable(InterestingHandle* v) { local_vars_.push_back(v); }

  const std::vector<InterestingHandle*>& parameters() const {
    return parameters_;
  }

  const std::vector<InterestingHandle*>& local_vars() const {
    return local_vars_;
  }

  bool is_special() const { return is_special_; }

  static std::set<Replacement> GetReplacements() {
    std::set<Replacement> result;
    for (const auto& [_, f] : interesting_) {
      for (InterestingHandle* p : f.parameters()) {
        if (p != nullptr && p->CanMigrate()) {
          result.insert(p->GetReplacement());
        }
      }
      for (InterestingHandle* v : f.local_vars()) {
        if (v->CanMigrate()) {
          result.insert(v->GetReplacement());
        }
      }
    }
    return result;
  }

 private:
  explicit InterestingFunction(const FunctionDecl* decl)
      : name_(decl->getQualifiedNameAsString()),
        location_(decl->getLocation()),
        parameters_(decl->getNumParams(), nullptr) {
    if (auto* method_decl = dyn_cast<CXXMethodDecl>(decl)) {
      is_special_ = method_decl->isVirtual();
    } else {
      is_special_ = decl->isTemplateInstantiation() ||
                    decl->isFunctionTemplateSpecialization();
    }
  }

  std::string name_;
  SourceLocation location_;
  bool is_special_ = false;
  std::vector<InterestingHandle*> parameters_;
  std::vector<InterestingHandle*> local_vars_;

  using Container = std::unordered_map<const FunctionDecl*,
                                       InterestingFunction,
                                       ASTNodeHash<FunctionDecl>,
                                       ASTNodeEquals<FunctionDecl>>;
  static Container interesting_;
};

InterestingFunction::Container InterestingFunction::interesting_;

bool InterestingHandle::CanMigrate() const {
  if (dependent_to_ != nullptr) {
    return dependent_to_->CanMigrate();
  }
  if (!is_definition_) {
    return false;
  }
  if (function_ != nullptr && function_->is_special()) {
    return false;
  }
  return replacement_.has_value();
}

// Keep track of where we are, in the AST.
// This is used only for debugging purposes.
// ----------------------------------------------------------------------------
class WhereWeAreVisitor : public MatchFinder::MatchCallback {
 private:
  static DeclarationMatcher matcher() { return decl().bind("decl"); }

 public:
  explicit WhereWeAreVisitor(MatchFinder& finder) {
    finder.addMatcher(matcher(), this);
  }

  void run(MatchFinder::MatchResult const& Result) override {
    auto* decl = Result.Nodes.getNodeAs<Decl>("decl");
    assert(decl != nullptr);

    if (VERBOSE >= kVerboseWhereAreWe) {
      ASTContext* context = Result.Context;
      auto loc = decl->getBeginLoc();
      llvm::outs() << "At: " << decl->getDeclKindName() << " ";
      loc.print(llvm::outs(), context->getSourceManager());
      llvm::outs() << "\n";
    }
  }
};

// Find and record interesting functions:
// - some parameter is a Handle<T>, or
// - the result is a Handle<T>, or
// - is a method of Handle<T>, because the object pointed to by `this` is a
// `Handle<T>`.
// ----------------------------------------------------------------------------
class InterestingFunctionVisitor : public MatchFinder::MatchCallback {
 private:
  static DeclarationMatcher matcher() {
    return functionDecl(anyOf(hasAnyParameter(parmVarDecl(hasType(handleType))),
                              returns(handleType),
                              cxxMethodDecl(ofClass(handleDecl))))
        .bind("interesting-function");
  }

 public:
  explicit InterestingFunctionVisitor(MatchFinder& finder,
                                      bool only_in_main_file = false)
      : only_in_main_file_(only_in_main_file) {
    finder.addMatcher(matcher(), this);
  }

  void run(MatchFinder::MatchResult const& Result) override {
    auto* decl = Result.Nodes.getNodeAs<FunctionDecl>("interesting-function");
    assert(decl != nullptr);

    if (only_in_main_file_) {
      ASTContext* context = Result.Context;
      if (!context->getSourceManager().isWrittenInMainFile(
              decl->getBeginLoc())) {
        return;
      }
    }

    InterestingFunction::Insert(decl);

    if (VERBOSE >= kVerboseReportInterestingFunctions) {
      ASTContext* context = Result.Context;
      auto loc = decl->getBeginLoc();
      llvm::outs() << "Func: ";
      loc.print(llvm::outs(), context->getSourceManager());
      llvm::outs() << "\n";
      llvm::outs() << "  name " << decl->getQualifiedNameAsString() << "\n";
      for (const auto& param : decl->parameters()) {
        auto type = param->getOriginalType();
        llvm::outs() << "  param " << param->getFunctionScopeIndex()
                     << " of type " << type.getAsString() << "\n";
      }
      auto result_type = decl->getCallResultType();
      llvm::outs() << "  result " << result_type.getAsString() << "\n";
      llvm::outs() << "  templated kind " << decl->getTemplatedKind() << "\n";
    }
  }

 private:
  bool only_in_main_file_;
};

// Find and record interesting variables.
// - of type Handle<T>; and
// - local variables or parameters.
// ----------------------------------------------------------------------------
class HandleDeclVisitor : public MatchFinder::MatchCallback {
 private:
  static DeclarationMatcher matcher() {
    return anyOf(
        varDecl(allOf(hasLocalStorage(), hasType(handleType),
                      hasAncestor(functionDecl().bind("func-decl"))))
            .bind("var-decl"),
        bindingDecl(allOf(hasType(handleType),
                          hasAncestor(functionDecl().bind("func-decl"))))
            .bind("binding-decl"));
  }

 public:
  explicit HandleDeclVisitor(MatchFinder& finder,
                             bool only_in_main_file = false)
      : only_in_main_file_(only_in_main_file) {
    finder.addMatcher(matcher(), this);
  }

  void run(MatchFinder::MatchResult const& Result) override {
    auto* decl = Result.Nodes.getNodeAs<VarDecl>("var-decl");
    if (decl == nullptr) {
      auto* binding = Result.Nodes.getNodeAs<BindingDecl>("binding-decl");
      assert(binding != nullptr);
      decl = binding->getHoldingVar();
      assert(decl != nullptr);
    }

    if (only_in_main_file_) {
      ASTContext* context = Result.Context;
      if (!context->getSourceManager().isWrittenInMainFile(
              decl->getBeginLoc())) {
        return;
      }
    }

    auto* func_decl = Result.Nodes.getNodeAs<FunctionDecl>("func-decl");
    assert(func_decl != nullptr);

    if (auto* param = dyn_cast<ParmVarDecl>(decl)) {
      auto* ctxt = param->getDeclContext();
      assert(ctxt != nullptr);
      auto type = param->getType();
      auto* func = dyn_cast<FunctionDecl>(ctxt);
      if (func == nullptr) {
        // TODO(42203211): This may happen, for example, if a handle parameter
        // is part of some other parameter's type, e.g.
        //
        //     void f(std::function<void(Handle<HeapObject>)> g);
        //
        // Migrating higher-order functions is out of the scope of this tool
        // right now. For migrating the definition of `f` here, we would need to
        // check all its call sites and see what the actual function passed as
        // the `g` parameter is. If the actual parameter can be migrated in all
        // cases to a function expecting a `DirectHandle`, then `f` can be
        // migrated, otherwise it cannot.
        //
        // Such cases are ignored now and we expect that they be migrated
        // manually.
        llvm::outs() << "Warning: this parameter does not lead to function "
                        "declaration\n";
        ASTContext* context = Result.Context;
        auto loc = decl->getBeginLoc();
        llvm::outs() << "Decl parm: ";
        loc.print(llvm::outs(), context->getSourceManager());
        llvm::outs() << "\n";
        llvm::outs() << "  type " << type.getAsString() << "\n";
        llvm::outs() << "  index " << param->getFunctionScopeIndex() << "\n";
        return;
      }
      if (func != func_decl) {
        llvm::outs() << "Warning: function declaration mismatch\n";
        llvm::outs() << "  func: " << *func << "\n";
        llvm::outs() << "  func_decl: " << *func_decl << "\n";
      }
      auto* f = InterestingFunction::Lookup(func_decl);
      if (f != nullptr && !func_decl->isDefaulted() &&
          !func_decl->isTemplateInstantiation()) {
        auto* p = InterestingHandle::Lookup(param);
        if (p == nullptr) {
          bool is_definition = func_decl->hasBody();
          p = InterestingHandle::Insert(param, is_definition);
          // If there's no function definition, nothing to be done yet.
          if (auto* func_def = func_decl->getDefinition()) {
            if (func_def == func_decl) {
              // If this is the function definition.
              assert(is_definition);
              // Look for all registered declarations of this function.
              for (const auto& prev_decl : func_decl->redecls()) {
                if (auto* d = InterestingFunction::Lookup(prev_decl)) {
                  // Mark the corresponding parameter of the declaration as
                  // dependent to this entry.
                  auto* q = d->parameters()[param->getFunctionScopeIndex()];
                  if (q != nullptr) {
                    p->AddDependent(q);
                  }
                }
              }
            } else if (auto* d = InterestingFunction::Lookup(func_def)) {
              // If there is a registered function definition, mark this entry
              // as dependent to the corresponding parameter of the function
              // definition.
              auto* q = d->parameters()[param->getFunctionScopeIndex()];
              assert(q != nullptr);
              q->AddDependent(p);
            }
          }
        }
        f->AddOrCheckParameter(param, p);
      }

      if (VERBOSE >= kVerboseReportInterestingHandleDecl) {
        ASTContext* context = Result.Context;
        auto loc = decl->getBeginLoc();
        llvm::outs() << "Decl parm: ";
        loc.print(llvm::outs(), context->getSourceManager());
        llvm::outs() << "\n";
        llvm::outs() << "  type " << type.getAsString() << "\n";
        llvm::outs() << "  index " << param->getFunctionScopeIndex() << "\n";
        llvm::outs() << "  func " << func->getQualifiedNameAsString() << "\n";
      }
    } else {
      auto* p = InterestingHandle::Insert(decl, true);
      auto* f = InterestingFunction::Lookup(func_decl);
      if (!func_decl->isDefaulted() && !func_decl->isTemplateInstantiation()) {
        if (f == nullptr) {
          assert(func_decl->hasBody());
          f = InterestingFunction::Insert(func_decl);
        }
        assert(f != nullptr);
        f->AddLocalVariable(p);
      }

      if (VERBOSE >= kVerboseReportInterestingHandleDecl) {
        ASTContext* context = Result.Context;
        auto loc = decl->getBeginLoc();
        llvm::outs() << "Decl var: ";
        loc.print(llvm::outs(), context->getSourceManager());
        llvm::outs() << "\n"
                     << "  type " << decl->getType().getAsString() << "\n";
      }
    }
  }

 private:
  bool only_in_main_file_;
};

// Find and process uses of handle parameters or variables.
//
// Tracking such uses is important, because we want to disallow the migration of
// a variable's type from `Handle<T>` to `DirectHandle<T>` if the variable is
// used (at least once) in a context where a `Handle<T>` is really required.
// In general, if a variable of type `Handle<T>` is used, we need to prevent the
// migration of a variable. This is the purpose of `HandleUseVisitor`. However,
// there are cases when such a variable is used in a manner that is compatible
// with a `DirectHandle<T>`, e.g., when the handle is dereferenced, or
// implicitly converted to a direct handle. In these cases there is no need to
// prevent the migration and this is the purpose of more specific visitors, such
// as `HandleDereferenceVisitor` or `ImplicitHandleToDirectHandleVisitor` below.
//
// As mentioned in the comment before `InterestingHandle::RegisterUsage`, the
// order in which visitors are executed is important. For a given variable
// usage, migration is prevented if the first executed visitor decides to
// prevent it.
//
// Consider the following example:
//
//     void consume_direct(DirectHandle<HeapObject> o);  /* line: 1 */
//     Handle<HeapObject> h;                             /* line: 2 */
//     consume_direct(h);                                /* line: 3 */
//     Tagged<Map> map = h->map();                       /* line: 4 */
//
// The use of variable `h` in line 3 will be processed by two visitors:
//
// 1. `HandleUseVisitor` (this one), which will claim that the use of this
//     variable is reason enough for disallowing its migration.
// 2. `ImplicitHandleToDirectHandleVisitor` (below), which will realize that
//    the handle is implicitly converted to a direct handle, therefore we can
//    allow its migration.
//
// Because visitor 1 is added last to the match finder (we rely on this),
// visitor 2 will run before visitor 1 for this node, thus not preventing the
// migration.
//
// Similarly, the use of variable `h` in line 4 will be processed by two
// visitors: first `HandleDereferenceVisitor` and then `HandleUseVisitor`, in
// this order, and migration will again not be prevented. As none of the
// variable's uses has prevented migration, the type of variable `h` in line 2
// will be migrated from `Handle<HeapObject>` to `DirectHandle<HeapObject>`.
// ----------------------------------------------------------------------------
class HandleUseVisitor : public MatchFinder::MatchCallback {
 public:
  static StatementMatcher matcher() {
    return declRefExpr(
               allOf(to(varDecl().bind("var-decl")), hasType(handleType),
                     hasAncestor(
                         functionDecl(allOf(isDefinition(), hasBody(stmt())))
                             .bind("func-def"))))
        .bind("handle-use");
  }

 public:
  explicit HandleUseVisitor(MatchFinder& finder, bool only_in_main_file = false)
      : only_in_main_file_(only_in_main_file) {
    finder.addMatcher(matcher(), this);
  }

  void run(MatchFinder::MatchResult const& Result) override {
    auto* use = Result.Nodes.getNodeAs<DeclRefExpr>("handle-use");
    assert(use != nullptr);
    auto* decl = Result.Nodes.getNodeAs<VarDecl>("var-decl");
    assert(decl != nullptr);
    auto* func = Result.Nodes.getNodeAs<FunctionDecl>("func-def");
    assert(func != nullptr);

    if (only_in_main_file_) {
      ASTContext* context = Result.Context;
      if (!context->getSourceManager().isWrittenInMainFile(
              use->getBeginLoc())) {
        return;
      }
    }

    auto* h = InterestingHandle::Lookup(decl);
    assert(h != nullptr || func->isDefaulted() ||
           func->isTemplateInstantiation());

    if (VERBOSE >= kVerboseReportInterestingHandleUse) {
      auto type = decl->getType();
      ASTContext* context = Result.Context;
      auto loc = use->getBeginLoc();
      llvm::outs() << "Use var: ";
      loc.print(llvm::outs(), context->getSourceManager());
      llvm::outs() << "\n";
      llvm::outs() << "  var of type " << type.getAsString() << "\n";
    }

    if (h != nullptr) {
      // This will disallow migration, unless some other more specific visitor
      // has already run and explicitly allowed migration for the same variable
      // usage. Here, we rely on the fact that `HandleUseVisitor` is added last
      // to the match finder, therefore it will run last for any given AST node.
      h->RegisterUsage(use, false);
    }
  }

 private:
  bool only_in_main_file_;
};

// Find and process calls to interesting functions.
// Currently, this does nothing interesting except for logging.
// ----------------------------------------------------------------------------
class CallExprWithHandleVisitor : public MatchFinder::MatchCallback {
 private:
  static StatementMatcher matcher() {
    return callExpr(hasAnyArgument(hasType(handleType))).bind("call-expr");
  }

 public:
  explicit CallExprWithHandleVisitor(MatchFinder& finder,
                                     bool only_in_main_file = false)
      : only_in_main_file_(only_in_main_file) {
    finder.addMatcher(matcher(), this);
  }

  void run(MatchFinder::MatchResult const& Result) override {
    auto* call = Result.Nodes.getNodeAs<CallExpr>("call-expr");
    assert(call != nullptr);

    if (only_in_main_file_) {
      ASTContext* context = Result.Context;
      if (!context->getSourceManager().isWrittenInMainFile(
              call->getBeginLoc())) {
        return;
      }
    }

    auto* decl = call->getCalleeDecl();
    // This happens when we have a call with an unresolved expression in a
    // template definition.
    if (decl == nullptr) {
      return;
    }
    auto* func = dyn_cast<FunctionDecl>(decl);
    if (func == nullptr) {
      llvm::outs() << "Warning: This is not a FunctionDecl but a "
                   << decl->getDeclKindName() << "\n";
      return;
    }

    if (VERBOSE >= kVerboseReportInterestingFunctionCall) {
      ASTContext* context = Result.Context;
      auto loc = call->getBeginLoc();
      llvm::outs() << "Call: ";
      loc.print(llvm::outs(), context->getSourceManager());
      llvm::outs() << "\n";
      llvm::outs() << "  callee " << func->getQualifiedNameAsString() << "\n";

      int i = 0;
      for (const auto& arg : call->arguments()) {
        auto type = arg->getType();
        llvm::outs() << "  param " << i << " of type " << type.getAsString()
                     << "\n";
        ++i;
      }
    }
  }

 private:
  bool only_in_main_file_;
};

// Implicit Handle<T> -> DirectHandle<T> conversions.
// They do not prevent handle migration.
// ----------------------------------------------------------------------------
class ImplicitHandleToDirectHandleVisitor : public MatchFinder::MatchCallback {
 private:
  static StatementMatcher matcher() {
    return implicitCastExpr(
               allOf(hasImplicitDestinationType(directHandleType),
                     hasCastKind(CK_ConstructorConversion),
                     hasSourceExpression(
                         constructorWithOneArgument(constructorWithOneArgument(
                             HandleUseVisitor::matcher())))))
        .bind("implicit-cast");
  }

 public:
  explicit ImplicitHandleToDirectHandleVisitor(MatchFinder& finder,
                                               bool only_in_main_file = false)
      : only_in_main_file_(only_in_main_file) {
    finder.addMatcher(matcher(), this);
  }

  void run(MatchFinder::MatchResult const& Result) override {
    auto* expr = Result.Nodes.getNodeAs<ImplicitCastExpr>("implicit-cast");
    assert(expr != nullptr);

    if (only_in_main_file_) {
      ASTContext* context = Result.Context;
      if (!context->getSourceManager().isWrittenInMainFile(
              expr->getBeginLoc())) {
        return;
      }
    }

    if (VERBOSE >= kVerboseReportImplicitHandleConversion) {
      ASTContext* context = Result.Context;
      auto loc = expr->getBeginLoc();
      llvm::outs() << "H->DH: ";
      loc.print(llvm::outs(), context->getSourceManager());
      llvm::outs() << "\n";
    }

    auto* use = Result.Nodes.getNodeAs<DeclRefExpr>("handle-use");
    assert(use != nullptr);
    auto* decl = Result.Nodes.getNodeAs<VarDecl>("var-decl");
    assert(decl != nullptr);

    auto* h = InterestingHandle::Lookup(decl);
    if (h != nullptr) {
      // This will allow migration for this variable usage.
      h->RegisterUsage(use, true);
    }
  }

 private:
  bool only_in_main_file_;
};

// Handle<T>::operator* and Handle<T>::operator->
// They do not prevent handle migration.
// ----------------------------------------------------------------------------
class HandleDereferenceVisitor : public MatchFinder::MatchCallback {
 private:
  static StatementMatcher matcher() {
    return cxxOperatorCallExpr(
               hasAnyOverloadedOperatorName("*", "->"),
               hasAnyArgument(ignoringImplicit(HandleUseVisitor::matcher())))
        .bind("handle-deref");
  }

 public:
  explicit HandleDereferenceVisitor(MatchFinder& finder,
                                    bool only_in_main_file = false)
      : only_in_main_file_(only_in_main_file) {
    finder.addMatcher(matcher(), this);
  }

  void run(MatchFinder::MatchResult const& Result) override {
    auto* expr = Result.Nodes.getNodeAs<CXXOperatorCallExpr>("handle-deref");
    assert(expr != nullptr);

    if (only_in_main_file_) {
      ASTContext* context = Result.Context;
      if (!context->getSourceManager().isWrittenInMainFile(
              expr->getBeginLoc())) {
        return;
      }
    }

    if (VERBOSE >= kVerboseReportHandleDereference) {
      ASTContext* context = Result.Context;
      auto loc = expr->getBeginLoc();
      llvm::outs() << "Handle deref: ";
      loc.print(llvm::outs(), context->getSourceManager());
      llvm::outs() << "\n";
    }

    auto* use = Result.Nodes.getNodeAs<DeclRefExpr>("handle-use");
    assert(use != nullptr);
    auto* decl = Result.Nodes.getNodeAs<VarDecl>("var-decl");
    assert(decl != nullptr);

    auto* h = InterestingHandle::Lookup(decl);
    if (h != nullptr) {
      // This will allow migration for this variable usage.
      h->RegisterUsage(use, true);
    }
  }

 private:
  bool only_in_main_file_;
};

// Main program.
// ----------------------------------------------------------------------------

int main(int argc, const char* argv[]) {
  auto expected_parser =
      CommonOptionsParser::create(argc, argv, my_tool_category);
  if (!expected_parser) {
    // Fail gracefully for unsupported options.
    llvm::errs() << expected_parser.takeError();
    return 1;
  }
  CommonOptionsParser& options_parser = expected_parser.get();
  ClangTool Tool(options_parser.getCompilations(),
                 options_parser.getSourcePathList());

  MatchFinder finder;
  std::optional<WhereWeAreVisitor> where_we_are_visitor;
  if (VERBOSE >= kVerboseWhereAreWe) {
    where_we_are_visitor.emplace(finder);
  }

  // These populate the database of functions and handle declarations.
  InterestingFunctionVisitor interesting_function_visitor(finder,
                                                          only_in_main_file);
  HandleDeclVisitor handle_decl_visitor(finder, only_in_main_file);
  // These allow migration in some special cases.
  HandleDereferenceVisitor handle_deref_callback(finder, only_in_main_file);
  ImplicitHandleToDirectHandleVisitor implicit_conversion_visitor(
      finder, only_in_main_file);
  // This is not used, except for logging.
  std::optional<CallExprWithHandleVisitor> call_expr_with_handle_visitor;
  if (VERBOSE >= kVerboseReportInterestingFunctionCall) {
    call_expr_with_handle_visitor.emplace(finder, only_in_main_file);
  }
  // This needs to be last, to disallow migration in all other cases.
  HandleUseVisitor handle_use_callback(finder, only_in_main_file);

  int error_code = Tool.run(newFrontendActionFactory(&finder).get());
  if (error_code) {
    return error_code;
  }

  std::set<Replacement> replacements = InterestingFunction::GetReplacements();
  if (replacements.empty()) {
    return 0;
  }

  // Serialization format is documented in tools/clang/scripts/run_tool.py
  llvm::outs() << "==== BEGIN EDITS ====\n";
  for (const auto& r : replacements) {
    std::string replacement_text = r.getReplacementText().str();
    std::replace(replacement_text.begin(), replacement_text.end(), '\n', '\0');
    llvm::outs() << "r:::" << r.getFilePath() << ":::" << r.getOffset()
                 << ":::" << r.getLength() << ":::" << replacement_text << "\n";
  }
  llvm::outs() << "==== END EDITS ====\n";

  return 0;
}