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

Last change on this file since 5814 was 5812, checked in by nmedfort, 15 months ago

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

File size: 19.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 <re/printer_re.h>
34#include <toolchain/toolchain.h>
35#include <toolchain/cpudriver.h>
36#include <iostream>
37#include <cc/multiplex_CCs.h>
38#include <llvm/Support/raw_ostream.h>
39#include <util/aligned_allocator.h>
40#include <sys/stat.h>
41#include <fcntl.h>
42#include <errno.h>
43#include <llvm/ADT/STLExtras.h> // for make_unique
44#include <llvm/Support/CommandLine.h>
45#include <llvm/Support/Debug.h>
46#include <sched.h>
47
48using namespace parabix;
49using namespace llvm;
50using namespace cc;
51
52static cl::opt<int> Threads("t", cl::desc("Total number of threads."), cl::init(2));
53
54namespace grep {
55
56// Grep Engine construction and initialization.
57
58GrepEngine::GrepEngine() :
59    mGrepDriver(nullptr),
60    mNextFileToGrep(0),
61    mNextFileToPrint(0),
62    grepMatchFound(false),
63    mMoveMatchesToEOL(true),
64    mEngineThread(pthread_self()) {}
65
66GrepEngine::~GrepEngine() {
67    delete mGrepDriver;
68}
69
70QuietModeEngine::QuietModeEngine() : GrepEngine() {
71    mMoveMatchesToEOL = false;
72}
73
74MatchOnlyEngine::MatchOnlyEngine(bool showFilesWithoutMatch) :
75    GrepEngine(), mRequiredCount(showFilesWithoutMatch) {
76    mFileSuffix = NullFlag ? std::string("\0", 1) : "\n";
77    mMoveMatchesToEOL = false;
78}
79
80CountOnlyEngine::CountOnlyEngine() : GrepEngine() {
81    mFileSuffix = ":";
82}
83
84EmitMatchesEngine::EmitMatchesEngine() : GrepEngine() {
85    mFileSuffix = InitialTabFlag ? "\t:" : ":";
86    if (LineRegexpFlag) mMoveMatchesToEOL = false;
87}
88
89void GrepEngine::initFileResult(std::vector<std::string> & filenames) {
90    const unsigned n = filenames.size();
91    mResultStrs.resize(n);
92    mFileStatus.resize(n, FileStatus::Pending);
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;
105
106    StreamSetBuffer * BasisBits = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(encodingBits, 1), segmentSize * bufferSegments);
107    kernel::Kernel * s2pk = mGrepDriver->addKernelInstance<kernel::S2PKernel>(idb);
108    mGrepDriver->makeKernelCall(s2pk, {ByteStream}, {BasisBits});
109
110    StreamSetBuffer * LineFeedStream = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize * bufferSegments);
111    kernel::Kernel * linefeedK = mGrepDriver->addKernelInstance<kernel::LineFeedKernelBuilder>(idb, encodingBits);
112    mGrepDriver->makeKernelCall(linefeedK, {BasisBits}, {LineFeedStream});
113
114    StreamSetBuffer * LineBreakStream = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize * bufferSegments);
115    StreamSetBuffer * CRLFStream = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize * bufferSegments);
116    kernel::Kernel * linebreakK = mGrepDriver->addKernelInstance<kernel::LineBreakKernelBuilder>(idb, encodingBits);
117    mGrepDriver->makeKernelCall(linebreakK, {BasisBits, LineFeedStream}, {LineBreakStream, CRLFStream});
118
119    kernel::Kernel * requiredStreamsK = mGrepDriver->addKernelInstance<kernel::RequiredStreams_UTF8>(idb);
120    StreamSetBuffer * RequiredStreams = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(3, 1), segmentSize * bufferSegments);
121    mGrepDriver->makeKernelCall(requiredStreamsK, {BasisBits}, {RequiredStreams});
122
123    const auto n = REs.size();
124    std::vector<std::vector<re::CC *>> charclasses(n);
125    std::vector<StreamSetBuffer *> MatchResultsBufs(n);
126
127    for(unsigned i = 0; i < n; ++i) {
128        REs[i] = resolveModesAndExternalSymbols(REs[i]);
129        REs[i] = excludeUnicodeLineBreak(REs[i]);
130#define USE_MULTIPLEX_CC
131#ifdef USE_MULTIPLEX_CC
132       
133        REs[i] = multiplexing_prepasses(REs[i]);
134        const std::vector<const re::CC *> UnicodeSets = re::collectUnicodeSets(REs[i]);
135        mpx = make_unique<MultiplexedAlphabet>("mpx", UnicodeSets);
136        REs[i] = transformCCs(mpx.get(), REs[i]);
137        //llvm::errs() << Printer_RE::PrintRE(REs[i]) << '\n';
138        std::vector<re::CC *> mpx_basis = mpx->getMultiplexedCCs();
139        auto numOfCharacterClasses = mpx_basis.size();
140        StreamSetBuffer * CharClasses = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(numOfCharacterClasses), segmentSize * bufferSegments);
141        kernel::Kernel * ccK = mGrepDriver->addKernelInstance<kernel::CharClassesKernel>(idb, std::move(mpx_basis));
142        mGrepDriver->makeKernelCall(ccK, {BasisBits}, {CharClasses});
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);
145        mGrepDriver->makeKernelCall(icgrepK, {CharClasses, LineBreakStream, CRLFStream, RequiredStreams}, {MatchResults});
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
152        MatchResultsBufs[i] = MatchResults;
153    }
154    StreamSetBuffer * MergedResults = MatchResultsBufs[0];
155    if (REs.size() > 1) {
156        MergedResults = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize * bufferSegments);
157        kernel::Kernel * streamsMergeK = mGrepDriver->addKernelInstance<kernel::StreamsMerge>(idb, 1, REs.size());
158        mGrepDriver->makeKernelCall(streamsMergeK, MatchResultsBufs, {MergedResults});
159    }
160    StreamSetBuffer * Matches = MergedResults;
161
162    if (mMoveMatchesToEOL) {
163        StreamSetBuffer * OriginalMatches = Matches;
164        kernel::Kernel * matchedLinesK = mGrepDriver->addKernelInstance<kernel::MatchedLinesKernel>(idb);
165        Matches = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize * bufferSegments);
166        mGrepDriver->makeKernelCall(matchedLinesK, {OriginalMatches, LineBreakStream}, {Matches});
167    }
168
169    if (InvertMatchFlag) {
170        kernel::Kernel * invertK = mGrepDriver->addKernelInstance<kernel::InvertMatchesKernel>(idb);
171        StreamSetBuffer * OriginalMatches = Matches;
172        Matches = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize * bufferSegments);
173        mGrepDriver->makeKernelCall(invertK, {OriginalMatches, LineBreakStream}, {Matches});
174    }
175    if (MaxCountFlag > 0) {
176        kernel::Kernel * untilK = mGrepDriver->addKernelInstance<kernel::UntilNkernel>(idb);
177        untilK->setInitialArguments({idb->getSize(MaxCountFlag)});
178        StreamSetBuffer * AllMatches = Matches;
179        Matches = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize * bufferSegments);
180        mGrepDriver->makeKernelCall(untilK, {AllMatches}, {Matches});
181    }
182    return std::pair<StreamSetBuffer *, StreamSetBuffer *>(LineBreakStream, Matches);
183}
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).
187//
188
189void GrepEngine::grepCodeGen(std::vector<re::RE *> REs) {
190
191    assert (mGrepDriver == nullptr);
192    mGrepDriver = new ParabixDriver("engine");
193    auto & idb = mGrepDriver->getBuilder();
194    Module * M = idb->getModule();
195
196    const auto segmentSize = codegen::SegmentSize;
197    const auto bufferSegments = codegen::BufferSegments * codegen::ThreadNum;
198
199    const unsigned encodingBits = 8;
200
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();
205
206    Value * const fileDescriptor = &*(args++);
207    fileDescriptor->setName("fileDescriptor");
208
209    StreamSetBuffer * ByteStream = mGrepDriver->addBuffer<SourceBuffer>(idb, idb->getStreamSetTy(1, encodingBits));
210    kernel::Kernel * sourceK = mGrepDriver->addKernelInstance<kernel::FDSourceKernel>(idb, segmentSize * bufferSegments);
211    sourceK->setInitialArguments({fileDescriptor});
212    mGrepDriver->makeKernelCall(sourceK, {}, {ByteStream});
213
214    StreamSetBuffer * LineBreakStream;
215    StreamSetBuffer * Matches;
216    std::tie(LineBreakStream, Matches) = grepPipeline(REs, ByteStream);
217
218    kernel::Kernel * matchCountK = mGrepDriver->addKernelInstance<kernel::PopcountKernel>(idb);
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
233class EmitMatch : public MatchAccumulator {
234    friend class EmitMatchesEngine;
235public:
236    EmitMatch(std::string linePrefix, std::ostringstream & strm) : mLinePrefix(linePrefix), mLineCount(0), mTerminated(true), mResultStr(strm) {}
237    void accumulate_match(const size_t lineNum, char * line_start, char * line_end) override;
238    void finalize_match(char * buffer_end) override;
239protected:
240    std::string mLinePrefix;
241    size_t mLineCount;
242    bool mTerminated;
243    std::ostringstream & mResultStr;
244};
245
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.
249//
250void EmitMatch::accumulate_match (const size_t lineNum, char * line_start, char * line_end) {
251    if (WithFilenameFlag) {
252        mResultStr << mLinePrefix;
253    }
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) {
258            mResultStr << lineNum+1 << "\t:";
259        }
260        else {
261            mResultStr << lineNum+1 << ":";
262        }
263    }
264    size_t bytes = line_end - line_start + 1;
265    mResultStr.write(line_start, bytes);
266    mLineCount++;
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);
272        }
273        else {
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));
278        }
279    }
280}
281
282void EmitMatch::finalize_match(char * buffer_end) {
283    if (!mTerminated) mResultStr << "\n";
284}
285
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();
291
292    const auto segmentSize = codegen::SegmentSize;
293    const auto bufferSegments = codegen::BufferSegments * codegen::ThreadNum;
294    const unsigned encodingBits = 8;
295
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();
300
301    Value * const fileDescriptor = &*(args++);
302    fileDescriptor->setName("fileDescriptor");
303    Value * match_accumulator = &*(args++);
304    match_accumulator->setName("match_accumulator");
305
306    StreamSetBuffer * ByteStream = mGrepDriver->addBuffer<SourceBuffer>(idb, idb->getStreamSetTy(1, encodingBits));
307    kernel::Kernel * sourceK = mGrepDriver->addKernelInstance<kernel::FDSourceKernel>(idb, segmentSize * bufferSegments);
308    sourceK->setInitialArguments({fileDescriptor});
309    mGrepDriver->makeKernelCall(sourceK, {}, {ByteStream});
310
311    StreamSetBuffer * LineBreakStream;
312    StreamSetBuffer * Matches;
313    std::tie(LineBreakStream, Matches) = grepPipeline(REs, ByteStream);
314
315    kernel::Kernel * scanMatchK = mGrepDriver->addKernelInstance<kernel::ScanMatchKernel>(idb);
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);
320
321    mGrepDriver->generatePipelineIR();
322    mGrepDriver->deallocateBuffers();
323    idb->CreateRet(idb->getInt64(0));
324    mGrepDriver->finalizeObject();
325}
326
327
328//
329//  The doGrep methods apply a GrepEngine to a single file, processing the results
330//  differently based on the engine type.
331
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());
335
336    int32_t fileDescriptor = openFile(fileName, mResultStrs[fileIdx]);
337    if (fileDescriptor == -1) return 0;
338
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);
346    if (WithFilenameFlag) mResultStrs[fileIdx] << linePrefix(fileName);
347    mResultStrs[fileIdx] << grepResult << "\n";
348    return grepResult;
349}
350
351std::string GrepEngine::linePrefix(std::string fileName) {
352    if (fileName == "-") {
353        return LabelFlag + mFileSuffix;
354    }
355    else {
356        return fileName + mFileSuffix;
357    }
358}
359
360uint64_t MatchOnlyEngine::doGrep(const std::string & fileName, const uint32_t fileIdx) {
361    uint64_t grepResult = GrepEngine::doGrep(fileName, fileIdx);
362    if (grepResult == mRequiredCount) {
363       mResultStrs[fileIdx] << linePrefix(fileName);
364    }
365    return grepResult;
366}
367
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());
371
372    int32_t fileDescriptor = openFile(fileName, mResultStrs[fileIdx]);
373    if (fileDescriptor == -1) return 0;
374    EmitMatch accum(linePrefix(fileName), mResultStrs[fileIdx]);
375    f(fileDescriptor, reinterpret_cast<intptr_t>(&accum));
376    close(fileDescriptor);
377    if (accum.mLineCount > 0) grepMatchFound = true;
378    return accum.mLineCount;
379}
380
381// Open a file and return its file desciptor.
382int32_t GrepEngine::openFile(const std::string & fileName, std::ostringstream & msgstrm) {
383    if (fileName == "-") {
384        return STDIN_FILENO;
385    }
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) {
392                    msgstrm << "icgrep: " << fileName << ": Permission denied.\n";
393                }
394                else if (errno == ENOENT) {
395                    msgstrm << "icgrep: " << fileName << ": No such file.\n";
396                }
397                else {
398                    msgstrm << "icgrep: " << fileName << ": Failed.\n";
399                }
400            }
401            return fileDescriptor;
402        }
403        if (stat(fileName.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
404            if (!NoMessagesFlag) {
405                msgstrm << "icgrep: " << fileName << ": Is a directory.\n";
406            }
407            close(fileDescriptor);
408            return -1;
409        }
410        return fileDescriptor;
411    }
412}
413
414// The process of searching a group of files may use a sequential or a task
415// parallel approach.
416
417void * DoGrepThreadFunction(void *args) {
418    return reinterpret_cast<GrepEngine *>(args)->DoGrepThreadMethod();
419}
420
421bool GrepEngine::searchAllFiles() {
422    const unsigned numOfThreads = std::min(static_cast<unsigned>(Threads), static_cast<unsigned>(inputFiles.size())); 
423    std::vector<pthread_t> threads(numOfThreads);
424
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));
429        }
430    }
431    // Main thread also does the work;
432
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));
439        }
440    }
441    return grepMatchFound;
442}
443
444
445// DoGrep thread function.
446void * GrepEngine::DoGrepThreadMethod() {
447
448    unsigned fileIdx = mNextFileToGrep++;
449    while (fileIdx < inputFiles.size()) {
450        const auto grepResult = doGrep(inputFiles[fileIdx], fileIdx);
451        mFileStatus[fileIdx] = FileStatus::GrepComplete;
452        if (grepResult > 0) {
453            grepMatchFound = true;
454        }
455        if (QuietMode && grepMatchFound) {
456            if (pthread_self() != mEngineThread) {
457                pthread_exit(nullptr);
458            }
459            return nullptr;
460        }
461        fileIdx = mNextFileToGrep++;
462    }
463
464    unsigned printIdx = mNextFileToPrint++;
465    while (printIdx < inputFiles.size()) {
466        const bool readyToPrint = ((printIdx == 0) || (mFileStatus[printIdx - 1] == FileStatus::PrintComplete)) && (mFileStatus[printIdx] == FileStatus::GrepComplete);
467        if (readyToPrint) {
468            const auto output = mResultStrs[printIdx].str();
469            if (!output.empty()) {
470                llvm::outs() << output;
471            }
472            mFileStatus[printIdx] = FileStatus::PrintComplete;
473            printIdx = mNextFileToPrint++;
474        } else {
475            mGrepDriver->performIncrementalCacheCleanupStep();
476        }
477        sched_yield();
478    }
479
480    if (pthread_self() != mEngineThread) {
481        pthread_exit(nullptr);
482    } else {
483        // Always perform one final cache cleanup step.
484        mGrepDriver->performIncrementalCacheCleanupStep();
485    }
486    return nullptr;
487}
488
489}
Note: See TracBrowser for help on using the repository browser.