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

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

Bug fix for binary detection/abort

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