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

Last change on this file since 5787 was 5787, checked in by cameron, 7 months ago

RE parser restructuring; parsing symbolic ranges, collation and equivalence exprs

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