source: icGREP/icgrep-devel/icgrep/grep/grep_engine.cpp @ 5963

Last change on this file since 5963 was 5963, checked in by cameron, 10 months ago

Fixes for internal buffer search

File size: 37.8 KB
Line 
1/*
2 *  Copyright (c) 2018 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#include <set>
7#include "grep_engine.h"
8#include <llvm/IR/Module.h>
9#include <boost/filesystem.hpp>
10#include <UCD/resolve_properties.h>
11#include <kernels/charclasses.h>
12#include <kernels/cc_kernel.h>
13#include <kernels/grep_kernel.h>
14#include <kernels/UCD_property_kernel.h>
15#include <kernels/grapheme_kernel.h>
16#include <kernels/linebreak_kernel.h>
17#include <kernels/streams_merge.h>
18#include <kernels/source_kernel.h>
19#include <kernels/s2p_kernel.h>
20#include <kernels/scanmatchgen.h>
21#include <kernels/streamset.h>
22#include <kernels/until_n.h>
23#include <kernels/kernel_builder.h>
24#include <pablo/pablo_kernel.h>
25#include <cc/alphabet.h>
26#include <re/re_cc.h>
27#include <re/re_name.h>
28#include <re/casing.h>
29#include <re/exclude_CC.h>
30#include <re/to_utf8.h>
31#include <re/re_toolchain.h>
32#include <toolchain/toolchain.h>
33#include <re/re_analysis.h>
34#include <re/re_name_resolve.h>
35#include <re/re_name_gather.h>
36#include <re/collect_ccs.h>
37#include <re/replaceCC.h>
38#include <re/re_multiplex.h>
39#include <re/grapheme_clusters.h>
40#include <re/printer_re.h>
41#include <toolchain/toolchain.h>
42#include <toolchain/cpudriver.h>
43#include <iostream>
44#include <cc/multiplex_CCs.h>
45#include <llvm/Support/raw_ostream.h>
46#include <util/file_select.h>
47#include <util/aligned_allocator.h>
48#include <sys/stat.h>
49#include <fcntl.h>
50#include <errno.h>
51#include <llvm/ADT/STLExtras.h> // for make_unique
52#include <llvm/Support/CommandLine.h>
53#include <llvm/Support/Debug.h>
54#include <llvm/Support/Casting.h>
55#include <sched.h>
56
57using namespace parabix;
58using namespace llvm;
59using namespace cc;
60using namespace kernel;
61
62static cl::opt<int> Threads("t", cl::desc("Total number of threads."), cl::init(2));
63static cl::opt<bool> PabloTransposition("enable-pablo-s2p", cl::desc("Enable experimental pablo transposition."));
64static cl::opt<bool> CC_Multiplexing("CC-multiplexing", cl::desc("Enable CC multiplexing."), cl::init(false));
65static cl::opt<bool> PropertyKernels("enable-property-kernels", cl::desc("Enable Unicode property kernels."), cl::init(false));
66static cl::opt<bool> MultithreadedSimpleRE("enable-simple-RE-kernels", cl::desc("Enable individual CC kernels for simple REs."), cl::init(false));
67const unsigned DefaultByteCClimit = 6;
68
69static cl::opt<unsigned> ByteCClimit("byte-CC-limit", cl::desc("Max number of CCs for byte CC pipeline."), cl::init(DefaultByteCClimit));
70
71
72namespace grep {
73   
74
75extern "C" void accumulate_match_wrapper(intptr_t accum_addr, const size_t lineNum, char * line_start, char * line_end) {
76    reinterpret_cast<MatchAccumulator *>(accum_addr)->accumulate_match(lineNum, line_start, line_end);
77}
78
79extern "C" void finalize_match_wrapper(intptr_t accum_addr, char * buffer_end) {
80    reinterpret_cast<MatchAccumulator *>(accum_addr)->finalize_match(buffer_end);
81}
82   
83
84inline static size_t ceil_log2(const size_t v) {
85    assert ("log2(0) is undefined!" && v != 0);
86    assert ("sizeof(size_t) == sizeof(long)" && sizeof(size_t) == sizeof(long));
87    return (sizeof(size_t) * CHAR_BIT) - __builtin_clzl(v - 1UL);
88}
89
90void SearchableBuffer::addSearchCandidate(const char * C_string_ptr) {
91    size_t length = strlen(C_string_ptr)+1;
92    if (mSpace_used + length >= mAllocated_capacity) {
93        size_t new_capacity = size_t{1} << (ceil_log2(mSpace_used + length + 1));
94        AlignedAllocator<char, BUFFER_ALIGNMENT> alloc;
95        char * new_buffer = mAllocator.allocate(new_capacity, 0);
96        memcpy(new_buffer, mBuffer_base, mSpace_used);
97        memset(&new_buffer[mSpace_used], 0, new_capacity-mSpace_used);
98        if (mBuffer_base != mInitial_buffer) {
99            alloc.deallocate(mBuffer_base, 0);
100        }
101        mBuffer_base = new_buffer;
102        mAllocated_capacity = new_capacity;
103    }
104    memcpy((void * ) &mBuffer_base[mSpace_used], C_string_ptr, length);
105    mSpace_used += length;
106    assert("Search candidate not null terminated" && (mBuffer_base[mSpace_used] == '\0'));
107    mEntries++;
108}
109
110SearchableBuffer::SearchableBuffer() :
111    mAllocated_capacity(INITIAL_CAPACITY),
112    mSpace_used(0),
113    mEntries(0),
114    mBuffer_base(mInitial_buffer) {
115    memset(mBuffer_base, 0, INITIAL_CAPACITY);
116}
117
118SearchableBuffer::~SearchableBuffer() {
119    if (mBuffer_base != mInitial_buffer) {
120        mAllocator.deallocate(mBuffer_base, 0);
121    }
122}
123
124
125
126// Grep Engine construction and initialization.
127
128GrepEngine::GrepEngine() :
129    mSuppressFileMessages(false),
130    mPreferMMap(true),
131    mShowFileNames(false),
132    mStdinLabel("(stdin)"),
133    mShowLineNumbers(false),
134    mInitialTab(false),
135    mCaseInsensitive(false),
136    mInvertMatches(false),
137    mMaxCount(0),
138    mGrepDriver(nullptr),
139    mNextFileToGrep(0),
140    mNextFileToPrint(0),
141    grepMatchFound(false),
142    mGrepRecordBreak(GrepRecordBreakKind::LF),
143    mMoveMatchesToEOL(true),
144    mEngineThread(pthread_self()) {}
145
146GrepEngine::~GrepEngine() {
147    delete mGrepDriver;
148}
149
150QuietModeEngine::QuietModeEngine() : GrepEngine() {
151    mEngineKind = EngineKind::QuietMode;
152    mMoveMatchesToEOL = false;
153    mMaxCount = 1;
154}
155
156MatchOnlyEngine::MatchOnlyEngine(bool showFilesWithoutMatch, bool useNullSeparators) :
157    GrepEngine(), mRequiredCount(showFilesWithoutMatch) {
158    mEngineKind = EngineKind::MatchOnly;
159    mFileSuffix = useNullSeparators ? std::string("\0", 1) : "\n";
160    mMoveMatchesToEOL = false;
161    mMaxCount = 1;
162}
163
164CountOnlyEngine::CountOnlyEngine() : GrepEngine() {
165    mEngineKind = EngineKind::CountOnly;
166    mFileSuffix = ":";
167}
168
169EmitMatchesEngine::EmitMatchesEngine() : GrepEngine() {
170    mEngineKind = EngineKind::EmitMatches;
171    mFileSuffix = mInitialTab ? "\t:" : ":";
172}
173
174   
175void GrepEngine::setRecordBreak(GrepRecordBreakKind b) {
176    mGrepRecordBreak = b;
177}
178
179   
180
181   
182void GrepEngine::initFileResult(std::vector<std::string> & filenames) {
183    const unsigned n = filenames.size();
184    mResultStrs.resize(n);
185    mFileStatus.resize(n, FileStatus::Pending);
186    inputFiles = filenames;
187}
188
189void GrepEngine::initREs(std::vector<re::RE *> & REs) {
190    if (mGrepRecordBreak == GrepRecordBreakKind::Unicode) {
191        mBreakCC = re::makeCC(re::makeCC(0x0A, 0x0D), re::makeCC(re::makeCC(0x85), re::makeCC(0x2028, 0x2029)));
192    } else if (mGrepRecordBreak == GrepRecordBreakKind::Null) {
193        mBreakCC = re::makeByte(0);  // Null
194    } else {
195        mBreakCC = re::makeByte(0x0A); // LF
196    }
197    re::RE * anchorRE = mBreakCC;
198    if (mGrepRecordBreak == GrepRecordBreakKind::Unicode) {
199        re::Name * anchorName = re::makeName("UTF8_LB", re::Name::Type::Unicode);
200        anchorName->setDefinition(UCD::UnicodeBreakRE());
201        anchorRE = anchorName;
202    }
203   
204    mREs = REs;
205    bool allAnchored = true;
206    for(unsigned i = 0; i < mREs.size(); ++i) {
207        if (!hasEndAnchor(mREs[i])) allAnchored = false;
208        mREs[i] = resolveModesAndExternalSymbols(mREs[i], mCaseInsensitive);
209        mREs[i] = re::exclude_CC(mREs[i], mBreakCC);
210        mREs[i] = resolveAnchors(mREs[i], anchorRE);
211        re::gatherUnicodeProperties(mREs[i], mUnicodeProperties);
212        mREs[i] = regular_expression_passes(mREs[i]);
213    }
214    if (allAnchored && (mGrepRecordBreak != GrepRecordBreakKind::Unicode)) mMoveMatchesToEOL = false;
215
216}
217
218
219   
220// Code Generation
221//
222// All engines share a common pipeline to compute a stream of Matches from a given input Bytestream.
223
224unsigned LLVM_READNONE calculateMaxCountRate(const std::unique_ptr<kernel::KernelBuilder> & b) {
225    const unsigned packSize = b->getSizeTy()->getBitWidth();
226    return (packSize * packSize) / b->getBitBlockWidth();
227}
228   
229std::pair<StreamSetBuffer *, StreamSetBuffer *> GrepEngine::grepPipeline(StreamSetBuffer * ByteStream) {
230    auto & idb = mGrepDriver->getBuilder();
231    const unsigned segmentSize = codegen::SegmentSize;
232    const unsigned bufferSegments = codegen::BufferSegments * codegen::ThreadNum;
233    // TODO: until we automate stream buffer sizing, use this calculation to determine how large our matches buffer needs to be.
234    const unsigned baseBufferSize = segmentSize * (mMaxCount > 0 ? (std::max(bufferSegments, calculateMaxCountRate(idb))) : bufferSegments);
235    const unsigned encodingBits = 8;
236   
237   
238    //  Regular Expression Processing and Analysis Phase
239    const auto nREs = mREs.size();
240    bool hasGCB[nREs];
241    bool anyGCB = false;
242
243    for(unsigned i = 0; i < nREs; ++i) {
244        hasGCB[i] = hasGraphemeClusterBoundary(mREs[i]);
245        anyGCB |= hasGCB[i];
246    }
247    StreamSetBuffer * LineBreakStream = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
248    std::vector<StreamSetBuffer *> MatchResultsBufs(nREs);
249   
250    re::RE * prefixRE;
251    re::RE * suffixRE;
252    // For simple regular expressions with a small number of characters, we
253    // can bypass transposition and use the Direct CC compiler.
254    bool isSimple = (nREs == 1) && (mGrepRecordBreak != GrepRecordBreakKind::Unicode) && (!anyGCB);
255    if (isSimple) {
256        mREs[0] = toUTF8(mREs[0]);
257    }
258    if (isSimple && byteTestsWithinLimit(mREs[0], ByteCClimit)) {
259        std::vector<std::string> externalStreamNames;
260        std::vector<StreamSetBuffer *> icgrepInputSets = {ByteStream};
261        if (MultithreadedSimpleRE && hasTriCCwithinLimit(mREs[0], ByteCClimit, prefixRE, suffixRE)) {
262            auto CCs = re::collectCCs(prefixRE, &cc::Byte);
263            for (auto cc : CCs) {
264                auto ccName = makeName(cc);
265                mREs[0] = re::replaceCC(mREs[0], cc, ccName);
266                std::string ccNameStr = ccName->getFullName();
267                StreamSetBuffer * ccStream = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
268                kernel::Kernel * ccK = mGrepDriver->addKernelInstance<kernel::DirectCharacterClassKernelBuilder>(idb, ccNameStr, std::vector<re::CC *>{cc});
269                mGrepDriver->makeKernelCall(ccK, {ByteStream}, {ccStream});
270                externalStreamNames.push_back(ccNameStr);
271                icgrepInputSets.push_back(ccStream);
272            }
273        }
274        StreamSetBuffer * MatchResults = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
275        kernel::Kernel * icgrepK = mGrepDriver->addKernelInstance<kernel::ByteGrepKernel>(idb, mREs[0], externalStreamNames);
276        mGrepDriver->makeKernelCall(icgrepK, icgrepInputSets, {MatchResults});
277        MatchResultsBufs[0] = MatchResults;
278        kernel::Kernel * breakK = mGrepDriver->addKernelInstance<kernel::DirectCharacterClassKernelBuilder>(idb, "breakCC", std::vector<re::CC *>{mBreakCC});
279        mGrepDriver->makeKernelCall(breakK, {ByteStream}, {LineBreakStream});
280    } else if (isSimple && hasTriCCwithinLimit(mREs[0], ByteCClimit, prefixRE, suffixRE)) {
281        std::vector<std::string> externalStreamNames;
282        std::vector<StreamSetBuffer *> icgrepInputSets = {ByteStream};
283        if (MultithreadedSimpleRE) {
284            auto CCs = re::collectCCs(prefixRE, &cc::Byte);
285            for (auto cc : CCs) {
286                auto ccName = makeName(cc);
287                mREs[0] = re::replaceCC(mREs[0], cc, ccName);
288                std::string ccNameStr = ccName->getFullName();
289                StreamSetBuffer * ccStream = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
290                kernel::Kernel * ccK = mGrepDriver->addKernelInstance<kernel::DirectCharacterClassKernelBuilder>(idb, ccNameStr, std::vector<re::CC *>{cc});
291                mGrepDriver->makeKernelCall(ccK, {ByteStream}, {ccStream});
292                externalStreamNames.push_back(ccNameStr);
293                icgrepInputSets.push_back(ccStream);
294            }
295        }
296        StreamSetBuffer * MatchResults = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
297        kernel::Kernel * icgrepK = mGrepDriver->addKernelInstance<kernel::ByteBitGrepKernel>(idb, prefixRE, suffixRE, externalStreamNames);
298        mGrepDriver->makeKernelCall(icgrepK, icgrepInputSets, {MatchResults});
299        MatchResultsBufs[0] = MatchResults;
300        kernel::Kernel * breakK = mGrepDriver->addKernelInstance<kernel::DirectCharacterClassKernelBuilder>(idb, "breakCC", std::vector<re::CC *>{mBreakCC});
301        mGrepDriver->makeKernelCall(breakK, {ByteStream}, {LineBreakStream});
302    } else {
303       
304        StreamSetBuffer * BasisBits = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(encodingBits, 1), baseBufferSize);
305        kernel::Kernel * s2pk = nullptr;
306        if (PabloTransposition) {
307            s2pk = mGrepDriver->addKernelInstance<kernel::S2P_PabloKernel>(idb);
308        }
309        else {
310            s2pk = mGrepDriver->addKernelInstance<kernel::S2PKernel>(idb);
311        }
312        mGrepDriver->makeKernelCall(s2pk, {ByteStream}, {BasisBits});
313
314        StreamSetBuffer * RequiredStreams = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
315        StreamSetBuffer * UnicodeLB = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
316
317        StreamSetBuffer * LineFeedStream = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
318        kernel::Kernel * linefeedK = mGrepDriver->addKernelInstance<kernel::LineFeedKernelBuilder>(idb, Binding{idb->getStreamSetTy(8), "basis", FixedRate(), Principal()});
319        mGrepDriver->makeKernelCall(linefeedK, {BasisBits}, {LineFeedStream});
320       
321        kernel::Kernel * requiredStreamsK = mGrepDriver->addKernelInstance<kernel::RequiredStreams_UTF8>(idb);
322        mGrepDriver->makeKernelCall(requiredStreamsK, {BasisBits, LineFeedStream}, {RequiredStreams, UnicodeLB});
323
324        if (mGrepRecordBreak == GrepRecordBreakKind::LF) {
325            LineBreakStream = LineFeedStream;
326        } else if (mGrepRecordBreak == GrepRecordBreakKind::Null) {
327            kernel::Kernel * breakK = mGrepDriver->addKernelInstance<kernel::ParabixCharacterClassKernelBuilder>(idb, "Null", std::vector<re::CC *>{mBreakCC}, 8);
328            mGrepDriver->makeKernelCall(breakK, {BasisBits}, {LineBreakStream});
329        } else {
330            LineBreakStream = UnicodeLB;
331        }
332       
333        std::map<std::string, StreamSetBuffer *> propertyStream;
334        if (PropertyKernels) {
335            for (auto p : mUnicodeProperties) {
336                auto name = p->getFullName();
337                StreamSetBuffer * s = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
338                propertyStream.emplace(std::make_pair(name, s));
339                kernel::Kernel * propertyK = mGrepDriver->addKernelInstance<kernel::UnicodePropertyKernelBuilder>(idb, p);
340                mGrepDriver->makeKernelCall(propertyK, {BasisBits}, {s});
341            }
342        }
343        StreamSetBuffer * GCB_stream = nullptr;
344        if (anyGCB) {
345            GCB_stream = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
346            kernel::Kernel * gcbK = mGrepDriver->addKernelInstance<kernel::GraphemeClusterBreakKernel>(idb);
347            mGrepDriver->makeKernelCall(gcbK, {BasisBits, RequiredStreams}, {GCB_stream});
348        }
349
350        for(unsigned i = 0; i < nREs; ++i) {
351            std::vector<std::string> externalStreamNames;
352            std::vector<StreamSetBuffer *> icgrepInputSets = {BasisBits};
353            if (mGrepRecordBreak == GrepRecordBreakKind::Unicode) {
354                externalStreamNames.push_back("UTF8_LB");
355                icgrepInputSets.push_back(LineBreakStream);
356                externalStreamNames.push_back("UTF8_nonfinal");
357                icgrepInputSets.push_back(RequiredStreams);
358            }
359            std::set<re::Name *> UnicodeProperties;
360            if (PropertyKernels) {
361                re::gatherUnicodeProperties(mREs[i], UnicodeProperties);
362                for (auto p : UnicodeProperties) {
363                    auto name = p->getFullName();
364                    auto f = propertyStream.find(name);
365                    if (f == propertyStream.end()) report_fatal_error(name + " not found\n");
366                    externalStreamNames.push_back(name);
367                    icgrepInputSets.push_back(f->second);
368                }
369            }
370            if (hasGCB[i]) {
371                externalStreamNames.push_back("\\b{g}");
372                icgrepInputSets.push_back(GCB_stream);
373            }
374            if (CC_Multiplexing) {
375                const auto UnicodeSets = re::collectCCs(mREs[i], &cc::Unicode, std::set<re::Name *>({re::makeZeroWidth("\\b{g}")}));
376                StreamSetBuffer * const MatchResults = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
377                if (UnicodeSets.size() <= 1) {
378                    kernel::Kernel * icgrepK = mGrepDriver->addKernelInstance<kernel::ICGrepKernel>(idb, mREs[i], externalStreamNames);
379                    mGrepDriver->makeKernelCall(icgrepK, icgrepInputSets, {MatchResults});
380                    MatchResultsBufs[i] = MatchResults;
381                } else {
382                    mpx = make_unique<MultiplexedAlphabet>("mpx", UnicodeSets);
383                    mREs[i] = transformCCs(mpx.get(), mREs[i]);
384                    std::vector<re::CC *> mpx_basis = mpx->getMultiplexedCCs();
385                    auto numOfCharacterClasses = mpx_basis.size();
386                    StreamSetBuffer * CharClasses = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(numOfCharacterClasses), baseBufferSize);
387                    kernel::Kernel * ccK = mGrepDriver->addKernelInstance<kernel::CharClassesKernel>(idb, std::move(mpx_basis));
388                    mGrepDriver->makeKernelCall(ccK, {BasisBits}, {CharClasses});
389    //                kernel::Kernel * ccK = mGrepDriver->addKernelInstance<kernel::CharClassesKernel>(idb, std::move(mpx_basis), true);
390    //                mGrepDriver->makeKernelCall(ccK, {ByteStream}, {CharClasses});
391                    kernel::Kernel * icgrepK = mGrepDriver->addKernelInstance<kernel::ICGrepKernel>(idb, mREs[i], externalStreamNames, std::vector<cc::Alphabet *>{mpx.get()});
392                    icgrepInputSets.push_back(CharClasses);
393                    mGrepDriver->makeKernelCall(icgrepK, icgrepInputSets, {MatchResults});
394                    MatchResultsBufs[i] = MatchResults;
395                }
396            } else {
397                StreamSetBuffer * MatchResults = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
398                kernel::Kernel * icgrepK = mGrepDriver->addKernelInstance<kernel::ICGrepKernel>(idb, mREs[i], externalStreamNames);
399                mGrepDriver->makeKernelCall(icgrepK, icgrepInputSets, {MatchResults});
400                MatchResultsBufs[i] = MatchResults;
401            }
402        }
403    }
404
405    StreamSetBuffer * MergedResults = MatchResultsBufs[0];
406    if (mREs.size() > 1) {
407        MergedResults = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
408        kernel::Kernel * streamsMergeK = mGrepDriver->addKernelInstance<kernel::StreamsMerge>(idb, 1, mREs.size());
409        mGrepDriver->makeKernelCall(streamsMergeK, MatchResultsBufs, {MergedResults});
410    }
411    StreamSetBuffer * Matches = MergedResults;
412    if (mMoveMatchesToEOL) {
413        StreamSetBuffer * OriginalMatches = Matches;
414        kernel::Kernel * matchedLinesK = mGrepDriver->addKernelInstance<kernel::MatchedLinesKernel>(idb);
415        Matches = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
416        mGrepDriver->makeKernelCall(matchedLinesK, {OriginalMatches, LineBreakStream}, {Matches});
417    }
418    if (mInvertMatches) {
419        kernel::Kernel * invertK = mGrepDriver->addKernelInstance<kernel::InvertMatchesKernel>(idb);
420        StreamSetBuffer * OriginalMatches = Matches;
421        Matches = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
422        mGrepDriver->makeKernelCall(invertK, {OriginalMatches, LineBreakStream}, {Matches});
423    }
424    if (mMaxCount > 0) {
425        kernel::Kernel * untilK = mGrepDriver->addKernelInstance<kernel::UntilNkernel>(idb);
426        untilK->setInitialArguments({idb->getSize(mMaxCount)});
427        StreamSetBuffer * const AllMatches = Matches;
428        Matches = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
429        mGrepDriver->makeKernelCall(untilK, {AllMatches}, {Matches});
430    }
431
432    return std::pair<StreamSetBuffer *, StreamSetBuffer *>(LineBreakStream, Matches);
433}
434
435// The QuietMode, MatchOnly and CountOnly engines share a common code generation main function,
436// which returns a count of the matches found (possibly subject to a MaxCount).
437//
438
439void GrepEngine::grepCodeGen() {
440
441    assert (mGrepDriver == nullptr);
442    mGrepDriver = new ParabixDriver("engine");
443    auto & idb = mGrepDriver->getBuilder();
444    Module * M = idb->getModule();
445
446    const unsigned encodingBits = 8;
447
448    Function * mainFunc = cast<Function>(M->getOrInsertFunction("Main", idb->getInt64Ty(), idb->getInt8Ty(), idb->getInt32Ty(), nullptr));
449    mainFunc->setCallingConv(CallingConv::C);
450    idb->SetInsertPoint(BasicBlock::Create(M->getContext(), "entry", mainFunc, 0));
451    auto args = mainFunc->arg_begin();
452
453    Value * const useMMap = &*(args++);
454    useMMap->setName("useMMap");
455    Value * const fileDescriptor = &*(args++);
456    fileDescriptor->setName("fileDescriptor");
457
458    StreamSetBuffer * ByteStream = mGrepDriver->addBuffer<SourceBuffer>(idb, idb->getStreamSetTy(1, encodingBits));
459    kernel::Kernel * sourceK = mGrepDriver->addKernelInstance<kernel::FDSourceKernel>(idb);
460    sourceK->setInitialArguments({useMMap, fileDescriptor});
461    mGrepDriver->makeKernelCall(sourceK, {}, {ByteStream});
462
463    StreamSetBuffer * LineBreakStream;
464    StreamSetBuffer * Matches;
465    std::tie(LineBreakStream, Matches) = grepPipeline(ByteStream);
466
467    kernel::Kernel * matchCountK = mGrepDriver->addKernelInstance<kernel::PopcountKernel>(idb);
468    mGrepDriver->makeKernelCall(matchCountK, {Matches}, {});
469    mGrepDriver->generatePipelineIR();
470    idb->setKernel(matchCountK);
471    Value * matchedLineCount = idb->getAccumulator("countResult");
472    matchedLineCount = idb->CreateZExt(matchedLineCount, idb->getInt64Ty());
473    mGrepDriver->deallocateBuffers();
474    idb->CreateRet(matchedLineCount);
475    mGrepDriver->finalizeObject();
476}
477
478
479//
480//  Default Report Match:  lines are emitted with whatever line terminators are found in the
481//  input.  However, if the final line is not terminated, a new line is appended.
482//
483void EmitMatch::accumulate_match (const size_t lineNum, char * line_start, char * line_end) {
484    mResultStr << mLinePrefix;
485    if (mShowLineNumbers) {
486        // Internally line numbers are counted from 0.  For display, adjust
487        // the line number so that lines are numbered from 1.
488        if (mInitialTab) {
489            mResultStr << lineNum+1 << "\t:";
490        }
491        else {
492            mResultStr << lineNum+1 << ":";
493        }
494    }
495    size_t bytes = line_end - line_start + 1;
496    mResultStr.write(line_start, bytes);
497    mLineCount++;
498    unsigned last_byte = *line_end;
499    mTerminated = (last_byte >= 0x0A) && (last_byte <= 0x0D);
500    if (LLVM_UNLIKELY(!mTerminated)) {
501        if (last_byte == 0x85) {  //  Possible NEL terminator.
502            mTerminated = (bytes >= 2) && (static_cast<unsigned>(line_end[-1]) == 0xC2);
503        }
504        else {
505            // Possible LS or PS terminators.
506            mTerminated = (bytes >= 3) && (static_cast<unsigned>(line_end[-2]) == 0xE2)
507                                       && (static_cast<unsigned>(line_end[-1]) == 0x80)
508                                       && ((last_byte == 0xA8) || (last_byte == 0xA9));
509        }
510    }
511}
512
513void EmitMatch::finalize_match(char * buffer_end) {
514    if (!mTerminated) mResultStr << "\n";
515}
516
517void EmitMatchesEngine::grepCodeGen() {
518    assert (mGrepDriver == nullptr);
519    mGrepDriver = new ParabixDriver("engine");
520    auto & idb = mGrepDriver->getBuilder();
521    Module * M = idb->getModule();
522
523    const unsigned encodingBits = 8;
524
525    Function * mainFunc = cast<Function>(M->getOrInsertFunction("Main", idb->getInt64Ty(), idb->getInt8Ty(), idb->getInt32Ty(), idb->getIntAddrTy(), nullptr));
526    mainFunc->setCallingConv(CallingConv::C);
527    idb->SetInsertPoint(BasicBlock::Create(M->getContext(), "entry", mainFunc, 0));
528    auto args = mainFunc->arg_begin();
529
530    Value * const useMMap = &*(args++);
531    useMMap->setName("useMMap");
532    Value * const fileDescriptor = &*(args++);
533    fileDescriptor->setName("fileDescriptor");
534    Value * match_accumulator = &*(args++);
535    match_accumulator->setName("match_accumulator");
536
537    StreamSetBuffer * ByteStream = mGrepDriver->addBuffer<SourceBuffer>(idb, idb->getStreamSetTy(1, encodingBits));
538    kernel::Kernel * sourceK = mGrepDriver->addKernelInstance<kernel::FDSourceKernel>(idb);
539    sourceK->setInitialArguments({useMMap, fileDescriptor});
540    mGrepDriver->makeKernelCall(sourceK, {}, {ByteStream});
541
542    StreamSetBuffer * LineBreakStream;
543    StreamSetBuffer * Matches;
544    std::tie(LineBreakStream, Matches) = grepPipeline(ByteStream);
545
546    kernel::Kernel * scanMatchK = mGrepDriver->addKernelInstance<kernel::ScanMatchKernel>(idb);
547    scanMatchK->setInitialArguments({match_accumulator});
548    mGrepDriver->makeKernelCall(scanMatchK, {Matches, LineBreakStream, ByteStream}, {});
549    mGrepDriver->LinkFunction(*scanMatchK, "accumulate_match_wrapper", &accumulate_match_wrapper);
550    mGrepDriver->LinkFunction(*scanMatchK, "finalize_match_wrapper", &finalize_match_wrapper);
551
552    mGrepDriver->generatePipelineIR();
553    mGrepDriver->deallocateBuffers();
554    idb->CreateRet(idb->getInt64(0));
555    mGrepDriver->finalizeObject();
556}
557
558
559//
560//  The doGrep methods apply a GrepEngine to a single file, processing the results
561//  differently based on the engine type.
562
563uint64_t GrepEngine::doGrep(const std::string & fileName, const uint32_t fileIdx) {
564    typedef uint64_t (*GrepFunctionType)(bool useMMap, int32_t fileDescriptor);
565    using namespace boost::filesystem;
566    path p(fileName);
567    bool useMMap = mPreferMMap;
568    if (p == "-") useMMap = false;
569    if (!is_regular_file(p)) useMMap = false;
570
571    auto f = reinterpret_cast<GrepFunctionType>(mGrepDriver->getMain());
572
573    int32_t fileDescriptor = openFile(fileName, mResultStrs[fileIdx]);
574    if (fileDescriptor == -1) return 0;
575
576    uint64_t grepResult = f(useMMap, fileDescriptor);
577    close(fileDescriptor);
578    return grepResult;
579}
580
581uint64_t CountOnlyEngine::doGrep(const std::string & fileName, const uint32_t fileIdx) {
582    uint64_t grepResult = GrepEngine::doGrep(fileName, fileIdx);
583    if (mShowFileNames) mResultStrs[fileIdx] << linePrefix(fileName);
584    mResultStrs[fileIdx] << grepResult << "\n";
585    return grepResult;
586}
587
588std::string GrepEngine::linePrefix(std::string fileName) {
589    if (!mShowFileNames) return "";
590    if (fileName == "-") {
591        return mStdinLabel + mFileSuffix;
592    }
593    else {
594        return fileName + mFileSuffix;
595    }
596}
597
598uint64_t MatchOnlyEngine::doGrep(const std::string & fileName, const uint32_t fileIdx) {
599    uint64_t grepResult = GrepEngine::doGrep(fileName, fileIdx);
600    if (grepResult == mRequiredCount) {
601       mResultStrs[fileIdx] << linePrefix(fileName);
602    }
603    return grepResult;
604}
605
606uint64_t EmitMatchesEngine::doGrep(const std::string & fileName, const uint32_t fileIdx) {
607    typedef uint64_t (*GrepFunctionType)(bool useMMap, int32_t fileDescriptor, intptr_t accum_addr);
608    using namespace boost::filesystem;
609    path p(fileName);
610    bool useMMap = mPreferMMap;
611    if (p == "-") useMMap = false;
612    if (!is_regular_file(p)) useMMap = false;
613    auto f = reinterpret_cast<GrepFunctionType>(mGrepDriver->getMain());
614    int32_t fileDescriptor = openFile(fileName, mResultStrs[fileIdx]);
615    if (fileDescriptor == -1) return 0;
616    EmitMatch accum(linePrefix(fileName), mShowLineNumbers, mInitialTab, mResultStrs[fileIdx]);
617    f(useMMap, fileDescriptor, reinterpret_cast<intptr_t>(&accum));
618    close(fileDescriptor);
619    if (accum.mLineCount > 0) grepMatchFound = true;
620    return accum.mLineCount;
621}
622
623// Open a file and return its file desciptor.
624int32_t GrepEngine::openFile(const std::string & fileName, std::ostringstream & msgstrm) {
625    if (fileName == "-") {
626        return STDIN_FILENO;
627    }
628    else {
629        struct stat sb;
630        int32_t fileDescriptor = open(fileName.c_str(), O_RDONLY);
631        if (LLVM_UNLIKELY(fileDescriptor == -1)) {
632            if (!mSuppressFileMessages) {
633                if (errno == EACCES) {
634                    msgstrm << "icgrep: " << fileName << ": Permission denied.\n";
635                }
636                else if (errno == ENOENT) {
637                    msgstrm << "icgrep: " << fileName << ": No such file.\n";
638                }
639                else {
640                    msgstrm << "icgrep: " << fileName << ": Failed.\n";
641                }
642            }
643            return fileDescriptor;
644        }
645        if (stat(fileName.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
646            if (!mSuppressFileMessages) {
647                msgstrm << "icgrep: " << fileName << ": Is a directory.\n";
648            }
649            close(fileDescriptor);
650            return -1;
651        }
652        return fileDescriptor;
653    }
654}
655
656// The process of searching a group of files may use a sequential or a task
657// parallel approach.
658
659void * DoGrepThreadFunction(void *args) {
660    return reinterpret_cast<GrepEngine *>(args)->DoGrepThreadMethod();
661}
662
663bool GrepEngine::searchAllFiles() {
664    const unsigned numOfThreads = std::min(static_cast<unsigned>(Threads), static_cast<unsigned>(inputFiles.size())); 
665    std::vector<pthread_t> threads(numOfThreads);
666
667    for(unsigned long i = 1; i < numOfThreads; ++i) {
668        const int rc = pthread_create(&threads[i], nullptr, DoGrepThreadFunction, (void *)this);
669        if (rc) {
670            llvm::report_fatal_error("Failed to create thread: code " + std::to_string(rc));
671        }
672    }
673    // Main thread also does the work;
674    DoGrepThreadMethod();
675    for(unsigned i = 1; i < numOfThreads; ++i) {
676        void * status = nullptr;
677        const int rc = pthread_join(threads[i], &status);
678        if (rc) {
679            llvm::report_fatal_error("Failed to join thread: code " + std::to_string(rc));
680        }
681    }
682    return grepMatchFound;
683}
684
685
686// DoGrep thread function.
687void * GrepEngine::DoGrepThreadMethod() {
688
689    unsigned fileIdx = mNextFileToGrep++;
690    while (fileIdx < inputFiles.size()) {
691        if (codegen::DebugOptionIsSet(codegen::TraceCounts)) {
692            errs() << "Tracing " << inputFiles[fileIdx] << "\n";
693        }
694        const auto grepResult = doGrep(inputFiles[fileIdx], fileIdx);
695        mFileStatus[fileIdx] = FileStatus::GrepComplete;
696        if (grepResult > 0) {
697            grepMatchFound = true;
698        }
699        if ((mEngineKind == EngineKind::QuietMode) && grepMatchFound) {
700            if (pthread_self() != mEngineThread) {
701                pthread_exit(nullptr);
702            }
703            return nullptr;
704        }
705        fileIdx = mNextFileToGrep++;
706    }
707
708    unsigned printIdx = mNextFileToPrint++;
709    while (printIdx < inputFiles.size()) {
710        const bool readyToPrint = ((printIdx == 0) || (mFileStatus[printIdx - 1] == FileStatus::PrintComplete)) && (mFileStatus[printIdx] == FileStatus::GrepComplete);
711        if (readyToPrint) {
712            const auto output = mResultStrs[printIdx].str();
713            if (!output.empty()) {
714                llvm::outs() << output;
715            }
716            mFileStatus[printIdx] = FileStatus::PrintComplete;
717            printIdx = mNextFileToPrint++;
718        } else {
719            mGrepDriver->performIncrementalCacheCleanupStep();
720        }
721        sched_yield();
722    }
723
724    if (pthread_self() != mEngineThread) {
725        pthread_exit(nullptr);
726    } else {
727        // Always perform one final cache cleanup step.
728        mGrepDriver->performIncrementalCacheCleanupStep();
729    }
730    return nullptr;
731}
732
733   
734   
735InternalSearchEngine::InternalSearchEngine() :
736    mGrepRecordBreak(GrepRecordBreakKind::LF),
737    mCaseInsensitive(false),
738    mGrepDriver(nullptr),
739    grepMatchFound(false) {}
740   
741InternalSearchEngine::~InternalSearchEngine() {
742    delete mGrepDriver;
743}
744
745void InternalSearchEngine::grepCodeGen(re::RE * matchingRE, re::RE * excludedRE, MatchAccumulator * accum) {
746    mGrepDriver = new ParabixDriver("InternalEngine");
747    auto & idb = mGrepDriver->getBuilder();
748    Module * M = idb->getModule();
749   
750    const unsigned encodingBits = 8;
751    const unsigned segmentSize = codegen::BufferSegments * codegen::SegmentSize * codegen::ThreadNum;
752   
753    re::CC * breakCC = nullptr;
754    if (mGrepRecordBreak == GrepRecordBreakKind::Null) {
755        breakCC = re::makeByte(0x0);
756    } else {// if (mGrepRecordBreak == GrepRecordBreakKind::LF)
757        breakCC = re::makeByte(0x0A);
758    }
759    if (matchingRE != nullptr) {
760        matchingRE = resolveCaseInsensitiveMode(matchingRE, mCaseInsensitive);
761        matchingRE = regular_expression_passes(matchingRE);
762        matchingRE = re::exclude_CC(matchingRE, breakCC);
763        matchingRE = resolveAnchors(matchingRE, breakCC);
764        matchingRE = toUTF8(matchingRE);
765    }
766    if (excludedRE != nullptr) {
767        excludedRE = resolveCaseInsensitiveMode(excludedRE, mCaseInsensitive);
768        excludedRE = regular_expression_passes(excludedRE);
769        excludedRE = re::exclude_CC(excludedRE, breakCC);
770        excludedRE = resolveAnchors(excludedRE, breakCC);
771        excludedRE = toUTF8(excludedRE);
772    }
773    Function * mainFunc = cast<Function>(M->getOrInsertFunction("Main", idb->getVoidTy(), idb->getInt8PtrTy(), idb->getSizeTy(), nullptr));
774    mainFunc->setCallingConv(CallingConv::C);
775    auto args = mainFunc->arg_begin();
776    Value * const buffer = &*(args++);
777    buffer->setName("buffer");
778    Value * length = &*(args++);
779    length->setName("length");
780   
781    idb->SetInsertPoint(BasicBlock::Create(M->getContext(), "entry", mainFunc, 0));
782    StreamSetBuffer * ByteStream = mGrepDriver->addBuffer<SourceBuffer>(idb, idb->getStreamSetTy(1, 8));
783    kernel::Kernel * sourceK = mGrepDriver->addKernelInstance<kernel::MemorySourceKernel>(idb, idb->getInt8PtrTy());
784    sourceK->setInitialArguments({buffer, length});
785    mGrepDriver->makeKernelCall(sourceK, {}, {ByteStream});
786    StreamSetBuffer * BasisBits = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(8, 1), segmentSize);
787    kernel::Kernel * s2pk = mGrepDriver->addKernelInstance<kernel::S2PKernel>(idb);
788    mGrepDriver->makeKernelCall(s2pk, {ByteStream}, {BasisBits});
789   
790    StreamSetBuffer * RecordBreakStream = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize);
791    std::string RBname = (mGrepRecordBreak == GrepRecordBreakKind::Null) ? "Null" : "LF";
792    kernel::Kernel * breakK = mGrepDriver->addKernelInstance<kernel::ParabixCharacterClassKernelBuilder>(idb, RBname, std::vector<re::CC *>{breakCC}, 8);
793    mGrepDriver->makeKernelCall(breakK, {BasisBits}, {RecordBreakStream});
794   
795   
796    std::vector<std::string> externalStreamNames;
797    StreamSetBuffer * MatchingRecords = nullptr;
798    if (matchingRE != nullptr) {
799        StreamSetBuffer * MatchResults = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize);
800        kernel::Kernel * includeK = mGrepDriver->addKernelInstance<kernel::ICGrepKernel>(idb, matchingRE, externalStreamNames);
801        mGrepDriver->makeKernelCall(includeK, {BasisBits}, {MatchResults});
802        MatchingRecords = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize);
803        kernel::Kernel * matchedLinesK = mGrepDriver->addKernelInstance<kernel::MatchedLinesKernel>(idb);
804        mGrepDriver->makeKernelCall(matchedLinesK, {MatchResults, RecordBreakStream}, {MatchingRecords});
805    }
806    if (excludedRE != nullptr) {
807        StreamSetBuffer * ExcludedResults = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize);
808        kernel::Kernel * excludeK = mGrepDriver->addKernelInstance<kernel::ICGrepKernel>(idb, excludedRE, externalStreamNames);
809        mGrepDriver->makeKernelCall(excludeK, {BasisBits}, {ExcludedResults});
810        StreamSetBuffer * ExcludedRecords = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize);
811        kernel::Kernel * matchedLinesK = mGrepDriver->addKernelInstance<kernel::MatchedLinesKernel>(idb);
812        mGrepDriver->makeKernelCall(matchedLinesK, {ExcludedResults, RecordBreakStream}, {ExcludedRecords});
813
814        kernel::Kernel * invertK = mGrepDriver->addKernelInstance<kernel::InvertMatchesKernel>(idb);
815        if (matchingRE != nullptr) {
816            StreamSetBuffer * nonExcluded = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize);
817            mGrepDriver->makeKernelCall(invertK, {ExcludedRecords, RecordBreakStream}, {nonExcluded});
818            StreamSetBuffer * included = MatchingRecords;
819            MatchingRecords = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize);
820            kernel::Kernel * streamsIntersectK = mGrepDriver->addKernelInstance<kernel::StreamsIntersect>(idb, 1, 2);
821            mGrepDriver->makeKernelCall(streamsIntersectK, {included, nonExcluded}, {MatchingRecords});
822        }
823        else {
824            MatchingRecords = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize);
825            mGrepDriver->makeKernelCall(invertK, {ExcludedRecords, RecordBreakStream}, {MatchingRecords});
826        }
827    }
828    kernel::Kernel * scanMatchK = mGrepDriver->addKernelInstance<kernel::ScanMatchKernel>(idb);
829    scanMatchK->setInitialArguments({ConstantInt::get(idb->getIntAddrTy(), reinterpret_cast<intptr_t>(accum))});
830    mGrepDriver->makeKernelCall(scanMatchK, {MatchingRecords, RecordBreakStream, ByteStream}, {});
831    mGrepDriver->LinkFunction(*scanMatchK, "accumulate_match_wrapper", &accumulate_match_wrapper);
832    mGrepDriver->LinkFunction(*scanMatchK, "finalize_match_wrapper", &finalize_match_wrapper);
833    mGrepDriver->generatePipelineIR();
834    mGrepDriver->deallocateBuffers();
835    idb->CreateRetVoid();
836    mGrepDriver->finalizeObject();
837}
838
839void InternalSearchEngine::doGrep(const char * search_buffer, size_t bufferLength) {
840    typedef void (*GrepFunctionType)(const char * buffer, const size_t length);
841    auto f = reinterpret_cast<GrepFunctionType>(mGrepDriver->getMain());
842    f(search_buffer, bufferLength);
843}
844
845}
Note: See TracBrowser for help on using the repository browser.