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

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

Restructuring step/tidy-up for re_passes

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