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

Last change on this file since 5894 was 5894, checked in by cameron, 17 months ago

Line break controls for Unicode/LF/Null - initial check in

File size: 28.1 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 "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/UCD_property_kernel.h>
16#include <kernels/grapheme_kernel.h>
17#include <kernels/linebreak_kernel.h>
18#include <kernels/streams_merge.h>
19#include <kernels/source_kernel.h>
20#include <kernels/s2p_kernel.h>
21#include <kernels/scanmatchgen.h>
22#include <kernels/streamset.h>
23#include <kernels/until_n.h>
24#include <kernels/kernel_builder.h>
25#include <pablo/pablo_kernel.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/re_toolchain.h>
31#include <toolchain/toolchain.h>
32#include <re/re_name_resolve.h>
33#include <re/re_name_gather.h>
34#include <re/re_collect_unicodesets.h>
35#include <re/re_multiplex.h>
36#include <re/grapheme_clusters.h>
37#include <re/printer_re.h>
38#include <toolchain/toolchain.h>
39#include <toolchain/cpudriver.h>
40#include <iostream>
41#include <cc/multiplex_CCs.h>
42#include <llvm/Support/raw_ostream.h>
43#include <util/aligned_allocator.h>
44#include <sys/stat.h>
45#include <fcntl.h>
46#include <errno.h>
47#include <llvm/ADT/STLExtras.h> // for make_unique
48#include <llvm/Support/CommandLine.h>
49#include <llvm/Support/Debug.h>
50#include <sched.h>
51
52using namespace parabix;
53using namespace llvm;
54using namespace cc;
55using namespace kernel;
56
57static cl::opt<int> Threads("t", cl::desc("Total number of threads."), cl::init(2));
58static cl::opt<bool> PabloTransposition("enable-pablo-s2p", cl::desc("Enable experimental pablo transposition."));
59static cl::opt<bool> CC_Multiplexing("CC-multiplexing", cl::desc("Enable CC multiplexing."), cl::init(false));
60static cl::opt<bool> PropertyKernels("enable-property-kernels", cl::desc("Enable Unicode property kernels."), cl::init(false));
61
62
63namespace grep {
64   
65
66void accumulate_match_wrapper(intptr_t accum_addr, const size_t lineNum, char * line_start, char * line_end) {
67    reinterpret_cast<MatchAccumulator *>(accum_addr)->accumulate_match(lineNum, line_start, line_end);
68}
69
70void finalize_match_wrapper(intptr_t accum_addr, char * buffer_end) {
71    reinterpret_cast<MatchAccumulator *>(accum_addr)->finalize_match(buffer_end);
72}
73
74void grepBuffer(re::RE * pattern, const char * search_buffer, size_t bufferLength, MatchAccumulator * accum) {
75    const unsigned segmentSize = codegen::BufferSegments * codegen::SegmentSize * codegen::ThreadNum;
76   
77    pattern = resolveCaseInsensitiveMode(pattern, false);
78    pattern = regular_expression_passes(pattern);
79   
80   
81    ParabixDriver pxDriver("codepointEngine");
82    auto & idb = pxDriver.getBuilder();
83    Module * M = idb->getModule();
84   
85    Function * mainFunc = cast<Function>(M->getOrInsertFunction("Main", idb->getVoidTy(), idb->getInt8PtrTy(), idb->getSizeTy(), nullptr));
86    mainFunc->setCallingConv(CallingConv::C);
87    auto args = mainFunc->arg_begin();
88    Value * const buffer = &*(args++);
89    buffer->setName("buffer");
90    Value * length = &*(args++);
91    length->setName("length");
92   
93    idb->SetInsertPoint(BasicBlock::Create(M->getContext(), "entry", mainFunc, 0));
94   
95    StreamSetBuffer * ByteStream = pxDriver.addBuffer<SourceBuffer>(idb, idb->getStreamSetTy(1, 8));
96    kernel::Kernel * sourceK = pxDriver.addKernelInstance<kernel::MemorySourceKernel>(idb, idb->getInt8PtrTy());
97    sourceK->setInitialArguments({buffer, length});
98    pxDriver.makeKernelCall(sourceK, {}, {ByteStream});
99   
100   
101    StreamSetBuffer * BasisBits = pxDriver.addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(8, 1), segmentSize);
102    kernel::Kernel * s2pk = pxDriver.addKernelInstance<kernel::S2PKernel>(idb);
103    pxDriver.makeKernelCall(s2pk, {ByteStream}, {BasisBits});
104   
105    StreamSetBuffer * LineFeedStream = pxDriver.addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize);
106    kernel::Kernel * linefeedK = pxDriver.addKernelInstance<kernel::LineFeedKernelBuilder>(idb, Binding{idb->getStreamSetTy(8), "basis", FixedRate(), Principal()});
107    pxDriver.makeKernelCall(linefeedK, {BasisBits}, {LineFeedStream});
108   
109    StreamSetBuffer * LineBreakStream = pxDriver.addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize);
110   
111    kernel::Kernel * requiredStreamsK = pxDriver.addKernelInstance<kernel::RequiredStreams_UTF8>(idb);
112    StreamSetBuffer * RequiredStreams = pxDriver.addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize);
113    pxDriver.makeKernelCall(requiredStreamsK, {BasisBits, LineFeedStream}, {RequiredStreams, LineBreakStream});
114   
115    StreamSetBuffer * MatchResults = pxDriver.addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize);
116    kernel::Kernel * icgrepK = pxDriver.addKernelInstance<kernel::ICGrepKernel>(idb, pattern, std::vector<std::string>{"UTF8_LB", "UTF8_nonfinal"});
117    pxDriver.makeKernelCall(icgrepK, {BasisBits, LineBreakStream, RequiredStreams}, {MatchResults});
118   
119    StreamSetBuffer * MatchedLines = pxDriver.addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize);
120    kernel::Kernel * matchedLinesK = pxDriver.addKernelInstance<kernel::MatchedLinesKernel>(idb);
121    pxDriver.makeKernelCall(matchedLinesK, {MatchResults, LineBreakStream}, {MatchedLines});
122   
123    kernel::Kernel * scanMatchK = pxDriver.addKernelInstance<kernel::ScanMatchKernel>(idb);
124    scanMatchK->setInitialArguments({ConstantInt::get(idb->getIntAddrTy(), reinterpret_cast<intptr_t>(accum))});
125    pxDriver.makeKernelCall(scanMatchK, {MatchedLines, LineBreakStream, ByteStream}, {});
126    pxDriver.LinkFunction(*scanMatchK, "accumulate_match_wrapper", &accumulate_match_wrapper);
127    pxDriver.LinkFunction(*scanMatchK, "finalize_match_wrapper", &finalize_match_wrapper);
128   
129    pxDriver.generatePipelineIR();
130    pxDriver.deallocateBuffers();
131    idb->CreateRetVoid();
132    pxDriver.finalizeObject();
133   
134    typedef void (*GrepFunctionType)(const char * buffer, const size_t length);
135    auto f = reinterpret_cast<GrepFunctionType>(pxDriver.getMain());
136    f(search_buffer, bufferLength);
137}
138
139
140
141// Grep Engine construction and initialization.
142
143GrepEngine::GrepEngine() :
144    mGrepDriver(nullptr),
145    mNextFileToGrep(0),
146    mNextFileToPrint(0),
147    grepMatchFound(false),
148    mGrepRecordBreak(GrepRecordBreakKind::Unicode),
149    mMoveMatchesToEOL(true),
150    mEngineThread(pthread_self()) {}
151
152GrepEngine::~GrepEngine() {
153    delete mGrepDriver;
154}
155
156QuietModeEngine::QuietModeEngine() : GrepEngine() {
157    mMoveMatchesToEOL = false;
158}
159
160MatchOnlyEngine::MatchOnlyEngine(bool showFilesWithoutMatch) :
161    GrepEngine(), mRequiredCount(showFilesWithoutMatch) {
162    mFileSuffix = NullFlag ? std::string("\0", 1) : "\n";
163    mMoveMatchesToEOL = false;
164}
165
166CountOnlyEngine::CountOnlyEngine() : GrepEngine() {
167    mFileSuffix = ":";
168}
169
170EmitMatchesEngine::EmitMatchesEngine() : GrepEngine() {
171    mFileSuffix = InitialTabFlag ? "\t:" : ":";
172    if (LineRegexpFlag) mMoveMatchesToEOL = false;
173}
174
175   
176void GrepEngine::setRecordBreak(GrepRecordBreakKind b) {
177    mGrepRecordBreak = b;
178}
179
180void GrepEngine::initFileResult(std::vector<std::string> & filenames) {
181    const unsigned n = filenames.size();
182    mResultStrs.resize(n);
183    mFileStatus.resize(n, FileStatus::Pending);
184    inputFiles = filenames;
185}
186
187// Code Generation
188//
189// All engines share a common pipeline to compute a stream of Matches from a given input Bytestream.
190
191unsigned LLVM_READNONE calculateMaxCountRate(const std::unique_ptr<kernel::KernelBuilder> & b) {
192    const unsigned packSize = b->getSizeTy()->getBitWidth();
193    return (packSize * packSize) / b->getBitBlockWidth();
194}
195
196std::pair<StreamSetBuffer *, StreamSetBuffer *> GrepEngine::grepPipeline(std::vector<re::RE *> & REs, StreamSetBuffer * ByteStream) {
197    auto & idb = mGrepDriver->getBuilder();
198    const unsigned segmentSize = codegen::SegmentSize;
199    const unsigned bufferSegments = codegen::BufferSegments * codegen::ThreadNum;
200    // TODO: until we automate stream buffer sizing, use this calculation to determine how large our matches buffer needs to be.
201    const unsigned baseBufferSize = segmentSize * (MaxCountFlag > 0 ? (std::max(bufferSegments, calculateMaxCountRate(idb))) : bufferSegments);
202    const unsigned encodingBits = 8;
203   
204   
205    //  Regular Expression Processing and Analysis Phase
206    const auto nREs = REs.size();
207    bool hasGCB[nREs];
208    bool anyGCB = false;
209   
210    std::set<re::Name *> UnicodeProperties;
211   
212    re::CC * breakCC = nullptr;
213    std::string breakName;
214    if (mGrepRecordBreak == GrepRecordBreakKind::Unicode) {
215        breakCC = re::makeCC(re::makeCC(0x0A, 0x0D), re::makeCC(re::makeCC(0x85), re::makeCC(0x2028, 0x2029)));
216        breakName = "UTF8_LB";
217    } else if (mGrepRecordBreak == GrepRecordBreakKind::Null) {
218        breakCC = re::makeByte(0);  // Null
219        breakName = "NULL";
220    } else {
221        breakCC = re::makeByte(0x0A); // LF
222        breakName = "LF";
223    }
224
225    for(unsigned i = 0; i < nREs; ++i) {
226        REs[i] = resolveModesAndExternalSymbols(REs[i]);
227        REs[i] = re::exclude_CC(REs[i], breakCC);
228        if (mGrepRecordBreak != GrepRecordBreakKind::Unicode) {
229            REs[i] = resolveAnchors(REs[i], breakCC);
230        }
231        re::gatherUnicodeProperties(REs[i], UnicodeProperties);
232        REs[i] = regular_expression_passes(REs[i]);
233        hasGCB[i] = hasGraphemeClusterBoundary(REs[i]);
234        anyGCB |= hasGCB[i];
235    }
236   
237    StreamSetBuffer * BasisBits = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(encodingBits, 1), baseBufferSize);
238    kernel::Kernel * s2pk = nullptr;
239    if (PabloTransposition) {
240        s2pk = mGrepDriver->addKernelInstance<kernel::S2P_PabloKernel>(idb);
241    }
242    else {
243        s2pk = mGrepDriver->addKernelInstance<kernel::S2PKernel>(idb);
244    }
245    mGrepDriver->makeKernelCall(s2pk, {ByteStream}, {BasisBits});
246
247    StreamSetBuffer * LineBreakStream = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
248    StreamSetBuffer * RequiredStreams = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
249    StreamSetBuffer * UnicodeLB = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
250
251    StreamSetBuffer * LineFeedStream = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
252    kernel::Kernel * linefeedK = mGrepDriver->addKernelInstance<kernel::LineFeedKernelBuilder>(idb, Binding{idb->getStreamSetTy(8), "basis", FixedRate(), Principal()});
253    mGrepDriver->makeKernelCall(linefeedK, {BasisBits}, {LineFeedStream});
254   
255    kernel::Kernel * requiredStreamsK = mGrepDriver->addKernelInstance<kernel::RequiredStreams_UTF8>(idb);
256    mGrepDriver->makeKernelCall(requiredStreamsK, {BasisBits, LineFeedStream}, {RequiredStreams, UnicodeLB});
257
258    if (mGrepRecordBreak == GrepRecordBreakKind::LF) {
259        LineBreakStream = LineFeedStream;
260    } else if (mGrepRecordBreak == GrepRecordBreakKind::Null) {
261        kernel::Kernel * breakK = mGrepDriver->addKernelInstance<kernel::ParabixCharacterClassKernelBuilder>(idb, "Null", std::vector<re::CC *>{breakCC}, 8);
262        mGrepDriver->makeKernelCall(breakK, {BasisBits}, {LineBreakStream});
263    } else {
264        LineBreakStream = UnicodeLB;
265    }
266   
267    std::map<std::string, StreamSetBuffer *> propertyStream;
268    if (PropertyKernels) {
269        for (auto p : UnicodeProperties) {
270            auto name = p->getFullName();
271            StreamSetBuffer * s = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
272            propertyStream.emplace(std::make_pair(name, s));
273            kernel::Kernel * propertyK = mGrepDriver->addKernelInstance<kernel::UnicodePropertyKernelBuilder>(idb, p);
274            mGrepDriver->makeKernelCall(propertyK, {BasisBits}, {s});
275        }
276    }
277    StreamSetBuffer * GCB_stream = nullptr;
278    if (anyGCB) {
279        GCB_stream = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
280        kernel::Kernel * gcbK = mGrepDriver->addKernelInstance<kernel::GraphemeClusterBreakKernel>(idb);
281        mGrepDriver->makeKernelCall(gcbK, {BasisBits, RequiredStreams}, {GCB_stream});
282    }
283
284    std::vector<StreamSetBuffer *> MatchResultsBufs(nREs);
285    for(unsigned i = 0; i < nREs; ++i) {
286        std::vector<std::string> externalStreamNames = std::vector<std::string>{"UTF8_LB", "UTF8_nonfinal"};
287        std::vector<StreamSetBuffer *> icgrepInputSets = {BasisBits, LineBreakStream, RequiredStreams};
288        std::set<re::Name *> UnicodeProperties;
289        if (PropertyKernels) {
290            re::gatherUnicodeProperties(REs[i], UnicodeProperties);
291            for (auto p : UnicodeProperties) {
292                auto name = p->getFullName();
293                auto f = propertyStream.find(name);
294                if (f == propertyStream.end()) report_fatal_error(name + " not found\n");
295                externalStreamNames.push_back(name);
296                icgrepInputSets.push_back(f->second);
297            }
298        }
299        if (hasGCB[i]) {
300            externalStreamNames.push_back("\\b{g}");
301            icgrepInputSets.push_back(GCB_stream);
302        }
303        if (CC_Multiplexing) {
304            const auto UnicodeSets = re::collectUnicodeSets(REs[i], std::set<re::Name *>({re::makeZeroWidth("\\b{g}")}));
305            StreamSetBuffer * const MatchResults = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
306            if (UnicodeSets.size() <= 1) {
307                kernel::Kernel * icgrepK = mGrepDriver->addKernelInstance<kernel::ICGrepKernel>(idb, REs[i], externalStreamNames);
308                mGrepDriver->makeKernelCall(icgrepK, icgrepInputSets, {MatchResults});
309                MatchResultsBufs[i] = MatchResults;
310            } else {
311                mpx = make_unique<MultiplexedAlphabet>("mpx", UnicodeSets);
312                REs[i] = transformCCs(mpx.get(), REs[i]);
313                std::vector<re::CC *> mpx_basis = mpx->getMultiplexedCCs();
314                auto numOfCharacterClasses = mpx_basis.size();
315                StreamSetBuffer * CharClasses = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(numOfCharacterClasses), baseBufferSize);
316                kernel::Kernel * ccK = mGrepDriver->addKernelInstance<kernel::CharClassesKernel>(idb, std::move(mpx_basis));
317                mGrepDriver->makeKernelCall(ccK, {BasisBits}, {CharClasses});
318//                kernel::Kernel * ccK = mGrepDriver->addKernelInstance<kernel::CharClassesKernel>(idb, std::move(mpx_basis), true);
319//                mGrepDriver->makeKernelCall(ccK, {ByteStream}, {CharClasses});
320                kernel::Kernel * icgrepK = mGrepDriver->addKernelInstance<kernel::ICGrepKernel>(idb, REs[i], externalStreamNames, std::vector<cc::Alphabet *>{mpx.get()});
321                icgrepInputSets.push_back(CharClasses);
322                mGrepDriver->makeKernelCall(icgrepK, icgrepInputSets, {MatchResults});
323                MatchResultsBufs[i] = MatchResults;
324            }
325        } else {
326            StreamSetBuffer * MatchResults = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
327            kernel::Kernel * icgrepK = mGrepDriver->addKernelInstance<kernel::ICGrepKernel>(idb, REs[i], externalStreamNames);
328            mGrepDriver->makeKernelCall(icgrepK, icgrepInputSets, {MatchResults});
329            MatchResultsBufs[i] = MatchResults;
330        }
331    }
332    StreamSetBuffer * MergedResults = MatchResultsBufs[0];
333    if (REs.size() > 1) {
334        MergedResults = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
335        kernel::Kernel * streamsMergeK = mGrepDriver->addKernelInstance<kernel::StreamsMerge>(idb, 1, REs.size());
336        mGrepDriver->makeKernelCall(streamsMergeK, MatchResultsBufs, {MergedResults});
337    }
338    StreamSetBuffer * Matches = MergedResults;
339
340    if (mMoveMatchesToEOL) {
341        StreamSetBuffer * OriginalMatches = Matches;
342        kernel::Kernel * matchedLinesK = mGrepDriver->addKernelInstance<kernel::MatchedLinesKernel>(idb);
343        Matches = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
344        mGrepDriver->makeKernelCall(matchedLinesK, {OriginalMatches, LineBreakStream}, {Matches});
345    }
346
347    if (InvertMatchFlag) {
348        kernel::Kernel * invertK = mGrepDriver->addKernelInstance<kernel::InvertMatchesKernel>(idb);
349        StreamSetBuffer * OriginalMatches = Matches;
350        Matches = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
351        mGrepDriver->makeKernelCall(invertK, {OriginalMatches, LineBreakStream}, {Matches});
352    }
353    if (MaxCountFlag > 0) {
354        kernel::Kernel * untilK = mGrepDriver->addKernelInstance<kernel::UntilNkernel>(idb);
355        untilK->setInitialArguments({idb->getSize(MaxCountFlag)});
356        StreamSetBuffer * const AllMatches = Matches;
357        Matches = mGrepDriver->addBuffer<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), baseBufferSize);
358        mGrepDriver->makeKernelCall(untilK, {AllMatches}, {Matches});
359    }
360    return std::pair<StreamSetBuffer *, StreamSetBuffer *>(LineBreakStream, Matches);
361}
362
363// The QuietMode, MatchOnly and CountOnly engines share a common code generation main function,
364// which returns a count of the matches found (possibly subject to a MaxCount).
365//
366
367void GrepEngine::grepCodeGen(std::vector<re::RE *> REs) {
368
369    assert (mGrepDriver == nullptr);
370    mGrepDriver = new ParabixDriver("engine");
371    auto & idb = mGrepDriver->getBuilder();
372    Module * M = idb->getModule();
373
374    const unsigned encodingBits = 8;
375
376    Function * mainFunc = cast<Function>(M->getOrInsertFunction("Main", idb->getInt64Ty(), idb->getInt32Ty(), nullptr));
377    mainFunc->setCallingConv(CallingConv::C);
378    idb->SetInsertPoint(BasicBlock::Create(M->getContext(), "entry", mainFunc, 0));
379    auto args = mainFunc->arg_begin();
380
381    Value * const fileDescriptor = &*(args++);
382    fileDescriptor->setName("fileDescriptor");
383
384    StreamSetBuffer * ByteStream = mGrepDriver->addBuffer<SourceBuffer>(idb, idb->getStreamSetTy(1, encodingBits));
385    kernel::Kernel * sourceK = mGrepDriver->addKernelInstance<kernel::FDSourceKernel>(idb);
386    sourceK->setInitialArguments({fileDescriptor});
387    mGrepDriver->makeKernelCall(sourceK, {}, {ByteStream});
388
389    StreamSetBuffer * LineBreakStream;
390    StreamSetBuffer * Matches;
391    std::tie(LineBreakStream, Matches) = grepPipeline(REs, ByteStream);
392
393    kernel::Kernel * matchCountK = mGrepDriver->addKernelInstance<kernel::PopcountKernel>(idb);
394    mGrepDriver->makeKernelCall(matchCountK, {Matches}, {});
395    mGrepDriver->generatePipelineIR();
396    idb->setKernel(matchCountK);
397    Value * matchedLineCount = idb->getAccumulator("countResult");
398    matchedLineCount = idb->CreateZExt(matchedLineCount, idb->getInt64Ty());
399    mGrepDriver->deallocateBuffers();
400    idb->CreateRet(matchedLineCount);
401    mGrepDriver->finalizeObject();
402}
403
404//
405// The EmitMatches engine uses an EmitMatchesAccumulator object to concatenate together
406// matched lines.
407
408class EmitMatch : public MatchAccumulator {
409    friend class EmitMatchesEngine;
410public:
411    EmitMatch(std::string linePrefix, std::ostringstream & strm) : mLinePrefix(linePrefix), mLineCount(0), mTerminated(true), mResultStr(strm) {}
412    void accumulate_match(const size_t lineNum, char * line_start, char * line_end) override;
413    void finalize_match(char * buffer_end) override;
414protected:
415    std::string mLinePrefix;
416    size_t mLineCount;
417    bool mTerminated;
418    std::ostringstream & mResultStr;
419};
420
421//
422//  Default Report Match:  lines are emitted with whatever line terminators are found in the
423//  input.  However, if the final line is not terminated, a new line is appended.
424//
425void EmitMatch::accumulate_match (const size_t lineNum, char * line_start, char * line_end) {
426    if (WithFilenameFlag) {
427        mResultStr << mLinePrefix;
428    }
429    if (LineNumberFlag) {
430        // Internally line numbers are counted from 0.  For display, adjust
431        // the line number so that lines are numbered from 1.
432        if (InitialTabFlag) {
433            mResultStr << lineNum+1 << "\t:";
434        }
435        else {
436            mResultStr << lineNum+1 << ":";
437        }
438    }
439    size_t bytes = line_end - line_start + 1;
440    mResultStr.write(line_start, bytes);
441    mLineCount++;
442    unsigned last_byte = *line_end;
443    mTerminated = (last_byte >= 0x0A) && (last_byte <= 0x0D);
444    if (LLVM_UNLIKELY(!mTerminated)) {
445        if (last_byte == 0x85) {  //  Possible NEL terminator.
446            mTerminated = (bytes >= 2) && (static_cast<unsigned>(line_end[-1]) == 0xC2);
447        }
448        else {
449            // Possible LS or PS terminators.
450            mTerminated = (bytes >= 3) && (static_cast<unsigned>(line_end[-2]) == 0xE2)
451                                       && (static_cast<unsigned>(line_end[-1]) == 0x80)
452                                       && ((last_byte == 0xA8) || (last_byte == 0xA9));
453        }
454    }
455}
456
457void EmitMatch::finalize_match(char * buffer_end) {
458    if (!mTerminated) mResultStr << "\n";
459}
460
461void EmitMatchesEngine::grepCodeGen(std::vector<re::RE *> REs) {
462    assert (mGrepDriver == nullptr);
463    mGrepDriver = new ParabixDriver("engine");
464    auto & idb = mGrepDriver->getBuilder();
465    Module * M = idb->getModule();
466
467    const unsigned encodingBits = 8;
468
469    Function * mainFunc = cast<Function>(M->getOrInsertFunction("Main", idb->getInt64Ty(), idb->getInt32Ty(), idb->getIntAddrTy(), nullptr));
470    mainFunc->setCallingConv(CallingConv::C);
471    idb->SetInsertPoint(BasicBlock::Create(M->getContext(), "entry", mainFunc, 0));
472    auto args = mainFunc->arg_begin();
473
474    Value * const fileDescriptor = &*(args++);
475    fileDescriptor->setName("fileDescriptor");
476    Value * match_accumulator = &*(args++);
477    match_accumulator->setName("match_accumulator");
478
479    StreamSetBuffer * ByteStream = mGrepDriver->addBuffer<SourceBuffer>(idb, idb->getStreamSetTy(1, encodingBits));
480    kernel::Kernel * sourceK = mGrepDriver->addKernelInstance<kernel::FDSourceKernel>(idb);
481    sourceK->setInitialArguments({fileDescriptor});
482    mGrepDriver->makeKernelCall(sourceK, {}, {ByteStream});
483
484    StreamSetBuffer * LineBreakStream;
485    StreamSetBuffer * Matches;
486    std::tie(LineBreakStream, Matches) = grepPipeline(REs, ByteStream);
487
488    kernel::Kernel * scanMatchK = mGrepDriver->addKernelInstance<kernel::ScanMatchKernel>(idb);
489    scanMatchK->setInitialArguments({match_accumulator});
490    mGrepDriver->makeKernelCall(scanMatchK, {Matches, LineBreakStream, ByteStream}, {});
491    mGrepDriver->LinkFunction(*scanMatchK, "accumulate_match_wrapper", &accumulate_match_wrapper);
492    mGrepDriver->LinkFunction(*scanMatchK, "finalize_match_wrapper", &finalize_match_wrapper);
493
494    mGrepDriver->generatePipelineIR();
495    mGrepDriver->deallocateBuffers();
496    idb->CreateRet(idb->getInt64(0));
497    mGrepDriver->finalizeObject();
498}
499
500
501//
502//  The doGrep methods apply a GrepEngine to a single file, processing the results
503//  differently based on the engine type.
504
505uint64_t GrepEngine::doGrep(const std::string & fileName, const uint32_t fileIdx) {
506    typedef uint64_t (*GrepFunctionType)(int32_t fileDescriptor);
507    auto f = reinterpret_cast<GrepFunctionType>(mGrepDriver->getMain());
508
509    int32_t fileDescriptor = openFile(fileName, mResultStrs[fileIdx]);
510    if (fileDescriptor == -1) return 0;
511
512    uint64_t grepResult = f(fileDescriptor);
513    close(fileDescriptor);
514    return grepResult;
515}
516
517uint64_t CountOnlyEngine::doGrep(const std::string & fileName, const uint32_t fileIdx) {
518    uint64_t grepResult = GrepEngine::doGrep(fileName, fileIdx);
519    if (WithFilenameFlag) mResultStrs[fileIdx] << linePrefix(fileName);
520    mResultStrs[fileIdx] << grepResult << "\n";
521    return grepResult;
522}
523
524std::string GrepEngine::linePrefix(std::string fileName) {
525    if (fileName == "-") {
526        return LabelFlag + mFileSuffix;
527    }
528    else {
529        return fileName + mFileSuffix;
530    }
531}
532
533uint64_t MatchOnlyEngine::doGrep(const std::string & fileName, const uint32_t fileIdx) {
534    uint64_t grepResult = GrepEngine::doGrep(fileName, fileIdx);
535    if (grepResult == mRequiredCount) {
536       mResultStrs[fileIdx] << linePrefix(fileName);
537    }
538    return grepResult;
539}
540
541uint64_t EmitMatchesEngine::doGrep(const std::string & fileName, const uint32_t fileIdx) {
542    typedef uint64_t (*GrepFunctionType)(int32_t fileDescriptor, intptr_t accum_addr);
543    auto f = reinterpret_cast<GrepFunctionType>(mGrepDriver->getMain());
544
545    int32_t fileDescriptor = openFile(fileName, mResultStrs[fileIdx]);
546    if (fileDescriptor == -1) return 0;
547    EmitMatch accum(linePrefix(fileName), mResultStrs[fileIdx]);
548    f(fileDescriptor, reinterpret_cast<intptr_t>(&accum));
549    close(fileDescriptor);
550    if (accum.mLineCount > 0) grepMatchFound = true;
551    return accum.mLineCount;
552}
553
554// Open a file and return its file desciptor.
555int32_t GrepEngine::openFile(const std::string & fileName, std::ostringstream & msgstrm) {
556    if (fileName == "-") {
557        return STDIN_FILENO;
558    }
559    else {
560        struct stat sb;
561        int32_t fileDescriptor = open(fileName.c_str(), O_RDONLY);
562        if (LLVM_UNLIKELY(fileDescriptor == -1)) {
563            if (!NoMessagesFlag) {
564                if (errno == EACCES) {
565                    msgstrm << "icgrep: " << fileName << ": Permission denied.\n";
566                }
567                else if (errno == ENOENT) {
568                    msgstrm << "icgrep: " << fileName << ": No such file.\n";
569                }
570                else {
571                    msgstrm << "icgrep: " << fileName << ": Failed.\n";
572                }
573            }
574            return fileDescriptor;
575        }
576        if (stat(fileName.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
577            if (!NoMessagesFlag) {
578                msgstrm << "icgrep: " << fileName << ": Is a directory.\n";
579            }
580            close(fileDescriptor);
581            return -1;
582        }
583        return fileDescriptor;
584    }
585}
586
587// The process of searching a group of files may use a sequential or a task
588// parallel approach.
589
590void * DoGrepThreadFunction(void *args) {
591    return reinterpret_cast<GrepEngine *>(args)->DoGrepThreadMethod();
592}
593
594bool GrepEngine::searchAllFiles() {
595    const unsigned numOfThreads = std::min(static_cast<unsigned>(Threads), static_cast<unsigned>(inputFiles.size())); 
596    std::vector<pthread_t> threads(numOfThreads);
597
598    for(unsigned long i = 1; i < numOfThreads; ++i) {
599        const int rc = pthread_create(&threads[i], nullptr, DoGrepThreadFunction, (void *)this);
600        if (rc) {
601            llvm::report_fatal_error("Failed to create thread: code " + std::to_string(rc));
602        }
603    }
604    // Main thread also does the work;
605
606    DoGrepThreadMethod();
607    for(unsigned i = 1; i < numOfThreads; ++i) {
608        void * status = nullptr;
609        const int rc = pthread_join(threads[i], &status);
610        if (rc) {
611            llvm::report_fatal_error("Failed to join thread: code " + std::to_string(rc));
612        }
613    }
614    return grepMatchFound;
615}
616
617
618// DoGrep thread function.
619void * GrepEngine::DoGrepThreadMethod() {
620
621    unsigned fileIdx = mNextFileToGrep++;
622    while (fileIdx < inputFiles.size()) {
623        const auto grepResult = doGrep(inputFiles[fileIdx], fileIdx);
624        mFileStatus[fileIdx] = FileStatus::GrepComplete;
625        if (grepResult > 0) {
626            grepMatchFound = true;
627        }
628        if (QuietMode && grepMatchFound) {
629            if (pthread_self() != mEngineThread) {
630                pthread_exit(nullptr);
631            }
632            return nullptr;
633        }
634        fileIdx = mNextFileToGrep++;
635    }
636
637    unsigned printIdx = mNextFileToPrint++;
638    while (printIdx < inputFiles.size()) {
639        const bool readyToPrint = ((printIdx == 0) || (mFileStatus[printIdx - 1] == FileStatus::PrintComplete)) && (mFileStatus[printIdx] == FileStatus::GrepComplete);
640        if (readyToPrint) {
641            const auto output = mResultStrs[printIdx].str();
642            if (!output.empty()) {
643                llvm::outs() << output;
644            }
645            mFileStatus[printIdx] = FileStatus::PrintComplete;
646            printIdx = mNextFileToPrint++;
647        } else {
648            mGrepDriver->performIncrementalCacheCleanupStep();
649        }
650        sched_yield();
651    }
652
653    if (pthread_self() != mEngineThread) {
654        pthread_exit(nullptr);
655    } else {
656        // Always perform one final cache cleanup step.
657        mGrepDriver->performIncrementalCacheCleanupStep();
658    }
659    return nullptr;
660}
661
662}
Note: See TracBrowser for help on using the repository browser.