File: llvm_dynamic_dsp_aux.cpp

package info (click to toggle)
faust 2.79.3%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 397,496 kB
  • sloc: cpp: 278,433; ansic: 116,164; javascript: 18,529; vhdl: 14,052; sh: 13,884; java: 5,900; objc: 3,852; python: 3,222; makefile: 2,655; cs: 1,672; lisp: 1,146; ruby: 954; yacc: 586; xml: 471; lex: 247; awk: 110; tcl: 26
file content (961 lines) | stat: -rw-r--r-- 33,801 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
/************************************************************************
 ************************************************************************
    FAUST compiler
    Copyright (C) 2003-2018 GRAME, Centre National de Creation Musicale
    ---------------------------------------------------------------------
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation; either version 2.1 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 ************************************************************************
 ************************************************************************/

#ifdef WIN32
#pragma warning(disable : 4141 4244 4291 4146 4267 4275 4624 4800)
#endif

#include <string.h>
#include <fstream>
#include <iostream>
#include <sstream>

#include "Text.hh"
#include "compatibility.hh"
#include "global.hh"
#include "libfaust.h"
#include "llvm_dynamic_dsp_aux.hh"
#include "lock_api.hh"
#include "rn_base64.h"

#include <llvm/ExecutionEngine/MCJIT.h>
#include <llvm/ExecutionEngine/ObjectCache.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/IRPrintingPasses.h>
#include <llvm/IR/LegacyPassManager.h>
#include <llvm/IR/LegacyPassNameParser.h>
#include <llvm/IR/PassManager.h>
#include <llvm/IR/Verifier.h>
#include <llvm/IRReader/IRReader.h>
#include <llvm/Linker/Linker.h>
#include <llvm/Support/FileSystem.h>
#include <llvm/Support/FormattedStream.h>
#if LLVM_VERSION_MAJOR >= 16
#include <llvm/TargetParser/Host.h>
#else
#include <llvm/Support/Host.h>
#endif
#include <llvm/Support/ManagedStatic.h>
#include <llvm/Support/MemoryBuffer.h>
#include <llvm/Support/SourceMgr.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Transforms/IPO.h>
#if LLVM_VERSION_MAJOR < 17
#include <llvm/Transforms/IPO/PassManagerBuilder.h>
#endif
#include <llvm/Analysis/TargetLibraryInfo.h>
#include <llvm/Analysis/TargetTransformInfo.h>
#include <llvm/Bitcode/BitcodeReader.h>
#include <llvm/Bitcode/BitcodeWriter.h>
#include <llvm/Target/TargetMachine.h>
#include <llvm/Transforms/IPO/AlwaysInliner.h>
#include <llvm/Transforms/Scalar.h>

#if LLVM_VERSION_MAJOR >= 17
#include <llvm/Analysis/CGSCCPassManager.h>
#include <llvm/Analysis/LoopAnalysisManager.h>
#include <llvm/Passes/PassBuilder.h>
#endif

// Disappears in LLVM 15
#if LLVM_VERSION_MAJOR >= 14
#include <llvm/MC/TargetRegistry.h>
#else
#include <llvm/Support/TargetRegistry.h>
#endif

#if LLVM_VERSION_MAJOR >= 10
#include <llvm/InitializePasses.h>
#include <llvm/Support/CodeGen.h>
#endif

using namespace llvm;
using namespace std;

#define dumpLLVM(val)                    \
    {                                    \
        string             res;          \
        raw_string_ostream out_str(res); \
        out_str << *val;                 \
        cout << out_str.str() << endl;   \
    }

// Assuming there is a single JSON string in the module
std::string llvm_dsp_factory_aux::findJSON(llvm::Module* module)
{
    for (const auto& global : module->globals()) {
        auto* initializer = global.getInitializer();
        if (auto* array = llvm::dyn_cast<llvm::ConstantDataArray>(initializer)) {
            if (array->isString()) {
                return array->getAsString().str();
            }
        }
    }
    return "";
}

static void splitTarget(const string& target, string& triple, string& cpu)
{
    size_t pos1 = target.find_first_of(':');
    triple      = target.substr(0, pos1);
    if (pos1 != string::npos) {
        cpu = target.substr(pos1 + 1);
    }
}

static string getParam(int argc, const char* argv[], const string& param, const string& def)
{
    for (int i = 0; i < argc; i++) {
        if (string(argv[i]) == param) {
            return argv[i + 1];
        }
    }
    return def;
}

static Module* ParseBitcodeFile(MEMORY_BUFFER buffer, LLVMContext& context, string& error_msg)
{
    Expected<unique_ptr<Module>> module_or_err = parseBitcodeFile(buffer, context);
    if (error_code ec = errorToErrorCode(module_or_err.takeError())) {
        error_msg = "ERROR : failed to read bitcode\n";
        return nullptr;
    } else {
        return module_or_err.get().release();
    }
}

void llvm_dynamic_dsp_factory_aux::write(ostream* out, bool binary, bool small)
{
    string             res;
    raw_string_ostream out_str(res);
    if (binary) {
#if LLVM_VERSION_MAJOR >= 8
        WriteBitcodeToFile(*fModule, out_str);
#else
        WriteBitcodeToFile(fModule, out_str);
#endif
    } else {
        out_str << *fModule;
    }
    *out << out_str.str();
}

// Bitcode
string llvm_dynamic_dsp_factory_aux::writeDSPFactoryToBitcode()
{
    string             res;
    raw_string_ostream out(res);
#if LLVM_VERSION_MAJOR >= 8
    WriteBitcodeToFile(*fModule, out);
#else
    WriteBitcodeToFile(fModule, out);
#endif
    out.flush();
    return base64_encode(res);
}

bool llvm_dynamic_dsp_factory_aux::writeDSPFactoryToBitcodeFile(const string& bit_code_path)
{
    STREAM_ERROR   err;
    raw_fd_ostream out(bit_code_path.c_str(), err, sysfs_binary_flag);
    if (err) {
        cerr << "ERROR : writeDSPFactoryToBitcodeFile could not open file : " << err.message();
        return false;
    }
#if LLVM_VERSION_MAJOR >= 8
    WriteBitcodeToFile(*fModule, out);
#else
    WriteBitcodeToFile(fModule, out);
#endif
    return true;
}

// IR
string llvm_dynamic_dsp_factory_aux::writeDSPFactoryToIR()
{
    string             res;
    raw_string_ostream out(res);
    PASS_MANAGER       PM;
    PM.add(llvmcreatePrintModulePass(out));
    PM.run(*fModule);
    out.flush();
    return res;
}

bool llvm_dynamic_dsp_factory_aux::writeDSPFactoryToIRFile(const string& ir_code_path)
{
    STREAM_ERROR   err;
    raw_fd_ostream out(ir_code_path.c_str(), err, sysfs_binary_flag);
    if (err) {
        cerr << "ERROR : writeDSPFactoryToBitcodeFile could not open file : " << err.message();
        return false;
    }
    PASS_MANAGER PM;
    PM.add(llvmcreatePrintModulePass(out));
    PM.run(*fModule);
    out.flush();
    return true;
}

#if LLVM_VERSION_MAJOR < 17
/// AddOptimizationPasses - This routine adds optimization passes
/// based on selected optimization level, OptLevel. This routine
/// duplicates llvm-gcc behaviour.
///
/// OptLevel - Optimization Level
static void AddOptimizationPasses(PassManagerBase& MPM, FUNCTION_PASS_MANAGER& FPM,
                                  unsigned OptLevel, unsigned SizeLevel)
{
    FPM.add(createVerifierPass());  // Verify that input is correct

    PassManagerBuilder Builder;
    Builder.OptLevel  = OptLevel;
    Builder.SizeLevel = SizeLevel;

    if (OptLevel > 1) {
        unsigned Threshold = 225;
        if (SizeLevel == 1) {  // -Os
            Threshold = 75;
        } else if (SizeLevel == 2) {  // -Oz
            Threshold = 25;
        }
        if (OptLevel > 2) {
            Threshold = 275;
        }
#if LLVM_VERSION_MAJOR < 17
        Builder.Inliner = createFunctionInliningPass(Threshold);
#endif
    } else {
        Builder.Inliner = createAlwaysInlinerLegacyPass();
    }

    Builder.DisableUnrollLoops = (OptLevel == 0);

    // Add auto-vectorization passes
    if (OptLevel > 3) {
        Builder.LoopVectorize = true;
        Builder.SLPVectorize  = true;
    }

    Builder.populateFunctionPassManager(FPM);
    Builder.populateModulePassManager(MPM);
}
#endif

bool llvm_dynamic_dsp_factory_aux::initJIT(string& error_msg)
{
    startTiming("initJIT");
    faustassert(fModule);

#ifdef LLVM_BUILD_UNIVERSAL
    // For multiple target support
    InitializeAllTargets();
    InitializeAllTargetMCs();
    InitializeAllAsmPrinters();
    InitializeAllAsmParsers();
#endif

    // For host target support
    InitializeNativeTarget();
    InitializeNativeTargetAsmPrinter();
    InitializeNativeTargetAsmParser();

    // For ObjectCache to work...
    LLVMLinkInMCJIT();

    EngineBuilder builder((unique_ptr<Module>(fModule)));

#if LLVM_VERSION_MAJOR >= 18
    builder.setOptLevel(CodeGenOptLevel::Aggressive);
#else
    builder.setOptLevel(CodeGenOpt::Aggressive);
#endif

    builder.setEngineKind(EngineKind::JIT);

    string buider_error;
    builder.setErrorStr(&buider_error);

    string triple, cpu;
    splitTarget(fTarget, triple, cpu);
    fModule->setTargetTriple(triple);

    builder.setMCPU((cpu == "") ? sys::getHostCPUName() : StringRef(cpu));
    TargetOptions targetOptions;

    if (!gGlobal->isOpt("FAUST_LLVM_NO_FM")) {
        // -fastmath is activated at IR level, and has to be setup at JIT level also
        targetOptions.AllowFPOpFusion       = FPOpFusion::Fast;
        targetOptions.UnsafeFPMath          = true;
        targetOptions.NoInfsFPMath          = true;
        targetOptions.NoNaNsFPMath          = true;
        targetOptions.GuaranteedTailCallOpt = true;
        targetOptions.NoTrappingFPMath      = true;
    }

#if LLVM_VERSION_MAJOR >= 9
    targetOptions.NoSignedZerosFPMath = true;
#endif

#if LLVM_VERSION_MAJOR >= 11
    targetOptions.setFPDenormalMode(DenormalMode::getIEEE());
#else
    targetOptions.FPDenormalMode = FPDenormal::IEEE;
#endif

    targetOptions.GuaranteedTailCallOpt = true;

    if (global::isDebug("FAUST_LLVM3")) {
#if LLVM_VERSION_MAJOR < 12
        targetOptions.PrintMachineCode = true;
#endif
    }

    builder.setTargetOptions(targetOptions);
    TargetMachine* tm = builder.selectTarget();

    fJIT = builder.create(tm);
    if (!fJIT) {
        endTiming("initJIT");
        error_msg = "ERROR : cannot create LLVM JIT : " + buider_error + "\n";
        return false;
    }

    int optlevel = getOptlevel();

    if ((optlevel == -1) || (fOptLevel > optlevel)) {
#if LLVM_VERSION_MAJOR >= 17
        // See: https://llvm.org/docs/NewPassManager.html

        // Create the analysis managers.
        LoopAnalysisManager     LAM;
        FunctionAnalysisManager FAM;
        CGSCCAnalysisManager    CGAM;
        ModuleAnalysisManager   MAM;

        // Create the new pass manager builder.
        // Take a look at the PassBuilder constructor parameters for more
        // customization, e.g. specifying a TargetMachine or various debugging
        // options.
        PassBuilder PB;

        // Register all the basic analyses with the managers.
        PB.registerModuleAnalyses(MAM);
        PB.registerCGSCCAnalyses(CGAM);
        PB.registerFunctionAnalyses(FAM);
        PB.registerLoopAnalyses(LAM);
        PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);

        // Create the pass manager.
        OptimizationLevel opt_table[] = {OptimizationLevel::O0, OptimizationLevel::O1,
                                         OptimizationLevel::O2, OptimizationLevel::O3};
        fOptLevel                     = std::min(fOptLevel, 3);
        ModulePassManager MPM         = PB.buildPerModuleDefaultPipeline(opt_table[fOptLevel]);

        if (global::isDebug("FAUST_LLVM1")) {
            dumpLLVM(fModule);
        }

        // Optimize the IR
        MPM.run(*fModule, MAM);
        if (global::isDebug("FAUST_LLVM2")) {
            dumpLLVM(fModule);
        }
#else
        PASS_MANAGER          pm;
        FUNCTION_PASS_MANAGER fpm(fModule);

        // Code taken from opt.cpp
        TargetLibraryInfoImpl TLII(Triple(fModule->getTargetTriple()));
        pm.add(new TargetLibraryInfoWrapperPass(TLII));
        fModule->setDataLayout(fJIT->getDataLayout());

        // Add internal analysis passes from the target machine (mandatory for vectorization to
        // work) Code taken from opt.cpp
        pm.add(createTargetTransformInfoWrapperPass(tm->getTargetIRAnalysis()));

        if (fOptLevel > 0) {
            AddOptimizationPasses(pm, fpm, fOptLevel, 0);
        }

        if (global::isDebug("FAUST_LLVM1")) {
            dumpLLVM(fModule);
        }

        fpm.doInitialization();
        for (Module::iterator F = fModule->begin(), E = fModule->end(); F != E; ++F) {
            fpm.run(*F);
        }
        fpm.doFinalization();
        pm.add(createVerifierPass());

        if (global::isDebug("FAUST_LLVM4")) {
            // TODO
            // tm->addPassesToEmitFile(pm, fouts(), TargetMachine::CGFT_AssemblyFile, true);
        }

        // Now that we have all of the passes ready, run them.
        pm.run(*fModule);
        if (global::isDebug("FAUST_LLVM2")) {
            dumpLLVM(fModule);
        }
#endif
    }

    fObjectCache = new FaustObjectCache();
    fJIT->setObjectCache(fObjectCache);
    return initJITAux();
}

// Bitcode <==> string
static llvm_dsp_factory* readDSPFactoryFromBitcodeAux(MEMORY_BUFFER buffer, const string& target,
                                                      string& error_msg, int opt_level)
{
    string sha_key = generateSHA1(MEMORY_BUFFER_GET(buffer).str());
    dsp_factory_table<SDsp_factory>::factory_iterator it;

    if (llvm_dsp_factory_aux::gLLVMFactoryTable.getFactory(sha_key, it)) {
        SDsp_factory sfactory = (*it).first;
        sfactory->addReference();
        return sfactory;
    } else {
        try {
            LLVMContext* context = new LLVMContext();
            Module*      module  = ParseBitcodeFile(buffer, *context, error_msg);
            if (!module) {
                return nullptr;
            }
            llvm_dynamic_dsp_factory_aux* factory_aux =
                new llvm_dynamic_dsp_factory_aux(sha_key, module, context, target, opt_level);
            if (factory_aux->initJIT(error_msg)) {
                llvm_dsp_factory* factory = new llvm_dsp_factory(factory_aux);
                llvm_dsp_factory_aux::gLLVMFactoryTable.setFactory(factory);
                factory->setSHAKey(sha_key);
                return factory;
            } else {
                delete factory_aux;
                return nullptr;
            }
        } catch (faustexception& e) {
            error_msg = e.what();
            return nullptr;
        }
    }
}

// Object code <==> file (taken from toy.cpp)
bool llvm_dynamic_dsp_factory_aux::writeDSPFactoryToObjectcodeFileAux(
    const string& object_code_path)
{
    auto TargetTriple = sys::getDefaultTargetTriple();
    fModule->setTargetTriple(TargetTriple);
    string Error;
    auto   Target = TargetRegistry::lookupTarget(TargetTriple, Error);

    // Print an error and exit if we couldn't find the requested target.
    // This generally occurs if we've forgotten to initialise the
    // TargetRegistry or we have a bogus target triple.
    if (!Target) {
        errs() << "ERROR : " << Error;
        return false;
    }

    StringRef     CPU = sys::getHostCPUName();
    string        Features;
    TargetOptions opt;
#if LLVM_VERSION_MAJOR >= 16
    auto RM = optional<Reloc::Model>();
#else
    auto RM = Optional<Reloc::Model>();
#endif
    auto TheTargetMachine = Target->createTargetMachine(TargetTriple, CPU, Features, opt, RM);
    fModule->setDataLayout(TheTargetMachine->createDataLayout());

    error_code     EC;
    raw_fd_ostream dest(object_code_path.c_str(), EC, sys::fs::OF_None);
    if (EC) {
        errs() << "ERROR : writeDSPFactoryToObjectcodeFile could not open file : " << EC.message();
        return false;
    }

    legacy::PassManager pass;
#if LLVM_VERSION_MAJOR >= 18
    if (TheTargetMachine->addPassesToEmitFile(pass, dest, nullptr, CodeGenFileType::ObjectFile)) {
#elif LLVM_VERSION_MAJOR >= 10
    if (TheTargetMachine->addPassesToEmitFile(pass, dest, nullptr, CGFT_ObjectFile)) {
#elif LLVM_VERSION_MAJOR >= 8
    if (TheTargetMachine->addPassesToEmitFile(pass, dest, nullptr,
                                              TargetMachine::CGFT_ObjectFile)) {
#else
    if (TheTargetMachine->addPassesToEmitFile(pass, dest, TargetMachine::CGFT_ObjectFile, true)) {
#endif
        errs() << "ERROR : writeDSPFactoryToObjectcodeFile : can't emit a file of this type";
        return false;
    }

    pass.run(*fModule);
    dest.flush();
    return true;
}

// Object code <==> file
bool llvm_dynamic_dsp_factory_aux::writeDSPFactoryToObjectcodeFile(const string& object_code_path,
                                                                   const string& target)
{
    if (target != "" && target != getTarget()) {
        // Recompilation is required
        string old_target = getTarget();
        if (crossCompile(target)) {
            bool res = writeDSPFactoryToObjectcodeFileAux(object_code_path);
            // Restore old target
            crossCompile(old_target);
            return res;
        } else {
            return false;
        }
    } else {
        return writeDSPFactoryToObjectcodeFileAux(object_code_path);
    }
}

// IR <==> string
static llvm_dsp_factory* readDSPFactoryFromIRAux(MEMORY_BUFFER buffer, const string& target,
                                                 string& error_msg, int opt_level)
{
    string sha_key = generateSHA1(MEMORY_BUFFER_GET(buffer).str());
    dsp_factory_table<SDsp_factory>::factory_iterator it;

    if (llvm_dsp_factory_aux::gLLVMFactoryTable.getFactory(sha_key, it)) {
        SDsp_factory sfactory = (*it).first;
        sfactory->addReference();
        return sfactory;
    } else {
        try {
            char* tmp_local = setlocale(LC_ALL, NULL);
            if (tmp_local) {
                tmp_local = strdup(tmp_local);
            }
            setlocale(LC_ALL, "C");
            LLVMContext* context = new LLVMContext();
            SMDiagnostic err;
            // parseIR takes ownership of the given buffer, so don't delete it
            Module* module = parseIR(buffer, err, *context).release();
            if (!module) {
                error_msg = "ERROR : " + string(err.getMessage().data()) + "\n";
                return nullptr;
            }
            if (tmp_local) {
                setlocale(LC_ALL, tmp_local);
                free(tmp_local);
            }
            llvm_dynamic_dsp_factory_aux* factory_aux =
                new llvm_dynamic_dsp_factory_aux(sha_key, module, context, target, opt_level);
            if (factory_aux->initJIT(error_msg)) {
                llvm_dsp_factory* factory = new llvm_dsp_factory(factory_aux);
                llvm_dsp_factory_aux::gLLVMFactoryTable.setFactory(factory);
                factory->setSHAKey(sha_key);
                return factory;
            } else {
                delete factory_aux;
                return nullptr;
            }
        } catch (faustexception& e) {
            error_msg = e.what();
            return nullptr;
        }
    }
}

// Helper public functions
ModulePTR loadSingleModule(const string filename, LLVMContext* context)
{
    SMDiagnostic err;
    ModulePTR    module = parseIRFile(filename, err, *context);
    return module;
}

ModulePTR loadModule(const string& module_name, LLVMContext* context)
{
    // Try as a complete path
    if (ModulePTR module = loadSingleModule(module_name, context)) {
        return module;
    } else {
        // Otherwise use import directories
        for (size_t i = 0; i < gGlobal->gImportDirList.size(); i++) {
            string file_name = gGlobal->gImportDirList[i] + '/' + module_name;
            if (ModulePTR module1 = loadSingleModule(file_name, context)) {
                return module1;
            }
        }
        return nullptr;
    }
}

bool linkModules(Module* dst, ModulePTR src, string& error)
{
    bool res = false;
    if (Linker::linkModules(*dst, MovePTR(src))) {
        error = "cannot link module";
    } else {
        res = true;
    }
    return res;
}

Module* linkAllModules(LLVMContext* context, Module* dst, string& error)
{
    for (size_t i = 0; i < gGlobal->gLibraryList.size(); i++) {
        string    module_name = gGlobal->gLibraryList[i];
        ModulePTR src         = loadModule(module_name, context);
        if (!src) {
            error = "cannot load module : " + module_name;
            return nullptr;
        }
        if (!linkModules(dst, MovePTR(src), error)) {
            return nullptr;
        }
    }
    return dst;
}

// Public C++ API
LIBFAUST_API llvm_dsp_factory* createDSPFactoryFromFile(const string& filename, int argc,
                                                        const char* argv[], const string& target,
                                                        string& error_msg, int opt_level)
{
    string base = basename((char*)filename.c_str());
    size_t pos  = filename.find(".dsp");

    if (pos != string::npos) {
        return createDSPFactoryFromString(base.substr(0, pos), pathToContent(filename), argc, argv,
                                          target, error_msg, opt_level);
    } else {
        error_msg = "ERROR : file extension is not the one expected (.dsp expected)\n";
        return nullptr;
    }
}

LIBFAUST_API llvm_dsp_factory* createDSPFactoryFromString(const string& name_app,
                                                          const string& dsp_content, int argc,
                                                          const char* argv[], const string& target,
                                                          string& error_msg, int opt_level)
{
    LOCK_API
    string expanded_dsp_content, sha_key;

    if ((expanded_dsp_content = sha1FromDSP(name_app, dsp_content, argc, argv, sha_key)) == "") {
        return nullptr;
    } else {
        dsp_factory_table<SDsp_factory>::factory_iterator it;
        if (llvm_dsp_factory_aux::gLLVMFactoryTable.getFactory(sha_key, it)) {
            SDsp_factory sfactory = (*it).first;
            sfactory->addReference();
            return sfactory;
        } else {
            try {
                int         argc1 = 0;
                const char* argv1[64];
                argv1[argc1++] = "faust";
                argv1[argc1++] = "-lang";
                argv1[argc1++] = "llvm";
                argv1[argc1++] = "-o";
                argv1[argc1++] = "string";
                // Copy arguments
                for (int i = 0; i < argc; i++) {
                    argv1[argc1++] = argv[i];
                }
                argv1[argc1] = nullptr;  // NULL terminated argv

                llvm_dynamic_dsp_factory_aux* factory_aux =
                    static_cast<llvm_dynamic_dsp_factory_aux*>(
                        createFactory(name_app, dsp_content, argc1, argv1, error_msg, true));
                if (factory_aux && factory_aux->initJIT(error_msg)) {
                    factory_aux->setTarget(target);
                    factory_aux->setOptlevel(opt_level);
                    factory_aux->setClassName(getParam(argc, argv, "-cn", "mydsp"));
                    factory_aux->setName(name_app);
                    llvm_dsp_factory* factory = new llvm_dsp_factory(factory_aux);
                    llvm_dsp_factory_aux::gLLVMFactoryTable.setFactory(factory);
                    factory->setSHAKey(sha_key);
                    factory->setDSPCode(expanded_dsp_content);
                    return factory;
                } else {
                    delete factory_aux;
                    return nullptr;
                }
            } catch (faustexception& e) {
                error_msg = e.what();
                return nullptr;
            }
        }
    }
}

LIBFAUST_API llvm_dsp_factory* createDSPFactoryFromSignals(const string& name_app, tvec signals,
                                                           int argc, const char* argv[],
                                                           const string& target, string& error_msg,
                                                           int opt_level)
{
    LOCK_API
    try {
        int         argc1 = 0;
        const char* argv1[64];
        argv1[argc1++] = "faust";
        argv1[argc1++] = "-lang";
        argv1[argc1++] = "llvm";
        argv1[argc1++] = "-o";
        argv1[argc1++] = "string";
        // Copy arguments
        for (int i = 0; i < argc; i++) {
            argv1[argc1++] = argv[i];
        }
        argv1[argc1] = nullptr;  // NULL terminated argv

        llvm_dynamic_dsp_factory_aux* factory_aux = static_cast<llvm_dynamic_dsp_factory_aux*>(
            createFactory(name_app, signals, argc1, argv1, error_msg));
        if (factory_aux && factory_aux->initJIT(error_msg)) {
            factory_aux->setTarget(target);
            factory_aux->setOptlevel(opt_level);
            factory_aux->setClassName(getParam(argc, argv, "-cn", "mydsp"));
            factory_aux->setName(name_app);
            llvm_dsp_factory* factory = new llvm_dsp_factory(factory_aux);
            llvm_dsp_factory_aux::gLLVMFactoryTable.setFactory(factory);
            return factory;
        } else {
            delete factory_aux;
            return nullptr;
        }
    } catch (faustexception& e) {
        error_msg = e.what();
        return nullptr;
    }
}

LIBFAUST_API llvm_dsp_factory* createDSPFactoryFromBoxes(const string& name_app, Tree box, int argc,
                                                         const char* argv[], const string& target,
                                                         string& error_msg, int opt_level)
{
    LOCK_API
    try {
        tvec signals = boxesToSignalsAux(box);
        return createDSPFactoryFromSignals(name_app, signals, argc, argv, target, error_msg,
                                           opt_level);
    } catch (faustexception& e) {
        error_msg = e.Message();
        return nullptr;
    }
}

LIBFAUST_API llvm_dsp_factory* readDSPFactoryFromBitcode(const string& bit_code,
                                                         const string& target, string& error_msg,
                                                         int opt_level)
{
    LOCK_API
    return readDSPFactoryFromBitcodeAux(MEMORY_BUFFER_CREATE(StringRef(base64_decode(bit_code))),
                                        target, error_msg, opt_level);
}

LIBFAUST_API string writeDSPFactoryToBitcode(llvm_dsp_factory* factory)
{
    LOCK_API
    return (factory) ? factory->writeDSPFactoryToBitcode() : "";
}

// Bitcode <==> file
LIBFAUST_API llvm_dsp_factory* readDSPFactoryFromBitcodeFile(const string& bit_code_path,
                                                             const string& target,
                                                             string& error_msg, int opt_level)
{
    LOCK_API
    ErrorOr<OwningPtr<MemoryBuffer>> buffer = MemoryBuffer::getFileOrSTDIN(bit_code_path);
    if (error_code ec = buffer.getError()) {
        error_msg = "ERROR : " + ec.message() + "\n";
        return nullptr;
    } else {
        return readDSPFactoryFromBitcodeAux(MEMORY_BUFFER_GET_REF(buffer), target, error_msg,
                                            opt_level);
    }
}

LIBFAUST_API bool writeDSPFactoryToBitcodeFile(llvm_dsp_factory* factory,
                                               const string&     bit_code_path)
{
    LOCK_API
    return (factory) ? factory->writeDSPFactoryToBitcodeFile(bit_code_path) : false;
}

LIBFAUST_API llvm_dsp_factory* readDSPFactoryFromIR(const string& ir_code, const string& target,
                                                    string& error_msg, int opt_level)
{
    LOCK_API
    return readDSPFactoryFromIRAux(MEMORY_BUFFER_CREATE(StringRef(ir_code)), target, error_msg,
                                   opt_level);
}

LIBFAUST_API string writeDSPFactoryToIR(llvm_dsp_factory* factory)
{
    LOCK_API
    return (factory) ? factory->writeDSPFactoryToIR() : "";
}

// IR <==> file
LIBFAUST_API llvm_dsp_factory* readDSPFactoryFromIRFile(const string& ir_code_path,
                                                        const string& target, string& error_msg,
                                                        int opt_level)
{
    LOCK_API
    ErrorOr<OwningPtr<MemoryBuffer>> buffer = MemoryBuffer::getFileOrSTDIN(ir_code_path);
    if (error_code ec = buffer.getError()) {
        error_msg = "ERROR : " + ec.message() + "\n";
        return nullptr;
    } else {
        return readDSPFactoryFromIRAux(MEMORY_BUFFER_GET_REF(buffer), target, error_msg, opt_level);
    }
}

LIBFAUST_API bool writeDSPFactoryToIRFile(llvm_dsp_factory* factory, const string& ir_code_path)
{
    LOCK_API
    return (factory) ? factory->writeDSPFactoryToIRFile(ir_code_path) : false;
}

// Public C interface : lock management is done by called C++ API
#ifdef __cplusplus
extern "C" {
#endif

LIBFAUST_API llvm_dsp_factory* createCDSPFactoryFromFile(const char* filename, int argc,
                                                         const char* argv[], const char* target,
                                                         char* error_msg, int opt_level)
{
    string            error_msg_aux;
    llvm_dsp_factory* factory =
        createDSPFactoryFromFile(filename, argc, argv, target, error_msg_aux, opt_level);
    strncpy(error_msg, error_msg_aux.c_str(), 4096);
    return factory;
}

LIBFAUST_API llvm_dsp_factory* createCDSPFactoryFromString(const char* name_app,
                                                           const char* dsp_content, int argc,
                                                           const char* argv[], const char* target,
                                                           char* error_msg, int opt_level)
{
    string            error_msg_aux;
    llvm_dsp_factory* factory = createDSPFactoryFromString(name_app, dsp_content, argc, argv,
                                                           target, error_msg_aux, opt_level);
    strncpy(error_msg, error_msg_aux.c_str(), 4096);
    return factory;
}

LIBFAUST_API llvm_dsp_factory* createCDSPFactoryFromSignals(const char* name_app,
                                                            Signal* signals_aux, int argc,
                                                            const char* argv[], const char* target,
                                                            char* error_msg, int opt_level)
{
    string error_msg_aux;
    tvec   signals;
    int    i = 0;
    while (signals_aux[i]) {
        signals.push_back(signals_aux[i]);
        i++;
    }
    llvm_dsp_factory* factory = createDSPFactoryFromSignals(name_app, signals, argc, argv, target,
                                                            error_msg_aux, opt_level);
    strncpy(error_msg, error_msg_aux.c_str(), 4096);
    return factory;
}

LIBFAUST_API llvm_dsp_factory* createCDSPFactoryFromBoxes(const char* name_app, Tree box, int argc,
                                                          const char* argv[], const char* target,
                                                          char* error_msg, int opt_level)
{
    string            error_msg_aux;
    llvm_dsp_factory* factory =
        createDSPFactoryFromBoxes(name_app, box, argc, argv, target, error_msg_aux, opt_level);
    strncpy(error_msg, error_msg_aux.c_str(), 4096);
    return factory;
}

LIBFAUST_API llvm_dsp_factory* readCDSPFactoryFromBitcode(const char* bit_code, const char* target,
                                                          char* error_msg, int opt_level)
{
    string            error_msg_aux;
    llvm_dsp_factory* factory =
        readDSPFactoryFromBitcode(bit_code, target, error_msg_aux, opt_level);
    strncpy(error_msg, error_msg_aux.c_str(), 4096);
    return factory;
}

LIBFAUST_API char* writeCDSPFactoryToBitcode(llvm_dsp_factory* factory)
{
    return (factory) ? strdup(writeDSPFactoryToBitcode(factory).c_str()) : nullptr;
}

LIBFAUST_API llvm_dsp_factory* readCDSPFactoryFromBitcodeFile(const char* bit_code_path,
                                                              const char* target, char* error_msg,
                                                              int opt_level)
{
    string            error_msg_aux;
    llvm_dsp_factory* factory =
        readDSPFactoryFromBitcodeFile(bit_code_path, target, error_msg_aux, opt_level);
    strncpy(error_msg, error_msg_aux.c_str(), 4096);
    return factory;
}

LIBFAUST_API bool writeCDSPFactoryToBitcodeFile(llvm_dsp_factory* factory,
                                                const char*       bit_code_path)
{
    return writeDSPFactoryToBitcodeFile(factory, bit_code_path);
}

LIBFAUST_API llvm_dsp_factory* readCDSPFactoryFromIR(const char* ir_code, const char* target,
                                                     char* error_msg, int opt_level)
{
    string            error_msg_aux;
    llvm_dsp_factory* factory = readDSPFactoryFromIR(ir_code, target, error_msg_aux, opt_level);
    strncpy(error_msg, error_msg_aux.c_str(), 4096);
    return factory;
}

LIBFAUST_API char* writeCDSPFactoryToIR(llvm_dsp_factory* factory)
{
    return (factory) ? strdup(writeDSPFactoryToIR(factory).c_str()) : nullptr;
}

LIBFAUST_API llvm_dsp_factory* readCDSPFactoryFromIRFile(const char* ir_code_path,
                                                         const char* target, char* error_msg,
                                                         int opt_level)
{
    string            error_msg_aux;
    llvm_dsp_factory* factory =
        readDSPFactoryFromIRFile(ir_code_path, target, error_msg_aux, opt_level);
    strncpy(error_msg, error_msg_aux.c_str(), 4096);
    return factory;
}

LIBFAUST_API bool writeCDSPFactoryToIRFile(llvm_dsp_factory* factory, const char* ir_code_path)
{
    return writeDSPFactoryToIRFile(factory, ir_code_path);
}

#ifdef __cplusplus
}
#endif