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

Last change on this file since 5952 was 5952, checked in by cameron, 11 months ago

Use AlignedAllocator? when boost::align unavailable (Jenkins test server).

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