File: | tools/llvm-profdata/llvm-profdata.cpp |
Warning: | line 323, column 23 Division by zero |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===- llvm-profdata.cpp - LLVM profile data tool -------------------------===// | |||
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 | // llvm-profdata merges .profdata files. | |||
11 | // | |||
12 | //===----------------------------------------------------------------------===// | |||
13 | ||||
14 | #include "llvm/ADT/SmallSet.h" | |||
15 | #include "llvm/ADT/SmallVector.h" | |||
16 | #include "llvm/ADT/StringRef.h" | |||
17 | #include "llvm/IR/LLVMContext.h" | |||
18 | #include "llvm/ProfileData/InstrProfReader.h" | |||
19 | #include "llvm/ProfileData/InstrProfWriter.h" | |||
20 | #include "llvm/ProfileData/ProfileCommon.h" | |||
21 | #include "llvm/ProfileData/SampleProfReader.h" | |||
22 | #include "llvm/ProfileData/SampleProfWriter.h" | |||
23 | #include "llvm/Support/CommandLine.h" | |||
24 | #include "llvm/Support/Errc.h" | |||
25 | #include "llvm/Support/FileSystem.h" | |||
26 | #include "llvm/Support/Format.h" | |||
27 | #include "llvm/Support/InitLLVM.h" | |||
28 | #include "llvm/Support/MemoryBuffer.h" | |||
29 | #include "llvm/Support/Path.h" | |||
30 | #include "llvm/Support/WithColor.h" | |||
31 | #include "llvm/Support/ThreadPool.h" | |||
32 | #include "llvm/Support/raw_ostream.h" | |||
33 | #include <algorithm> | |||
34 | ||||
35 | using namespace llvm; | |||
36 | ||||
37 | enum ProfileFormat { | |||
38 | PF_None = 0, | |||
39 | PF_Text, | |||
40 | PF_Compact_Binary, | |||
41 | PF_GCC, | |||
42 | PF_Binary | |||
43 | }; | |||
44 | ||||
45 | static void warn(Twine Message, std::string Whence = "", | |||
46 | std::string Hint = "") { | |||
47 | WithColor::warning(); | |||
48 | if (!Whence.empty()) | |||
49 | errs() << Whence << ": "; | |||
50 | errs() << Message << "\n"; | |||
51 | if (!Hint.empty()) | |||
52 | WithColor::note() << Hint << "\n"; | |||
53 | } | |||
54 | ||||
55 | static void exitWithError(Twine Message, std::string Whence = "", | |||
56 | std::string Hint = "") { | |||
57 | WithColor::error(); | |||
58 | if (!Whence.empty()) | |||
59 | errs() << Whence << ": "; | |||
60 | errs() << Message << "\n"; | |||
61 | if (!Hint.empty()) | |||
62 | WithColor::note() << Hint << "\n"; | |||
63 | ::exit(1); | |||
64 | } | |||
65 | ||||
66 | static void exitWithError(Error E, StringRef Whence = "") { | |||
67 | if (E.isA<InstrProfError>()) { | |||
68 | handleAllErrors(std::move(E), [&](const InstrProfError &IPE) { | |||
69 | instrprof_error instrError = IPE.get(); | |||
70 | StringRef Hint = ""; | |||
71 | if (instrError == instrprof_error::unrecognized_format) { | |||
72 | // Hint for common error of forgetting -sample for sample profiles. | |||
73 | Hint = "Perhaps you forgot to use the -sample option?"; | |||
74 | } | |||
75 | exitWithError(IPE.message(), Whence, Hint); | |||
76 | }); | |||
77 | } | |||
78 | ||||
79 | exitWithError(toString(std::move(E)), Whence); | |||
80 | } | |||
81 | ||||
82 | static void exitWithErrorCode(std::error_code EC, StringRef Whence = "") { | |||
83 | exitWithError(EC.message(), Whence); | |||
84 | } | |||
85 | ||||
86 | namespace { | |||
87 | enum ProfileKinds { instr, sample }; | |||
88 | } | |||
89 | ||||
90 | static void handleMergeWriterError(Error E, StringRef WhenceFile = "", | |||
91 | StringRef WhenceFunction = "", | |||
92 | bool ShowHint = true) { | |||
93 | if (!WhenceFile.empty()) | |||
94 | errs() << WhenceFile << ": "; | |||
95 | if (!WhenceFunction.empty()) | |||
96 | errs() << WhenceFunction << ": "; | |||
97 | ||||
98 | auto IPE = instrprof_error::success; | |||
99 | E = handleErrors(std::move(E), | |||
100 | [&IPE](std::unique_ptr<InstrProfError> E) -> Error { | |||
101 | IPE = E->get(); | |||
102 | return Error(std::move(E)); | |||
103 | }); | |||
104 | errs() << toString(std::move(E)) << "\n"; | |||
105 | ||||
106 | if (ShowHint) { | |||
107 | StringRef Hint = ""; | |||
108 | if (IPE != instrprof_error::success) { | |||
109 | switch (IPE) { | |||
110 | case instrprof_error::hash_mismatch: | |||
111 | case instrprof_error::count_mismatch: | |||
112 | case instrprof_error::value_site_count_mismatch: | |||
113 | Hint = "Make sure that all profile data to be merged is generated " | |||
114 | "from the same binary."; | |||
115 | break; | |||
116 | default: | |||
117 | break; | |||
118 | } | |||
119 | } | |||
120 | ||||
121 | if (!Hint.empty()) | |||
122 | errs() << Hint << "\n"; | |||
123 | } | |||
124 | } | |||
125 | ||||
126 | namespace { | |||
127 | /// A remapper from original symbol names to new symbol names based on a file | |||
128 | /// containing a list of mappings from old name to new name. | |||
129 | class SymbolRemapper { | |||
130 | std::unique_ptr<MemoryBuffer> File; | |||
131 | DenseMap<StringRef, StringRef> RemappingTable; | |||
132 | ||||
133 | public: | |||
134 | /// Build a SymbolRemapper from a file containing a list of old/new symbols. | |||
135 | static std::unique_ptr<SymbolRemapper> create(StringRef InputFile) { | |||
136 | auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFile); | |||
137 | if (!BufOrError) | |||
138 | exitWithErrorCode(BufOrError.getError(), InputFile); | |||
139 | ||||
140 | auto Remapper = llvm::make_unique<SymbolRemapper>(); | |||
141 | Remapper->File = std::move(BufOrError.get()); | |||
142 | ||||
143 | for (line_iterator LineIt(*Remapper->File, /*SkipBlanks=*/true, '#'); | |||
144 | !LineIt.is_at_eof(); ++LineIt) { | |||
145 | std::pair<StringRef, StringRef> Parts = LineIt->split(' '); | |||
146 | if (Parts.first.empty() || Parts.second.empty() || | |||
147 | Parts.second.count(' ')) { | |||
148 | exitWithError("unexpected line in remapping file", | |||
149 | (InputFile + ":" + Twine(LineIt.line_number())).str(), | |||
150 | "expected 'old_symbol new_symbol'"); | |||
151 | } | |||
152 | Remapper->RemappingTable.insert(Parts); | |||
153 | } | |||
154 | return Remapper; | |||
155 | } | |||
156 | ||||
157 | /// Attempt to map the given old symbol into a new symbol. | |||
158 | /// | |||
159 | /// \return The new symbol, or \p Name if no such symbol was found. | |||
160 | StringRef operator()(StringRef Name) { | |||
161 | StringRef New = RemappingTable.lookup(Name); | |||
162 | return New.empty() ? Name : New; | |||
163 | } | |||
164 | }; | |||
165 | } | |||
166 | ||||
167 | struct WeightedFile { | |||
168 | std::string Filename; | |||
169 | uint64_t Weight; | |||
170 | }; | |||
171 | typedef SmallVector<WeightedFile, 5> WeightedFileVector; | |||
172 | ||||
173 | /// Keep track of merged data and reported errors. | |||
174 | struct WriterContext { | |||
175 | std::mutex Lock; | |||
176 | InstrProfWriter Writer; | |||
177 | Error Err; | |||
178 | std::string ErrWhence; | |||
179 | std::mutex &ErrLock; | |||
180 | SmallSet<instrprof_error, 4> &WriterErrorCodes; | |||
181 | ||||
182 | WriterContext(bool IsSparse, std::mutex &ErrLock, | |||
183 | SmallSet<instrprof_error, 4> &WriterErrorCodes) | |||
184 | : Lock(), Writer(IsSparse), Err(Error::success()), ErrWhence(""), | |||
185 | ErrLock(ErrLock), WriterErrorCodes(WriterErrorCodes) {} | |||
186 | }; | |||
187 | ||||
188 | /// Determine whether an error is fatal for profile merging. | |||
189 | static bool isFatalError(instrprof_error IPE) { | |||
190 | switch (IPE) { | |||
191 | default: | |||
192 | return true; | |||
193 | case instrprof_error::success: | |||
194 | case instrprof_error::eof: | |||
195 | case instrprof_error::unknown_function: | |||
196 | case instrprof_error::hash_mismatch: | |||
197 | case instrprof_error::count_mismatch: | |||
198 | case instrprof_error::counter_overflow: | |||
199 | case instrprof_error::value_site_count_mismatch: | |||
200 | return false; | |||
201 | } | |||
202 | } | |||
203 | ||||
204 | /// Load an input into a writer context. | |||
205 | static void loadInput(const WeightedFile &Input, SymbolRemapper *Remapper, | |||
206 | WriterContext *WC) { | |||
207 | std::unique_lock<std::mutex> CtxGuard{WC->Lock}; | |||
208 | ||||
209 | // If there's a pending hard error, don't do more work. | |||
210 | if (WC->Err) | |||
211 | return; | |||
212 | ||||
213 | // Copy the filename, because llvm::ThreadPool copied the input "const | |||
214 | // WeightedFile &" by value, making a reference to the filename within it | |||
215 | // invalid outside of this packaged task. | |||
216 | WC->ErrWhence = Input.Filename; | |||
217 | ||||
218 | auto ReaderOrErr = InstrProfReader::create(Input.Filename); | |||
219 | if (Error E = ReaderOrErr.takeError()) { | |||
220 | // Skip the empty profiles by returning sliently. | |||
221 | instrprof_error IPE = InstrProfError::take(std::move(E)); | |||
222 | if (IPE != instrprof_error::empty_raw_profile) | |||
223 | WC->Err = make_error<InstrProfError>(IPE); | |||
224 | return; | |||
225 | } | |||
226 | ||||
227 | auto Reader = std::move(ReaderOrErr.get()); | |||
228 | bool IsIRProfile = Reader->isIRLevelProfile(); | |||
229 | if (WC->Writer.setIsIRLevelProfile(IsIRProfile)) { | |||
230 | WC->Err = make_error<StringError>( | |||
231 | "Merge IR generated profile with Clang generated profile.", | |||
232 | std::error_code()); | |||
233 | return; | |||
234 | } | |||
235 | ||||
236 | for (auto &I : *Reader) { | |||
237 | if (Remapper) | |||
238 | I.Name = (*Remapper)(I.Name); | |||
239 | const StringRef FuncName = I.Name; | |||
240 | bool Reported = false; | |||
241 | WC->Writer.addRecord(std::move(I), Input.Weight, [&](Error E) { | |||
242 | if (Reported) { | |||
243 | consumeError(std::move(E)); | |||
244 | return; | |||
245 | } | |||
246 | Reported = true; | |||
247 | // Only show hint the first time an error occurs. | |||
248 | instrprof_error IPE = InstrProfError::take(std::move(E)); | |||
249 | std::unique_lock<std::mutex> ErrGuard{WC->ErrLock}; | |||
250 | bool firstTime = WC->WriterErrorCodes.insert(IPE).second; | |||
251 | handleMergeWriterError(make_error<InstrProfError>(IPE), Input.Filename, | |||
252 | FuncName, firstTime); | |||
253 | }); | |||
254 | } | |||
255 | if (Reader->hasError()) { | |||
256 | if (Error E = Reader->getError()) { | |||
257 | instrprof_error IPE = InstrProfError::take(std::move(E)); | |||
258 | if (isFatalError(IPE)) | |||
259 | WC->Err = make_error<InstrProfError>(IPE); | |||
260 | } | |||
261 | } | |||
262 | } | |||
263 | ||||
264 | /// Merge the \p Src writer context into \p Dst. | |||
265 | static void mergeWriterContexts(WriterContext *Dst, WriterContext *Src) { | |||
266 | // If we've already seen a hard error, continuing with the merge would | |||
267 | // clobber it. | |||
268 | if (Dst->Err || Src->Err) | |||
269 | return; | |||
270 | ||||
271 | bool Reported = false; | |||
272 | Dst->Writer.mergeRecordsFromWriter(std::move(Src->Writer), [&](Error E) { | |||
273 | if (Reported) { | |||
274 | consumeError(std::move(E)); | |||
275 | return; | |||
276 | } | |||
277 | Reported = true; | |||
278 | Dst->Err = std::move(E); | |||
279 | }); | |||
280 | } | |||
281 | ||||
282 | static void mergeInstrProfile(const WeightedFileVector &Inputs, | |||
283 | SymbolRemapper *Remapper, | |||
284 | StringRef OutputFilename, | |||
285 | ProfileFormat OutputFormat, bool OutputSparse, | |||
286 | unsigned NumThreads) { | |||
287 | if (OutputFilename.compare("-") == 0) | |||
288 | exitWithError("Cannot write indexed profdata format to stdout."); | |||
289 | ||||
290 | if (OutputFormat != PF_Binary && OutputFormat != PF_Compact_Binary && | |||
291 | OutputFormat != PF_Text) | |||
292 | exitWithError("Unknown format is specified."); | |||
293 | ||||
294 | std::error_code EC; | |||
295 | raw_fd_ostream Output(OutputFilename.data(), EC, sys::fs::F_None); | |||
296 | if (EC) | |||
297 | exitWithErrorCode(EC, OutputFilename); | |||
298 | ||||
299 | std::mutex ErrorLock; | |||
300 | SmallSet<instrprof_error, 4> WriterErrorCodes; | |||
301 | ||||
302 | // If NumThreads is not specified, auto-detect a good default. | |||
303 | if (NumThreads == 0) | |||
304 | NumThreads = | |||
305 | std::min(hardware_concurrency(), unsigned((Inputs.size() + 1) / 2)); | |||
306 | ||||
307 | // Initialize the writer contexts. | |||
308 | SmallVector<std::unique_ptr<WriterContext>, 4> Contexts; | |||
309 | for (unsigned I = 0; I < NumThreads; ++I) | |||
310 | Contexts.emplace_back(llvm::make_unique<WriterContext>( | |||
311 | OutputSparse, ErrorLock, WriterErrorCodes)); | |||
312 | ||||
313 | if (NumThreads == 1) { | |||
314 | for (const auto &Input : Inputs) | |||
315 | loadInput(Input, Remapper, Contexts[0].get()); | |||
316 | } else { | |||
317 | ThreadPool Pool(NumThreads); | |||
318 | ||||
319 | // Load the inputs in parallel (N/NumThreads serial steps). | |||
320 | unsigned Ctx = 0; | |||
321 | for (const auto &Input : Inputs) { | |||
322 | Pool.async(loadInput, Input, Remapper, Contexts[Ctx].get()); | |||
323 | Ctx = (Ctx + 1) % NumThreads; | |||
| ||||
324 | } | |||
325 | Pool.wait(); | |||
326 | ||||
327 | // Merge the writer contexts together (~ lg(NumThreads) serial steps). | |||
328 | unsigned Mid = Contexts.size() / 2; | |||
329 | unsigned End = Contexts.size(); | |||
330 | assert(Mid > 0 && "Expected more than one context")((Mid > 0 && "Expected more than one context") ? static_cast <void> (0) : __assert_fail ("Mid > 0 && \"Expected more than one context\"" , "/build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-profdata/llvm-profdata.cpp" , 330, __PRETTY_FUNCTION__)); | |||
331 | do { | |||
332 | for (unsigned I = 0; I < Mid; ++I) | |||
333 | Pool.async(mergeWriterContexts, Contexts[I].get(), | |||
334 | Contexts[I + Mid].get()); | |||
335 | Pool.wait(); | |||
336 | if (End & 1) { | |||
337 | Pool.async(mergeWriterContexts, Contexts[0].get(), | |||
338 | Contexts[End - 1].get()); | |||
339 | Pool.wait(); | |||
340 | } | |||
341 | End = Mid; | |||
342 | Mid /= 2; | |||
343 | } while (Mid > 0); | |||
344 | } | |||
345 | ||||
346 | // Handle deferred hard errors encountered during merging. | |||
347 | for (std::unique_ptr<WriterContext> &WC : Contexts) { | |||
348 | if (!WC->Err) | |||
349 | continue; | |||
350 | if (!WC->Err.isA<InstrProfError>()) | |||
351 | exitWithError(std::move(WC->Err), WC->ErrWhence); | |||
352 | ||||
353 | instrprof_error IPE = InstrProfError::take(std::move(WC->Err)); | |||
354 | if (isFatalError(IPE)) | |||
355 | exitWithError(make_error<InstrProfError>(IPE), WC->ErrWhence); | |||
356 | else | |||
357 | warn(toString(make_error<InstrProfError>(IPE)), | |||
358 | WC->ErrWhence); | |||
359 | } | |||
360 | ||||
361 | InstrProfWriter &Writer = Contexts[0]->Writer; | |||
362 | if (OutputFormat == PF_Text) { | |||
363 | if (Error E = Writer.writeText(Output)) | |||
364 | exitWithError(std::move(E)); | |||
365 | } else { | |||
366 | Writer.write(Output); | |||
367 | } | |||
368 | } | |||
369 | ||||
370 | /// Make a copy of the given function samples with all symbol names remapped | |||
371 | /// by the provided symbol remapper. | |||
372 | static sampleprof::FunctionSamples | |||
373 | remapSamples(const sampleprof::FunctionSamples &Samples, | |||
374 | SymbolRemapper &Remapper, sampleprof_error &Error) { | |||
375 | sampleprof::FunctionSamples Result; | |||
376 | Result.setName(Remapper(Samples.getName())); | |||
377 | Result.addTotalSamples(Samples.getTotalSamples()); | |||
378 | Result.addHeadSamples(Samples.getHeadSamples()); | |||
379 | for (const auto &BodySample : Samples.getBodySamples()) { | |||
380 | Result.addBodySamples(BodySample.first.LineOffset, | |||
381 | BodySample.first.Discriminator, | |||
382 | BodySample.second.getSamples()); | |||
383 | for (const auto &Target : BodySample.second.getCallTargets()) { | |||
384 | Result.addCalledTargetSamples(BodySample.first.LineOffset, | |||
385 | BodySample.first.Discriminator, | |||
386 | Remapper(Target.first()), Target.second); | |||
387 | } | |||
388 | } | |||
389 | for (const auto &CallsiteSamples : Samples.getCallsiteSamples()) { | |||
390 | sampleprof::FunctionSamplesMap &Target = | |||
391 | Result.functionSamplesAt(CallsiteSamples.first); | |||
392 | for (const auto &Callsite : CallsiteSamples.second) { | |||
393 | sampleprof::FunctionSamples Remapped = | |||
394 | remapSamples(Callsite.second, Remapper, Error); | |||
395 | MergeResult(Error, Target[Remapped.getName()].merge(Remapped)); | |||
396 | } | |||
397 | } | |||
398 | return Result; | |||
399 | } | |||
400 | ||||
401 | static sampleprof::SampleProfileFormat FormatMap[] = { | |||
402 | sampleprof::SPF_None, sampleprof::SPF_Text, sampleprof::SPF_Compact_Binary, | |||
403 | sampleprof::SPF_GCC, sampleprof::SPF_Binary}; | |||
404 | ||||
405 | static void mergeSampleProfile(const WeightedFileVector &Inputs, | |||
406 | SymbolRemapper *Remapper, | |||
407 | StringRef OutputFilename, | |||
408 | ProfileFormat OutputFormat) { | |||
409 | using namespace sampleprof; | |||
410 | auto WriterOrErr = | |||
411 | SampleProfileWriter::create(OutputFilename, FormatMap[OutputFormat]); | |||
412 | if (std::error_code EC = WriterOrErr.getError()) | |||
413 | exitWithErrorCode(EC, OutputFilename); | |||
414 | ||||
415 | auto Writer = std::move(WriterOrErr.get()); | |||
416 | StringMap<FunctionSamples> ProfileMap; | |||
417 | SmallVector<std::unique_ptr<sampleprof::SampleProfileReader>, 5> Readers; | |||
418 | LLVMContext Context; | |||
419 | for (const auto &Input : Inputs) { | |||
420 | auto ReaderOrErr = SampleProfileReader::create(Input.Filename, Context); | |||
421 | if (std::error_code EC = ReaderOrErr.getError()) | |||
422 | exitWithErrorCode(EC, Input.Filename); | |||
423 | ||||
424 | // We need to keep the readers around until after all the files are | |||
425 | // read so that we do not lose the function names stored in each | |||
426 | // reader's memory. The function names are needed to write out the | |||
427 | // merged profile map. | |||
428 | Readers.push_back(std::move(ReaderOrErr.get())); | |||
429 | const auto Reader = Readers.back().get(); | |||
430 | if (std::error_code EC = Reader->read()) | |||
431 | exitWithErrorCode(EC, Input.Filename); | |||
432 | ||||
433 | StringMap<FunctionSamples> &Profiles = Reader->getProfiles(); | |||
434 | for (StringMap<FunctionSamples>::iterator I = Profiles.begin(), | |||
435 | E = Profiles.end(); | |||
436 | I != E; ++I) { | |||
437 | sampleprof_error Result = sampleprof_error::success; | |||
438 | FunctionSamples Remapped = | |||
439 | Remapper ? remapSamples(I->second, *Remapper, Result) | |||
440 | : FunctionSamples(); | |||
441 | FunctionSamples &Samples = Remapper ? Remapped : I->second; | |||
442 | StringRef FName = Samples.getName(); | |||
443 | MergeResult(Result, ProfileMap[FName].merge(Samples, Input.Weight)); | |||
444 | if (Result != sampleprof_error::success) { | |||
445 | std::error_code EC = make_error_code(Result); | |||
446 | handleMergeWriterError(errorCodeToError(EC), Input.Filename, FName); | |||
447 | } | |||
448 | } | |||
449 | } | |||
450 | Writer->write(ProfileMap); | |||
451 | } | |||
452 | ||||
453 | static WeightedFile parseWeightedFile(const StringRef &WeightedFilename) { | |||
454 | StringRef WeightStr, FileName; | |||
455 | std::tie(WeightStr, FileName) = WeightedFilename.split(','); | |||
456 | ||||
457 | uint64_t Weight; | |||
458 | if (WeightStr.getAsInteger(10, Weight) || Weight < 1) | |||
459 | exitWithError("Input weight must be a positive integer."); | |||
460 | ||||
461 | return {FileName, Weight}; | |||
462 | } | |||
463 | ||||
464 | static std::unique_ptr<MemoryBuffer> | |||
465 | getInputFilenamesFileBuf(const StringRef &InputFilenamesFile) { | |||
466 | if (InputFilenamesFile == "") | |||
467 | return {}; | |||
468 | ||||
469 | auto BufOrError = MemoryBuffer::getFileOrSTDIN(InputFilenamesFile); | |||
470 | if (!BufOrError) | |||
471 | exitWithErrorCode(BufOrError.getError(), InputFilenamesFile); | |||
472 | ||||
473 | return std::move(*BufOrError); | |||
474 | } | |||
475 | ||||
476 | static void addWeightedInput(WeightedFileVector &WNI, const WeightedFile &WF) { | |||
477 | StringRef Filename = WF.Filename; | |||
478 | uint64_t Weight = WF.Weight; | |||
479 | ||||
480 | // If it's STDIN just pass it on. | |||
481 | if (Filename == "-") { | |||
482 | WNI.push_back({Filename, Weight}); | |||
483 | return; | |||
484 | } | |||
485 | ||||
486 | llvm::sys::fs::file_status Status; | |||
487 | llvm::sys::fs::status(Filename, Status); | |||
488 | if (!llvm::sys::fs::exists(Status)) | |||
489 | exitWithErrorCode(make_error_code(errc::no_such_file_or_directory), | |||
490 | Filename); | |||
491 | // If it's a source file, collect it. | |||
492 | if (llvm::sys::fs::is_regular_file(Status)) { | |||
493 | WNI.push_back({Filename, Weight}); | |||
494 | return; | |||
495 | } | |||
496 | ||||
497 | if (llvm::sys::fs::is_directory(Status)) { | |||
498 | std::error_code EC; | |||
499 | for (llvm::sys::fs::recursive_directory_iterator F(Filename, EC), E; | |||
500 | F != E && !EC; F.increment(EC)) { | |||
501 | if (llvm::sys::fs::is_regular_file(F->path())) { | |||
502 | addWeightedInput(WNI, {F->path(), Weight}); | |||
503 | } | |||
504 | } | |||
505 | if (EC) | |||
506 | exitWithErrorCode(EC, Filename); | |||
507 | } | |||
508 | } | |||
509 | ||||
510 | static void parseInputFilenamesFile(MemoryBuffer *Buffer, | |||
511 | WeightedFileVector &WFV) { | |||
512 | if (!Buffer) | |||
513 | return; | |||
514 | ||||
515 | SmallVector<StringRef, 8> Entries; | |||
516 | StringRef Data = Buffer->getBuffer(); | |||
517 | Data.split(Entries, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false); | |||
518 | for (const StringRef &FileWeightEntry : Entries) { | |||
519 | StringRef SanitizedEntry = FileWeightEntry.trim(" \t\v\f\r"); | |||
520 | // Skip comments. | |||
521 | if (SanitizedEntry.startswith("#")) | |||
522 | continue; | |||
523 | // If there's no comma, it's an unweighted profile. | |||
524 | else if (SanitizedEntry.find(',') == StringRef::npos) | |||
525 | addWeightedInput(WFV, {SanitizedEntry, 1}); | |||
526 | else | |||
527 | addWeightedInput(WFV, parseWeightedFile(SanitizedEntry)); | |||
528 | } | |||
529 | } | |||
530 | ||||
531 | static int merge_main(int argc, const char *argv[]) { | |||
532 | cl::list<std::string> InputFilenames(cl::Positional, | |||
533 | cl::desc("<filename...>")); | |||
534 | cl::list<std::string> WeightedInputFilenames("weighted-input", | |||
535 | cl::desc("<weight>,<filename>")); | |||
536 | cl::opt<std::string> InputFilenamesFile( | |||
537 | "input-files", cl::init(""), | |||
538 | cl::desc("Path to file containing newline-separated " | |||
539 | "[<weight>,]<filename> entries")); | |||
540 | cl::alias InputFilenamesFileA("f", cl::desc("Alias for --input-files"), | |||
541 | cl::aliasopt(InputFilenamesFile)); | |||
542 | cl::opt<bool> DumpInputFileList( | |||
543 | "dump-input-file-list", cl::init(false), cl::Hidden, | |||
544 | cl::desc("Dump the list of input files and their weights, then exit")); | |||
545 | cl::opt<std::string> RemappingFile("remapping-file", cl::value_desc("file"), | |||
546 | cl::desc("Symbol remapping file")); | |||
547 | cl::alias RemappingFileA("r", cl::desc("Alias for --remapping-file"), | |||
548 | cl::aliasopt(RemappingFile)); | |||
549 | cl::opt<std::string> OutputFilename("output", cl::value_desc("output"), | |||
550 | cl::init("-"), cl::Required, | |||
551 | cl::desc("Output file")); | |||
552 | cl::alias OutputFilenameA("o", cl::desc("Alias for --output"), | |||
553 | cl::aliasopt(OutputFilename)); | |||
554 | cl::opt<ProfileKinds> ProfileKind( | |||
555 | cl::desc("Profile kind:"), cl::init(instr), | |||
556 | cl::values(clEnumVal(instr, "Instrumentation profile (default)")llvm::cl::OptionEnumValue { "instr", int(instr), "Instrumentation profile (default)" }, | |||
557 | clEnumVal(sample, "Sample profile")llvm::cl::OptionEnumValue { "sample", int(sample), "Sample profile" })); | |||
558 | cl::opt<ProfileFormat> OutputFormat( | |||
559 | cl::desc("Format of output profile"), cl::init(PF_Binary), | |||
560 | cl::values(clEnumValN(PF_Binary, "binary", "Binary encoding (default)")llvm::cl::OptionEnumValue { "binary", int(PF_Binary), "Binary encoding (default)" }, | |||
561 | clEnumValN(PF_Compact_Binary, "compbinary",llvm::cl::OptionEnumValue { "compbinary", int(PF_Compact_Binary ), "Compact binary encoding" } | |||
562 | "Compact binary encoding")llvm::cl::OptionEnumValue { "compbinary", int(PF_Compact_Binary ), "Compact binary encoding" }, | |||
563 | clEnumValN(PF_Text, "text", "Text encoding")llvm::cl::OptionEnumValue { "text", int(PF_Text), "Text encoding" }, | |||
564 | clEnumValN(PF_GCC, "gcc",llvm::cl::OptionEnumValue { "gcc", int(PF_GCC), "GCC encoding (only meaningful for -sample)" } | |||
565 | "GCC encoding (only meaningful for -sample)")llvm::cl::OptionEnumValue { "gcc", int(PF_GCC), "GCC encoding (only meaningful for -sample)" })); | |||
566 | cl::opt<bool> OutputSparse("sparse", cl::init(false), | |||
567 | cl::desc("Generate a sparse profile (only meaningful for -instr)")); | |||
568 | cl::opt<unsigned> NumThreads( | |||
569 | "num-threads", cl::init(0), | |||
570 | cl::desc("Number of merge threads to use (default: autodetect)")); | |||
571 | cl::alias NumThreadsA("j", cl::desc("Alias for --num-threads"), | |||
572 | cl::aliasopt(NumThreads)); | |||
573 | ||||
574 | cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n"); | |||
575 | ||||
576 | WeightedFileVector WeightedInputs; | |||
577 | for (StringRef Filename : InputFilenames) | |||
578 | addWeightedInput(WeightedInputs, {Filename, 1}); | |||
579 | for (StringRef WeightedFilename : WeightedInputFilenames) | |||
580 | addWeightedInput(WeightedInputs, parseWeightedFile(WeightedFilename)); | |||
581 | ||||
582 | // Make sure that the file buffer stays alive for the duration of the | |||
583 | // weighted input vector's lifetime. | |||
584 | auto Buffer = getInputFilenamesFileBuf(InputFilenamesFile); | |||
585 | parseInputFilenamesFile(Buffer.get(), WeightedInputs); | |||
586 | ||||
587 | if (WeightedInputs.empty()) | |||
588 | exitWithError("No input files specified. See " + | |||
589 | sys::path::filename(argv[0]) + " -help"); | |||
590 | ||||
591 | if (DumpInputFileList) { | |||
592 | for (auto &WF : WeightedInputs) | |||
593 | outs() << WF.Weight << "," << WF.Filename << "\n"; | |||
594 | return 0; | |||
595 | } | |||
596 | ||||
597 | std::unique_ptr<SymbolRemapper> Remapper; | |||
598 | if (!RemappingFile.empty()) | |||
599 | Remapper = SymbolRemapper::create(RemappingFile); | |||
600 | ||||
601 | if (ProfileKind == instr) | |||
602 | mergeInstrProfile(WeightedInputs, Remapper.get(), OutputFilename, | |||
603 | OutputFormat, OutputSparse, NumThreads); | |||
604 | else | |||
605 | mergeSampleProfile(WeightedInputs, Remapper.get(), OutputFilename, | |||
606 | OutputFormat); | |||
607 | ||||
608 | return 0; | |||
609 | } | |||
610 | ||||
611 | typedef struct ValueSitesStats { | |||
612 | ValueSitesStats() | |||
613 | : TotalNumValueSites(0), TotalNumValueSitesWithValueProfile(0), | |||
614 | TotalNumValues(0) {} | |||
615 | uint64_t TotalNumValueSites; | |||
616 | uint64_t TotalNumValueSitesWithValueProfile; | |||
617 | uint64_t TotalNumValues; | |||
618 | std::vector<unsigned> ValueSitesHistogram; | |||
619 | } ValueSitesStats; | |||
620 | ||||
621 | static void traverseAllValueSites(const InstrProfRecord &Func, uint32_t VK, | |||
622 | ValueSitesStats &Stats, raw_fd_ostream &OS, | |||
623 | InstrProfSymtab *Symtab) { | |||
624 | uint32_t NS = Func.getNumValueSites(VK); | |||
625 | Stats.TotalNumValueSites += NS; | |||
626 | for (size_t I = 0; I < NS; ++I) { | |||
627 | uint32_t NV = Func.getNumValueDataForSite(VK, I); | |||
628 | std::unique_ptr<InstrProfValueData[]> VD = Func.getValueForSite(VK, I); | |||
629 | Stats.TotalNumValues += NV; | |||
630 | if (NV) { | |||
631 | Stats.TotalNumValueSitesWithValueProfile++; | |||
632 | if (NV > Stats.ValueSitesHistogram.size()) | |||
633 | Stats.ValueSitesHistogram.resize(NV, 0); | |||
634 | Stats.ValueSitesHistogram[NV - 1]++; | |||
635 | } | |||
636 | for (uint32_t V = 0; V < NV; V++) { | |||
637 | OS << "\t[ " << I << ", "; | |||
638 | if (Symtab == nullptr) | |||
639 | OS << VD[V].Value; | |||
640 | else | |||
641 | OS << Symtab->getFuncName(VD[V].Value); | |||
642 | OS << ", " << VD[V].Count << " ]\n"; | |||
643 | } | |||
644 | } | |||
645 | } | |||
646 | ||||
647 | static void showValueSitesStats(raw_fd_ostream &OS, uint32_t VK, | |||
648 | ValueSitesStats &Stats) { | |||
649 | OS << " Total number of sites: " << Stats.TotalNumValueSites << "\n"; | |||
650 | OS << " Total number of sites with values: " | |||
651 | << Stats.TotalNumValueSitesWithValueProfile << "\n"; | |||
652 | OS << " Total number of profiled values: " << Stats.TotalNumValues << "\n"; | |||
653 | ||||
654 | OS << " Value sites histogram:\n\tNumTargets, SiteCount\n"; | |||
655 | for (unsigned I = 0; I < Stats.ValueSitesHistogram.size(); I++) { | |||
656 | if (Stats.ValueSitesHistogram[I] > 0) | |||
657 | OS << "\t" << I + 1 << ", " << Stats.ValueSitesHistogram[I] << "\n"; | |||
658 | } | |||
659 | } | |||
660 | ||||
661 | static int showInstrProfile(const std::string &Filename, bool ShowCounts, | |||
662 | uint32_t TopN, bool ShowIndirectCallTargets, | |||
663 | bool ShowMemOPSizes, bool ShowDetailedSummary, | |||
664 | std::vector<uint32_t> DetailedSummaryCutoffs, | |||
665 | bool ShowAllFunctions, | |||
666 | const std::string &ShowFunction, bool TextFormat, | |||
667 | raw_fd_ostream &OS) { | |||
668 | auto ReaderOrErr = InstrProfReader::create(Filename); | |||
669 | std::vector<uint32_t> Cutoffs = std::move(DetailedSummaryCutoffs); | |||
670 | if (ShowDetailedSummary && Cutoffs.empty()) { | |||
671 | Cutoffs = {800000, 900000, 950000, 990000, 999000, 999900, 999990}; | |||
672 | } | |||
673 | InstrProfSummaryBuilder Builder(std::move(Cutoffs)); | |||
674 | if (Error E = ReaderOrErr.takeError()) | |||
675 | exitWithError(std::move(E), Filename); | |||
676 | ||||
677 | auto Reader = std::move(ReaderOrErr.get()); | |||
678 | bool IsIRInstr = Reader->isIRLevelProfile(); | |||
679 | size_t ShownFunctions = 0; | |||
680 | int NumVPKind = IPVK_Last - IPVK_First + 1; | |||
681 | std::vector<ValueSitesStats> VPStats(NumVPKind); | |||
682 | ||||
683 | auto MinCmp = [](const std::pair<std::string, uint64_t> &v1, | |||
684 | const std::pair<std::string, uint64_t> &v2) { | |||
685 | return v1.second > v2.second; | |||
686 | }; | |||
687 | ||||
688 | std::priority_queue<std::pair<std::string, uint64_t>, | |||
689 | std::vector<std::pair<std::string, uint64_t>>, | |||
690 | decltype(MinCmp)> | |||
691 | HottestFuncs(MinCmp); | |||
692 | ||||
693 | // Add marker so that IR-level instrumentation round-trips properly. | |||
694 | if (TextFormat && IsIRInstr) | |||
695 | OS << ":ir\n"; | |||
696 | ||||
697 | for (const auto &Func : *Reader) { | |||
698 | bool Show = | |||
699 | ShowAllFunctions || (!ShowFunction.empty() && | |||
700 | Func.Name.find(ShowFunction) != Func.Name.npos); | |||
701 | ||||
702 | bool doTextFormatDump = (Show && TextFormat); | |||
703 | ||||
704 | if (doTextFormatDump) { | |||
705 | InstrProfSymtab &Symtab = Reader->getSymtab(); | |||
706 | InstrProfWriter::writeRecordInText(Func.Name, Func.Hash, Func, Symtab, | |||
707 | OS); | |||
708 | continue; | |||
709 | } | |||
710 | ||||
711 | assert(Func.Counts.size() > 0 && "function missing entry counter")((Func.Counts.size() > 0 && "function missing entry counter" ) ? static_cast<void> (0) : __assert_fail ("Func.Counts.size() > 0 && \"function missing entry counter\"" , "/build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-profdata/llvm-profdata.cpp" , 711, __PRETTY_FUNCTION__)); | |||
712 | Builder.addRecord(Func); | |||
713 | ||||
714 | if (TopN) { | |||
715 | uint64_t FuncMax = 0; | |||
716 | for (size_t I = 0, E = Func.Counts.size(); I < E; ++I) | |||
717 | FuncMax = std::max(FuncMax, Func.Counts[I]); | |||
718 | ||||
719 | if (HottestFuncs.size() == TopN) { | |||
720 | if (HottestFuncs.top().second < FuncMax) { | |||
721 | HottestFuncs.pop(); | |||
722 | HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax)); | |||
723 | } | |||
724 | } else | |||
725 | HottestFuncs.emplace(std::make_pair(std::string(Func.Name), FuncMax)); | |||
726 | } | |||
727 | ||||
728 | if (Show) { | |||
729 | ||||
730 | if (!ShownFunctions) | |||
731 | OS << "Counters:\n"; | |||
732 | ||||
733 | ++ShownFunctions; | |||
734 | ||||
735 | OS << " " << Func.Name << ":\n" | |||
736 | << " Hash: " << format("0x%016" PRIx64"l" "x", Func.Hash) << "\n" | |||
737 | << " Counters: " << Func.Counts.size() << "\n"; | |||
738 | if (!IsIRInstr) | |||
739 | OS << " Function count: " << Func.Counts[0] << "\n"; | |||
740 | ||||
741 | if (ShowIndirectCallTargets) | |||
742 | OS << " Indirect Call Site Count: " | |||
743 | << Func.getNumValueSites(IPVK_IndirectCallTarget) << "\n"; | |||
744 | ||||
745 | uint32_t NumMemOPCalls = Func.getNumValueSites(IPVK_MemOPSize); | |||
746 | if (ShowMemOPSizes && NumMemOPCalls > 0) | |||
747 | OS << " Number of Memory Intrinsics Calls: " << NumMemOPCalls | |||
748 | << "\n"; | |||
749 | ||||
750 | if (ShowCounts) { | |||
751 | OS << " Block counts: ["; | |||
752 | size_t Start = (IsIRInstr ? 0 : 1); | |||
753 | for (size_t I = Start, E = Func.Counts.size(); I < E; ++I) { | |||
754 | OS << (I == Start ? "" : ", ") << Func.Counts[I]; | |||
755 | } | |||
756 | OS << "]\n"; | |||
757 | } | |||
758 | ||||
759 | if (ShowIndirectCallTargets) { | |||
760 | OS << " Indirect Target Results:\n"; | |||
761 | traverseAllValueSites(Func, IPVK_IndirectCallTarget, | |||
762 | VPStats[IPVK_IndirectCallTarget], OS, | |||
763 | &(Reader->getSymtab())); | |||
764 | } | |||
765 | ||||
766 | if (ShowMemOPSizes && NumMemOPCalls > 0) { | |||
767 | OS << " Memory Intrinsic Size Results:\n"; | |||
768 | traverseAllValueSites(Func, IPVK_MemOPSize, VPStats[IPVK_MemOPSize], OS, | |||
769 | nullptr); | |||
770 | } | |||
771 | } | |||
772 | } | |||
773 | if (Reader->hasError()) | |||
774 | exitWithError(Reader->getError(), Filename); | |||
775 | ||||
776 | if (TextFormat) | |||
777 | return 0; | |||
778 | std::unique_ptr<ProfileSummary> PS(Builder.getSummary()); | |||
779 | OS << "Instrumentation level: " | |||
780 | << (Reader->isIRLevelProfile() ? "IR" : "Front-end") << "\n"; | |||
781 | if (ShowAllFunctions || !ShowFunction.empty()) | |||
782 | OS << "Functions shown: " << ShownFunctions << "\n"; | |||
783 | OS << "Total functions: " << PS->getNumFunctions() << "\n"; | |||
784 | OS << "Maximum function count: " << PS->getMaxFunctionCount() << "\n"; | |||
785 | OS << "Maximum internal block count: " << PS->getMaxInternalCount() << "\n"; | |||
786 | ||||
787 | if (TopN) { | |||
788 | std::vector<std::pair<std::string, uint64_t>> SortedHottestFuncs; | |||
789 | while (!HottestFuncs.empty()) { | |||
790 | SortedHottestFuncs.emplace_back(HottestFuncs.top()); | |||
791 | HottestFuncs.pop(); | |||
792 | } | |||
793 | OS << "Top " << TopN | |||
794 | << " functions with the largest internal block counts: \n"; | |||
795 | for (auto &hotfunc : llvm::reverse(SortedHottestFuncs)) | |||
796 | OS << " " << hotfunc.first << ", max count = " << hotfunc.second << "\n"; | |||
797 | } | |||
798 | ||||
799 | if (ShownFunctions && ShowIndirectCallTargets) { | |||
800 | OS << "Statistics for indirect call sites profile:\n"; | |||
801 | showValueSitesStats(OS, IPVK_IndirectCallTarget, | |||
802 | VPStats[IPVK_IndirectCallTarget]); | |||
803 | } | |||
804 | ||||
805 | if (ShownFunctions && ShowMemOPSizes) { | |||
806 | OS << "Statistics for memory intrinsic calls sizes profile:\n"; | |||
807 | showValueSitesStats(OS, IPVK_MemOPSize, VPStats[IPVK_MemOPSize]); | |||
808 | } | |||
809 | ||||
810 | if (ShowDetailedSummary) { | |||
811 | OS << "Detailed summary:\n"; | |||
812 | OS << "Total number of blocks: " << PS->getNumCounts() << "\n"; | |||
813 | OS << "Total count: " << PS->getTotalCount() << "\n"; | |||
814 | for (auto Entry : PS->getDetailedSummary()) { | |||
815 | OS << Entry.NumCounts << " blocks with count >= " << Entry.MinCount | |||
816 | << " account for " | |||
817 | << format("%0.6g", (float)Entry.Cutoff / ProfileSummary::Scale * 100) | |||
818 | << " percentage of the total counts.\n"; | |||
819 | } | |||
820 | } | |||
821 | return 0; | |||
822 | } | |||
823 | ||||
824 | static int showSampleProfile(const std::string &Filename, bool ShowCounts, | |||
825 | bool ShowAllFunctions, | |||
826 | const std::string &ShowFunction, | |||
827 | raw_fd_ostream &OS) { | |||
828 | using namespace sampleprof; | |||
829 | LLVMContext Context; | |||
830 | auto ReaderOrErr = SampleProfileReader::create(Filename, Context); | |||
831 | if (std::error_code EC = ReaderOrErr.getError()) | |||
832 | exitWithErrorCode(EC, Filename); | |||
833 | ||||
834 | auto Reader = std::move(ReaderOrErr.get()); | |||
835 | if (std::error_code EC = Reader->read()) | |||
836 | exitWithErrorCode(EC, Filename); | |||
837 | ||||
838 | if (ShowAllFunctions || ShowFunction.empty()) | |||
839 | Reader->dump(OS); | |||
840 | else | |||
841 | Reader->dumpFunctionProfile(ShowFunction, OS); | |||
842 | ||||
843 | return 0; | |||
844 | } | |||
845 | ||||
846 | static int show_main(int argc, const char *argv[]) { | |||
847 | cl::opt<std::string> Filename(cl::Positional, cl::Required, | |||
848 | cl::desc("<profdata-file>")); | |||
849 | ||||
850 | cl::opt<bool> ShowCounts("counts", cl::init(false), | |||
851 | cl::desc("Show counter values for shown functions")); | |||
852 | cl::opt<bool> TextFormat( | |||
853 | "text", cl::init(false), | |||
854 | cl::desc("Show instr profile data in text dump format")); | |||
855 | cl::opt<bool> ShowIndirectCallTargets( | |||
856 | "ic-targets", cl::init(false), | |||
857 | cl::desc("Show indirect call site target values for shown functions")); | |||
858 | cl::opt<bool> ShowMemOPSizes( | |||
859 | "memop-sizes", cl::init(false), | |||
860 | cl::desc("Show the profiled sizes of the memory intrinsic calls " | |||
861 | "for shown functions")); | |||
862 | cl::opt<bool> ShowDetailedSummary("detailed-summary", cl::init(false), | |||
863 | cl::desc("Show detailed profile summary")); | |||
864 | cl::list<uint32_t> DetailedSummaryCutoffs( | |||
865 | cl::CommaSeparated, "detailed-summary-cutoffs", | |||
866 | cl::desc( | |||
867 | "Cutoff percentages (times 10000) for generating detailed summary"), | |||
868 | cl::value_desc("800000,901000,999999")); | |||
869 | cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false), | |||
870 | cl::desc("Details for every function")); | |||
871 | cl::opt<std::string> ShowFunction("function", | |||
872 | cl::desc("Details for matching functions")); | |||
873 | ||||
874 | cl::opt<std::string> OutputFilename("output", cl::value_desc("output"), | |||
875 | cl::init("-"), cl::desc("Output file")); | |||
876 | cl::alias OutputFilenameA("o", cl::desc("Alias for --output"), | |||
877 | cl::aliasopt(OutputFilename)); | |||
878 | cl::opt<ProfileKinds> ProfileKind( | |||
879 | cl::desc("Profile kind:"), cl::init(instr), | |||
880 | cl::values(clEnumVal(instr, "Instrumentation profile (default)")llvm::cl::OptionEnumValue { "instr", int(instr), "Instrumentation profile (default)" }, | |||
881 | clEnumVal(sample, "Sample profile")llvm::cl::OptionEnumValue { "sample", int(sample), "Sample profile" })); | |||
882 | cl::opt<uint32_t> TopNFunctions( | |||
883 | "topn", cl::init(0), | |||
884 | cl::desc("Show the list of functions with the largest internal counts")); | |||
885 | ||||
886 | cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n"); | |||
887 | ||||
888 | if (OutputFilename.empty()) | |||
889 | OutputFilename = "-"; | |||
890 | ||||
891 | std::error_code EC; | |||
892 | raw_fd_ostream OS(OutputFilename.data(), EC, sys::fs::F_Text); | |||
893 | if (EC) | |||
894 | exitWithErrorCode(EC, OutputFilename); | |||
895 | ||||
896 | if (ShowAllFunctions && !ShowFunction.empty()) | |||
897 | WithColor::warning() << "-function argument ignored: showing all functions\n"; | |||
898 | ||||
899 | std::vector<uint32_t> Cutoffs(DetailedSummaryCutoffs.begin(), | |||
900 | DetailedSummaryCutoffs.end()); | |||
901 | if (ProfileKind == instr) | |||
902 | return showInstrProfile(Filename, ShowCounts, TopNFunctions, | |||
903 | ShowIndirectCallTargets, ShowMemOPSizes, | |||
904 | ShowDetailedSummary, DetailedSummaryCutoffs, | |||
905 | ShowAllFunctions, ShowFunction, TextFormat, OS); | |||
906 | else | |||
907 | return showSampleProfile(Filename, ShowCounts, ShowAllFunctions, | |||
908 | ShowFunction, OS); | |||
909 | } | |||
910 | ||||
911 | int main(int argc, const char *argv[]) { | |||
912 | InitLLVM X(argc, argv); | |||
913 | ||||
914 | StringRef ProgName(sys::path::filename(argv[0])); | |||
915 | if (argc > 1) { | |||
| ||||
916 | int (*func)(int, const char *[]) = nullptr; | |||
917 | ||||
918 | if (strcmp(argv[1], "merge") == 0) | |||
919 | func = merge_main; | |||
920 | else if (strcmp(argv[1], "show") == 0) | |||
921 | func = show_main; | |||
922 | ||||
923 | if (func) { | |||
924 | std::string Invocation(ProgName.str() + " " + argv[1]); | |||
925 | argv[1] = Invocation.c_str(); | |||
926 | return func(argc - 1, argv + 1); | |||
927 | } | |||
928 | ||||
929 | if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-help") == 0 || | |||
930 | strcmp(argv[1], "--help") == 0) { | |||
931 | ||||
932 | errs() << "OVERVIEW: LLVM profile data tools\n\n" | |||
933 | << "USAGE: " << ProgName << " <command> [args...]\n" | |||
934 | << "USAGE: " << ProgName << " <command> -help\n\n" | |||
935 | << "See each individual command --help for more details.\n" | |||
936 | << "Available commands: merge, show\n"; | |||
937 | return 0; | |||
938 | } | |||
939 | } | |||
940 | ||||
941 | if (argc < 2) | |||
942 | errs() << ProgName << ": No command specified!\n"; | |||
943 | else | |||
944 | errs() << ProgName << ": Unknown command!\n"; | |||
945 | ||||
946 | errs() << "USAGE: " << ProgName << " <merge|show> [args...]\n"; | |||
947 | return 1; | |||
948 | } |
1 | // Core algorithmic facilities -*- C++ -*- |
2 | |
3 | // Copyright (C) 2001-2016 Free Software Foundation, Inc. |
4 | // |
5 | // This file is part of the GNU ISO C++ Library. This library is free |
6 | // software; you can redistribute it and/or modify it under the |
7 | // terms of the GNU General Public License as published by the |
8 | // Free Software Foundation; either version 3, or (at your option) |
9 | // any later version. |
10 | |
11 | // This library is distributed in the hope that it will be useful, |
12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of |
13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
14 | // GNU General Public License for more details. |
15 | |
16 | // Under Section 7 of GPL version 3, you are granted additional |
17 | // permissions described in the GCC Runtime Library Exception, version |
18 | // 3.1, as published by the Free Software Foundation. |
19 | |
20 | // You should have received a copy of the GNU General Public License and |
21 | // a copy of the GCC Runtime Library Exception along with this program; |
22 | // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see |
23 | // <http://www.gnu.org/licenses/>. |
24 | |
25 | /* |
26 | * |
27 | * Copyright (c) 1994 |
28 | * Hewlett-Packard Company |
29 | * |
30 | * Permission to use, copy, modify, distribute and sell this software |
31 | * and its documentation for any purpose is hereby granted without fee, |
32 | * provided that the above copyright notice appear in all copies and |
33 | * that both that copyright notice and this permission notice appear |
34 | * in supporting documentation. Hewlett-Packard Company makes no |
35 | * representations about the suitability of this software for any |
36 | * purpose. It is provided "as is" without express or implied warranty. |
37 | * |
38 | * |
39 | * Copyright (c) 1996-1998 |
40 | * Silicon Graphics Computer Systems, Inc. |
41 | * |
42 | * Permission to use, copy, modify, distribute and sell this software |
43 | * and its documentation for any purpose is hereby granted without fee, |
44 | * provided that the above copyright notice appear in all copies and |
45 | * that both that copyright notice and this permission notice appear |
46 | * in supporting documentation. Silicon Graphics makes no |
47 | * representations about the suitability of this software for any |
48 | * purpose. It is provided "as is" without express or implied warranty. |
49 | */ |
50 | |
51 | /** @file bits/stl_algobase.h |
52 | * This is an internal header file, included by other library headers. |
53 | * Do not attempt to use it directly. @headername{algorithm} |
54 | */ |
55 | |
56 | #ifndef _STL_ALGOBASE_H1 |
57 | #define _STL_ALGOBASE_H1 1 |
58 | |
59 | #include <bits/c++config.h> |
60 | #include <bits/functexcept.h> |
61 | #include <bits/cpp_type_traits.h> |
62 | #include <ext/type_traits.h> |
63 | #include <ext/numeric_traits.h> |
64 | #include <bits/stl_pair.h> |
65 | #include <bits/stl_iterator_base_types.h> |
66 | #include <bits/stl_iterator_base_funcs.h> |
67 | #include <bits/stl_iterator.h> |
68 | #include <bits/concept_check.h> |
69 | #include <debug/debug.h> |
70 | #include <bits/move.h> // For std::swap and _GLIBCXX_MOVE |
71 | #include <bits/predefined_ops.h> |
72 | |
73 | namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default"))) |
74 | { |
75 | _GLIBCXX_BEGIN_NAMESPACE_VERSION |
76 | |
77 | #if __cplusplus201103L < 201103L |
78 | // See http://gcc.gnu.org/ml/libstdc++/2004-08/msg00167.html: in a |
79 | // nutshell, we are partially implementing the resolution of DR 187, |
80 | // when it's safe, i.e., the value_types are equal. |
81 | template<bool _BoolType> |
82 | struct __iter_swap |
83 | { |
84 | template<typename _ForwardIterator1, typename _ForwardIterator2> |
85 | static void |
86 | iter_swap(_ForwardIterator1 __a, _ForwardIterator2 __b) |
87 | { |
88 | typedef typename iterator_traits<_ForwardIterator1>::value_type |
89 | _ValueType1; |
90 | _ValueType1 __tmp = _GLIBCXX_MOVE(*__a)std::move(*__a); |
91 | *__a = _GLIBCXX_MOVE(*__b)std::move(*__b); |
92 | *__b = _GLIBCXX_MOVE(__tmp)std::move(__tmp); |
93 | } |
94 | }; |
95 | |
96 | template<> |
97 | struct __iter_swap<true> |
98 | { |
99 | template<typename _ForwardIterator1, typename _ForwardIterator2> |
100 | static void |
101 | iter_swap(_ForwardIterator1 __a, _ForwardIterator2 __b) |
102 | { |
103 | swap(*__a, *__b); |
104 | } |
105 | }; |
106 | #endif |
107 | |
108 | /** |
109 | * @brief Swaps the contents of two iterators. |
110 | * @ingroup mutating_algorithms |
111 | * @param __a An iterator. |
112 | * @param __b Another iterator. |
113 | * @return Nothing. |
114 | * |
115 | * This function swaps the values pointed to by two iterators, not the |
116 | * iterators themselves. |
117 | */ |
118 | template<typename _ForwardIterator1, typename _ForwardIterator2> |
119 | inline void |
120 | iter_swap(_ForwardIterator1 __a, _ForwardIterator2 __b) |
121 | { |
122 | // concept requirements |
123 | __glibcxx_function_requires(_Mutable_ForwardIteratorConcept< |
124 | _ForwardIterator1>) |
125 | __glibcxx_function_requires(_Mutable_ForwardIteratorConcept< |
126 | _ForwardIterator2>) |
127 | |
128 | #if __cplusplus201103L < 201103L |
129 | typedef typename iterator_traits<_ForwardIterator1>::value_type |
130 | _ValueType1; |
131 | typedef typename iterator_traits<_ForwardIterator2>::value_type |
132 | _ValueType2; |
133 | |
134 | __glibcxx_function_requires(_ConvertibleConcept<_ValueType1, |
135 | _ValueType2>) |
136 | __glibcxx_function_requires(_ConvertibleConcept<_ValueType2, |
137 | _ValueType1>) |
138 | |
139 | typedef typename iterator_traits<_ForwardIterator1>::reference |
140 | _ReferenceType1; |
141 | typedef typename iterator_traits<_ForwardIterator2>::reference |
142 | _ReferenceType2; |
143 | std::__iter_swap<__are_same<_ValueType1, _ValueType2>::__value |
144 | && __are_same<_ValueType1&, _ReferenceType1>::__value |
145 | && __are_same<_ValueType2&, _ReferenceType2>::__value>:: |
146 | iter_swap(__a, __b); |
147 | #else |
148 | swap(*__a, *__b); |
149 | #endif |
150 | } |
151 | |
152 | /** |
153 | * @brief Swap the elements of two sequences. |
154 | * @ingroup mutating_algorithms |
155 | * @param __first1 A forward iterator. |
156 | * @param __last1 A forward iterator. |
157 | * @param __first2 A forward iterator. |
158 | * @return An iterator equal to @p first2+(last1-first1). |
159 | * |
160 | * Swaps each element in the range @p [first1,last1) with the |
161 | * corresponding element in the range @p [first2,(last1-first1)). |
162 | * The ranges must not overlap. |
163 | */ |
164 | template<typename _ForwardIterator1, typename _ForwardIterator2> |
165 | _ForwardIterator2 |
166 | swap_ranges(_ForwardIterator1 __first1, _ForwardIterator1 __last1, |
167 | _ForwardIterator2 __first2) |
168 | { |
169 | // concept requirements |
170 | __glibcxx_function_requires(_Mutable_ForwardIteratorConcept< |
171 | _ForwardIterator1>) |
172 | __glibcxx_function_requires(_Mutable_ForwardIteratorConcept< |
173 | _ForwardIterator2>) |
174 | __glibcxx_requires_valid_range(__first1, __last1); |
175 | |
176 | for (; __first1 != __last1; ++__first1, (void)++__first2) |
177 | std::iter_swap(__first1, __first2); |
178 | return __first2; |
179 | } |
180 | |
181 | /** |
182 | * @brief This does what you think it does. |
183 | * @ingroup sorting_algorithms |
184 | * @param __a A thing of arbitrary type. |
185 | * @param __b Another thing of arbitrary type. |
186 | * @return The lesser of the parameters. |
187 | * |
188 | * This is the simple classic generic implementation. It will work on |
189 | * temporary expressions, since they are only evaluated once, unlike a |
190 | * preprocessor macro. |
191 | */ |
192 | template<typename _Tp> |
193 | _GLIBCXX14_CONSTEXPR |
194 | inline const _Tp& |
195 | min(const _Tp& __a, const _Tp& __b) |
196 | { |
197 | // concept requirements |
198 | __glibcxx_function_requires(_LessThanComparableConcept<_Tp>) |
199 | //return __b < __a ? __b : __a; |
200 | if (__b < __a) |
201 | return __b; |
202 | return __a; |
203 | } |
204 | |
205 | /** |
206 | * @brief This does what you think it does. |
207 | * @ingroup sorting_algorithms |
208 | * @param __a A thing of arbitrary type. |
209 | * @param __b Another thing of arbitrary type. |
210 | * @return The greater of the parameters. |
211 | * |
212 | * This is the simple classic generic implementation. It will work on |
213 | * temporary expressions, since they are only evaluated once, unlike a |
214 | * preprocessor macro. |
215 | */ |
216 | template<typename _Tp> |
217 | _GLIBCXX14_CONSTEXPR |
218 | inline const _Tp& |
219 | max(const _Tp& __a, const _Tp& __b) |
220 | { |
221 | // concept requirements |
222 | __glibcxx_function_requires(_LessThanComparableConcept<_Tp>) |
223 | //return __a < __b ? __b : __a; |
224 | if (__a < __b) |
225 | return __b; |
226 | return __a; |
227 | } |
228 | |
229 | /** |
230 | * @brief This does what you think it does. |
231 | * @ingroup sorting_algorithms |
232 | * @param __a A thing of arbitrary type. |
233 | * @param __b Another thing of arbitrary type. |
234 | * @param __comp A @link comparison_functors comparison functor@endlink. |
235 | * @return The lesser of the parameters. |
236 | * |
237 | * This will work on temporary expressions, since they are only evaluated |
238 | * once, unlike a preprocessor macro. |
239 | */ |
240 | template<typename _Tp, typename _Compare> |
241 | _GLIBCXX14_CONSTEXPR |
242 | inline const _Tp& |
243 | min(const _Tp& __a, const _Tp& __b, _Compare __comp) |
244 | { |
245 | //return __comp(__b, __a) ? __b : __a; |
246 | if (__comp(__b, __a)) |
247 | return __b; |
248 | return __a; |
249 | } |
250 | |
251 | /** |
252 | * @brief This does what you think it does. |
253 | * @ingroup sorting_algorithms |
254 | * @param __a A thing of arbitrary type. |
255 | * @param __b Another thing of arbitrary type. |
256 | * @param __comp A @link comparison_functors comparison functor@endlink. |
257 | * @return The greater of the parameters. |
258 | * |
259 | * This will work on temporary expressions, since they are only evaluated |
260 | * once, unlike a preprocessor macro. |
261 | */ |
262 | template<typename _Tp, typename _Compare> |
263 | _GLIBCXX14_CONSTEXPR |
264 | inline const _Tp& |
265 | max(const _Tp& __a, const _Tp& __b, _Compare __comp) |
266 | { |
267 | //return __comp(__a, __b) ? __b : __a; |
268 | if (__comp(__a, __b)) |
269 | return __b; |
270 | return __a; |
271 | } |
272 | |
273 | // Fallback implementation of the function in bits/stl_iterator.h used to |
274 | // remove the __normal_iterator wrapper. See copy, fill, ... |
275 | template<typename _Iterator> |
276 | inline _Iterator |
277 | __niter_base(_Iterator __it) |
278 | { return __it; } |
279 | |
280 | // All of these auxiliary structs serve two purposes. (1) Replace |
281 | // calls to copy with memmove whenever possible. (Memmove, not memcpy, |
282 | // because the input and output ranges are permitted to overlap.) |
283 | // (2) If we're using random access iterators, then write the loop as |
284 | // a for loop with an explicit count. |
285 | |
286 | template<bool, bool, typename> |
287 | struct __copy_move |
288 | { |
289 | template<typename _II, typename _OI> |
290 | static _OI |
291 | __copy_m(_II __first, _II __last, _OI __result) |
292 | { |
293 | for (; __first != __last; ++__result, (void)++__first) |
294 | *__result = *__first; |
295 | return __result; |
296 | } |
297 | }; |
298 | |
299 | #if __cplusplus201103L >= 201103L |
300 | template<typename _Category> |
301 | struct __copy_move<true, false, _Category> |
302 | { |
303 | template<typename _II, typename _OI> |
304 | static _OI |
305 | __copy_m(_II __first, _II __last, _OI __result) |
306 | { |
307 | for (; __first != __last; ++__result, (void)++__first) |
308 | *__result = std::move(*__first); |
309 | return __result; |
310 | } |
311 | }; |
312 | #endif |
313 | |
314 | template<> |
315 | struct __copy_move<false, false, random_access_iterator_tag> |
316 | { |
317 | template<typename _II, typename _OI> |
318 | static _OI |
319 | __copy_m(_II __first, _II __last, _OI __result) |
320 | { |
321 | typedef typename iterator_traits<_II>::difference_type _Distance; |
322 | for(_Distance __n = __last - __first; __n > 0; --__n) |
323 | { |
324 | *__result = *__first; |
325 | ++__first; |
326 | ++__result; |
327 | } |
328 | return __result; |
329 | } |
330 | }; |
331 | |
332 | #if __cplusplus201103L >= 201103L |
333 | template<> |
334 | struct __copy_move<true, false, random_access_iterator_tag> |
335 | { |
336 | template<typename _II, typename _OI> |
337 | static _OI |
338 | __copy_m(_II __first, _II __last, _OI __result) |
339 | { |
340 | typedef typename iterator_traits<_II>::difference_type _Distance; |
341 | for(_Distance __n = __last - __first; __n > 0; --__n) |
342 | { |
343 | *__result = std::move(*__first); |
344 | ++__first; |
345 | ++__result; |
346 | } |
347 | return __result; |
348 | } |
349 | }; |
350 | #endif |
351 | |
352 | template<bool _IsMove> |
353 | struct __copy_move<_IsMove, true, random_access_iterator_tag> |
354 | { |
355 | template<typename _Tp> |
356 | static _Tp* |
357 | __copy_m(const _Tp* __first, const _Tp* __last, _Tp* __result) |
358 | { |
359 | #if __cplusplus201103L >= 201103L |
360 | using __assignable = conditional<_IsMove, |
361 | is_move_assignable<_Tp>, |
362 | is_copy_assignable<_Tp>>; |
363 | // trivial types can have deleted assignment |
364 | static_assert( __assignable::type::value, "type is not assignable" ); |
365 | #endif |
366 | const ptrdiff_t _Num = __last - __first; |
367 | if (_Num) |
368 | __builtin_memmove(__result, __first, sizeof(_Tp) * _Num); |
369 | return __result + _Num; |
370 | } |
371 | }; |
372 | |
373 | template<bool _IsMove, typename _II, typename _OI> |
374 | inline _OI |
375 | __copy_move_a(_II __first, _II __last, _OI __result) |
376 | { |
377 | typedef typename iterator_traits<_II>::value_type _ValueTypeI; |
378 | typedef typename iterator_traits<_OI>::value_type _ValueTypeO; |
379 | typedef typename iterator_traits<_II>::iterator_category _Category; |
380 | const bool __simple = (__is_trivial(_ValueTypeI) |
381 | && __is_pointer<_II>::__value |
382 | && __is_pointer<_OI>::__value |
383 | && __are_same<_ValueTypeI, _ValueTypeO>::__value); |
384 | |
385 | return std::__copy_move<_IsMove, __simple, |
386 | _Category>::__copy_m(__first, __last, __result); |
387 | } |
388 | |
389 | // Helpers for streambuf iterators (either istream or ostream). |
390 | // NB: avoid including <iosfwd>, relatively large. |
391 | template<typename _CharT> |
392 | struct char_traits; |
393 | |
394 | template<typename _CharT, typename _Traits> |
395 | class istreambuf_iterator; |
396 | |
397 | template<typename _CharT, typename _Traits> |
398 | class ostreambuf_iterator; |
399 | |
400 | template<bool _IsMove, typename _CharT> |
401 | typename __gnu_cxx::__enable_if<__is_char<_CharT>::__value, |
402 | ostreambuf_iterator<_CharT, char_traits<_CharT> > >::__type |
403 | __copy_move_a2(_CharT*, _CharT*, |
404 | ostreambuf_iterator<_CharT, char_traits<_CharT> >); |
405 | |
406 | template<bool _IsMove, typename _CharT> |
407 | typename __gnu_cxx::__enable_if<__is_char<_CharT>::__value, |
408 | ostreambuf_iterator<_CharT, char_traits<_CharT> > >::__type |
409 | __copy_move_a2(const _CharT*, const _CharT*, |
410 | ostreambuf_iterator<_CharT, char_traits<_CharT> >); |
411 | |
412 | template<bool _IsMove, typename _CharT> |
413 | typename __gnu_cxx::__enable_if<__is_char<_CharT>::__value, |
414 | _CharT*>::__type |
415 | __copy_move_a2(istreambuf_iterator<_CharT, char_traits<_CharT> >, |
416 | istreambuf_iterator<_CharT, char_traits<_CharT> >, _CharT*); |
417 | |
418 | template<bool _IsMove, typename _II, typename _OI> |
419 | inline _OI |
420 | __copy_move_a2(_II __first, _II __last, _OI __result) |
421 | { |
422 | return _OI(std::__copy_move_a<_IsMove>(std::__niter_base(__first), |
423 | std::__niter_base(__last), |
424 | std::__niter_base(__result))); |
425 | } |
426 | |
427 | /** |
428 | * @brief Copies the range [first,last) into result. |
429 | * @ingroup mutating_algorithms |
430 | * @param __first An input iterator. |
431 | * @param __last An input iterator. |
432 | * @param __result An output iterator. |
433 | * @return result + (first - last) |
434 | * |
435 | * This inline function will boil down to a call to @c memmove whenever |
436 | * possible. Failing that, if random access iterators are passed, then the |
437 | * loop count will be known (and therefore a candidate for compiler |
438 | * optimizations such as unrolling). Result may not be contained within |
439 | * [first,last); the copy_backward function should be used instead. |
440 | * |
441 | * Note that the end of the output range is permitted to be contained |
442 | * within [first,last). |
443 | */ |
444 | template<typename _II, typename _OI> |
445 | inline _OI |
446 | copy(_II __first, _II __last, _OI __result) |
447 | { |
448 | // concept requirements |
449 | __glibcxx_function_requires(_InputIteratorConcept<_II>) |
450 | __glibcxx_function_requires(_OutputIteratorConcept<_OI, |
451 | typename iterator_traits<_II>::value_type>) |
452 | __glibcxx_requires_valid_range(__first, __last); |
453 | |
454 | return (std::__copy_move_a2<__is_move_iterator<_II>::__value> |
455 | (std::__miter_base(__first), std::__miter_base(__last), |
456 | __result)); |
457 | } |
458 | |
459 | #if __cplusplus201103L >= 201103L |
460 | /** |
461 | * @brief Moves the range [first,last) into result. |
462 | * @ingroup mutating_algorithms |
463 | * @param __first An input iterator. |
464 | * @param __last An input iterator. |
465 | * @param __result An output iterator. |
466 | * @return result + (first - last) |
467 | * |
468 | * This inline function will boil down to a call to @c memmove whenever |
469 | * possible. Failing that, if random access iterators are passed, then the |
470 | * loop count will be known (and therefore a candidate for compiler |
471 | * optimizations such as unrolling). Result may not be contained within |
472 | * [first,last); the move_backward function should be used instead. |
473 | * |
474 | * Note that the end of the output range is permitted to be contained |
475 | * within [first,last). |
476 | */ |
477 | template<typename _II, typename _OI> |
478 | inline _OI |
479 | move(_II __first, _II __last, _OI __result) |
480 | { |
481 | // concept requirements |
482 | __glibcxx_function_requires(_InputIteratorConcept<_II>) |
483 | __glibcxx_function_requires(_OutputIteratorConcept<_OI, |
484 | typename iterator_traits<_II>::value_type>) |
485 | __glibcxx_requires_valid_range(__first, __last); |
486 | |
487 | return std::__copy_move_a2<true>(std::__miter_base(__first), |
488 | std::__miter_base(__last), __result); |
489 | } |
490 | |
491 | #define _GLIBCXX_MOVE3(_Tp, _Up, _Vp)std::move(_Tp, _Up, _Vp) std::move(_Tp, _Up, _Vp) |
492 | #else |
493 | #define _GLIBCXX_MOVE3(_Tp, _Up, _Vp)std::move(_Tp, _Up, _Vp) std::copy(_Tp, _Up, _Vp) |
494 | #endif |
495 | |
496 | template<bool, bool, typename> |
497 | struct __copy_move_backward |
498 | { |
499 | template<typename _BI1, typename _BI2> |
500 | static _BI2 |
501 | __copy_move_b(_BI1 __first, _BI1 __last, _BI2 __result) |
502 | { |
503 | while (__first != __last) |
504 | *--__result = *--__last; |
505 | return __result; |
506 | } |
507 | }; |
508 | |
509 | #if __cplusplus201103L >= 201103L |
510 | template<typename _Category> |
511 | struct __copy_move_backward<true, false, _Category> |
512 | { |
513 | template<typename _BI1, typename _BI2> |
514 | static _BI2 |
515 | __copy_move_b(_BI1 __first, _BI1 __last, _BI2 __result) |
516 | { |
517 | while (__first != __last) |
518 | *--__result = std::move(*--__last); |
519 | return __result; |
520 | } |
521 | }; |
522 | #endif |
523 | |
524 | template<> |
525 | struct __copy_move_backward<false, false, random_access_iterator_tag> |
526 | { |
527 | template<typename _BI1, typename _BI2> |
528 | static _BI2 |
529 | __copy_move_b(_BI1 __first, _BI1 __last, _BI2 __result) |
530 | { |
531 | typename iterator_traits<_BI1>::difference_type __n; |
532 | for (__n = __last - __first; __n > 0; --__n) |
533 | *--__result = *--__last; |
534 | return __result; |
535 | } |
536 | }; |
537 | |
538 | #if __cplusplus201103L >= 201103L |
539 | template<> |
540 | struct __copy_move_backward<true, false, random_access_iterator_tag> |
541 | { |
542 | template<typename _BI1, typename _BI2> |
543 | static _BI2 |
544 | __copy_move_b(_BI1 __first, _BI1 __last, _BI2 __result) |
545 | { |
546 | typename iterator_traits<_BI1>::difference_type __n; |
547 | for (__n = __last - __first; __n > 0; --__n) |
548 | *--__result = std::move(*--__last); |
549 | return __result; |
550 | } |
551 | }; |
552 | #endif |
553 | |
554 | template<bool _IsMove> |
555 | struct __copy_move_backward<_IsMove, true, random_access_iterator_tag> |
556 | { |
557 | template<typename _Tp> |
558 | static _Tp* |
559 | __copy_move_b(const _Tp* __first, const _Tp* __last, _Tp* __result) |
560 | { |
561 | #if __cplusplus201103L >= 201103L |
562 | using __assignable = conditional<_IsMove, |
563 | is_move_assignable<_Tp>, |
564 | is_copy_assignable<_Tp>>; |
565 | // trivial types can have deleted assignment |
566 | static_assert( __assignable::type::value, "type is not assignable" ); |
567 | #endif |
568 | const ptrdiff_t _Num = __last - __first; |
569 | if (_Num) |
570 | __builtin_memmove(__result - _Num, __first, sizeof(_Tp) * _Num); |
571 | return __result - _Num; |
572 | } |
573 | }; |
574 | |
575 | template<bool _IsMove, typename _BI1, typename _BI2> |
576 | inline _BI2 |
577 | __copy_move_backward_a(_BI1 __first, _BI1 __last, _BI2 __result) |
578 | { |
579 | typedef typename iterator_traits<_BI1>::value_type _ValueType1; |
580 | typedef typename iterator_traits<_BI2>::value_type _ValueType2; |
581 | typedef typename iterator_traits<_BI1>::iterator_category _Category; |
582 | const bool __simple = (__is_trivial(_ValueType1) |
583 | && __is_pointer<_BI1>::__value |
584 | && __is_pointer<_BI2>::__value |
585 | && __are_same<_ValueType1, _ValueType2>::__value); |
586 | |
587 | return std::__copy_move_backward<_IsMove, __simple, |
588 | _Category>::__copy_move_b(__first, |
589 | __last, |
590 | __result); |
591 | } |
592 | |
593 | template<bool _IsMove, typename _BI1, typename _BI2> |
594 | inline _BI2 |
595 | __copy_move_backward_a2(_BI1 __first, _BI1 __last, _BI2 __result) |
596 | { |
597 | return _BI2(std::__copy_move_backward_a<_IsMove> |
598 | (std::__niter_base(__first), std::__niter_base(__last), |
599 | std::__niter_base(__result))); |
600 | } |
601 | |
602 | /** |
603 | * @brief Copies the range [first,last) into result. |
604 | * @ingroup mutating_algorithms |
605 | * @param __first A bidirectional iterator. |
606 | * @param __last A bidirectional iterator. |
607 | * @param __result A bidirectional iterator. |
608 | * @return result - (first - last) |
609 | * |
610 | * The function has the same effect as copy, but starts at the end of the |
611 | * range and works its way to the start, returning the start of the result. |
612 | * This inline function will boil down to a call to @c memmove whenever |
613 | * possible. Failing that, if random access iterators are passed, then the |
614 | * loop count will be known (and therefore a candidate for compiler |
615 | * optimizations such as unrolling). |
616 | * |
617 | * Result may not be in the range (first,last]. Use copy instead. Note |
618 | * that the start of the output range may overlap [first,last). |
619 | */ |
620 | template<typename _BI1, typename _BI2> |
621 | inline _BI2 |
622 | copy_backward(_BI1 __first, _BI1 __last, _BI2 __result) |
623 | { |
624 | // concept requirements |
625 | __glibcxx_function_requires(_BidirectionalIteratorConcept<_BI1>) |
626 | __glibcxx_function_requires(_Mutable_BidirectionalIteratorConcept<_BI2>) |
627 | __glibcxx_function_requires(_ConvertibleConcept< |
628 | typename iterator_traits<_BI1>::value_type, |
629 | typename iterator_traits<_BI2>::value_type>) |
630 | __glibcxx_requires_valid_range(__first, __last); |
631 | |
632 | return (std::__copy_move_backward_a2<__is_move_iterator<_BI1>::__value> |
633 | (std::__miter_base(__first), std::__miter_base(__last), |
634 | __result)); |
635 | } |
636 | |
637 | #if __cplusplus201103L >= 201103L |
638 | /** |
639 | * @brief Moves the range [first,last) into result. |
640 | * @ingroup mutating_algorithms |
641 | * @param __first A bidirectional iterator. |
642 | * @param __last A bidirectional iterator. |
643 | * @param __result A bidirectional iterator. |
644 | * @return result - (first - last) |
645 | * |
646 | * The function has the same effect as move, but starts at the end of the |
647 | * range and works its way to the start, returning the start of the result. |
648 | * This inline function will boil down to a call to @c memmove whenever |
649 | * possible. Failing that, if random access iterators are passed, then the |
650 | * loop count will be known (and therefore a candidate for compiler |
651 | * optimizations such as unrolling). |
652 | * |
653 | * Result may not be in the range (first,last]. Use move instead. Note |
654 | * that the start of the output range may overlap [first,last). |
655 | */ |
656 | template<typename _BI1, typename _BI2> |
657 | inline _BI2 |
658 | move_backward(_BI1 __first, _BI1 __last, _BI2 __result) |
659 | { |
660 | // concept requirements |
661 | __glibcxx_function_requires(_BidirectionalIteratorConcept<_BI1>) |
662 | __glibcxx_function_requires(_Mutable_BidirectionalIteratorConcept<_BI2>) |
663 | __glibcxx_function_requires(_ConvertibleConcept< |
664 | typename iterator_traits<_BI1>::value_type, |
665 | typename iterator_traits<_BI2>::value_type>) |
666 | __glibcxx_requires_valid_range(__first, __last); |
667 | |
668 | return std::__copy_move_backward_a2<true>(std::__miter_base(__first), |
669 | std::__miter_base(__last), |
670 | __result); |
671 | } |
672 | |
673 | #define _GLIBCXX_MOVE_BACKWARD3(_Tp, _Up, _Vp)std::move_backward(_Tp, _Up, _Vp) std::move_backward(_Tp, _Up, _Vp) |
674 | #else |
675 | #define _GLIBCXX_MOVE_BACKWARD3(_Tp, _Up, _Vp)std::move_backward(_Tp, _Up, _Vp) std::copy_backward(_Tp, _Up, _Vp) |
676 | #endif |
677 | |
678 | template<typename _ForwardIterator, typename _Tp> |
679 | inline typename |
680 | __gnu_cxx::__enable_if<!__is_scalar<_Tp>::__value, void>::__type |
681 | __fill_a(_ForwardIterator __first, _ForwardIterator __last, |
682 | const _Tp& __value) |
683 | { |
684 | for (; __first != __last; ++__first) |
685 | *__first = __value; |
686 | } |
687 | |
688 | template<typename _ForwardIterator, typename _Tp> |
689 | inline typename |
690 | __gnu_cxx::__enable_if<__is_scalar<_Tp>::__value, void>::__type |
691 | __fill_a(_ForwardIterator __first, _ForwardIterator __last, |
692 | const _Tp& __value) |
693 | { |
694 | const _Tp __tmp = __value; |
695 | for (; __first != __last; ++__first) |
696 | *__first = __tmp; |
697 | } |
698 | |
699 | // Specialization: for char types we can use memset. |
700 | template<typename _Tp> |
701 | inline typename |
702 | __gnu_cxx::__enable_if<__is_byte<_Tp>::__value, void>::__type |
703 | __fill_a(_Tp* __first, _Tp* __last, const _Tp& __c) |
704 | { |
705 | const _Tp __tmp = __c; |
706 | if (const size_t __len = __last - __first) |
707 | __builtin_memset(__first, static_cast<unsigned char>(__tmp), __len); |
708 | } |
709 | |
710 | /** |
711 | * @brief Fills the range [first,last) with copies of value. |
712 | * @ingroup mutating_algorithms |
713 | * @param __first A forward iterator. |
714 | * @param __last A forward iterator. |
715 | * @param __value A reference-to-const of arbitrary type. |
716 | * @return Nothing. |
717 | * |
718 | * This function fills a range with copies of the same value. For char |
719 | * types filling contiguous areas of memory, this becomes an inline call |
720 | * to @c memset or @c wmemset. |
721 | */ |
722 | template<typename _ForwardIterator, typename _Tp> |
723 | inline void |
724 | fill(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value) |
725 | { |
726 | // concept requirements |
727 | __glibcxx_function_requires(_Mutable_ForwardIteratorConcept< |
728 | _ForwardIterator>) |
729 | __glibcxx_requires_valid_range(__first, __last); |
730 | |
731 | std::__fill_a(std::__niter_base(__first), std::__niter_base(__last), |
732 | __value); |
733 | } |
734 | |
735 | template<typename _OutputIterator, typename _Size, typename _Tp> |
736 | inline typename |
737 | __gnu_cxx::__enable_if<!__is_scalar<_Tp>::__value, _OutputIterator>::__type |
738 | __fill_n_a(_OutputIterator __first, _Size __n, const _Tp& __value) |
739 | { |
740 | for (__decltype(__n + 0) __niter = __n; |
741 | __niter > 0; --__niter, ++__first) |
742 | *__first = __value; |
743 | return __first; |
744 | } |
745 | |
746 | template<typename _OutputIterator, typename _Size, typename _Tp> |
747 | inline typename |
748 | __gnu_cxx::__enable_if<__is_scalar<_Tp>::__value, _OutputIterator>::__type |
749 | __fill_n_a(_OutputIterator __first, _Size __n, const _Tp& __value) |
750 | { |
751 | const _Tp __tmp = __value; |
752 | for (__decltype(__n + 0) __niter = __n; |
753 | __niter > 0; --__niter, ++__first) |
754 | *__first = __tmp; |
755 | return __first; |
756 | } |
757 | |
758 | template<typename _Size, typename _Tp> |
759 | inline typename |
760 | __gnu_cxx::__enable_if<__is_byte<_Tp>::__value, _Tp*>::__type |
761 | __fill_n_a(_Tp* __first, _Size __n, const _Tp& __c) |
762 | { |
763 | std::__fill_a(__first, __first + __n, __c); |
764 | return __first + __n; |
765 | } |
766 | |
767 | /** |
768 | * @brief Fills the range [first,first+n) with copies of value. |
769 | * @ingroup mutating_algorithms |
770 | * @param __first An output iterator. |
771 | * @param __n The count of copies to perform. |
772 | * @param __value A reference-to-const of arbitrary type. |
773 | * @return The iterator at first+n. |
774 | * |
775 | * This function fills a range with copies of the same value. For char |
776 | * types filling contiguous areas of memory, this becomes an inline call |
777 | * to @c memset or @ wmemset. |
778 | * |
779 | * _GLIBCXX_RESOLVE_LIB_DEFECTS |
780 | * DR 865. More algorithms that throw away information |
781 | */ |
782 | template<typename _OI, typename _Size, typename _Tp> |
783 | inline _OI |
784 | fill_n(_OI __first, _Size __n, const _Tp& __value) |
785 | { |
786 | // concept requirements |
787 | __glibcxx_function_requires(_OutputIteratorConcept<_OI, _Tp>) |
788 | |
789 | return _OI(std::__fill_n_a(std::__niter_base(__first), __n, __value)); |
790 | } |
791 | |
792 | template<bool _BoolType> |
793 | struct __equal |
794 | { |
795 | template<typename _II1, typename _II2> |
796 | static bool |
797 | equal(_II1 __first1, _II1 __last1, _II2 __first2) |
798 | { |
799 | for (; __first1 != __last1; ++__first1, (void)++__first2) |
800 | if (!(*__first1 == *__first2)) |
801 | return false; |
802 | return true; |
803 | } |
804 | }; |
805 | |
806 | template<> |
807 | struct __equal<true> |
808 | { |
809 | template<typename _Tp> |
810 | static bool |
811 | equal(const _Tp* __first1, const _Tp* __last1, const _Tp* __first2) |
812 | { |
813 | if (const size_t __len = (__last1 - __first1)) |
814 | return !__builtin_memcmp(__first1, __first2, sizeof(_Tp) * __len); |
815 | return true; |
816 | } |
817 | }; |
818 | |
819 | template<typename _II1, typename _II2> |
820 | inline bool |
821 | __equal_aux(_II1 __first1, _II1 __last1, _II2 __first2) |
822 | { |
823 | typedef typename iterator_traits<_II1>::value_type _ValueType1; |
824 | typedef typename iterator_traits<_II2>::value_type _ValueType2; |
825 | const bool __simple = ((__is_integer<_ValueType1>::__value |
826 | || __is_pointer<_ValueType1>::__value) |
827 | && __is_pointer<_II1>::__value |
828 | && __is_pointer<_II2>::__value |
829 | && __are_same<_ValueType1, _ValueType2>::__value); |
830 | |
831 | return std::__equal<__simple>::equal(__first1, __last1, __first2); |
832 | } |
833 | |
834 | template<typename, typename> |
835 | struct __lc_rai |
836 | { |
837 | template<typename _II1, typename _II2> |
838 | static _II1 |
839 | __newlast1(_II1, _II1 __last1, _II2, _II2) |
840 | { return __last1; } |
841 | |
842 | template<typename _II> |
843 | static bool |
844 | __cnd2(_II __first, _II __last) |
845 | { return __first != __last; } |
846 | }; |
847 | |
848 | template<> |
849 | struct __lc_rai<random_access_iterator_tag, random_access_iterator_tag> |
850 | { |
851 | template<typename _RAI1, typename _RAI2> |
852 | static _RAI1 |
853 | __newlast1(_RAI1 __first1, _RAI1 __last1, |
854 | _RAI2 __first2, _RAI2 __last2) |
855 | { |
856 | const typename iterator_traits<_RAI1>::difference_type |
857 | __diff1 = __last1 - __first1; |
858 | const typename iterator_traits<_RAI2>::difference_type |
859 | __diff2 = __last2 - __first2; |
860 | return __diff2 < __diff1 ? __first1 + __diff2 : __last1; |
861 | } |
862 | |
863 | template<typename _RAI> |
864 | static bool |
865 | __cnd2(_RAI, _RAI) |
866 | { return true; } |
867 | }; |
868 | |
869 | template<typename _II1, typename _II2, typename _Compare> |
870 | bool |
871 | __lexicographical_compare_impl(_II1 __first1, _II1 __last1, |
872 | _II2 __first2, _II2 __last2, |
873 | _Compare __comp) |
874 | { |
875 | typedef typename iterator_traits<_II1>::iterator_category _Category1; |
876 | typedef typename iterator_traits<_II2>::iterator_category _Category2; |
877 | typedef std::__lc_rai<_Category1, _Category2> __rai_type; |
878 | |
879 | __last1 = __rai_type::__newlast1(__first1, __last1, __first2, __last2); |
880 | for (; __first1 != __last1 && __rai_type::__cnd2(__first2, __last2); |
881 | ++__first1, (void)++__first2) |
882 | { |
883 | if (__comp(__first1, __first2)) |
884 | return true; |
885 | if (__comp(__first2, __first1)) |
886 | return false; |
887 | } |
888 | return __first1 == __last1 && __first2 != __last2; |
889 | } |
890 | |
891 | template<bool _BoolType> |
892 | struct __lexicographical_compare |
893 | { |
894 | template<typename _II1, typename _II2> |
895 | static bool __lc(_II1, _II1, _II2, _II2); |
896 | }; |
897 | |
898 | template<bool _BoolType> |
899 | template<typename _II1, typename _II2> |
900 | bool |
901 | __lexicographical_compare<_BoolType>:: |
902 | __lc(_II1 __first1, _II1 __last1, _II2 __first2, _II2 __last2) |
903 | { |
904 | return std::__lexicographical_compare_impl(__first1, __last1, |
905 | __first2, __last2, |
906 | __gnu_cxx::__ops::__iter_less_iter()); |
907 | } |
908 | |
909 | template<> |
910 | struct __lexicographical_compare<true> |
911 | { |
912 | template<typename _Tp, typename _Up> |
913 | static bool |
914 | __lc(const _Tp* __first1, const _Tp* __last1, |
915 | const _Up* __first2, const _Up* __last2) |
916 | { |
917 | const size_t __len1 = __last1 - __first1; |
918 | const size_t __len2 = __last2 - __first2; |
919 | if (const size_t __len = std::min(__len1, __len2)) |
920 | if (int __result = __builtin_memcmp(__first1, __first2, __len)) |
921 | return __result < 0; |
922 | return __len1 < __len2; |
923 | } |
924 | }; |
925 | |
926 | template<typename _II1, typename _II2> |
927 | inline bool |
928 | __lexicographical_compare_aux(_II1 __first1, _II1 __last1, |
929 | _II2 __first2, _II2 __last2) |
930 | { |
931 | typedef typename iterator_traits<_II1>::value_type _ValueType1; |
932 | typedef typename iterator_traits<_II2>::value_type _ValueType2; |
933 | const bool __simple = |
934 | (__is_byte<_ValueType1>::__value && __is_byte<_ValueType2>::__value |
935 | && !__gnu_cxx::__numeric_traits<_ValueType1>::__is_signed |
936 | && !__gnu_cxx::__numeric_traits<_ValueType2>::__is_signed |
937 | && __is_pointer<_II1>::__value |
938 | && __is_pointer<_II2>::__value); |
939 | |
940 | return std::__lexicographical_compare<__simple>::__lc(__first1, __last1, |
941 | __first2, __last2); |
942 | } |
943 | |
944 | template<typename _ForwardIterator, typename _Tp, typename _Compare> |
945 | _ForwardIterator |
946 | __lower_bound(_ForwardIterator __first, _ForwardIterator __last, |
947 | const _Tp& __val, _Compare __comp) |
948 | { |
949 | typedef typename iterator_traits<_ForwardIterator>::difference_type |
950 | _DistanceType; |
951 | |
952 | _DistanceType __len = std::distance(__first, __last); |
953 | |
954 | while (__len > 0) |
955 | { |
956 | _DistanceType __half = __len >> 1; |
957 | _ForwardIterator __middle = __first; |
958 | std::advance(__middle, __half); |
959 | if (__comp(__middle, __val)) |
960 | { |
961 | __first = __middle; |
962 | ++__first; |
963 | __len = __len - __half - 1; |
964 | } |
965 | else |
966 | __len = __half; |
967 | } |
968 | return __first; |
969 | } |
970 | |
971 | /** |
972 | * @brief Finds the first position in which @a val could be inserted |
973 | * without changing the ordering. |
974 | * @param __first An iterator. |
975 | * @param __last Another iterator. |
976 | * @param __val The search term. |
977 | * @return An iterator pointing to the first element <em>not less |
978 | * than</em> @a val, or end() if every element is less than |
979 | * @a val. |
980 | * @ingroup binary_search_algorithms |
981 | */ |
982 | template<typename _ForwardIterator, typename _Tp> |
983 | inline _ForwardIterator |
984 | lower_bound(_ForwardIterator __first, _ForwardIterator __last, |
985 | const _Tp& __val) |
986 | { |
987 | // concept requirements |
988 | __glibcxx_function_requires(_ForwardIteratorConcept<_ForwardIterator>) |
989 | __glibcxx_function_requires(_LessThanOpConcept< |
990 | typename iterator_traits<_ForwardIterator>::value_type, _Tp>) |
991 | __glibcxx_requires_partitioned_lower(__first, __last, __val); |
992 | |
993 | return std::__lower_bound(__first, __last, __val, |
994 | __gnu_cxx::__ops::__iter_less_val()); |
995 | } |
996 | |
997 | /// This is a helper function for the sort routines and for random.tcc. |
998 | // Precondition: __n > 0. |
999 | inline _GLIBCXX_CONSTEXPRconstexpr int |
1000 | __lg(int __n) |
1001 | { return sizeof(int) * __CHAR_BIT__8 - 1 - __builtin_clz(__n); } |
1002 | |
1003 | inline _GLIBCXX_CONSTEXPRconstexpr unsigned |
1004 | __lg(unsigned __n) |
1005 | { return sizeof(int) * __CHAR_BIT__8 - 1 - __builtin_clz(__n); } |
1006 | |
1007 | inline _GLIBCXX_CONSTEXPRconstexpr long |
1008 | __lg(long __n) |
1009 | { return sizeof(long) * __CHAR_BIT__8 - 1 - __builtin_clzl(__n); } |
1010 | |
1011 | inline _GLIBCXX_CONSTEXPRconstexpr unsigned long |
1012 | __lg(unsigned long __n) |
1013 | { return sizeof(long) * __CHAR_BIT__8 - 1 - __builtin_clzl(__n); } |
1014 | |
1015 | inline _GLIBCXX_CONSTEXPRconstexpr long long |
1016 | __lg(long long __n) |
1017 | { return sizeof(long long) * __CHAR_BIT__8 - 1 - __builtin_clzll(__n); } |
1018 | |
1019 | inline _GLIBCXX_CONSTEXPRconstexpr unsigned long long |
1020 | __lg(unsigned long long __n) |
1021 | { return sizeof(long long) * __CHAR_BIT__8 - 1 - __builtin_clzll(__n); } |
1022 | |
1023 | _GLIBCXX_END_NAMESPACE_VERSION |
1024 | |
1025 | _GLIBCXX_BEGIN_NAMESPACE_ALGO |
1026 | |
1027 | /** |
1028 | * @brief Tests a range for element-wise equality. |
1029 | * @ingroup non_mutating_algorithms |
1030 | * @param __first1 An input iterator. |
1031 | * @param __last1 An input iterator. |
1032 | * @param __first2 An input iterator. |
1033 | * @return A boolean true or false. |
1034 | * |
1035 | * This compares the elements of two ranges using @c == and returns true or |
1036 | * false depending on whether all of the corresponding elements of the |
1037 | * ranges are equal. |
1038 | */ |
1039 | template<typename _II1, typename _II2> |
1040 | inline bool |
1041 | equal(_II1 __first1, _II1 __last1, _II2 __first2) |
1042 | { |
1043 | // concept requirements |
1044 | __glibcxx_function_requires(_InputIteratorConcept<_II1>) |
1045 | __glibcxx_function_requires(_InputIteratorConcept<_II2>) |
1046 | __glibcxx_function_requires(_EqualOpConcept< |
1047 | typename iterator_traits<_II1>::value_type, |
1048 | typename iterator_traits<_II2>::value_type>) |
1049 | __glibcxx_requires_valid_range(__first1, __last1); |
1050 | |
1051 | return std::__equal_aux(std::__niter_base(__first1), |
1052 | std::__niter_base(__last1), |
1053 | std::__niter_base(__first2)); |
1054 | } |
1055 | |
1056 | /** |
1057 | * @brief Tests a range for element-wise equality. |
1058 | * @ingroup non_mutating_algorithms |
1059 | * @param __first1 An input iterator. |
1060 | * @param __last1 An input iterator. |
1061 | * @param __first2 An input iterator. |
1062 | * @param __binary_pred A binary predicate @link functors |
1063 | * functor@endlink. |
1064 | * @return A boolean true or false. |
1065 | * |
1066 | * This compares the elements of two ranges using the binary_pred |
1067 | * parameter, and returns true or |
1068 | * false depending on whether all of the corresponding elements of the |
1069 | * ranges are equal. |
1070 | */ |
1071 | template<typename _IIter1, typename _IIter2, typename _BinaryPredicate> |
1072 | inline bool |
1073 | equal(_IIter1 __first1, _IIter1 __last1, |
1074 | _IIter2 __first2, _BinaryPredicate __binary_pred) |
1075 | { |
1076 | // concept requirements |
1077 | __glibcxx_function_requires(_InputIteratorConcept<_IIter1>) |
1078 | __glibcxx_function_requires(_InputIteratorConcept<_IIter2>) |
1079 | __glibcxx_requires_valid_range(__first1, __last1); |
1080 | |
1081 | for (; __first1 != __last1; ++__first1, (void)++__first2) |
1082 | if (!bool(__binary_pred(*__first1, *__first2))) |
1083 | return false; |
1084 | return true; |
1085 | } |
1086 | |
1087 | #if __cplusplus201103L > 201103L |
1088 | |
1089 | #define __cpp_lib_robust_nonmodifying_seq_ops 201304 |
1090 | |
1091 | /** |
1092 | * @brief Tests a range for element-wise equality. |
1093 | * @ingroup non_mutating_algorithms |
1094 | * @param __first1 An input iterator. |
1095 | * @param __last1 An input iterator. |
1096 | * @param __first2 An input iterator. |
1097 | * @param __last2 An input iterator. |
1098 | * @return A boolean true or false. |
1099 | * |
1100 | * This compares the elements of two ranges using @c == and returns true or |
1101 | * false depending on whether all of the corresponding elements of the |
1102 | * ranges are equal. |
1103 | */ |
1104 | template<typename _II1, typename _II2> |
1105 | inline bool |
1106 | equal(_II1 __first1, _II1 __last1, _II2 __first2, _II2 __last2) |
1107 | { |
1108 | // concept requirements |
1109 | __glibcxx_function_requires(_InputIteratorConcept<_II1>) |
1110 | __glibcxx_function_requires(_InputIteratorConcept<_II2>) |
1111 | __glibcxx_function_requires(_EqualOpConcept< |
1112 | typename iterator_traits<_II1>::value_type, |
1113 | typename iterator_traits<_II2>::value_type>) |
1114 | __glibcxx_requires_valid_range(__first1, __last1); |
1115 | __glibcxx_requires_valid_range(__first2, __last2); |
1116 | |
1117 | using _RATag = random_access_iterator_tag; |
1118 | using _Cat1 = typename iterator_traits<_II1>::iterator_category; |
1119 | using _Cat2 = typename iterator_traits<_II2>::iterator_category; |
1120 | using _RAIters = __and_<is_same<_Cat1, _RATag>, is_same<_Cat2, _RATag>>; |
1121 | if (_RAIters()) |
1122 | { |
1123 | auto __d1 = std::distance(__first1, __last1); |
1124 | auto __d2 = std::distance(__first2, __last2); |
1125 | if (__d1 != __d2) |
1126 | return false; |
1127 | return _GLIBCXX_STD_Astd::equal(__first1, __last1, __first2); |
1128 | } |
1129 | |
1130 | for (; __first1 != __last1 && __first2 != __last2; |
1131 | ++__first1, (void)++__first2) |
1132 | if (!(*__first1 == *__first2)) |
1133 | return false; |
1134 | return __first1 == __last1 && __first2 == __last2; |
1135 | } |
1136 | |
1137 | /** |
1138 | * @brief Tests a range for element-wise equality. |
1139 | * @ingroup non_mutating_algorithms |
1140 | * @param __first1 An input iterator. |
1141 | * @param __last1 An input iterator. |
1142 | * @param __first2 An input iterator. |
1143 | * @param __last2 An input iterator. |
1144 | * @param __binary_pred A binary predicate @link functors |
1145 | * functor@endlink. |
1146 | * @return A boolean true or false. |
1147 | * |
1148 | * This compares the elements of two ranges using the binary_pred |
1149 | * parameter, and returns true or |
1150 | * false depending on whether all of the corresponding elements of the |
1151 | * ranges are equal. |
1152 | */ |
1153 | template<typename _IIter1, typename _IIter2, typename _BinaryPredicate> |
1154 | inline bool |
1155 | equal(_IIter1 __first1, _IIter1 __last1, |
1156 | _IIter2 __first2, _IIter2 __last2, _BinaryPredicate __binary_pred) |
1157 | { |
1158 | // concept requirements |
1159 | __glibcxx_function_requires(_InputIteratorConcept<_IIter1>) |
1160 | __glibcxx_function_requires(_InputIteratorConcept<_IIter2>) |
1161 | __glibcxx_requires_valid_range(__first1, __last1); |
1162 | __glibcxx_requires_valid_range(__first2, __last2); |
1163 | |
1164 | using _RATag = random_access_iterator_tag; |
1165 | using _Cat1 = typename iterator_traits<_IIter1>::iterator_category; |
1166 | using _Cat2 = typename iterator_traits<_IIter2>::iterator_category; |
1167 | using _RAIters = __and_<is_same<_Cat1, _RATag>, is_same<_Cat2, _RATag>>; |
1168 | if (_RAIters()) |
1169 | { |
1170 | auto __d1 = std::distance(__first1, __last1); |
1171 | auto __d2 = std::distance(__first2, __last2); |
1172 | if (__d1 != __d2) |
1173 | return false; |
1174 | return _GLIBCXX_STD_Astd::equal(__first1, __last1, __first2, |
1175 | __binary_pred); |
1176 | } |
1177 | |
1178 | for (; __first1 != __last1 && __first2 != __last2; |
1179 | ++__first1, (void)++__first2) |
1180 | if (!bool(__binary_pred(*__first1, *__first2))) |
1181 | return false; |
1182 | return __first1 == __last1 && __first2 == __last2; |
1183 | } |
1184 | #endif |
1185 | |
1186 | /** |
1187 | * @brief Performs @b dictionary comparison on ranges. |
1188 | * @ingroup sorting_algorithms |
1189 | * @param __first1 An input iterator. |
1190 | * @param __last1 An input iterator. |
1191 | * @param __first2 An input iterator. |
1192 | * @param __last2 An input iterator. |
1193 | * @return A boolean true or false. |
1194 | * |
1195 | * <em>Returns true if the sequence of elements defined by the range |
1196 | * [first1,last1) is lexicographically less than the sequence of elements |
1197 | * defined by the range [first2,last2). Returns false otherwise.</em> |
1198 | * (Quoted from [25.3.8]/1.) If the iterators are all character pointers, |
1199 | * then this is an inline call to @c memcmp. |
1200 | */ |
1201 | template<typename _II1, typename _II2> |
1202 | inline bool |
1203 | lexicographical_compare(_II1 __first1, _II1 __last1, |
1204 | _II2 __first2, _II2 __last2) |
1205 | { |
1206 | #ifdef _GLIBCXX_CONCEPT_CHECKS |
1207 | // concept requirements |
1208 | typedef typename iterator_traits<_II1>::value_type _ValueType1; |
1209 | typedef typename iterator_traits<_II2>::value_type _ValueType2; |
1210 | #endif |
1211 | __glibcxx_function_requires(_InputIteratorConcept<_II1>) |
1212 | __glibcxx_function_requires(_InputIteratorConcept<_II2>) |
1213 | __glibcxx_function_requires(_LessThanOpConcept<_ValueType1, _ValueType2>) |
1214 | __glibcxx_function_requires(_LessThanOpConcept<_ValueType2, _ValueType1>) |
1215 | __glibcxx_requires_valid_range(__first1, __last1); |
1216 | __glibcxx_requires_valid_range(__first2, __last2); |
1217 | |
1218 | return std::__lexicographical_compare_aux(std::__niter_base(__first1), |
1219 | std::__niter_base(__last1), |
1220 | std::__niter_base(__first2), |
1221 | std::__niter_base(__last2)); |
1222 | } |
1223 | |
1224 | /** |
1225 | * @brief Performs @b dictionary comparison on ranges. |
1226 | * @ingroup sorting_algorithms |
1227 | * @param __first1 An input iterator. |
1228 | * @param __last1 An input iterator. |
1229 | * @param __first2 An input iterator. |
1230 | * @param __last2 An input iterator. |
1231 | * @param __comp A @link comparison_functors comparison functor@endlink. |
1232 | * @return A boolean true or false. |
1233 | * |
1234 | * The same as the four-parameter @c lexicographical_compare, but uses the |
1235 | * comp parameter instead of @c <. |
1236 | */ |
1237 | template<typename _II1, typename _II2, typename _Compare> |
1238 | inline bool |
1239 | lexicographical_compare(_II1 __first1, _II1 __last1, |
1240 | _II2 __first2, _II2 __last2, _Compare __comp) |
1241 | { |
1242 | // concept requirements |
1243 | __glibcxx_function_requires(_InputIteratorConcept<_II1>) |
1244 | __glibcxx_function_requires(_InputIteratorConcept<_II2>) |
1245 | __glibcxx_requires_valid_range(__first1, __last1); |
1246 | __glibcxx_requires_valid_range(__first2, __last2); |
1247 | |
1248 | return std::__lexicographical_compare_impl |
1249 | (__first1, __last1, __first2, __last2, |
1250 | __gnu_cxx::__ops::__iter_comp_iter(__comp)); |
1251 | } |
1252 | |
1253 | template<typename _InputIterator1, typename _InputIterator2, |
1254 | typename _BinaryPredicate> |
1255 | pair<_InputIterator1, _InputIterator2> |
1256 | __mismatch(_InputIterator1 __first1, _InputIterator1 __last1, |
1257 | _InputIterator2 __first2, _BinaryPredicate __binary_pred) |
1258 | { |
1259 | while (__first1 != __last1 && __binary_pred(__first1, __first2)) |
1260 | { |
1261 | ++__first1; |
1262 | ++__first2; |
1263 | } |
1264 | return pair<_InputIterator1, _InputIterator2>(__first1, __first2); |
1265 | } |
1266 | |
1267 | /** |
1268 | * @brief Finds the places in ranges which don't match. |
1269 | * @ingroup non_mutating_algorithms |
1270 | * @param __first1 An input iterator. |
1271 | * @param __last1 An input iterator. |
1272 | * @param __first2 An input iterator. |
1273 | * @return A pair of iterators pointing to the first mismatch. |
1274 | * |
1275 | * This compares the elements of two ranges using @c == and returns a pair |
1276 | * of iterators. The first iterator points into the first range, the |
1277 | * second iterator points into the second range, and the elements pointed |
1278 | * to by the iterators are not equal. |
1279 | */ |
1280 | template<typename _InputIterator1, typename _InputIterator2> |
1281 | inline pair<_InputIterator1, _InputIterator2> |
1282 | mismatch(_InputIterator1 __first1, _InputIterator1 __last1, |
1283 | _InputIterator2 __first2) |
1284 | { |
1285 | // concept requirements |
1286 | __glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>) |
1287 | __glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>) |
1288 | __glibcxx_function_requires(_EqualOpConcept< |
1289 | typename iterator_traits<_InputIterator1>::value_type, |
1290 | typename iterator_traits<_InputIterator2>::value_type>) |
1291 | __glibcxx_requires_valid_range(__first1, __last1); |
1292 | |
1293 | return _GLIBCXX_STD_Astd::__mismatch(__first1, __last1, __first2, |
1294 | __gnu_cxx::__ops::__iter_equal_to_iter()); |
1295 | } |
1296 | |
1297 | /** |
1298 | * @brief Finds the places in ranges which don't match. |
1299 | * @ingroup non_mutating_algorithms |
1300 | * @param __first1 An input iterator. |
1301 | * @param __last1 An input iterator. |
1302 | * @param __first2 An input iterator. |
1303 | * @param __binary_pred A binary predicate @link functors |
1304 | * functor@endlink. |
1305 | * @return A pair of iterators pointing to the first mismatch. |
1306 | * |
1307 | * This compares the elements of two ranges using the binary_pred |
1308 | * parameter, and returns a pair |
1309 | * of iterators. The first iterator points into the first range, the |
1310 | * second iterator points into the second range, and the elements pointed |
1311 | * to by the iterators are not equal. |
1312 | */ |
1313 | template<typename _InputIterator1, typename _InputIterator2, |
1314 | typename _BinaryPredicate> |
1315 | inline pair<_InputIterator1, _InputIterator2> |
1316 | mismatch(_InputIterator1 __first1, _InputIterator1 __last1, |
1317 | _InputIterator2 __first2, _BinaryPredicate __binary_pred) |
1318 | { |
1319 | // concept requirements |
1320 | __glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>) |
1321 | __glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>) |
1322 | __glibcxx_requires_valid_range(__first1, __last1); |
1323 | |
1324 | return _GLIBCXX_STD_Astd::__mismatch(__first1, __last1, __first2, |
1325 | __gnu_cxx::__ops::__iter_comp_iter(__binary_pred)); |
1326 | } |
1327 | |
1328 | #if __cplusplus201103L > 201103L |
1329 | |
1330 | template<typename _InputIterator1, typename _InputIterator2, |
1331 | typename _BinaryPredicate> |
1332 | pair<_InputIterator1, _InputIterator2> |
1333 | __mismatch(_InputIterator1 __first1, _InputIterator1 __last1, |
1334 | _InputIterator2 __first2, _InputIterator2 __last2, |
1335 | _BinaryPredicate __binary_pred) |
1336 | { |
1337 | while (__first1 != __last1 && __first2 != __last2 |
1338 | && __binary_pred(__first1, __first2)) |
1339 | { |
1340 | ++__first1; |
1341 | ++__first2; |
1342 | } |
1343 | return pair<_InputIterator1, _InputIterator2>(__first1, __first2); |
1344 | } |
1345 | |
1346 | /** |
1347 | * @brief Finds the places in ranges which don't match. |
1348 | * @ingroup non_mutating_algorithms |
1349 | * @param __first1 An input iterator. |
1350 | * @param __last1 An input iterator. |
1351 | * @param __first2 An input iterator. |
1352 | * @param __last2 An input iterator. |
1353 | * @return A pair of iterators pointing to the first mismatch. |
1354 | * |
1355 | * This compares the elements of two ranges using @c == and returns a pair |
1356 | * of iterators. The first iterator points into the first range, the |
1357 | * second iterator points into the second range, and the elements pointed |
1358 | * to by the iterators are not equal. |
1359 | */ |
1360 | template<typename _InputIterator1, typename _InputIterator2> |
1361 | inline pair<_InputIterator1, _InputIterator2> |
1362 | mismatch(_InputIterator1 __first1, _InputIterator1 __last1, |
1363 | _InputIterator2 __first2, _InputIterator2 __last2) |
1364 | { |
1365 | // concept requirements |
1366 | __glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>) |
1367 | __glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>) |
1368 | __glibcxx_function_requires(_EqualOpConcept< |
1369 | typename iterator_traits<_InputIterator1>::value_type, |
1370 | typename iterator_traits<_InputIterator2>::value_type>) |
1371 | __glibcxx_requires_valid_range(__first1, __last1); |
1372 | __glibcxx_requires_valid_range(__first2, __last2); |
1373 | |
1374 | return _GLIBCXX_STD_Astd::__mismatch(__first1, __last1, __first2, __last2, |
1375 | __gnu_cxx::__ops::__iter_equal_to_iter()); |
1376 | } |
1377 | |
1378 | /** |
1379 | * @brief Finds the places in ranges which don't match. |
1380 | * @ingroup non_mutating_algorithms |
1381 | * @param __first1 An input iterator. |
1382 | * @param __last1 An input iterator. |
1383 | * @param __first2 An input iterator. |
1384 | * @param __last2 An input iterator. |
1385 | * @param __binary_pred A binary predicate @link functors |
1386 | * functor@endlink. |
1387 | * @return A pair of iterators pointing to the first mismatch. |
1388 | * |
1389 | * This compares the elements of two ranges using the binary_pred |
1390 | * parameter, and returns a pair |
1391 | * of iterators. The first iterator points into the first range, the |
1392 | * second iterator points into the second range, and the elements pointed |
1393 | * to by the iterators are not equal. |
1394 | */ |
1395 | template<typename _InputIterator1, typename _InputIterator2, |
1396 | typename _BinaryPredicate> |
1397 | inline pair<_InputIterator1, _InputIterator2> |
1398 | mismatch(_InputIterator1 __first1, _InputIterator1 __last1, |
1399 | _InputIterator2 __first2, _InputIterator2 __last2, |
1400 | _BinaryPredicate __binary_pred) |
1401 | { |
1402 | // concept requirements |
1403 | __glibcxx_function_requires(_InputIteratorConcept<_InputIterator1>) |
1404 | __glibcxx_function_requires(_InputIteratorConcept<_InputIterator2>) |
1405 | __glibcxx_requires_valid_range(__first1, __last1); |
1406 | __glibcxx_requires_valid_range(__first2, __last2); |
1407 | |
1408 | return _GLIBCXX_STD_Astd::__mismatch(__first1, __last1, __first2, __last2, |
1409 | __gnu_cxx::__ops::__iter_comp_iter(__binary_pred)); |
1410 | } |
1411 | #endif |
1412 | |
1413 | _GLIBCXX_END_NAMESPACE_ALGO |
1414 | } // namespace std |
1415 | |
1416 | // NB: This file is included within many other C++ includes, as a way |
1417 | // of getting the base algorithms. So, make sure that parallel bits |
1418 | // come in too if requested. |
1419 | #ifdef _GLIBCXX_PARALLEL |
1420 | # include <parallel/algobase.h> |
1421 | #endif |
1422 | |
1423 | #endif |