LLVM 24.0.0git
CoverageMapping.cpp
Go to the documentation of this file.
1//===- CoverageMapping.cpp - Code coverage mapping support ----------------===//
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//
9// This file contains support for clang's and llvm's instrumentation based
10// code coverage.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/Object/BuildID.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Support/Errc.h"
27#include "llvm/Support/Error.h"
32#include <algorithm>
33#include <cassert>
34#include <cstdint>
35#include <iterator>
36#include <map>
37#include <memory>
38#include <optional>
39#include <stack>
40#include <string>
41#include <system_error>
42#include <utility>
43#include <vector>
44
45using namespace llvm;
46using namespace coverage;
47
48#define DEBUG_TYPE "coverage-mapping"
49
50Counter CounterExpressionBuilder::get(const CounterExpression &E) {
51 auto [It, Inserted] = ExpressionIndices.try_emplace(E, Expressions.size());
52 if (Inserted)
53 Expressions.push_back(E);
54 return Counter::getExpression(It->second);
55}
56
57void CounterExpressionBuilder::extractTerms(Counter C, int Factor,
58 SmallVectorImpl<Term> &Terms) {
59 switch (C.getKind()) {
60 case Counter::Zero:
61 break;
63 Terms.emplace_back(C.getCounterID(), Factor);
64 break;
66 const auto &E = Expressions[C.getExpressionID()];
67 extractTerms(E.LHS, Factor, Terms);
68 extractTerms(
69 E.RHS, E.Kind == CounterExpression::Subtract ? -Factor : Factor, Terms);
70 break;
71 }
72}
73
74Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) {
75 // Gather constant terms.
77 extractTerms(ExpressionTree, +1, Terms);
78
79 // If there are no terms, this is just a zero. The algorithm below assumes at
80 // least one term.
81 if (Terms.size() == 0)
82 return Counter::getZero();
83
84 // Group the terms by counter ID.
85 llvm::sort(Terms, [](const Term &LHS, const Term &RHS) {
86 return LHS.CounterID < RHS.CounterID;
87 });
88
89 // Combine terms by counter ID to eliminate counters that sum to zero.
90 auto Prev = Terms.begin();
91 for (auto I = Prev + 1, E = Terms.end(); I != E; ++I) {
92 if (I->CounterID == Prev->CounterID) {
93 Prev->Factor += I->Factor;
94 continue;
95 }
96 ++Prev;
97 *Prev = *I;
98 }
99 Terms.erase(++Prev, Terms.end());
100
101 Counter C;
102 // Create additions. We do this before subtractions to avoid constructs like
103 // ((0 - X) + Y), as opposed to (Y - X).
104 for (auto T : Terms) {
105 if (T.Factor <= 0)
106 continue;
107 for (int I = 0; I < T.Factor; ++I)
108 if (C.isZero())
109 C = Counter::getCounter(T.CounterID);
110 else
111 C = get(CounterExpression(CounterExpression::Add, C,
112 Counter::getCounter(T.CounterID)));
113 }
114
115 // Create subtractions.
116 for (auto T : Terms) {
117 if (T.Factor >= 0)
118 continue;
119 for (int I = 0; I < -T.Factor; ++I)
120 C = get(CounterExpression(CounterExpression::Subtract, C,
121 Counter::getCounter(T.CounterID)));
122 }
123 return C;
124}
125
127 auto Cnt = get(CounterExpression(CounterExpression::Add, LHS, RHS));
128 return Simplify ? simplify(Cnt) : Cnt;
129}
130
132 bool Simplify) {
133 auto Cnt = get(CounterExpression(CounterExpression::Subtract, LHS, RHS));
134 return Simplify ? simplify(Cnt) : Cnt;
135}
136
138 // Replace C with the value found in Map even if C is Expression.
139 if (auto I = Map.find(C); I != Map.end())
140 return I->second;
141
142 if (!C.isExpression())
143 return C;
144
145 auto CE = Expressions[C.getExpressionID()];
146 auto NewLHS = subst(CE.LHS, Map);
147 auto NewRHS = subst(CE.RHS, Map);
148
149 // Reconstruct Expression with induced subexpressions.
150 switch (CE.Kind) {
152 C = add(NewLHS, NewRHS);
153 break;
155 C = subtract(NewLHS, NewRHS);
156 break;
157 }
158
159 return C;
160}
161
163 switch (C.getKind()) {
164 case Counter::Zero:
165 OS << '0';
166 return;
168 OS << '#' << C.getCounterID();
169 break;
170 case Counter::Expression: {
171 if (C.getExpressionID() >= Expressions.size())
172 return;
173 const auto &E = Expressions[C.getExpressionID()];
174 OS << '(';
175 dump(E.LHS, OS);
176 OS << (E.Kind == CounterExpression::Subtract ? " - " : " + ");
177 dump(E.RHS, OS);
178 OS << ')';
179 break;
180 }
181 }
182 if (CounterValues.empty())
183 return;
185 if (auto E = Value.takeError()) {
186 consumeError(std::move(E));
187 return;
188 }
189 OS << '[' << *Value << ']';
190}
191
193 struct StackElem {
194 Counter ICounter;
195 int64_t LHS = 0;
196 enum {
197 KNeverVisited = 0,
198 KVisitedOnce = 1,
199 KVisitedTwice = 2,
200 } VisitCount = KNeverVisited;
201 };
202
203 std::stack<StackElem> CounterStack;
204 CounterStack.push({C});
205
206 int64_t LastPoppedValue;
207
208 while (!CounterStack.empty()) {
209 StackElem &Current = CounterStack.top();
210
211 switch (Current.ICounter.getKind()) {
212 case Counter::Zero:
213 LastPoppedValue = 0;
214 CounterStack.pop();
215 break;
217 if (Current.ICounter.getCounterID() >= CounterValues.size())
219 LastPoppedValue = CounterValues[Current.ICounter.getCounterID()];
220 CounterStack.pop();
221 break;
222 case Counter::Expression: {
223 if (Current.ICounter.getExpressionID() >= Expressions.size())
225 const auto &E = Expressions[Current.ICounter.getExpressionID()];
226 if (Current.VisitCount == StackElem::KNeverVisited) {
227 CounterStack.push(StackElem{E.LHS});
228 Current.VisitCount = StackElem::KVisitedOnce;
229 } else if (Current.VisitCount == StackElem::KVisitedOnce) {
230 Current.LHS = LastPoppedValue;
231 CounterStack.push(StackElem{E.RHS});
232 Current.VisitCount = StackElem::KVisitedTwice;
233 } else {
234 int64_t LHS = Current.LHS;
235 int64_t RHS = LastPoppedValue;
236 LastPoppedValue =
237 E.Kind == CounterExpression::Subtract ? LHS - RHS : LHS + RHS;
238 CounterStack.pop();
239 }
240 break;
241 }
242 }
243 }
244
245 return LastPoppedValue;
246}
247
248// Find an independence pair for each condition:
249// - The condition is true in one test and false in the other.
250// - The decision outcome is true one test and false in the other.
251// - All other conditions' values must be equal or marked as "don't care".
253 if (IndependencePairs)
254 return;
255
256 IndependencePairs.emplace();
257
258 unsigned NumTVs = TV.size();
259 // Will be replaced to shorter expr.
260 unsigned TVTrueIdx = std::distance(
261 TV.begin(),
262 llvm::find_if(TV,
263 [&](auto I) { return (I.second == MCDCRecord::MCDC_True); })
264
265 );
266 for (unsigned I = TVTrueIdx; I < NumTVs; ++I) {
267 const auto &[A, ACond] = TV[I];
269 for (unsigned J = 0; J < TVTrueIdx; ++J) {
270 const auto &[B, BCond] = TV[J];
272 // If the two vectors differ in exactly one condition, ignoring DontCare
273 // conditions, we have found an independence pair.
274 auto AB = A.getDifferences(B);
275 if (AB.count() == 1)
276 IndependencePairs->insert(
277 {AB.find_first(), std::make_pair(J + 1, I + 1)});
278 }
279 }
280}
281
283 int Offset)
284 : Indices(NextIDs.size()) {
285 // Construct Nodes and set up each InCount
286 auto N = NextIDs.size();
288 for (unsigned ID = 0; ID < N; ++ID) {
289 for (unsigned C = 0; C < 2; ++C) {
290#ifndef NDEBUG
291 Indices[ID][C] = INT_MIN;
292#endif
293 auto NextID = NextIDs[ID][C];
294 Nodes[ID].NextIDs[C] = NextID;
295 if (NextID >= 0)
296 ++Nodes[NextID].InCount;
297 }
298 }
299
300 // Sort key ordered by <-Width, Ord>
301 SmallVector<std::tuple<int, /// -Width
302 unsigned, /// Ord
303 int, /// ID
304 unsigned /// Cond (0 or 1)
305 >>
306 Decisions;
307
308 // Traverse Nodes to assign Idx
310 assert(Nodes[0].InCount == 0);
311 Nodes[0].Width = 1;
312 Q.push_back(0);
313
314 unsigned Ord = 0;
315 while (!Q.empty()) {
316 auto IID = Q.begin();
317 int ID = *IID;
318 Q.erase(IID);
319 auto &Node = Nodes[ID];
320 assert(Node.Width > 0);
321
322 for (unsigned I = 0; I < 2; ++I) {
323 auto NextID = Node.NextIDs[I];
324 assert(NextID != 0 && "NextID should not point to the top");
325 if (NextID < 0) {
326 // Decision
327 Decisions.emplace_back(-Node.Width, Ord++, ID, I);
328 assert(Ord == Decisions.size());
329 continue;
330 }
331
332 // Inter Node
333 auto &NextNode = Nodes[NextID];
334 assert(NextNode.InCount > 0);
335
336 // Assign Idx
337 assert(Indices[ID][I] == INT_MIN);
338 Indices[ID][I] = NextNode.Width;
339 auto NextWidth = int64_t(NextNode.Width) + Node.Width;
340 if (NextWidth > HardMaxTVs) {
341 NumTestVectors = HardMaxTVs; // Overflow
342 return;
343 }
344 NextNode.Width = NextWidth;
345
346 // Ready if all incomings are processed.
347 // Or NextNode.Width hasn't been confirmed yet.
348 if (--NextNode.InCount == 0)
349 Q.push_back(NextID);
350 }
351 }
352
353 llvm::sort(Decisions);
354
355 // Assign TestVector Indices in Decision Nodes
356 int64_t CurIdx = 0;
357 for (auto [NegWidth, Ord, ID, C] : Decisions) {
358 int Width = -NegWidth;
359 assert(Nodes[ID].Width == Width);
360 assert(Nodes[ID].NextIDs[C] < 0);
361 assert(Indices[ID][C] == INT_MIN);
362 Indices[ID][C] = Offset + CurIdx;
363 CurIdx += Width;
364 if (CurIdx > HardMaxTVs) {
365 NumTestVectors = HardMaxTVs; // Overflow
366 return;
367 }
368 }
369
370 assert(CurIdx < HardMaxTVs);
371 NumTestVectors = CurIdx;
372
373#ifndef NDEBUG
374 for (const auto &Idxs : Indices)
375 for (auto Idx : Idxs)
376 assert(Idx != INT_MIN);
377 SavedNodes = std::move(Nodes);
378#endif
379}
380
381namespace {
382
383/// Construct this->NextIDs with Branches for TVIdxBuilder to use it
384/// before MCDCRecordProcessor().
385class NextIDsBuilder {
386protected:
388
389public:
390 NextIDsBuilder(const ArrayRef<const CounterMappingRegion *> Branches)
391 : NextIDs(Branches.size()) {
392#ifndef NDEBUG
394#endif
395 for (const auto *Branch : Branches) {
396 const auto &BranchParams = Branch->getBranchParams();
397 assert(SeenIDs.insert(BranchParams.ID).second && "Duplicate CondID");
398 NextIDs[BranchParams.ID] = BranchParams.Conds;
399 }
400 assert(SeenIDs.size() == Branches.size());
401 }
402};
403
404class MCDCRecordProcessor : NextIDsBuilder, mcdc::TVIdxBuilder {
405 /// A bitmap representing the executed test vectors for a boolean expression.
406 /// Each index of the bitmap corresponds to a possible test vector. An index
407 /// with a bit value of '1' indicates that the corresponding Test Vector
408 /// identified by that index was executed.
409 const BitVector &Bitmap;
410
411 /// Decision Region to which the ExecutedTestVectorBitmap applies.
413 const mcdc::DecisionParameters &DecisionParams;
414
415 /// Array of branch regions corresponding each conditions in the boolean
416 /// expression.
418
419 /// Total number of conditions in the boolean expression.
420 unsigned NumConditions;
421
422 /// Vector used to track whether a condition is constant folded.
424
425 /// Helper for sorting ExecVectors / NotExecVectors.
426 struct TVIdxTuple {
427 MCDCRecord::CondState MCDCCond; /// True/False
428 unsigned BIdx; /// Bitmap Index
429 unsigned Ord; /// Last position in exec / not-exec TVs
430
431 TVIdxTuple(MCDCRecord::CondState MCDCCond, unsigned BIdx, unsigned Ord)
432 : MCDCCond(MCDCCond), BIdx(BIdx), Ord(Ord) {}
433
434 bool operator<(const TVIdxTuple &RHS) const {
435 return (std::tie(this->MCDCCond, this->BIdx, this->Ord) <
436 std::tie(RHS.MCDCCond, RHS.BIdx, RHS.Ord));
437 }
438 };
439
440 std::vector<TVIdxTuple> ExecVectorIdxs;
441 std::vector<TVIdxTuple> NotExecVectorIdxs;
442
443 /// Actual executed Test Vectors for the boolean expression, based on
444 /// ExecutedTestVectorBitmap.
445 MCDCRecord::TestVectors ExecVectors;
446 /// Never-executed test vectors
447 MCDCRecord::TestVectors NotExecVectors;
448
449#ifndef NDEBUG
450 DenseSet<unsigned> TVIdxs;
451#endif
452
453 bool IsVersion11;
454
455public:
456 MCDCRecordProcessor(const BitVector &Bitmap,
457 const CounterMappingRegion &Region,
459 bool IsVersion11)
460 : NextIDsBuilder(Branches), TVIdxBuilder(this->NextIDs), Bitmap(Bitmap),
461 Region(Region), DecisionParams(Region.getDecisionParams()),
462 Branches(Branches), NumConditions(DecisionParams.NumConditions),
463 Folded{{BitVector(NumConditions), BitVector(NumConditions)}},
464 IsVersion11(IsVersion11) {}
465
466private:
467 // Walk the binary decision diagram and try assigning both false and true to
468 // each node. When a terminal node (ID == 0) is reached, fill in the value in
469 // the truth table.
470 void buildTestVector(MCDCRecord::TestVector &TV, mcdc::ConditionID ID,
471 int TVIdx) {
472 for (auto MCDCCond : {MCDCRecord::MCDC_False, MCDCRecord::MCDC_True}) {
473 static_assert(MCDCRecord::MCDC_False == 0);
474 static_assert(MCDCRecord::MCDC_True == 1);
475 TV.set(ID, MCDCCond);
476 auto NextID = NextIDs[ID][MCDCCond];
477 auto NextTVIdx = TVIdx + Indices[ID][MCDCCond];
478 assert(NextID == SavedNodes[ID].NextIDs[MCDCCond]);
479 if (NextID >= 0) {
480 buildTestVector(TV, NextID, NextTVIdx);
481 continue;
482 }
483
484 assert(TVIdx < SavedNodes[ID].Width);
485 assert(TVIdxs.insert(NextTVIdx).second && "Duplicate TVIdx");
486
487 bool Executed =
488 Bitmap[IsVersion11
489 ? DecisionParams.BitmapIdx * CHAR_BIT + TV.getIndex()
490 : DecisionParams.BitmapIdx - NumTestVectors + NextTVIdx];
491 if (Executed) {
492 ExecVectorIdxs.emplace_back(MCDCCond, NextTVIdx, ExecVectors.size());
493 // Copy the completed test vector to the vector of testvectors.
494 // The final value (T,F) is equal to the last non-dontcare state on the
495 // path (in a short-circuiting system).
496 ExecVectors.push_back({TV, MCDCCond});
497 } else {
498 NotExecVectorIdxs.emplace_back(MCDCCond, NextTVIdx,
499 NotExecVectors.size());
500 NotExecVectors.push_back({TV, MCDCCond});
501 }
502 }
503
504 // Reset back to DontCare.
506 }
507
508 /// Walk the bits in the bitmap. A bit set to '1' indicates that the test
509 /// vector at the corresponding index was executed during a test run.
510 /// Vectors with '0' bit are collected separately for UI.
511 void findTestVectors() {
512 // Walk the binary decision diagram to enumerate all possible test vectors.
513 // We start at the root node (ID == 0) with all values being DontCare.
514 // `TVIdx` starts with 0 and is in the traversal.
515 // `Index` encodes the bitmask of true values and is initially 0.
516 MCDCRecord::TestVector TV(NumConditions);
517 buildTestVector(TV, 0, 0);
518 assert(TVIdxs.size() == unsigned(NumTestVectors) &&
519 "TVIdxs wasn't fulfilled");
520
521 llvm::sort(ExecVectorIdxs);
523 for (const auto &IdxTuple : ExecVectorIdxs)
524 NewExec.push_back(std::move(ExecVectors[IdxTuple.Ord]));
525 ExecVectors = std::move(NewExec);
526
527 llvm::sort(NotExecVectorIdxs);
528 MCDCRecord::TestVectors NewNotExec;
529 for (const auto &IdxTuple : NotExecVectorIdxs)
530 NewNotExec.push_back(std::move(NotExecVectors[IdxTuple.Ord]));
531 NotExecVectors = std::move(NewNotExec);
532 }
533
534public:
535 /// Process the MC/DC Record in order to produce a result for a boolean
536 /// expression. This process includes tracking the conditions that comprise
537 /// the decision region, calculating the list of all possible test vectors,
538 /// marking the executed test vectors, and then finding an Independence Pair
539 /// out of the executed test vectors for each condition in the boolean
540 /// expression. A condition is tracked to ensure that its ID can be mapped to
541 /// its ordinal position in the boolean expression. The condition's source
542 /// location is also tracked, as well as whether it is constant folded (in
543 /// which case it is excuded from the metric).
544 MCDCRecord processMCDCRecord() {
545 MCDCRecord::CondIDMap PosToID;
547
548 // Walk the Record's BranchRegions (representing Conditions) in order to:
549 // - Hash the condition based on its corresponding ID. This will be used to
550 // calculate the test vectors.
551 // - Keep a map of the condition's ordinal position (1, 2, 3, 4) to its
552 // actual ID. This will be used to visualize the conditions in the
553 // correct order.
554 // - Keep track of the condition source location. This will be used to
555 // visualize where the condition is.
556 // - Record whether the condition is constant folded so that we exclude it
557 // from being measured.
558 for (auto [I, B] : enumerate(Branches)) {
559 const auto &BranchParams = B->getBranchParams();
560 PosToID[I] = BranchParams.ID;
561 CondLoc[I] = B->startLoc();
562 Folded[false][I] = B->FalseCount.isZero();
563 Folded[true][I] = B->Count.isZero();
564 }
565
566 // Using Profile Bitmap from runtime, mark the test vectors.
567 findTestVectors();
568
569 // Record executed vectors, not-executed vectors, and independence pairs.
570 return MCDCRecord(Region, std::move(ExecVectors), std::move(NotExecVectors),
571 std::move(Folded), std::move(PosToID),
572 std::move(CondLoc));
573 }
574};
575
576} // namespace
577
580 ArrayRef<const CounterMappingRegion *> Branches, bool IsVersion11) {
581
582 MCDCRecordProcessor MCDCProcessor(Bitmap, Region, Branches, IsVersion11);
583 return MCDCProcessor.processMCDCRecord();
584}
585
587 struct StackElem {
588 Counter ICounter;
589 int64_t LHS = 0;
590 enum {
591 KNeverVisited = 0,
592 KVisitedOnce = 1,
593 KVisitedTwice = 2,
594 } VisitCount = KNeverVisited;
595 };
596
597 std::stack<StackElem> CounterStack;
598 CounterStack.push({C});
599
600 int64_t LastPoppedValue;
601
602 while (!CounterStack.empty()) {
603 StackElem &Current = CounterStack.top();
604
605 switch (Current.ICounter.getKind()) {
606 case Counter::Zero:
607 LastPoppedValue = 0;
608 CounterStack.pop();
609 break;
611 LastPoppedValue = Current.ICounter.getCounterID();
612 CounterStack.pop();
613 break;
614 case Counter::Expression: {
615 if (Current.ICounter.getExpressionID() >= Expressions.size()) {
616 LastPoppedValue = 0;
617 CounterStack.pop();
618 } else {
619 const auto &E = Expressions[Current.ICounter.getExpressionID()];
620 if (Current.VisitCount == StackElem::KNeverVisited) {
621 CounterStack.push(StackElem{E.LHS});
622 Current.VisitCount = StackElem::KVisitedOnce;
623 } else if (Current.VisitCount == StackElem::KVisitedOnce) {
624 Current.LHS = LastPoppedValue;
625 CounterStack.push(StackElem{E.RHS});
626 Current.VisitCount = StackElem::KVisitedTwice;
627 } else {
628 int64_t LHS = Current.LHS;
629 int64_t RHS = LastPoppedValue;
630 LastPoppedValue = std::max(LHS, RHS);
631 CounterStack.pop();
632 }
633 }
634 break;
635 }
636 }
637 }
638
639 return LastPoppedValue;
640}
641
642void FunctionRecordIterator::skipOtherFiles() {
643 while (Current != Records.end() && !Filename.empty() &&
644 Filename != Current->Filenames[0])
645 advanceOne();
646 if (Current == Records.end())
647 *this = FunctionRecordIterator();
648}
649
650ArrayRef<unsigned> CoverageMapping::getImpreciseRecordIndicesForFilename(
651 StringRef Filename) const {
652 size_t FilenameHash = hash_value(Filename);
653 auto RecordIt = FilenameHash2RecordIndices.find(FilenameHash);
654 if (RecordIt == FilenameHash2RecordIndices.end())
655 return {};
656 return RecordIt->second;
657}
658
659static unsigned getMaxCounterID(const CounterMappingContext &Ctx,
661 unsigned MaxCounterID = 0;
662 for (const auto &Region : Record.MappingRegions) {
663 MaxCounterID = std::max(MaxCounterID, Ctx.getMaxCounterID(Region.Count));
664 if (Region.isBranch())
665 MaxCounterID =
666 std::max(MaxCounterID, Ctx.getMaxCounterID(Region.FalseCount));
667 }
668 return MaxCounterID;
669}
670
671/// Returns the bit count
673 bool IsVersion11) {
674 unsigned MaxBitmapIdx = 0;
675 unsigned NumConditions = 0;
676 // Scan max(BitmapIdx).
677 // Note that `<=` is used insted of `<`, because `BitmapIdx == 0` is valid
678 // and `MaxBitmapIdx is `unsigned`. `BitmapIdx` is unique in the record.
679 for (const auto &Region : reverse(Record.MappingRegions)) {
681 continue;
682 const auto &DecisionParams = Region.getDecisionParams();
683 if (MaxBitmapIdx <= DecisionParams.BitmapIdx) {
684 MaxBitmapIdx = DecisionParams.BitmapIdx;
685 NumConditions = DecisionParams.NumConditions;
686 }
687 }
688
689 if (IsVersion11)
690 MaxBitmapIdx = MaxBitmapIdx * CHAR_BIT +
691 llvm::alignTo(uint64_t(1) << NumConditions, CHAR_BIT);
692
693 return MaxBitmapIdx;
694}
695
696namespace {
697
698/// Walk MappingRegions along Expansions and emit CountedRegions.
699struct CountedRegionEmitter {
700 /// A nestable Decision.
701 struct DecisionRecord {
702 const CounterMappingRegion *DecisionRegion;
703 unsigned NumConditions; ///< Copy of DecisionRegion.NumConditions
704 /// Pushed by traversal order.
706#ifndef NDEBUG
707 DenseSet<mcdc::ConditionID> ConditionIDs;
708#endif
709
710 DecisionRecord(const CounterMappingRegion &Decision)
711 : DecisionRegion(&Decision),
712 NumConditions(Decision.getDecisionParams().NumConditions) {
714 }
715
716 bool pushBranch(const CounterMappingRegion &B) {
718 assert(ConditionIDs.insert(B.getBranchParams().ID).second &&
719 "Duplicate CondID");
720 MCDCBranches.push_back(&B);
721 assert(MCDCBranches.size() <= NumConditions &&
722 "MCDCBranch exceeds NumConds");
723 return (MCDCBranches.size() == NumConditions);
724 }
725 };
726
727 const CoverageMappingRecord &Record;
728 CounterMappingContext &Ctx;
729 FunctionRecord &Function;
730 bool IsVersion11;
731
732 /// Evaluated Counters.
733 std::map<Counter, uint64_t> CounterValues;
734
735 /// Decisions are nestable.
736 SmallVector<DecisionRecord, 1> DecisionStack;
737
738 /// A File pointed by Expansion
739 struct FileInfo {
740 /// The last index(+1) for each FileID in MappingRegions.
741 unsigned LastIndex = 0;
742 /// Mark Files pointed by Expansions.
743 /// Non-marked Files are root Files.
744 bool IsExpanded = false;
745 };
746
747 /// The last element is a sentinel with Index=NumRegions.
748 std::vector<FileInfo> Files;
749#ifndef NDEBUG
750 DenseSet<unsigned> Visited;
751#endif
752
753 CountedRegionEmitter(const CoverageMappingRecord &Record,
754 CounterMappingContext &Ctx, FunctionRecord &Function,
755 bool IsVersion11)
756 : Record(Record), Ctx(Ctx), Function(Function), IsVersion11(IsVersion11),
757 Files(Record.Filenames.size()) {
758 // Scan MappingRegions and mark each last index by FileID.
759 for (auto [I, Region] : enumerate(Record.MappingRegions)) {
760 if (Region.FileID >= Files.size()) {
761 // Extend (only possible in CoverageMappingTests)
762 Files.resize(Region.FileID + 1);
763 }
764 Files[Region.FileID].LastIndex = I + 1;
766 if (Region.ExpandedFileID >= Files.size()) {
767 // Extend (only possible in CoverageMappingTests)
768 Files.resize(Region.ExpandedFileID + 1);
769 }
770 Files[Region.ExpandedFileID].IsExpanded = true;
771 }
772 }
773 }
774
775 /// Evaluate C and store its evaluated Value into CounterValues.
776 Error evaluateAndCacheCounter(Counter C) {
777 if (CounterValues.count(C) > 0)
778 return Error::success();
779
780 auto ValueOrErr = Ctx.evaluate(C);
781 if (!ValueOrErr)
782 return ValueOrErr.takeError();
783 CounterValues[C] = *ValueOrErr;
784 return Error::success();
785 }
786
787 Error walk(unsigned Idx) {
788 assert(Idx < Files.size());
789 unsigned B = (Idx == 0 ? 0 : Files[Idx - 1].LastIndex);
790 unsigned E = Files[Idx].LastIndex;
791 assert(B != E && "Empty FileID");
792 assert(Visited.insert(Idx).second && "Duplicate Expansions");
793 for (unsigned I = B; I != E; ++I) {
794 const auto &Region = Record.MappingRegions[I];
795 if (Region.FileID != Idx)
796 break;
797
799 if (auto E = walk(Region.ExpandedFileID))
800 return E;
801
802 if (auto E = evaluateAndCacheCounter(Region.Count))
803 return E;
804
806 // Start the new Decision on the stack.
807 DecisionStack.emplace_back(Region);
809 assert(!DecisionStack.empty() && "Orphan MCDCBranch");
810 auto &D = DecisionStack.back();
811
812 if (D.pushBranch(Region)) {
813 // All Branches have been found in the Decision.
814 auto RecordOrErr = Ctx.evaluateMCDCRegion(
815 *D.DecisionRegion, D.MCDCBranches, IsVersion11);
816 if (!RecordOrErr)
817 return RecordOrErr.takeError();
818
819 // Finish the stack.
820 Function.pushMCDCRecord(std::move(*RecordOrErr));
821 DecisionStack.pop_back();
822 }
823 }
824
825 // Evaluate FalseCount
826 // It may have the Counter in Branches, or Zero.
827 if (auto E = evaluateAndCacheCounter(Region.FalseCount))
828 return E;
829 }
830
831 assert((Idx != 0 || DecisionStack.empty()) && "Decision wasn't closed");
832
833 return Error::success();
834 }
835
836 Error emitCountedRegions() {
837 // Walk MappingRegions along Expansions.
838 // - Evaluate Counters
839 // - Emit MCDCRecords
840 for (auto [I, F] : enumerate(Files)) {
841 if (!F.IsExpanded)
842 if (auto E = walk(I))
843 return E;
844 }
845 assert(Visited.size() == Files.size() && "Dangling FileID");
846
847 // Emit CountedRegions in the same order as MappingRegions.
848 for (const auto &Region : Record.MappingRegions) {
850 continue; // Don't emit.
851 // Adopt values from the CounterValues.
852 // FalseCount may be Zero unless Branches.
853 Function.pushRegion(Region, CounterValues[Region.Count],
854 CounterValues[Region.FalseCount]);
855 }
856
857#ifndef NDEBUG
858 // Region lookups assume FileID order.
859 auto ByFileID = [](const CountedRegion &L, const CountedRegion &R) {
860 return L.FileID < R.FileID;
861 };
862 assert(llvm::is_sorted(Function.CountedRegions, ByFileID) &&
863 "CountedRegions must be sorted by FileID");
864 assert(llvm::is_sorted(Function.CountedBranchRegions, ByFileID) &&
865 "CountedBranchRegions must be sorted by FileID");
866#endif
867
868 return Error::success();
869 }
870};
871
872} // namespace
873
874Error CoverageMapping::loadFunctionRecord(
875 const CoverageMappingRecord &Record,
876 const std::optional<std::reference_wrapper<IndexedInstrProfReader>>
877 &ProfileReader) {
878 StringRef OrigFuncName = Record.FunctionName;
879 if (OrigFuncName.empty())
881 "record function name is empty");
882
883 if (Record.Filenames.empty())
884 OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName);
885 else
886 OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName, Record.Filenames[0]);
887
888 CounterMappingContext Ctx(Record.Expressions);
889
890 std::vector<uint64_t> Counts;
891 if (ProfileReader) {
892 if (Error E = ProfileReader.value().get().getFunctionCounts(
893 Record.FunctionName, Record.FunctionHash, Counts)) {
894 instrprof_error IPE = std::get<0>(InstrProfError::take(std::move(E)));
896 FuncHashMismatches.emplace_back(std::string(Record.FunctionName),
897 Record.FunctionHash);
898 return Error::success();
899 }
901 return make_error<InstrProfError>(IPE);
902 Counts.assign(getMaxCounterID(Ctx, Record) + 1, 0);
903 }
904 } else {
905 Counts.assign(getMaxCounterID(Ctx, Record) + 1, 0);
906 }
907 Ctx.setCounts(Counts);
908
909 bool IsVersion11 =
910 ProfileReader && ProfileReader.value().get().getVersion() <
912
913 BitVector Bitmap;
914 if (ProfileReader) {
915 if (Error E = ProfileReader.value().get().getFunctionBitmap(
916 Record.FunctionName, Record.FunctionHash, Bitmap)) {
917 instrprof_error IPE = std::get<0>(InstrProfError::take(std::move(E)));
919 FuncHashMismatches.emplace_back(std::string(Record.FunctionName),
920 Record.FunctionHash);
921 return Error::success();
922 }
924 return make_error<InstrProfError>(IPE);
925 Bitmap = BitVector(getMaxBitmapSize(Record, IsVersion11));
926 }
927 } else {
928 Bitmap = BitVector(getMaxBitmapSize(Record, false));
929 }
930 Ctx.setBitmap(std::move(Bitmap));
931
932 assert(!Record.MappingRegions.empty() && "Function has no regions");
933
934 // This coverage record is a zero region for a function that's unused in
935 // some TU, but used in a different TU. Ignore it. The coverage maps from the
936 // the other TU will either be loaded (providing full region counts) or they
937 // won't (in which case we don't unintuitively report functions as uncovered
938 // when they have non-zero counts in the profile).
939 if (Record.MappingRegions.size() == 1 &&
940 Record.MappingRegions[0].Count.isZero() && Counts[0] > 0)
941 return Error::success();
942
943 FunctionRecord Function(OrigFuncName, Record.Filenames);
944
945 // Emit CountedRegions into FunctionRecord.
946 if (auto E = CountedRegionEmitter(Record, Ctx, Function, IsVersion11)
947 .emitCountedRegions()) {
948 errs() << "warning: " << Record.FunctionName << ": ";
949 logAllUnhandledErrors(std::move(E), errs());
950 return Error::success();
951 }
952
953 // Don't create records for (filenames, function) pairs we've already seen.
954 auto FilenamesHash = hash_combine_range(Record.Filenames);
955 if (!RecordProvenance[FilenamesHash].insert(hash_value(OrigFuncName)).second)
956 return Error::success();
957
958 Functions.push_back(std::move(Function));
959
960 // Performance optimization: keep track of the indices of the function records
961 // which correspond to each filename. This can be used to substantially speed
962 // up queries for coverage info in a file.
963 unsigned RecordIndex = Functions.size() - 1;
964 for (StringRef Filename : Record.Filenames) {
965 auto &RecordIndices = FilenameHash2RecordIndices[hash_value(Filename)];
966 // Note that there may be duplicates in the filename set for a function
967 // record, because of e.g. macro expansions in the function in which both
968 // the macro and the function are defined in the same file.
969 if (RecordIndices.empty() || RecordIndices.back() != RecordIndex)
970 RecordIndices.push_back(RecordIndex);
971 }
972
973 return Error::success();
974}
975
976// This function is for memory optimization by shortening the lifetimes
977// of CoverageMappingReader instances.
978Error CoverageMapping::loadFromReaders(
979 ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
980 std::optional<std::reference_wrapper<IndexedInstrProfReader>>
981 &ProfileReader,
982 CoverageMapping &Coverage) {
983 assert(!Coverage.SingleByteCoverage || !ProfileReader ||
984 *Coverage.SingleByteCoverage ==
985 ProfileReader.value().get().hasSingleByteCoverage());
986 Coverage.SingleByteCoverage =
987 !ProfileReader || ProfileReader.value().get().hasSingleByteCoverage();
988 for (const auto &CoverageReader : CoverageReaders) {
989 for (auto RecordOrErr : *CoverageReader) {
990 if (Error E = RecordOrErr.takeError())
991 return E;
992 const auto &Record = *RecordOrErr;
993 if (Error E = Coverage.loadFunctionRecord(Record, ProfileReader))
994 return E;
995 }
996 }
997 return Error::success();
998}
999
1001 ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
1002 std::optional<std::reference_wrapper<IndexedInstrProfReader>>
1003 &ProfileReader) {
1004 auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
1005 if (Error E = loadFromReaders(CoverageReaders, ProfileReader, *Coverage))
1006 return std::move(E);
1007 return std::move(Coverage);
1008}
1009
1010// If E is a no_data_found error, returns success. Otherwise returns E.
1012 return handleErrors(std::move(E), [](const CoverageMapError &CME) {
1014 return static_cast<Error>(Error::success());
1015 return make_error<CoverageMapError>(CME.get(), CME.getMessage());
1016 });
1017}
1018
1019Error CoverageMapping::loadFromFile(
1020 StringRef Filename, StringRef Arch, StringRef CompilationDir,
1021 std::optional<std::reference_wrapper<IndexedInstrProfReader>>
1022 &ProfileReader,
1023 CoverageMapping &Coverage, bool &DataFound,
1024 SmallVectorImpl<object::BuildID> *FoundBinaryIDs) {
1025 auto CovMappingBufOrErr = MemoryBuffer::getFileOrSTDIN(
1026 Filename, /*IsText=*/false, /*RequiresNullTerminator=*/false);
1027 if (std::error_code EC = CovMappingBufOrErr.getError())
1029 MemoryBufferRef CovMappingBufRef =
1030 CovMappingBufOrErr.get()->getMemBufferRef();
1032
1034 auto CoverageReadersOrErr = BinaryCoverageReader::create(
1035 CovMappingBufRef, Arch, Buffers, CompilationDir,
1036 FoundBinaryIDs ? &BinaryIDs : nullptr);
1037 if (Error E = CoverageReadersOrErr.takeError()) {
1038 E = handleMaybeNoDataFoundError(std::move(E));
1039 if (E)
1040 return createFileError(Filename, std::move(E));
1041 return E;
1042 }
1043
1045 for (auto &Reader : CoverageReadersOrErr.get())
1046 Readers.push_back(std::move(Reader));
1047 if (FoundBinaryIDs && !Readers.empty()) {
1048 llvm::append_range(*FoundBinaryIDs,
1049 llvm::map_range(BinaryIDs, [](object::BuildIDRef BID) {
1050 return object::BuildID(BID);
1051 }));
1052 }
1053 DataFound |= !Readers.empty();
1054 if (Error E = loadFromReaders(Readers, ProfileReader, Coverage))
1055 return createFileError(Filename, std::move(E));
1056 return Error::success();
1057}
1058
1060 ArrayRef<StringRef> ObjectFilenames,
1061 std::optional<StringRef> ProfileFilename, vfs::FileSystem &FS,
1062 ArrayRef<StringRef> Arches, StringRef CompilationDir,
1063 const object::BuildIDFetcher *BIDFetcher, bool CheckBinaryIDs) {
1064 std::unique_ptr<IndexedInstrProfReader> ProfileReader;
1065 if (ProfileFilename) {
1066 auto ProfileReaderOrErr =
1067 IndexedInstrProfReader::create(ProfileFilename.value(), FS);
1068 if (Error E = ProfileReaderOrErr.takeError())
1069 return createFileError(ProfileFilename.value(), std::move(E));
1070 ProfileReader = std::move(ProfileReaderOrErr.get());
1071 }
1072 auto ProfileReaderRef =
1073 ProfileReader
1074 ? std::optional<std::reference_wrapper<IndexedInstrProfReader>>(
1075 *ProfileReader)
1076 : std::nullopt;
1077 auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
1078 bool DataFound = false;
1079
1080 auto GetArch = [&](size_t Idx) {
1081 if (Arches.empty())
1082 return StringRef();
1083 if (Arches.size() == 1)
1084 return Arches.front();
1085 return Arches[Idx];
1086 };
1087
1088 SmallVector<object::BuildID> FoundBinaryIDs;
1089 for (const auto &File : llvm::enumerate(ObjectFilenames)) {
1090 if (Error E = loadFromFile(File.value(), GetArch(File.index()),
1091 CompilationDir, ProfileReaderRef, *Coverage,
1092 DataFound, &FoundBinaryIDs))
1093 return std::move(E);
1094 }
1095
1096 if (BIDFetcher) {
1097 std::vector<object::BuildID> ProfileBinaryIDs;
1098 if (ProfileReader)
1099 if (Error E = ProfileReader->readBinaryIds(ProfileBinaryIDs))
1100 return createFileError(ProfileFilename.value(), std::move(E));
1101
1102 SmallVector<object::BuildIDRef> BinaryIDsToFetch;
1103 if (!ProfileBinaryIDs.empty()) {
1104 const auto &Compare = [](object::BuildIDRef A, object::BuildIDRef B) {
1105 return std::lexicographical_compare(A.begin(), A.end(), B.begin(),
1106 B.end());
1107 };
1108 llvm::sort(FoundBinaryIDs, Compare);
1109 std::set_difference(
1110 ProfileBinaryIDs.begin(), ProfileBinaryIDs.end(),
1111 FoundBinaryIDs.begin(), FoundBinaryIDs.end(),
1112 std::inserter(BinaryIDsToFetch, BinaryIDsToFetch.end()), Compare);
1113 }
1114
1115 for (object::BuildIDRef BinaryID : BinaryIDsToFetch) {
1116 if (Expected<std::string> Path = BIDFetcher->fetch(BinaryID)) {
1117 StringRef Arch = Arches.size() == 1 ? Arches.front() : StringRef();
1118 if (Error E = loadFromFile(*Path, Arch, CompilationDir,
1119 ProfileReaderRef, *Coverage, DataFound))
1120 return std::move(E);
1121 } else {
1122 // Conditionally propagate as new error.
1123 consumeError(Path.takeError());
1124 if (CheckBinaryIDs) {
1125 return createFileError(
1126 ProfileFilename.value(),
1128 "Missing binary ID: " +
1129 llvm::toHex(BinaryID, /*LowerCase=*/true)));
1130 }
1131 }
1132 }
1133 }
1134
1135 if (!DataFound)
1136 return createFileError(
1137 join(ObjectFilenames.begin(), ObjectFilenames.end(), ", "),
1139 return std::move(Coverage);
1140}
1141
1142/// Return the subrange of \p Regions whose FileID is \p FileID.
1143/// \p Regions must be grouped by ascending FileID.
1145 unsigned FileID) {
1146 auto Begin = llvm::lower_bound(
1147 Regions, FileID,
1148 [](const CountedRegion &R, unsigned ID) { return R.FileID < ID; });
1149 auto End = std::upper_bound(
1150 Begin, Regions.end(), FileID,
1151 [](unsigned ID, const CountedRegion &R) { return ID < R.FileID; });
1152 return ArrayRef<CountedRegion>(Begin, End);
1153}
1154
1155namespace {
1156
1157/// Distributes functions into instantiation sets.
1158///
1159/// An instantiation set is a collection of functions that have the same source
1160/// code, ie, template functions specializations.
1161class FunctionInstantiationSetCollector {
1162 using MapT = std::map<LineColPair, std::vector<const FunctionRecord *>>;
1163 MapT InstantiatedFunctions;
1164
1165public:
1166 void insert(const FunctionRecord &Function, unsigned FileID) {
1167 ArrayRef<CountedRegion> Regions =
1168 regionsForFileID(Function.CountedRegions, FileID);
1169 assert(!Regions.empty() && "function does not cover the given file");
1170 auto &Functions = InstantiatedFunctions[Regions.front().startLoc()];
1171 Functions.push_back(&Function);
1172 }
1173
1174 MapT::iterator begin() { return InstantiatedFunctions.begin(); }
1175 MapT::iterator end() { return InstantiatedFunctions.end(); }
1176};
1177
1178class SegmentBuilder {
1179 std::vector<CoverageSegment> &Segments;
1181
1182 SegmentBuilder(std::vector<CoverageSegment> &Segments) : Segments(Segments) {}
1183
1184 /// Emit a segment with the count from \p Region starting at \p StartLoc.
1185 //
1186 /// \p IsRegionEntry: The segment is at the start of a new non-gap region.
1187 /// \p EmitSkippedRegion: The segment must be emitted as a skipped region.
1188 void startSegment(const CountedRegion &Region, LineColPair StartLoc,
1189 bool IsRegionEntry, bool EmitSkippedRegion = false) {
1190 bool HasCount = !EmitSkippedRegion &&
1192
1193 // If the new segment wouldn't affect coverage rendering, skip it.
1194 if (!Segments.empty() && !IsRegionEntry && !EmitSkippedRegion) {
1195 const auto &Last = Segments.back();
1196 if (Last.HasCount == HasCount && Last.Count == Region.ExecutionCount &&
1197 !Last.IsRegionEntry)
1198 return;
1199 }
1200
1201 if (HasCount)
1202 Segments.emplace_back(StartLoc.first, StartLoc.second,
1203 Region.ExecutionCount, IsRegionEntry,
1205 else
1206 Segments.emplace_back(StartLoc.first, StartLoc.second, IsRegionEntry);
1207
1208 LLVM_DEBUG({
1209 const auto &Last = Segments.back();
1210 dbgs() << "Segment at " << Last.Line << ":" << Last.Col
1211 << " (count = " << Last.Count << ")"
1212 << (Last.IsRegionEntry ? ", RegionEntry" : "")
1213 << (!Last.HasCount ? ", Skipped" : "")
1214 << (Last.IsGapRegion ? ", Gap" : "") << "\n";
1215 });
1216 }
1217
1218 /// Emit segments for active regions which end before \p Loc.
1219 ///
1220 /// \p Loc: The start location of the next region. If std::nullopt, all active
1221 /// regions are completed.
1222 /// \p FirstCompletedRegion: Index of the first completed region.
1223 void completeRegionsUntil(std::optional<LineColPair> Loc,
1224 unsigned FirstCompletedRegion) {
1225 // Sort the completed regions by end location. This makes it simple to
1226 // emit closing segments in sorted order.
1227 auto CompletedRegionsIt = ActiveRegions.begin() + FirstCompletedRegion;
1228 std::stable_sort(CompletedRegionsIt, ActiveRegions.end(),
1229 [](const CountedRegion *L, const CountedRegion *R) {
1230 return L->endLoc() < R->endLoc();
1231 });
1232
1233 // Emit segments for all completed regions.
1234 for (unsigned I = FirstCompletedRegion + 1, E = ActiveRegions.size(); I < E;
1235 ++I) {
1236 const auto *CompletedRegion = ActiveRegions[I];
1237 assert((!Loc || CompletedRegion->endLoc() <= *Loc) &&
1238 "Completed region ends after start of new region");
1239
1240 const auto *PrevCompletedRegion = ActiveRegions[I - 1];
1241 auto CompletedSegmentLoc = PrevCompletedRegion->endLoc();
1242
1243 // Don't emit any more segments if they start where the new region begins.
1244 if (Loc && CompletedSegmentLoc == *Loc)
1245 break;
1246
1247 // Don't emit a segment if the next completed region ends at the same
1248 // location as this one.
1249 if (CompletedSegmentLoc == CompletedRegion->endLoc())
1250 continue;
1251
1252 // Use the count from the last completed region which ends at this loc.
1253 for (unsigned J = I + 1; J < E; ++J)
1254 if (CompletedRegion->endLoc() == ActiveRegions[J]->endLoc())
1255 CompletedRegion = ActiveRegions[J];
1256
1257 startSegment(*CompletedRegion, CompletedSegmentLoc, false);
1258 }
1259
1260 auto Last = ActiveRegions.back();
1261 if (FirstCompletedRegion && Last->endLoc() != *Loc) {
1262 // If there's a gap after the end of the last completed region and the
1263 // start of the new region, use the last active region to fill the gap.
1264 startSegment(*ActiveRegions[FirstCompletedRegion - 1], Last->endLoc(),
1265 false);
1266 } else if (!FirstCompletedRegion && (!Loc || *Loc != Last->endLoc())) {
1267 // Emit a skipped segment if there are no more active regions. This
1268 // ensures that gaps between functions are marked correctly.
1269 startSegment(*Last, Last->endLoc(), false, true);
1270 }
1271
1272 // Pop the completed regions.
1273 ActiveRegions.erase(CompletedRegionsIt, ActiveRegions.end());
1274 }
1275
1276 void buildSegmentsImpl(ArrayRef<CountedRegion> Regions) {
1277 for (const auto &CR : enumerate(Regions)) {
1278 auto CurStartLoc = CR.value().startLoc();
1279
1280 // Active regions which end before the current region need to be popped.
1281 auto CompletedRegions =
1282 std::stable_partition(ActiveRegions.begin(), ActiveRegions.end(),
1283 [&](const CountedRegion *Region) {
1284 return !(Region->endLoc() <= CurStartLoc);
1285 });
1286 if (CompletedRegions != ActiveRegions.end()) {
1287 unsigned FirstCompletedRegion =
1288 std::distance(ActiveRegions.begin(), CompletedRegions);
1289 completeRegionsUntil(CurStartLoc, FirstCompletedRegion);
1290 }
1291
1292 bool GapRegion = CR.value().Kind == CounterMappingRegion::GapRegion;
1293
1294 // Try to emit a segment for the current region.
1295 if (CurStartLoc == CR.value().endLoc()) {
1296 // Avoid making zero-length regions active. If it's the last region,
1297 // emit a skipped segment. Otherwise use its predecessor's count.
1298 const bool Skipped =
1299 (CR.index() + 1) == Regions.size() ||
1300 CR.value().Kind == CounterMappingRegion::SkippedRegion;
1301 startSegment(ActiveRegions.empty() ? CR.value() : *ActiveRegions.back(),
1302 CurStartLoc, !GapRegion, Skipped);
1303 // If it is skipped segment, create a segment with last pushed
1304 // regions's count at CurStartLoc.
1305 if (Skipped && !ActiveRegions.empty())
1306 startSegment(*ActiveRegions.back(), CurStartLoc, false);
1307 continue;
1308 }
1309 if (CR.index() + 1 == Regions.size() ||
1310 CurStartLoc != Regions[CR.index() + 1].startLoc()) {
1311 // Emit a segment if the next region doesn't start at the same location
1312 // as this one.
1313 startSegment(CR.value(), CurStartLoc, !GapRegion);
1314 }
1315
1316 // This region is active (i.e not completed).
1317 ActiveRegions.push_back(&CR.value());
1318 }
1319
1320 // Complete any remaining active regions.
1321 if (!ActiveRegions.empty())
1322 completeRegionsUntil(std::nullopt, 0);
1323 }
1324
1325 /// Sort a nested sequence of regions from a single file.
1326 static void sortNestedRegions(MutableArrayRef<CountedRegion> Regions) {
1327 llvm::sort(Regions, [](const CountedRegion &LHS, const CountedRegion &RHS) {
1328 if (LHS.startLoc() != RHS.startLoc())
1329 return LHS.startLoc() < RHS.startLoc();
1330 if (LHS.endLoc() != RHS.endLoc())
1331 // When LHS completely contains RHS, we sort LHS first.
1332 return RHS.endLoc() < LHS.endLoc();
1333 // If LHS and RHS cover the same area, we need to sort them according
1334 // to their kinds so that the most suitable region will become "active"
1335 // in combineRegions(). Because we accumulate counter values only from
1336 // regions of the same kind as the first region of the area, prefer
1337 // CodeRegion to ExpansionRegion and ExpansionRegion to SkippedRegion.
1338 static_assert(CounterMappingRegion::CodeRegion <
1342 "Unexpected order of region kind values");
1343 return LHS.Kind < RHS.Kind;
1344 });
1345 }
1346
1347 /// Combine counts of regions which cover the same area.
1349 combineRegions(MutableArrayRef<CountedRegion> Regions) {
1350 if (Regions.empty())
1351 return Regions;
1352 auto Active = Regions.begin();
1353 auto End = Regions.end();
1354 for (auto I = Regions.begin() + 1; I != End; ++I) {
1355 if (Active->startLoc() != I->startLoc() ||
1356 Active->endLoc() != I->endLoc()) {
1357 // Shift to the next region.
1358 ++Active;
1359 if (Active != I)
1360 *Active = *I;
1361 continue;
1362 }
1363 // Merge duplicate region.
1364 // If CodeRegions and ExpansionRegions cover the same area, it's probably
1365 // a macro which is fully expanded to another macro. In that case, we need
1366 // to accumulate counts only from CodeRegions, or else the area will be
1367 // counted twice.
1368 // On the other hand, a macro may have a nested macro in its body. If the
1369 // outer macro is used several times, the ExpansionRegion for the nested
1370 // macro will also be added several times. These ExpansionRegions cover
1371 // the same source locations and have to be combined to reach the correct
1372 // value for that area.
1373 // We add counts of the regions of the same kind as the active region
1374 // to handle the both situations.
1375 if (I->Kind == Active->Kind)
1376 Active->ExecutionCount += I->ExecutionCount;
1377 }
1378 return Regions.drop_back(std::distance(++Active, End));
1379 }
1380
1381public:
1382 /// Build a sorted list of CoverageSegments from a list of Regions.
1383 static std::vector<CoverageSegment>
1384 buildSegments(MutableArrayRef<CountedRegion> Regions) {
1385 std::vector<CoverageSegment> Segments;
1386 SegmentBuilder Builder(Segments);
1387
1388 sortNestedRegions(Regions);
1389 ArrayRef<CountedRegion> CombinedRegions = combineRegions(Regions);
1390
1391 LLVM_DEBUG({
1392 dbgs() << "Combined regions:\n";
1393 for (const auto &CR : CombinedRegions)
1394 dbgs() << " " << CR.LineStart << ":" << CR.ColumnStart << " -> "
1395 << CR.LineEnd << ":" << CR.ColumnEnd
1396 << " (count=" << CR.ExecutionCount << ")\n";
1397 });
1398
1399 Builder.buildSegmentsImpl(CombinedRegions);
1400
1401#ifndef NDEBUG
1402 for (unsigned I = 1, E = Segments.size(); I < E; ++I) {
1403 const auto &L = Segments[I - 1];
1404 const auto &R = Segments[I];
1405 if (!(L.Line < R.Line) && !(L.Line == R.Line && L.Col < R.Col)) {
1406 if (L.Line == R.Line && L.Col == R.Col && !L.HasCount)
1407 continue;
1408 LLVM_DEBUG(dbgs() << " ! Segment " << L.Line << ":" << L.Col
1409 << " followed by " << R.Line << ":" << R.Col << "\n");
1410 assert(false && "Coverage segments not unique or sorted");
1411 }
1412 }
1413#endif
1414
1415 return Segments;
1416 }
1417};
1418
1419struct MergeableCoverageData : public CoverageData {
1420 std::vector<CountedRegion> CodeRegions;
1421
1422 MergeableCoverageData(bool Single, StringRef Filename)
1423 : CoverageData(Single, Filename) {}
1424
1425 void addFunctionRegions(
1426 const FunctionRecord &Function,
1427 std::function<bool(const CounterMappingRegion &CR)> shouldProcess,
1428 std::function<bool(const CountedRegion &CR)> shouldExpand) {
1429 for (const auto &CR : Function.CountedRegions)
1430 if (shouldProcess(CR)) {
1431 CodeRegions.push_back(CR);
1432 if (shouldExpand(CR))
1433 Expansions.emplace_back(CR, Function);
1434 }
1435 // Capture branch regions specific to the function (excluding expansions).
1436 for (const auto &CR : Function.CountedBranchRegions)
1437 if (shouldProcess(CR))
1438 BranchRegions.push_back(CR);
1439 // Capture MCDC records specific to the function.
1440 for (const auto &MR : Function.MCDCRecords)
1441 if (shouldProcess(MR.getDecisionRegion()))
1442 MCDCRecords.push_back(MR);
1443 }
1444
1445 CoverageData buildSegments() {
1446 Segments = SegmentBuilder::buildSegments(CodeRegions);
1447 return CoverageData(std::move(*this));
1448 }
1449};
1450} // end anonymous namespace
1451
1452std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() const {
1453 std::vector<StringRef> Filenames;
1454 for (const auto &Function : getCoveredFunctions())
1455 llvm::append_range(Filenames, Function.Filenames);
1456 llvm::sort(Filenames);
1457 auto Last = llvm::unique(Filenames);
1458 Filenames.erase(Last, Filenames.end());
1459 return Filenames;
1460}
1461
1463 const FunctionRecord &Function) {
1464 SmallBitVector FilenameEquivalence(Function.Filenames.size(), false);
1465 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
1466 if (SourceFile == Function.Filenames[I])
1467 FilenameEquivalence[I] = true;
1468 return FilenameEquivalence;
1469}
1470
1471/// Return the ID of the file where the definition of the function is located.
1472static std::optional<unsigned>
1474 if (Function.CountedRegions.empty())
1475 return std::nullopt;
1476 SmallBitVector IsNotExpandedFile(Function.Filenames.size(), true);
1477 for (const auto &CR : Function.CountedRegions)
1479 IsNotExpandedFile[CR.ExpandedFileID] = false;
1480 int I = IsNotExpandedFile.find_first();
1481 if (I == -1)
1482 return std::nullopt;
1483 return I;
1484}
1485
1486/// Check if SourceFile is the file that contains the definition of
1487/// the Function. Return the ID of the file in that case or std::nullopt
1488/// otherwise.
1489static std::optional<unsigned>
1491 std::optional<unsigned> I = findMainViewFileID(Function);
1492 if (I && SourceFile == Function.Filenames[*I])
1493 return I;
1494 return std::nullopt;
1495}
1496
1497static bool isExpansion(const CountedRegion &R, unsigned FileID) {
1498 return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID;
1499}
1500
1502 assert(SingleByteCoverage);
1503 MergeableCoverageData FileCoverage(*SingleByteCoverage, Filename);
1504
1505 // Look up the function records in the given file. Due to hash collisions on
1506 // the filename, we may get back some records that are not in the file.
1507 ArrayRef<unsigned> RecordIndices =
1508 getImpreciseRecordIndicesForFilename(Filename);
1509 for (unsigned RecordIndex : RecordIndices) {
1510 const FunctionRecord &Function = Functions[RecordIndex];
1511 auto MainFileID = findMainViewFileID(Filename, Function);
1512 auto FileIDs = gatherFileIDs(Filename, Function);
1513 FileCoverage.addFunctionRegions(
1514 Function, [&](auto &CR) { return FileIDs.test(CR.FileID); },
1515 [&](auto &CR) { return (MainFileID && isExpansion(CR, *MainFileID)); });
1516 }
1517
1518 LLVM_DEBUG(dbgs() << "Emitting segments for file: " << Filename << "\n");
1519
1520 return FileCoverage.buildSegments();
1521}
1522
1523std::vector<InstantiationGroup>
1525 FunctionInstantiationSetCollector InstantiationSetCollector;
1526 // Look up the function records in the given file. Due to hash collisions on
1527 // the filename, we may get back some records that are not in the file.
1528 ArrayRef<unsigned> RecordIndices =
1529 getImpreciseRecordIndicesForFilename(Filename);
1530 for (unsigned RecordIndex : RecordIndices) {
1531 const FunctionRecord &Function = Functions[RecordIndex];
1532 auto MainFileID = findMainViewFileID(Filename, Function);
1533 if (!MainFileID)
1534 continue;
1535 InstantiationSetCollector.insert(Function, *MainFileID);
1536 }
1537
1538 std::vector<InstantiationGroup> Result;
1539 for (auto &InstantiationSet : InstantiationSetCollector) {
1540 InstantiationGroup IG{InstantiationSet.first.first,
1541 InstantiationSet.first.second,
1542 std::move(InstantiationSet.second)};
1543 Result.emplace_back(std::move(IG));
1544 }
1545 return Result;
1546}
1547
1550 auto MainFileID = findMainViewFileID(Function);
1551 if (!MainFileID)
1552 return CoverageData();
1553
1554 assert(SingleByteCoverage);
1555 MergeableCoverageData FunctionCoverage(*SingleByteCoverage,
1556 Function.Filenames[*MainFileID]);
1557 FunctionCoverage.addFunctionRegions(
1558 Function, [&](auto &CR) { return (CR.FileID == *MainFileID); },
1559 [&](auto &CR) { return isExpansion(CR, *MainFileID); });
1560
1561 LLVM_DEBUG(dbgs() << "Emitting segments for function: " << Function.Name
1562 << "\n");
1563
1564 return FunctionCoverage.buildSegments();
1565}
1566
1568 const ExpansionRecord &Expansion) const {
1569 assert(SingleByteCoverage);
1570 CoverageData ExpansionCoverage(
1571 *SingleByteCoverage, Expansion.Function.Filenames[Expansion.FileID]);
1572 std::vector<CountedRegion> Regions;
1573 for (const auto &CR :
1574 regionsForFileID(Expansion.Function.CountedRegions, Expansion.FileID)) {
1575 Regions.push_back(CR);
1576 if (isExpansion(CR, Expansion.FileID))
1577 ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function);
1578 }
1579 // Capture branch regions that only pertain to the corresponding expansion.
1580 for (const auto &CR : regionsForFileID(
1581 Expansion.Function.CountedBranchRegions, Expansion.FileID))
1582 ExpansionCoverage.BranchRegions.push_back(CR);
1583
1584 LLVM_DEBUG(dbgs() << "Emitting segments for expansion of file "
1585 << Expansion.FileID << "\n");
1586 ExpansionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
1587
1588 return ExpansionCoverage;
1589}
1590
1591LineCoverageStats::LineCoverageStats(
1593 const CoverageSegment *WrappedSegment, unsigned Line)
1594 : ExecutionCount(0), HasMultipleRegions(false), Mapped(false), Line(Line),
1595 LineSegments(LineSegments), WrappedSegment(WrappedSegment) {
1596 // Find the minimum number of regions which start in this line.
1597 unsigned MinRegionCount = 0;
1598 auto isStartOfRegion = [](const CoverageSegment *S) {
1599 return !S->IsGapRegion && S->HasCount && S->IsRegionEntry;
1600 };
1601 for (unsigned I = 0; I < LineSegments.size() && MinRegionCount < 2; ++I)
1602 if (isStartOfRegion(LineSegments[I]))
1603 ++MinRegionCount;
1604
1605 bool StartOfSkippedRegion = !LineSegments.empty() &&
1606 !LineSegments.front()->HasCount &&
1607 LineSegments.front()->IsRegionEntry;
1608
1609 HasMultipleRegions = MinRegionCount > 1;
1610 Mapped =
1611 !StartOfSkippedRegion &&
1612 ((WrappedSegment && WrappedSegment->HasCount) || (MinRegionCount > 0));
1613
1614 // if there is any starting segment at this line with a counter, it must be
1615 // mapped
1616 Mapped |= any_of(LineSegments, [](const auto *Seq) {
1617 return Seq->IsRegionEntry && Seq->HasCount;
1618 });
1619
1620 if (!Mapped) {
1621 return;
1622 }
1623
1624 // Pick the max count from the non-gap, region entry segments and the
1625 // wrapped count.
1626 if (WrappedSegment)
1627 ExecutionCount = WrappedSegment->Count;
1628 if (!MinRegionCount)
1629 return;
1630 for (const auto *LS : LineSegments)
1631 if (isStartOfRegion(LS))
1632 ExecutionCount = std::max(ExecutionCount, LS->Count);
1633}
1634
1636 if (Next == CD.end()) {
1637 Stats = LineCoverageStats();
1638 Ended = true;
1639 return *this;
1640 }
1641 if (Segments.size())
1642 WrappedSegment = Segments.back();
1643 Segments.clear();
1644 while (Next != CD.end() && Next->Line == Line)
1645 Segments.push_back(&*Next++);
1646 Stats = LineCoverageStats(Segments, WrappedSegment, Line);
1647 ++Line;
1648 return *this;
1649}
1650
1652 const std::string &ErrMsg = "") {
1653 std::string Msg;
1655
1656 switch (Err) {
1658 OS << "success";
1659 break;
1661 OS << "end of File";
1662 break;
1664 OS << "no coverage data found";
1665 break;
1667 OS << "unsupported coverage format version";
1668 break;
1670 OS << "truncated coverage data";
1671 break;
1673 OS << "malformed coverage data";
1674 break;
1676 OS << "failed to decompress coverage data (zlib)";
1677 break;
1679 OS << "`-arch` specifier is invalid or missing for universal binary";
1680 break;
1681 }
1682
1683 // If optional error message is not empty, append it to the message.
1684 if (!ErrMsg.empty())
1685 OS << ": " << ErrMsg;
1686
1687 return Msg;
1688}
1689
1690namespace {
1691
1692// FIXME: This class is only here to support the transition to llvm::Error. It
1693// will be removed once this transition is complete. Clients should prefer to
1694// deal with the Error value directly, rather than converting to error_code.
1695class CoverageMappingErrorCategoryType : public std::error_category {
1696 const char *name() const noexcept override { return "llvm.coveragemap"; }
1697 std::string message(int IE) const override {
1698 return getCoverageMapErrString(static_cast<coveragemap_error>(IE));
1699 }
1700};
1701
1702} // end anonymous namespace
1703
1704std::string CoverageMapError::message() const {
1705 return getCoverageMapErrString(Err, Msg);
1706}
1707
1708const std::error_category &llvm::coverage::coveragemap_category() {
1709 static CoverageMappingErrorCategoryType ErrorCategory;
1710 return ErrorCategory;
1711}
1712
1713char CoverageMapError::ID = 0;
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
uint64_t uint64_t
This file declares a library for handling Build IDs and using them to find debug info.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static SmallBitVector gatherFileIDs(StringRef SourceFile, const FunctionRecord &Function)
static std::optional< unsigned > findMainViewFileID(const FunctionRecord &Function)
Return the ID of the file where the definition of the function is located.
static bool isExpansion(const CountedRegion &R, unsigned FileID)
static Error handleMaybeNoDataFoundError(Error E)
static unsigned getMaxBitmapSize(const CoverageMappingRecord &Record, bool IsVersion11)
Returns the bit count.
static ArrayRef< CountedRegion > regionsForFileID(ArrayRef< CountedRegion > Regions, unsigned FileID)
Return the subrange of Regions whose FileID is FileID.
static std::string getCoverageMapErrString(coveragemap_error Err, const std::string &ErrMsg="")
static unsigned getMaxCounterID(const CounterMappingContext &Ctx, const CoverageMappingRecord &Record)
DXIL Intrinsic Expansion
This file defines the DenseMap class.
hexagon bit simplify
MachineBasicBlock * Folded
if(!TBB||Cond.size()< 1) return false
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
static constexpr StringLiteral Filename
if(PassOpts->AAPipeline)
const char * Msg
This file contains some templates that are useful if you are working with the STL at all.
static const char * name
This file implements the SmallBitVector class.
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Defines the virtual file system interface vfs::FileSystem.
Value * RHS
Value * LHS
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & front() const
Get the first element.
Definition ArrayRef.h:144
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
bool empty() const
Definition Function.h:853
size_t size() const
Definition Function.h:852
static Expected< std::unique_ptr< IndexedInstrProfReader > > create(const Twine &Path, vfs::FileSystem &FS, const Twine &RemappingPath="")
Factory method to create an indexed reader.
static std::pair< instrprof_error, std::string > take(Error E)
Consume an Error and return the raw enum value contained within it, and the optional error message.
Definition InstrProf.h:464
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
iterator end() const
Definition ArrayRef.h:339
iterator begin() const
Definition ArrayRef.h:338
MutableArrayRef< T > drop_back(size_t N=1) const
Definition ArrayRef.h:388
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
int find_first() const
Returns the index of the first set bit, -1 if none of the bits are set.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
iterator erase(const_iterator CI)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
LLVM Value Representation.
Definition Value.h:75
static Expected< std::vector< std::unique_ptr< BinaryCoverageReader > > > create(MemoryBufferRef ObjectBuffer, StringRef Arch, SmallVectorImpl< std::unique_ptr< MemoryBuffer > > &ObjectFileBuffers, StringRef CompilationDir="", SmallVectorImpl< object::BuildIDRef > *BinaryIDs=nullptr)
LLVM_ABI Counter subtract(Counter LHS, Counter RHS, bool Simplify=true)
Return a counter that represents the expression that subtracts RHS from LHS.
LLVM_ABI Counter add(Counter LHS, Counter RHS, bool Simplify=true)
Return a counter that represents the expression that adds LHS and RHS.
LLVM_ABI Counter subst(Counter C, const SubstMap &Map)
std::map< Counter, Counter > SubstMap
K to V map.
A Counter mapping context is used to connect the counters, expressions and the obtained counter value...
LLVM_ABI Expected< MCDCRecord > evaluateMCDCRegion(const CounterMappingRegion &Region, ArrayRef< const CounterMappingRegion * > Branches, bool IsVersion11)
Return an MCDC record that indicates executed test vectors and condition pairs.
void setCounts(ArrayRef< uint64_t > Counts)
LLVM_ABI Expected< int64_t > evaluate(const Counter &C) const
Return the number of times that a region of code associated with this counter was executed.
void setBitmap(BitVector &&Bitmap_)
LLVM_ABI unsigned getMaxCounterID(const Counter &C) const
LLVM_ABI void dump(const Counter &C, raw_ostream &OS) const
Coverage information to be processed or displayed.
std::vector< CountedRegion > BranchRegions
std::vector< CoverageSegment > Segments
std::vector< ExpansionRecord > Expansions
std::string message() const override
Return the error message as a string.
coveragemap_error get() const
const std::string & getMessage() const
static LLVM_ABI Expected< std::unique_ptr< CoverageMapping > > load(ArrayRef< std::unique_ptr< CoverageMappingReader > > CoverageReaders, std::optional< std::reference_wrapper< IndexedInstrProfReader > > &ProfileReader)
Load the coverage mapping using the given readers.
LLVM_ABI std::vector< StringRef > getUniqueSourceFiles() const
Returns a lexicographically sorted, unique list of files that are covered.
LLVM_ABI CoverageData getCoverageForExpansion(const ExpansionRecord &Expansion) const
Get the coverage for an expansion within a coverage set.
iterator_range< FunctionRecordIterator > getCoveredFunctions() const
Gets all of the functions covered by this profile.
LLVM_ABI CoverageData getCoverageForFunction(const FunctionRecord &Function) const
Get the coverage for a particular function.
LLVM_ABI std::vector< InstantiationGroup > getInstantiationGroups(StringRef Filename) const
Get the list of function instantiation groups in a particular file.
LLVM_ABI CoverageData getCoverageForFile(StringRef Filename) const
Get the coverage for a particular file.
Iterator over Functions, optionally filtered to a single file.
An instantiation group contains a FunctionRecord list, such that each record corresponds to a distinc...
LineCoverageIterator(const CoverageData &CD)
LLVM_ABI LineCoverageIterator & operator++()
Coverage statistics for a single line.
auto getIndex() const
Equivalent to buildTestVector's Index.
void set(int I, CondState Val)
Set the condition Val at position I.
Compute TestVector Indices "TVIdx" from the Conds graph.
static constexpr auto HardMaxTVs
Hard limit of test vectors.
LLVM_ABI TVIdxBuilder(const SmallVectorImpl< ConditionIDs > &NextIDs, int Offset=0)
Calculate and assign Indices.
SmallVector< std::array< int, 2 > > Indices
Output: Index for TestVectors bitmap (These are not CondIDs)
int NumTestVectors
Output: The number of test vectors.
SmallVector< MCDCNode > SavedNodes
This is no longer needed after the assignment.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
size_type size() const
Definition DenseSet.h:85
BuildIDFetcher searches local cache directories for debug info.
Definition BuildID.h:41
virtual Expected< std::string > fetch(BuildIDRef BuildID) const
Returns the path to the debug file with the given build ID.
Definition BuildID.cpp:83
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
The virtual file system interface.
@ Skipped
Validation or recovery was skipped, as it was not needed.
int16_t ConditionID
The ID for MCDCBranch.
Definition MCDCTypes.h:25
std::array< ConditionID, 2 > ConditionIDs
Definition MCDCTypes.h:26
LLVM_ABI const std::error_category & coveragemap_category()
std::pair< unsigned, unsigned > LineColPair
SmallVector< uint8_t, 10 > BuildID
A build ID in binary form.
Definition BuildID.h:27
ArrayRef< uint8_t > BuildIDRef
A reference to a BuildID in binary form.
Definition BuildID.h:30
iterator end() const
Definition BasicBlock.h:89
LLVM_ABI iterator begin() const
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:360
LLVM_ABI void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
Definition Error.cpp:61
hash_code hash_value(const FixedPointSemantics &Val)
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
Definition Error.h:1415
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
LLVM_ABI StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName="<unknown>")
Given a PGO function name, remove the filename prefix and return the original (static) function name.
Error handleErrors(Error E, HandlerTs &&... Hs)
Pass the ErrorInfo(s) contained in E to their respective handlers.
Definition Error.h:990
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2150
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:366
@ no_such_file_or_directory
Definition Errc.h:65
@ argument_out_of_domain
Definition Errc.h:37
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
bool is_sorted(R &&Range, Compare C)
Wrapper function around std::is_sorted to check if elements in a range R are sorted with respect to a...
Definition STLExtras.h:1986
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
std::string join(IteratorT Begin, IteratorT End, StringRef Separator)
Joins the strings in the range [Begin, End), adding Separator between the elements.
instrprof_error
Definition InstrProf.h:390
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2068
ArrayRef(const T &OneElt) -> ArrayRef< T >
void toHex(ArrayRef< uint8_t > Input, bool LowerCase, SmallVectorImpl< char > &Output)
Convert buffer Input to its hexadecimal representation. The returned string is double the size of Inp...
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition Error.cpp:107
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition Hashing.h:287
#define N
Associates a source range with an execution count.
A Counter expression is a value that represents an arithmetic operation with two counters.
A Counter mapping region associates a source range with a specific counter.
@ ExpansionRegion
An ExpansionRegion represents a file expansion region that associates a source range with the expansi...
@ MCDCDecisionRegion
A DecisionRegion represents a top-level boolean expression and is associated with a variable length b...
@ MCDCBranchRegion
A Branch Region can be extended to include IDs to facilitate MC/DC.
@ SkippedRegion
A SkippedRegion represents a source range with code that was skipped by a preprocessor or similar mea...
@ GapRegion
A GapRegion is like a CodeRegion, but its count is only set as the line execution count when its the ...
@ CodeRegion
A CodeRegion associates some code with a counter.
A Counter is an abstract value that describes how to compute the execution count for a region of code...
static Counter getZero()
Return the counter that represents the number zero.
static Counter getCounter(unsigned CounterId)
Return the counter that corresponds to a specific profile counter.
static Counter getExpression(unsigned ExpressionId)
Return the counter that corresponds to a specific addition counter expression.
Coverage mapping information for a single function.
The execution count information starting at a point in a file.
Coverage information for a macro expansion or included file.
Code coverage information for a single function.
llvm::SmallVector< std::pair< TestVector, CondState > > TestVectors
LLVM_ABI void findIndependencePairs()
llvm::DenseMap< unsigned, unsigned > CondIDMap
llvm::DenseMap< unsigned, LineColPair > LineColPairMap
CondState
CondState represents the evaluation of a condition in an executed test vector, which can be True or F...
std::array< BitVector, 2 > BoolVector
unsigned BitmapIdx
Byte Index of Bitmap Coverage Object for a Decision Region.
Definition MCDCTypes.h:30
uint16_t NumConditions
Number of Conditions used for a Decision Region.
Definition MCDCTypes.h:33