Bug Summary

File:lib/ProfileData/Coverage/CoverageMappingReader.cpp
Warning:line 221, column 19
The left operand of '&' is a garbage value

Annotated Source Code

/build/llvm-toolchain-snapshot-6.0~svn318211/lib/ProfileData/Coverage/CoverageMappingReader.cpp

1//===- CoverageMappingReader.cpp - Code coverage mapping reader -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains support for reading coverage mapping data for
11// instrumentation based coverage.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/StringRef.h"
21#include "llvm/ADT/Triple.h"
22#include "llvm/Object/Binary.h"
23#include "llvm/Object/COFF.h"
24#include "llvm/Object/Error.h"
25#include "llvm/Object/MachOUniversal.h"
26#include "llvm/Object/ObjectFile.h"
27#include "llvm/ProfileData/InstrProf.h"
28#include "llvm/Support/Casting.h"
29#include "llvm/Support/Debug.h"
30#include "llvm/Support/Endian.h"
31#include "llvm/Support/Error.h"
32#include "llvm/Support/ErrorHandling.h"
33#include "llvm/Support/LEB128.h"
34#include "llvm/Support/MathExtras.h"
35#include "llvm/Support/raw_ostream.h"
36#include <algorithm>
37#include <cassert>
38#include <cstddef>
39#include <cstdint>
40#include <limits>
41#include <memory>
42#include <utility>
43#include <vector>
44
45using namespace llvm;
46using namespace coverage;
47using namespace object;
48
49#define DEBUG_TYPE"coverage-mapping" "coverage-mapping"
50
51void CoverageMappingIterator::increment() {
52 if (ReadErr != coveragemap_error::success)
53 return;
54
55 // Check if all the records were read or if an error occurred while reading
56 // the next record.
57 if (auto E = Reader->readNextRecord(Record))
58 handleAllErrors(std::move(E), [&](const CoverageMapError &CME) {
59 if (CME.get() == coveragemap_error::eof)
60 *this = CoverageMappingIterator();
61 else
62 ReadErr = CME.get();
63 });
64}
65
66Error RawCoverageReader::readULEB128(uint64_t &Result) {
67 if (Data.empty())
40
Assuming the condition is true
41
Taking true branch
68 return make_error<CoverageMapError>(coveragemap_error::truncated);
42
Calling 'make_error'
49
Returning from 'make_error'
69 unsigned N = 0;
70 Result = decodeULEB128(reinterpret_cast<const uint8_t *>(Data.data()), &N);
71 if (N > Data.size())
72 return make_error<CoverageMapError>(coveragemap_error::malformed);
73 Data = Data.substr(N);
74 return Error::success();
75}
76
77Error RawCoverageReader::readIntMax(uint64_t &Result, uint64_t MaxPlus1) {
78 if (auto Err = readULEB128(Result))
39
Calling 'RawCoverageReader::readULEB128'
50
Returning from 'RawCoverageReader::readULEB128'
51
Calling move constructor for 'Error'
75
Returning from move constructor for 'Error'
76
Calling 'Error::operator bool'
85
Returning from 'Error::operator bool'
86
Taking true branch
79 return Err;
87
Calling '~Error'
94
Returning from '~Error'
80 if (Result >= MaxPlus1)
81 return make_error<CoverageMapError>(coveragemap_error::malformed);
82 return Error::success();
83}
84
85Error RawCoverageReader::readSize(uint64_t &Result) {
86 if (auto Err = readULEB128(Result))
87 return Err;
88 // Sanity check the number.
89 if (Result > Data.size())
90 return make_error<CoverageMapError>(coveragemap_error::malformed);
91 return Error::success();
92}
93
94Error RawCoverageReader::readString(StringRef &Result) {
95 uint64_t Length;
96 if (auto Err = readSize(Length))
97 return Err;
98 Result = Data.substr(0, Length);
99 Data = Data.substr(Length);
100 return Error::success();
101}
102
103Error RawCoverageFilenamesReader::read() {
104 uint64_t NumFilenames;
105 if (auto Err = readSize(NumFilenames))
106 return Err;
107 for (size_t I = 0; I < NumFilenames; ++I) {
108 StringRef Filename;
109 if (auto Err = readString(Filename))
110 return Err;
111 Filenames.push_back(Filename);
112 }
113 return Error::success();
114}
115
116Error RawCoverageMappingReader::decodeCounter(unsigned Value, Counter &C) {
117 auto Tag = Value & Counter::EncodingTagMask;
118 switch (Tag) {
119 case Counter::Zero:
120 C = Counter::getZero();
121 return Error::success();
122 case Counter::CounterValueReference:
123 C = Counter::getCounter(Value >> Counter::EncodingTagBits);
124 return Error::success();
125 default:
126 break;
127 }
128 Tag -= Counter::Expression;
129 switch (Tag) {
130 case CounterExpression::Subtract:
131 case CounterExpression::Add: {
132 auto ID = Value >> Counter::EncodingTagBits;
133 if (ID >= Expressions.size())
134 return make_error<CoverageMapError>(coveragemap_error::malformed);
135 Expressions[ID].Kind = CounterExpression::ExprKind(Tag);
136 C = Counter::getExpression(ID);
137 break;
138 }
139 default:
140 return make_error<CoverageMapError>(coveragemap_error::malformed);
141 }
142 return Error::success();
143}
144
145Error RawCoverageMappingReader::readCounter(Counter &C) {
146 uint64_t EncodedCounter;
147 if (auto Err =
148 readIntMax(EncodedCounter, std::numeric_limits<unsigned>::max()))
149 return Err;
150 if (auto Err = decodeCounter(EncodedCounter, C))
151 return Err;
152 return Error::success();
153}
154
155static const unsigned EncodingExpansionRegionBit = 1
156 << Counter::EncodingTagBits;
157
158/// \brief Read the sub-array of regions for the given inferred file id.
159/// \param NumFileIDs the number of file ids that are defined for this
160/// function.
161Error RawCoverageMappingReader::readMappingRegionsSubArray(
162 std::vector<CounterMappingRegion> &MappingRegions, unsigned InferredFileID,
163 size_t NumFileIDs) {
164 uint64_t NumRegions;
165 if (auto Err = readSize(NumRegions))
22
Taking false branch
166 return Err;
167 unsigned LineStart = 0;
168 for (size_t I = 0; I < NumRegions; ++I) {
23
Assuming 'I' is < 'NumRegions'
24
Loop condition is true. Entering loop body
169 Counter C;
170 CounterMappingRegion::RegionKind Kind = CounterMappingRegion::CodeRegion;
171
172 // Read the combined counter + region kind.
173 uint64_t EncodedCounterAndRegion;
174 if (auto Err = readIntMax(EncodedCounterAndRegion,
25
Taking false branch
175 std::numeric_limits<unsigned>::max()))
176 return Err;
177 unsigned Tag = EncodedCounterAndRegion & Counter::EncodingTagMask;
178 uint64_t ExpandedFileID = 0;
179 if (Tag != Counter::Zero) {
26
Assuming 'Tag' is equal to Zero
27
Taking false branch
180 if (auto Err = decodeCounter(EncodedCounterAndRegion, C))
181 return Err;
182 } else {
183 // Is it an expansion region?
184 if (EncodedCounterAndRegion & EncodingExpansionRegionBit) {
28
Assuming the condition is false
29
Taking false branch
185 Kind = CounterMappingRegion::ExpansionRegion;
186 ExpandedFileID = EncodedCounterAndRegion >>
187 Counter::EncodingCounterTagAndExpansionRegionTagBits;
188 if (ExpandedFileID >= NumFileIDs)
189 return make_error<CoverageMapError>(coveragemap_error::malformed);
190 } else {
191 switch (EncodedCounterAndRegion >>
30
Control jumps to 'case SkippedRegion:' at line 196
192 Counter::EncodingCounterTagAndExpansionRegionTagBits) {
193 case CounterMappingRegion::CodeRegion:
194 // Don't do anything when we have a code region with a zero counter.
195 break;
196 case CounterMappingRegion::SkippedRegion:
197 Kind = CounterMappingRegion::SkippedRegion;
198 break;
31
Execution continues on line 206
199 default:
200 return make_error<CoverageMapError>(coveragemap_error::malformed);
201 }
202 }
203 }
204
205 // Read the source range.
206 uint64_t LineStartDelta, ColumnStart, NumLines, ColumnEnd;
32
'ColumnEnd' declared without an initial value
207 if (auto Err =
33
Taking false branch
208 readIntMax(LineStartDelta, std::numeric_limits<unsigned>::max()))
209 return Err;
210 if (auto Err = readULEB128(ColumnStart))
34
Taking false branch
211 return Err;
212 if (ColumnStart > std::numeric_limits<unsigned>::max())
35
Assuming the condition is false
36
Taking false branch
213 return make_error<CoverageMapError>(coveragemap_error::malformed);
214 if (auto Err = readIntMax(NumLines, std::numeric_limits<unsigned>::max()))
37
Taking false branch
215 return Err;
216 if (auto Err = readIntMax(ColumnEnd, std::numeric_limits<unsigned>::max()))
38
Calling 'RawCoverageReader::readIntMax'
95
Returning from 'RawCoverageReader::readIntMax'
96
Taking false branch
217 return Err;
218 LineStart += LineStartDelta;
219
220 // If the high bit of ColumnEnd is set, this is a gap region.
221 if (ColumnEnd & (1U << 31)) {
97
The left operand of '&' is a garbage value
222 Kind = CounterMappingRegion::GapRegion;
223 ColumnEnd &= ~(1U << 31);
224 }
225
226 // Adjust the column locations for the empty regions that are supposed to
227 // cover whole lines. Those regions should be encoded with the
228 // column range (1 -> std::numeric_limits<unsigned>::max()), but because
229 // the encoded std::numeric_limits<unsigned>::max() is several bytes long,
230 // we set the column range to (0 -> 0) to ensure that the column start and
231 // column end take up one byte each.
232 // The std::numeric_limits<unsigned>::max() is used to represent a column
233 // position at the end of the line without knowing the length of that line.
234 if (ColumnStart == 0 && ColumnEnd == 0) {
235 ColumnStart = 1;
236 ColumnEnd = std::numeric_limits<unsigned>::max();
237 }
238
239 DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("coverage-mapping")) { { dbgs() << "Counter in file " <<
InferredFileID << " " << LineStart << ":" <<
ColumnStart << " -> " << (LineStart + NumLines
) << ":" << ColumnEnd << ", "; if (Kind == CounterMappingRegion
::ExpansionRegion) dbgs() << "Expands to file " <<
ExpandedFileID; else CounterMappingContext(Expressions).dump
(C, dbgs()); dbgs() << "\n"; }; } } while (false)
240 dbgs() << "Counter in file " << InferredFileID << " " << LineStart << ":"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("coverage-mapping")) { { dbgs() << "Counter in file " <<
InferredFileID << " " << LineStart << ":" <<
ColumnStart << " -> " << (LineStart + NumLines
) << ":" << ColumnEnd << ", "; if (Kind == CounterMappingRegion
::ExpansionRegion) dbgs() << "Expands to file " <<
ExpandedFileID; else CounterMappingContext(Expressions).dump
(C, dbgs()); dbgs() << "\n"; }; } } while (false)
241 << ColumnStart << " -> " << (LineStart + NumLines) << ":"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("coverage-mapping")) { { dbgs() << "Counter in file " <<
InferredFileID << " " << LineStart << ":" <<
ColumnStart << " -> " << (LineStart + NumLines
) << ":" << ColumnEnd << ", "; if (Kind == CounterMappingRegion
::ExpansionRegion) dbgs() << "Expands to file " <<
ExpandedFileID; else CounterMappingContext(Expressions).dump
(C, dbgs()); dbgs() << "\n"; }; } } while (false)
242 << ColumnEnd << ", ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("coverage-mapping")) { { dbgs() << "Counter in file " <<
InferredFileID << " " << LineStart << ":" <<
ColumnStart << " -> " << (LineStart + NumLines
) << ":" << ColumnEnd << ", "; if (Kind == CounterMappingRegion
::ExpansionRegion) dbgs() << "Expands to file " <<
ExpandedFileID; else CounterMappingContext(Expressions).dump
(C, dbgs()); dbgs() << "\n"; }; } } while (false)
243 if (Kind == CounterMappingRegion::ExpansionRegion)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("coverage-mapping")) { { dbgs() << "Counter in file " <<
InferredFileID << " " << LineStart << ":" <<
ColumnStart << " -> " << (LineStart + NumLines
) << ":" << ColumnEnd << ", "; if (Kind == CounterMappingRegion
::ExpansionRegion) dbgs() << "Expands to file " <<
ExpandedFileID; else CounterMappingContext(Expressions).dump
(C, dbgs()); dbgs() << "\n"; }; } } while (false)
244 dbgs() << "Expands to file " << ExpandedFileID;do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("coverage-mapping")) { { dbgs() << "Counter in file " <<
InferredFileID << " " << LineStart << ":" <<
ColumnStart << " -> " << (LineStart + NumLines
) << ":" << ColumnEnd << ", "; if (Kind == CounterMappingRegion
::ExpansionRegion) dbgs() << "Expands to file " <<
ExpandedFileID; else CounterMappingContext(Expressions).dump
(C, dbgs()); dbgs() << "\n"; }; } } while (false)
245 elsedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("coverage-mapping")) { { dbgs() << "Counter in file " <<
InferredFileID << " " << LineStart << ":" <<
ColumnStart << " -> " << (LineStart + NumLines
) << ":" << ColumnEnd << ", "; if (Kind == CounterMappingRegion
::ExpansionRegion) dbgs() << "Expands to file " <<
ExpandedFileID; else CounterMappingContext(Expressions).dump
(C, dbgs()); dbgs() << "\n"; }; } } while (false)
246 CounterMappingContext(Expressions).dump(C, dbgs());do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("coverage-mapping")) { { dbgs() << "Counter in file " <<
InferredFileID << " " << LineStart << ":" <<
ColumnStart << " -> " << (LineStart + NumLines
) << ":" << ColumnEnd << ", "; if (Kind == CounterMappingRegion
::ExpansionRegion) dbgs() << "Expands to file " <<
ExpandedFileID; else CounterMappingContext(Expressions).dump
(C, dbgs()); dbgs() << "\n"; }; } } while (false)
247 dbgs() << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("coverage-mapping")) { { dbgs() << "Counter in file " <<
InferredFileID << " " << LineStart << ":" <<
ColumnStart << " -> " << (LineStart + NumLines
) << ":" << ColumnEnd << ", "; if (Kind == CounterMappingRegion
::ExpansionRegion) dbgs() << "Expands to file " <<
ExpandedFileID; else CounterMappingContext(Expressions).dump
(C, dbgs()); dbgs() << "\n"; }; } } while (false)
248 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("coverage-mapping")) { { dbgs() << "Counter in file " <<
InferredFileID << " " << LineStart << ":" <<
ColumnStart << " -> " << (LineStart + NumLines
) << ":" << ColumnEnd << ", "; if (Kind == CounterMappingRegion
::ExpansionRegion) dbgs() << "Expands to file " <<
ExpandedFileID; else CounterMappingContext(Expressions).dump
(C, dbgs()); dbgs() << "\n"; }; } } while (false)
;
249
250 auto CMR = CounterMappingRegion(C, InferredFileID, ExpandedFileID,
251 LineStart, ColumnStart,
252 LineStart + NumLines, ColumnEnd, Kind);
253 if (CMR.startLoc() > CMR.endLoc())
254 return make_error<CoverageMapError>(coveragemap_error::malformed);
255 MappingRegions.push_back(CMR);
256 }
257 return Error::success();
258}
259
260Error RawCoverageMappingReader::read() {
261 // Read the virtual file mapping.
262 SmallVector<unsigned, 8> VirtualFileMapping;
263 uint64_t NumFileMappings;
264 if (auto Err = readSize(NumFileMappings))
3
Taking false branch
265 return Err;
266 for (size_t I = 0; I < NumFileMappings; ++I) {
4
Assuming 'I' is >= 'NumFileMappings'
5
Loop condition is false. Execution continues on line 274
267 uint64_t FilenameIndex;
268 if (auto Err = readIntMax(FilenameIndex, TranslationUnitFilenames.size()))
269 return Err;
270 VirtualFileMapping.push_back(FilenameIndex);
271 }
272
273 // Construct the files using unique filenames and virtual file mapping.
274 for (auto I : VirtualFileMapping) {
6
Assuming '__begin' is equal to '__end'
275 Filenames.push_back(TranslationUnitFilenames[I]);
276 }
277
278 // Read the expressions.
279 uint64_t NumExpressions;
280 if (auto Err = readSize(NumExpressions))
7
Taking false branch
281 return Err;
282 // Create an array of dummy expressions that get the proper counters
283 // when the expressions are read, and the proper kinds when the counters
284 // are decoded.
285 Expressions.resize(
286 NumExpressions,
287 CounterExpression(CounterExpression::Subtract, Counter(), Counter()));
288 for (size_t I = 0; I < NumExpressions; ++I) {
8
Assuming 'I' is >= 'NumExpressions'
9
Loop condition is false. Execution continues on line 296
289 if (auto Err = readCounter(Expressions[I].LHS))
290 return Err;
291 if (auto Err = readCounter(Expressions[I].RHS))
292 return Err;
293 }
294
295 // Read the mapping regions sub-arrays.
296 for (unsigned InferredFileID = 0, S = VirtualFileMapping.size();
11
Loop condition is true. Entering loop body
14
Loop condition is true. Entering loop body
17
Loop condition is true. Entering loop body
20
Loop condition is true. Entering loop body
297 InferredFileID < S; ++InferredFileID) {
10
Assuming 'InferredFileID' is < 'S'
13
Assuming 'InferredFileID' is < 'S'
16
Assuming 'InferredFileID' is < 'S'
19
Assuming 'InferredFileID' is < 'S'
298 if (auto Err = readMappingRegionsSubArray(MappingRegions, InferredFileID,
12
Taking false branch
15
Taking false branch
18
Taking false branch
21
Calling 'RawCoverageMappingReader::readMappingRegionsSubArray'
299 VirtualFileMapping.size()))
300 return Err;
301 }
302
303 // Set the counters for the expansion regions.
304 // i.e. Counter of expansion region = counter of the first region
305 // from the expanded file.
306 // Perform multiple passes to correctly propagate the counters through
307 // all the nested expansion regions.
308 SmallVector<CounterMappingRegion *, 8> FileIDExpansionRegionMapping;
309 FileIDExpansionRegionMapping.resize(VirtualFileMapping.size(), nullptr);
310 for (unsigned Pass = 1, S = VirtualFileMapping.size(); Pass < S; ++Pass) {
311 for (auto &R : MappingRegions) {
312 if (R.Kind != CounterMappingRegion::ExpansionRegion)
313 continue;
314 assert(!FileIDExpansionRegionMapping[R.ExpandedFileID])((!FileIDExpansionRegionMapping[R.ExpandedFileID]) ? static_cast
<void> (0) : __assert_fail ("!FileIDExpansionRegionMapping[R.ExpandedFileID]"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/lib/ProfileData/Coverage/CoverageMappingReader.cpp"
, 314, __PRETTY_FUNCTION__))
;
315 FileIDExpansionRegionMapping[R.ExpandedFileID] = &R;
316 }
317 for (auto &R : MappingRegions) {
318 if (FileIDExpansionRegionMapping[R.FileID]) {
319 FileIDExpansionRegionMapping[R.FileID]->Count = R.Count;
320 FileIDExpansionRegionMapping[R.FileID] = nullptr;
321 }
322 }
323 }
324
325 return Error::success();
326}
327
328Expected<bool> RawCoverageMappingDummyChecker::isDummy() {
329 // A dummy coverage mapping data consists of just one region with zero count.
330 uint64_t NumFileMappings;
331 if (Error Err = readSize(NumFileMappings))
332 return std::move(Err);
333 if (NumFileMappings != 1)
334 return false;
335 // We don't expect any specific value for the filename index, just skip it.
336 uint64_t FilenameIndex;
337 if (Error Err =
338 readIntMax(FilenameIndex, std::numeric_limits<unsigned>::max()))
339 return std::move(Err);
340 uint64_t NumExpressions;
341 if (Error Err = readSize(NumExpressions))
342 return std::move(Err);
343 if (NumExpressions != 0)
344 return false;
345 uint64_t NumRegions;
346 if (Error Err = readSize(NumRegions))
347 return std::move(Err);
348 if (NumRegions != 1)
349 return false;
350 uint64_t EncodedCounterAndRegion;
351 if (Error Err = readIntMax(EncodedCounterAndRegion,
352 std::numeric_limits<unsigned>::max()))
353 return std::move(Err);
354 unsigned Tag = EncodedCounterAndRegion & Counter::EncodingTagMask;
355 return Tag == Counter::Zero;
356}
357
358Error InstrProfSymtab::create(SectionRef &Section) {
359 if (auto EC = Section.getContents(Data))
360 return errorCodeToError(EC);
361 Address = Section.getAddress();
362 return Error::success();
363}
364
365StringRef InstrProfSymtab::getFuncName(uint64_t Pointer, size_t Size) {
366 if (Pointer < Address)
367 return StringRef();
368 auto Offset = Pointer - Address;
369 if (Offset + Size > Data.size())
370 return StringRef();
371 return Data.substr(Pointer - Address, Size);
372}
373
374// Check if the mapping data is a dummy, i.e. is emitted for an unused function.
375static Expected<bool> isCoverageMappingDummy(uint64_t Hash, StringRef Mapping) {
376 // The hash value of dummy mapping records is always zero.
377 if (Hash)
378 return false;
379 return RawCoverageMappingDummyChecker(Mapping).isDummy();
380}
381
382namespace {
383
384struct CovMapFuncRecordReader {
385 virtual ~CovMapFuncRecordReader() = default;
386
387 // The interface to read coverage mapping function records for a module.
388 //
389 // \p Buf points to the buffer containing the \c CovHeader of the coverage
390 // mapping data associated with the module.
391 //
392 // Returns a pointer to the next \c CovHeader if it exists, or a pointer
393 // greater than \p End if not.
394 virtual Expected<const char *> readFunctionRecords(const char *Buf,
395 const char *End) = 0;
396
397 template <class IntPtrT, support::endianness Endian>
398 static Expected<std::unique_ptr<CovMapFuncRecordReader>>
399 get(CovMapVersion Version, InstrProfSymtab &P,
400 std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
401 std::vector<StringRef> &F);
402};
403
404// A class for reading coverage mapping function records for a module.
405template <CovMapVersion Version, class IntPtrT, support::endianness Endian>
406class VersionedCovMapFuncRecordReader : public CovMapFuncRecordReader {
407 using FuncRecordType =
408 typename CovMapTraits<Version, IntPtrT>::CovMapFuncRecordType;
409 using NameRefType = typename CovMapTraits<Version, IntPtrT>::NameRefType;
410
411 // Maps function's name references to the indexes of their records
412 // in \c Records.
413 DenseMap<NameRefType, size_t> FunctionRecords;
414 InstrProfSymtab &ProfileNames;
415 std::vector<StringRef> &Filenames;
416 std::vector<BinaryCoverageReader::ProfileMappingRecord> &Records;
417
418 // Add the record to the collection if we don't already have a record that
419 // points to the same function name. This is useful to ignore the redundant
420 // records for the functions with ODR linkage.
421 // In addition, prefer records with real coverage mapping data to dummy
422 // records, which were emitted for inline functions which were seen but
423 // not used in the corresponding translation unit.
424 Error insertFunctionRecordIfNeeded(const FuncRecordType *CFR,
425 StringRef Mapping, size_t FilenamesBegin) {
426 uint64_t FuncHash = CFR->template getFuncHash<Endian>();
427 NameRefType NameRef = CFR->template getFuncNameRef<Endian>();
428 auto InsertResult =
429 FunctionRecords.insert(std::make_pair(NameRef, Records.size()));
430 if (InsertResult.second) {
431 StringRef FuncName;
432 if (Error Err = CFR->template getFuncName<Endian>(ProfileNames, FuncName))
433 return Err;
434 if (FuncName.empty())
435 return make_error<InstrProfError>(instrprof_error::malformed);
436 Records.emplace_back(Version, FuncName, FuncHash, Mapping, FilenamesBegin,
437 Filenames.size() - FilenamesBegin);
438 return Error::success();
439 }
440 // Update the existing record if it's a dummy and the new record is real.
441 size_t OldRecordIndex = InsertResult.first->second;
442 BinaryCoverageReader::ProfileMappingRecord &OldRecord =
443 Records[OldRecordIndex];
444 Expected<bool> OldIsDummyExpected = isCoverageMappingDummy(
445 OldRecord.FunctionHash, OldRecord.CoverageMapping);
446 if (Error Err = OldIsDummyExpected.takeError())
447 return Err;
448 if (!*OldIsDummyExpected)
449 return Error::success();
450 Expected<bool> NewIsDummyExpected =
451 isCoverageMappingDummy(FuncHash, Mapping);
452 if (Error Err = NewIsDummyExpected.takeError())
453 return Err;
454 if (*NewIsDummyExpected)
455 return Error::success();
456 OldRecord.FunctionHash = FuncHash;
457 OldRecord.CoverageMapping = Mapping;
458 OldRecord.FilenamesBegin = FilenamesBegin;
459 OldRecord.FilenamesSize = Filenames.size() - FilenamesBegin;
460 return Error::success();
461 }
462
463public:
464 VersionedCovMapFuncRecordReader(
465 InstrProfSymtab &P,
466 std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
467 std::vector<StringRef> &F)
468 : ProfileNames(P), Filenames(F), Records(R) {}
469
470 ~VersionedCovMapFuncRecordReader() override = default;
471
472 Expected<const char *> readFunctionRecords(const char *Buf,
473 const char *End) override {
474 using namespace support;
475
476 if (Buf + sizeof(CovMapHeader) > End)
477 return make_error<CoverageMapError>(coveragemap_error::malformed);
478 auto CovHeader = reinterpret_cast<const CovMapHeader *>(Buf);
479 uint32_t NRecords = CovHeader->getNRecords<Endian>();
480 uint32_t FilenamesSize = CovHeader->getFilenamesSize<Endian>();
481 uint32_t CoverageSize = CovHeader->getCoverageSize<Endian>();
482 assert((CovMapVersion)CovHeader->getVersion<Endian>() == Version)(((CovMapVersion)CovHeader->getVersion<Endian>() == Version
) ? static_cast<void> (0) : __assert_fail ("(CovMapVersion)CovHeader->getVersion<Endian>() == Version"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/lib/ProfileData/Coverage/CoverageMappingReader.cpp"
, 482, __PRETTY_FUNCTION__))
;
483 Buf = reinterpret_cast<const char *>(CovHeader + 1);
484
485 // Skip past the function records, saving the start and end for later.
486 const char *FunBuf = Buf;
487 Buf += NRecords * sizeof(FuncRecordType);
488 const char *FunEnd = Buf;
489
490 // Get the filenames.
491 if (Buf + FilenamesSize > End)
492 return make_error<CoverageMapError>(coveragemap_error::malformed);
493 size_t FilenamesBegin = Filenames.size();
494 RawCoverageFilenamesReader Reader(StringRef(Buf, FilenamesSize), Filenames);
495 if (auto Err = Reader.read())
496 return std::move(Err);
497 Buf += FilenamesSize;
498
499 // We'll read the coverage mapping records in the loop below.
500 const char *CovBuf = Buf;
501 Buf += CoverageSize;
502 const char *CovEnd = Buf;
503
504 if (Buf > End)
505 return make_error<CoverageMapError>(coveragemap_error::malformed);
506 // Each coverage map has an alignment of 8, so we need to adjust alignment
507 // before reading the next map.
508 Buf += alignmentAdjustment(Buf, 8);
509
510 auto CFR = reinterpret_cast<const FuncRecordType *>(FunBuf);
511 while ((const char *)CFR < FunEnd) {
512 // Read the function information
513 uint32_t DataSize = CFR->template getDataSize<Endian>();
514
515 // Now use that to read the coverage data.
516 if (CovBuf + DataSize > CovEnd)
517 return make_error<CoverageMapError>(coveragemap_error::malformed);
518 auto Mapping = StringRef(CovBuf, DataSize);
519 CovBuf += DataSize;
520
521 if (Error Err =
522 insertFunctionRecordIfNeeded(CFR, Mapping, FilenamesBegin))
523 return std::move(Err);
524 CFR++;
525 }
526 return Buf;
527 }
528};
529
530} // end anonymous namespace
531
532template <class IntPtrT, support::endianness Endian>
533Expected<std::unique_ptr<CovMapFuncRecordReader>> CovMapFuncRecordReader::get(
534 CovMapVersion Version, InstrProfSymtab &P,
535 std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
536 std::vector<StringRef> &F) {
537 using namespace coverage;
538
539 switch (Version) {
540 case CovMapVersion::Version1:
541 return llvm::make_unique<VersionedCovMapFuncRecordReader<
542 CovMapVersion::Version1, IntPtrT, Endian>>(P, R, F);
543 case CovMapVersion::Version2:
544 case CovMapVersion::Version3:
545 // Decompress the name data.
546 if (Error E = P.create(P.getNameData()))
547 return std::move(E);
548 if (Version == CovMapVersion::Version2)
549 return llvm::make_unique<VersionedCovMapFuncRecordReader<
550 CovMapVersion::Version2, IntPtrT, Endian>>(P, R, F);
551 else
552 return llvm::make_unique<VersionedCovMapFuncRecordReader<
553 CovMapVersion::Version3, IntPtrT, Endian>>(P, R, F);
554 }
555 llvm_unreachable("Unsupported version")::llvm::llvm_unreachable_internal("Unsupported version", "/build/llvm-toolchain-snapshot-6.0~svn318211/lib/ProfileData/Coverage/CoverageMappingReader.cpp"
, 555)
;
556}
557
558template <typename T, support::endianness Endian>
559static Error readCoverageMappingData(
560 InstrProfSymtab &ProfileNames, StringRef Data,
561 std::vector<BinaryCoverageReader::ProfileMappingRecord> &Records,
562 std::vector<StringRef> &Filenames) {
563 using namespace coverage;
564
565 // Read the records in the coverage data section.
566 auto CovHeader =
567 reinterpret_cast<const CovMapHeader *>(Data.data());
568 CovMapVersion Version = (CovMapVersion)CovHeader->getVersion<Endian>();
569 if (Version > CovMapVersion::CurrentVersion)
570 return make_error<CoverageMapError>(coveragemap_error::unsupported_version);
571 Expected<std::unique_ptr<CovMapFuncRecordReader>> ReaderExpected =
572 CovMapFuncRecordReader::get<T, Endian>(Version, ProfileNames, Records,
573 Filenames);
574 if (Error E = ReaderExpected.takeError())
575 return E;
576 auto Reader = std::move(ReaderExpected.get());
577 for (const char *Buf = Data.data(), *End = Buf + Data.size(); Buf < End;) {
578 auto NextHeaderOrErr = Reader->readFunctionRecords(Buf, End);
579 if (auto E = NextHeaderOrErr.takeError())
580 return E;
581 Buf = NextHeaderOrErr.get();
582 }
583 return Error::success();
584}
585
586static const char *TestingFormatMagic = "llvmcovmtestdata";
587
588static Error loadTestingFormat(StringRef Data, InstrProfSymtab &ProfileNames,
589 StringRef &CoverageMapping,
590 uint8_t &BytesInAddress,
591 support::endianness &Endian) {
592 BytesInAddress = 8;
593 Endian = support::endianness::little;
594
595 Data = Data.substr(StringRef(TestingFormatMagic).size());
596 if (Data.empty())
597 return make_error<CoverageMapError>(coveragemap_error::truncated);
598 unsigned N = 0;
599 auto ProfileNamesSize =
600 decodeULEB128(reinterpret_cast<const uint8_t *>(Data.data()), &N);
601 if (N > Data.size())
602 return make_error<CoverageMapError>(coveragemap_error::malformed);
603 Data = Data.substr(N);
604 if (Data.empty())
605 return make_error<CoverageMapError>(coveragemap_error::truncated);
606 N = 0;
607 uint64_t Address =
608 decodeULEB128(reinterpret_cast<const uint8_t *>(Data.data()), &N);
609 if (N > Data.size())
610 return make_error<CoverageMapError>(coveragemap_error::malformed);
611 Data = Data.substr(N);
612 if (Data.size() < ProfileNamesSize)
613 return make_error<CoverageMapError>(coveragemap_error::malformed);
614 if (Error E = ProfileNames.create(Data.substr(0, ProfileNamesSize), Address))
615 return E;
616 CoverageMapping = Data.substr(ProfileNamesSize);
617 // Skip the padding bytes because coverage map data has an alignment of 8.
618 if (CoverageMapping.empty())
619 return make_error<CoverageMapError>(coveragemap_error::truncated);
620 size_t Pad = alignmentAdjustment(CoverageMapping.data(), 8);
621 if (CoverageMapping.size() < Pad)
622 return make_error<CoverageMapError>(coveragemap_error::malformed);
623 CoverageMapping = CoverageMapping.substr(Pad);
624 return Error::success();
625}
626
627static Expected<SectionRef> lookupSection(ObjectFile &OF, StringRef Name) {
628 StringRef FoundName;
629 for (const auto &Section : OF.sections()) {
630 if (auto EC = Section.getName(FoundName))
631 return errorCodeToError(EC);
632 if (FoundName == Name)
633 return Section;
634 }
635 return make_error<CoverageMapError>(coveragemap_error::no_data_found);
636}
637
638static Error loadBinaryFormat(MemoryBufferRef ObjectBuffer,
639 InstrProfSymtab &ProfileNames,
640 StringRef &CoverageMapping,
641 uint8_t &BytesInAddress,
642 support::endianness &Endian, StringRef Arch) {
643 auto BinOrErr = createBinary(ObjectBuffer);
644 if (!BinOrErr)
645 return BinOrErr.takeError();
646 auto Bin = std::move(BinOrErr.get());
647 std::unique_ptr<ObjectFile> OF;
648 if (auto *Universal = dyn_cast<MachOUniversalBinary>(Bin.get())) {
649 // If we have a universal binary, try to look up the object for the
650 // appropriate architecture.
651 auto ObjectFileOrErr = Universal->getObjectForArch(Arch);
652 if (!ObjectFileOrErr)
653 return ObjectFileOrErr.takeError();
654 OF = std::move(ObjectFileOrErr.get());
655 } else if (isa<ObjectFile>(Bin.get())) {
656 // For any other object file, upcast and take ownership.
657 OF.reset(cast<ObjectFile>(Bin.release()));
658 // If we've asked for a particular arch, make sure they match.
659 if (!Arch.empty() && OF->getArch() != Triple(Arch).getArch())
660 return errorCodeToError(object_error::arch_not_found);
661 } else
662 // We can only handle object files.
663 return make_error<CoverageMapError>(coveragemap_error::malformed);
664
665 // The coverage uses native pointer sizes for the object it's written in.
666 BytesInAddress = OF->getBytesInAddress();
667 Endian = OF->isLittleEndian() ? support::endianness::little
668 : support::endianness::big;
669
670 // Look for the sections that we are interested in.
671 auto ObjFormat = OF->getTripleObjectFormat();
672 auto NamesSection =
673 lookupSection(*OF, getInstrProfSectionName(IPSK_name, ObjFormat,
674 /*AddSegmentInfo=*/false));
675 if (auto E = NamesSection.takeError())
676 return E;
677 auto CoverageSection =
678 lookupSection(*OF, getInstrProfSectionName(IPSK_covmap, ObjFormat,
679 /*AddSegmentInfo=*/false));
680 if (auto E = CoverageSection.takeError())
681 return E;
682
683 // Get the contents of the given sections.
684 if (auto EC = CoverageSection->getContents(CoverageMapping))
685 return errorCodeToError(EC);
686 if (Error E = ProfileNames.create(*NamesSection))
687 return E;
688
689 return Error::success();
690}
691
692Expected<std::unique_ptr<BinaryCoverageReader>>
693BinaryCoverageReader::create(std::unique_ptr<MemoryBuffer> &ObjectBuffer,
694 StringRef Arch) {
695 std::unique_ptr<BinaryCoverageReader> Reader(new BinaryCoverageReader());
696
697 StringRef Coverage;
698 uint8_t BytesInAddress;
699 support::endianness Endian;
700 Error E = Error::success();
701 consumeError(std::move(E));
702 if (ObjectBuffer->getBuffer().startswith(TestingFormatMagic))
703 // This is a special format used for testing.
704 E = loadTestingFormat(ObjectBuffer->getBuffer(), Reader->ProfileNames,
705 Coverage, BytesInAddress, Endian);
706 else
707 E = loadBinaryFormat(ObjectBuffer->getMemBufferRef(), Reader->ProfileNames,
708 Coverage, BytesInAddress, Endian, Arch);
709 if (E)
710 return std::move(E);
711
712 if (BytesInAddress == 4 && Endian == support::endianness::little)
713 E = readCoverageMappingData<uint32_t, support::endianness::little>(
714 Reader->ProfileNames, Coverage, Reader->MappingRecords,
715 Reader->Filenames);
716 else if (BytesInAddress == 4 && Endian == support::endianness::big)
717 E = readCoverageMappingData<uint32_t, support::endianness::big>(
718 Reader->ProfileNames, Coverage, Reader->MappingRecords,
719 Reader->Filenames);
720 else if (BytesInAddress == 8 && Endian == support::endianness::little)
721 E = readCoverageMappingData<uint64_t, support::endianness::little>(
722 Reader->ProfileNames, Coverage, Reader->MappingRecords,
723 Reader->Filenames);
724 else if (BytesInAddress == 8 && Endian == support::endianness::big)
725 E = readCoverageMappingData<uint64_t, support::endianness::big>(
726 Reader->ProfileNames, Coverage, Reader->MappingRecords,
727 Reader->Filenames);
728 else
729 return make_error<CoverageMapError>(coveragemap_error::malformed);
730 if (E)
731 return std::move(E);
732 return std::move(Reader);
733}
734
735Error BinaryCoverageReader::readNextRecord(CoverageMappingRecord &Record) {
736 if (CurrentRecord >= MappingRecords.size())
1
Taking false branch
737 return make_error<CoverageMapError>(coveragemap_error::eof);
738
739 FunctionsFilenames.clear();
740 Expressions.clear();
741 MappingRegions.clear();
742 auto &R = MappingRecords[CurrentRecord];
743 RawCoverageMappingReader Reader(
744 R.CoverageMapping,
745 makeArrayRef(Filenames).slice(R.FilenamesBegin, R.FilenamesSize),
746 FunctionsFilenames, Expressions, MappingRegions);
747 if (auto Err = Reader.read())
2
Calling 'RawCoverageMappingReader::read'
748 return Err;
749
750 Record.FunctionName = R.FunctionName;
751 Record.FunctionHash = R.FunctionHash;
752 Record.Filenames = FunctionsFilenames;
753 Record.Expressions = Expressions;
754 Record.MappingRegions = MappingRegions;
755
756 ++CurrentRecord;
757 return Error::success();
758}

/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/Support/Error.h

1//===- llvm/Support/Error.h - Recoverable error handling --------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines an API used to report recoverable errors.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_SUPPORT_ERROR_H
15#define LLVM_SUPPORT_ERROR_H
16
17#include "llvm/ADT/SmallVector.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/StringExtras.h"
20#include "llvm/ADT/Twine.h"
21#include "llvm/Config/abi-breaking.h"
22#include "llvm/Support/AlignOf.h"
23#include "llvm/Support/Compiler.h"
24#include "llvm/Support/Debug.h"
25#include "llvm/Support/ErrorHandling.h"
26#include "llvm/Support/ErrorOr.h"
27#include "llvm/Support/raw_ostream.h"
28#include <algorithm>
29#include <cassert>
30#include <cstdint>
31#include <cstdlib>
32#include <functional>
33#include <memory>
34#include <new>
35#include <string>
36#include <system_error>
37#include <type_traits>
38#include <utility>
39#include <vector>
40
41namespace llvm {
42
43class ErrorSuccess;
44
45/// Base class for error info classes. Do not extend this directly: Extend
46/// the ErrorInfo template subclass instead.
47class ErrorInfoBase {
48public:
49 virtual ~ErrorInfoBase() = default;
50
51 /// Print an error message to an output stream.
52 virtual void log(raw_ostream &OS) const = 0;
53
54 /// Return the error message as a string.
55 virtual std::string message() const {
56 std::string Msg;
57 raw_string_ostream OS(Msg);
58 log(OS);
59 return OS.str();
60 }
61
62 /// Convert this error to a std::error_code.
63 ///
64 /// This is a temporary crutch to enable interaction with code still
65 /// using std::error_code. It will be removed in the future.
66 virtual std::error_code convertToErrorCode() const = 0;
67
68 // Returns the class ID for this type.
69 static const void *classID() { return &ID; }
70
71 // Returns the class ID for the dynamic type of this ErrorInfoBase instance.
72 virtual const void *dynamicClassID() const = 0;
73
74 // Check whether this instance is a subclass of the class identified by
75 // ClassID.
76 virtual bool isA(const void *const ClassID) const {
77 return ClassID == classID();
78 }
79
80 // Check whether this instance is a subclass of ErrorInfoT.
81 template <typename ErrorInfoT> bool isA() const {
82 return isA(ErrorInfoT::classID());
83 }
84
85private:
86 virtual void anchor();
87
88 static char ID;
89};
90
91/// Lightweight error class with error context and mandatory checking.
92///
93/// Instances of this class wrap a ErrorInfoBase pointer. Failure states
94/// are represented by setting the pointer to a ErrorInfoBase subclass
95/// instance containing information describing the failure. Success is
96/// represented by a null pointer value.
97///
98/// Instances of Error also contains a 'Checked' flag, which must be set
99/// before the destructor is called, otherwise the destructor will trigger a
100/// runtime error. This enforces at runtime the requirement that all Error
101/// instances be checked or returned to the caller.
102///
103/// There are two ways to set the checked flag, depending on what state the
104/// Error instance is in. For Error instances indicating success, it
105/// is sufficient to invoke the boolean conversion operator. E.g.:
106///
107/// @code{.cpp}
108/// Error foo(<...>);
109///
110/// if (auto E = foo(<...>))
111/// return E; // <- Return E if it is in the error state.
112/// // We have verified that E was in the success state. It can now be safely
113/// // destroyed.
114/// @endcode
115///
116/// A success value *can not* be dropped. For example, just calling 'foo(<...>)'
117/// without testing the return value will raise a runtime error, even if foo
118/// returns success.
119///
120/// For Error instances representing failure, you must use either the
121/// handleErrors or handleAllErrors function with a typed handler. E.g.:
122///
123/// @code{.cpp}
124/// class MyErrorInfo : public ErrorInfo<MyErrorInfo> {
125/// // Custom error info.
126/// };
127///
128/// Error foo(<...>) { return make_error<MyErrorInfo>(...); }
129///
130/// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo.
131/// auto NewE =
132/// handleErrors(E,
133/// [](const MyErrorInfo &M) {
134/// // Deal with the error.
135/// },
136/// [](std::unique_ptr<OtherError> M) -> Error {
137/// if (canHandle(*M)) {
138/// // handle error.
139/// return Error::success();
140/// }
141/// // Couldn't handle this error instance. Pass it up the stack.
142/// return Error(std::move(M));
143/// );
144/// // Note - we must check or return NewE in case any of the handlers
145/// // returned a new error.
146/// @endcode
147///
148/// The handleAllErrors function is identical to handleErrors, except
149/// that it has a void return type, and requires all errors to be handled and
150/// no new errors be returned. It prevents errors (assuming they can all be
151/// handled) from having to be bubbled all the way to the top-level.
152///
153/// *All* Error instances must be checked before destruction, even if
154/// they're moved-assigned or constructed from Success values that have already
155/// been checked. This enforces checking through all levels of the call stack.
156class LLVM_NODISCARD[[clang::warn_unused_result]] Error {
157 // ErrorList needs to be able to yank ErrorInfoBase pointers out of this
158 // class to add to the error list.
159 friend class ErrorList;
160
161 // handleErrors needs to be able to set the Checked flag.
162 template <typename... HandlerTs>
163 friend Error handleErrors(Error E, HandlerTs &&... Handlers);
164
165 // Expected<T> needs to be able to steal the payload when constructed from an
166 // error.
167 template <typename T> friend class Expected;
168
169protected:
170 /// Create a success value. Prefer using 'Error::success()' for readability
171 Error() {
172 setPtr(nullptr);
173 setChecked(false);
174 }
175
176public:
177 /// Create a success value.
178 static ErrorSuccess success();
179
180 // Errors are not copy-constructable.
181 Error(const Error &Other) = delete;
182
183 /// Move-construct an error value. The newly constructed error is considered
184 /// unchecked, even if the source error had been checked. The original error
185 /// becomes a checked Success value, regardless of its original state.
186 Error(Error &&Other) {
187 setChecked(true);
52
Calling 'Error::setChecked'
54
Returning from 'Error::setChecked'
188 *this = std::move(Other);
55
Calling 'move'
56
Returning from 'move'
57
Calling move assignment operator for 'Error'
74
Returning from move assignment operator for 'Error'
189 }
190
191 /// Create an error value. Prefer using the 'make_error' function, but
192 /// this constructor can be useful when "re-throwing" errors from handlers.
193 Error(std::unique_ptr<ErrorInfoBase> Payload) {
194 setPtr(Payload.release());
195 setChecked(false);
196 }
197
198 // Errors are not copy-assignable.
199 Error &operator=(const Error &Other) = delete;
200
201 /// Move-assign an error value. The current error must represent success, you
202 /// you cannot overwrite an unhandled error. The current error is then
203 /// considered unchecked. The source error becomes a checked success value,
204 /// regardless of its original state.
205 Error &operator=(Error &&Other) {
206 // Don't allow overwriting of unchecked values.
207 assertIsChecked();
58
Calling 'Error::assertIsChecked'
61
Returning from 'Error::assertIsChecked'
208 setPtr(Other.getPtr());
62
Calling 'Error::getPtr'
63
Returning from 'Error::getPtr'
64
Calling 'Error::setPtr'
65
Returning from 'Error::setPtr'
209
210 // This Error is unchecked, even if the source error was checked.
211 setChecked(false);
66
Calling 'Error::setChecked'
68
Returning from 'Error::setChecked'
212
213 // Null out Other's payload and set its checked bit.
214 Other.setPtr(nullptr);
69
Calling 'Error::setPtr'
70
Returning from 'Error::setPtr'
215 Other.setChecked(true);
71
Calling 'Error::setChecked'
73
Returning from 'Error::setChecked'
216
217 return *this;
218 }
219
220 /// Destroy a Error. Fails with a call to abort() if the error is
221 /// unchecked.
222 ~Error() {
223 assertIsChecked();
88
Calling 'Error::assertIsChecked'
91
Returning from 'Error::assertIsChecked'
224 delete getPtr();
92
Calling 'Error::getPtr'
93
Returning from 'Error::getPtr'
225 }
226
227 /// Bool conversion. Returns true if this Error is in a failure state,
228 /// and false if it is in an accept state. If the error is in a Success state
229 /// it will be considered checked.
230 explicit operator bool() {
231 setChecked(getPtr() == nullptr);
77
Calling 'Error::getPtr'
78
Returning from 'Error::getPtr'
79
Calling 'Error::setChecked'
82
Returning from 'Error::setChecked'
232 return getPtr() != nullptr;
83
Calling 'Error::getPtr'
84
Returning from 'Error::getPtr'
233 }
234
235 /// Check whether one error is a subclass of another.
236 template <typename ErrT> bool isA() const {
237 return getPtr() && getPtr()->isA(ErrT::classID());
238 }
239
240 /// Returns the dynamic class id of this error, or null if this is a success
241 /// value.
242 const void* dynamicClassID() const {
243 if (!getPtr())
244 return nullptr;
245 return getPtr()->dynamicClassID();
246 }
247
248private:
249#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
250 // assertIsChecked() happens very frequently, but under normal circumstances
251 // is supposed to be a no-op. So we want it to be inlined, but having a bunch
252 // of debug prints can cause the function to be too large for inlining. So
253 // it's important that we define this function out of line so that it can't be
254 // inlined.
255 LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn))
256 void fatalUncheckedError() const;
257#endif
258
259 void assertIsChecked() {
260#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
261 if (LLVM_UNLIKELY(!getChecked() || getPtr())__builtin_expect((bool)(!getChecked() || getPtr()), false))
59
Within the expansion of the macro 'LLVM_UNLIKELY':
a
Calling 'Error::getChecked'
b
Returning from 'Error::getChecked'
c
Calling 'Error::getPtr'
d
Returning from 'Error::getPtr'
60
Taking false branch
89
Within the expansion of the macro 'LLVM_UNLIKELY':
a
Calling 'Error::getChecked'
b
Returning from 'Error::getChecked'
90
Taking false branch
262 fatalUncheckedError();
263#endif
264 }
265
266 ErrorInfoBase *getPtr() const {
267 return reinterpret_cast<ErrorInfoBase*>(
268 reinterpret_cast<uintptr_t>(Payload) &
269 ~static_cast<uintptr_t>(0x1));
270 }
271
272 void setPtr(ErrorInfoBase *EI) {
273#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
274 Payload = reinterpret_cast<ErrorInfoBase*>(
275 (reinterpret_cast<uintptr_t>(EI) &
276 ~static_cast<uintptr_t>(0x1)) |
277 (reinterpret_cast<uintptr_t>(Payload) & 0x1));
278#else
279 Payload = EI;
280#endif
281 }
282
283 bool getChecked() const {
284#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
285 return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0;
286#else
287 return true;
288#endif
289 }
290
291 void setChecked(bool V) {
292 Payload = reinterpret_cast<ErrorInfoBase*>(
293 (reinterpret_cast<uintptr_t>(Payload) &
294 ~static_cast<uintptr_t>(0x1)) |
295 (V ? 0 : 1));
53
'?' condition is true
67
'?' condition is false
72
'?' condition is true
80
Assuming 'V' is 0
81
'?' condition is false
296 }
297
298 std::unique_ptr<ErrorInfoBase> takePayload() {
299 std::unique_ptr<ErrorInfoBase> Tmp(getPtr());
300 setPtr(nullptr);
301 setChecked(true);
302 return Tmp;
303 }
304
305 ErrorInfoBase *Payload = nullptr;
306};
307
308/// Subclass of Error for the sole purpose of identifying the success path in
309/// the type system. This allows to catch invalid conversion to Expected<T> at
310/// compile time.
311class ErrorSuccess : public Error {};
312
313inline ErrorSuccess Error::success() { return ErrorSuccess(); }
314
315/// Make a Error instance representing failure using the given error info
316/// type.
317template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) {
318 return Error(llvm::make_unique<ErrT>(std::forward<ArgTs>(Args)...));
43
Calling 'forward'
44
Returning from 'forward'
45
Calling 'make_unique'
48
Returning from 'make_unique'
319}
320
321/// Base class for user error types. Users should declare their error types
322/// like:
323///
324/// class MyError : public ErrorInfo<MyError> {
325/// ....
326/// };
327///
328/// This class provides an implementation of the ErrorInfoBase::kind
329/// method, which is used by the Error RTTI system.
330template <typename ThisErrT, typename ParentErrT = ErrorInfoBase>
331class ErrorInfo : public ParentErrT {
332public:
333 static const void *classID() { return &ThisErrT::ID; }
334
335 const void *dynamicClassID() const override { return &ThisErrT::ID; }
336
337 bool isA(const void *const ClassID) const override {
338 return ClassID == classID() || ParentErrT::isA(ClassID);
339 }
340};
341
342/// Special ErrorInfo subclass representing a list of ErrorInfos.
343/// Instances of this class are constructed by joinError.
344class ErrorList final : public ErrorInfo<ErrorList> {
345 // handleErrors needs to be able to iterate the payload list of an
346 // ErrorList.
347 template <typename... HandlerTs>
348 friend Error handleErrors(Error E, HandlerTs &&... Handlers);
349
350 // joinErrors is implemented in terms of join.
351 friend Error joinErrors(Error, Error);
352
353public:
354 void log(raw_ostream &OS) const override {
355 OS << "Multiple errors:\n";
356 for (auto &ErrPayload : Payloads) {
357 ErrPayload->log(OS);
358 OS << "\n";
359 }
360 }
361
362 std::error_code convertToErrorCode() const override;
363
364 // Used by ErrorInfo::classID.
365 static char ID;
366
367private:
368 ErrorList(std::unique_ptr<ErrorInfoBase> Payload1,
369 std::unique_ptr<ErrorInfoBase> Payload2) {
370 assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() &&((!Payload1->isA<ErrorList>() && !Payload2->
isA<ErrorList>() && "ErrorList constructor payloads should be singleton errors"
) ? static_cast<void> (0) : __assert_fail ("!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() && \"ErrorList constructor payloads should be singleton errors\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/Support/Error.h"
, 371, __PRETTY_FUNCTION__))
371 "ErrorList constructor payloads should be singleton errors")((!Payload1->isA<ErrorList>() && !Payload2->
isA<ErrorList>() && "ErrorList constructor payloads should be singleton errors"
) ? static_cast<void> (0) : __assert_fail ("!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() && \"ErrorList constructor payloads should be singleton errors\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/Support/Error.h"
, 371, __PRETTY_FUNCTION__))
;
372 Payloads.push_back(std::move(Payload1));
373 Payloads.push_back(std::move(Payload2));
374 }
375
376 static Error join(Error E1, Error E2) {
377 if (!E1)
378 return E2;
379 if (!E2)
380 return E1;
381 if (E1.isA<ErrorList>()) {
382 auto &E1List = static_cast<ErrorList &>(*E1.getPtr());
383 if (E2.isA<ErrorList>()) {
384 auto E2Payload = E2.takePayload();
385 auto &E2List = static_cast<ErrorList &>(*E2Payload);
386 for (auto &Payload : E2List.Payloads)
387 E1List.Payloads.push_back(std::move(Payload));
388 } else
389 E1List.Payloads.push_back(E2.takePayload());
390
391 return E1;
392 }
393 if (E2.isA<ErrorList>()) {
394 auto &E2List = static_cast<ErrorList &>(*E2.getPtr());
395 E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload());
396 return E2;
397 }
398 return Error(std::unique_ptr<ErrorList>(
399 new ErrorList(E1.takePayload(), E2.takePayload())));
400 }
401
402 std::vector<std::unique_ptr<ErrorInfoBase>> Payloads;
403};
404
405/// Concatenate errors. The resulting Error is unchecked, and contains the
406/// ErrorInfo(s), if any, contained in E1, followed by the
407/// ErrorInfo(s), if any, contained in E2.
408inline Error joinErrors(Error E1, Error E2) {
409 return ErrorList::join(std::move(E1), std::move(E2));
410}
411
412/// Tagged union holding either a T or a Error.
413///
414/// This class parallels ErrorOr, but replaces error_code with Error. Since
415/// Error cannot be copied, this class replaces getError() with
416/// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the
417/// error class type.
418template <class T> class LLVM_NODISCARD[[clang::warn_unused_result]] Expected {
419 template <class T1> friend class ExpectedAsOutParameter;
420 template <class OtherT> friend class Expected;
421
422 static const bool isRef = std::is_reference<T>::value;
423
424 using wrap = ReferenceStorage<typename std::remove_reference<T>::type>;
425
426 using error_type = std::unique_ptr<ErrorInfoBase>;
427
428public:
429 using storage_type = typename std::conditional<isRef, wrap, T>::type;
430 using value_type = T;
431
432private:
433 using reference = typename std::remove_reference<T>::type &;
434 using const_reference = const typename std::remove_reference<T>::type &;
435 using pointer = typename std::remove_reference<T>::type *;
436 using const_pointer = const typename std::remove_reference<T>::type *;
437
438public:
439 /// Create an Expected<T> error value from the given Error.
440 Expected(Error Err)
441 : HasError(true)
442#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
443 // Expected is unchecked upon construction in Debug builds.
444 , Unchecked(true)
445#endif
446 {
447 assert(Err && "Cannot create Expected<T> from Error success value.")((Err && "Cannot create Expected<T> from Error success value."
) ? static_cast<void> (0) : __assert_fail ("Err && \"Cannot create Expected<T> from Error success value.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/Support/Error.h"
, 447, __PRETTY_FUNCTION__))
;
448 new (getErrorStorage()) error_type(Err.takePayload());
449 }
450
451 /// Forbid to convert from Error::success() implicitly, this avoids having
452 /// Expected<T> foo() { return Error::success(); } which compiles otherwise
453 /// but triggers the assertion above.
454 Expected(ErrorSuccess) = delete;
455
456 /// Create an Expected<T> success value from the given OtherT value, which
457 /// must be convertible to T.
458 template <typename OtherT>
459 Expected(OtherT &&Val,
460 typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
461 * = nullptr)
462 : HasError(false)
463#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
464 // Expected is unchecked upon construction in Debug builds.
465 , Unchecked(true)
466#endif
467 {
468 new (getStorage()) storage_type(std::forward<OtherT>(Val));
469 }
470
471 /// Move construct an Expected<T> value.
472 Expected(Expected &&Other) { moveConstruct(std::move(Other)); }
473
474 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
475 /// must be convertible to T.
476 template <class OtherT>
477 Expected(Expected<OtherT> &&Other,
478 typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
479 * = nullptr) {
480 moveConstruct(std::move(Other));
481 }
482
483 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
484 /// isn't convertible to T.
485 template <class OtherT>
486 explicit Expected(
487 Expected<OtherT> &&Other,
488 typename std::enable_if<!std::is_convertible<OtherT, T>::value>::type * =
489 nullptr) {
490 moveConstruct(std::move(Other));
491 }
492
493 /// Move-assign from another Expected<T>.
494 Expected &operator=(Expected &&Other) {
495 moveAssign(std::move(Other));
496 return *this;
497 }
498
499 /// Destroy an Expected<T>.
500 ~Expected() {
501 assertIsChecked();
502 if (!HasError)
503 getStorage()->~storage_type();
504 else
505 getErrorStorage()->~error_type();
506 }
507
508 /// \brief Return false if there is an error.
509 explicit operator bool() {
510#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
511 Unchecked = HasError;
512#endif
513 return !HasError;
514 }
515
516 /// \brief Returns a reference to the stored T value.
517 reference get() {
518 assertIsChecked();
519 return *getStorage();
520 }
521
522 /// \brief Returns a const reference to the stored T value.
523 const_reference get() const {
524 assertIsChecked();
525 return const_cast<Expected<T> *>(this)->get();
526 }
527
528 /// \brief Check that this Expected<T> is an error of type ErrT.
529 template <typename ErrT> bool errorIsA() const {
530 return HasError && (*getErrorStorage())->template isA<ErrT>();
531 }
532
533 /// \brief Take ownership of the stored error.
534 /// After calling this the Expected<T> is in an indeterminate state that can
535 /// only be safely destructed. No further calls (beside the destructor) should
536 /// be made on the Expected<T> vaule.
537 Error takeError() {
538#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
539 Unchecked = false;
540#endif
541 return HasError ? Error(std::move(*getErrorStorage())) : Error::success();
542 }
543
544 /// \brief Returns a pointer to the stored T value.
545 pointer operator->() {
546 assertIsChecked();
547 return toPointer(getStorage());
548 }
549
550 /// \brief Returns a const pointer to the stored T value.
551 const_pointer operator->() const {
552 assertIsChecked();
553 return toPointer(getStorage());
554 }
555
556 /// \brief Returns a reference to the stored T value.
557 reference operator*() {
558 assertIsChecked();
559 return *getStorage();
560 }
561
562 /// \brief Returns a const reference to the stored T value.
563 const_reference operator*() const {
564 assertIsChecked();
565 return *getStorage();
566 }
567
568private:
569 template <class T1>
570 static bool compareThisIfSameType(const T1 &a, const T1 &b) {
571 return &a == &b;
572 }
573
574 template <class T1, class T2>
575 static bool compareThisIfSameType(const T1 &a, const T2 &b) {
576 return false;
577 }
578
579 template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) {
580 HasError = Other.HasError;
581#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
582 Unchecked = true;
583 Other.Unchecked = false;
584#endif
585
586 if (!HasError)
587 new (getStorage()) storage_type(std::move(*Other.getStorage()));
588 else
589 new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage()));
590 }
591
592 template <class OtherT> void moveAssign(Expected<OtherT> &&Other) {
593 assertIsChecked();
594
595 if (compareThisIfSameType(*this, Other))
596 return;
597
598 this->~Expected();
599 new (this) Expected(std::move(Other));
600 }
601
602 pointer toPointer(pointer Val) { return Val; }
603
604 const_pointer toPointer(const_pointer Val) const { return Val; }
605
606 pointer toPointer(wrap *Val) { return &Val->get(); }
607
608 const_pointer toPointer(const wrap *Val) const { return &Val->get(); }
609
610 storage_type *getStorage() {
611 assert(!HasError && "Cannot get value when an error exists!")((!HasError && "Cannot get value when an error exists!"
) ? static_cast<void> (0) : __assert_fail ("!HasError && \"Cannot get value when an error exists!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/Support/Error.h"
, 611, __PRETTY_FUNCTION__))
;
612 return reinterpret_cast<storage_type *>(TStorage.buffer);
613 }
614
615 const storage_type *getStorage() const {
616 assert(!HasError && "Cannot get value when an error exists!")((!HasError && "Cannot get value when an error exists!"
) ? static_cast<void> (0) : __assert_fail ("!HasError && \"Cannot get value when an error exists!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/Support/Error.h"
, 616, __PRETTY_FUNCTION__))
;
617 return reinterpret_cast<const storage_type *>(TStorage.buffer);
618 }
619
620 error_type *getErrorStorage() {
621 assert(HasError && "Cannot get error when a value exists!")((HasError && "Cannot get error when a value exists!"
) ? static_cast<void> (0) : __assert_fail ("HasError && \"Cannot get error when a value exists!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/Support/Error.h"
, 621, __PRETTY_FUNCTION__))
;
622 return reinterpret_cast<error_type *>(ErrorStorage.buffer);
623 }
624
625 const error_type *getErrorStorage() const {
626 assert(HasError && "Cannot get error when a value exists!")((HasError && "Cannot get error when a value exists!"
) ? static_cast<void> (0) : __assert_fail ("HasError && \"Cannot get error when a value exists!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/Support/Error.h"
, 626, __PRETTY_FUNCTION__))
;
627 return reinterpret_cast<const error_type *>(ErrorStorage.buffer);
628 }
629
630 // Used by ExpectedAsOutParameter to reset the checked flag.
631 void setUnchecked() {
632#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
633 Unchecked = true;
634#endif
635 }
636
637#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
638 LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn))
639 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline))
640 void fatalUncheckedExpected() const {
641 dbgs() << "Expected<T> must be checked before access or destruction.\n";
642 if (HasError) {
643 dbgs() << "Unchecked Expected<T> contained error:\n";
644 (*getErrorStorage())->log(dbgs());
645 } else
646 dbgs() << "Expected<T> value was in success state. (Note: Expected<T> "
647 "values in success mode must still be checked prior to being "
648 "destroyed).\n";
649 abort();
650 }
651#endif
652
653 void assertIsChecked() {
654#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
655 if (LLVM_UNLIKELY(Unchecked)__builtin_expect((bool)(Unchecked), false))
656 fatalUncheckedExpected();
657#endif
658 }
659
660 union {
661 AlignedCharArrayUnion<storage_type> TStorage;
662 AlignedCharArrayUnion<error_type> ErrorStorage;
663 };
664 bool HasError : 1;
665#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
666 bool Unchecked : 1;
667#endif
668};
669
670/// Report a serious error, calling any installed error handler. See
671/// ErrorHandling.h.
672LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) void report_fatal_error(Error Err,
673 bool gen_crash_diag = true);
674
675/// Report a fatal error if Err is a failure value.
676///
677/// This function can be used to wrap calls to fallible functions ONLY when it
678/// is known that the Error will always be a success value. E.g.
679///
680/// @code{.cpp}
681/// // foo only attempts the fallible operation if DoFallibleOperation is
682/// // true. If DoFallibleOperation is false then foo always returns
683/// // Error::success().
684/// Error foo(bool DoFallibleOperation);
685///
686/// cantFail(foo(false));
687/// @endcode
688inline void cantFail(Error Err, const char *Msg = nullptr) {
689 if (Err) {
690 if (!Msg)
691 Msg = "Failure value returned from cantFail wrapped call";
692 llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/Support/Error.h"
, 692)
;
693 }
694}
695
696/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
697/// returns the contained value.
698///
699/// This function can be used to wrap calls to fallible functions ONLY when it
700/// is known that the Error will always be a success value. E.g.
701///
702/// @code{.cpp}
703/// // foo only attempts the fallible operation if DoFallibleOperation is
704/// // true. If DoFallibleOperation is false then foo always returns an int.
705/// Expected<int> foo(bool DoFallibleOperation);
706///
707/// int X = cantFail(foo(false));
708/// @endcode
709template <typename T>
710T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) {
711 if (ValOrErr)
712 return std::move(*ValOrErr);
713 else {
714 if (!Msg)
715 Msg = "Failure value returned from cantFail wrapped call";
716 llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/Support/Error.h"
, 716)
;
717 }
718}
719
720/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
721/// returns the contained reference.
722///
723/// This function can be used to wrap calls to fallible functions ONLY when it
724/// is known that the Error will always be a success value. E.g.
725///
726/// @code{.cpp}
727/// // foo only attempts the fallible operation if DoFallibleOperation is
728/// // true. If DoFallibleOperation is false then foo always returns a Bar&.
729/// Expected<Bar&> foo(bool DoFallibleOperation);
730///
731/// Bar &X = cantFail(foo(false));
732/// @endcode
733template <typename T>
734T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) {
735 if (ValOrErr)
736 return *ValOrErr;
737 else {
738 if (!Msg)
739 Msg = "Failure value returned from cantFail wrapped call";
740 llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/Support/Error.h"
, 740)
;
741 }
742}
743
744/// Helper for testing applicability of, and applying, handlers for
745/// ErrorInfo types.
746template <typename HandlerT>
747class ErrorHandlerTraits
748 : public ErrorHandlerTraits<decltype(
749 &std::remove_reference<HandlerT>::type::operator())> {};
750
751// Specialization functions of the form 'Error (const ErrT&)'.
752template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> {
753public:
754 static bool appliesTo(const ErrorInfoBase &E) {
755 return E.template isA<ErrT>();
756 }
757
758 template <typename HandlerT>
759 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
760 assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast
<void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/Support/Error.h"
, 760, __PRETTY_FUNCTION__))
;
761 return H(static_cast<ErrT &>(*E));
762 }
763};
764
765// Specialization functions of the form 'void (const ErrT&)'.
766template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> {
767public:
768 static bool appliesTo(const ErrorInfoBase &E) {
769 return E.template isA<ErrT>();
770 }
771
772 template <typename HandlerT>
773 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
774 assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast
<void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/Support/Error.h"
, 774, __PRETTY_FUNCTION__))
;
775 H(static_cast<ErrT &>(*E));
776 return Error::success();
777 }
778};
779
780/// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'.
781template <typename ErrT>
782class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> {
783public:
784 static bool appliesTo(const ErrorInfoBase &E) {
785 return E.template isA<ErrT>();
786 }
787
788 template <typename HandlerT>
789 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
790 assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast
<void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/Support/Error.h"
, 790, __PRETTY_FUNCTION__))
;
791 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
792 return H(std::move(SubE));
793 }
794};
795
796/// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'.
797template <typename ErrT>
798class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> {
799public:
800 static bool appliesTo(const ErrorInfoBase &E) {
801 return E.template isA<ErrT>();
802 }
803
804 template <typename HandlerT>
805 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
806 assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast
<void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/Support/Error.h"
, 806, __PRETTY_FUNCTION__))
;
807 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
808 H(std::move(SubE));
809 return Error::success();
810 }
811};
812
813// Specialization for member functions of the form 'RetT (const ErrT&)'.
814template <typename C, typename RetT, typename ErrT>
815class ErrorHandlerTraits<RetT (C::*)(ErrT &)>
816 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
817
818// Specialization for member functions of the form 'RetT (const ErrT&) const'.
819template <typename C, typename RetT, typename ErrT>
820class ErrorHandlerTraits<RetT (C::*)(ErrT &) const>
821 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
822
823// Specialization for member functions of the form 'RetT (const ErrT&)'.
824template <typename C, typename RetT, typename ErrT>
825class ErrorHandlerTraits<RetT (C::*)(const ErrT &)>
826 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
827
828// Specialization for member functions of the form 'RetT (const ErrT&) const'.
829template <typename C, typename RetT, typename ErrT>
830class ErrorHandlerTraits<RetT (C::*)(const ErrT &) const>
831 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
832
833/// Specialization for member functions of the form
834/// 'RetT (std::unique_ptr<ErrT>)'.
835template <typename C, typename RetT, typename ErrT>
836class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)>
837 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
838
839/// Specialization for member functions of the form
840/// 'RetT (std::unique_ptr<ErrT>) const'.
841template <typename C, typename RetT, typename ErrT>
842class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const>
843 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
844
845inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) {
846 return Error(std::move(Payload));
847}
848
849template <typename HandlerT, typename... HandlerTs>
850Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload,
851 HandlerT &&Handler, HandlerTs &&... Handlers) {
852 if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload))
853 return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler),
854 std::move(Payload));
855 return handleErrorImpl(std::move(Payload),
856 std::forward<HandlerTs>(Handlers)...);
857}
858
859/// Pass the ErrorInfo(s) contained in E to their respective handlers. Any
860/// unhandled errors (or Errors returned by handlers) are re-concatenated and
861/// returned.
862/// Because this function returns an error, its result must also be checked
863/// or returned. If you intend to handle all errors use handleAllErrors
864/// (which returns void, and will abort() on unhandled errors) instead.
865template <typename... HandlerTs>
866Error handleErrors(Error E, HandlerTs &&... Hs) {
867 if (!E)
868 return Error::success();
869
870 std::unique_ptr<ErrorInfoBase> Payload = E.takePayload();
871
872 if (Payload->isA<ErrorList>()) {
873 ErrorList &List = static_cast<ErrorList &>(*Payload);
874 Error R;
875 for (auto &P : List.Payloads)
876 R = ErrorList::join(
877 std::move(R),
878 handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...));
879 return R;
880 }
881
882 return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...);
883}
884
885/// Behaves the same as handleErrors, except that it requires that all
886/// errors be handled by the given handlers. If any unhandled error remains
887/// after the handlers have run, report_fatal_error() will be called.
888template <typename... HandlerTs>
889void handleAllErrors(Error E, HandlerTs &&... Handlers) {
890 cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...));
891}
892
893/// Check that E is a non-error, then drop it.
894/// If E is an error report_fatal_error will be called.
895inline void handleAllErrors(Error E) {
896 cantFail(std::move(E));
897}
898
899/// Handle any errors (if present) in an Expected<T>, then try a recovery path.
900///
901/// If the incoming value is a success value it is returned unmodified. If it
902/// is a failure value then it the contained error is passed to handleErrors.
903/// If handleErrors is able to handle the error then the RecoveryPath functor
904/// is called to supply the final result. If handleErrors is not able to
905/// handle all errors then the unhandled errors are returned.
906///
907/// This utility enables the follow pattern:
908///
909/// @code{.cpp}
910/// enum FooStrategy { Aggressive, Conservative };
911/// Expected<Foo> foo(FooStrategy S);
912///
913/// auto ResultOrErr =
914/// handleExpected(
915/// foo(Aggressive),
916/// []() { return foo(Conservative); },
917/// [](AggressiveStrategyError&) {
918/// // Implicitly conusme this - we'll recover by using a conservative
919/// // strategy.
920/// });
921///
922/// @endcode
923template <typename T, typename RecoveryFtor, typename... HandlerTs>
924Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath,
925 HandlerTs &&... Handlers) {
926 if (ValOrErr)
927 return ValOrErr;
928
929 if (auto Err = handleErrors(ValOrErr.takeError(),
930 std::forward<HandlerTs>(Handlers)...))
931 return std::move(Err);
932
933 return RecoveryPath();
934}
935
936/// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner
937/// will be printed before the first one is logged. A newline will be printed
938/// after each error.
939///
940/// This is useful in the base level of your program to allow clean termination
941/// (allowing clean deallocation of resources, etc.), while reporting error
942/// information to the user.
943void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner);
944
945/// Write all error messages (if any) in E to a string. The newline character
946/// is used to separate error messages.
947inline std::string toString(Error E) {
948 SmallVector<std::string, 2> Errors;
949 handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) {
950 Errors.push_back(EI.message());
951 });
952 return join(Errors.begin(), Errors.end(), "\n");
953}
954
955/// Consume a Error without doing anything. This method should be used
956/// only where an error can be considered a reasonable and expected return
957/// value.
958///
959/// Uses of this method are potentially indicative of design problems: If it's
960/// legitimate to do nothing while processing an "error", the error-producer
961/// might be more clearly refactored to return an Optional<T>.
962inline void consumeError(Error Err) {
963 handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {});
964}
965
966/// Helper for Errors used as out-parameters.
967///
968/// This helper is for use with the Error-as-out-parameter idiom, where an error
969/// is passed to a function or method by reference, rather than being returned.
970/// In such cases it is helpful to set the checked bit on entry to the function
971/// so that the error can be written to (unchecked Errors abort on assignment)
972/// and clear the checked bit on exit so that clients cannot accidentally forget
973/// to check the result. This helper performs these actions automatically using
974/// RAII:
975///
976/// @code{.cpp}
977/// Result foo(Error &Err) {
978/// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set
979/// // <body of foo>
980/// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed.
981/// }
982/// @endcode
983///
984/// ErrorAsOutParameter takes an Error* rather than Error& so that it can be
985/// used with optional Errors (Error pointers that are allowed to be null). If
986/// ErrorAsOutParameter took an Error reference, an instance would have to be
987/// created inside every condition that verified that Error was non-null. By
988/// taking an Error pointer we can just create one instance at the top of the
989/// function.
990class ErrorAsOutParameter {
991public:
992 ErrorAsOutParameter(Error *Err) : Err(Err) {
993 // Raise the checked bit if Err is success.
994 if (Err)
995 (void)!!*Err;
996 }
997
998 ~ErrorAsOutParameter() {
999 // Clear the checked bit.
1000 if (Err && !*Err)
1001 *Err = Error::success();
1002 }
1003
1004private:
1005 Error *Err;
1006};
1007
1008/// Helper for Expected<T>s used as out-parameters.
1009///
1010/// See ErrorAsOutParameter.
1011template <typename T>
1012class ExpectedAsOutParameter {
1013public:
1014 ExpectedAsOutParameter(Expected<T> *ValOrErr)
1015 : ValOrErr(ValOrErr) {
1016 if (ValOrErr)
1017 (void)!!*ValOrErr;
1018 }
1019
1020 ~ExpectedAsOutParameter() {
1021 if (ValOrErr)
1022 ValOrErr->setUnchecked();
1023 }
1024
1025private:
1026 Expected<T> *ValOrErr;
1027};
1028
1029/// This class wraps a std::error_code in a Error.
1030///
1031/// This is useful if you're writing an interface that returns a Error
1032/// (or Expected) and you want to call code that still returns
1033/// std::error_codes.
1034class ECError : public ErrorInfo<ECError> {
1035 friend Error errorCodeToError(std::error_code);
1036
1037public:
1038 void setErrorCode(std::error_code EC) { this->EC = EC; }
1039 std::error_code convertToErrorCode() const override { return EC; }
1040 void log(raw_ostream &OS) const override { OS << EC.message(); }
1041
1042 // Used by ErrorInfo::classID.
1043 static char ID;
1044
1045protected:
1046 ECError() = default;
1047 ECError(std::error_code EC) : EC(EC) {}
1048
1049 std::error_code EC;
1050};
1051
1052/// The value returned by this function can be returned from convertToErrorCode
1053/// for Error values where no sensible translation to std::error_code exists.
1054/// It should only be used in this situation, and should never be used where a
1055/// sensible conversion to std::error_code is available, as attempts to convert
1056/// to/from this error will result in a fatal error. (i.e. it is a programmatic
1057///error to try to convert such a value).
1058std::error_code inconvertibleErrorCode();
1059
1060/// Helper for converting an std::error_code to a Error.
1061Error errorCodeToError(std::error_code EC);
1062
1063/// Helper for converting an ECError to a std::error_code.
1064///
1065/// This method requires that Err be Error() or an ECError, otherwise it
1066/// will trigger a call to abort().
1067std::error_code errorToErrorCode(Error Err);
1068
1069/// Convert an ErrorOr<T> to an Expected<T>.
1070template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) {
1071 if (auto EC = EO.getError())
1072 return errorCodeToError(EC);
1073 return std::move(*EO);
1074}
1075
1076/// Convert an Expected<T> to an ErrorOr<T>.
1077template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) {
1078 if (auto Err = E.takeError())
1079 return errorToErrorCode(std::move(Err));
1080 return std::move(*E);
1081}
1082
1083/// This class wraps a string in an Error.
1084///
1085/// StringError is useful in cases where the client is not expected to be able
1086/// to consume the specific error message programmatically (for example, if the
1087/// error message is to be presented to the user).
1088class StringError : public ErrorInfo<StringError> {
1089public:
1090 static char ID;
1091
1092 StringError(const Twine &S, std::error_code EC);
1093
1094 void log(raw_ostream &OS) const override;
1095 std::error_code convertToErrorCode() const override;
1096
1097 const std::string &getMessage() const { return Msg; }
1098
1099private:
1100 std::string Msg;
1101 std::error_code EC;
1102};
1103
1104/// Helper for check-and-exit error handling.
1105///
1106/// For tool use only. NOT FOR USE IN LIBRARY CODE.
1107///
1108class ExitOnError {
1109public:
1110 /// Create an error on exit helper.
1111 ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1)
1112 : Banner(std::move(Banner)),
1113 GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {}
1114
1115 /// Set the banner string for any errors caught by operator().
1116 void setBanner(std::string Banner) { this->Banner = std::move(Banner); }
1117
1118 /// Set the exit-code mapper function.
1119 void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) {
1120 this->GetExitCode = std::move(GetExitCode);
1121 }
1122
1123 /// Check Err. If it's in a failure state log the error(s) and exit.
1124 void operator()(Error Err) const { checkError(std::move(Err)); }
1125
1126 /// Check E. If it's in a success state then return the contained value. If
1127 /// it's in a failure state log the error(s) and exit.
1128 template <typename T> T operator()(Expected<T> &&E) const {
1129 checkError(E.takeError());
1130 return std::move(*E);
1131 }
1132
1133 /// Check E. If it's in a success state then return the contained reference. If
1134 /// it's in a failure state log the error(s) and exit.
1135 template <typename T> T& operator()(Expected<T&> &&E) const {
1136 checkError(E.takeError());
1137 return *E;
1138 }
1139
1140private:
1141 void checkError(Error Err) const {
1142 if (Err) {
1143 int ExitCode = GetExitCode(Err);
1144 logAllUnhandledErrors(std::move(Err), errs(), Banner);
1145 exit(ExitCode);
1146 }
1147 }
1148
1149 std::string Banner;
1150 std::function<int(const Error &)> GetExitCode;
1151};
1152
1153} // end namespace llvm
1154
1155#endif // LLVM_SUPPORT_ERROR_H

/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/ADT/STLExtras.h

1//===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains some templates that are useful if you are working with the
11// STL at all.
12//
13// No library is required when using these functions.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_ADT_STLEXTRAS_H
18#define LLVM_ADT_STLEXTRAS_H
19
20#include "llvm/ADT/Optional.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/iterator.h"
23#include "llvm/ADT/iterator_range.h"
24#include "llvm/Support/ErrorHandling.h"
25#include <algorithm>
26#include <cassert>
27#include <cstddef>
28#include <cstdint>
29#include <cstdlib>
30#include <functional>
31#include <initializer_list>
32#include <iterator>
33#include <limits>
34#include <memory>
35#include <tuple>
36#include <type_traits>
37#include <utility>
38
39namespace llvm {
40
41// Only used by compiler if both template types are the same. Useful when
42// using SFINAE to test for the existence of member functions.
43template <typename T, T> struct SameType;
44
45namespace detail {
46
47template <typename RangeT>
48using IterOfRange = decltype(std::begin(std::declval<RangeT &>()));
49
50template <typename RangeT>
51using ValueOfRange = typename std::remove_reference<decltype(
52 *std::begin(std::declval<RangeT &>()))>::type;
53
54} // end namespace detail
55
56//===----------------------------------------------------------------------===//
57// Extra additions to <functional>
58//===----------------------------------------------------------------------===//
59
60template <class Ty> struct identity {
61 using argument_type = Ty;
62
63 Ty &operator()(Ty &self) const {
64 return self;
65 }
66 const Ty &operator()(const Ty &self) const {
67 return self;
68 }
69};
70
71template <class Ty> struct less_ptr {
72 bool operator()(const Ty* left, const Ty* right) const {
73 return *left < *right;
74 }
75};
76
77template <class Ty> struct greater_ptr {
78 bool operator()(const Ty* left, const Ty* right) const {
79 return *right < *left;
80 }
81};
82
83/// An efficient, type-erasing, non-owning reference to a callable. This is
84/// intended for use as the type of a function parameter that is not used
85/// after the function in question returns.
86///
87/// This class does not own the callable, so it is not in general safe to store
88/// a function_ref.
89template<typename Fn> class function_ref;
90
91template<typename Ret, typename ...Params>
92class function_ref<Ret(Params...)> {
93 Ret (*callback)(intptr_t callable, Params ...params) = nullptr;
94 intptr_t callable;
95
96 template<typename Callable>
97 static Ret callback_fn(intptr_t callable, Params ...params) {
98 return (*reinterpret_cast<Callable*>(callable))(
99 std::forward<Params>(params)...);
100 }
101
102public:
103 function_ref() = default;
104
105 template <typename Callable>
106 function_ref(Callable &&callable,
107 typename std::enable_if<
108 !std::is_same<typename std::remove_reference<Callable>::type,
109 function_ref>::value>::type * = nullptr)
110 : callback(callback_fn<typename std::remove_reference<Callable>::type>),
111 callable(reinterpret_cast<intptr_t>(&callable)) {}
112
113 Ret operator()(Params ...params) const {
114 return callback(callable, std::forward<Params>(params)...);
115 }
116
117 operator bool() const { return callback; }
118};
119
120// deleter - Very very very simple method that is used to invoke operator
121// delete on something. It is used like this:
122//
123// for_each(V.begin(), B.end(), deleter<Interval>);
124template <class T>
125inline void deleter(T *Ptr) {
126 delete Ptr;
127}
128
129//===----------------------------------------------------------------------===//
130// Extra additions to <iterator>
131//===----------------------------------------------------------------------===//
132
133// mapped_iterator - This is a simple iterator adapter that causes a function to
134// be applied whenever operator* is invoked on the iterator.
135
136template <typename ItTy, typename FuncTy,
137 typename FuncReturnTy =
138 decltype(std::declval<FuncTy>()(*std::declval<ItTy>()))>
139class mapped_iterator
140 : public iterator_adaptor_base<
141 mapped_iterator<ItTy, FuncTy>, ItTy,
142 typename std::iterator_traits<ItTy>::iterator_category,
143 typename std::remove_reference<FuncReturnTy>::type> {
144public:
145 mapped_iterator(ItTy U, FuncTy F)
146 : mapped_iterator::iterator_adaptor_base(std::move(U)), F(std::move(F)) {}
147
148 ItTy getCurrent() { return this->I; }
149
150 FuncReturnTy operator*() { return F(*this->I); }
151
152private:
153 FuncTy F;
154};
155
156// map_iterator - Provide a convenient way to create mapped_iterators, just like
157// make_pair is useful for creating pairs...
158template <class ItTy, class FuncTy>
159inline mapped_iterator<ItTy, FuncTy> map_iterator(ItTy I, FuncTy F) {
160 return mapped_iterator<ItTy, FuncTy>(std::move(I), std::move(F));
161}
162
163/// Helper to determine if type T has a member called rbegin().
164template <typename Ty> class has_rbegin_impl {
165 using yes = char[1];
166 using no = char[2];
167
168 template <typename Inner>
169 static yes& test(Inner *I, decltype(I->rbegin()) * = nullptr);
170
171 template <typename>
172 static no& test(...);
173
174public:
175 static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
176};
177
178/// Metafunction to determine if T& or T has a member called rbegin().
179template <typename Ty>
180struct has_rbegin : has_rbegin_impl<typename std::remove_reference<Ty>::type> {
181};
182
183// Returns an iterator_range over the given container which iterates in reverse.
184// Note that the container must have rbegin()/rend() methods for this to work.
185template <typename ContainerTy>
186auto reverse(ContainerTy &&C,
187 typename std::enable_if<has_rbegin<ContainerTy>::value>::type * =
188 nullptr) -> decltype(make_range(C.rbegin(), C.rend())) {
189 return make_range(C.rbegin(), C.rend());
190}
191
192// Returns a std::reverse_iterator wrapped around the given iterator.
193template <typename IteratorTy>
194std::reverse_iterator<IteratorTy> make_reverse_iterator(IteratorTy It) {
195 return std::reverse_iterator<IteratorTy>(It);
196}
197
198// Returns an iterator_range over the given container which iterates in reverse.
199// Note that the container must have begin()/end() methods which return
200// bidirectional iterators for this to work.
201template <typename ContainerTy>
202auto reverse(
203 ContainerTy &&C,
204 typename std::enable_if<!has_rbegin<ContainerTy>::value>::type * = nullptr)
205 -> decltype(make_range(llvm::make_reverse_iterator(std::end(C)),
206 llvm::make_reverse_iterator(std::begin(C)))) {
207 return make_range(llvm::make_reverse_iterator(std::end(C)),
208 llvm::make_reverse_iterator(std::begin(C)));
209}
210
211/// An iterator adaptor that filters the elements of given inner iterators.
212///
213/// The predicate parameter should be a callable object that accepts the wrapped
214/// iterator's reference type and returns a bool. When incrementing or
215/// decrementing the iterator, it will call the predicate on each element and
216/// skip any where it returns false.
217///
218/// \code
219/// int A[] = { 1, 2, 3, 4 };
220/// auto R = make_filter_range(A, [](int N) { return N % 2 == 1; });
221/// // R contains { 1, 3 }.
222/// \endcode
223template <typename WrappedIteratorT, typename PredicateT>
224class filter_iterator
225 : public iterator_adaptor_base<
226 filter_iterator<WrappedIteratorT, PredicateT>, WrappedIteratorT,
227 typename std::common_type<
228 std::forward_iterator_tag,
229 typename std::iterator_traits<
230 WrappedIteratorT>::iterator_category>::type> {
231 using BaseT = iterator_adaptor_base<
232 filter_iterator<WrappedIteratorT, PredicateT>, WrappedIteratorT,
233 typename std::common_type<
234 std::forward_iterator_tag,
235 typename std::iterator_traits<WrappedIteratorT>::iterator_category>::
236 type>;
237
238 struct PayloadType {
239 WrappedIteratorT End;
240 PredicateT Pred;
241 };
242
243 Optional<PayloadType> Payload;
244
245 void findNextValid() {
246 assert(Payload && "Payload should be engaged when findNextValid is called")((Payload && "Payload should be engaged when findNextValid is called"
) ? static_cast<void> (0) : __assert_fail ("Payload && \"Payload should be engaged when findNextValid is called\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/ADT/STLExtras.h"
, 246, __PRETTY_FUNCTION__))
;
247 while (this->I != Payload->End && !Payload->Pred(*this->I))
248 BaseT::operator++();
249 }
250
251 // Construct the begin iterator. The begin iterator requires to know where end
252 // is, so that it can properly stop when it hits end.
253 filter_iterator(WrappedIteratorT Begin, WrappedIteratorT End, PredicateT Pred)
254 : BaseT(std::move(Begin)),
255 Payload(PayloadType{std::move(End), std::move(Pred)}) {
256 findNextValid();
257 }
258
259 // Construct the end iterator. It's not incrementable, so Payload doesn't
260 // have to be engaged.
261 filter_iterator(WrappedIteratorT End) : BaseT(End) {}
262
263public:
264 using BaseT::operator++;
265
266 filter_iterator &operator++() {
267 BaseT::operator++();
268 findNextValid();
269 return *this;
270 }
271
272 template <typename RT, typename PT>
273 friend iterator_range<filter_iterator<detail::IterOfRange<RT>, PT>>
274 make_filter_range(RT &&, PT);
275};
276
277/// Convenience function that takes a range of elements and a predicate,
278/// and return a new filter_iterator range.
279///
280/// FIXME: Currently if RangeT && is a rvalue reference to a temporary, the
281/// lifetime of that temporary is not kept by the returned range object, and the
282/// temporary is going to be dropped on the floor after the make_iterator_range
283/// full expression that contains this function call.
284template <typename RangeT, typename PredicateT>
285iterator_range<filter_iterator<detail::IterOfRange<RangeT>, PredicateT>>
286make_filter_range(RangeT &&Range, PredicateT Pred) {
287 using FilterIteratorT =
288 filter_iterator<detail::IterOfRange<RangeT>, PredicateT>;
289 return make_range(FilterIteratorT(std::begin(std::forward<RangeT>(Range)),
290 std::end(std::forward<RangeT>(Range)),
291 std::move(Pred)),
292 FilterIteratorT(std::end(std::forward<RangeT>(Range))));
293}
294
295// forward declarations required by zip_shortest/zip_first
296template <typename R, typename UnaryPredicate>
297bool all_of(R &&range, UnaryPredicate P);
298
299template <size_t... I> struct index_sequence;
300
301template <class... Ts> struct index_sequence_for;
302
303namespace detail {
304
305using std::declval;
306
307// We have to alias this since inlining the actual type at the usage site
308// in the parameter list of iterator_facade_base<> below ICEs MSVC 2017.
309template<typename... Iters> struct ZipTupleType {
310 using type = std::tuple<decltype(*declval<Iters>())...>;
311};
312
313template <typename ZipType, typename... Iters>
314using zip_traits = iterator_facade_base<
315 ZipType, typename std::common_type<std::bidirectional_iterator_tag,
316 typename std::iterator_traits<
317 Iters>::iterator_category...>::type,
318 // ^ TODO: Implement random access methods.
319 typename ZipTupleType<Iters...>::type,
320 typename std::iterator_traits<typename std::tuple_element<
321 0, std::tuple<Iters...>>::type>::difference_type,
322 // ^ FIXME: This follows boost::make_zip_iterator's assumption that all
323 // inner iterators have the same difference_type. It would fail if, for
324 // instance, the second field's difference_type were non-numeric while the
325 // first is.
326 typename ZipTupleType<Iters...>::type *,
327 typename ZipTupleType<Iters...>::type>;
328
329template <typename ZipType, typename... Iters>
330struct zip_common : public zip_traits<ZipType, Iters...> {
331 using Base = zip_traits<ZipType, Iters...>;
332 using value_type = typename Base::value_type;
333
334 std::tuple<Iters...> iterators;
335
336protected:
337 template <size_t... Ns> value_type deref(index_sequence<Ns...>) const {
338 return value_type(*std::get<Ns>(iterators)...);
339 }
340
341 template <size_t... Ns>
342 decltype(iterators) tup_inc(index_sequence<Ns...>) const {
343 return std::tuple<Iters...>(std::next(std::get<Ns>(iterators))...);
344 }
345
346 template <size_t... Ns>
347 decltype(iterators) tup_dec(index_sequence<Ns...>) const {
348 return std::tuple<Iters...>(std::prev(std::get<Ns>(iterators))...);
349 }
350
351public:
352 zip_common(Iters &&... ts) : iterators(std::forward<Iters>(ts)...) {}
353
354 value_type operator*() { return deref(index_sequence_for<Iters...>{}); }
355
356 const value_type operator*() const {
357 return deref(index_sequence_for<Iters...>{});
358 }
359
360 ZipType &operator++() {
361 iterators = tup_inc(index_sequence_for<Iters...>{});
362 return *reinterpret_cast<ZipType *>(this);
363 }
364
365 ZipType &operator--() {
366 static_assert(Base::IsBidirectional,
367 "All inner iterators must be at least bidirectional.");
368 iterators = tup_dec(index_sequence_for<Iters...>{});
369 return *reinterpret_cast<ZipType *>(this);
370 }
371};
372
373template <typename... Iters>
374struct zip_first : public zip_common<zip_first<Iters...>, Iters...> {
375 using Base = zip_common<zip_first<Iters...>, Iters...>;
376
377 bool operator==(const zip_first<Iters...> &other) const {
378 return std::get<0>(this->iterators) == std::get<0>(other.iterators);
379 }
380
381 zip_first(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
382};
383
384template <typename... Iters>
385class zip_shortest : public zip_common<zip_shortest<Iters...>, Iters...> {
386 template <size_t... Ns>
387 bool test(const zip_shortest<Iters...> &other, index_sequence<Ns...>) const {
388 return all_of(std::initializer_list<bool>{std::get<Ns>(this->iterators) !=
389 std::get<Ns>(other.iterators)...},
390 identity<bool>{});
391 }
392
393public:
394 using Base = zip_common<zip_shortest<Iters...>, Iters...>;
395
396 zip_shortest(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
397
398 bool operator==(const zip_shortest<Iters...> &other) const {
399 return !test(other, index_sequence_for<Iters...>{});
400 }
401};
402
403template <template <typename...> class ItType, typename... Args> class zippy {
404public:
405 using iterator = ItType<decltype(std::begin(std::declval<Args>()))...>;
406 using iterator_category = typename iterator::iterator_category;
407 using value_type = typename iterator::value_type;
408 using difference_type = typename iterator::difference_type;
409 using pointer = typename iterator::pointer;
410 using reference = typename iterator::reference;
411
412private:
413 std::tuple<Args...> ts;
414
415 template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) const {
416 return iterator(std::begin(std::get<Ns>(ts))...);
417 }
418 template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) const {
419 return iterator(std::end(std::get<Ns>(ts))...);
420 }
421
422public:
423 zippy(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {}
424
425 iterator begin() const { return begin_impl(index_sequence_for<Args...>{}); }
426 iterator end() const { return end_impl(index_sequence_for<Args...>{}); }
427};
428
429} // end namespace detail
430
431/// zip iterator for two or more iteratable types.
432template <typename T, typename U, typename... Args>
433detail::zippy<detail::zip_shortest, T, U, Args...> zip(T &&t, U &&u,
434 Args &&... args) {
435 return detail::zippy<detail::zip_shortest, T, U, Args...>(
436 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
437}
438
439/// zip iterator that, for the sake of efficiency, assumes the first iteratee to
440/// be the shortest.
441template <typename T, typename U, typename... Args>
442detail::zippy<detail::zip_first, T, U, Args...> zip_first(T &&t, U &&u,
443 Args &&... args) {
444 return detail::zippy<detail::zip_first, T, U, Args...>(
445 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
446}
447
448/// Iterator wrapper that concatenates sequences together.
449///
450/// This can concatenate different iterators, even with different types, into
451/// a single iterator provided the value types of all the concatenated
452/// iterators expose `reference` and `pointer` types that can be converted to
453/// `ValueT &` and `ValueT *` respectively. It doesn't support more
454/// interesting/customized pointer or reference types.
455///
456/// Currently this only supports forward or higher iterator categories as
457/// inputs and always exposes a forward iterator interface.
458template <typename ValueT, typename... IterTs>
459class concat_iterator
460 : public iterator_facade_base<concat_iterator<ValueT, IterTs...>,
461 std::forward_iterator_tag, ValueT> {
462 using BaseT = typename concat_iterator::iterator_facade_base;
463
464 /// We store both the current and end iterators for each concatenated
465 /// sequence in a tuple of pairs.
466 ///
467 /// Note that something like iterator_range seems nice at first here, but the
468 /// range properties are of little benefit and end up getting in the way
469 /// because we need to do mutation on the current iterators.
470 std::tuple<std::pair<IterTs, IterTs>...> IterPairs;
471
472 /// Attempts to increment a specific iterator.
473 ///
474 /// Returns true if it was able to increment the iterator. Returns false if
475 /// the iterator is already at the end iterator.
476 template <size_t Index> bool incrementHelper() {
477 auto &IterPair = std::get<Index>(IterPairs);
478 if (IterPair.first == IterPair.second)
479 return false;
480
481 ++IterPair.first;
482 return true;
483 }
484
485 /// Increments the first non-end iterator.
486 ///
487 /// It is an error to call this with all iterators at the end.
488 template <size_t... Ns> void increment(index_sequence<Ns...>) {
489 // Build a sequence of functions to increment each iterator if possible.
490 bool (concat_iterator::*IncrementHelperFns[])() = {
491 &concat_iterator::incrementHelper<Ns>...};
492
493 // Loop over them, and stop as soon as we succeed at incrementing one.
494 for (auto &IncrementHelperFn : IncrementHelperFns)
495 if ((this->*IncrementHelperFn)())
496 return;
497
498 llvm_unreachable("Attempted to increment an end concat iterator!")::llvm::llvm_unreachable_internal("Attempted to increment an end concat iterator!"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/ADT/STLExtras.h"
, 498)
;
499 }
500
501 /// Returns null if the specified iterator is at the end. Otherwise,
502 /// dereferences the iterator and returns the address of the resulting
503 /// reference.
504 template <size_t Index> ValueT *getHelper() const {
505 auto &IterPair = std::get<Index>(IterPairs);
506 if (IterPair.first == IterPair.second)
507 return nullptr;
508
509 return &*IterPair.first;
510 }
511
512 /// Finds the first non-end iterator, dereferences, and returns the resulting
513 /// reference.
514 ///
515 /// It is an error to call this with all iterators at the end.
516 template <size_t... Ns> ValueT &get(index_sequence<Ns...>) const {
517 // Build a sequence of functions to get from iterator if possible.
518 ValueT *(concat_iterator::*GetHelperFns[])() const = {
519 &concat_iterator::getHelper<Ns>...};
520
521 // Loop over them, and return the first result we find.
522 for (auto &GetHelperFn : GetHelperFns)
523 if (ValueT *P = (this->*GetHelperFn)())
524 return *P;
525
526 llvm_unreachable("Attempted to get a pointer from an end concat iterator!")::llvm::llvm_unreachable_internal("Attempted to get a pointer from an end concat iterator!"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/ADT/STLExtras.h"
, 526)
;
527 }
528
529public:
530 /// Constructs an iterator from a squence of ranges.
531 ///
532 /// We need the full range to know how to switch between each of the
533 /// iterators.
534 template <typename... RangeTs>
535 explicit concat_iterator(RangeTs &&... Ranges)
536 : IterPairs({std::begin(Ranges), std::end(Ranges)}...) {}
537
538 using BaseT::operator++;
539
540 concat_iterator &operator++() {
541 increment(index_sequence_for<IterTs...>());
542 return *this;
543 }
544
545 ValueT &operator*() const { return get(index_sequence_for<IterTs...>()); }
546
547 bool operator==(const concat_iterator &RHS) const {
548 return IterPairs == RHS.IterPairs;
549 }
550};
551
552namespace detail {
553
554/// Helper to store a sequence of ranges being concatenated and access them.
555///
556/// This is designed to facilitate providing actual storage when temporaries
557/// are passed into the constructor such that we can use it as part of range
558/// based for loops.
559template <typename ValueT, typename... RangeTs> class concat_range {
560public:
561 using iterator =
562 concat_iterator<ValueT,
563 decltype(std::begin(std::declval<RangeTs &>()))...>;
564
565private:
566 std::tuple<RangeTs...> Ranges;
567
568 template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) {
569 return iterator(std::get<Ns>(Ranges)...);
570 }
571 template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) {
572 return iterator(make_range(std::end(std::get<Ns>(Ranges)),
573 std::end(std::get<Ns>(Ranges)))...);
574 }
575
576public:
577 concat_range(RangeTs &&... Ranges)
578 : Ranges(std::forward<RangeTs>(Ranges)...) {}
579
580 iterator begin() { return begin_impl(index_sequence_for<RangeTs...>{}); }
581 iterator end() { return end_impl(index_sequence_for<RangeTs...>{}); }
582};
583
584} // end namespace detail
585
586/// Concatenated range across two or more ranges.
587///
588/// The desired value type must be explicitly specified.
589template <typename ValueT, typename... RangeTs>
590detail::concat_range<ValueT, RangeTs...> concat(RangeTs &&... Ranges) {
591 static_assert(sizeof...(RangeTs) > 1,
592 "Need more than one range to concatenate!");
593 return detail::concat_range<ValueT, RangeTs...>(
594 std::forward<RangeTs>(Ranges)...);
595}
596
597//===----------------------------------------------------------------------===//
598// Extra additions to <utility>
599//===----------------------------------------------------------------------===//
600
601/// \brief Function object to check whether the first component of a std::pair
602/// compares less than the first component of another std::pair.
603struct less_first {
604 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
605 return lhs.first < rhs.first;
606 }
607};
608
609/// \brief Function object to check whether the second component of a std::pair
610/// compares less than the second component of another std::pair.
611struct less_second {
612 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
613 return lhs.second < rhs.second;
614 }
615};
616
617// A subset of N3658. More stuff can be added as-needed.
618
619/// \brief Represents a compile-time sequence of integers.
620template <class T, T... I> struct integer_sequence {
621 using value_type = T;
622
623 static constexpr size_t size() { return sizeof...(I); }
624};
625
626/// \brief Alias for the common case of a sequence of size_ts.
627template <size_t... I>
628struct index_sequence : integer_sequence<std::size_t, I...> {};
629
630template <std::size_t N, std::size_t... I>
631struct build_index_impl : build_index_impl<N - 1, N - 1, I...> {};
632template <std::size_t... I>
633struct build_index_impl<0, I...> : index_sequence<I...> {};
634
635/// \brief Creates a compile-time integer sequence for a parameter pack.
636template <class... Ts>
637struct index_sequence_for : build_index_impl<sizeof...(Ts)> {};
638
639/// Utility type to build an inheritance chain that makes it easy to rank
640/// overload candidates.
641template <int N> struct rank : rank<N - 1> {};
642template <> struct rank<0> {};
643
644/// \brief traits class for checking whether type T is one of any of the given
645/// types in the variadic list.
646template <typename T, typename... Ts> struct is_one_of {
647 static const bool value = false;
648};
649
650template <typename T, typename U, typename... Ts>
651struct is_one_of<T, U, Ts...> {
652 static const bool value =
653 std::is_same<T, U>::value || is_one_of<T, Ts...>::value;
654};
655
656/// \brief traits class for checking whether type T is a base class for all
657/// the given types in the variadic list.
658template <typename T, typename... Ts> struct are_base_of {
659 static const bool value = true;
660};
661
662template <typename T, typename U, typename... Ts>
663struct are_base_of<T, U, Ts...> {
664 static const bool value =
665 std::is_base_of<T, U>::value && are_base_of<T, Ts...>::value;
666};
667
668//===----------------------------------------------------------------------===//
669// Extra additions for arrays
670//===----------------------------------------------------------------------===//
671
672/// Find the length of an array.
673template <class T, std::size_t N>
674constexpr inline size_t array_lengthof(T (&)[N]) {
675 return N;
676}
677
678/// Adapt std::less<T> for array_pod_sort.
679template<typename T>
680inline int array_pod_sort_comparator(const void *P1, const void *P2) {
681 if (std::less<T>()(*reinterpret_cast<const T*>(P1),
682 *reinterpret_cast<const T*>(P2)))
683 return -1;
684 if (std::less<T>()(*reinterpret_cast<const T*>(P2),
685 *reinterpret_cast<const T*>(P1)))
686 return 1;
687 return 0;
688}
689
690/// get_array_pod_sort_comparator - This is an internal helper function used to
691/// get type deduction of T right.
692template<typename T>
693inline int (*get_array_pod_sort_comparator(const T &))
694 (const void*, const void*) {
695 return array_pod_sort_comparator<T>;
696}
697
698/// array_pod_sort - This sorts an array with the specified start and end
699/// extent. This is just like std::sort, except that it calls qsort instead of
700/// using an inlined template. qsort is slightly slower than std::sort, but
701/// most sorts are not performance critical in LLVM and std::sort has to be
702/// template instantiated for each type, leading to significant measured code
703/// bloat. This function should generally be used instead of std::sort where
704/// possible.
705///
706/// This function assumes that you have simple POD-like types that can be
707/// compared with std::less and can be moved with memcpy. If this isn't true,
708/// you should use std::sort.
709///
710/// NOTE: If qsort_r were portable, we could allow a custom comparator and
711/// default to std::less.
712template<class IteratorTy>
713inline void array_pod_sort(IteratorTy Start, IteratorTy End) {
714 // Don't inefficiently call qsort with one element or trigger undefined
715 // behavior with an empty sequence.
716 auto NElts = End - Start;
717 if (NElts <= 1) return;
718 qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start));
719}
720
721template <class IteratorTy>
722inline void array_pod_sort(
723 IteratorTy Start, IteratorTy End,
724 int (*Compare)(
725 const typename std::iterator_traits<IteratorTy>::value_type *,
726 const typename std::iterator_traits<IteratorTy>::value_type *)) {
727 // Don't inefficiently call qsort with one element or trigger undefined
728 // behavior with an empty sequence.
729 auto NElts = End - Start;
730 if (NElts <= 1) return;
731 qsort(&*Start, NElts, sizeof(*Start),
732 reinterpret_cast<int (*)(const void *, const void *)>(Compare));
733}
734
735//===----------------------------------------------------------------------===//
736// Extra additions to <algorithm>
737//===----------------------------------------------------------------------===//
738
739/// For a container of pointers, deletes the pointers and then clears the
740/// container.
741template<typename Container>
742void DeleteContainerPointers(Container &C) {
743 for (auto V : C)
744 delete V;
745 C.clear();
746}
747
748/// In a container of pairs (usually a map) whose second element is a pointer,
749/// deletes the second elements and then clears the container.
750template<typename Container>
751void DeleteContainerSeconds(Container &C) {
752 for (auto &V : C)
753 delete V.second;
754 C.clear();
755}
756
757/// Provide wrappers to std::for_each which take ranges instead of having to
758/// pass begin/end explicitly.
759template <typename R, typename UnaryPredicate>
760UnaryPredicate for_each(R &&Range, UnaryPredicate P) {
761 return std::for_each(std::begin(Range), std::end(Range), P);
762}
763
764/// Provide wrappers to std::all_of which take ranges instead of having to pass
765/// begin/end explicitly.
766template <typename R, typename UnaryPredicate>
767bool all_of(R &&Range, UnaryPredicate P) {
768 return std::all_of(std::begin(Range), std::end(Range), P);
769}
770
771/// Provide wrappers to std::any_of which take ranges instead of having to pass
772/// begin/end explicitly.
773template <typename R, typename UnaryPredicate>
774bool any_of(R &&Range, UnaryPredicate P) {
775 return std::any_of(std::begin(Range), std::end(Range), P);
776}
777
778/// Provide wrappers to std::none_of which take ranges instead of having to pass
779/// begin/end explicitly.
780template <typename R, typename UnaryPredicate>
781bool none_of(R &&Range, UnaryPredicate P) {
782 return std::none_of(std::begin(Range), std::end(Range), P);
783}
784
785/// Provide wrappers to std::find which take ranges instead of having to pass
786/// begin/end explicitly.
787template <typename R, typename T>
788auto find(R &&Range, const T &Val) -> decltype(std::begin(Range)) {
789 return std::find(std::begin(Range), std::end(Range), Val);
790}
791
792/// Provide wrappers to std::find_if which take ranges instead of having to pass
793/// begin/end explicitly.
794template <typename R, typename UnaryPredicate>
795auto find_if(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range)) {
796 return std::find_if(std::begin(Range), std::end(Range), P);
797}
798
799template <typename R, typename UnaryPredicate>
800auto find_if_not(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range)) {
801 return std::find_if_not(std::begin(Range), std::end(Range), P);
802}
803
804/// Provide wrappers to std::remove_if which take ranges instead of having to
805/// pass begin/end explicitly.
806template <typename R, typename UnaryPredicate>
807auto remove_if(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range)) {
808 return std::remove_if(std::begin(Range), std::end(Range), P);
809}
810
811/// Provide wrappers to std::copy_if which take ranges instead of having to
812/// pass begin/end explicitly.
813template <typename R, typename OutputIt, typename UnaryPredicate>
814OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P) {
815 return std::copy_if(std::begin(Range), std::end(Range), Out, P);
816}
817
818/// Wrapper function around std::find to detect if an element exists
819/// in a container.
820template <typename R, typename E>
821bool is_contained(R &&Range, const E &Element) {
822 return std::find(std::begin(Range), std::end(Range), Element) !=
823 std::end(Range);
824}
825
826/// Wrapper function around std::count to count the number of times an element
827/// \p Element occurs in the given range \p Range.
828template <typename R, typename E>
829auto count(R &&Range, const E &Element) -> typename std::iterator_traits<
830 decltype(std::begin(Range))>::difference_type {
831 return std::count(std::begin(Range), std::end(Range), Element);
832}
833
834/// Wrapper function around std::count_if to count the number of times an
835/// element satisfying a given predicate occurs in a range.
836template <typename R, typename UnaryPredicate>
837auto count_if(R &&Range, UnaryPredicate P) -> typename std::iterator_traits<
838 decltype(std::begin(Range))>::difference_type {
839 return std::count_if(std::begin(Range), std::end(Range), P);
840}
841
842/// Wrapper function around std::transform to apply a function to a range and
843/// store the result elsewhere.
844template <typename R, typename OutputIt, typename UnaryPredicate>
845OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P) {
846 return std::transform(std::begin(Range), std::end(Range), d_first, P);
847}
848
849/// Provide wrappers to std::partition which take ranges instead of having to
850/// pass begin/end explicitly.
851template <typename R, typename UnaryPredicate>
852auto partition(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range)) {
853 return std::partition(std::begin(Range), std::end(Range), P);
854}
855
856/// Provide wrappers to std::lower_bound which take ranges instead of having to
857/// pass begin/end explicitly.
858template <typename R, typename ForwardIt>
859auto lower_bound(R &&Range, ForwardIt I) -> decltype(std::begin(Range)) {
860 return std::lower_bound(std::begin(Range), std::end(Range), I);
861}
862
863/// \brief Given a range of type R, iterate the entire range and return a
864/// SmallVector with elements of the vector. This is useful, for example,
865/// when you want to iterate a range and then sort the results.
866template <unsigned Size, typename R>
867SmallVector<typename std::remove_const<detail::ValueOfRange<R>>::type, Size>
868to_vector(R &&Range) {
869 return {std::begin(Range), std::end(Range)};
870}
871
872/// Provide a container algorithm similar to C++ Library Fundamentals v2's
873/// `erase_if` which is equivalent to:
874///
875/// C.erase(remove_if(C, pred), C.end());
876///
877/// This version works for any container with an erase method call accepting
878/// two iterators.
879template <typename Container, typename UnaryPredicate>
880void erase_if(Container &C, UnaryPredicate P) {
881 C.erase(remove_if(C, P), C.end());
882}
883
884//===----------------------------------------------------------------------===//
885// Extra additions to <memory>
886//===----------------------------------------------------------------------===//
887
888// Implement make_unique according to N3656.
889
890/// \brief Constructs a `new T()` with the given args and returns a
891/// `unique_ptr<T>` which owns the object.
892///
893/// Example:
894///
895/// auto p = make_unique<int>();
896/// auto p = make_unique<std::tuple<int, int>>(0, 1);
897template <class T, class... Args>
898typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
899make_unique(Args &&... args) {
900 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
46
Calling 'forward'
47
Returning from 'forward'
901}
902
903/// \brief Constructs a `new T[n]` with the given args and returns a
904/// `unique_ptr<T[]>` which owns the object.
905///
906/// \param n size of the new array.
907///
908/// Example:
909///
910/// auto p = make_unique<int[]>(2); // value-initializes the array with 0's.
911template <class T>
912typename std::enable_if<std::is_array<T>::value && std::extent<T>::value == 0,
913 std::unique_ptr<T>>::type
914make_unique(size_t n) {
915 return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]());
916}
917
918/// This function isn't used and is only here to provide better compile errors.
919template <class T, class... Args>
920typename std::enable_if<std::extent<T>::value != 0>::type
921make_unique(Args &&...) = delete;
922
923struct FreeDeleter {
924 void operator()(void* v) {
925 ::free(v);
926 }
927};
928
929template<typename First, typename Second>
930struct pair_hash {
931 size_t operator()(const std::pair<First, Second> &P) const {
932 return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second);
933 }
934};
935
936/// A functor like C++14's std::less<void> in its absence.
937struct less {
938 template <typename A, typename B> bool operator()(A &&a, B &&b) const {
939 return std::forward<A>(a) < std::forward<B>(b);
940 }
941};
942
943/// A functor like C++14's std::equal<void> in its absence.
944struct equal {
945 template <typename A, typename B> bool operator()(A &&a, B &&b) const {
946 return std::forward<A>(a) == std::forward<B>(b);
947 }
948};
949
950/// Binary functor that adapts to any other binary functor after dereferencing
951/// operands.
952template <typename T> struct deref {
953 T func;
954
955 // Could be further improved to cope with non-derivable functors and
956 // non-binary functors (should be a variadic template member function
957 // operator()).
958 template <typename A, typename B>
959 auto operator()(A &lhs, B &rhs) const -> decltype(func(*lhs, *rhs)) {
960 assert(lhs)((lhs) ? static_cast<void> (0) : __assert_fail ("lhs", "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/ADT/STLExtras.h"
, 960, __PRETTY_FUNCTION__))
;
961 assert(rhs)((rhs) ? static_cast<void> (0) : __assert_fail ("rhs", "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/ADT/STLExtras.h"
, 961, __PRETTY_FUNCTION__))
;
962 return func(*lhs, *rhs);
963 }
964};
965
966namespace detail {
967
968template <typename R> class enumerator_iter;
969
970template <typename R> struct result_pair {
971 friend class enumerator_iter<R>;
972
973 result_pair() = default;
974 result_pair(std::size_t Index, IterOfRange<R> Iter)
975 : Index(Index), Iter(Iter) {}
976
977 result_pair<R> &operator=(const result_pair<R> &Other) {
978 Index = Other.Index;
979 Iter = Other.Iter;
980 return *this;
981 }
982
983 std::size_t index() const { return Index; }
984 const ValueOfRange<R> &value() const { return *Iter; }
985 ValueOfRange<R> &value() { return *Iter; }
986
987private:
988 std::size_t Index = std::numeric_limits<std::size_t>::max();
989 IterOfRange<R> Iter;
990};
991
992template <typename R>
993class enumerator_iter
994 : public iterator_facade_base<
995 enumerator_iter<R>, std::forward_iterator_tag, result_pair<R>,
996 typename std::iterator_traits<IterOfRange<R>>::difference_type,
997 typename std::iterator_traits<IterOfRange<R>>::pointer,
998 typename std::iterator_traits<IterOfRange<R>>::reference> {
999 using result_type = result_pair<R>;
1000
1001public:
1002 explicit enumerator_iter(IterOfRange<R> EndIter)
1003 : Result(std::numeric_limits<size_t>::max(), EndIter) {}
1004
1005 enumerator_iter(std::size_t Index, IterOfRange<R> Iter)
1006 : Result(Index, Iter) {}
1007
1008 result_type &operator*() { return Result; }
1009 const result_type &operator*() const { return Result; }
1010
1011 enumerator_iter<R> &operator++() {
1012 assert(Result.Index != std::numeric_limits<size_t>::max())((Result.Index != std::numeric_limits<size_t>::max()) ?
static_cast<void> (0) : __assert_fail ("Result.Index != std::numeric_limits<size_t>::max()"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/ADT/STLExtras.h"
, 1012, __PRETTY_FUNCTION__))
;
1013 ++Result.Iter;
1014 ++Result.Index;
1015 return *this;
1016 }
1017
1018 bool operator==(const enumerator_iter<R> &RHS) const {
1019 // Don't compare indices here, only iterators. It's possible for an end
1020 // iterator to have different indices depending on whether it was created
1021 // by calling std::end() versus incrementing a valid iterator.
1022 return Result.Iter == RHS.Result.Iter;
1023 }
1024
1025 enumerator_iter<R> &operator=(const enumerator_iter<R> &Other) {
1026 Result = Other.Result;
1027 return *this;
1028 }
1029
1030private:
1031 result_type Result;
1032};
1033
1034template <typename R> class enumerator {
1035public:
1036 explicit enumerator(R &&Range) : TheRange(std::forward<R>(Range)) {}
1037
1038 enumerator_iter<R> begin() {
1039 return enumerator_iter<R>(0, std::begin(TheRange));
1040 }
1041
1042 enumerator_iter<R> end() {
1043 return enumerator_iter<R>(std::end(TheRange));
1044 }
1045
1046private:
1047 R TheRange;
1048};
1049
1050} // end namespace detail
1051
1052/// Given an input range, returns a new range whose values are are pair (A,B)
1053/// such that A is the 0-based index of the item in the sequence, and B is
1054/// the value from the original sequence. Example:
1055///
1056/// std::vector<char> Items = {'A', 'B', 'C', 'D'};
1057/// for (auto X : enumerate(Items)) {
1058/// printf("Item %d - %c\n", X.index(), X.value());
1059/// }
1060///
1061/// Output:
1062/// Item 0 - A
1063/// Item 1 - B
1064/// Item 2 - C
1065/// Item 3 - D
1066///
1067template <typename R> detail::enumerator<R> enumerate(R &&TheRange) {
1068 return detail::enumerator<R>(std::forward<R>(TheRange));
1069}
1070
1071namespace detail {
1072
1073template <typename F, typename Tuple, std::size_t... I>
1074auto apply_tuple_impl(F &&f, Tuple &&t, index_sequence<I...>)
1075 -> decltype(std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...)) {
1076 return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
1077}
1078
1079} // end namespace detail
1080
1081/// Given an input tuple (a1, a2, ..., an), pass the arguments of the
1082/// tuple variadically to f as if by calling f(a1, a2, ..., an) and
1083/// return the result.
1084template <typename F, typename Tuple>
1085auto apply_tuple(F &&f, Tuple &&t) -> decltype(detail::apply_tuple_impl(
1086 std::forward<F>(f), std::forward<Tuple>(t),
1087 build_index_impl<
1088 std::tuple_size<typename std::decay<Tuple>::type>::value>{})) {
1089 using Indices = build_index_impl<
1090 std::tuple_size<typename std::decay<Tuple>::type>::value>;
1091
1092 return detail::apply_tuple_impl(std::forward<F>(f), std::forward<Tuple>(t),
1093 Indices{});
1094}
1095
1096} // end namespace llvm
1097
1098#endif // LLVM_ADT_STLEXTRAS_H