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

Last change on this file since 5781 was 5779, checked in by cameron, 18 months ago

Remove RE compiler dependency on linebreak/mAny

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/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);
104    kernel::Kernel * s2pk = mGrepDriver->addKernelInstance<kernel::S2PKernel>(idb);
105    mGrepDriver->makeKernelCall(s2pk, {ByteStream}, {BasisBits});
106
107    StreamSetBuffer * LineBreakStream = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize * bufferSegments);
108    kernel::Kernel * linebreakK = mGrepDriver->addKernelInstance<kernel::LineBreakKernelBuilder>(idb, encodingBits);
109    mGrepDriver->makeKernelCall(linebreakK, {BasisBits}, {LineBreakStream});
110
111    kernel::Kernel * requiredStreamsK = mGrepDriver->addKernelInstance<kernel::RequiredStreams_UTF8>(idb);
112    StreamSetBuffer * RequiredStreams = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(4, 1), segmentSize * bufferSegments);
113    mGrepDriver->makeKernelCall(requiredStreamsK, {BasisBits}, {RequiredStreams});
114
115    const auto n = REs.size();
116    std::vector<std::vector<re::CC *>> charclasses(n);
117    for (unsigned i = 0; i < n; i++) {
118        REs[i] = resolveCaseInsensitiveMode(REs[i], grep::IgnoreCaseFlag);
119        REs[i] = resolveGraphemeMode(REs[i], false /* not in grapheme mode at top level*/);
120        REs[i] = re::resolveNames(REs[i]);
121        REs[i] = exclude_CC(REs[i], re::makeCC(re::makeCC(0x0A, 0x0D), re::makeCC(re::makeCC(0x85), re::makeCC(0x2028, 0x2029))));
122
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::ostringstream & 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::ostringstream & 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]);
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]);
361    if (fileDescriptor == -1) return 0;
362    EmitMatch accum(linePrefix(fileName), mResultStrs[fileIdx]);
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::ostringstream & 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    unsigned fileIdx = mNextFileToGrep++;
437    while (fileIdx < inputFiles.size()) {
438        const auto 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    unsigned 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                llvm::outs() << output;
459            }
460            mFileStatus[printIdx] = FileStatus::PrintComplete;
461            printIdx = mNextFileToPrint++;
462        } else {
463            mGrepDriver->performIncrementalCacheCleanupStep();
464        }
465        sched_yield();
466    }
467
468    if (pthread_self() != mEngineThread) {
469        pthread_exit(nullptr);
470    } else {
471        return nullptr;
472    }
473}
474
475}
Note: See TracBrowser for help on using the repository browser.