source: icGREP/icgrep-devel/icgrep/u8u16.cpp @ 5021

Last change on this file since 5021 was 5021, checked in by cameron, 18 months ago

Large file fix: use boost mapped_file_source

File size: 16.9 KB
Line 
1/*
2 *  Copyright (c) 2015 International Characters.
3 *  This software is licensed to the public under the Open Software License 3.0.
4 *  icgrep is a trademark of International Characters.
5 */
6
7#include <string>
8#include <iostream>
9#include <fstream>
10#include <sstream>
11
12#include <llvm/IR/Function.h>
13#include <llvm/IR/Module.h>
14#include <llvm/ExecutionEngine/ExecutionEngine.h>
15#include <llvm/ExecutionEngine/MCJIT.h>
16#include <llvm/IRReader/IRReader.h>
17#include <llvm/IR/Verifier.h>
18#include <llvm/Support/Debug.h>
19
20#include <llvm/Support/CommandLine.h>
21#include <llvm/CodeGen/CommandFlags.h>
22#include <llvm/Support/SourceMgr.h>
23#include <llvm/Support/TargetSelect.h>
24#include <llvm/Support/Host.h>
25#include <llvm/Support/raw_ostream.h>
26
27#include <re/re_cc.h>
28#include <cc/cc_compiler.h>
29#include <pablo/function.h>
30#include <IDISA/idisa_builder.h>
31#include <IDISA/idisa_target.h>
32#include <kernels/u8u16_pipeline.h>
33
34// Dynamic processor detection
35#define ISPC_LLVM_VERSION ISPC_LLVM_3_6
36#include <util/ispc.cpp>
37
38#include <utf_encoding.h>
39
40// mmap system
41#include <boost/filesystem.hpp>
42#include <boost/iostreams/device/mapped_file.hpp>
43using namespace boost::iostreams;
44using namespace boost::filesystem;
45
46#include <fcntl.h>
47
48static cl::list<std::string> inputFiles(cl::Positional, cl::desc("<input file ...>"), cl::OneOrMore);
49
50static cl::OptionCategory eIRDumpOptions("LLVM IR Dump Options", "These options control dumping of LLVM IR.");
51static cl::opt<bool> DumpGeneratedIR("dump-generated-IR", cl::init(false), cl::desc("Print LLVM IR generated by Pablo Compiler."), cl::cat(eIRDumpOptions));
52
53static cl::OptionCategory cMachineCodeOptimization("Machine Code Optimizations", "These options control back-end compilier optimization levels.");
54
55static cl::opt<char> OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] (default = '-O0')"),
56                              cl::cat(cMachineCodeOptimization), cl::Prefix, cl::ZeroOrMore, cl::init('0'));
57
58
59//
60//  Functions taken from toolchain.cpp and modified for casefold
61//  JIT_t_ExecutionEngine : remove object cache
62//  icgrep_Linking:   unneeded?
63//  all others: definitely unneeded
64//
65
66ExecutionEngine * JIT_to_ExecutionEngine (Module * m) {
67
68    InitializeNativeTarget();
69    InitializeNativeTargetAsmPrinter();
70    InitializeNativeTargetAsmParser();
71
72    PassRegistry * Registry = PassRegistry::getPassRegistry();
73    initializeCore(*Registry);
74    initializeCodeGen(*Registry);
75    initializeLowerIntrinsicsPass(*Registry);
76
77    std::string errMessage;
78    EngineBuilder builder(std::move(std::unique_ptr<Module>(m)));
79    builder.setErrorStr(&errMessage);
80    builder.setMCPU(sys::getHostCPUName());
81    CodeGenOpt::Level optLevel = CodeGenOpt::Level::None;
82    switch (OptLevel) {
83        case '0': optLevel = CodeGenOpt::None; break;
84        case '1': optLevel = CodeGenOpt::Less; break;
85        case '2': optLevel = CodeGenOpt::Default; break;
86        case '3': optLevel = CodeGenOpt::Aggressive; break;
87        default: errs() << OptLevel << " is an invalid optimization level.\n";
88    }
89    builder.setOptLevel(optLevel);
90
91    if ((strncmp(lGetSystemISA(), "avx2", 4) == 0)) {
92            std::vector<std::string> attrs;
93            attrs.push_back("avx2");
94            builder.setMAttrs(attrs);
95    }
96
97    // builder.selectTarget();
98
99    //builder.setOptLevel(mMaxWhileDepth ? CodeGenOpt::Level::Less : CodeGenOpt::Level::None);
100    ExecutionEngine * engine = builder.create();
101    if (engine == nullptr) {
102        throw std::runtime_error("Could not create ExecutionEngine: " + errMessage);
103    }
104    return engine;
105}
106
107
108//
109//
110//
111namespace pablo {
112
113PabloFunction * u8u16_pablo(const Encoding encoding) {
114    //  input: 8 basis bit streams
115    //  output: 16 u8-indexed streams, + delmask stream + error stream
116    PabloFunction * function = PabloFunction::Create("u8u16", 8, 18);
117    cc::CC_Compiler ccc(*function, encoding);
118   
119    PabloBuilder pBuilder(ccc.getBuilder().getPabloBlock(), ccc.getBuilder());
120    const std::vector<Var *> u8_bits = ccc.getBasisBits();
121    // Outputs
122    Assign * u16_hi[8];
123    Assign * u16_lo[8];
124    Assign * delmask;
125    Assign * error_mask;
126   
127    // The logic for processing non-ASCII bytes is to be embedded within an if-hierarchy.
128    PabloAST * nonASCII = ccc.compileCC(re::makeCC(0x80, 0xFF));
129   
130    // Builder for the if statement handling all non-ASCII logic
131    PabloBuilder nAb = PabloBuilder::Create(pBuilder);
132    // Bits 3 through 7 of a 2-byte prefix are data bits, needed to
133    // produce the UTF-16 code unit data ...,
134    PabloAST * bit3a1 = nAb.createAdvance(u8_bits[3], 1);
135    PabloAST * bit4a1 = nAb.createAdvance(u8_bits[4], 1);
136    PabloAST * bit5a1 = nAb.createAdvance(u8_bits[5], 1);
137    PabloAST * bit6a1 = nAb.createAdvance(u8_bits[6], 1);
138    PabloAST * bit7a1 = nAb.createAdvance(u8_bits[7], 1);
139   
140    // Entry condition for 3 or 4 byte sequences: we have a prefix byte in the range 0xE0-0xFF.
141    PabloAST * pfx34 = ccc.compileCC(re::makeCC(0xE0, 0xFF), nAb);
142    // Builder for the if statement handling all logic for 3- and 4-byte sequences.
143    PabloBuilder p34b = PabloBuilder::Create(nAb);
144    // Bits 4 through 7 of a 3-byte prefix are data bits.  They must be moved
145    // to the final position of the 3-byte sequence.
146    PabloAST * bit2a1 = p34b.createAdvance(u8_bits[2], 1);
147    PabloAST * bit4a2 = p34b.createAdvance(bit4a1, 1);
148    PabloAST * bit5a2 = p34b.createAdvance(bit5a1, 1);
149    PabloAST * bit6a2 = p34b.createAdvance(bit6a1, 1);
150    PabloAST * bit7a2 = p34b.createAdvance(bit7a1, 1);
151    //
152    // Logic for 4-byte UTF-8 sequences
153    //
154    // Entry condition  or 4 byte sequences: we have a prefix byte in the range 0xF0-0xFF.
155    PabloAST * pfx4 = ccc.compileCC(re::makeCC(0xF0, 0xFF), p34b);
156    // Builder for the if statement handling all logic for 4-byte sequences only.
157    PabloBuilder p4b = PabloBuilder::Create(p34b);
158    // Illegal 4-byte sequences
159    PabloAST * F0 = ccc.compileCC(re::makeCC(0xF0), p4b);
160    PabloAST * F4 = ccc.compileCC(re::makeCC(0xF4), p4b);
161    PabloAST * F0_err = p4b.createAnd(p4b.createAdvance(F0, 1), ccc.compileCC(re::makeCC(0x80, 0x8F), p4b));
162    PabloAST * F4_err = p4b.createAnd(p4b.createAdvance(F4, 1), ccc.compileCC(re::makeCC(0x90, 0xBF), p4b));
163    PabloAST * F5_FF = ccc.compileCC(re::makeCC(0xF5, 0xFF), p4b);
164    Assign * FX_err = p4b.createAssign("FX_err", p4b.createOr(F5_FF, p4b.createOr(F0_err, F4_err)));
165    //
166    // 4-byte prefixes have a scope that extends over the next 3 bytes.
167    Assign * u8scope42 = p4b.createAssign("u8scope42", p4b.createAdvance(pfx4, 1));
168    Assign * u8scope43 = p4b.createAssign("u8scope43", p4b.createAdvance(u8scope42, 1));
169    Assign * u8scope44 = p4b.createAssign("u8scope44", p4b.createAdvance(u8scope43, 1));
170    //
171   
172    //  From the 4-byte sequence 11110abc 10defghi 10jklmno 10pqrstu,
173    //  we must calculate the value abcde - 1 to produce the bit values
174    //  for u16_hi6, hi7, lo0, lo1 at the scope43 position.
175    Assign * s43_lo1 = p4b.createAssign("scope43_lo1", p4b.createAnd(u8scope43, p4b.createNot(bit3a1)));           // e - 1
176    Assign * s43_lo0 = p4b.createAssign("scope43_lo0", p4b.createAnd(u8scope43, p4b.createXor(bit2a1, s43_lo1)));  // d - borrow
177    PabloAST * brw1 = p4b.createAnd(s43_lo1, p4b.createNot(bit2a1));
178    Assign * s43_hi7 = p4b.createAssign("scope43_hi7", p4b.createAnd(u8scope43, p4b.createXor(bit7a2, brw1)));     // c - borrow
179    PabloAST * brw2 = p4b.createAnd(brw1, p4b.createNot(bit7a2));
180    Assign * s43_hi6 = p4b.createAssign("scope43_hi6", p4b.createAnd(u8scope43, p4b.createXor(bit6a2, brw2)));     // b - borrow
181    //
182    Assign * s43_lo2 = p4b.createAssign("scope43_lo2", p4b.createAnd(u8scope43, bit4a1));
183    Assign * s43_lo3 = p4b.createAssign("scope43_lo3", p4b.createAnd(u8scope43, bit5a1));
184    Assign * s43_lo4 = p4b.createAssign("scope43_lo4", p4b.createAnd(u8scope43, bit6a1));
185    Assign * s43_lo5 = p4b.createAssign("scope43_lo5", p4b.createAnd(u8scope43, bit7a1));
186    Assign * s43_lo6 = p4b.createAssign("scope43_lo6", p4b.createAnd(u8scope43, u8_bits[2]));
187    Assign * s43_lo7 = p4b.createAssign("scope43_lo7", p4b.createAnd(u8scope43, u8_bits[3]));
188    //
189    //
190    p34b.createIf(pfx4,
191                  {FX_err, u8scope42, u8scope43, u8scope44, s43_hi6, s43_hi7,
192                   s43_lo0, s43_lo1, s43_lo2, s43_lo3, s43_lo4, s43_lo5, s43_lo6, s43_lo7},
193                   p4b);
194    //
195    // Combined logic for 3 and 4 byte sequences
196    //
197    PabloAST * pfx3 = ccc.compileCC(re::makeCC(0xE0, 0xEF), p34b);
198    Assign * u8scope32 = p34b.createAssign("u8scope32", p34b.createAdvance(pfx3, 1));
199    Assign * u8scope33 = p34b.createAssign("u8scope33", p34b.createAdvance(u8scope32, 1));
200
201    // Illegal 3-byte sequences
202    PabloAST * E0 = ccc.compileCC(re::makeCC(0xE0), p34b);
203    PabloAST * ED = ccc.compileCC(re::makeCC(0xED), p34b);
204    PabloAST * E0_err = p34b.createAnd(p34b.createAdvance(E0, 1), ccc.compileCC(re::makeCC(0x80, 0x9F), p34b));
205    PabloAST * ED_err = p34b.createAnd(p34b.createAdvance(ED, 1), ccc.compileCC(re::makeCC(0xA0, 0xBF), p34b));
206    Assign * EX_FX_err = p34b.createAssign("EX_FX_err", p34b.createOr(p34b.createOr(E0_err, ED_err), FX_err));
207    // Two surrogate UTF-16 units are computed at the 3rd and 4th positions of 4-byte sequences.
208    PabloAST * surrogate = p34b.createOr(u8scope43, u8scope44);
209   
210    Assign * p34del = p34b.createAssign("p34del", p34b.createOr(u8scope32, u8scope42));
211
212
213    // The high 5 bits of the UTF-16 code unit are only nonzero for 3 and 4-byte
214    // UTF-8 sequences.
215    u16_hi[0] = p34b.createAssign("u16_hi0", p34b.createOr(p34b.createAnd(u8scope33, bit4a2), surrogate));
216    u16_hi[1] = p34b.createAssign("u16_hi1", p34b.createOr(p34b.createAnd(u8scope33, bit5a2), surrogate));
217    u16_hi[2] = p34b.createAssign("u16_hi2", p34b.createAnd(u8scope33, bit6a2));
218    u16_hi[3] = p34b.createAssign("u16_hi3", p34b.createOr(p34b.createAnd(u8scope33, bit7a2), surrogate));
219    u16_hi[4] = p34b.createAssign("u16_hi4", p34b.createOr(p34b.createAnd(u8scope33, bit2a1), surrogate));
220   
221    //
222    nAb.createIf(pfx34, 
223                 {u8scope33, EX_FX_err, p34del, 
224                  u16_hi[0], u16_hi[1], u16_hi[2], u16_hi[3], u16_hi[4], u8scope44, s43_hi6, s43_hi7,
225                  s43_lo0, s43_lo1, s43_lo2, s43_lo3, s43_lo4, s43_lo5, s43_lo6, s43_lo7},
226                 p34b);
227    //
228    // Combined logic for 2, 3 and 4 byte sequences
229    //
230    PabloAST * pfx2 = ccc.compileCC(re::makeCC(0xC0, 0xDF), nAb);
231    PabloAST * u8scope22 = nAb.createAdvance(pfx2, 1);
232    Assign * u8lastscope = nAb.createAssign("u8lastscope", nAb.createOr(u8scope22, nAb.createOr(u8scope33, u8scope44)));
233    PabloAST * u8anyscope = nAb.createOr(u8lastscope, p34del);
234
235    PabloAST * C0_C1_err = ccc.compileCC(re::makeCC(0xC0, 0xC1), nAb);
236    PabloAST * scope_suffix_mismatch = nAb.createXor(u8anyscope, ccc.compileCC(re::makeCC(0x80, 0xBF), nAb));
237    error_mask = nAb.createAssign("errormask", nAb.createOr(scope_suffix_mismatch, nAb.createOr(C0_C1_err, EX_FX_err)));
238    delmask = nAb.createAssign("delmask", nAb.createOr(p34del, ccc.compileCC(re::makeCC(0xC0, 0xFF), nAb)));
239   
240    // The low 3 bits of the high byte of the UTF-16 code unit as well as the high bit of the
241    // low byte are only nonzero for 2, 3 and 4 byte sequences.
242    u16_hi[5] = nAb.createAssign("u16_hi5", nAb.createOr(nAb.createAnd(u8lastscope, bit3a1), u8scope44));
243    u16_hi[6] = nAb.createAssign("u16_hi6", nAb.createOr(nAb.createAnd(u8lastscope, bit4a1), s43_hi6));
244    u16_hi[7] = nAb.createAssign("u16_hi7", nAb.createOr(nAb.createAnd(u8lastscope, bit5a1), s43_hi7));
245    u16_lo[0] = nAb.createAssign("u16_lo0", nAb.createOr(nAb.createAnd(u8lastscope, bit6a1), s43_lo0));
246    Assign * p234_lo1 = nAb.createAssign("p234_lo1", nAb.createOr(nAb.createAnd(u8lastscope, bit7a1), s43_lo1));
247
248    pBuilder.createIf(nonASCII, 
249                      {error_mask, delmask, u8lastscope,
250                       u16_hi[0], u16_hi[1], u16_hi[2], u16_hi[3], u16_hi[4], u16_hi[5], u16_hi[6], u16_hi[7],
251                       u16_lo[0], p234_lo1, s43_lo2, s43_lo3, s43_lo4, s43_lo5, s43_lo6, s43_lo7},
252                      nAb);
253    //
254    //
255    PabloAST * ASCII = ccc.compileCC(re::makeCC(0x0, 0x7F));
256    PabloAST * last_byte = pBuilder.createOr(ASCII, u8lastscope);
257    u16_lo[1] = pBuilder.createAssign("u16_lo1", pBuilder.createOr(pBuilder.createAnd(ASCII, u8_bits[1]), p234_lo1));
258    u16_lo[2] = pBuilder.createAssign("u16_lo2", pBuilder.createOr(pBuilder.createAnd(last_byte, u8_bits[2]), s43_lo2));
259    u16_lo[3] = pBuilder.createAssign("u16_lo3", pBuilder.createOr(pBuilder.createAnd(last_byte, u8_bits[3]), s43_lo3));
260    u16_lo[4] = pBuilder.createAssign("u16_lo4", pBuilder.createOr(pBuilder.createAnd(last_byte, u8_bits[4]), s43_lo4));
261    u16_lo[5] = pBuilder.createAssign("u16_lo5", pBuilder.createOr(pBuilder.createAnd(last_byte, u8_bits[5]), s43_lo5));
262    u16_lo[6] = pBuilder.createAssign("u16_lo6", pBuilder.createOr(pBuilder.createAnd(last_byte, u8_bits[6]), s43_lo6));
263    u16_lo[7] = pBuilder.createAssign("u16_lo7", pBuilder.createOr(pBuilder.createAnd(last_byte, u8_bits[7]), s43_lo7));
264   
265    for (unsigned i = 0; i < 8; i++) {
266        function->setResult(i, pBuilder.createAssign("u16_hi" + std::to_string(i), u16_hi[i]));
267        function->setResult(i+8, pBuilder.createAssign("u16_lo" + std::to_string(i), u16_lo[i]));
268    }
269    function->setResult(16, pBuilder.createAssign("delbits", delmask));
270    function->setResult(17, pBuilder.createAssign("errors", error_mask));
271
272    return function;
273}
274}
275
276
277typedef void (*u8u16FunctionType)(char * byte_data, size_t filesize);
278
279static ExecutionEngine * u8u16Engine = nullptr;
280
281u8u16FunctionType u8u16CodeGen(void) {
282                           
283    Module * M = new Module("u8u16", getGlobalContext());
284   
285    IDISA::IDISA_Builder * idb = GetIDISA_Builder(M);
286
287    kernel::PipelineBuilder pipelineBuilder(M, idb);
288
289    Encoding encoding(Encoding::Type::UTF_8, 8);
290   
291    pablo::PabloFunction * function = pablo::u8u16_pablo(encoding);
292   
293
294    pipelineBuilder.CreateKernels(function);
295
296    llvm::Function * main_IR = pipelineBuilder.ExecuteKernels();
297   
298    if (DumpGeneratedIR) {
299        M->dump();
300    }
301   
302    verifyModule(*M, &dbgs());
303    //std::cerr << "ExecuteKernels(); done\n";
304    u8u16Engine = JIT_to_ExecutionEngine(M);
305   
306    u8u16Engine->finalizeObject();
307    //std::cerr << "finalizeObject(); done\n";
308
309    delete idb;
310    return reinterpret_cast<u8u16FunctionType>(u8u16Engine->getPointerToFunction(main_IR));
311}
312
313void u8u16(u8u16FunctionType fn_ptr, const std::string & fileName) {
314    std::string mFileName = fileName;
315    size_t mFileSize;
316    char * mFileBuffer;
317   
318    const path file(mFileName);
319    if (exists(file)) {
320        if (is_directory(file)) {
321            return;
322        }
323    } else {
324        std::cerr << "Error: cannot open " << mFileName << " for processing. Skipped.\n";
325        return;
326    }
327   
328    mFileSize = file_size(file);
329    mapped_file_source mFile;
330    if (mFileSize == 0) {
331        mFileBuffer = nullptr;
332    }
333    else {
334        try {
335            mFile.open(mFileName);
336        } catch (std::exception &e) {
337            std::cerr << "Error: Boost mmap of " << mFileName << ": " << e.what() << std::endl;
338            return;
339        }
340        mFileBuffer = const_cast<char *>(mFile.data());
341    }
342    //std::cerr << "mFileSize =" << mFileSize << "\n";
343    //std::cerr << "fn_ptr =" << std::hex << reinterpret_cast<intptr_t>(fn_ptr) << "\n";
344
345    fn_ptr(mFileBuffer, mFileSize);
346
347    mFile.close();
348   
349}
350
351
352int main(int argc, char *argv[]) {
353    StringMap<cl::Option*> Map;
354    cl::getRegisteredOptions(Map);
355    Map["time-passes"]->setHiddenFlag(cl::Hidden);
356    Map["disable-spill-fusing"]->setHiddenFlag(cl::Hidden);
357    Map["enable-misched"]->setHiddenFlag(cl::Hidden);
358    Map["enable-tbaa"]->setHiddenFlag(cl::Hidden);
359    Map["exhaustive-register-search"]->setHiddenFlag(cl::Hidden);
360    Map["join-liveintervals"]->setHiddenFlag(cl::Hidden);
361    Map["limit-float-precision"]->setHiddenFlag(cl::Hidden);
362    Map["mc-x86-disable-arith-relaxation"]->setHiddenFlag(cl::Hidden);
363    Map["limit-float-precision"]->setHiddenFlag(cl::Hidden);
364    Map["print-after-all"]->setHiddenFlag(cl::Hidden);
365    Map["print-before-all"]->setHiddenFlag(cl::Hidden);
366    Map["print-machineinstrs"]->setHiddenFlag(cl::Hidden);
367    Map["regalloc"]->setHiddenFlag(cl::Hidden);
368    Map["rng-seed"]->setHiddenFlag(cl::Hidden);
369    Map["stackmap-version"]->setHiddenFlag(cl::Hidden);
370    Map["x86-asm-syntax"]->setHiddenFlag(cl::Hidden);
371    Map["verify-debug-info"]->setHiddenFlag(cl::Hidden);
372    Map["verify-dom-info"]->setHiddenFlag(cl::Hidden);
373    Map["verify-loop-info"]->setHiddenFlag(cl::Hidden);
374    Map["verify-regalloc"]->setHiddenFlag(cl::Hidden);
375    Map["verify-scev"]->setHiddenFlag(cl::Hidden);
376    Map["x86-recip-refinement-steps"]->setHiddenFlag(cl::Hidden);
377    Map["rewrite-map-file"]->setHiddenFlag(cl::Hidden);
378
379    cl::ParseCommandLineOptions(argc, argv);
380
381    u8u16FunctionType fn_ptr = u8u16CodeGen();
382
383    for (unsigned i = 0; i != inputFiles.size(); ++i) {
384        u8u16(fn_ptr, inputFiles[i]);
385    }
386
387    delete u8u16Engine;
388
389    return 0;
390}
391
392                       
Note: See TracBrowser for help on using the repository browser.