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

Last change on this file since 5768 was 5768, checked in by cameron, 23 months ago

Regular expression system restructuring progress

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