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

Last change on this file since 5815 was 5812, checked in by nmedfort, 16 months ago

Bug fix for RE local + some clean up of RE local and the RE Compiler

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