{"text":"\/\/===----------------------------------------------------------------------===\/\/\n\/\/ LLVM 'GCCAS' UTILITY \n\/\/\n\/\/ This utility is designed to be used by the GCC frontend for creating bytecode\n\/\/ files from its intermediate LLVM assembly. The requirements for this utility\n\/\/ are thus slightly different than that of the standard `as' util.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Module.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Analysis\/LoadValueNumbering.h\"\n#include \"llvm\/Analysis\/Verifier.h\"\n#include \"llvm\/Assembly\/Parser.h\"\n#include \"llvm\/Bytecode\/WriteBytecodePass.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Transforms\/RaisePointerReferences.h\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"Support\/CommandLine.h\"\n#include \"Support\/Signals.h\"\n#include \n#include \n\nnamespace {\n cl::opt\n InputFilename(cl::Positional,cl::desc(\"\"),cl::init(\"-\"));\n\n cl::opt \n OutputFilename(\"o\", cl::desc(\"Override output filename\"),\n cl::value_desc(\"filename\"));\n\n cl::opt\n RunNPasses(\"stopAfterNPasses\",\n cl::desc(\"Only run the first N passes of gccas\"), cl::Hidden,\n cl::value_desc(\"# passes\"));\n\n cl::opt \n Verify(\"verify\", cl::desc(\"Verify each pass result\"));\n}\n\n\nstatic inline void addPass(PassManager &PM, Pass *P) {\n static int NumPassesCreated = 0;\n \n \/\/ If we haven't already created the number of passes that was requested...\n if (RunNPasses == 0 || RunNPasses > NumPassesCreated) {\n \/\/ Add the pass to the pass manager...\n PM.add(P);\n\n \/\/ If we are verifying all of the intermediate steps, add the verifier...\n if (Verify) PM.add(createVerifierPass());\n\n \/\/ Keep track of how many passes we made for -stopAfterNPasses\n ++NumPassesCreated;\n } else {\n delete P; \/\/ We don't want this pass to run, just delete it now\n }\n}\n\n\nvoid AddConfiguredTransformationPasses(PassManager &PM) {\n PM.add(createVerifierPass()); \/\/ Verify that input is correct\n addPass(PM, createFunctionResolvingPass()); \/\/ Resolve (...) functions\n addPass(PM, createGlobalDCEPass()); \/\/ Kill unused uinit g-vars\n addPass(PM, createDeadTypeEliminationPass()); \/\/ Eliminate dead types\n addPass(PM, createConstantMergePass()); \/\/ Merge dup global constants\n addPass(PM, createRaiseAllocationsPass()); \/\/ call %malloc -> malloc inst\n addPass(PM, createInstructionCombiningPass()); \/\/ Cleanup code for raise\n addPass(PM, createRaisePointerReferencesPass());\/\/ Recover type information\n addPass(PM, createTailDuplicationPass()); \/\/ Simplify cfg by copying code\n addPass(PM, createCFGSimplificationPass()); \/\/ Merge & remove BBs\n addPass(PM, createInstructionCombiningPass()); \/\/ Combine silly seq's\n addPass(PM, createScalarReplAggregatesPass()); \/\/ Break up aggregate allocas\n addPass(PM, createPromoteMemoryToRegister()); \/\/ Promote alloca's to regs\n addPass(PM, createIndVarSimplifyPass()); \/\/ Simplify indvars\n addPass(PM, createReassociatePass()); \/\/ Reassociate expressions\n \/\/ Kill corr branches\n \/\/addPass(PM, createCorrelatedExpressionEliminationPass());\n addPass(PM, createInstructionCombiningPass()); \/\/ Combine silly seq's\n addPass(PM, createCFGSimplificationPass()); \/\/ Merge & remove BBs\n addPass(PM, createLICMPass()); \/\/ Hoist loop invariants\n addPass(PM, createLoadValueNumberingPass()); \/\/ GVN for load instructions\n addPass(PM, createGCSEPass()); \/\/ Remove common subexprs\n addPass(PM, createSCCPPass()); \/\/ Constant prop with SCCP\n\n \/\/ Run instcombine after redundancy elimination to exploit opportunities\n \/\/ opened up by them.\n addPass(PM, createInstructionCombiningPass());\n addPass(PM, createAggressiveDCEPass()); \/\/ SSA based 'Aggressive DCE'\n addPass(PM, createCFGSimplificationPass()); \/\/ Merge & remove BBs\n}\n\n\nint main(int argc, char **argv) {\n cl::ParseCommandLineOptions(argc, argv, \" llvm .s -> .o assembler for GCC\\n\");\n\n std::auto_ptr M;\n try {\n \/\/ Parse the file now...\n M.reset(ParseAssemblyFile(InputFilename));\n } catch (const ParseException &E) {\n std::cerr << argv[0] << \": \" << E.getMessage() << \"\\n\";\n return 1;\n }\n\n if (M.get() == 0) {\n std::cerr << argv[0] << \": assembly didn't read correctly.\\n\";\n return 1;\n }\n\n std::ostream *Out = 0;\n if (OutputFilename == \"\") { \/\/ Didn't specify an output filename?\n if (InputFilename == \"-\") {\n OutputFilename = \"-\";\n } else {\n std::string IFN = InputFilename;\n int Len = IFN.length();\n if (IFN[Len-2] == '.' && IFN[Len-1] == 's') { \/\/ Source ends in .s?\n OutputFilename = std::string(IFN.begin(), IFN.end()-2);\n } else {\n OutputFilename = IFN; \/\/ Append a .o to it\n }\n OutputFilename += \".o\";\n }\n }\n\n if (OutputFilename == \"-\")\n Out = &std::cout;\n else {\n Out = new std::ofstream(OutputFilename.c_str(), std::ios::out);\n\n \/\/ Make sure that the Out file gets unlink'd from the disk if we get a\n \/\/ signal\n RemoveFileOnSignal(OutputFilename);\n }\n\n \n if (!Out->good()) {\n std::cerr << argv[0] << \": error opening \" << OutputFilename << \"!\\n\";\n return 1;\n }\n\n \/\/ In addition to just parsing the input from GCC, we also want to spiff it up\n \/\/ a little bit. Do this now.\n \/\/\n PassManager Passes;\n\n \/\/ Add an appropriate TargetData instance for this module...\n Passes.add(new TargetData(\"gccas\", M.get()));\n\n \/\/ Add all of the transformation passes to the pass manager to do the cleanup\n \/\/ and optimization of the GCC output.\n \/\/\n AddConfiguredTransformationPasses(Passes);\n\n \/\/ Write bytecode to file...\n Passes.add(new WriteBytecodePass(Out));\n\n \/\/ Run our queue of passes all at once now, efficiently.\n Passes.run(*M.get());\n\n if (Out != &std::cout) delete Out;\n return 0;\n}\nCompletely remove mention of the correlated branch elimination pass. It has bugs and needs to be reworked anyway.\/\/===----------------------------------------------------------------------===\/\/\n\/\/ LLVM 'GCCAS' UTILITY \n\/\/\n\/\/ This utility is designed to be used by the GCC frontend for creating bytecode\n\/\/ files from its intermediate LLVM assembly. The requirements for this utility\n\/\/ are thus slightly different than that of the standard `as' util.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Module.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Analysis\/LoadValueNumbering.h\"\n#include \"llvm\/Analysis\/Verifier.h\"\n#include \"llvm\/Assembly\/Parser.h\"\n#include \"llvm\/Bytecode\/WriteBytecodePass.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Transforms\/RaisePointerReferences.h\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"Support\/CommandLine.h\"\n#include \"Support\/Signals.h\"\n#include \n#include \n\nnamespace {\n cl::opt\n InputFilename(cl::Positional,cl::desc(\"\"),cl::init(\"-\"));\n\n cl::opt \n OutputFilename(\"o\", cl::desc(\"Override output filename\"),\n cl::value_desc(\"filename\"));\n\n cl::opt\n RunNPasses(\"stopAfterNPasses\",\n cl::desc(\"Only run the first N passes of gccas\"), cl::Hidden,\n cl::value_desc(\"# passes\"));\n\n cl::opt \n Verify(\"verify\", cl::desc(\"Verify each pass result\"));\n}\n\n\nstatic inline void addPass(PassManager &PM, Pass *P) {\n static int NumPassesCreated = 0;\n \n \/\/ If we haven't already created the number of passes that was requested...\n if (RunNPasses == 0 || RunNPasses > NumPassesCreated) {\n \/\/ Add the pass to the pass manager...\n PM.add(P);\n\n \/\/ If we are verifying all of the intermediate steps, add the verifier...\n if (Verify) PM.add(createVerifierPass());\n\n \/\/ Keep track of how many passes we made for -stopAfterNPasses\n ++NumPassesCreated;\n } else {\n delete P; \/\/ We don't want this pass to run, just delete it now\n }\n}\n\n\nvoid AddConfiguredTransformationPasses(PassManager &PM) {\n PM.add(createVerifierPass()); \/\/ Verify that input is correct\n addPass(PM, createFunctionResolvingPass()); \/\/ Resolve (...) functions\n addPass(PM, createGlobalDCEPass()); \/\/ Kill unused uinit g-vars\n addPass(PM, createDeadTypeEliminationPass()); \/\/ Eliminate dead types\n addPass(PM, createConstantMergePass()); \/\/ Merge dup global constants\n addPass(PM, createRaiseAllocationsPass()); \/\/ call %malloc -> malloc inst\n addPass(PM, createInstructionCombiningPass()); \/\/ Cleanup code for raise\n addPass(PM, createRaisePointerReferencesPass());\/\/ Recover type information\n addPass(PM, createTailDuplicationPass()); \/\/ Simplify cfg by copying code\n addPass(PM, createCFGSimplificationPass()); \/\/ Merge & remove BBs\n addPass(PM, createInstructionCombiningPass()); \/\/ Combine silly seq's\n addPass(PM, createScalarReplAggregatesPass()); \/\/ Break up aggregate allocas\n addPass(PM, createPromoteMemoryToRegister()); \/\/ Promote alloca's to regs\n addPass(PM, createIndVarSimplifyPass()); \/\/ Simplify indvars\n addPass(PM, createReassociatePass()); \/\/ Reassociate expressions\n addPass(PM, createInstructionCombiningPass()); \/\/ Combine silly seq's\n addPass(PM, createCFGSimplificationPass()); \/\/ Merge & remove BBs\n addPass(PM, createLICMPass()); \/\/ Hoist loop invariants\n addPass(PM, createLoadValueNumberingPass()); \/\/ GVN for load instructions\n addPass(PM, createGCSEPass()); \/\/ Remove common subexprs\n addPass(PM, createSCCPPass()); \/\/ Constant prop with SCCP\n\n \/\/ Run instcombine after redundancy elimination to exploit opportunities\n \/\/ opened up by them.\n addPass(PM, createInstructionCombiningPass());\n addPass(PM, createAggressiveDCEPass()); \/\/ SSA based 'Aggressive DCE'\n addPass(PM, createCFGSimplificationPass()); \/\/ Merge & remove BBs\n}\n\n\nint main(int argc, char **argv) {\n cl::ParseCommandLineOptions(argc, argv, \" llvm .s -> .o assembler for GCC\\n\");\n\n std::auto_ptr M;\n try {\n \/\/ Parse the file now...\n M.reset(ParseAssemblyFile(InputFilename));\n } catch (const ParseException &E) {\n std::cerr << argv[0] << \": \" << E.getMessage() << \"\\n\";\n return 1;\n }\n\n if (M.get() == 0) {\n std::cerr << argv[0] << \": assembly didn't read correctly.\\n\";\n return 1;\n }\n\n std::ostream *Out = 0;\n if (OutputFilename == \"\") { \/\/ Didn't specify an output filename?\n if (InputFilename == \"-\") {\n OutputFilename = \"-\";\n } else {\n std::string IFN = InputFilename;\n int Len = IFN.length();\n if (IFN[Len-2] == '.' && IFN[Len-1] == 's') { \/\/ Source ends in .s?\n OutputFilename = std::string(IFN.begin(), IFN.end()-2);\n } else {\n OutputFilename = IFN; \/\/ Append a .o to it\n }\n OutputFilename += \".o\";\n }\n }\n\n if (OutputFilename == \"-\")\n Out = &std::cout;\n else {\n Out = new std::ofstream(OutputFilename.c_str(), std::ios::out);\n\n \/\/ Make sure that the Out file gets unlink'd from the disk if we get a\n \/\/ signal\n RemoveFileOnSignal(OutputFilename);\n }\n\n \n if (!Out->good()) {\n std::cerr << argv[0] << \": error opening \" << OutputFilename << \"!\\n\";\n return 1;\n }\n\n \/\/ In addition to just parsing the input from GCC, we also want to spiff it up\n \/\/ a little bit. Do this now.\n \/\/\n PassManager Passes;\n\n \/\/ Add an appropriate TargetData instance for this module...\n Passes.add(new TargetData(\"gccas\", M.get()));\n\n \/\/ Add all of the transformation passes to the pass manager to do the cleanup\n \/\/ and optimization of the GCC output.\n \/\/\n AddConfiguredTransformationPasses(Passes);\n\n \/\/ Write bytecode to file...\n Passes.add(new WriteBytecodePass(Out));\n\n \/\/ Run our queue of passes all at once now, efficiently.\n Passes.run(*M.get());\n\n if (Out != &std::cout) delete Out;\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"HexagonOffload.h\"\n#include \"IRMutator.h\"\n#include \"Closure.h\"\n#include \"Param.h\"\n\nnamespace Halide {\nnamespace Internal {\n\nusing std::string;\nusing std::vector;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nclass InjectHexagonRpc : public IRMutator {\n using IRMutator::visit;\n\npublic:\n Module device_code;\n\n InjectHexagonRpc() : device_code(\"hexagon\", Target(Target::HexagonStandalone, Target::Hexagon, 32)) {}\n\n void visit(const For *loop) {\n if (loop->device_api == DeviceAPI::Hexagon) {\n std::string hex_name = \"hex_\" + loop->name;\n\n \/\/ Build a closure for the device code.\n \/\/ TODO: Should this move the body of the loop to Hexagon,\n \/\/ or the loop itself? Currently, this moves the loop itself.\n Closure c(loop);\n\n \/\/ Make an argument list, and generate a function in the device_code module.\n std::vector args;\n for (const auto& i : c.buffers) {\n Argument::Kind kind = Argument::InputBuffer;\n if (i.second.write) {\n kind = Argument::OutputBuffer;\n }\n args.push_back(Argument(i.first, kind, i.second.type, i.second.dimensions));\n }\n for (const auto& i : c.vars) {\n args.push_back(Argument(i.first, Argument::InputScalar, i.second, 0));\n }\n device_code.append(LoweredFunc(hex_name, args, loop, LoweredFunc::External));\n\n \/\/ Generate a call to hexagon_device_run.\n std::vector params;\n params.push_back(user_context_value());\n params.push_back(hex_name);\n for (const auto& i : c.buffers) {\n params.push_back(Variable::make(Handle(), i.first + \".buffer\"));\n }\n for (const auto& i : c.vars) {\n params.push_back(Variable::make(i.second, i.first));\n }\n\n stmt = Evaluate::make(Call::make(Int(32), \"halide_hexagon_run\", params, Call::Extern));\n } else {\n IRMutator::visit(loop);\n }\n }\n};\n\nStmt inject_hexagon_rpc(Stmt s, std::vector& device_code) {\n InjectHexagonRpc injector;\n s = injector.mutate(s);\n device_code.push_back(injector.device_code);\n return s;\n}\n\n}\n\n}\nFix call to halide_hexagon_run to pass arguments as arrays.#include \"HexagonOffload.h\"\n#include \"IRMutator.h\"\n#include \"Closure.h\"\n#include \"Param.h\"\n\nnamespace Halide {\nnamespace Internal {\n\nusing std::string;\nusing std::vector;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nclass InjectHexagonRpc : public IRMutator {\n using IRMutator::visit;\n\npublic:\n Module device_code;\n\n InjectHexagonRpc() : device_code(\"hexagon\", Target(Target::HexagonStandalone, Target::Hexagon, 32)) {}\n\n void visit(const For *loop) {\n if (loop->device_api == DeviceAPI::Hexagon) {\n std::string hex_name = \"hex_\" + loop->name;\n\n \/\/ Build a closure for the device code.\n \/\/ TODO: Should this move the body of the loop to Hexagon,\n \/\/ or the loop itself? Currently, this moves the loop itself.\n Closure c(loop);\n\n \/\/ Make an argument list, and generate a function in the device_code module.\n std::vector args;\n for (const auto& i : c.buffers) {\n Argument::Kind kind = Argument::InputBuffer;\n if (i.second.write) {\n kind = Argument::OutputBuffer;\n }\n args.push_back(Argument(i.first, kind, i.second.type, i.second.dimensions));\n }\n for (const auto& i : c.vars) {\n args.push_back(Argument(i.first, Argument::InputScalar, i.second, 0));\n }\n device_code.append(LoweredFunc(hex_name, args, loop, LoweredFunc::External));\n\n \/\/ Generate a call to hexagon_device_run.\n std::vector arg_sizes;\n std::vector arg_ptrs;\n std::vector arg_is_buffer;\n\n for (const auto& i : c.buffers) {\n arg_sizes.push_back(Expr((size_t)sizeof(buffer_t*)));\n arg_ptrs.push_back(Variable::make(type_of(), i.first + \".buffer\"));\n arg_is_buffer.push_back(Expr((uint8_t)true));\n }\n for (const auto& i : c.vars) {\n Expr arg = Variable::make(i.second, i.first);\n Expr arg_ptr = Call::make(type_of(), Call::make_struct, {arg}, Call::Intrinsic);\n\n arg_sizes.push_back(Expr((size_t)i.second.bytes()));\n arg_ptrs.push_back(arg_ptr);\n arg_is_buffer.push_back(Expr((uint8_t)false));\n }\n\n std::vector params;\n params.push_back(user_context_value());\n params.push_back(hex_name);\n params.push_back(Call::make(type_of(), Call::make_struct, arg_sizes, Call::Intrinsic));\n params.push_back(Call::make(type_of(), Call::make_struct, arg_ptrs, Call::Intrinsic));\n params.push_back(Call::make(type_of(), Call::make_struct, arg_is_buffer, Call::Intrinsic));\n\n stmt = Evaluate::make(Call::make(Int(32), \"halide_hexagon_run\", params, Call::Extern));\n } else {\n IRMutator::visit(loop);\n }\n }\n};\n\nStmt inject_hexagon_rpc(Stmt s, std::vector& device_code) {\n InjectHexagonRpc injector;\n s = injector.mutate(s);\n device_code.push_back(injector.device_code);\n return s;\n}\n\n}\n\n}\n<|endoftext|>"} {"text":"\/\/===- gccld.cpp - LLVM 'ld' compatible linker ----------------------------===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This utility is intended to be compatible with GCC, and follows standard\n\/\/ system 'ld' conventions. As such, the default output file is .\/a.out.\n\/\/ Additionally, this program outputs a shell script that is used to invoke LLI\n\/\/ to execute the program. In this manner, the generated executable (a.out for\n\/\/ example), is directly executable, whereas the bytecode file actually lives in\n\/\/ the a.out.bc file generated by this program. Also, Force is on by default.\n\/\/\n\/\/ Note that if someone (or a script) deletes the executable program generated,\n\/\/ the .bc file will be left around. Considering that this is a temporary hack,\n\/\/ I'm not too worried about this.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"gccld.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Bytecode\/Reader.h\"\n#include \"llvm\/Bytecode\/WriteBytecodePass.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Transforms\/Utils\/Linker.h\"\n#include \"Support\/CommandLine.h\"\n#include \"Support\/FileUtilities.h\"\n#include \"Support\/Signals.h\"\n#include \"Support\/SystemUtils.h\"\n#include \n#include \n\nusing namespace llvm;\n\nnamespace {\n cl::list \n InputFilenames(cl::Positional, cl::desc(\"\"),\n cl::OneOrMore);\n\n cl::opt \n OutputFilename(\"o\", cl::desc(\"Override output filename\"), cl::init(\"a.out\"),\n cl::value_desc(\"filename\"));\n\n cl::opt \n Verbose(\"v\", cl::desc(\"Print information about actions taken\"));\n \n cl::list \n LibPaths(\"L\", cl::desc(\"Specify a library search path\"), cl::Prefix,\n cl::value_desc(\"directory\"));\n\n cl::list \n Libraries(\"l\", cl::desc(\"Specify libraries to link to\"), cl::Prefix,\n cl::value_desc(\"library prefix\"));\n\n cl::opt\n Strip(\"s\", cl::desc(\"Strip symbol info from executable\"));\n\n cl::opt\n NoInternalize(\"disable-internalize\",\n cl::desc(\"Do not mark all symbols as internal\"));\n cl::alias\n ExportDynamic(\"export-dynamic\", cl::desc(\"Alias for -disable-internalize\"),\n cl::aliasopt(NoInternalize));\n\n cl::opt\n LinkAsLibrary(\"link-as-library\", cl::desc(\"Link the .bc files together as a\"\n \" library, not an executable\"));\n cl::alias\n Relink(\"r\", cl::desc(\"Alias for -link-as-library\"),\n cl::aliasopt(LinkAsLibrary));\n\n cl::opt \n Native(\"native\",\n cl::desc(\"Generate a native binary instead of a shell script\"));\n \n \/\/ Compatibility options that are ignored but supported by LD\n cl::opt\n CO3(\"soname\", cl::Hidden, cl::desc(\"Compatibility option: ignored\"));\n cl::opt\n CO4(\"version-script\", cl::Hidden, cl::desc(\"Compatibility option: ignored\"));\n cl::opt\n CO5(\"eh-frame-hdr\", cl::Hidden, cl::desc(\"Compatibility option: ignored\"));\n}\n\nnamespace llvm {\n\n\/\/\/ PrintAndReturn - Prints a message to standard error and returns a value\n\/\/\/ usable for an exit status.\n\/\/\/\n\/\/\/ Inputs:\n\/\/\/ progname - The name of the program (i.e. argv[0]).\n\/\/\/ Message - The message to print to standard error.\n\/\/\/ Extra - Extra information to print between the program name and thei\n\/\/\/ message. It is optional.\n\/\/\/\n\/\/\/ Return value:\n\/\/\/ Returns a value that can be used as the exit status (i.e. for exit()).\n\/\/\/\nint\nPrintAndReturn(const char *progname,\n const std::string &Message,\n const std::string &Extra)\n{\n std::cerr << progname << Extra << \": \" << Message << \"\\n\";\n return 1;\n}\n\n\/\/\/ CopyEnv - This function takes an array of environment variables and makes a\n\/\/\/ copy of it. This copy can then be manipulated any way the caller likes\n\/\/\/ without affecting the process's real environment.\n\/\/\/\n\/\/\/ Inputs:\n\/\/\/ envp - An array of C strings containing an environment.\n\/\/\/\n\/\/\/ Return value:\n\/\/\/ NULL - An error occurred.\n\/\/\/\n\/\/\/ Otherwise, a pointer to a new array of C strings is returned. Every string\n\/\/\/ in the array is a duplicate of the one in the original array (i.e. we do\n\/\/\/ not copy the char *'s from one array to another).\n\/\/\/\nchar ** CopyEnv(char ** const envp) {\n \/\/ Count the number of entries in the old list;\n unsigned entries; \/\/ The number of entries in the old environment list\n for (entries = 0; envp[entries] != NULL; entries++)\n {\n ;\n }\n\n \/\/ Add one more entry for the NULL pointer that ends the list.\n ++entries;\n\n \/\/ If there are no entries at all, just return NULL.\n if (entries == 0)\n return NULL;\n\n \/\/ Allocate a new environment list.\n char **newenv;\n if ((newenv = new (char *) [entries]) == NULL)\n return NULL;\n\n \/\/ Make a copy of the list. Don't forget the NULL that ends the list.\n entries = 0;\n while (envp[entries] != NULL) {\n newenv[entries] = new char[strlen (envp[entries]) + 1];\n strcpy (newenv[entries], envp[entries]);\n ++entries;\n }\n newenv[entries] = NULL;\n\n return newenv;\n}\n\n\n\/\/\/ RemoveEnv - Remove the specified environment variable from the environment\n\/\/\/ array.\n\/\/\/\n\/\/\/ Inputs:\n\/\/\/ name - The name of the variable to remove. It cannot be NULL.\n\/\/\/ envp - The array of environment variables. It cannot be NULL.\n\/\/\/\n\/\/\/ Notes:\n\/\/\/ This is mainly done because functions to remove items from the environment\n\/\/\/ are not available across all platforms. In particular, Solaris does not\n\/\/\/ seem to have an unsetenv() function or a setenv() function (or they are\n\/\/\/ undocumented if they do exist).\n\/\/\/\nvoid RemoveEnv(const char * name, char ** const envp) {\n for (unsigned index=0; envp[index] != NULL; index++) {\n \/\/ Find the first equals sign in the array and make it an EOS character.\n char *p = strchr (envp[index], '=');\n if (p == NULL)\n continue;\n else\n *p = '\\0';\n\n \/\/ Compare the two strings. If they are equal, zap this string.\n \/\/ Otherwise, restore it.\n if (!strcmp(name, envp[index]))\n *envp[index] = '\\0';\n else\n *p = '=';\n }\n\n return;\n}\n\n} \/\/ End llvm namespace\n\nint main(int argc, char **argv, char **envp) {\n cl::ParseCommandLineOptions(argc, argv, \" llvm linker for GCC\\n\");\n\n std::string ModuleID(\"gccld-output\");\n std::auto_ptr Composite(new Module(ModuleID));\n\n \/\/ We always look first in the current directory when searching for libraries.\n LibPaths.insert(LibPaths.begin(), \".\");\n\n \/\/ If the user specified an extra search path in their environment, respect\n \/\/ it.\n if (char *SearchPath = getenv(\"LLVM_LIB_SEARCH_PATH\"))\n LibPaths.push_back(SearchPath);\n\n \/\/ Remove any consecutive duplicates of the same library...\n Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),\n Libraries.end());\n\n \/\/ Link in all of the files\n if (LinkFiles(argv[0], Composite.get(), InputFilenames, Verbose))\n return 1; \/\/ Error already printed\n\n if (!LinkAsLibrary)\n LinkLibraries(argv[0], Composite.get(), Libraries, LibPaths,\n Verbose, Native);\n\n \/\/ Link in all of the libraries next...\n\n \/\/ Create the output file.\n std::string RealBytecodeOutput = OutputFilename;\n if (!LinkAsLibrary) RealBytecodeOutput += \".bc\";\n std::ofstream Out(RealBytecodeOutput.c_str());\n if (!Out.good())\n return PrintAndReturn(argv[0], \"error opening '\" + RealBytecodeOutput +\n \"' for writing!\");\n\n \/\/ Ensure that the bytecode file gets removed from the disk if we get a\n \/\/ SIGINT signal.\n RemoveFileOnSignal(RealBytecodeOutput);\n\n \/\/ Generate the bytecode file.\n if (GenerateBytecode(Composite.get(), Strip, !NoInternalize, &Out)) {\n Out.close();\n return PrintAndReturn(argv[0], \"error generating bytecode\");\n }\n\n \/\/ Close the bytecode file.\n Out.close();\n\n \/\/ If we are not linking a library, generate either a native executable\n \/\/ or a JIT shell script, depending upon what the user wants.\n if (!LinkAsLibrary) {\n \/\/ If the user wants to generate a native executable, compile it from the\n \/\/ bytecode file.\n \/\/\n \/\/ Otherwise, create a script that will run the bytecode through the JIT.\n if (Native) {\n \/\/ Name of the Assembly Language output file\n std::string AssemblyFile = OutputFilename + \".s\";\n\n \/\/ Mark the output files for removal if we get an interrupt.\n RemoveFileOnSignal(AssemblyFile);\n RemoveFileOnSignal(OutputFilename);\n\n \/\/ Determine the locations of the llc and gcc programs.\n std::string llc = FindExecutable(\"llc\", argv[0]);\n std::string gcc = FindExecutable(\"gcc\", argv[0]);\n if (llc.empty())\n return PrintAndReturn(argv[0], \"Failed to find llc\");\n\n if (gcc.empty())\n return PrintAndReturn(argv[0], \"Failed to find gcc\");\n\n \/\/ Generate an assembly language file for the bytecode.\n if (Verbose) std::cout << \"Generating Assembly Code\\n\";\n GenerateAssembly(AssemblyFile, RealBytecodeOutput, llc, envp);\n if (Verbose) std::cout << \"Generating Native Code\\n\";\n GenerateNative(OutputFilename, AssemblyFile, Libraries, LibPaths,\n gcc, envp);\n\n \/\/ Remove the assembly language file.\n removeFile (AssemblyFile);\n } else {\n \/\/ Output the script to start the program...\n std::ofstream Out2(OutputFilename.c_str());\n if (!Out2.good())\n return PrintAndReturn(argv[0], \"error opening '\" + OutputFilename +\n \"' for writing!\");\n Out2 << \"#!\/bin\/sh\\nlli $0.bc $*\\n\";\n Out2.close();\n }\n \n \/\/ Make the script executable...\n MakeFileExecutable(OutputFilename);\n\n \/\/ Make the bytecode file readable and directly executable in LLEE as well\n MakeFileExecutable(RealBytecodeOutput);\n MakeFileReadable(RealBytecodeOutput);\n }\n\n return 0;\n}\nWhen writing out the runner script, add -load= lines to pull in all the shared objects automagically, so it doesn't have to be done by hand.\/\/===- gccld.cpp - LLVM 'ld' compatible linker ----------------------------===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This utility is intended to be compatible with GCC, and follows standard\n\/\/ system 'ld' conventions. As such, the default output file is .\/a.out.\n\/\/ Additionally, this program outputs a shell script that is used to invoke LLI\n\/\/ to execute the program. In this manner, the generated executable (a.out for\n\/\/ example), is directly executable, whereas the bytecode file actually lives in\n\/\/ the a.out.bc file generated by this program. Also, Force is on by default.\n\/\/\n\/\/ Note that if someone (or a script) deletes the executable program generated,\n\/\/ the .bc file will be left around. Considering that this is a temporary hack,\n\/\/ I'm not too worried about this.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"gccld.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Bytecode\/Reader.h\"\n#include \"llvm\/Bytecode\/WriteBytecodePass.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Transforms\/Utils\/Linker.h\"\n#include \"Support\/CommandLine.h\"\n#include \"Support\/FileUtilities.h\"\n#include \"Support\/Signals.h\"\n#include \"Support\/SystemUtils.h\"\n#include \n#include \n\nusing namespace llvm;\n\nnamespace {\n cl::list \n InputFilenames(cl::Positional, cl::desc(\"\"),\n cl::OneOrMore);\n\n cl::opt \n OutputFilename(\"o\", cl::desc(\"Override output filename\"), cl::init(\"a.out\"),\n cl::value_desc(\"filename\"));\n\n cl::opt \n Verbose(\"v\", cl::desc(\"Print information about actions taken\"));\n \n cl::list \n LibPaths(\"L\", cl::desc(\"Specify a library search path\"), cl::Prefix,\n cl::value_desc(\"directory\"));\n\n cl::list \n Libraries(\"l\", cl::desc(\"Specify libraries to link to\"), cl::Prefix,\n cl::value_desc(\"library prefix\"));\n\n cl::opt\n Strip(\"s\", cl::desc(\"Strip symbol info from executable\"));\n\n cl::opt\n NoInternalize(\"disable-internalize\",\n cl::desc(\"Do not mark all symbols as internal\"));\n cl::alias\n ExportDynamic(\"export-dynamic\", cl::desc(\"Alias for -disable-internalize\"),\n cl::aliasopt(NoInternalize));\n\n cl::opt\n LinkAsLibrary(\"link-as-library\", cl::desc(\"Link the .bc files together as a\"\n \" library, not an executable\"));\n cl::alias\n Relink(\"r\", cl::desc(\"Alias for -link-as-library\"),\n cl::aliasopt(LinkAsLibrary));\n\n cl::opt \n Native(\"native\",\n cl::desc(\"Generate a native binary instead of a shell script\"));\n \n \/\/ Compatibility options that are ignored but supported by LD\n cl::opt\n CO3(\"soname\", cl::Hidden, cl::desc(\"Compatibility option: ignored\"));\n cl::opt\n CO4(\"version-script\", cl::Hidden, cl::desc(\"Compatibility option: ignored\"));\n cl::opt\n CO5(\"eh-frame-hdr\", cl::Hidden, cl::desc(\"Compatibility option: ignored\"));\n}\n\nnamespace llvm {\n\n\/\/\/ PrintAndReturn - Prints a message to standard error and returns a value\n\/\/\/ usable for an exit status.\n\/\/\/\n\/\/\/ Inputs:\n\/\/\/ progname - The name of the program (i.e. argv[0]).\n\/\/\/ Message - The message to print to standard error.\n\/\/\/ Extra - Extra information to print between the program name and thei\n\/\/\/ message. It is optional.\n\/\/\/\n\/\/\/ Return value:\n\/\/\/ Returns a value that can be used as the exit status (i.e. for exit()).\n\/\/\/\nint\nPrintAndReturn(const char *progname,\n const std::string &Message,\n const std::string &Extra)\n{\n std::cerr << progname << Extra << \": \" << Message << \"\\n\";\n return 1;\n}\n\n\/\/\/ CopyEnv - This function takes an array of environment variables and makes a\n\/\/\/ copy of it. This copy can then be manipulated any way the caller likes\n\/\/\/ without affecting the process's real environment.\n\/\/\/\n\/\/\/ Inputs:\n\/\/\/ envp - An array of C strings containing an environment.\n\/\/\/\n\/\/\/ Return value:\n\/\/\/ NULL - An error occurred.\n\/\/\/\n\/\/\/ Otherwise, a pointer to a new array of C strings is returned. Every string\n\/\/\/ in the array is a duplicate of the one in the original array (i.e. we do\n\/\/\/ not copy the char *'s from one array to another).\n\/\/\/\nchar ** CopyEnv(char ** const envp) {\n \/\/ Count the number of entries in the old list;\n unsigned entries; \/\/ The number of entries in the old environment list\n for (entries = 0; envp[entries] != NULL; entries++)\n {\n ;\n }\n\n \/\/ Add one more entry for the NULL pointer that ends the list.\n ++entries;\n\n \/\/ If there are no entries at all, just return NULL.\n if (entries == 0)\n return NULL;\n\n \/\/ Allocate a new environment list.\n char **newenv;\n if ((newenv = new (char *) [entries]) == NULL)\n return NULL;\n\n \/\/ Make a copy of the list. Don't forget the NULL that ends the list.\n entries = 0;\n while (envp[entries] != NULL) {\n newenv[entries] = new char[strlen (envp[entries]) + 1];\n strcpy (newenv[entries], envp[entries]);\n ++entries;\n }\n newenv[entries] = NULL;\n\n return newenv;\n}\n\n\n\/\/\/ RemoveEnv - Remove the specified environment variable from the environment\n\/\/\/ array.\n\/\/\/\n\/\/\/ Inputs:\n\/\/\/ name - The name of the variable to remove. It cannot be NULL.\n\/\/\/ envp - The array of environment variables. It cannot be NULL.\n\/\/\/\n\/\/\/ Notes:\n\/\/\/ This is mainly done because functions to remove items from the environment\n\/\/\/ are not available across all platforms. In particular, Solaris does not\n\/\/\/ seem to have an unsetenv() function or a setenv() function (or they are\n\/\/\/ undocumented if they do exist).\n\/\/\/\nvoid RemoveEnv(const char * name, char ** const envp) {\n for (unsigned index=0; envp[index] != NULL; index++) {\n \/\/ Find the first equals sign in the array and make it an EOS character.\n char *p = strchr (envp[index], '=');\n if (p == NULL)\n continue;\n else\n *p = '\\0';\n\n \/\/ Compare the two strings. If they are equal, zap this string.\n \/\/ Otherwise, restore it.\n if (!strcmp(name, envp[index]))\n *envp[index] = '\\0';\n else\n *p = '=';\n }\n\n return;\n}\n\n} \/\/ End llvm namespace\n\nint main(int argc, char **argv, char **envp) {\n cl::ParseCommandLineOptions(argc, argv, \" llvm linker for GCC\\n\");\n\n std::string ModuleID(\"gccld-output\");\n std::auto_ptr Composite(new Module(ModuleID));\n\n \/\/ We always look first in the current directory when searching for libraries.\n LibPaths.insert(LibPaths.begin(), \".\");\n\n \/\/ If the user specified an extra search path in their environment, respect\n \/\/ it.\n if (char *SearchPath = getenv(\"LLVM_LIB_SEARCH_PATH\"))\n LibPaths.push_back(SearchPath);\n\n \/\/ Remove any consecutive duplicates of the same library...\n Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),\n Libraries.end());\n\n \/\/ Link in all of the files\n if (LinkFiles(argv[0], Composite.get(), InputFilenames, Verbose))\n return 1; \/\/ Error already printed\n\n if (!LinkAsLibrary)\n LinkLibraries(argv[0], Composite.get(), Libraries, LibPaths,\n Verbose, Native);\n\n \/\/ Link in all of the libraries next...\n\n \/\/ Create the output file.\n std::string RealBytecodeOutput = OutputFilename;\n if (!LinkAsLibrary) RealBytecodeOutput += \".bc\";\n std::ofstream Out(RealBytecodeOutput.c_str());\n if (!Out.good())\n return PrintAndReturn(argv[0], \"error opening '\" + RealBytecodeOutput +\n \"' for writing!\");\n\n \/\/ Ensure that the bytecode file gets removed from the disk if we get a\n \/\/ SIGINT signal.\n RemoveFileOnSignal(RealBytecodeOutput);\n\n \/\/ Generate the bytecode file.\n if (GenerateBytecode(Composite.get(), Strip, !NoInternalize, &Out)) {\n Out.close();\n return PrintAndReturn(argv[0], \"error generating bytecode\");\n }\n\n \/\/ Close the bytecode file.\n Out.close();\n\n \/\/ If we are not linking a library, generate either a native executable\n \/\/ or a JIT shell script, depending upon what the user wants.\n if (!LinkAsLibrary) {\n \/\/ If the user wants to generate a native executable, compile it from the\n \/\/ bytecode file.\n \/\/\n \/\/ Otherwise, create a script that will run the bytecode through the JIT.\n if (Native) {\n \/\/ Name of the Assembly Language output file\n std::string AssemblyFile = OutputFilename + \".s\";\n\n \/\/ Mark the output files for removal if we get an interrupt.\n RemoveFileOnSignal(AssemblyFile);\n RemoveFileOnSignal(OutputFilename);\n\n \/\/ Determine the locations of the llc and gcc programs.\n std::string llc = FindExecutable(\"llc\", argv[0]);\n std::string gcc = FindExecutable(\"gcc\", argv[0]);\n if (llc.empty())\n return PrintAndReturn(argv[0], \"Failed to find llc\");\n\n if (gcc.empty())\n return PrintAndReturn(argv[0], \"Failed to find gcc\");\n\n \/\/ Generate an assembly language file for the bytecode.\n if (Verbose) std::cout << \"Generating Assembly Code\\n\";\n GenerateAssembly(AssemblyFile, RealBytecodeOutput, llc, envp);\n if (Verbose) std::cout << \"Generating Native Code\\n\";\n GenerateNative(OutputFilename, AssemblyFile, Libraries, LibPaths,\n gcc, envp);\n\n \/\/ Remove the assembly language file.\n removeFile (AssemblyFile);\n } else {\n \/\/ Output the script to start the program...\n std::ofstream Out2(OutputFilename.c_str());\n if (!Out2.good())\n return PrintAndReturn(argv[0], \"error opening '\" + OutputFilename +\n \"' for writing!\");\n Out2 << \"#!\/bin\/sh\\nlli \\\\\\n\";\n \/\/ gcc accepts -l and implicitly searches \/lib and \/usr\/lib.\n LibPaths.push_back(\"\/lib\");\n LibPaths.push_back(\"\/usr\/lib\");\n \/\/ We don't need to link in libc! In fact, \/usr\/lib\/libc.so may not be a\n \/\/ shared object at all! See RH 8: plain text.\n std::vector::iterator libc = \n std::find(Libraries.begin(), Libraries.end(), \"c\");\n if (libc != Libraries.end()) Libraries.erase(libc);\n \/\/ List all the shared object (native) libraries this executable will need\n \/\/ on the command line, so that we don't have to do this manually!\n for (std::vector::iterator i = Libraries.begin(), \n e = Libraries.end(); i != e; ++i) {\n std::string FullLibraryPath = FindLib(*i, LibPaths, true);\n if (!FullLibraryPath.empty())\n Out2 << \" -load=\" << FullLibraryPath << \" \\\\\\n\";\n }\n Out2 << \" $0.bc $*\\n\";\n Out2.close();\n }\n \n \/\/ Make the script executable...\n MakeFileExecutable(OutputFilename);\n\n \/\/ Make the bytecode file readable and directly executable in LLEE as well\n MakeFileExecutable(RealBytecodeOutput);\n MakeFileReadable(RealBytecodeOutput);\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"multiVolumes.h\"\n\nnamespace cura \n{\n \nvoid carveMultipleVolumes(std::vector &volumes, bool alternate_carve_order)\n{\n \/\/Go trough all the volumes, and remove the previous volume outlines from our own outline, so we never have overlapped areas.\n for (unsigned int volume_1_idx = 1; volume_1_idx < volumes.size(); volume_1_idx++)\n {\n Slicer& volume_1 = *volumes[volume_1_idx];\n if (volume_1.mesh->getSettingBoolean(\"infill_mesh\") \n || volume_1.mesh->getSettingBoolean(\"anti_overhang_mesh\")\n || volume_1.mesh->getSettingBoolean(\"support_mesh\")\n )\n {\n continue;\n }\n for (unsigned int volume_2_idx = 0; volume_2_idx < volume_1_idx; volume_2_idx++)\n {\n Slicer& volume_2 = *volumes[volume_2_idx];\n if (volume_2.mesh->getSettingBoolean(\"infill_mesh\")\n || volume_2.mesh->getSettingBoolean(\"anti_overhang_mesh\")\n || volume_2.mesh->getSettingBoolean(\"support_mesh\")\n )\n {\n continue;\n }\n if (!volume_1.mesh->getAABB().hit(volume_2.mesh->getAABB()))\n {\n continue;\n }\n for (unsigned int layerNr = 0; layerNr < volume_1.layers.size(); layerNr++)\n {\n SlicerLayer& layer1 = volume_1.layers[layerNr];\n SlicerLayer& layer2 = volume_2.layers[layerNr];\n if (alternate_carve_order && layerNr % 2 == 0)\n {\n layer2.polygons = layer2.polygons.difference(layer1.polygons);\n }\n else\n {\n layer1.polygons = layer1.polygons.difference(layer2.polygons);\n }\n }\n }\n }\n}\n \n\/\/Expand each layer a bit and then keep the extra overlapping parts that overlap with other volumes.\n\/\/This generates some overlap in dual extrusion, for better bonding in touching parts.\nvoid generateMultipleVolumesOverlap(std::vector &volumes)\n{\n if (volumes.size() < 2)\n {\n return;\n }\n\n int offset_to_merge_other_merged_volumes = 20;\n for (Slicer* volume : volumes)\n {\n int overlap = volume->mesh->getSettingInMicrons(\"multiple_mesh_overlap\");\n if (volume->mesh->getSettingBoolean(\"infill_mesh\")\n || volume->mesh->getSettingBoolean(\"anti_overhang_mesh\")\n || volume->mesh->getSettingBoolean(\"support_mesh\")\n || overlap == 0)\n {\n continue;\n }\n AABB3D aabb(volume->mesh->getAABB());\n aabb.expandXY(overlap); \/\/ expand to account for the case where two models and their bounding boxes are adjacent along the X or Y-direction\n for (unsigned int layer_nr = 0; layer_nr < volume->layers.size(); layer_nr++)\n {\n Polygons all_other_volumes;\n for (Slicer* other_volume : volumes)\n {\n if (other_volume->mesh->getSettingBoolean(\"infill_mesh\")\n || other_volume->mesh->getSettingBoolean(\"anti_overhang_mesh\")\n || other_volume->mesh->getSettingBoolean(\"support_mesh\")\n || !other_volume->mesh->getAABB().hit(aabb)\n || other_volume == volume\n )\n {\n continue;\n }\n SlicerLayer& other_volume_layer = other_volume->layers[layer_nr];\n all_other_volumes = all_other_volumes.unionPolygons(other_volume_layer.polygons.offset(offset_to_merge_other_merged_volumes));\n }\n\n SlicerLayer& volume_layer = volume->layers[layer_nr];\n volume_layer.polygons = volume_layer.polygons.unionPolygons(all_other_volumes.intersection(volume_layer.polygons.offset(overlap \/ 2)));\n }\n }\n}\n\nvoid MultiVolumes::carveCuttingMeshes(std::vector& volumes, const std::vector& meshes)\n{\n for (unsigned int carving_mesh_idx = 0; carving_mesh_idx < volumes.size(); carving_mesh_idx++)\n {\n const Mesh& cutting_mesh = meshes[carving_mesh_idx];\n if (!cutting_mesh.getSettingBoolean(\"cutting_mesh\"))\n {\n continue;\n }\n Slicer& cutting_mesh_volume = *volumes[carving_mesh_idx];\n for (unsigned int layer_nr = 0; layer_nr < cutting_mesh_volume.layers.size(); layer_nr++)\n {\n Polygons& cutting_mesh_layer = cutting_mesh_volume.layers[layer_nr].polygons;\n Polygons new_outlines;\n for (unsigned int carved_mesh_idx = 0; carved_mesh_idx < volumes.size(); carved_mesh_idx++)\n {\n const Mesh& carved_mesh = meshes[carved_mesh_idx];\n if (carved_mesh_idx == carving_mesh_idx || carved_mesh.getSettingBoolean(\"cutting_mesh\"))\n {\n continue;\n }\n Slicer& carved_volume = *volumes[carved_mesh_idx];\n Polygons& carved_mesh_layer = carved_volume.layers[layer_nr].polygons;\n Polygons intersection = cutting_mesh_layer.intersection(carved_mesh_layer);\n new_outlines.add(intersection);\n carved_mesh_layer = carved_mesh_layer.difference(cutting_mesh_layer);\n }\n cutting_mesh_layer = new_outlines;\n }\n }\n}\n\n\n}\/\/namespace cura\nfix: union polygons after cutting meshes (CURA-966)#include \"multiVolumes.h\"\n\nnamespace cura \n{\n \nvoid carveMultipleVolumes(std::vector &volumes, bool alternate_carve_order)\n{\n \/\/Go trough all the volumes, and remove the previous volume outlines from our own outline, so we never have overlapped areas.\n for (unsigned int volume_1_idx = 1; volume_1_idx < volumes.size(); volume_1_idx++)\n {\n Slicer& volume_1 = *volumes[volume_1_idx];\n if (volume_1.mesh->getSettingBoolean(\"infill_mesh\") \n || volume_1.mesh->getSettingBoolean(\"anti_overhang_mesh\")\n || volume_1.mesh->getSettingBoolean(\"support_mesh\")\n )\n {\n continue;\n }\n for (unsigned int volume_2_idx = 0; volume_2_idx < volume_1_idx; volume_2_idx++)\n {\n Slicer& volume_2 = *volumes[volume_2_idx];\n if (volume_2.mesh->getSettingBoolean(\"infill_mesh\")\n || volume_2.mesh->getSettingBoolean(\"anti_overhang_mesh\")\n || volume_2.mesh->getSettingBoolean(\"support_mesh\")\n )\n {\n continue;\n }\n if (!volume_1.mesh->getAABB().hit(volume_2.mesh->getAABB()))\n {\n continue;\n }\n for (unsigned int layerNr = 0; layerNr < volume_1.layers.size(); layerNr++)\n {\n SlicerLayer& layer1 = volume_1.layers[layerNr];\n SlicerLayer& layer2 = volume_2.layers[layerNr];\n if (alternate_carve_order && layerNr % 2 == 0)\n {\n layer2.polygons = layer2.polygons.difference(layer1.polygons);\n }\n else\n {\n layer1.polygons = layer1.polygons.difference(layer2.polygons);\n }\n }\n }\n }\n}\n \n\/\/Expand each layer a bit and then keep the extra overlapping parts that overlap with other volumes.\n\/\/This generates some overlap in dual extrusion, for better bonding in touching parts.\nvoid generateMultipleVolumesOverlap(std::vector &volumes)\n{\n if (volumes.size() < 2)\n {\n return;\n }\n\n int offset_to_merge_other_merged_volumes = 20;\n for (Slicer* volume : volumes)\n {\n int overlap = volume->mesh->getSettingInMicrons(\"multiple_mesh_overlap\");\n if (volume->mesh->getSettingBoolean(\"infill_mesh\")\n || volume->mesh->getSettingBoolean(\"anti_overhang_mesh\")\n || volume->mesh->getSettingBoolean(\"support_mesh\")\n || overlap == 0)\n {\n continue;\n }\n AABB3D aabb(volume->mesh->getAABB());\n aabb.expandXY(overlap); \/\/ expand to account for the case where two models and their bounding boxes are adjacent along the X or Y-direction\n for (unsigned int layer_nr = 0; layer_nr < volume->layers.size(); layer_nr++)\n {\n Polygons all_other_volumes;\n for (Slicer* other_volume : volumes)\n {\n if (other_volume->mesh->getSettingBoolean(\"infill_mesh\")\n || other_volume->mesh->getSettingBoolean(\"anti_overhang_mesh\")\n || other_volume->mesh->getSettingBoolean(\"support_mesh\")\n || !other_volume->mesh->getAABB().hit(aabb)\n || other_volume == volume\n )\n {\n continue;\n }\n SlicerLayer& other_volume_layer = other_volume->layers[layer_nr];\n all_other_volumes = all_other_volumes.unionPolygons(other_volume_layer.polygons.offset(offset_to_merge_other_merged_volumes));\n }\n\n SlicerLayer& volume_layer = volume->layers[layer_nr];\n volume_layer.polygons = volume_layer.polygons.unionPolygons(all_other_volumes.intersection(volume_layer.polygons.offset(overlap \/ 2)));\n }\n }\n}\n\nvoid MultiVolumes::carveCuttingMeshes(std::vector& volumes, const std::vector& meshes)\n{\n for (unsigned int carving_mesh_idx = 0; carving_mesh_idx < volumes.size(); carving_mesh_idx++)\n {\n const Mesh& cutting_mesh = meshes[carving_mesh_idx];\n if (!cutting_mesh.getSettingBoolean(\"cutting_mesh\"))\n {\n continue;\n }\n Slicer& cutting_mesh_volume = *volumes[carving_mesh_idx];\n for (unsigned int layer_nr = 0; layer_nr < cutting_mesh_volume.layers.size(); layer_nr++)\n {\n Polygons& cutting_mesh_layer = cutting_mesh_volume.layers[layer_nr].polygons;\n Polygons new_outlines;\n for (unsigned int carved_mesh_idx = 0; carved_mesh_idx < volumes.size(); carved_mesh_idx++)\n {\n const Mesh& carved_mesh = meshes[carved_mesh_idx];\n if (carved_mesh_idx == carving_mesh_idx || carved_mesh.getSettingBoolean(\"cutting_mesh\"))\n {\n continue;\n }\n Slicer& carved_volume = *volumes[carved_mesh_idx];\n Polygons& carved_mesh_layer = carved_volume.layers[layer_nr].polygons;\n Polygons intersection = cutting_mesh_layer.intersection(carved_mesh_layer);\n new_outlines.add(intersection);\n carved_mesh_layer = carved_mesh_layer.difference(cutting_mesh_layer);\n }\n cutting_mesh_layer = new_outlines.unionPolygons();\n }\n }\n}\n\n\n}\/\/namespace cura\n<|endoftext|>"} {"text":"#include \"radial_solver.h\"\n\nnamespace sirius {\n\nint Radial_solver::integrate(int nr, int l, double enu, sirius::Spline& ve, sirius::Spline& mp, \n std::vector& p, std::vector& dpdr, std::vector& q, \n std::vector& dqdr)\n{\n double alpha2 = 0.5 * pow((1 \/ speed_of_light), 2);\n if (!relativistic_) alpha2 = 0.0;\n\n double enu0 = 0.0;\n if (relativistic_) enu0 = enu;\n\n double ll2 = 0.5 * l * (l + 1);\n\n double x2 = radial_grid_[0];\n double x2inv = radial_grid_.rinv(0);\n double v2 = ve[0] + zn_ \/ x2;\n double m2 = 1 - (v2 - enu0) * alpha2;\n\n p.resize(nr);\n dpdr.resize(nr);\n q.resize(nr);\n dqdr.resize(nr);\n\n \/\/ TODO: check r->0 asymptotic\n p[0] = pow(radial_grid_[0], l + 1) * exp(zn_ * radial_grid_[0] \/ (l + 1));\n q[0] = (0.5 \/ m2) * p[0] * (l \/ radial_grid_[0] + zn_ \/ (l + 1));\n\n double p2 = p[0];\n double q2 = q[0];\n double mp2 = mp[0];\n double vl2 = ll2 \/ m2 \/ pow(x2, 2);\n\n double v2enuvl2 = (v2 - enu + vl2);\n\n double pk[4];\n double qk[4];\n \n for (int i = 0; i < nr - 1; i++)\n {\n double x0 = x2;\n x2 = radial_grid_[i + 1];\n double x0inv = x2inv;\n x2inv = radial_grid_.rinv(i + 1);\n double h = radial_grid_.dr(i);\n double h1 = h \/ 2;\n\n double x1 = x0 + h1;\n double x1inv = 1.0 \/ x1;\n double p0 = p2;\n double q0 = q2;\n double m0 = m2;\n v2 = ve[i + 1] + zn_ * x2inv;\n\n double mp0 = mp2;\n mp2 = mp[i + 1];\n double mp1 = mp(i, h1);\n double v1 = ve(i, h1) + zn_ * x1inv;\n double m1 = 1 - (v1 - enu0) * alpha2;\n m2 = 1 - (v2 - enu0) * alpha2;\n vl2 = ll2 \/ m2 \/ pow(x2, 2);\n \n double v0enuvl0 = v2enuvl2;\n v2enuvl2 = (v2 - enu + vl2);\n \n double vl1 = ll2 \/ m1 \/ pow(x1, 2);\n\n double v1enuvl1 = (v1 - enu + vl1);\n \n \/\/ k0 = F(Y(x), x)\n pk[0] = 2 * m0 * q0 + p0 * x0inv;\n qk[0] = v0enuvl0 * p0 - q0 * x0inv - mp0;\n\n \/\/ k1 = F(Y(x) + k0 * h\/2, x + h\/2)\n pk[1] = 2 * m1 * (q0 + qk[0] * h1) + (p0 + pk[0] * h1) * x1inv;\n qk[1] = v1enuvl1 * (p0 + pk[0] * h1) - (q0 + qk[0] * h1) * x1inv - mp1;\n\n \/\/ k2 = F(Y(x) + k1 * h\/2, x + h\/2)\n pk[2] = 2 * m1 * (q0 + qk[1] * h1) + (p0 + pk[1] * h1) * x1inv; \n qk[2] = v1enuvl1 * (p0 + pk[1] * h1) - (q0 + qk[1] * h1) * x1inv - mp1;\n\n \/\/ k3 = F(Y(x) + k2 * h, x + h)\n pk[3] = 2 * m2 * (q0 + qk[2] * h) + (p0 + pk[2] * h) * x2inv; \n qk[3] = v2enuvl2 * (p0 + pk[2] * h) - (q0 + qk[2] * h) * x2inv - mp2;\n \n \/\/ Y(x + h) = Y(x) + h * (k0 + 2 * k1 + 2 * k2 + k3) \/ 6\n p2 = p0 + (pk[0] + 2 * (pk[1] + pk[2]) + pk[3]) * h \/ 6.0;\n q2 = q0 + (qk[0] + 2 * (qk[1] + qk[2]) + qk[3]) * h \/ 6.0;\n \n p2 = std::max(std::min(1e10, p2), -1e10);\n q2 = std::max(std::min(1e10, q2), -1e10);\n \n p[i + 1] = p2;\n q[i + 1] = q2;\n }\n\n int nn = 0;\n for (int i = 0; i < nr - 1; i++) if (p[i] * p[i + 1] < 0.0) nn++;\n\n for (int i = 0; i < nr; i++)\n {\n double V = ve[i] + zn_ * radial_grid_.rinv(i); \n double M = 1.0 - (V - enu0) * alpha2;\n\n \/\/ P' = 2MQ + \\frac{P}{r}\n dpdr[i] = 2 * M * q[i] + p[i] * radial_grid_.rinv(i);\n\n \/\/ Q' = (V - E + \\frac{\\ell(\\ell + 1)}{2 M r^2}) P - \\frac{Q}{r}\n dqdr[i] = (V - enu + double(l * (l + 1)) \/ (2 * M * pow(radial_grid_[i], 2))) * p[i] - \n q[i] * radial_grid_.rinv(i) - mp[i];\n }\n\n return nn;\n}\n \ndouble Radial_solver::find_enu(int n, int l, std::vector& v, double enu0)\n{\n std::vector p;\n std::vector hp;\n \n double enu = enu0;\n double de = 0.001;\n bool found = false;\n double dpdr;\n int nndp = 0;\n for (int i = 0; i < 1000; i++)\n {\n int nnd = solve_in_mt(l, enu, 0, v, p, hp, dpdr) - (n - l - 1);\n if (nnd > 0)\n {\n enu -= de;\n }\n else\n {\n enu += de;\n }\n if (i > 0)\n {\n if (nnd != nndp) \n {\n de *= 0.5;\n }\n else\n {\n de *= 1.25;\n }\n }\n nndp = nnd;\n if (fabs(de) < 1e-10)\n {\n found = true;\n break;\n }\n }\n if (!found)\n { \n error_local(__FILE__, __LINE__, \"top of the band is not found\");\n }\n double etop = enu;\n de = -0.001;\n found = false;\n double p1p = 0;\n for (int i = 0; i < 1000; i++)\n {\n solve_in_mt(l, enu, 0, v, p, hp, dpdr);\n\n if (i > 0)\n {\n if (dpdr * p1p < 0.0)\n {\n if (fabs(de) < 1e-10)\n {\n found = true;\n break;\n }\n de *= -0.5;\n }\n else\n {\n de *= 1.25;\n }\n }\n p1p = dpdr;\n enu += de;\n }\n if (!found)\n { \n error_local(__FILE__, __LINE__, \"bottom of the band is not found\");\n }\n return (enu + etop) \/ 2.0;\n}\n \nint Radial_solver::solve_in_mt(int l, double enu, int m, std::vector& v, std::vector& p, \n std::vector& hp, double& dpdr_R)\n{\n std::vector ve(radial_grid_.num_mt_points());\n for (int i = 0; i < radial_grid_.num_mt_points(); i++) ve[i] = v[i] - zn_ \/ radial_grid_[i];\n \n sirius::Spline ve_spline(radial_grid_.num_mt_points(), radial_grid_, ve);\n\n sirius::Spline mp_spline(radial_grid_.num_mt_points(), radial_grid_);\n\n std::vector q;\n std::vector dpdr;\n std::vector dqdr;\n\n int nn = 0;\n \n for (int j = 0; j <= m; j++)\n {\n if (j)\n {\n for (int i = 0; i < radial_grid_.num_mt_points(); i++) mp_spline[i] = j * p[i];\n \n mp_spline.interpolate();\n }\n \n nn = integrate(radial_grid_.num_mt_points(), l, enu, ve_spline, mp_spline, p, dpdr, q, dqdr);\n }\n\n hp.resize(radial_grid_.num_mt_points());\n double alph2 = 0.0;\n if (relativistic_) alph2 = pow((1.0 \/ speed_of_light), 2);\n for (int i = 0; i < radial_grid_.num_mt_points(); i++)\n {\n double t1 = 2.0 - v[i] * alph2;\n hp[i] = (double(l * (l + 1)) \/ t1 \/ pow(radial_grid_[i], 2.0) + v[i]) * p[i] - q[i] \/ radial_grid_[i] - dqdr[i];\n }\n dpdr_R = dpdr[radial_grid_.num_mt_points() - 1];\n return nn;\n}\n \nint Radial_solver::solve_in_mt(int l, double enu, int m, std::vector& v, std::vector& p0, \n std::vector& p1, std::vector& q0, std::vector& q1)\n{\n std::vector ve(radial_grid_.num_mt_points());\n for (int i = 0; i < radial_grid_.num_mt_points(); i++) ve[i] = v[i] - zn_ \/ radial_grid_[i];\n \n sirius::Spline ve_spline(radial_grid_.num_mt_points(), radial_grid_, ve);\n\n sirius::Spline mp_spline(radial_grid_.num_mt_points(), radial_grid_);\n\n int nn = 0;\n \n for (int j = 0; j <= m; j++)\n {\n if (j)\n {\n for (int i = 0; i < radial_grid_.num_mt_points(); i++) mp_spline[i] = j * p0[i];\n \n mp_spline.interpolate();\n }\n \n nn = integrate(radial_grid_.num_mt_points(), l, enu, ve_spline, mp_spline, p0, p1, q0, q1);\n }\n\n return nn;\n}\n\nvoid Radial_solver::bound_state(int n, int l, std::vector& v, double& enu, std::vector& p)\n{\n std::vector ve(radial_grid_.size());\n for (int i = 0; i < radial_grid_.size(); i++) ve[i] = v[i] - zn_ \/ radial_grid_[i];\n \n sirius::Spline ve_spline(radial_grid_.size(), radial_grid_, ve);\n sirius::Spline mp_spline(radial_grid_.size(), radial_grid_);\n \n std::vector q(radial_grid_.size());\n std::vector dpdr(radial_grid_.size());\n std::vector dqdr(radial_grid_.size());\n \n int s = 1;\n int sp;\n double denu = enu_tolerance_;\n\n for (int iter = 0; iter < 1000; iter++)\n {\n int nn = integrate(radial_grid_.size(), l, enu, ve_spline, mp_spline, p, dpdr, q, dqdr);\n \n sp = s;\n s = (nn > (n - l - 1)) ? -1 : 1;\n denu = s * fabs(denu);\n denu = (s != sp) ? denu * 0.5 : denu * 1.25;\n enu += denu;\n \n if (fabs(denu) < enu_tolerance_ && iter > 4) break;\n }\n \n if (fabs(denu) >= enu_tolerance_) \n {\n std::stringstream s;\n s << \"enu is not converged for n = \" << n << \" and l = \" << l; \n error_local(__FILE__, __LINE__, s);\n }\n\n \/\/ search for the turning point\n int idxtp = radial_grid_.size() - 1;\n for (int i = 0; i < radial_grid_.size(); i++)\n {\n if (v[i] > enu)\n {\n idxtp = i;\n break;\n }\n }\n\n \/\/ zero the tail of the wave-function\n double t1 = 1e100;\n for (int i = idxtp; i < radial_grid_.size(); i++)\n {\n if ((fabs(p[i]) < t1) && (p[i - 1] * p[i] > 0))\n {\n t1 = fabs(p[i]);\n }\n else\n {\n t1 = 0.0;\n p[i] = 0.0;\n }\n }\n\n std::vector rho(radial_grid_.size());\n for (int i = 0; i < radial_grid_.size(); i++) rho[i] = p[i] * p[i];\n\n double norm = sirius::Spline(radial_grid_.size(), radial_grid_, rho).integrate();\n \n for (int i = 0; i < radial_grid_.size(); i++) p[i] \/= sqrt(norm);\n\n \/\/ count number of nodes\n int nn = 0;\n for (int i = 0; i < radial_grid_.size() - 1; i++) if (p[i] * p[i + 1] < 0.0) nn++;\n\n if (nn != (n - l - 1))\n {\n std::stringstream s;\n s << \"n = \" << n << std::endl \n << \"l = \" << l << std::endl\n << \"enu = \" << enu << std::endl\n << \"wrong number of nodes : \" << nn << \" instead of \" << (n - l - 1);\n error_local(__FILE__, __LINE__, s);\n }\n}\n\n}\n\nsize->num_points name change#include \"radial_solver.h\"\n\nnamespace sirius {\n\nint Radial_solver::integrate(int nr, int l, double enu, sirius::Spline& ve, sirius::Spline& mp, \n std::vector& p, std::vector& dpdr, std::vector& q, \n std::vector& dqdr)\n{\n double alpha2 = 0.5 * pow((1 \/ speed_of_light), 2);\n if (!relativistic_) alpha2 = 0.0;\n\n double enu0 = 0.0;\n if (relativistic_) enu0 = enu;\n\n double ll2 = 0.5 * l * (l + 1);\n\n double x2 = radial_grid_[0];\n double x2inv = radial_grid_.rinv(0);\n double v2 = ve[0] + zn_ \/ x2;\n double m2 = 1 - (v2 - enu0) * alpha2;\n\n p.resize(nr);\n dpdr.resize(nr);\n q.resize(nr);\n dqdr.resize(nr);\n\n \/\/ TODO: check r->0 asymptotic\n p[0] = pow(radial_grid_[0], l + 1) * exp(zn_ * radial_grid_[0] \/ (l + 1));\n q[0] = (0.5 \/ m2) * p[0] * (l \/ radial_grid_[0] + zn_ \/ (l + 1));\n\n double p2 = p[0];\n double q2 = q[0];\n double mp2 = mp[0];\n double vl2 = ll2 \/ m2 \/ pow(x2, 2);\n\n double v2enuvl2 = (v2 - enu + vl2);\n\n double pk[4];\n double qk[4];\n \n for (int i = 0; i < nr - 1; i++)\n {\n double x0 = x2;\n x2 = radial_grid_[i + 1];\n double x0inv = x2inv;\n x2inv = radial_grid_.rinv(i + 1);\n double h = radial_grid_.dr(i);\n double h1 = h \/ 2;\n\n double x1 = x0 + h1;\n double x1inv = 1.0 \/ x1;\n double p0 = p2;\n double q0 = q2;\n double m0 = m2;\n v2 = ve[i + 1] + zn_ * x2inv;\n\n double mp0 = mp2;\n mp2 = mp[i + 1];\n double mp1 = mp(i, h1);\n double v1 = ve(i, h1) + zn_ * x1inv;\n double m1 = 1 - (v1 - enu0) * alpha2;\n m2 = 1 - (v2 - enu0) * alpha2;\n vl2 = ll2 \/ m2 \/ pow(x2, 2);\n \n double v0enuvl0 = v2enuvl2;\n v2enuvl2 = (v2 - enu + vl2);\n \n double vl1 = ll2 \/ m1 \/ pow(x1, 2);\n\n double v1enuvl1 = (v1 - enu + vl1);\n \n \/\/ k0 = F(Y(x), x)\n pk[0] = 2 * m0 * q0 + p0 * x0inv;\n qk[0] = v0enuvl0 * p0 - q0 * x0inv - mp0;\n\n \/\/ k1 = F(Y(x) + k0 * h\/2, x + h\/2)\n pk[1] = 2 * m1 * (q0 + qk[0] * h1) + (p0 + pk[0] * h1) * x1inv;\n qk[1] = v1enuvl1 * (p0 + pk[0] * h1) - (q0 + qk[0] * h1) * x1inv - mp1;\n\n \/\/ k2 = F(Y(x) + k1 * h\/2, x + h\/2)\n pk[2] = 2 * m1 * (q0 + qk[1] * h1) + (p0 + pk[1] * h1) * x1inv; \n qk[2] = v1enuvl1 * (p0 + pk[1] * h1) - (q0 + qk[1] * h1) * x1inv - mp1;\n\n \/\/ k3 = F(Y(x) + k2 * h, x + h)\n pk[3] = 2 * m2 * (q0 + qk[2] * h) + (p0 + pk[2] * h) * x2inv; \n qk[3] = v2enuvl2 * (p0 + pk[2] * h) - (q0 + qk[2] * h) * x2inv - mp2;\n \n \/\/ Y(x + h) = Y(x) + h * (k0 + 2 * k1 + 2 * k2 + k3) \/ 6\n p2 = p0 + (pk[0] + 2 * (pk[1] + pk[2]) + pk[3]) * h \/ 6.0;\n q2 = q0 + (qk[0] + 2 * (qk[1] + qk[2]) + qk[3]) * h \/ 6.0;\n \n p2 = std::max(std::min(1e10, p2), -1e10);\n q2 = std::max(std::min(1e10, q2), -1e10);\n \n p[i + 1] = p2;\n q[i + 1] = q2;\n }\n\n int nn = 0;\n for (int i = 0; i < nr - 1; i++) if (p[i] * p[i + 1] < 0.0) nn++;\n\n for (int i = 0; i < nr; i++)\n {\n double V = ve[i] + zn_ * radial_grid_.rinv(i); \n double M = 1.0 - (V - enu0) * alpha2;\n\n \/\/ P' = 2MQ + \\frac{P}{r}\n dpdr[i] = 2 * M * q[i] + p[i] * radial_grid_.rinv(i);\n\n \/\/ Q' = (V - E + \\frac{\\ell(\\ell + 1)}{2 M r^2}) P - \\frac{Q}{r}\n dqdr[i] = (V - enu + double(l * (l + 1)) \/ (2 * M * pow(radial_grid_[i], 2))) * p[i] - \n q[i] * radial_grid_.rinv(i) - mp[i];\n }\n\n return nn;\n}\n \ndouble Radial_solver::find_enu(int n, int l, std::vector& v, double enu0)\n{\n std::vector p;\n std::vector hp;\n \n double enu = enu0;\n double de = 0.001;\n bool found = false;\n double dpdr;\n int nndp = 0;\n for (int i = 0; i < 1000; i++)\n {\n int nnd = solve_in_mt(l, enu, 0, v, p, hp, dpdr) - (n - l - 1);\n if (nnd > 0)\n {\n enu -= de;\n }\n else\n {\n enu += de;\n }\n if (i > 0)\n {\n if (nnd != nndp) \n {\n de *= 0.5;\n }\n else\n {\n de *= 1.25;\n }\n }\n nndp = nnd;\n if (fabs(de) < 1e-10)\n {\n found = true;\n break;\n }\n }\n if (!found)\n { \n error_local(__FILE__, __LINE__, \"top of the band is not found\");\n }\n double etop = enu;\n de = -0.001;\n found = false;\n double p1p = 0;\n for (int i = 0; i < 1000; i++)\n {\n solve_in_mt(l, enu, 0, v, p, hp, dpdr);\n\n if (i > 0)\n {\n if (dpdr * p1p < 0.0)\n {\n if (fabs(de) < 1e-10)\n {\n found = true;\n break;\n }\n de *= -0.5;\n }\n else\n {\n de *= 1.25;\n }\n }\n p1p = dpdr;\n enu += de;\n }\n if (!found)\n { \n error_local(__FILE__, __LINE__, \"bottom of the band is not found\");\n }\n return (enu + etop) \/ 2.0;\n}\n \nint Radial_solver::solve_in_mt(int l, double enu, int m, std::vector& v, std::vector& p, \n std::vector& hp, double& dpdr_R)\n{\n std::vector ve(radial_grid_.num_mt_points());\n for (int i = 0; i < radial_grid_.num_mt_points(); i++) ve[i] = v[i] - zn_ \/ radial_grid_[i];\n \n sirius::Spline ve_spline(radial_grid_.num_mt_points(), radial_grid_, ve);\n\n sirius::Spline mp_spline(radial_grid_.num_mt_points(), radial_grid_);\n\n std::vector q;\n std::vector dpdr;\n std::vector dqdr;\n\n int nn = 0;\n \n for (int j = 0; j <= m; j++)\n {\n if (j)\n {\n for (int i = 0; i < radial_grid_.num_mt_points(); i++) mp_spline[i] = j * p[i];\n \n mp_spline.interpolate();\n }\n \n nn = integrate(radial_grid_.num_mt_points(), l, enu, ve_spline, mp_spline, p, dpdr, q, dqdr);\n }\n\n hp.resize(radial_grid_.num_mt_points());\n double alph2 = 0.0;\n if (relativistic_) alph2 = pow((1.0 \/ speed_of_light), 2);\n for (int i = 0; i < radial_grid_.num_mt_points(); i++)\n {\n double t1 = 2.0 - v[i] * alph2;\n hp[i] = (double(l * (l + 1)) \/ t1 \/ pow(radial_grid_[i], 2.0) + v[i]) * p[i] - q[i] \/ radial_grid_[i] - dqdr[i];\n }\n dpdr_R = dpdr[radial_grid_.num_mt_points() - 1];\n return nn;\n}\n \nint Radial_solver::solve_in_mt(int l, double enu, int m, std::vector& v, std::vector& p0, \n std::vector& p1, std::vector& q0, std::vector& q1)\n{\n std::vector ve(radial_grid_.num_mt_points());\n for (int i = 0; i < radial_grid_.num_mt_points(); i++) ve[i] = v[i] - zn_ \/ radial_grid_[i];\n \n sirius::Spline ve_spline(radial_grid_.num_mt_points(), radial_grid_, ve);\n\n sirius::Spline mp_spline(radial_grid_.num_mt_points(), radial_grid_);\n\n int nn = 0;\n \n for (int j = 0; j <= m; j++)\n {\n if (j)\n {\n for (int i = 0; i < radial_grid_.num_mt_points(); i++) mp_spline[i] = j * p0[i];\n \n mp_spline.interpolate();\n }\n \n nn = integrate(radial_grid_.num_mt_points(), l, enu, ve_spline, mp_spline, p0, p1, q0, q1);\n }\n\n return nn;\n}\n\nvoid Radial_solver::bound_state(int n, int l, std::vector& v, double& enu, std::vector& p)\n{\n int np = radial_grid_.num_points();\n\n std::vector ve(np);\n for (int i = 0; i < np; i++) ve[i] = v[i] - zn_ \/ radial_grid_[i];\n \n sirius::Spline ve_spline(np, radial_grid_, ve);\n sirius::Spline mp_spline(np, radial_grid_);\n \n std::vector q(np);\n std::vector dpdr(np);\n std::vector dqdr(np);\n \n int s = 1;\n int sp;\n double denu = enu_tolerance_;\n\n for (int iter = 0; iter < 1000; iter++)\n {\n int nn = integrate(np, l, enu, ve_spline, mp_spline, p, dpdr, q, dqdr);\n \n sp = s;\n s = (nn > (n - l - 1)) ? -1 : 1;\n denu = s * fabs(denu);\n denu = (s != sp) ? denu * 0.5 : denu * 1.25;\n enu += denu;\n \n if (fabs(denu) < enu_tolerance_ && iter > 4) break;\n }\n \n if (fabs(denu) >= enu_tolerance_) \n {\n std::stringstream s;\n s << \"enu is not converged for n = \" << n << \" and l = \" << l; \n error_local(__FILE__, __LINE__, s);\n }\n\n \/\/ search for the turning point\n int idxtp = np - 1;\n for (int i = 0; i < np; i++)\n {\n if (v[i] > enu)\n {\n idxtp = i;\n break;\n }\n }\n\n \/\/ zero the tail of the wave-function\n double t1 = 1e100;\n for (int i = idxtp; i < np; i++)\n {\n if ((fabs(p[i]) < t1) && (p[i - 1] * p[i] > 0))\n {\n t1 = fabs(p[i]);\n }\n else\n {\n t1 = 0.0;\n p[i] = 0.0;\n }\n }\n\n std::vector rho(np);\n for (int i = 0; i < np; i++) rho[i] = p[i] * p[i];\n\n double norm = sirius::Spline(np, radial_grid_, rho).integrate();\n \n for (int i = 0; i < np; i++) p[i] \/= sqrt(norm);\n\n \/\/ count number of nodes\n int nn = 0;\n for (int i = 0; i < np - 1; i++) if (p[i] * p[i + 1] < 0.0) nn++;\n\n if (nn != (n - l - 1))\n {\n std::stringstream s;\n s << \"n = \" << n << std::endl \n << \"l = \" << l << std::endl\n << \"enu = \" << enu << std::endl\n << \"wrong number of nodes : \" << nn << \" instead of \" << (n - l - 1);\n error_local(__FILE__, __LINE__, s);\n }\n}\n\n}\n\n<|endoftext|>"} {"text":"#include \"caixa.h\"\n\nCOORD const MAX = { 120, 60 };\/\/ ?\nBOOL OR(BOOL A, BOOL B) { return (A || B); }\nBOOL NOR(BOOL A, BOOL B) { return (!A && !B); }\/\/ return !OR(A, B); }\/\/\nBOOL AND(BOOL A, BOOL B) { return (A && B); }\nBOOL NAND(BOOL A, BOOL B) { return (!A || !B); }\/\/return !AND(A, B); };\/\/\n\n\n\/\/ Caixas\n\/\/-------\n\nCaixas &Caixas::caixa(COORD pos, short width, short height, char ch, WORD attr)\n{\n \/\/ validar a caixa\n if (NOR(pos.X < 0, pos.Y < 0) && \/\/ não tem coordenadas negativas\n NOR(pos.X > _max.X, pos.Y > _max.Y)) { \/\/ não tem coordenadas maiores que _max\n _caixas.push_back(Caixa(pos, width, height, ch, attr));\n }\n\n return *this;\n}\n\n\/\/ devolve (iterador da) caixa na posição pos (do mapa)\nvector::iterator Caixas::caixa(COORD pos)\n{\n vector::iterator it = _caixas.begin();\n for (it; it != _caixas.end(); it++) {\n if (pos.X == it->pos().X && pos.Y == it->pos().Y) {\n return it;\n }\n }\n\n return it;\n}\n\n\/\/ devolve caixas definidas numa determinada zona\nvector Caixas::caixas(COORD pos, short width, short height)\n{\n vector caixas;\n for (Caixa caixa : _caixas) {\n \/\/ coordenada da caixa\n COORD P = caixa.pos();\n \/\/ dentro da zona\n if (NOR(P.X - pos.X < 0, P.X - pos.X > width) &&\n NOR(P.Y - pos.Y < 0, P.Y - pos.Y > height)) {\n caixas.push_back(caixa);\n }\n }\n return caixas;\n}\n\n\/\/ devolve ás caixas que comtêm um determinado ponto\nvector Caixas::contem(COORD ponto)\n{\n vector caixas;\n\n for (Caixa caixa : _caixas) {\n \/\/ coordenada da caixa\n COORD P = caixa.pos();\n COORD size = caixa.size();\n\n \/\/ dentro da caixa\n if (NOR(ponto.X - P.X < 0, ponto.X - P.X > size.X) &&\n NOR(ponto.Y - P.Y < 0, ponto.Y - P.Y > size.Y)) {\n caixas.push_back(caixa);\n }\n }\n return caixas;\n}\nUpdate Caixa#include \"caixa.h\"\n\nCOORD const MAX = { 120, 60 };\/\/ ?\nBOOL OR(BOOL A, BOOL B) { return (A || B); }\nBOOL NOR(BOOL A, BOOL B) { return (!A && !B); }\/\/ return !OR(A, B); }\/\/\nBOOL AND(BOOL A, BOOL B) { return (A && B); }\nBOOL NAND(BOOL A, BOOL B) { return (!A || !B); }\/\/return !AND(A, B); };\/\/\n\n\/\/ Caixas\n\/\/-------\n\nCaixas &Caixas::caixa(COORD pos, short width, short height, char ch, WORD attr)\n{\n \/\/ validar a caixa\n if (NOR(pos.X < 0, pos.Y < 0) && \/\/ não tem coordenadas negativas\n NOR(pos.X > _max.X, pos.Y > _max.Y)) { \/\/ não tem coordenadas maiores que _max\n _caixas.push_back(Caixa(pos, width, height, ch, attr));\n }\n\n return *this;\n}\n\n\/\/ devolve (iterador da) caixa na posição pos (do mapa)\nvector::iterator Caixas::caixa(COORD pos)\n{\n vector::iterator it = _caixas.begin();\n for (it; it != _caixas.end(); it++) {\n if (pos.X == it->pos().X && pos.Y == it->pos().Y) {\n return it;\n }\n }\n\n return it;\n}\n\n\/\/ devolve caixas definidas numa determinada zona\nvector Caixas::caixas(COORD pos, short width, short height)\n{\n vector caixas;\n\n for (Caixa caixa : _caixas) {\n \/\/ cantos da caixa\n COORD P[4];\n P[0] = caixa.pos();\n P[1] = { P[0].X, P[0].Y + caixa.height() - 1 };\n P[2] = { P[0].X + caixa.width() - 1, P[0].Y };\n P[3] = { P[0].X + caixa.width() - 1, P[0].Y + caixa.height() - 1 };\n for (int i = 0; i < 4; i++) {\n \/\/ dentro da zona\n if (NOR(P[i].X - pos.X < 0, P[i].X - pos.X > width) &&\n NOR(P[i].Y - pos.Y < 0, P[i].Y - pos.Y > height)) {\n caixas.push_back(caixa);\n break;\n }\n }\n }\n\n return caixas;\n}\n\n\/\/ devolve ás caixas que comtêm um determinado ponto\nvector Caixas::contem(COORD ponto)\n{\n vector caixas;\n\n for (Caixa caixa : _caixas) {\n \/\/ coordenada da caixa\n COORD P = caixa.pos();\n COORD size = caixa.size();\n \/\/ dentro da caixa\n if (NOR(ponto.X - P.X < 0, ponto.X - P.X > size.X) &&\n NOR(ponto.Y - P.Y < 0, ponto.Y - P.Y > size.Y)) {\n caixas.push_back(caixa);\n }\n }\n\n return caixas;\n}\n<|endoftext|>"} {"text":"#include \"llvm\/ADT\/APInt.h\"\n#include \"llvm\/IR\/ConstantRange.h\"\n#include \"llvm\/IR\/IRBuilder.h\"\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IR\/NoFolder.h\"\n#include \"llvm\/IR\/Type.h\"\n#include \"llvm\/IR\/Verifier.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \n#include \n#include \n\nusing namespace llvm;\nusing namespace std;\n\nstatic LLVMContext C;\nstatic IRBuilder Builder(C);\nstatic std::unique_ptr M = llvm::make_unique(\"calc\", C);\nstatic ifstream gInFile;\nchar gCurValue = -1;\nint gArgsLen = 6;\nint gLineNo = 1;\nenum oper {ADD = 0, SUB, MUL, DIV, MOD};\nbool debug = true;\n\nValue* parseExpression();\nvoid skipSpaces();\n\nvoid usage(void) {\n printf(\"executable \\r\\n\");\n return;\n}\n\nbool openFile(int argc, char **argv) {\n if (argc < 2) {\n usage();\n return false;\n }\n gInFile.open (argv[1], ifstream::in);\n return true;\n}\n\nchar getChar() {\n return gCurValue;\n}\n\nvoid nextChar(void) {\n if (!gInFile.eof()) {\n gCurValue = gInFile.get();\n } else {\n gCurValue = EOF;\n }\n} \n\nchar getnextChar() {\n nextChar();\n return gCurValue;\n}\n\nbool accept(char c) {\n if (getChar() == c) {\n nextChar();\n return true;\n }\n return false;\n}\n\nbool check(char c) {\n if (getChar() == c) {\n return true;\n }\n return false;\n}\n\nstring getContext() {\n string context;\n getline(gInFile, context);\n return context;\n}\n\nvoid printError(int lineno) {\n printf (\"%d:Invalid statement at LineNo:%d:%d - %c%s\",\n lineno,\n gLineNo, (int)gInFile.tellg(), getChar(), getContext().c_str());\n exit(0);\n}\n\nvoid printError(int lineno, const char *c) {\n printf(\"%d:Unable to compile due to error %s at Line: %d FilePosition:%d \\r\\n\",\n lineno,\n c, gLineNo, (int)gInFile.tellg());\n printf(\"Remaining Code: %c%s\", getChar(), getContext().c_str());\n exit(0);\n}\n\nvoid parseComment() {\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n while (getnextChar() != '\\n');\n \/\/Skip \\n\n getnextChar();\n gLineNo++;\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n}\n\nValue* parseArgs() {\n char errmsg[50];\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n int i;\n \/\/Move the pointer next to a\n getnextChar();\n for (i = 0; i < gArgsLen; i++) {\n if (accept('0' + (i - 0))) { \/\/Change from int to char\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n return ConstantInt::get(Type::getInt64Ty(C), i);\n } \n }\n sprintf(errmsg, \"Invalid argument (a%c) used in the program\", \n getChar());\n printError(__LINE__, errmsg);\n return NULL;\n}\n\n\/\/Guess this should return an LLVM object\nValue* parseArithmeticOperation(char oper) {\n Value* result = NULL;\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n\n switch (oper) {\n case '+':\n result = Builder.CreateAdd(parseExpression(), \n\t\t\t\t\t\t \t\t\t\t\t\t\t\t parseExpression(), \"addtmp\");\n case '-':\n result = Builder.CreateSub(parseExpression(), \n\t\t\t\t\t\t \t\t\t\t\t\t\t\t parseExpression(), \"subtmp\");\n case '*':\n result = Builder.CreateMul(parseExpression(), \n\t\t\t\t\t\t \t\t\t\t\t\t\t\t parseExpression(), \"multmp\");\n case '\/':\n result = Builder.CreateSDiv(parseExpression(), \n\t\t\t\t\t\t \t\t\t\t\t\t\t parseExpression(), \"divtmp\");\n case '%':\n result = Builder.CreateSRem(parseExpression(), \n\t\t\t\t\t \t\t\t\t\t\t\t\t \t parseExpression(), \"modtmp\");\n default:\n printError(__LINE__, \"Fatal error in compiler. Cannot reach here\");\n }\n\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n return result;\n}\n\nValue* parseNumber() {\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n\n int num = 0, count = 0;\n bool isNegative = false;\n char ch = getChar();\n\n if (ch == '-') {\n isNegative = true;\n ch = getnextChar();\n }\n while ((ch >= '0') && (ch <= '9')) {\n num = (num * 10 * count++) + (0 + (ch - '0'));\n ch = getnextChar();\n }\n if (isNegative) {\n num = num * (-1);\n }\n\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n return ConstantInt::get(C, APInt(64, num));\n}\n\nValue* parseRelationalOperation() {\n Value* result = NULL;\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n\n if (accept('>')) {\n if (accept('=')) {\n \/\/This is greater than equals \n result = Builder.CreateICmpSGE(parseExpression(),\n parseExpression(), \"gethan\");\n } else {\n \/\/This is greater than\n result = Builder.CreateICmpSGT(parseExpression(),\n parseExpression(), \"gthan\");\n }\n } else if (accept('<')) {\n if (accept('=')) {\n \/\/This is less than equals \n result = Builder.CreateICmpSLE(parseExpression(),\n parseExpression(), \"lethan\");\n } else {\n \/\/This is less than\n result = Builder.CreateICmpSLT(parseExpression(),\n parseExpression(), \"lthan\");\n }\n } else if (accept('!') && accept('=')) {\n \/\/This is not equal to\n result = Builder.CreateICmpNE(parseExpression(),\n parseExpression(), \"ne\");\n } else if (accept('=') && accept('=')) {\n \/\/This is double equals \n result = Builder.CreateICmpEQ(parseExpression(),\n parseExpression(), \"eq\");\n } else {\n printError(__LINE__, \"Invalid Relational Operator used\");\n }\n\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n return result;\n}\n\nValue* parseBoolExpression() {\n Value* result = NULL;\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n\n skipSpaces();\n\n char ch = getChar();\n\n if (accept('t') && accept('r') && accept('u') && accept('e')) {\n \/\/Its a true condition\n result = ConstantInt::get(C, APInt(64, 1));\n } else if (accept('f') && accept('a') && accept('l') \n && accept('s') && accept('e')) {\n \/\/Its a false condition\n result = ConstantInt::get(C, APInt(64, 0));\n } else if ((ch == '>') || (ch == '<') || (ch == '=') || \n (ch == '!')) {\n result = parseRelationalOperation(); \n } else if (ch == ('(')) {\n getnextChar();\n result = parseBoolExpression();\n if (accept(')') == false) {\n printError(__LINE__, \"Missing ) Paranthesis in boolean exp\");\n }\n } else {\n printError(__LINE__, \"Boolean expression Missing\");\n }\n\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n return result;\n}\n\nValue* parseIf() {\n Value *result = NULL;\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n\n if (accept('i') && accept('f')) {\n result = Builder.CreateSelect(parseBoolExpression(),\n parseExpression(),\n parseExpression());\n } else {\n printError(__LINE__);\n }\n\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n return result;\n}\n\nvoid skipSpaces() {\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n\n while (getChar() != EOF) {\n if (accept(' ')) {\n continue;\n } else if (accept('\\n')) {\n gLineNo++;\n continue;\n }\n break;\n }\n\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n}\n\nValue* parseExpression() {\n char errmsg[75];\n Value *result;\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n\n skipSpaces();\n\n char ch = getChar();\n\n do{\n if (ch == '#') {\n parseComment();\n } else if (ch == 'a') {\n result = parseArgs();\n break;\n } else if (ch == '\\n') {\n \/\/Increment the line number, so that we can give a \n \/\/meaningful error message\n gLineNo++;\n } else if (ch == ' ') {\n \/\/Ignore White space\n } else if ((ch == '+') || (ch == '-') || (ch == '*') || \n (ch == '\/') || (ch == '%')) {\n getnextChar();\n result = parseArithmeticOperation(ch); \n break;\n } else if (ch == '-') {\n result = parseNumber();\n break;\n } else if ((ch >= '0') && (ch <= '9')) {\n result = parseNumber();\n break;\n } else if (ch == '(') {\n getnextChar();\n result = parseExpression();\n if (accept(')') == false) {\n printError(__LINE__, \"Missing Matching paranthesis\");\n }\n break;\n } else if (ch == 'i') {\n result = parseIf();\n break;\n } else if (ch == ')') {\n getnextChar();\n break;\n } else {\n printError(__LINE__);\n }\n ch = getChar();\n }while (ch != EOF);\n\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n return result;\n}\n\nValue* parser() {\n Value *result = NULL;\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n char ch = getnextChar();\n while(ch != EOF) {\n if (ch == '#') {\n parseComment();\n } else {\n result = parseExpression();\n skipSpaces();\n if (getChar() == EOF) {\n break;\n } else {\n printError(__LINE__);\n }\n }\n ch = getChar();\n }\n printf(\"Parsed successfully\\r\\n\");\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n return result;\n}\n\nstatic int compile() {\n M->setTargetTriple(llvm::sys::getProcessTriple());\n std::vector SixInts(6, Type::getInt64Ty(C));\n FunctionType *FT = FunctionType::get(Type::getInt64Ty(C), SixInts, false);\n Function *F = Function::Create(FT, Function::ExternalLinkage, \"f\", &*M);\n BasicBlock *BB = BasicBlock::Create(C, \"entry\", F);\n Builder.SetInsertPoint(BB);\n\n \/\/ TODO: parse the source program\n \/\/ TODO: generate correct LLVM instead of just an empty function\n\n Value *RetVal = ConstantInt::get(C, APInt(64, 0));\n Builder.CreateRet(RetVal);\n assert(!verifyModule(*M, &outs()));\n M->dump();\n return 0;\n}\n\nint main(int argc, char **argv) { \n if (openFile(argc, argv) == true) {\n parser();\n \/\/return compile(); \n } \n return -1;\n}\nAdding the parsing code#include \"llvm\/ADT\/APInt.h\"\n#include \"llvm\/IR\/ConstantRange.h\"\n#include \"llvm\/IR\/IRBuilder.h\"\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IR\/NoFolder.h\"\n#include \"llvm\/IR\/Type.h\"\n#include \"llvm\/IR\/Verifier.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \n#include \n#include \n\nusing namespace llvm;\nusing namespace std;\n\nstatic LLVMContext C;\nstatic IRBuilder Builder(C);\nstatic std::unique_ptr M = llvm::make_unique(\"calc\", C);\nstatic ifstream gInFile;\nchar gCurValue = -1;\nint gArgsLen = 6;\nint gLineNo = 1;\nenum oper {ADD = 0, SUB, MUL, DIV, MOD};\nbool debug = true;\n\nValue* parseExpression();\nvoid skipSpaces();\n\nvoid usage(void) {\n printf(\"executable \\r\\n\");\n return;\n}\n\nbool openFile(int argc, char **argv) {\n if (argc < 2) {\n usage();\n return false;\n }\n gInFile.open (argv[1], ifstream::in);\n return true;\n}\n\nchar getChar() {\n return gCurValue;\n}\n\nvoid nextChar(void) {\n if (!gInFile.eof()) {\n gCurValue = gInFile.get();\n } else {\n gCurValue = EOF;\n }\n} \n\nchar getnextChar() {\n nextChar();\n return gCurValue;\n}\n\nbool accept(char c) {\n if (getChar() == c) {\n nextChar();\n return true;\n }\n return false;\n}\n\nbool check(char c) {\n if (getChar() == c) {\n return true;\n }\n return false;\n}\n\nstring getContext() {\n string context;\n getline(gInFile, context);\n return context;\n}\n\nvoid printError(int lineno) {\n printf (\"%d:Invalid statement at LineNo:%d:%d - %c%s\",\n lineno,\n gLineNo, (int)gInFile.tellg(), getChar(), getContext().c_str());\n exit(0);\n}\n\nvoid printError(int lineno, const char *c) {\n printf(\"%d:Unable to compile due to error %s at Line: %d FilePosition:%d \\r\\n\",\n lineno,\n c, gLineNo, (int)gInFile.tellg());\n printf(\"Remaining Code: %c%s\", getChar(), getContext().c_str());\n exit(0);\n}\n\nvoid parseComment() {\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n while (getnextChar() != '\\n');\n \/\/Skip \\n\n getnextChar();\n gLineNo++;\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n}\n\nValue* parseArgs() {\n char errmsg[50];\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n int i;\n \/\/Move the pointer next to a\n getnextChar();\n for (i = 0; i < gArgsLen; i++) {\n if (accept('0' + (i - 0))) { \/\/Change from int to char\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n return ConstantInt::get(Type::getInt64Ty(C), i);\n } \n }\n sprintf(errmsg, \"Invalid argument (a%c) used in the program\", \n getChar());\n printError(__LINE__, errmsg);\n return NULL;\n}\n\n\/\/Guess this should return an LLVM object\nValue* parseArithmeticOperation(char oper) {\n Value* result = NULL;\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n\n switch (oper) {\n case '+':\n result = Builder.CreateAdd(parseExpression(), \n\t\t\t\t\t\t \t\t\t\t\t\t\t\t parseExpression(), \"addtmp\");\n case '-':\n result = Builder.CreateSub(parseExpression(), \n\t\t\t\t\t\t \t\t\t\t\t\t\t\t parseExpression(), \"subtmp\");\n case '*':\n result = Builder.CreateMul(parseExpression(), \n\t\t\t\t\t\t \t\t\t\t\t\t\t\t parseExpression(), \"multmp\");\n case '\/':\n result = Builder.CreateSDiv(parseExpression(), \n\t\t\t\t\t\t \t\t\t\t\t\t\t parseExpression(), \"divtmp\");\n case '%':\n result = Builder.CreateSRem(parseExpression(), \n\t\t\t\t\t \t\t\t\t\t\t\t\t \t parseExpression(), \"modtmp\");\n default:\n printError(__LINE__, \"Fatal error in compiler. Cannot reach here\");\n }\n\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n return result;\n}\n\nValue* parseNumber() {\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n\n int num = 0, count = 0;\n bool isNegative = false;\n char ch = getChar();\n\n if (ch == '-') {\n isNegative = true;\n ch = getnextChar();\n }\n while ((ch >= '0') && (ch <= '9')) {\n num = (num * 10 * count++) + (0 + (ch - '0'));\n ch = getnextChar();\n }\n if (isNegative) {\n num = num * (-1);\n }\n\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n return ConstantInt::get(C, APInt(64, num));\n}\n\nValue* parseRelationalOperation() {\n Value* result = NULL;\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n\n if (accept('>')) {\n if (accept('=')) {\n \/\/This is greater than equals \n result = Builder.CreateICmpSGE(parseExpression(),\n parseExpression(), \"gethan\");\n } else {\n \/\/This is greater than\n result = Builder.CreateICmpSGT(parseExpression(),\n parseExpression(), \"gthan\");\n }\n } else if (accept('<')) {\n if (accept('=')) {\n \/\/This is less than equals \n result = Builder.CreateICmpSLE(parseExpression(),\n parseExpression(), \"lethan\");\n } else {\n \/\/This is less than\n result = Builder.CreateICmpSLT(parseExpression(),\n parseExpression(), \"lthan\");\n }\n } else if (accept('!') && accept('=')) {\n \/\/This is not equal to\n result = Builder.CreateICmpNE(parseExpression(),\n parseExpression(), \"ne\");\n } else if (accept('=') && accept('=')) {\n \/\/This is double equals \n result = Builder.CreateICmpEQ(parseExpression(),\n parseExpression(), \"eq\");\n } else {\n printError(__LINE__, \"Invalid Relational Operator used\");\n }\n\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n return result;\n}\n\nValue* parseBoolExpression() {\n Value* result = NULL;\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n\n skipSpaces();\n\n char ch = getChar();\n\n if (accept('t') && accept('r') && accept('u') && accept('e')) {\n \/\/Its a true condition\n result = ConstantInt::get(C, APInt(64, 1));\n } else if (accept('f') && accept('a') && accept('l') \n && accept('s') && accept('e')) {\n \/\/Its a false condition\n result = ConstantInt::get(C, APInt(64, 0));\n } else if ((ch == '>') || (ch == '<') || (ch == '=') || \n (ch == '!')) {\n result = parseRelationalOperation(); \n } else if (ch == ('(')) {\n getnextChar();\n result = parseBoolExpression();\n if (accept(')') == false) {\n printError(__LINE__, \"Missing ) Paranthesis in boolean exp\");\n }\n } else {\n printError(__LINE__, \"Boolean expression Missing\");\n }\n\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n return result;\n}\n\nValue* parseIf() {\n Value *result = NULL;\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n\n if (accept('i') && accept('f')) {\n result = Builder.CreateSelect(parseBoolExpression(),\n parseExpression(),\n parseExpression());\n } else {\n printError(__LINE__);\n }\n\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n return result;\n}\n\nvoid skipSpaces() {\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n\n while (getChar() != EOF) {\n if (accept(' ')) {\n continue;\n } else if (accept('\\n')) {\n gLineNo++;\n continue;\n }\n break;\n }\n\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n}\n\nValue* parseExpression() {\n char errmsg[75];\n Value *result;\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n\n skipSpaces();\n\n char ch = getChar();\n\n do{\n if (ch == '#') {\n parseComment();\n } else if (ch == 'a') {\n result = parseArgs();\n break;\n } else if (ch == '\\n') {\n \/\/Increment the line number, so that we can give a \n \/\/meaningful error message\n gLineNo++;\n } else if (ch == ' ') {\n \/\/Ignore White space\n } else if ((ch == '+') || (ch == '-') || (ch == '*') || \n (ch == '\/') || (ch == '%')) {\n getnextChar();\n result = parseArithmeticOperation(ch); \n break;\n } else if (ch == '-') {\n result = parseNumber();\n break;\n } else if ((ch >= '0') && (ch <= '9')) {\n result = parseNumber();\n break;\n } else if (ch == '(') {\n getnextChar();\n result = parseExpression();\n if (accept(')') == false) {\n printError(__LINE__, \"Missing Matching paranthesis\");\n }\n break;\n } else if (ch == 'i') {\n result = parseIf();\n break;\n } else if (ch == ')') {\n getnextChar();\n break;\n } else {\n printError(__LINE__);\n }\n ch = getChar();\n }while (ch != EOF);\n\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n return result;\n}\n\nValue* parser() {\n Value *result = NULL;\n if (debug) {\n printf(\"Enter %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n char ch = getnextChar();\n while(ch != EOF) {\n if (ch == '#') {\n parseComment();\n } else {\n result = parseExpression();\n skipSpaces();\n if (getChar() == EOF) {\n break;\n } else {\n printError(__LINE__);\n }\n }\n ch = getChar();\n }\n printf(\"Parsed successfully\\r\\n\");\n if (debug) {\n printf(\"Exit %s\\r\\n\", __PRETTY_FUNCTION__);\n }\n return result;\n}\n\nstatic int compile() {\n M->setTargetTriple(llvm::sys::getProcessTriple());\n std::vector SixInts(6, Type::getInt64Ty(C));\n FunctionType *FT = FunctionType::get(Type::getInt64Ty(C), SixInts, false);\n Function *F = Function::Create(FT, Function::ExternalLinkage, \"f\", &*M);\n BasicBlock *BB = BasicBlock::Create(C, \"entry\", F);\n Builder.SetInsertPoint(BB);\n\n \/\/ TODO: parse the source program\n \/\/ TODO: generate correct LLVM instead of just an empty function\n Value *RetVal = parser();\n\n \/\/Value *RetVal = ConstantInt::get(C, APInt(64, 0));\n Builder.CreateRet(RetVal);\n assert(!verifyModule(*M, &outs()));\n M->dump();\n return 0;\n}\n\nint main(int argc, char **argv) { \n if (openFile(argc, argv) == true) {\n return compile(); \n } \n return -1;\n}\n<|endoftext|>"} {"text":"logger = $logger;\n $this->repo = new Repository($this->logger);\n }\n\n public function readCommandLineArguments(array $argv, int $argc) {\n for ($i = 1; $i < $argc; $i++) {\n $a = $argv[$i];\n\n if ($a == '--local-only') {\n $this->debugLocalOnly = true;\n continue;\n }\n if ($a == '--fake-data') {\n $this->debugFakeData = true;\n continue;\n }\n if ($a == '--debug') {\n $this->logger->setHandlers(array(new \\Monolog\\Handler\\StreamHandler('php:\/\/stderr', \\Monolog\\Logger::DEBUG)));\n continue;\n }\n\n echo \"Invalid argument: {$a}\", PHP_EOL;\n exit(1);\n }\n }\n\n public static function main(array $argv, int $argc) {\n $listURL = '\/list.php?op=bypage&page=';\n\n $l = new \\Monolog\\Logger('census');\n $l->pushHandler(new \\Monolog\\Handler\\StreamHandler('php:\/\/stderr', \\Monolog\\Logger::WARNING));\n\n $c = new Census($l);\n $c->readCommandLineArguments($argv, $argc);\n\n $statsMap = Map {};\n\n if ($c->debugFakeData) {\n $sites = Vector {};\n\n $stats = new Stats();\n $stats->count = 103;\n $stats->dau = 12;\n $stats->mau = 23;\n $statsMap['site3'] = $stats;\n\n $stats = new Stats();\n $stats->count = 123;\n $stats->dau = 3;\n $stats->mau = 13;\n $statsMap['twx.rpglink.in'] = $stats;\n\n $stats = new Stats();\n $stats->count = 400;\n $stats->dau = 126;\n $stats->mau = 316;\n $statsMap['www.lotgd.net'] = $stats;\n\n $stats = new Stats();\n $stats->count = 594;\n $stats->dau = 33;\n $stats->mau = 135;\n $statsMap['www.dragonsofmyth.com'] = $stats;\n\n $stats = new Stats();\n $stats->count = 270;\n $stats->dau = 8;\n $stats->mau = 25;\n $statsMap['stormvalley.rpglink.in'] = $stats;\n\n $stats = new Stats();\n $stats->count = 29;\n $stats->dau = 1;\n $stats->mau = 10;\n $statsMap['dragonprimelogd.net'] = $stats;\n\n $stats = new Stats();\n $stats->count = 586;\n $stats->dau = 80;\n $stats->mau = 274;\n $statsMap['forbiddenrealm.rpglink.in'] = $stats;\n\n $stats = new Stats();\n $stats->count = 94;\n $stats->dau = 6;\n $stats->mau = 36;\n $statsMap['enchantedland.rpglink.in'] = $stats;\n\n $stats = new Stats();\n $stats->count = 7;\n $stats->dau = 0;\n $stats->mau = 0;\n $statsMap['twx.rpglink.in'] = $stats;\n\n $stats = new Stats();\n $stats->count = 30;\n $stats->dau = 3;\n $stats->mau = 7;\n $statsMap['ess.rpglink.in'] = $stats;\n\n $stats = new Stats();\n $stats->count = 395;\n $stats->dau = 66;\n $stats->mau = 214;\n $statsMap['lotgd4adults2.com'] = $stats;\n\n $stats = new Stats();\n $stats->count = 43;\n $stats->dau = 19;\n $stats->mau = 43;\n $statsMap['deathstar.rpglink.in'] = $stats;\n\n $stats = new Stats();\n $stats->count = 20;\n $stats->dau = 0;\n $stats->mau = 6;\n $statsMap['golden-empire.com'] = $stats;\n\n $stats = new Stats();\n $stats->count = 632;\n $stats->dau = 191;\n $stats->mau = 444;\n $statsMap['the-complex.net'] = $stats;\n\n $stats = new Stats();\n $stats->count = 54;\n $stats->dau = 12;\n $stats->mau = 38;\n $statsMap['tynastera2.com'] = $stats;\n\n $stats = new Stats();\n $stats->count = 1494;\n $stats->dau = 308;\n $stats->mau = 705;\n $statsMap['www.lotgd.de'] = $stats;\n } else {\n $sites = $c->repo->getSites();\n\n foreach ($sites as $site) {\n $stats = new Stats();\n\n $i = 1;\n while ($contents = file_get_contents($u = 'http:\/\/' . $site . $listURL . $i)) {\n if ($i > 100) {\n $c->logger->addError(\" too many pages\");\n break;\n }\n\n $c->logger->addDebug(\"Fetching {$u}\");\n $wp = new WarriorsPage($c->logger, $u, $contents);\n\n if ($wp->stats != null) {\n $stats->add($wp->stats);\n }\n if ($wp->state == WarriorsPageState::End || $wp->state == WarriorsPageState::Error) {\n break;\n }\n\n $i++;\n }\n\n $statsMap[$site] = $stats;\n }\n }\n\n $c->logger->addDebug('Sites data:');\n $c->logger->addDebug(var_export($statsMap, true));\n\n $c->updateReadme($statsMap);\n\n $c->updateCSV('data\/total.csv', $statsMap->map(function (Stats $s) : int {\n return $s->count;\n }));\n\n $c->updateCSV('data\/mau.csv', $statsMap->map(function (Stats $s) : int {\n return $s->mau;\n }));\n\n $c->updateCSV('data\/dau.csv', $statsMap->map(function (Stats $s) : int {\n return $s->dau;\n }));\n }\n\n private function updateCSV(string $file, Map $map) {\n $localFilePath = __DIR__ . '\/..\/..\/' . $file;\n if ($this->debugLocalOnly) {\n $contents = file_get_contents($localFilePath);\n } else {\n $contents = $this->repo->getFile($file);\n }\n\n if ($contents === null) {\n $this->logger->addError(\"Couldn't get {$file} from the repo.\");\n return;\n }\n\n $csv = new CSV($this->logger, $file, $contents);\n $csv->appendToRows($map);\n $result = $csv->contents();\n\n $this->logger->addDebug(\"Writing {$file}:\");\n $this->logger->addDebug($result);\n if ($this->debugLocalOnly) {\n file_put_contents($localFilePath, $result);\n } else {\n $this->repo->updateFile($file, $contents, 'The latest data.');\n }\n }\n\n private function updateReadme(Map $statsMap) {\n $localTemplateFilePath = __DIR__ . '\/..\/..\/templates\/README.md';\n $localReadmeFilePath = __DIR__ . '\/..\/..\/README.md';\n\n \/\/ Sort the map by total user count.\n $statsArray = $statsMap->toArray();\n uasort($statsArray, 'Stats::compare');\n\n if ($this->debugLocalOnly) {\n $readme = file_get_contents($localTemplateFilePath);\n } else {\n $readme = $this->repo->getFile('templates\/README.md');\n }\n\n $readme .= \"Site | Total | MAU | DAU\\n\";\n $readme .= \"--- | ---:| ---:| ---:\\n\";\n\n foreach ($statsArray as $s => $stats) {\n $count = $stats->count;\n $mau = $stats->mau;\n $dau = $stats->dau;\n $readme .= \"[$s](http:\/\/{$s})|{$count}|{$mau}|{$dau}\\n\";\n }\n\n $readme .= \"\\nAs of \" . date(\"F j, Y\") . \".\\n\";\n\n \/\/ Write the README.md with the latest data.\n $this->logger->addDebug(\"Writing README.md:\");\n $this->logger->addDebug($readme);\n if ($this->debugLocalOnly) {\n file_put_contents($localReadmeFilePath, $readme);\n } else {\n $this->repo->updateFile('README.md', $readme, 'The latest data.');\n }\n }\n}\nFixing dumb bug in CSV committing code, lolzlogger = $logger;\n $this->repo = new Repository($this->logger);\n }\n\n public function readCommandLineArguments(array $argv, int $argc) {\n for ($i = 1; $i < $argc; $i++) {\n $a = $argv[$i];\n\n if ($a == '--local-only') {\n $this->debugLocalOnly = true;\n continue;\n }\n if ($a == '--fake-data') {\n $this->debugFakeData = true;\n continue;\n }\n if ($a == '--debug') {\n $this->logger->setHandlers(array(new \\Monolog\\Handler\\StreamHandler('php:\/\/stderr', \\Monolog\\Logger::DEBUG)));\n continue;\n }\n\n echo \"Invalid argument: {$a}\", PHP_EOL;\n exit(1);\n }\n }\n\n public static function main(array $argv, int $argc) {\n $listURL = '\/list.php?op=bypage&page=';\n\n $l = new \\Monolog\\Logger('census');\n $l->pushHandler(new \\Monolog\\Handler\\StreamHandler('php:\/\/stderr', \\Monolog\\Logger::WARNING));\n\n $c = new Census($l);\n $c->readCommandLineArguments($argv, $argc);\n\n $statsMap = Map {};\n\n if ($c->debugFakeData) {\n $sites = Vector {};\n\n $stats = new Stats();\n $stats->count = 103;\n $stats->dau = 12;\n $stats->mau = 23;\n $statsMap['site3'] = $stats;\n\n $stats = new Stats();\n $stats->count = 123;\n $stats->dau = 3;\n $stats->mau = 13;\n $statsMap['twx.rpglink.in'] = $stats;\n\n $stats = new Stats();\n $stats->count = 400;\n $stats->dau = 126;\n $stats->mau = 316;\n $statsMap['www.lotgd.net'] = $stats;\n\n $stats = new Stats();\n $stats->count = 594;\n $stats->dau = 33;\n $stats->mau = 135;\n $statsMap['www.dragonsofmyth.com'] = $stats;\n\n $stats = new Stats();\n $stats->count = 270;\n $stats->dau = 8;\n $stats->mau = 25;\n $statsMap['stormvalley.rpglink.in'] = $stats;\n\n $stats = new Stats();\n $stats->count = 29;\n $stats->dau = 1;\n $stats->mau = 10;\n $statsMap['dragonprimelogd.net'] = $stats;\n\n $stats = new Stats();\n $stats->count = 586;\n $stats->dau = 80;\n $stats->mau = 274;\n $statsMap['forbiddenrealm.rpglink.in'] = $stats;\n\n $stats = new Stats();\n $stats->count = 94;\n $stats->dau = 6;\n $stats->mau = 36;\n $statsMap['enchantedland.rpglink.in'] = $stats;\n\n $stats = new Stats();\n $stats->count = 7;\n $stats->dau = 0;\n $stats->mau = 0;\n $statsMap['twx.rpglink.in'] = $stats;\n\n $stats = new Stats();\n $stats->count = 30;\n $stats->dau = 3;\n $stats->mau = 7;\n $statsMap['ess.rpglink.in'] = $stats;\n\n $stats = new Stats();\n $stats->count = 395;\n $stats->dau = 66;\n $stats->mau = 214;\n $statsMap['lotgd4adults2.com'] = $stats;\n\n $stats = new Stats();\n $stats->count = 43;\n $stats->dau = 19;\n $stats->mau = 43;\n $statsMap['deathstar.rpglink.in'] = $stats;\n\n $stats = new Stats();\n $stats->count = 20;\n $stats->dau = 0;\n $stats->mau = 6;\n $statsMap['golden-empire.com'] = $stats;\n\n $stats = new Stats();\n $stats->count = 632;\n $stats->dau = 191;\n $stats->mau = 444;\n $statsMap['the-complex.net'] = $stats;\n\n $stats = new Stats();\n $stats->count = 54;\n $stats->dau = 12;\n $stats->mau = 38;\n $statsMap['tynastera2.com'] = $stats;\n\n $stats = new Stats();\n $stats->count = 1494;\n $stats->dau = 308;\n $stats->mau = 705;\n $statsMap['www.lotgd.de'] = $stats;\n } else {\n $sites = $c->repo->getSites();\n\n foreach ($sites as $site) {\n $stats = new Stats();\n\n $i = 1;\n while ($contents = file_get_contents($u = 'http:\/\/' . $site . $listURL . $i)) {\n if ($i > 100) {\n $c->logger->addError(\" too many pages\");\n break;\n }\n\n $c->logger->addDebug(\"Fetching {$u}\");\n $wp = new WarriorsPage($c->logger, $u, $contents);\n\n if ($wp->stats != null) {\n $stats->add($wp->stats);\n }\n if ($wp->state == WarriorsPageState::End || $wp->state == WarriorsPageState::Error) {\n break;\n }\n\n $i++;\n }\n\n $statsMap[$site] = $stats;\n }\n }\n\n $c->logger->addDebug('Sites data:');\n $c->logger->addDebug(var_export($statsMap, true));\n\n $c->updateReadme($statsMap);\n\n $c->updateCSV('data\/total.csv', $statsMap->map(function (Stats $s) : int {\n return $s->count;\n }));\n\n $c->updateCSV('data\/mau.csv', $statsMap->map(function (Stats $s) : int {\n return $s->mau;\n }));\n\n $c->updateCSV('data\/dau.csv', $statsMap->map(function (Stats $s) : int {\n return $s->dau;\n }));\n }\n\n private function updateCSV(string $file, Map $map) {\n $localFilePath = __DIR__ . '\/..\/..\/' . $file;\n if ($this->debugLocalOnly) {\n $contents = file_get_contents($localFilePath);\n } else {\n $contents = $this->repo->getFile($file);\n }\n\n if ($contents === null) {\n $this->logger->addError(\"Couldn't get {$file} from the repo.\");\n return;\n }\n\n $csv = new CSV($this->logger, $file, $contents);\n $csv->appendToRows($map);\n $result = $csv->contents();\n\n $this->logger->addDebug(\"Writing {$file}:\");\n $this->logger->addDebug($result);\n if ($this->debugLocalOnly) {\n file_put_contents($localFilePath, $result);\n } else {\n $this->repo->updateFile($file, $result, 'The latest data.');\n }\n }\n\n private function updateReadme(Map $statsMap) {\n $localTemplateFilePath = __DIR__ . '\/..\/..\/templates\/README.md';\n $localReadmeFilePath = __DIR__ . '\/..\/..\/README.md';\n\n \/\/ Sort the map by total user count.\n $statsArray = $statsMap->toArray();\n uasort($statsArray, 'Stats::compare');\n\n if ($this->debugLocalOnly) {\n $readme = file_get_contents($localTemplateFilePath);\n } else {\n $readme = $this->repo->getFile('templates\/README.md');\n }\n\n $readme .= \"Site | Total | MAU | DAU\\n\";\n $readme .= \"--- | ---:| ---:| ---:\\n\";\n\n foreach ($statsArray as $s => $stats) {\n $count = $stats->count;\n $mau = $stats->mau;\n $dau = $stats->dau;\n $readme .= \"[$s](http:\/\/{$s})|{$count}|{$mau}|{$dau}\\n\";\n }\n\n $readme .= \"\\nAs of \" . date(\"F j, Y\") . \".\\n\";\n\n \/\/ Write the README.md with the latest data.\n $this->logger->addDebug(\"Writing README.md:\");\n $this->logger->addDebug($readme);\n if ($this->debugLocalOnly) {\n file_put_contents($localReadmeFilePath, $readme);\n } else {\n $this->repo->updateFile('README.md', $readme, 'The latest data.');\n }\n }\n}\n<|endoftext|>"} {"text":"\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ version: $Id$\n\/\/ author: Vassil Vassilev \n\/\/------------------------------------------------------------------------------\n\n#include \"cling\/Interpreter\/InterpreterCallbacks.h\"\n\n#include \"cling\/Interpreter\/Interpreter.h\"\n\n#include \"clang\/Frontend\/CompilerInstance.h\"\n#include \"clang\/Sema\/Sema.h\"\n#include \"clang\/Serialization\/ASTReader.h\"\n#include \"clang\/Serialization\/ASTDeserializationListener.h\"\n\n\nusing namespace clang;\n\nnamespace cling {\n\n \/\/\/\\brief Translates 'interesting' for the interpreter \n \/\/\/ ASTDeserializationListener events into interpreter callback.\n \/\/\/\n class InterpreterDeserializationListener : public ASTDeserializationListener {\n private:\n cling::InterpreterCallbacks* m_Callbacks;\n public:\n InterpreterDeserializationListener(InterpreterCallbacks* C)\n : m_Callbacks(C) {}\n\n virtual void DeclRead(serialization::DeclID, const Decl *D) {\n if (m_Callbacks)\n m_Callbacks->DeclDeserialized(D);\n }\n virtual void TypeRead(serialization::TypeIdx, QualType T) {\n if (m_Callbacks)\n m_Callbacks->TypeDeserialized(T.getTypePtr());\n }\n };\n\n \/\/\/\\brief Translates 'interesting' for the interpreter ExternalSemaSource \n \/\/\/ events into interpreter callbacks.\n \/\/\/\n class InterpreterExternalSemaSource : public clang::ExternalSemaSource {\n protected:\n \/\/\/\\brief The interpreter callback which are subscribed for the events.\n \/\/\/\n \/\/\/ Usually the callbacks is the owner of the class and the interpreter owns\n \/\/\/ the callbacks so they can't be out of sync. Eg we notifying the wrong\n \/\/\/ callback class.\n \/\/\/\n InterpreterCallbacks* m_Callbacks; \/\/ we don't own it.\n\n public:\n InterpreterExternalSemaSource(InterpreterCallbacks* C) : m_Callbacks(C){}\n\n ~InterpreterExternalSemaSource() {}\n\n InterpreterCallbacks* getCallbacks() const { return m_Callbacks; }\n\n \/\/\/ \\brief Provides last resort lookup for failed unqualified lookups.\n \/\/\/\n \/\/\/ This gets translated into InterpreterCallback's call.\n \/\/\/\n \/\/\/\\param[out] R The recovered symbol.\n \/\/\/\\param[in] S The scope in which the lookup failed.\n \/\/\/\n \/\/\/\\returns true if a suitable declaration is found.\n \/\/\/\n virtual bool LookupUnqualified(clang::LookupResult& R, clang::Scope* S) {\n if (m_Callbacks)\n return m_Callbacks->LookupObject(R, S);\n \n return false;\n }\n\n virtual bool FindExternalVisibleDeclsByName(const clang::DeclContext* DC,\n clang::DeclarationName Name) {\n if (m_Callbacks)\n return m_Callbacks->LookupObject(DC, Name);\n\n return false;\n }\n\n void UpdateWithNewDeclsFwd(const DeclContext *DC, DeclarationName Name, \n llvm::ArrayRef Decls) {\n SetExternalVisibleDeclsForName(DC, Name, Decls);\n }\n };\n\n\n InterpreterCallbacks::InterpreterCallbacks(Interpreter* interp,\n InterpreterExternalSemaSource* IESS,\n InterpreterDeserializationListener* IDL)\n : m_Interpreter(interp), m_ExternalSemaSource(IESS), m_IsRuntime(false),\n m_DeserializationListener(IDL) {\n if (IESS)\n m_Interpreter->getSema().addExternalSource(m_ExternalSemaSource.get());\n ASTReader* Reader = m_Interpreter->getCI()->getModuleManager();\n if (IDL && Reader)\n Reader->setDeserializationListener(IDL);\n }\n\n InterpreterCallbacks::InterpreterCallbacks(Interpreter* interp,\n bool enableExternalSemaSourceCallbacks\/* = false*\/,\n bool enableDeserializationListenerCallbacks\/* = false*\/)\n : m_Interpreter(interp), m_IsRuntime(false) {\n \n if (enableExternalSemaSourceCallbacks) {\n m_ExternalSemaSource.reset(new InterpreterExternalSemaSource(this));\n m_Interpreter->getSema().addExternalSource(m_ExternalSemaSource.get());\n }\n\n ASTReader* Reader = m_Interpreter->getCI()->getModuleManager();\n if (enableDeserializationListenerCallbacks && Reader) {\n \/\/ FIXME: need to create a multiplexer if a DeserializationListener is\n \/\/ alreday present.\n m_DeserializationListener.\n reset(new InterpreterDeserializationListener(this));\n Reader->setDeserializationListener(m_DeserializationListener.get());\n }\n }\n\n \/\/ pin the vtable here\n InterpreterCallbacks::~InterpreterCallbacks() {\n \/\/ FIXME: we have to remove the external source at destruction time. Needs\n \/\/ further tweaks of the patch in clang. This will be done later once the \n \/\/ patch is in clang's mainline.\n }\n\n ExternalSemaSource* \n InterpreterCallbacks::getInterpreterExternalSemaSource() const {\n return m_ExternalSemaSource.get();\n }\n\n ASTDeserializationListener* \n InterpreterCallbacks::getInterpreterDeserializationListener() const {\n return m_DeserializationListener.get();\n }\n\n bool InterpreterCallbacks::LookupObject(LookupResult&, Scope*) {\n return false;\n }\n\n bool InterpreterCallbacks::LookupObject(const DeclContext*, DeclarationName) {\n return false;\n }\n\n void InterpreterCallbacks::UpdateWithNewDecls(const DeclContext *DC, \n DeclarationName Name, \n llvm::ArrayRef Decls) {\n if (m_ExternalSemaSource)\n m_ExternalSemaSource->UpdateWithNewDeclsFwd(DC, Name, Decls);\n }\n} \/\/ end namespace cling\n\n\/\/ TODO: Make the build system in the testsuite aware how to build that class\n\/\/ and extract it out there again.\n#include \"DynamicLookup.h\"\n#include \"cling\/Utils\/AST.h\"\n\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/Lex\/Preprocessor.h\"\n#include \"clang\/Sema\/Lookup.h\"\n#include \"clang\/Sema\/Scope.h\"\nnamespace cling {\nnamespace test {\n TestProxy* Tester = 0;\n\n extern \"C\" int printf(const char* fmt, ...);\n TestProxy::TestProxy(){}\n int TestProxy::Draw(){ return 12; }\n const char* TestProxy::getVersion(){ return \"Interpreter.cpp\"; }\n\n int TestProxy::Add10(int num) { return num + 10;}\n\n int TestProxy::Add(int a, int b) {\n return a + b;\n }\n\n void TestProxy::PrintString(std::string s) { printf(\"%s\\n\", s.c_str()); }\n\n bool TestProxy::PrintArray(int a[], size_t size) {\n for (unsigned i = 0; i < size; ++i)\n printf(\"%i\", a[i]);\n\n printf(\"%s\", \"\\n\");\n\n return true;\n }\n\n void TestProxy::PrintArray(float a[][5], size_t size) {\n for (unsigned i = 0; i < size; ++i)\n for (unsigned j = 0; j < 5; ++j)\n printf(\"%i\", (int)a[i][j]);\n\n printf(\"%s\", \"\\n\");\n }\n\n void TestProxy::PrintArray(int a[][4][5], size_t size) {\n for (unsigned i = 0; i < size; ++i)\n for (unsigned j = 0; j < 4; ++j)\n for (unsigned k = 0; k < 5; ++k)\n printf(\"%i\", a[i][j][k]);\n\n printf(\"%s\", \"\\n\");\n }\n\n SymbolResolverCallback::SymbolResolverCallback(Interpreter* interp)\n : InterpreterCallbacks(interp), m_TesterDecl(0) {\n m_Interpreter->process(\"cling::test::Tester = new cling::test::TestProxy();\");\n }\n\n SymbolResolverCallback::~SymbolResolverCallback() { }\n\n bool SymbolResolverCallback::LookupObject(LookupResult& R, Scope* S) {\n if (m_IsRuntime) {\n \/\/ Only for demo resolve all unknown objects to cling::test::Tester\n if (!m_TesterDecl) {\n clang::Sema& SemaR = m_Interpreter->getSema();\n clang::NamespaceDecl* NSD = utils::Lookup::Namespace(&SemaR, \"cling\");\n NSD = utils::Lookup::Namespace(&SemaR, \"test\", NSD);\n m_TesterDecl = utils::Lookup::Named(&SemaR, \"Tester\", NSD);\n }\n assert (m_TesterDecl && \"Tester not found!\");\n R.addDecl(m_TesterDecl);\n return true; \/\/ Tell clang to continue.\n }\n\n if (ShouldResolveAtRuntime(R, S)) {\n ASTContext& C = R.getSema().getASTContext();\n DeclContext* DC = 0;\n \/\/ For DeclContext-less scopes like if (dyn_expr) {}\n while (!DC) {\n DC = static_cast(S->getEntity());\n S = S->getParent();\n }\n DeclarationName Name = R.getLookupName();\n IdentifierInfo* II = Name.getAsIdentifierInfo();\n SourceLocation Loc = R.getNameLoc();\n VarDecl* Res = VarDecl::Create(C, DC, Loc, Loc, II, C.DependentTy,\n \/*TypeSourceInfo*\/0, SC_None);\n\n \/\/ Annotate the decl to give a hint in cling. FIXME: Current implementation\n \/\/ is a gross hack, because TClingCallbacks shouldn't know about \n \/\/ EvaluateTSynthesizer at all!\n SourceRange invalidRange;\n Res->addAttr(new (C) AnnotateAttr(invalidRange, C, \"__ResolveAtRuntime\"));\n R.addDecl(Res);\n DC->addDecl(Res);\n \/\/ Say that we can handle the situation. Clang should try to recover\n return true;\n }\n\n return false;\n }\n\n bool SymbolResolverCallback::ShouldResolveAtRuntime(LookupResult& R, \n Scope* S) {\n\n if (R.getLookupKind() != Sema::LookupOrdinaryName) \n return false;\n\n if (R.isForRedeclaration()) \n return false;\n\n if (!R.empty())\n return false;\n\n \/\/ FIXME: Figure out better way to handle:\n \/\/ C++ [basic.lookup.classref]p1:\n \/\/ In a class member access expression (5.2.5), if the . or -> token is\n \/\/ immediately followed by an identifier followed by a <, the\n \/\/ identifier must be looked up to determine whether the < is the\n \/\/ beginning of a template argument list (14.2) or a less-than operator.\n \/\/ The identifier is first looked up in the class of the object\n \/\/ expression. If the identifier is not found, it is then looked up in\n \/\/ the context of the entire postfix-expression and shall name a class\n \/\/ or function template.\n \/\/\n \/\/ We want to ignore object(.|->)member