xref: /llvm-project/llvm/tools/llvm-mca/CodeRegion.cpp (revision 2946cd701067404b99c39fb29dc9c74bd7193eb3)
1 //===-------------------------- CodeRegion.cpp -----------------*- C++ -* -===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 ///
10 /// This file implements methods from the CodeRegions interface.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeRegion.h"
15 
16 namespace llvm {
17 namespace mca {
18 
19 bool CodeRegion::isLocInRange(llvm::SMLoc Loc) const {
20   if (RangeEnd.isValid() && Loc.getPointer() > RangeEnd.getPointer())
21     return false;
22   if (RangeStart.isValid() && Loc.getPointer() < RangeStart.getPointer())
23     return false;
24   return true;
25 }
26 
27 void CodeRegions::beginRegion(llvm::StringRef Description, llvm::SMLoc Loc) {
28   assert(!Regions.empty() && "Missing Default region");
29   const CodeRegion &CurrentRegion = *Regions.back();
30   if (CurrentRegion.startLoc().isValid() && !CurrentRegion.endLoc().isValid()) {
31     SM.PrintMessage(Loc, llvm::SourceMgr::DK_Warning,
32                     "Ignoring invalid region start");
33     return;
34   }
35 
36   // Remove the default region if there are user defined regions.
37   if (!CurrentRegion.startLoc().isValid())
38     Regions.erase(Regions.begin());
39   addRegion(Description, Loc);
40 }
41 
42 void CodeRegions::endRegion(llvm::SMLoc Loc) {
43   assert(!Regions.empty() && "Missing Default region");
44   CodeRegion &CurrentRegion = *Regions.back();
45   if (CurrentRegion.endLoc().isValid()) {
46     SM.PrintMessage(Loc, llvm::SourceMgr::DK_Warning,
47                     "Ignoring invalid region end");
48     return;
49   }
50 
51   CurrentRegion.setEndLocation(Loc);
52 }
53 
54 void CodeRegions::addInstruction(const llvm::MCInst &Instruction) {
55   const llvm::SMLoc &Loc = Instruction.getLoc();
56   const auto It =
57       std::find_if(Regions.rbegin(), Regions.rend(),
58                    [Loc](const std::unique_ptr<CodeRegion> &Region) {
59                      return Region->isLocInRange(Loc);
60                    });
61   if (It != Regions.rend())
62     (*It)->addInstruction(Instruction);
63 }
64 
65 } // namespace mca
66 } // namespace llvm
67