source: icGREP/icgrep-devel/icgrep/grep_engine.cpp @ 5861

Last change on this file since 5861 was 5861, checked in by cameron, 16 months ago

Using DirectCC builder updates; speedup wc -l

File size: 20.9 KB
Line 
1/*
2 *  Copyright (c) 2017 International Characters.
3 *  This software is licensed to the public under the Open Software License 3.0.
4 *  icgrep is a trademark of International Characters.
5 */
6
7#include "grep_engine.h"
8#include "grep_interface.h"
9#include <llvm/IR/Module.h>
10#include <boost/filesystem.hpp>
11#include <UCD/resolve_properties.h>
12#include <kernels/charclasses.h>
13#include <kernels/cc_kernel.h>
14#include <kernels/grep_kernel.h>
15#include <kernels/linebreak_kernel.h>
16#include <kernels/streams_merge.h>
17#include <kernels/source_kernel.h>
18#include <kernels/s2p_kernel.h>
19#include <kernels/scanmatchgen.h>
20#include <kernels/streamset.h>
21#include <kernels/until_n.h>
22#include <kernels/kernel_builder.h>
23#include <pablo/pablo_kernel.h>
24#include <re/re_cc.h>
25#include <re/casing.h>
26#include <re/exclude_CC.h>
27#include <re/re_toolchain.h>
28#include <toolchain/toolchain.h>
29#include <re/re_name_resolve.h>
30#include <re/re_collect_unicodesets.h>
31#include <re/re_multiplex.h>
32#include <re/grapheme_clusters.h>
33#include <re/printer_re.h>
34#include <toolchain/toolchain.h>
35#include <toolchain/cpudriver.h>
36#include <iostream>
37#include <cc/multiplex_CCs.h>
38#include <llvm/Support/raw_ostream.h>
39#include <util/aligned_allocator.h>
40#include <sys/stat.h>
41#include <fcntl.h>
42#include <errno.h>
43#include <llvm/ADT/STLExtras.h> // for make_unique
44#include <llvm/Support/CommandLine.h>
45#include <llvm/Support/Debug.h>
46#include <sched.h>
47
48using namespace parabix;
49using namespace llvm;
50using namespace cc;
51using namespace kernel;
52
53static cl::opt<int> Threads("t", cl::desc("Total number of threads."), cl::init(2));
54static cl::opt<bool> PabloTransposition("enable-pablo-s2p", cl::desc("Enable experimental pablo transposition."));
55static cl::opt<bool> CC_Multiplexing("CC-multiplexing", cl::desc("Enable CC multiplexing."), cl::init(true));
56
57namespace grep {
58
59// Grep Engine construction and initialization.
60
61GrepEngine::GrepEngine() :
62    mGrepDriver(nullptr),
63    mNextFileToGrep(0),
64    mNextFileToPrint(0),
65    grepMatchFound(false),
66    mMoveMatchesToEOL(true),
67    mEngineThread(pthread_self()) {}
68
69GrepEngine::~GrepEngine() {
70    delete mGrepDriver;
71}
72
73QuietModeEngine::QuietModeEngine() : GrepEngine() {
74    mMoveMatchesToEOL = false;
75}
76
77MatchOnlyEngine::MatchOnlyEngine(bool showFilesWithoutMatch) :
78    GrepEngine(), mRequiredCount(showFilesWithoutMatch) {
79    mFileSuffix = NullFlag ? std::string("\0", 1) : "\n";
80    mMoveMatchesToEOL = false;
81}
82
83CountOnlyEngine::CountOnlyEngine() : GrepEngine() {
84    mFileSuffix = ":";
85}
86
87EmitMatchesEngine::EmitMatchesEngine() : GrepEngine() {
88    mFileSuffix = InitialTabFlag ? "\t:" : ":";
89    if (LineRegexpFlag) mMoveMatchesToEOL = false;
90}
91
92void GrepEngine::initFileResult(std::vector<std::string> & filenames) {
93    const unsigned n = filenames.size();
94    mResultStrs.resize(n);
95    mFileStatus.resize(n, FileStatus::Pending);
96    inputFiles = filenames;
97}
98
99// Code Generation
100//
101// All engines share a common pipeline to compute a stream of Matches from a given input Bytestream.
102
103unsigned LLVM_READNONE calculateMaxCountRate(const std::unique_ptr<kernel::KernelBuilder> & b) {
104    const unsigned packSize = b->getSizeTy()->getBitWidth();
105    return (packSize * packSize) / b->getBitBlockWidth();
106}
107
108std::pair<StreamSetBuffer *, StreamSetBuffer *> GrepEngine::grepPipeline(std::vector<re::RE *> & REs, StreamSetBuffer * ByteStream) {
109    auto & idb = mGrepDriver->getBuilder();
110    const unsigned segmentSize = codegen::SegmentSize;
111    const unsigned bufferSegments = codegen::BufferSegments * codegen::ThreadNum;
112    // TODO: until we automate stream buffer sizing, use this calculation to determine how large our matches buffer needs to be.
113    const unsigned baseBufferSize = segmentSize * (MaxCountFlag > 0 ? (std::max(bufferSegments, calculateMaxCountRate(idb))) : bufferSegments);
114    const unsigned encodingBits = 8;
115
116    StreamSetBuffer * LineFeedStream = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
117
118    #ifdef USE_DIRECT_LF_BUILDER
119    kernel::Kernel * linefeedK = mGrepDriver->addKernelInstance<kernel::LineFeedKernelBuilder>(idb, Binding{idb->getStreamSetTy(1, 8), "byteStream", FixedRate(), Principal()});
120    mGrepDriver->makeKernelCall(linefeedK, {ByteStream}, {LineFeedStream});
121    #endif
122
123    StreamSetBuffer * BasisBits = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(encodingBits, 1), baseBufferSize);
124    kernel::Kernel * s2pk = nullptr;
125    if (PabloTransposition) {
126        s2pk = mGrepDriver->addKernelInstance<kernel::S2P_PabloKernel>(idb);
127    }
128    else {
129        s2pk = mGrepDriver->addKernelInstance<kernel::S2PKernel>(idb);
130    }
131    mGrepDriver->makeKernelCall(s2pk, {ByteStream}, {BasisBits});
132
133    #ifndef USE_DIRECT_LF_BUILDER
134    kernel::Kernel * linefeedK = mGrepDriver->addKernelInstance<kernel::LineFeedKernelBuilder>(idb, Binding{idb->getStreamSetTy(8), "basis", FixedRate(), Principal()});
135    mGrepDriver->makeKernelCall(linefeedK, {BasisBits}, {LineFeedStream});
136    #endif
137
138    StreamSetBuffer * LineBreakStream = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
139    StreamSetBuffer * CRLFStream = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
140    kernel::Kernel * linebreakK = mGrepDriver->addKernelInstance<kernel::LineBreakKernelBuilder>(idb, encodingBits);
141    mGrepDriver->makeKernelCall(linebreakK, {BasisBits, LineFeedStream}, {LineBreakStream, CRLFStream});
142
143    kernel::Kernel * requiredStreamsK = mGrepDriver->addKernelInstance<kernel::RequiredStreams_UTF8>(idb);
144    StreamSetBuffer * RequiredStreams = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(3, 1), baseBufferSize);
145    mGrepDriver->makeKernelCall(requiredStreamsK, {BasisBits}, {RequiredStreams});
146
147    const auto n = REs.size();
148    std::vector<StreamSetBuffer *> MatchResultsBufs(n);
149    for(unsigned i = 0; i < n; ++i) {
150        REs[i] = resolveModesAndExternalSymbols(REs[i]);
151        REs[i] = excludeUnicodeLineBreak(REs[i]);
152        REs[i] = regular_expression_passes(REs[i]);
153        if (CC_Multiplexing) {
154            const auto UnicodeSets = re::collectUnicodeSets(REs[i]);
155            StreamSetBuffer * const MatchResults = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
156            if (UnicodeSets.size() <= 1) {
157                kernel::Kernel * icgrepK = mGrepDriver->addKernelInstance<kernel::ICGrepKernel>(idb, REs[i]);
158                mGrepDriver->makeKernelCall(icgrepK, {BasisBits, LineBreakStream, CRLFStream, RequiredStreams}, {MatchResults});
159                MatchResultsBufs[i] = MatchResults;
160            } else {
161                mpx = make_unique<MultiplexedAlphabet>("mpx", UnicodeSets);
162                REs[i] = transformCCs(mpx.get(), REs[i]);
163                std::vector<re::CC *> mpx_basis = mpx->getMultiplexedCCs();
164                auto numOfCharacterClasses = mpx_basis.size();
165                StreamSetBuffer * CharClasses = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(numOfCharacterClasses), baseBufferSize);
166                kernel::Kernel * ccK = mGrepDriver->addKernelInstance<kernel::CharClassesKernel>(idb, std::move(mpx_basis));
167                mGrepDriver->makeKernelCall(ccK, {BasisBits}, {CharClasses});
168//                kernel::Kernel * ccK = mGrepDriver->addKernelInstance<kernel::CharClassesKernel>(idb, std::move(mpx_basis), true);
169//                mGrepDriver->makeKernelCall(ccK, {ByteStream}, {CharClasses});
170                kernel::Kernel * icgrepK = mGrepDriver->addKernelInstance<kernel::ICGrepKernel>(idb, REs[i], std::vector<cc::Alphabet *>{mpx.get()});
171                mGrepDriver->makeKernelCall(icgrepK, {BasisBits, LineBreakStream, CRLFStream, RequiredStreams, CharClasses}, {MatchResults});
172                MatchResultsBufs[i] = MatchResults;
173            }
174        } else {
175            StreamSetBuffer * MatchResults = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
176            kernel::Kernel * icgrepK = mGrepDriver->addKernelInstance<kernel::ICGrepKernel>(idb, REs[i]);
177            mGrepDriver->makeKernelCall(icgrepK, {BasisBits, LineBreakStream, CRLFStream, RequiredStreams}, {MatchResults});
178            MatchResultsBufs[i] = MatchResults;
179        }
180    }
181    StreamSetBuffer * MergedResults = MatchResultsBufs[0];
182    if (REs.size() > 1) {
183        MergedResults = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
184        kernel::Kernel * streamsMergeK = mGrepDriver->addKernelInstance<kernel::StreamsMerge>(idb, 1, REs.size());
185        mGrepDriver->makeKernelCall(streamsMergeK, MatchResultsBufs, {MergedResults});
186    }
187    StreamSetBuffer * Matches = MergedResults;
188
189    if (mMoveMatchesToEOL) {
190        StreamSetBuffer * OriginalMatches = Matches;
191        kernel::Kernel * matchedLinesK = mGrepDriver->addKernelInstance<kernel::MatchedLinesKernel>(idb);
192        Matches = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
193        mGrepDriver->makeKernelCall(matchedLinesK, {OriginalMatches, LineBreakStream}, {Matches});
194    }
195
196    if (InvertMatchFlag) {
197        kernel::Kernel * invertK = mGrepDriver->addKernelInstance<kernel::InvertMatchesKernel>(idb);
198        StreamSetBuffer * OriginalMatches = Matches;
199        Matches = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
200        mGrepDriver->makeKernelCall(invertK, {OriginalMatches, LineBreakStream}, {Matches});
201    }
202    if (MaxCountFlag > 0) {
203        kernel::Kernel * untilK = mGrepDriver->addKernelInstance<kernel::UntilNkernel>(idb);
204        untilK->setInitialArguments({idb->getSize(MaxCountFlag)});
205        StreamSetBuffer * const AllMatches = Matches;
206        Matches = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
207        mGrepDriver->makeKernelCall(untilK, {AllMatches}, {Matches});
208    }
209    return std::pair<StreamSetBuffer *, StreamSetBuffer *>(LineBreakStream, Matches);
210}
211
212// The QuietMode, MatchOnly and CountOnly engines share a common code generation main function,
213// which returns a count of the matches found (possibly subject to a MaxCount).
214//
215
216void GrepEngine::grepCodeGen(std::vector<re::RE *> REs) {
217
218    assert (mGrepDriver == nullptr);
219    mGrepDriver = new ParabixDriver("engine");
220    auto & idb = mGrepDriver->getBuilder();
221    Module * M = idb->getModule();
222
223    const unsigned encodingBits = 8;
224
225    Function * mainFunc = cast<Function>(M->getOrInsertFunction("Main", idb->getInt64Ty(), idb->getInt32Ty(), nullptr));
226    mainFunc->setCallingConv(CallingConv::C);
227    idb->SetInsertPoint(BasicBlock::Create(M->getContext(), "entry", mainFunc, 0));
228    auto args = mainFunc->arg_begin();
229
230    Value * const fileDescriptor = &*(args++);
231    fileDescriptor->setName("fileDescriptor");
232
233    StreamSetBuffer * ByteStream = mGrepDriver->addBuffer<SourceBuffer>(idb, idb->getStreamSetTy(1, encodingBits));
234    kernel::Kernel * sourceK = mGrepDriver->addKernelInstance<kernel::FDSourceKernel>(idb);
235    sourceK->setInitialArguments({fileDescriptor});
236    mGrepDriver->makeKernelCall(sourceK, {}, {ByteStream});
237
238    StreamSetBuffer * LineBreakStream;
239    StreamSetBuffer * Matches;
240    std::tie(LineBreakStream, Matches) = grepPipeline(REs, ByteStream);
241
242    kernel::Kernel * matchCountK = mGrepDriver->addKernelInstance<kernel::PopcountKernel>(idb);
243    mGrepDriver->makeKernelCall(matchCountK, {Matches}, {});
244    mGrepDriver->generatePipelineIR();
245    idb->setKernel(matchCountK);
246    Value * matchedLineCount = idb->getAccumulator("countResult");
247    matchedLineCount = idb->CreateZExt(matchedLineCount, idb->getInt64Ty());
248    mGrepDriver->deallocateBuffers();
249    idb->CreateRet(matchedLineCount);
250    mGrepDriver->finalizeObject();
251}
252
253//
254// The EmitMatches engine uses an EmitMatchesAccumulator object to concatenate together
255// matched lines.
256
257class EmitMatch : public MatchAccumulator {
258    friend class EmitMatchesEngine;
259public:
260    EmitMatch(std::string linePrefix, std::ostringstream & strm) : mLinePrefix(linePrefix), mLineCount(0), mTerminated(true), mResultStr(strm) {}
261    void accumulate_match(const size_t lineNum, char * line_start, char * line_end) override;
262    void finalize_match(char * buffer_end) override;
263protected:
264    std::string mLinePrefix;
265    size_t mLineCount;
266    bool mTerminated;
267    std::ostringstream & mResultStr;
268};
269
270//
271//  Default Report Match:  lines are emitted with whatever line terminators are found in the
272//  input.  However, if the final line is not terminated, a new line is appended.
273//
274void EmitMatch::accumulate_match (const size_t lineNum, char * line_start, char * line_end) {
275    if (WithFilenameFlag) {
276        mResultStr << mLinePrefix;
277    }
278    if (LineNumberFlag) {
279        // Internally line numbers are counted from 0.  For display, adjust
280        // the line number so that lines are numbered from 1.
281        if (InitialTabFlag) {
282            mResultStr << lineNum+1 << "\t:";
283        }
284        else {
285            mResultStr << lineNum+1 << ":";
286        }
287    }
288    size_t bytes = line_end - line_start + 1;
289    mResultStr.write(line_start, bytes);
290    mLineCount++;
291    unsigned last_byte = *line_end;
292    mTerminated = (last_byte >= 0x0A) && (last_byte <= 0x0D);
293    if (LLVM_UNLIKELY(!mTerminated)) {
294        if (last_byte == 0x85) {  //  Possible NEL terminator.
295            mTerminated = (bytes >= 2) && (static_cast<unsigned>(line_end[-1]) == 0xC2);
296        }
297        else {
298            // Possible LS or PS terminators.
299            mTerminated = (bytes >= 3) && (static_cast<unsigned>(line_end[-2]) == 0xE2)
300                                       && (static_cast<unsigned>(line_end[-1]) == 0x80)
301                                       && ((last_byte == 0xA8) || (last_byte == 0xA9));
302        }
303    }
304}
305
306void EmitMatch::finalize_match(char * buffer_end) {
307    if (!mTerminated) mResultStr << "\n";
308}
309
310void EmitMatchesEngine::grepCodeGen(std::vector<re::RE *> REs) {
311    assert (mGrepDriver == nullptr);
312    mGrepDriver = new ParabixDriver("engine");
313    auto & idb = mGrepDriver->getBuilder();
314    Module * M = idb->getModule();
315
316    const unsigned encodingBits = 8;
317
318    Function * mainFunc = cast<Function>(M->getOrInsertFunction("Main", idb->getInt64Ty(), idb->getInt32Ty(), idb->getIntAddrTy(), nullptr));
319    mainFunc->setCallingConv(CallingConv::C);
320    idb->SetInsertPoint(BasicBlock::Create(M->getContext(), "entry", mainFunc, 0));
321    auto args = mainFunc->arg_begin();
322
323    Value * const fileDescriptor = &*(args++);
324    fileDescriptor->setName("fileDescriptor");
325    Value * match_accumulator = &*(args++);
326    match_accumulator->setName("match_accumulator");
327
328    StreamSetBuffer * ByteStream = mGrepDriver->addBuffer<SourceBuffer>(idb, idb->getStreamSetTy(1, encodingBits));
329    kernel::Kernel * sourceK = mGrepDriver->addKernelInstance<kernel::FDSourceKernel>(idb);
330    sourceK->setInitialArguments({fileDescriptor});
331    mGrepDriver->makeKernelCall(sourceK, {}, {ByteStream});
332
333    StreamSetBuffer * LineBreakStream;
334    StreamSetBuffer * Matches;
335    std::tie(LineBreakStream, Matches) = grepPipeline(REs, ByteStream);
336
337    kernel::Kernel * scanMatchK = mGrepDriver->addKernelInstance<kernel::ScanMatchKernel>(idb);
338    scanMatchK->setInitialArguments({match_accumulator});
339    mGrepDriver->makeKernelCall(scanMatchK, {Matches, LineBreakStream, ByteStream}, {});
340    mGrepDriver->LinkFunction(*scanMatchK, "accumulate_match_wrapper", &accumulate_match_wrapper);
341    mGrepDriver->LinkFunction(*scanMatchK, "finalize_match_wrapper", &finalize_match_wrapper);
342
343    mGrepDriver->generatePipelineIR();
344    mGrepDriver->deallocateBuffers();
345    idb->CreateRet(idb->getInt64(0));
346    mGrepDriver->finalizeObject();
347}
348
349
350//
351//  The doGrep methods apply a GrepEngine to a single file, processing the results
352//  differently based on the engine type.
353
354uint64_t GrepEngine::doGrep(const std::string & fileName, const uint32_t fileIdx) {
355    typedef uint64_t (*GrepFunctionType)(int32_t fileDescriptor);
356    auto f = reinterpret_cast<GrepFunctionType>(mGrepDriver->getMain());
357
358    int32_t fileDescriptor = openFile(fileName, mResultStrs[fileIdx]);
359    if (fileDescriptor == -1) return 0;
360
361    uint64_t grepResult = f(fileDescriptor);
362    close(fileDescriptor);
363    return grepResult;
364}
365
366uint64_t CountOnlyEngine::doGrep(const std::string & fileName, const uint32_t fileIdx) {
367    uint64_t grepResult = GrepEngine::doGrep(fileName, fileIdx);
368    if (WithFilenameFlag) mResultStrs[fileIdx] << linePrefix(fileName);
369    mResultStrs[fileIdx] << grepResult << "\n";
370    return grepResult;
371}
372
373std::string GrepEngine::linePrefix(std::string fileName) {
374    if (fileName == "-") {
375        return LabelFlag + mFileSuffix;
376    }
377    else {
378        return fileName + mFileSuffix;
379    }
380}
381
382uint64_t MatchOnlyEngine::doGrep(const std::string & fileName, const uint32_t fileIdx) {
383    uint64_t grepResult = GrepEngine::doGrep(fileName, fileIdx);
384    if (grepResult == mRequiredCount) {
385       mResultStrs[fileIdx] << linePrefix(fileName);
386    }
387    return grepResult;
388}
389
390uint64_t EmitMatchesEngine::doGrep(const std::string & fileName, const uint32_t fileIdx) {
391    typedef uint64_t (*GrepFunctionType)(int32_t fileDescriptor, intptr_t accum_addr);
392    auto f = reinterpret_cast<GrepFunctionType>(mGrepDriver->getMain());
393
394    int32_t fileDescriptor = openFile(fileName, mResultStrs[fileIdx]);
395    if (fileDescriptor == -1) return 0;
396    EmitMatch accum(linePrefix(fileName), mResultStrs[fileIdx]);
397    f(fileDescriptor, reinterpret_cast<intptr_t>(&accum));
398    close(fileDescriptor);
399    if (accum.mLineCount > 0) grepMatchFound = true;
400    return accum.mLineCount;
401}
402
403// Open a file and return its file desciptor.
404int32_t GrepEngine::openFile(const std::string & fileName, std::ostringstream & msgstrm) {
405    if (fileName == "-") {
406        return STDIN_FILENO;
407    }
408    else {
409        struct stat sb;
410        int32_t fileDescriptor = open(fileName.c_str(), O_RDONLY);
411        if (LLVM_UNLIKELY(fileDescriptor == -1)) {
412            if (!NoMessagesFlag) {
413                if (errno == EACCES) {
414                    msgstrm << "icgrep: " << fileName << ": Permission denied.\n";
415                }
416                else if (errno == ENOENT) {
417                    msgstrm << "icgrep: " << fileName << ": No such file.\n";
418                }
419                else {
420                    msgstrm << "icgrep: " << fileName << ": Failed.\n";
421                }
422            }
423            return fileDescriptor;
424        }
425        if (stat(fileName.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
426            if (!NoMessagesFlag) {
427                msgstrm << "icgrep: " << fileName << ": Is a directory.\n";
428            }
429            close(fileDescriptor);
430            return -1;
431        }
432        return fileDescriptor;
433    }
434}
435
436// The process of searching a group of files may use a sequential or a task
437// parallel approach.
438
439void * DoGrepThreadFunction(void *args) {
440    return reinterpret_cast<GrepEngine *>(args)->DoGrepThreadMethod();
441}
442
443bool GrepEngine::searchAllFiles() {
444    const unsigned numOfThreads = std::min(static_cast<unsigned>(Threads), static_cast<unsigned>(inputFiles.size())); 
445    std::vector<pthread_t> threads(numOfThreads);
446
447    for(unsigned long i = 1; i < numOfThreads; ++i) {
448        const int rc = pthread_create(&threads[i], nullptr, DoGrepThreadFunction, (void *)this);
449        if (rc) {
450            llvm::report_fatal_error("Failed to create thread: code " + std::to_string(rc));
451        }
452    }
453    // Main thread also does the work;
454
455    DoGrepThreadMethod();
456    for(unsigned i = 1; i < numOfThreads; ++i) {
457        void * status = nullptr;
458        const int rc = pthread_join(threads[i], &status);
459        if (rc) {
460            llvm::report_fatal_error("Failed to join thread: code " + std::to_string(rc));
461        }
462    }
463    return grepMatchFound;
464}
465
466
467// DoGrep thread function.
468void * GrepEngine::DoGrepThreadMethod() {
469
470    unsigned fileIdx = mNextFileToGrep++;
471    while (fileIdx < inputFiles.size()) {
472        const auto grepResult = doGrep(inputFiles[fileIdx], fileIdx);
473        mFileStatus[fileIdx] = FileStatus::GrepComplete;
474        if (grepResult > 0) {
475            grepMatchFound = true;
476        }
477        if (QuietMode && grepMatchFound) {
478            if (pthread_self() != mEngineThread) {
479                pthread_exit(nullptr);
480            }
481            return nullptr;
482        }
483        fileIdx = mNextFileToGrep++;
484    }
485
486    unsigned printIdx = mNextFileToPrint++;
487    while (printIdx < inputFiles.size()) {
488        const bool readyToPrint = ((printIdx == 0) || (mFileStatus[printIdx - 1] == FileStatus::PrintComplete)) && (mFileStatus[printIdx] == FileStatus::GrepComplete);
489        if (readyToPrint) {
490            const auto output = mResultStrs[printIdx].str();
491            if (!output.empty()) {
492                llvm::outs() << output;
493            }
494            mFileStatus[printIdx] = FileStatus::PrintComplete;
495            printIdx = mNextFileToPrint++;
496        } else {
497            mGrepDriver->performIncrementalCacheCleanupStep();
498        }
499        sched_yield();
500    }
501
502    if (pthread_self() != mEngineThread) {
503        pthread_exit(nullptr);
504    } else {
505        // Always perform one final cache cleanup step.
506        mGrepDriver->performIncrementalCacheCleanupStep();
507    }
508    return nullptr;
509}
510
511}
Note: See TracBrowser for help on using the repository browser.