text
stringlengths
5
1.04M
// Copyright 2011 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <stdlib.h> #include <math.h> #include <limits.h> #include <cstdarg> #include "v8.h" #if defined(V8_TARGET_ARCH_MIPS) #include "cpu.h" #include "disasm.h" #include "assembler.h" #include "globals.h" // Need the BitCast. #include "mips/constants-mips.h" #include "mips/simulator-mips.h" // Only build the simulator if not compiling for real MIPS hardware. #if defined(USE_SIMULATOR) namespace v8 { namespace internal { // Utils functions. bool HaveSameSign(int32_t a, int32_t b) { return ((a ^ b) >= 0); } uint32_t get_fcsr_condition_bit(uint32_t cc) { if (cc == 0) { return 23; } else { return 24 + cc; } } // This macro provides a platform independent use of sscanf. The reason for // SScanF not being implemented in a platform independent was through // ::v8::internal::OS in the same way as SNPrintF is that the Windows C Run-Time // Library does not provide vsscanf. #define SScanF sscanf // NOLINT // The MipsDebugger class is used by the simulator while debugging simulated // code. class MipsDebugger { public: explicit MipsDebugger(Simulator* sim) : sim_(sim) { } ~MipsDebugger(); void Stop(Instruction* instr); void Debug(); // Print all registers with a nice formatting. void PrintAllRegs(); void PrintAllRegsIncludingFPU(); private: // We set the breakpoint code to 0xfffff to easily recognize it. static const Instr kBreakpointInstr = SPECIAL | BREAK | 0xfffff << 6; static const Instr kNopInstr = 0x0; Simulator* sim_; int32_t GetRegisterValue(int regnum); int32_t GetFPURegisterValueInt(int regnum); int64_t GetFPURegisterValueLong(int regnum); float GetFPURegisterValueFloat(int regnum); double GetFPURegisterValueDouble(int regnum); bool GetValue(const char* desc, int32_t* value); // Set or delete a breakpoint. Returns true if successful. bool SetBreakpoint(Instruction* breakpc); bool DeleteBreakpoint(Instruction* breakpc); // Undo and redo all breakpoints. This is needed to bracket disassembly and // execution to skip past breakpoints when run from the debugger. void UndoBreakpoints(); void RedoBreakpoints(); }; MipsDebugger::~MipsDebugger() { } #ifdef GENERATED_CODE_COVERAGE static FILE* coverage_log = NULL; static void InitializeCoverage() { char* file_name = getenv("V8_GENERATED_CODE_COVERAGE_LOG"); if (file_name != NULL) { coverage_log = fopen(file_name, "aw+"); } } void MipsDebugger::Stop(Instruction* instr) { // Get the stop code. uint32_t code = instr->Bits(25, 6); // Retrieve the encoded address, which comes just after this stop. char** msg_address = reinterpret_cast<char**>(sim_->get_pc() + Instr::kInstrSize); char* msg = *msg_address; ASSERT(msg != NULL); // Update this stop description. if (!watched_stops[code].desc) { watched_stops[code].desc = msg; } if (strlen(msg) > 0) { if (coverage_log != NULL) { fprintf(coverage_log, "%s\n", str); fflush(coverage_log); } // Overwrite the instruction and address with nops. instr->SetInstructionBits(kNopInstr); reinterpret_cast<Instr*>(msg_address)->SetInstructionBits(kNopInstr); } sim_->set_pc(sim_->get_pc() + 2 * Instruction::kInstructionSize); } #else // GENERATED_CODE_COVERAGE #define UNSUPPORTED() printf("Unsupported instruction.\n"); static void InitializeCoverage() {} void MipsDebugger::Stop(Instruction* instr) { // Get the stop code. uint32_t code = instr->Bits(25, 6); // Retrieve the encoded address, which comes just after this stop. char* msg = *reinterpret_cast<char**>(sim_->get_pc() + Instruction::kInstrSize); // Update this stop description. if (!sim_->watched_stops[code].desc) { sim_->watched_stops[code].desc = msg; } PrintF("Simulator hit %s (%u)\n", msg, code); sim_->set_pc(sim_->get_pc() + 2 * Instruction::kInstrSize); Debug(); } #endif // GENERATED_CODE_COVERAGE int32_t MipsDebugger::GetRegisterValue(int regnum) { if (regnum == kNumSimuRegisters) { return sim_->get_pc(); } else { return sim_->get_register(regnum); } } int32_t MipsDebugger::GetFPURegisterValueInt(int regnum) { if (regnum == kNumFPURegisters) { return sim_->get_pc(); } else { return sim_->get_fpu_register(regnum); } } int64_t MipsDebugger::GetFPURegisterValueLong(int regnum) { if (regnum == kNumFPURegisters) { return sim_->get_pc(); } else { return sim_->get_fpu_register_long(regnum); } } float MipsDebugger::GetFPURegisterValueFloat(int regnum) { if (regnum == kNumFPURegisters) { return sim_->get_pc(); } else { return sim_->get_fpu_register_float(regnum); } } double MipsDebugger::GetFPURegisterValueDouble(int regnum) { if (regnum == kNumFPURegisters) { return sim_->get_pc(); } else { return sim_->get_fpu_register_double(regnum); } } bool MipsDebugger::GetValue(const char* desc, int32_t* value) { int regnum = Registers::Number(desc); int fpuregnum = FPURegisters::Number(desc); if (regnum != kInvalidRegister) { *value = GetRegisterValue(regnum); return true; } else if (fpuregnum != kInvalidFPURegister) { *value = GetFPURegisterValueInt(fpuregnum); return true; } else if (strncmp(desc, "0x", 2) == 0) { return SScanF(desc, "%x", reinterpret_cast<uint32_t*>(value)) == 1; } else { return SScanF(desc, "%i", value) == 1; } return false; } bool MipsDebugger::SetBreakpoint(Instruction* breakpc) { // Check if a breakpoint can be set. If not return without any side-effects. if (sim_->break_pc_ != NULL) { return false; } // Set the breakpoint. sim_->break_pc_ = breakpc; sim_->break_instr_ = breakpc->InstructionBits(); // Not setting the breakpoint instruction in the code itself. It will be set // when the debugger shell continues. return true; } bool MipsDebugger::DeleteBreakpoint(Instruction* breakpc) { if (sim_->break_pc_ != NULL) { sim_->break_pc_->SetInstructionBits(sim_->break_instr_); } sim_->break_pc_ = NULL; sim_->break_instr_ = 0; return true; } void MipsDebugger::UndoBreakpoints() { if (sim_->break_pc_ != NULL) { sim_->break_pc_->SetInstructionBits(sim_->break_instr_); } } void MipsDebugger::RedoBreakpoints() { if (sim_->break_pc_ != NULL) { sim_->break_pc_->SetInstructionBits(kBreakpointInstr); } } void MipsDebugger::PrintAllRegs() { #define REG_INFO(n) Registers::Name(n), GetRegisterValue(n), GetRegisterValue(n) PrintF("\n"); // at, v0, a0. PrintF("%3s: 0x%08x %10d\t%3s: 0x%08x %10d\t%3s: 0x%08x %10d\n", REG_INFO(1), REG_INFO(2), REG_INFO(4)); // v1, a1. PrintF("%26s\t%3s: 0x%08x %10d\t%3s: 0x%08x %10d\n", "", REG_INFO(3), REG_INFO(5)); // a2. PrintF("%26s\t%26s\t%3s: 0x%08x %10d\n", "", "", REG_INFO(6)); // a3. PrintF("%26s\t%26s\t%3s: 0x%08x %10d\n", "", "", REG_INFO(7)); PrintF("\n"); // t0-t7, s0-s7 for (int i = 0; i < 8; i++) { PrintF("%3s: 0x%08x %10d\t%3s: 0x%08x %10d\n", REG_INFO(8+i), REG_INFO(16+i)); } PrintF("\n"); // t8, k0, LO. PrintF("%3s: 0x%08x %10d\t%3s: 0x%08x %10d\t%3s: 0x%08x %10d\n", REG_INFO(24), REG_INFO(26), REG_INFO(32)); // t9, k1, HI. PrintF("%3s: 0x%08x %10d\t%3s: 0x%08x %10d\t%3s: 0x%08x %10d\n", REG_INFO(25), REG_INFO(27), REG_INFO(33)); // sp, fp, gp. PrintF("%3s: 0x%08x %10d\t%3s: 0x%08x %10d\t%3s: 0x%08x %10d\n", REG_INFO(29), REG_INFO(30), REG_INFO(28)); // pc. PrintF("%3s: 0x%08x %10d\t%3s: 0x%08x %10d\n", REG_INFO(31), REG_INFO(34)); #undef REG_INFO #undef FPU_REG_INFO } void MipsDebugger::PrintAllRegsIncludingFPU() { #define FPU_REG_INFO(n) FPURegisters::Name(n), FPURegisters::Name(n+1), \ GetFPURegisterValueInt(n+1), \ GetFPURegisterValueInt(n), \ GetFPURegisterValueDouble(n) PrintAllRegs(); PrintF("\n\n"); // f0, f1, f2, ... f31. PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO(0) ); PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO(2) ); PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO(4) ); PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO(6) ); PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO(8) ); PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO(10)); PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO(12)); PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO(14)); PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO(16)); PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO(18)); PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO(20)); PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO(22)); PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO(24)); PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO(26)); PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO(28)); PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPU_REG_INFO(30)); #undef REG_INFO #undef FPU_REG_INFO } void MipsDebugger::Debug() { intptr_t last_pc = -1; bool done = false; #define COMMAND_SIZE 63 #define ARG_SIZE 255 #define STR(a) #a #define XSTR(a) STR(a) char cmd[COMMAND_SIZE + 1]; char arg1[ARG_SIZE + 1]; char arg2[ARG_SIZE + 1]; char* argv[3] = { cmd, arg1, arg2 }; // Make sure to have a proper terminating character if reaching the limit. cmd[COMMAND_SIZE] = 0; arg1[ARG_SIZE] = 0; arg2[ARG_SIZE] = 0; // Undo all set breakpoints while running in the debugger shell. This will // make them invisible to all commands. UndoBreakpoints(); while (!done && (sim_->get_pc() != Simulator::end_sim_pc)) { if (last_pc != sim_->get_pc()) { disasm::NameConverter converter; disasm::Disassembler dasm(converter); // Use a reasonably large buffer. v8::internal::EmbeddedVector<char, 256> buffer; dasm.InstructionDecode(buffer, reinterpret_cast<byte*>(sim_->get_pc())); PrintF(" 0x%08x %s\n", sim_->get_pc(), buffer.start()); last_pc = sim_->get_pc(); } char* line = ReadLine("sim> "); if (line == NULL) { break; } else { char* last_input = sim_->last_debugger_input(); if (strcmp(line, "\n") == 0 && last_input != NULL) { line = last_input; } else { // Ownership is transferred to sim_; sim_->set_last_debugger_input(line); } // Use sscanf to parse the individual parts of the command line. At the // moment no command expects more than two parameters. int argc = SScanF(line, "%" XSTR(COMMAND_SIZE) "s " "%" XSTR(ARG_SIZE) "s " "%" XSTR(ARG_SIZE) "s", cmd, arg1, arg2); if ((strcmp(cmd, "si") == 0) || (strcmp(cmd, "stepi") == 0)) { Instruction* instr = reinterpret_cast<Instruction*>(sim_->get_pc()); if (!(instr->IsTrap()) || instr->InstructionBits() == rtCallRedirInstr) { sim_->InstructionDecode( reinterpret_cast<Instruction*>(sim_->get_pc())); } else { // Allow si to jump over generated breakpoints. PrintF("/!\\ Jumping over generated breakpoint.\n"); sim_->set_pc(sim_->get_pc() + Instruction::kInstrSize); } } else if ((strcmp(cmd, "c") == 0) || (strcmp(cmd, "cont") == 0)) { // Execute the one instruction we broke at with breakpoints disabled. sim_->InstructionDecode(reinterpret_cast<Instruction*>(sim_->get_pc())); // Leave the debugger shell. done = true; } else if ((strcmp(cmd, "p") == 0) || (strcmp(cmd, "print") == 0)) { if (argc == 2) { int32_t value; float fvalue; if (strcmp(arg1, "all") == 0) { PrintAllRegs(); } else if (strcmp(arg1, "allf") == 0) { PrintAllRegsIncludingFPU(); } else { int regnum = Registers::Number(arg1); int fpuregnum = FPURegisters::Number(arg1); if (regnum != kInvalidRegister) { value = GetRegisterValue(regnum); PrintF("%s: 0x%08x %d \n", arg1, value, value); } else if (fpuregnum != kInvalidFPURegister) { if (fpuregnum % 2 == 1) { value = GetFPURegisterValueInt(fpuregnum); fvalue = GetFPURegisterValueFloat(fpuregnum); PrintF("%s: 0x%08x %11.4e\n", arg1, value, fvalue); } else { double dfvalue; int32_t lvalue1 = GetFPURegisterValueInt(fpuregnum); int32_t lvalue2 = GetFPURegisterValueInt(fpuregnum + 1); dfvalue = GetFPURegisterValueDouble(fpuregnum); PrintF("%3s,%3s: 0x%08x%08x %16.4e\n", FPURegisters::Name(fpuregnum+1), FPURegisters::Name(fpuregnum), lvalue1, lvalue2, dfvalue); } } else { PrintF("%s unrecognized\n", arg1); } } } else { if (argc == 3) { if (strcmp(arg2, "single") == 0) { int32_t value; float fvalue; int fpuregnum = FPURegisters::Number(arg1); if (fpuregnum != kInvalidFPURegister) { value = GetFPURegisterValueInt(fpuregnum); fvalue = GetFPURegisterValueFloat(fpuregnum); PrintF("%s: 0x%08x %11.4e\n", arg1, value, fvalue); } else { PrintF("%s unrecognized\n", arg1); } } else { PrintF("print <fpu register> single\n"); } } else { PrintF("print <register> or print <fpu register> single\n"); } } } else if ((strcmp(cmd, "po") == 0) || (strcmp(cmd, "printobject") == 0)) { if (argc == 2) { int32_t value; if (GetValue(arg1, &value)) { Object* obj = reinterpret_cast<Object*>(value); PrintF("%s: \n", arg1); #ifdef DEBUG obj->PrintLn(); #else obj->ShortPrint(); PrintF("\n"); #endif } else { PrintF("%s unrecognized\n", arg1); } } else { PrintF("printobject <value>\n"); } } else if (strcmp(cmd, "stack") == 0 || strcmp(cmd, "mem") == 0) { int32_t* cur = NULL; int32_t* end = NULL; int next_arg = 1; if (strcmp(cmd, "stack") == 0) { cur = reinterpret_cast<int32_t*>(sim_->get_register(Simulator::sp)); } else { // Command "mem". int32_t value; if (!GetValue(arg1, &value)) { PrintF("%s unrecognized\n", arg1); continue; } cur = reinterpret_cast<int32_t*>(value); next_arg++; } int32_t words; if (argc == next_arg) { words = 10; } else if (argc == next_arg + 1) { if (!GetValue(argv[next_arg], &words)) { words = 10; } } end = cur + words; while (cur < end) { PrintF(" 0x%08x: 0x%08x %10d", reinterpret_cast<intptr_t>(cur), *cur, *cur); HeapObject* obj = reinterpret_cast<HeapObject*>(*cur); int value = *cur; Heap* current_heap = v8::internal::Isolate::Current()->heap(); if (current_heap->Contains(obj) || ((value & 1) == 0)) { PrintF(" ("); if ((value & 1) == 0) { PrintF("smi %d", value / 2); } else { obj->ShortPrint(); } PrintF(")"); } PrintF("\n"); cur++; } } else if ((strcmp(cmd, "disasm") == 0) || (strcmp(cmd, "dpc") == 0) || (strcmp(cmd, "di") == 0)) { disasm::NameConverter converter; disasm::Disassembler dasm(converter); // Use a reasonably large buffer. v8::internal::EmbeddedVector<char, 256> buffer; byte* cur = NULL; byte* end = NULL; if (argc == 1) { cur = reinterpret_cast<byte*>(sim_->get_pc()); end = cur + (10 * Instruction::kInstrSize); } else if (argc == 2) { int regnum = Registers::Number(arg1); if (regnum != kInvalidRegister || strncmp(arg1, "0x", 2) == 0) { // The argument is an address or a register name. int32_t value; if (GetValue(arg1, &value)) { cur = reinterpret_cast<byte*>(value); // Disassemble 10 instructions at <arg1>. end = cur + (10 * Instruction::kInstrSize); } } else { // The argument is the number of instructions. int32_t value; if (GetValue(arg1, &value)) { cur = reinterpret_cast<byte*>(sim_->get_pc()); // Disassemble <arg1> instructions. end = cur + (value * Instruction::kInstrSize); } } } else { int32_t value1; int32_t value2; if (GetValue(arg1, &value1) && GetValue(arg2, &value2)) { cur = reinterpret_cast<byte*>(value1); end = cur + (value2 * Instruction::kInstrSize); } } while (cur < end) { dasm.InstructionDecode(buffer, cur); PrintF(" 0x%08x %s\n", reinterpret_cast<intptr_t>(cur), buffer.start()); cur += Instruction::kInstrSize; } } else if (strcmp(cmd, "gdb") == 0) { PrintF("relinquishing control to gdb\n"); v8::internal::OS::DebugBreak(); PrintF("regaining control from gdb\n"); } else if (strcmp(cmd, "break") == 0) { if (argc == 2) { int32_t value; if (GetValue(arg1, &value)) { if (!SetBreakpoint(reinterpret_cast<Instruction*>(value))) { PrintF("setting breakpoint failed\n"); } } else { PrintF("%s unrecognized\n", arg1); } } else { PrintF("break <address>\n"); } } else if (strcmp(cmd, "del") == 0) { if (!DeleteBreakpoint(NULL)) { PrintF("deleting breakpoint failed\n"); } } else if (strcmp(cmd, "flags") == 0) { PrintF("No flags on MIPS !\n"); } else if (strcmp(cmd, "stop") == 0) { int32_t value; intptr_t stop_pc = sim_->get_pc() - 2 * Instruction::kInstrSize; Instruction* stop_instr = reinterpret_cast<Instruction*>(stop_pc); Instruction* msg_address = reinterpret_cast<Instruction*>(stop_pc + Instruction::kInstrSize); if ((argc == 2) && (strcmp(arg1, "unstop") == 0)) { // Remove the current stop. if (sim_->IsStopInstruction(stop_instr)) { stop_instr->SetInstructionBits(kNopInstr); msg_address->SetInstructionBits(kNopInstr); } else { PrintF("Not at debugger stop.\n"); } } else if (argc == 3) { // Print information about all/the specified breakpoint(s). if (strcmp(arg1, "info") == 0) { if (strcmp(arg2, "all") == 0) { PrintF("Stop information:\n"); for (uint32_t i = kMaxWatchpointCode + 1; i <= kMaxStopCode; i++) { sim_->PrintStopInfo(i); } } else if (GetValue(arg2, &value)) { sim_->PrintStopInfo(value); } else { PrintF("Unrecognized argument.\n"); } } else if (strcmp(arg1, "enable") == 0) { // Enable all/the specified breakpoint(s). if (strcmp(arg2, "all") == 0) { for (uint32_t i = kMaxWatchpointCode + 1; i <= kMaxStopCode; i++) { sim_->EnableStop(i); } } else if (GetValue(arg2, &value)) { sim_->EnableStop(value); } else { PrintF("Unrecognized argument.\n"); } } else if (strcmp(arg1, "disable") == 0) { // Disable all/the specified breakpoint(s). if (strcmp(arg2, "all") == 0) { for (uint32_t i = kMaxWatchpointCode + 1; i <= kMaxStopCode; i++) { sim_->DisableStop(i); } } else if (GetValue(arg2, &value)) { sim_->DisableStop(value); } else { PrintF("Unrecognized argument.\n"); } } } else { PrintF("Wrong usage. Use help command for more information.\n"); } } else if ((strcmp(cmd, "stat") == 0) || (strcmp(cmd, "st") == 0)) { // Print registers and disassemble. PrintAllRegs(); PrintF("\n"); disasm::NameConverter converter; disasm::Disassembler dasm(converter); // Use a reasonably large buffer. v8::internal::EmbeddedVector<char, 256> buffer; byte* cur = NULL; byte* end = NULL; if (argc == 1) { cur = reinterpret_cast<byte*>(sim_->get_pc()); end = cur + (10 * Instruction::kInstrSize); } else if (argc == 2) { int32_t value; if (GetValue(arg1, &value)) { cur = reinterpret_cast<byte*>(value); // no length parameter passed, assume 10 instructions end = cur + (10 * Instruction::kInstrSize); } } else { int32_t value1; int32_t value2; if (GetValue(arg1, &value1) && GetValue(arg2, &value2)) { cur = reinterpret_cast<byte*>(value1); end = cur + (value2 * Instruction::kInstrSize); } } while (cur < end) { dasm.InstructionDecode(buffer, cur); PrintF(" 0x%08x %s\n", reinterpret_cast<intptr_t>(cur), buffer.start()); cur += Instruction::kInstrSize; } } else if ((strcmp(cmd, "h") == 0) || (strcmp(cmd, "help") == 0)) { PrintF("cont\n"); PrintF(" continue execution (alias 'c')\n"); PrintF("stepi\n"); PrintF(" step one instruction (alias 'si')\n"); PrintF("print <register>\n"); PrintF(" print register content (alias 'p')\n"); PrintF(" use register name 'all' to print all registers\n"); PrintF("printobject <register>\n"); PrintF(" print an object from a register (alias 'po')\n"); PrintF("stack [<words>]\n"); PrintF(" dump stack content, default dump 10 words)\n"); PrintF("mem <address> [<words>]\n"); PrintF(" dump memory content, default dump 10 words)\n"); PrintF("flags\n"); PrintF(" print flags\n"); PrintF("disasm [<instructions>]\n"); PrintF("disasm [<address/register>]\n"); PrintF("disasm [[<address/register>] <instructions>]\n"); PrintF(" disassemble code, default is 10 instructions\n"); PrintF(" from pc (alias 'di')\n"); PrintF("gdb\n"); PrintF(" enter gdb\n"); PrintF("break <address>\n"); PrintF(" set a break point on the address\n"); PrintF("del\n"); PrintF(" delete the breakpoint\n"); PrintF("stop feature:\n"); PrintF(" Description:\n"); PrintF(" Stops are debug instructions inserted by\n"); PrintF(" the Assembler::stop() function.\n"); PrintF(" When hitting a stop, the Simulator will\n"); PrintF(" stop and and give control to the Debugger.\n"); PrintF(" All stop codes are watched:\n"); PrintF(" - They can be enabled / disabled: the Simulator\n"); PrintF(" will / won't stop when hitting them.\n"); PrintF(" - The Simulator keeps track of how many times they \n"); PrintF(" are met. (See the info command.) Going over a\n"); PrintF(" disabled stop still increases its counter. \n"); PrintF(" Commands:\n"); PrintF(" stop info all/<code> : print infos about number <code>\n"); PrintF(" or all stop(s).\n"); PrintF(" stop enable/disable all/<code> : enables / disables\n"); PrintF(" all or number <code> stop(s)\n"); PrintF(" stop unstop\n"); PrintF(" ignore the stop instruction at the current location\n"); PrintF(" from now on\n"); } else { PrintF("Unknown command: %s\n", cmd); } } } // Add all the breakpoints back to stop execution and enter the debugger // shell when hit. RedoBreakpoints(); #undef COMMAND_SIZE #undef ARG_SIZE #undef STR #undef XSTR } static bool ICacheMatch(void* one, void* two) { ASSERT((reinterpret_cast<intptr_t>(one) & CachePage::kPageMask) == 0); ASSERT((reinterpret_cast<intptr_t>(two) & CachePage::kPageMask) == 0); return one == two; } static uint32_t ICacheHash(void* key) { return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(key)) >> 2; } static bool AllOnOnePage(uintptr_t start, int size) { intptr_t start_page = (start & ~CachePage::kPageMask); intptr_t end_page = ((start + size) & ~CachePage::kPageMask); return start_page == end_page; } void Simulator::set_last_debugger_input(char* input) { DeleteArray(last_debugger_input_); last_debugger_input_ = input; } void Simulator::FlushICache(v8::internal::HashMap* i_cache, void* start_addr, size_t size) { intptr_t start = reinterpret_cast<intptr_t>(start_addr); int intra_line = (start & CachePage::kLineMask); start -= intra_line; size += intra_line; size = ((size - 1) | CachePage::kLineMask) + 1; int offset = (start & CachePage::kPageMask); while (!AllOnOnePage(start, size - 1)) { int bytes_to_flush = CachePage::kPageSize - offset; FlushOnePage(i_cache, start, bytes_to_flush); start += bytes_to_flush; size -= bytes_to_flush; ASSERT_EQ(0, start & CachePage::kPageMask); offset = 0; } if (size != 0) { FlushOnePage(i_cache, start, size); } } CachePage* Simulator::GetCachePage(v8::internal::HashMap* i_cache, void* page) { v8::internal::HashMap::Entry* entry = i_cache->Lookup(page, ICacheHash(page), true); if (entry->value == NULL) { CachePage* new_page = new CachePage(); entry->value = new_page; } return reinterpret_cast<CachePage*>(entry->value); } // Flush from start up to and not including start + size. void Simulator::FlushOnePage(v8::internal::HashMap* i_cache, intptr_t start, int size) { ASSERT(size <= CachePage::kPageSize); ASSERT(AllOnOnePage(start, size - 1)); ASSERT((start & CachePage::kLineMask) == 0); ASSERT((size & CachePage::kLineMask) == 0); void* page = reinterpret_cast<void*>(start & (~CachePage::kPageMask)); int offset = (start & CachePage::kPageMask); CachePage* cache_page = GetCachePage(i_cache, page); char* valid_bytemap = cache_page->ValidityByte(offset); memset(valid_bytemap, CachePage::LINE_INVALID, size >> CachePage::kLineShift); } void Simulator::CheckICache(v8::internal::HashMap* i_cache, Instruction* instr) { intptr_t address = reinterpret_cast<intptr_t>(instr); void* page = reinterpret_cast<void*>(address & (~CachePage::kPageMask)); void* line = reinterpret_cast<void*>(address & (~CachePage::kLineMask)); int offset = (address & CachePage::kPageMask); CachePage* cache_page = GetCachePage(i_cache, page); char* cache_valid_byte = cache_page->ValidityByte(offset); bool cache_hit = (*cache_valid_byte == CachePage::LINE_VALID); char* cached_line = cache_page->CachedData(offset & ~CachePage::kLineMask); if (cache_hit) { // Check that the data in memory matches the contents of the I-cache. CHECK(memcmp(reinterpret_cast<void*>(instr), cache_page->CachedData(offset), Instruction::kInstrSize) == 0); } else { // Cache miss. Load memory into the cache. memcpy(cached_line, line, CachePage::kLineLength); *cache_valid_byte = CachePage::LINE_VALID; } } void Simulator::Initialize(Isolate* isolate) { if (isolate->simulator_initialized()) return; isolate->set_simulator_initialized(true); ::v8::internal::ExternalReference::set_redirector(isolate, &RedirectExternalReference); } Simulator::Simulator(Isolate* isolate) : isolate_(isolate) { i_cache_ = isolate_->simulator_i_cache(); if (i_cache_ == NULL) { i_cache_ = new v8::internal::HashMap(&ICacheMatch); isolate_->set_simulator_i_cache(i_cache_); } Initialize(isolate); // Setup simulator support first. Some of this information is needed to // setup the architecture state. stack_ = reinterpret_cast<char*>(malloc(stack_size_)); pc_modified_ = false; icount_ = 0; break_count_ = 0; break_pc_ = NULL; break_instr_ = 0; // Setup architecture state. // All registers are initialized to zero to start with. for (int i = 0; i < kNumSimuRegisters; i++) { registers_[i] = 0; } for (int i = 0; i < kNumFPURegisters; i++) { FPUregisters_[i] = 0; } FCSR_ = 0; // The sp is initialized to point to the bottom (high address) of the // allocated stack area. To be safe in potential stack underflows we leave // some buffer below. registers_[sp] = reinterpret_cast<int32_t>(stack_) + stack_size_ - 64; // The ra and pc are initialized to a known bad value that will cause an // access violation if the simulator ever tries to execute it. registers_[pc] = bad_ra; registers_[ra] = bad_ra; InitializeCoverage(); for (int i = 0; i < kNumExceptions; i++) { exceptions[i] = 0; } last_debugger_input_ = NULL; } // When the generated code calls an external reference we need to catch that in // the simulator. The external reference will be a function compiled for the // host architecture. We need to call that function instead of trying to // execute it with the simulator. We do that by redirecting the external // reference to a swi (software-interrupt) instruction that is handled by // the simulator. We write the original destination of the jump just at a known // offset from the swi instruction so the simulator knows what to call. class Redirection { public: Redirection(void* external_function, ExternalReference::Type type) : external_function_(external_function), swi_instruction_(rtCallRedirInstr), type_(type), next_(NULL) { Isolate* isolate = Isolate::Current(); next_ = isolate->simulator_redirection(); Simulator::current(isolate)-> FlushICache(isolate->simulator_i_cache(), reinterpret_cast<void*>(&swi_instruction_), Instruction::kInstrSize); isolate->set_simulator_redirection(this); } void* address_of_swi_instruction() { return reinterpret_cast<void*>(&swi_instruction_); } void* external_function() { return external_function_; } ExternalReference::Type type() { return type_; } static Redirection* Get(void* external_function, ExternalReference::Type type) { Isolate* isolate = Isolate::Current(); Redirection* current = isolate->simulator_redirection(); for (; current != NULL; current = current->next_) { if (current->external_function_ == external_function) return current; } return new Redirection(external_function, type); } static Redirection* FromSwiInstruction(Instruction* swi_instruction) { char* addr_of_swi = reinterpret_cast<char*>(swi_instruction); char* addr_of_redirection = addr_of_swi - OFFSET_OF(Redirection, swi_instruction_); return reinterpret_cast<Redirection*>(addr_of_redirection); } private: void* external_function_; uint32_t swi_instruction_; ExternalReference::Type type_; Redirection* next_; }; void* Simulator::RedirectExternalReference(void* external_function, ExternalReference::Type type) { Redirection* redirection = Redirection::Get(external_function, type); return redirection->address_of_swi_instruction(); } // Get the active Simulator for the current thread. Simulator* Simulator::current(Isolate* isolate) { v8::internal::Isolate::PerIsolateThreadData* isolate_data = isolate->FindOrAllocatePerThreadDataForThisThread(); ASSERT(isolate_data != NULL); ASSERT(isolate_data != NULL); Simulator* sim = isolate_data->simulator(); if (sim == NULL) { // TODO(146): delete the simulator object when a thread/isolate goes away. sim = new Simulator(isolate); isolate_data->set_simulator(sim); } return sim; } // Sets the register in the architecture state. It will also deal with updating // Simulator internal state for special registers such as PC. void Simulator::set_register(int reg, int32_t value) { ASSERT((reg >= 0) && (reg < kNumSimuRegisters)); if (reg == pc) { pc_modified_ = true; } // Zero register always holds 0. registers_[reg] = (reg == 0) ? 0 : value; } void Simulator::set_fpu_register(int fpureg, int32_t value) { ASSERT((fpureg >= 0) && (fpureg < kNumFPURegisters)); FPUregisters_[fpureg] = value; } void Simulator::set_fpu_register_float(int fpureg, float value) { ASSERT((fpureg >= 0) && (fpureg < kNumFPURegisters)); *BitCast<float*>(&FPUregisters_[fpureg]) = value; } void Simulator::set_fpu_register_double(int fpureg, double value) { ASSERT((fpureg >= 0) && (fpureg < kNumFPURegisters) && ((fpureg % 2) == 0)); *BitCast<double*>(&FPUregisters_[fpureg]) = value; } // Get the register from the architecture state. This function does handle // the special case of accessing the PC register. int32_t Simulator::get_register(int reg) const { ASSERT((reg >= 0) && (reg < kNumSimuRegisters)); if (reg == 0) return 0; else return registers_[reg] + ((reg == pc) ? Instruction::kPCReadOffset : 0); } int32_t Simulator::get_fpu_register(int fpureg) const { ASSERT((fpureg >= 0) && (fpureg < kNumFPURegisters)); return FPUregisters_[fpureg]; } int64_t Simulator::get_fpu_register_long(int fpureg) const { ASSERT((fpureg >= 0) && (fpureg < kNumFPURegisters) && ((fpureg % 2) == 0)); return *BitCast<int64_t*>( const_cast<int32_t*>(&FPUregisters_[fpureg])); } float Simulator::get_fpu_register_float(int fpureg) const { ASSERT((fpureg >= 0) && (fpureg < kNumFPURegisters)); return *BitCast<float*>( const_cast<int32_t*>(&FPUregisters_[fpureg])); } double Simulator::get_fpu_register_double(int fpureg) const { ASSERT((fpureg >= 0) && (fpureg < kNumFPURegisters) && ((fpureg % 2) == 0)); return *BitCast<double*>(const_cast<int32_t*>(&FPUregisters_[fpureg])); } // For use in calls that take two double values, constructed either // from a0-a3 or f12 and f14. void Simulator::GetFpArgs(double* x, double* y) { if (!IsMipsSoftFloatABI) { *x = get_fpu_register_double(12); *y = get_fpu_register_double(14); } else { // We use a char buffer to get around the strict-aliasing rules which // otherwise allow the compiler to optimize away the copy. char buffer[sizeof(*x)]; int32_t* reg_buffer = reinterpret_cast<int32_t*>(buffer); // Registers a0 and a1 -> x. reg_buffer[0] = get_register(a0); reg_buffer[1] = get_register(a1); memcpy(x, buffer, sizeof(buffer)); // Registers a2 and a3 -> y. reg_buffer[0] = get_register(a2); reg_buffer[1] = get_register(a3); memcpy(y, buffer, sizeof(buffer)); } } // For use in calls that take one double value, constructed either // from a0 and a1 or f12. void Simulator::GetFpArgs(double* x) { if (!IsMipsSoftFloatABI) { *x = get_fpu_register_double(12); } else { // We use a char buffer to get around the strict-aliasing rules which // otherwise allow the compiler to optimize away the copy. char buffer[sizeof(*x)]; int32_t* reg_buffer = reinterpret_cast<int32_t*>(buffer); // Registers a0 and a1 -> x. reg_buffer[0] = get_register(a0); reg_buffer[1] = get_register(a1); memcpy(x, buffer, sizeof(buffer)); } } // For use in calls that take one double value constructed either // from a0 and a1 or f12 and one integer value. void Simulator::GetFpArgs(double* x, int32_t* y) { if (!IsMipsSoftFloatABI) { *x = get_fpu_register_double(12); *y = get_register(a2); } else { // We use a char buffer to get around the strict-aliasing rules which // otherwise allow the compiler to optimize away the copy. char buffer[sizeof(*x)]; int32_t* reg_buffer = reinterpret_cast<int32_t*>(buffer); // Registers 0 and 1 -> x. reg_buffer[0] = get_register(a0); reg_buffer[1] = get_register(a1); memcpy(x, buffer, sizeof(buffer)); // Register 2 -> y. reg_buffer[0] = get_register(a2); memcpy(y, buffer, sizeof(*y)); } } // The return value is either in v0/v1 or f0. void Simulator::SetFpResult(const double& result) { if (!IsMipsSoftFloatABI) { set_fpu_register_double(0, result); } else { char buffer[2 * sizeof(registers_[0])]; int32_t* reg_buffer = reinterpret_cast<int32_t*>(buffer); memcpy(buffer, &result, sizeof(buffer)); // Copy result to v0 and v1. set_register(v0, reg_buffer[0]); set_register(v1, reg_buffer[1]); } } // Helper functions for setting and testing the FCSR register's bits. void Simulator::set_fcsr_bit(uint32_t cc, bool value) { if (value) { FCSR_ |= (1 << cc); } else { FCSR_ &= ~(1 << cc); } } bool Simulator::test_fcsr_bit(uint32_t cc) { return FCSR_ & (1 << cc); } // Sets the rounding error codes in FCSR based on the result of the rounding. // Returns true if the operation was invalid. bool Simulator::set_fcsr_round_error(double original, double rounded) { bool ret = false; if (!isfinite(original) || !isfinite(rounded)) { set_fcsr_bit(kFCSRInvalidOpFlagBit, true); ret = true; } if (original != rounded) { set_fcsr_bit(kFCSRInexactFlagBit, true); } if (rounded < DBL_MIN && rounded > -DBL_MIN && rounded != 0) { set_fcsr_bit(kFCSRUnderflowFlagBit, true); ret = true; } if (rounded > INT_MAX || rounded < INT_MIN) { set_fcsr_bit(kFCSROverflowFlagBit, true); // The reference is not really clear but it seems this is required: set_fcsr_bit(kFCSRInvalidOpFlagBit, true); ret = true; } return ret; } // Raw access to the PC register. void Simulator::set_pc(int32_t value) { pc_modified_ = true; registers_[pc] = value; } bool Simulator::has_bad_pc() const { return ((registers_[pc] == bad_ra) || (registers_[pc] == end_sim_pc)); } // Raw access to the PC register without the special adjustment when reading. int32_t Simulator::get_pc() const { return registers_[pc]; } // The MIPS cannot do unaligned reads and writes. On some MIPS platforms an // interrupt is caused. On others it does a funky rotation thing. For now we // simply disallow unaligned reads, but at some point we may want to move to // emulating the rotate behaviour. Note that simulator runs have the runtime // system running directly on the host system and only generated code is // executed in the simulator. Since the host is typically IA32 we will not // get the correct MIPS-like behaviour on unaligned accesses. int Simulator::ReadW(int32_t addr, Instruction* instr) { if (addr >=0 && addr < 0x400) { // This has to be a NULL-dereference, drop into debugger. PrintF("Memory read from bad address: 0x%08x, pc=0x%08x\n", addr, reinterpret_cast<intptr_t>(instr)); MipsDebugger dbg(this); dbg.Debug(); } if ((addr & kPointerAlignmentMask) == 0) { intptr_t* ptr = reinterpret_cast<intptr_t*>(addr); return *ptr; } PrintF("Unaligned read at 0x%08x, pc=0x%08" V8PRIxPTR "\n", addr, reinterpret_cast<intptr_t>(instr)); MipsDebugger dbg(this); dbg.Debug(); return 0; } void Simulator::WriteW(int32_t addr, int value, Instruction* instr) { if (addr >= 0 && addr < 0x400) { // This has to be a NULL-dereference, drop into debugger. PrintF("Memory write to bad address: 0x%08x, pc=0x%08x\n", addr, reinterpret_cast<intptr_t>(instr)); MipsDebugger dbg(this); dbg.Debug(); } if ((addr & kPointerAlignmentMask) == 0) { intptr_t* ptr = reinterpret_cast<intptr_t*>(addr); *ptr = value; return; } PrintF("Unaligned write at 0x%08x, pc=0x%08" V8PRIxPTR "\n", addr, reinterpret_cast<intptr_t>(instr)); MipsDebugger dbg(this); dbg.Debug(); } double Simulator::ReadD(int32_t addr, Instruction* instr) { if ((addr & kDoubleAlignmentMask) == 0) { double* ptr = reinterpret_cast<double*>(addr); return *ptr; } PrintF("Unaligned (double) read at 0x%08x, pc=0x%08" V8PRIxPTR "\n", addr, reinterpret_cast<intptr_t>(instr)); OS::Abort(); return 0; } void Simulator::WriteD(int32_t addr, double value, Instruction* instr) { if ((addr & kDoubleAlignmentMask) == 0) { double* ptr = reinterpret_cast<double*>(addr); *ptr = value; return; } PrintF("Unaligned (double) write at 0x%08x, pc=0x%08" V8PRIxPTR "\n", addr, reinterpret_cast<intptr_t>(instr)); OS::Abort(); } uint16_t Simulator::ReadHU(int32_t addr, Instruction* instr) { if ((addr & 1) == 0) { uint16_t* ptr = reinterpret_cast<uint16_t*>(addr); return *ptr; } PrintF("Unaligned unsigned halfword read at 0x%08x, pc=0x%08" V8PRIxPTR "\n", addr, reinterpret_cast<intptr_t>(instr)); OS::Abort(); return 0; } int16_t Simulator::ReadH(int32_t addr, Instruction* instr) { if ((addr & 1) == 0) { int16_t* ptr = reinterpret_cast<int16_t*>(addr); return *ptr; } PrintF("Unaligned signed halfword read at 0x%08x, pc=0x%08" V8PRIxPTR "\n", addr, reinterpret_cast<intptr_t>(instr)); OS::Abort(); return 0; } void Simulator::WriteH(int32_t addr, uint16_t value, Instruction* instr) { if ((addr & 1) == 0) { uint16_t* ptr = reinterpret_cast<uint16_t*>(addr); *ptr = value; return; } PrintF("Unaligned unsigned halfword write at 0x%08x, pc=0x%08" V8PRIxPTR "\n", addr, reinterpret_cast<intptr_t>(instr)); OS::Abort(); } void Simulator::WriteH(int32_t addr, int16_t value, Instruction* instr) { if ((addr & 1) == 0) { int16_t* ptr = reinterpret_cast<int16_t*>(addr); *ptr = value; return; } PrintF("Unaligned halfword write at 0x%08x, pc=0x%08" V8PRIxPTR "\n", addr, reinterpret_cast<intptr_t>(instr)); OS::Abort(); } uint32_t Simulator::ReadBU(int32_t addr) { uint8_t* ptr = reinterpret_cast<uint8_t*>(addr); return *ptr & 0xff; } int32_t Simulator::ReadB(int32_t addr) { int8_t* ptr = reinterpret_cast<int8_t*>(addr); return *ptr; } void Simulator::WriteB(int32_t addr, uint8_t value) { uint8_t* ptr = reinterpret_cast<uint8_t*>(addr); *ptr = value; } void Simulator::WriteB(int32_t addr, int8_t value) { int8_t* ptr = reinterpret_cast<int8_t*>(addr); *ptr = value; } // Returns the limit of the stack area to enable checking for stack overflows. uintptr_t Simulator::StackLimit() const { // Leave a safety margin of 512 bytes to prevent overrunning the stack when // pushing values. return reinterpret_cast<uintptr_t>(stack_) + 512; } // Unsupported instructions use Format to print an error and stop execution. void Simulator::Format(Instruction* instr, const char* format) { PrintF("Simulator found unsupported instruction:\n 0x%08x: %s\n", reinterpret_cast<intptr_t>(instr), format); UNIMPLEMENTED_MIPS(); } // Calls into the V8 runtime are based on this very simple interface. // Note: To be able to return two values from some calls the code in runtime.cc // uses the ObjectPair which is essentially two 32-bit values stuffed into a // 64-bit value. With the code below we assume that all runtime calls return // 64 bits of result. If they don't, the v1 result register contains a bogus // value, which is fine because it is caller-saved. typedef int64_t (*SimulatorRuntimeCall)(int32_t arg0, int32_t arg1, int32_t arg2, int32_t arg3, int32_t arg4, int32_t arg5); typedef double (*SimulatorRuntimeFPCall)(int32_t arg0, int32_t arg1, int32_t arg2, int32_t arg3); // This signature supports direct call in to API function native callback // (refer to InvocationCallback in v8.h). typedef v8::Handle<v8::Value> (*SimulatorRuntimeDirectApiCall)(int32_t arg0); // This signature supports direct call to accessor getter callback. typedef v8::Handle<v8::Value> (*SimulatorRuntimeDirectGetterCall)(int32_t arg0, int32_t arg1); // Software interrupt instructions are used by the simulator to call into the // C-based V8 runtime. They are also used for debugging with simulator. void Simulator::SoftwareInterrupt(Instruction* instr) { // There are several instructions that could get us here, // the break_ instruction, or several variants of traps. All // Are "SPECIAL" class opcode, and are distinuished by function. int32_t func = instr->FunctionFieldRaw(); uint32_t code = (func == BREAK) ? instr->Bits(25, 6) : -1; // We first check if we met a call_rt_redirected. if (instr->InstructionBits() == rtCallRedirInstr) { Redirection* redirection = Redirection::FromSwiInstruction(instr); int32_t arg0 = get_register(a0); int32_t arg1 = get_register(a1); int32_t arg2 = get_register(a2); int32_t arg3 = get_register(a3); int32_t* stack_pointer = reinterpret_cast<int32_t*>(get_register(sp)); // Args 4 and 5 are on the stack after the reserved space for args 0..3. int32_t arg4 = stack_pointer[4]; int32_t arg5 = stack_pointer[5]; bool fp_call = (redirection->type() == ExternalReference::BUILTIN_FP_FP_CALL) || (redirection->type() == ExternalReference::BUILTIN_COMPARE_CALL) || (redirection->type() == ExternalReference::BUILTIN_FP_CALL) || (redirection->type() == ExternalReference::BUILTIN_FP_INT_CALL); if (!IsMipsSoftFloatABI) { // With the hard floating point calling convention, double // arguments are passed in FPU registers. Fetch the arguments // from there and call the builtin using soft floating point // convention. switch (redirection->type()) { case ExternalReference::BUILTIN_FP_FP_CALL: case ExternalReference::BUILTIN_COMPARE_CALL: arg0 = get_fpu_register(f12); arg1 = get_fpu_register(f13); arg2 = get_fpu_register(f14); arg3 = get_fpu_register(f15); break; case ExternalReference::BUILTIN_FP_CALL: arg0 = get_fpu_register(f12); arg1 = get_fpu_register(f13); break; case ExternalReference::BUILTIN_FP_INT_CALL: arg0 = get_fpu_register(f12); arg1 = get_fpu_register(f13); arg2 = get_register(a2); break; default: break; } } // This is dodgy but it works because the C entry stubs are never moved. // See comment in codegen-arm.cc and bug 1242173. int32_t saved_ra = get_register(ra); intptr_t external = reinterpret_cast<intptr_t>(redirection->external_function()); // Based on CpuFeatures::IsSupported(FPU), Mips will use either hardware // FPU, or gcc soft-float routines. Hardware FPU is simulated in this // simulator. Soft-float has additional abstraction of ExternalReference, // to support serialization. if (fp_call) { SimulatorRuntimeFPCall target = reinterpret_cast<SimulatorRuntimeFPCall>(external); if (::v8::internal::FLAG_trace_sim) { double dval0, dval1; int32_t ival; switch (redirection->type()) { case ExternalReference::BUILTIN_FP_FP_CALL: case ExternalReference::BUILTIN_COMPARE_CALL: GetFpArgs(&dval0, &dval1); PrintF("Call to host function at %p with args %f, %f", FUNCTION_ADDR(target), dval0, dval1); break; case ExternalReference::BUILTIN_FP_CALL: GetFpArgs(&dval0); PrintF("Call to host function at %p with arg %f", FUNCTION_ADDR(target), dval0); break; case ExternalReference::BUILTIN_FP_INT_CALL: GetFpArgs(&dval0, &ival); PrintF("Call to host function at %p with args %f, %d", FUNCTION_ADDR(target), dval0, ival); break; default: UNREACHABLE(); break; } } double result = target(arg0, arg1, arg2, arg3); if (redirection->type() != ExternalReference::BUILTIN_COMPARE_CALL) { SetFpResult(result); } else { int32_t gpreg_pair[2]; memcpy(&gpreg_pair[0], &result, 2 * sizeof(int32_t)); set_register(v0, gpreg_pair[0]); set_register(v1, gpreg_pair[1]); } } else if (redirection->type() == ExternalReference::DIRECT_API_CALL) { // See DirectCEntryStub::GenerateCall for explanation of register usage. SimulatorRuntimeDirectApiCall target = reinterpret_cast<SimulatorRuntimeDirectApiCall>(external); if (::v8::internal::FLAG_trace_sim) { PrintF("Call to host function at %p args %08x\n", FUNCTION_ADDR(target), arg1); } v8::Handle<v8::Value> result = target(arg1); *(reinterpret_cast<int*>(arg0)) = (int32_t) *result; set_register(v0, arg0); } else if (redirection->type() == ExternalReference::DIRECT_GETTER_CALL) { // See DirectCEntryStub::GenerateCall for explanation of register usage. SimulatorRuntimeDirectGetterCall target = reinterpret_cast<SimulatorRuntimeDirectGetterCall>(external); if (::v8::internal::FLAG_trace_sim) { PrintF("Call to host function at %p args %08x %08x\n", FUNCTION_ADDR(target), arg1, arg2); } v8::Handle<v8::Value> result = target(arg1, arg2); *(reinterpret_cast<int*>(arg0)) = (int32_t) *result; set_register(v0, arg0); } else { SimulatorRuntimeCall target = reinterpret_cast<SimulatorRuntimeCall>(external); if (::v8::internal::FLAG_trace_sim) { PrintF( "Call to host function at %p " "args %08x, %08x, %08x, %08x, %08x, %08x\n", FUNCTION_ADDR(target), arg0, arg1, arg2, arg3, arg4, arg5); } int64_t result = target(arg0, arg1, arg2, arg3, arg4, arg5); set_register(v0, static_cast<int32_t>(result)); set_register(v1, static_cast<int32_t>(result >> 32)); } if (::v8::internal::FLAG_trace_sim) { PrintF("Returned %08x : %08x\n", get_register(v1), get_register(v0)); } set_register(ra, saved_ra); set_pc(get_register(ra)); } else if (func == BREAK && code <= kMaxStopCode) { if (IsWatchpoint(code)) { PrintWatchpoint(code); } else { IncreaseStopCounter(code); HandleStop(code, instr); } } else { // All remaining break_ codes, and all traps are handled here. MipsDebugger dbg(this); dbg.Debug(); } } // Stop helper functions. bool Simulator::IsWatchpoint(uint32_t code) { return (code <= kMaxWatchpointCode); } void Simulator::PrintWatchpoint(uint32_t code) { MipsDebugger dbg(this); ++break_count_; PrintF("\n---- break %d marker: %3d (instr count: %8d) ----------" "----------------------------------", code, break_count_, icount_); dbg.PrintAllRegs(); // Print registers and continue running. } void Simulator::HandleStop(uint32_t code, Instruction* instr) { // Stop if it is enabled, otherwise go on jumping over the stop // and the message address. if (IsEnabledStop(code)) { MipsDebugger dbg(this); dbg.Stop(instr); } else { set_pc(get_pc() + 2 * Instruction::kInstrSize); } } bool Simulator::IsStopInstruction(Instruction* instr) { int32_t func = instr->FunctionFieldRaw(); uint32_t code = static_cast<uint32_t>(instr->Bits(25, 6)); return (func == BREAK) && code > kMaxWatchpointCode && code <= kMaxStopCode; } bool Simulator::IsEnabledStop(uint32_t code) { ASSERT(code <= kMaxStopCode); ASSERT(code > kMaxWatchpointCode); return !(watched_stops[code].count & kStopDisabledBit); } void Simulator::EnableStop(uint32_t code) { if (!IsEnabledStop(code)) { watched_stops[code].count &= ~kStopDisabledBit; } } void Simulator::DisableStop(uint32_t code) { if (IsEnabledStop(code)) { watched_stops[code].count |= kStopDisabledBit; } } void Simulator::IncreaseStopCounter(uint32_t code) { ASSERT(code <= kMaxStopCode); if ((watched_stops[code].count & ~(1 << 31)) == 0x7fffffff) { PrintF("Stop counter for code %i has overflowed.\n" "Enabling this code and reseting the counter to 0.\n", code); watched_stops[code].count = 0; EnableStop(code); } else { watched_stops[code].count++; } } // Print a stop status. void Simulator::PrintStopInfo(uint32_t code) { if (code <= kMaxWatchpointCode) { PrintF("That is a watchpoint, not a stop.\n"); return; } else if (code > kMaxStopCode) { PrintF("Code too large, only %u stops can be used\n", kMaxStopCode + 1); return; } const char* state = IsEnabledStop(code) ? "Enabled" : "Disabled"; int32_t count = watched_stops[code].count & ~kStopDisabledBit; // Don't print the state of unused breakpoints. if (count != 0) { if (watched_stops[code].desc) { PrintF("stop %i - 0x%x: \t%s, \tcounter = %i, \t%s\n", code, code, state, count, watched_stops[code].desc); } else { PrintF("stop %i - 0x%x: \t%s, \tcounter = %i\n", code, code, state, count); } } } void Simulator::SignalExceptions() { for (int i = 1; i < kNumExceptions; i++) { if (exceptions[i] != 0) { V8_Fatal(__FILE__, __LINE__, "Error: Exception %i raised.", i); } } } // Handle execution based on instruction types. void Simulator::ConfigureTypeRegister(Instruction* instr, int32_t& alu_out, int64_t& i64hilo, uint64_t& u64hilo, int32_t& next_pc, bool& do_interrupt) { // Every local variable declared here needs to be const. // This is to make sure that changed values are sent back to // DecodeTypeRegister correctly. // Instruction fields. const Opcode op = instr->OpcodeFieldRaw(); const int32_t rs_reg = instr->RsValue(); const int32_t rs = get_register(rs_reg); const uint32_t rs_u = static_cast<uint32_t>(rs); const int32_t rt_reg = instr->RtValue(); const int32_t rt = get_register(rt_reg); const uint32_t rt_u = static_cast<uint32_t>(rt); const int32_t rd_reg = instr->RdValue(); const uint32_t sa = instr->SaValue(); const int32_t fs_reg = instr->FsValue(); // ---------- Configuration. switch (op) { case COP1: // Coprocessor instructions. switch (instr->RsFieldRaw()) { case BC1: // Handled in DecodeTypeImmed, should never come here. UNREACHABLE(); break; case CFC1: // At the moment only FCSR is supported. ASSERT(fs_reg == kFCSRRegister); alu_out = FCSR_; break; case MFC1: alu_out = get_fpu_register(fs_reg); break; case MFHC1: UNIMPLEMENTED_MIPS(); break; case CTC1: case MTC1: case MTHC1: // Do the store in the execution step. break; case S: case D: case W: case L: case PS: // Do everything in the execution step. break; default: UNIMPLEMENTED_MIPS(); }; break; case SPECIAL: switch (instr->FunctionFieldRaw()) { case JR: case JALR: next_pc = get_register(instr->RsValue()); break; case SLL: alu_out = rt << sa; break; case SRL: if (rs_reg == 0) { // Regular logical right shift of a word by a fixed number of // bits instruction. RS field is always equal to 0. alu_out = rt_u >> sa; } else { // Logical right-rotate of a word by a fixed number of bits. This // is special case of SRL instruction, added in MIPS32 Release 2. // RS field is equal to 00001. alu_out = (rt_u >> sa) | (rt_u << (32 - sa)); } break; case SRA: alu_out = rt >> sa; break; case SLLV: alu_out = rt << rs; break; case SRLV: if (sa == 0) { // Regular logical right-shift of a word by a variable number of // bits instruction. SA field is always equal to 0. alu_out = rt_u >> rs; } else { // Logical right-rotate of a word by a variable number of bits. // This is special case od SRLV instruction, added in MIPS32 // Release 2. SA field is equal to 00001. alu_out = (rt_u >> rs_u) | (rt_u << (32 - rs_u)); } break; case SRAV: alu_out = rt >> rs; break; case MFHI: alu_out = get_register(HI); break; case MFLO: alu_out = get_register(LO); break; case MULT: i64hilo = static_cast<int64_t>(rs) * static_cast<int64_t>(rt); break; case MULTU: u64hilo = static_cast<uint64_t>(rs_u) * static_cast<uint64_t>(rt_u); break; case ADD: if (HaveSameSign(rs, rt)) { if (rs > 0) { exceptions[kIntegerOverflow] = rs > (Registers::kMaxValue - rt); } else if (rs < 0) { exceptions[kIntegerUnderflow] = rs < (Registers::kMinValue - rt); } } alu_out = rs + rt; break; case ADDU: alu_out = rs + rt; break; case SUB: if (!HaveSameSign(rs, rt)) { if (rs > 0) { exceptions[kIntegerOverflow] = rs > (Registers::kMaxValue + rt); } else if (rs < 0) { exceptions[kIntegerUnderflow] = rs < (Registers::kMinValue + rt); } } alu_out = rs - rt; break; case SUBU: alu_out = rs - rt; break; case AND: alu_out = rs & rt; break; case OR: alu_out = rs | rt; break; case XOR: alu_out = rs ^ rt; break; case NOR: alu_out = ~(rs | rt); break; case SLT: alu_out = rs < rt ? 1 : 0; break; case SLTU: alu_out = rs_u < rt_u ? 1 : 0; break; // Break and trap instructions. case BREAK: do_interrupt = true; break; case TGE: do_interrupt = rs >= rt; break; case TGEU: do_interrupt = rs_u >= rt_u; break; case TLT: do_interrupt = rs < rt; break; case TLTU: do_interrupt = rs_u < rt_u; break; case TEQ: do_interrupt = rs == rt; break; case TNE: do_interrupt = rs != rt; break; case MOVN: case MOVZ: case MOVCI: // No action taken on decode. break; case DIV: case DIVU: // div and divu never raise exceptions. break; default: UNREACHABLE(); }; break; case SPECIAL2: switch (instr->FunctionFieldRaw()) { case MUL: alu_out = rs_u * rt_u; // Only the lower 32 bits are kept. break; case CLZ: alu_out = __builtin_clz(rs_u); break; default: UNREACHABLE(); }; break; case SPECIAL3: switch (instr->FunctionFieldRaw()) { case INS: { // Mips32r2 instruction. // Interpret rd field as 5-bit msb of insert. uint16_t msb = rd_reg; // Interpret sa field as 5-bit lsb of insert. uint16_t lsb = sa; uint16_t size = msb - lsb + 1; uint32_t mask = (1 << size) - 1; alu_out = (rt_u & ~(mask << lsb)) | ((rs_u & mask) << lsb); break; } case EXT: { // Mips32r2 instruction. // Interpret rd field as 5-bit msb of extract. uint16_t msb = rd_reg; // Interpret sa field as 5-bit lsb of extract. uint16_t lsb = sa; uint16_t size = msb + 1; uint32_t mask = (1 << size) - 1; alu_out = (rs_u & (mask << lsb)) >> lsb; break; } default: UNREACHABLE(); }; break; default: UNREACHABLE(); }; } void Simulator::DecodeTypeRegister(Instruction* instr) { // Instruction fields. const Opcode op = instr->OpcodeFieldRaw(); const int32_t rs_reg = instr->RsValue(); const int32_t rs = get_register(rs_reg); const uint32_t rs_u = static_cast<uint32_t>(rs); const int32_t rt_reg = instr->RtValue(); const int32_t rt = get_register(rt_reg); const uint32_t rt_u = static_cast<uint32_t>(rt); const int32_t rd_reg = instr->RdValue(); const int32_t fs_reg = instr->FsValue(); const int32_t ft_reg = instr->FtValue(); const int32_t fd_reg = instr->FdValue(); int64_t i64hilo = 0; uint64_t u64hilo = 0; // ALU output. // It should not be used as is. Instructions using it should always // initialize it first. int32_t alu_out = 0x12345678; // For break and trap instructions. bool do_interrupt = false; // For jr and jalr. // Get current pc. int32_t current_pc = get_pc(); // Next pc int32_t next_pc = 0; // Setup the variables if needed before executing the instruction. ConfigureTypeRegister(instr, alu_out, i64hilo, u64hilo, next_pc, do_interrupt); // ---------- Raise exceptions triggered. SignalExceptions(); // ---------- Execution. switch (op) { case COP1: switch (instr->RsFieldRaw()) { case BC1: // Branch on coprocessor condition. UNREACHABLE(); break; case CFC1: set_register(rt_reg, alu_out); case MFC1: set_register(rt_reg, alu_out); break; case MFHC1: UNIMPLEMENTED_MIPS(); break; case CTC1: // At the moment only FCSR is supported. ASSERT(fs_reg == kFCSRRegister); FCSR_ = registers_[rt_reg]; break; case MTC1: FPUregisters_[fs_reg] = registers_[rt_reg]; break; case MTHC1: UNIMPLEMENTED_MIPS(); break; case S: float f; switch (instr->FunctionFieldRaw()) { case CVT_D_S: f = get_fpu_register_float(fs_reg); set_fpu_register_double(fd_reg, static_cast<double>(f)); break; case CVT_W_S: case CVT_L_S: case TRUNC_W_S: case TRUNC_L_S: case ROUND_W_S: case ROUND_L_S: case FLOOR_W_S: case FLOOR_L_S: case CEIL_W_S: case CEIL_L_S: case CVT_PS_S: UNIMPLEMENTED_MIPS(); break; default: UNREACHABLE(); } break; case D: double ft, fs; uint32_t cc, fcsr_cc; int64_t i64; fs = get_fpu_register_double(fs_reg); ft = get_fpu_register_double(ft_reg); cc = instr->FCccValue(); fcsr_cc = get_fcsr_condition_bit(cc); switch (instr->FunctionFieldRaw()) { case ADD_D: set_fpu_register_double(fd_reg, fs + ft); break; case SUB_D: set_fpu_register_double(fd_reg, fs - ft); break; case MUL_D: set_fpu_register_double(fd_reg, fs * ft); break; case DIV_D: set_fpu_register_double(fd_reg, fs / ft); break; case ABS_D: set_fpu_register_double(fd_reg, fs < 0 ? -fs : fs); break; case MOV_D: set_fpu_register_double(fd_reg, fs); break; case NEG_D: set_fpu_register_double(fd_reg, -fs); break; case SQRT_D: set_fpu_register_double(fd_reg, sqrt(fs)); break; case C_UN_D: set_fcsr_bit(fcsr_cc, isnan(fs) || isnan(ft)); break; case C_EQ_D: set_fcsr_bit(fcsr_cc, (fs == ft)); break; case C_UEQ_D: set_fcsr_bit(fcsr_cc, (fs == ft) || (isnan(fs) || isnan(ft))); break; case C_OLT_D: set_fcsr_bit(fcsr_cc, (fs < ft)); break; case C_ULT_D: set_fcsr_bit(fcsr_cc, (fs < ft) || (isnan(fs) || isnan(ft))); break; case C_OLE_D: set_fcsr_bit(fcsr_cc, (fs <= ft)); break; case C_ULE_D: set_fcsr_bit(fcsr_cc, (fs <= ft) || (isnan(fs) || isnan(ft))); break; case CVT_W_D: // Convert double to word. // Rounding modes are not yet supported. ASSERT((FCSR_ & 3) == 0); // In rounding mode 0 it should behave like ROUND. case ROUND_W_D: // Round double to word. { double rounded = fs > 0 ? floor(fs + 0.5) : ceil(fs - 0.5); int32_t result = static_cast<int32_t>(rounded); set_fpu_register(fd_reg, result); if (set_fcsr_round_error(fs, rounded)) { set_fpu_register(fd_reg, kFPUInvalidResult); } } break; case TRUNC_W_D: // Truncate double to word (round towards 0). { double rounded = trunc(fs); int32_t result = static_cast<int32_t>(rounded); set_fpu_register(fd_reg, result); if (set_fcsr_round_error(fs, rounded)) { set_fpu_register(fd_reg, kFPUInvalidResult); } } break; case FLOOR_W_D: // Round double to word towards negative infinity. { double rounded = floor(fs); int32_t result = static_cast<int32_t>(rounded); set_fpu_register(fd_reg, result); if (set_fcsr_round_error(fs, rounded)) { set_fpu_register(fd_reg, kFPUInvalidResult); } } break; case CEIL_W_D: // Round double to word towards positive infinity. { double rounded = ceil(fs); int32_t result = static_cast<int32_t>(rounded); set_fpu_register(fd_reg, result); if (set_fcsr_round_error(fs, rounded)) { set_fpu_register(fd_reg, kFPUInvalidResult); } } break; case CVT_S_D: // Convert double to float (single). set_fpu_register_float(fd_reg, static_cast<float>(fs)); break; case CVT_L_D: { // Mips32r2: Truncate double to 64-bit long-word. double rounded = trunc(fs); i64 = static_cast<int64_t>(rounded); set_fpu_register(fd_reg, i64 & 0xffffffff); set_fpu_register(fd_reg + 1, i64 >> 32); break; } case TRUNC_L_D: { // Mips32r2 instruction. double rounded = trunc(fs); i64 = static_cast<int64_t>(rounded); set_fpu_register(fd_reg, i64 & 0xffffffff); set_fpu_register(fd_reg + 1, i64 >> 32); break; } case ROUND_L_D: { // Mips32r2 instruction. double rounded = fs > 0 ? floor(fs + 0.5) : ceil(fs - 0.5); i64 = static_cast<int64_t>(rounded); set_fpu_register(fd_reg, i64 & 0xffffffff); set_fpu_register(fd_reg + 1, i64 >> 32); break; } case FLOOR_L_D: // Mips32r2 instruction. i64 = static_cast<int64_t>(floor(fs)); set_fpu_register(fd_reg, i64 & 0xffffffff); set_fpu_register(fd_reg + 1, i64 >> 32); break; case CEIL_L_D: // Mips32r2 instruction. i64 = static_cast<int64_t>(ceil(fs)); set_fpu_register(fd_reg, i64 & 0xffffffff); set_fpu_register(fd_reg + 1, i64 >> 32); break; case C_F_D: UNIMPLEMENTED_MIPS(); break; default: UNREACHABLE(); } break; case W: switch (instr->FunctionFieldRaw()) { case CVT_S_W: // Convert word to float (single). alu_out = get_fpu_register(fs_reg); set_fpu_register_float(fd_reg, static_cast<float>(alu_out)); break; case CVT_D_W: // Convert word to double. alu_out = get_fpu_register(fs_reg); set_fpu_register_double(fd_reg, static_cast<double>(alu_out)); break; default: UNREACHABLE(); }; break; case L: switch (instr->FunctionFieldRaw()) { case CVT_D_L: // Mips32r2 instruction. // Watch the signs here, we want 2 32-bit vals // to make a sign-64. i64 = (uint32_t) get_fpu_register(fs_reg); i64 |= ((int64_t) get_fpu_register(fs_reg + 1) << 32); set_fpu_register_double(fd_reg, static_cast<double>(i64)); break; case CVT_S_L: UNIMPLEMENTED_MIPS(); break; default: UNREACHABLE(); } break; case PS: break; default: UNREACHABLE(); }; break; case SPECIAL: switch (instr->FunctionFieldRaw()) { case JR: { Instruction* branch_delay_instr = reinterpret_cast<Instruction*>( current_pc+Instruction::kInstrSize); BranchDelayInstructionDecode(branch_delay_instr); set_pc(next_pc); pc_modified_ = true; break; } case JALR: { Instruction* branch_delay_instr = reinterpret_cast<Instruction*>( current_pc+Instruction::kInstrSize); BranchDelayInstructionDecode(branch_delay_instr); set_register(31, current_pc + 2 * Instruction::kInstrSize); set_pc(next_pc); pc_modified_ = true; break; } // Instructions using HI and LO registers. case MULT: set_register(LO, static_cast<int32_t>(i64hilo & 0xffffffff)); set_register(HI, static_cast<int32_t>(i64hilo >> 32)); break; case MULTU: set_register(LO, static_cast<int32_t>(u64hilo & 0xffffffff)); set_register(HI, static_cast<int32_t>(u64hilo >> 32)); break; case DIV: // Divide by zero was not checked in the configuration step - div and // divu do not raise exceptions. On division by 0, the result will // be UNPREDICTABLE. if (rt != 0) { set_register(LO, rs / rt); set_register(HI, rs % rt); } break; case DIVU: if (rt_u != 0) { set_register(LO, rs_u / rt_u); set_register(HI, rs_u % rt_u); } break; // Break and trap instructions. case BREAK: case TGE: case TGEU: case TLT: case TLTU: case TEQ: case TNE: if (do_interrupt) { SoftwareInterrupt(instr); } break; // Conditional moves. case MOVN: if (rt) set_register(rd_reg, rs); break; case MOVCI: { uint32_t cc = instr->FBccValue(); uint32_t fcsr_cc = get_fcsr_condition_bit(cc); if (instr->Bit(16)) { // Read Tf bit. if (test_fcsr_bit(fcsr_cc)) set_register(rd_reg, rs); } else { if (!test_fcsr_bit(fcsr_cc)) set_register(rd_reg, rs); } break; } case MOVZ: if (!rt) set_register(rd_reg, rs); break; default: // For other special opcodes we do the default operation. set_register(rd_reg, alu_out); }; break; case SPECIAL2: switch (instr->FunctionFieldRaw()) { case MUL: set_register(rd_reg, alu_out); // HI and LO are UNPREDICTABLE after the operation. set_register(LO, Unpredictable); set_register(HI, Unpredictable); break; default: // For other special2 opcodes we do the default operation. set_register(rd_reg, alu_out); } break; case SPECIAL3: switch (instr->FunctionFieldRaw()) { case INS: // Ins instr leaves result in Rt, rather than Rd. set_register(rt_reg, alu_out); break; case EXT: // Ext instr leaves result in Rt, rather than Rd. set_register(rt_reg, alu_out); break; default: UNREACHABLE(); }; break; // Unimplemented opcodes raised an error in the configuration step before, // so we can use the default here to set the destination register in common // cases. default: set_register(rd_reg, alu_out); }; } // Type 2: instructions using a 16 bytes immediate. (eg: addi, beq). void Simulator::DecodeTypeImmediate(Instruction* instr) { // Instruction fields. Opcode op = instr->OpcodeFieldRaw(); int32_t rs = get_register(instr->RsValue()); uint32_t rs_u = static_cast<uint32_t>(rs); int32_t rt_reg = instr->RtValue(); // Destination register. int32_t rt = get_register(rt_reg); int16_t imm16 = instr->Imm16Value(); int32_t ft_reg = instr->FtValue(); // Destination register. // Zero extended immediate. uint32_t oe_imm16 = 0xffff & imm16; // Sign extended immediate. int32_t se_imm16 = imm16; // Get current pc. int32_t current_pc = get_pc(); // Next pc. int32_t next_pc = bad_ra; // Used for conditional branch instructions. bool do_branch = false; bool execute_branch_delay_instruction = false; // Used for arithmetic instructions. int32_t alu_out = 0; // Floating point. double fp_out = 0.0; uint32_t cc, cc_value, fcsr_cc; // Used for memory instructions. int32_t addr = 0x0; // Value to be written in memory. uint32_t mem_value = 0x0; // ---------- Configuration (and execution for REGIMM). switch (op) { // ------------- COP1. Coprocessor instructions. case COP1: switch (instr->RsFieldRaw()) { case BC1: // Branch on coprocessor condition. cc = instr->FBccValue(); fcsr_cc = get_fcsr_condition_bit(cc); cc_value = test_fcsr_bit(fcsr_cc); do_branch = (instr->FBtrueValue()) ? cc_value : !cc_value; execute_branch_delay_instruction = true; // Set next_pc. if (do_branch) { next_pc = current_pc + (imm16 << 2) + Instruction::kInstrSize; } else { next_pc = current_pc + kBranchReturnOffset; } break; default: UNREACHABLE(); }; break; // ------------- REGIMM class. case REGIMM: switch (instr->RtFieldRaw()) { case BLTZ: do_branch = (rs < 0); break; case BLTZAL: do_branch = rs < 0; break; case BGEZ: do_branch = rs >= 0; break; case BGEZAL: do_branch = rs >= 0; break; default: UNREACHABLE(); }; switch (instr->RtFieldRaw()) { case BLTZ: case BLTZAL: case BGEZ: case BGEZAL: // Branch instructions common part. execute_branch_delay_instruction = true; // Set next_pc. if (do_branch) { next_pc = current_pc + (imm16 << 2) + Instruction::kInstrSize; if (instr->IsLinkingInstruction()) { set_register(31, current_pc + kBranchReturnOffset); } } else { next_pc = current_pc + kBranchReturnOffset; } default: break; }; break; // case REGIMM. // ------------- Branch instructions. // When comparing to zero, the encoding of rt field is always 0, so we don't // need to replace rt with zero. case BEQ: do_branch = (rs == rt); break; case BNE: do_branch = rs != rt; break; case BLEZ: do_branch = rs <= 0; break; case BGTZ: do_branch = rs > 0; break; // ------------- Arithmetic instructions. case ADDI: if (HaveSameSign(rs, se_imm16)) { if (rs > 0) { exceptions[kIntegerOverflow] = rs > (Registers::kMaxValue - se_imm16); } else if (rs < 0) { exceptions[kIntegerUnderflow] = rs < (Registers::kMinValue - se_imm16); } } alu_out = rs + se_imm16; break; case ADDIU: alu_out = rs + se_imm16; break; case SLTI: alu_out = (rs < se_imm16) ? 1 : 0; break; case SLTIU: alu_out = (rs_u < static_cast<uint32_t>(se_imm16)) ? 1 : 0; break; case ANDI: alu_out = rs & oe_imm16; break; case ORI: alu_out = rs | oe_imm16; break; case XORI: alu_out = rs ^ oe_imm16; break; case LUI: alu_out = (oe_imm16 << 16); break; // ------------- Memory instructions. case LB: addr = rs + se_imm16; alu_out = ReadB(addr); break; case LH: addr = rs + se_imm16; alu_out = ReadH(addr, instr); break; case LWL: { // al_offset is offset of the effective address within an aligned word. uint8_t al_offset = (rs + se_imm16) & kPointerAlignmentMask; uint8_t byte_shift = kPointerAlignmentMask - al_offset; uint32_t mask = (1 << byte_shift * 8) - 1; addr = rs + se_imm16 - al_offset; alu_out = ReadW(addr, instr); alu_out <<= byte_shift * 8; alu_out |= rt & mask; break; } case LW: addr = rs + se_imm16; alu_out = ReadW(addr, instr); break; case LBU: addr = rs + se_imm16; alu_out = ReadBU(addr); break; case LHU: addr = rs + se_imm16; alu_out = ReadHU(addr, instr); break; case LWR: { // al_offset is offset of the effective address within an aligned word. uint8_t al_offset = (rs + se_imm16) & kPointerAlignmentMask; uint8_t byte_shift = kPointerAlignmentMask - al_offset; uint32_t mask = al_offset ? (~0 << (byte_shift + 1) * 8) : 0; addr = rs + se_imm16 - al_offset; alu_out = ReadW(addr, instr); alu_out = static_cast<uint32_t> (alu_out) >> al_offset * 8; alu_out |= rt & mask; break; } case SB: addr = rs + se_imm16; break; case SH: addr = rs + se_imm16; break; case SWL: { uint8_t al_offset = (rs + se_imm16) & kPointerAlignmentMask; uint8_t byte_shift = kPointerAlignmentMask - al_offset; uint32_t mask = byte_shift ? (~0 << (al_offset + 1) * 8) : 0; addr = rs + se_imm16 - al_offset; mem_value = ReadW(addr, instr) & mask; mem_value |= static_cast<uint32_t>(rt) >> byte_shift * 8; break; } case SW: addr = rs + se_imm16; break; case SWR: { uint8_t al_offset = (rs + se_imm16) & kPointerAlignmentMask; uint32_t mask = (1 << al_offset * 8) - 1; addr = rs + se_imm16 - al_offset; mem_value = ReadW(addr, instr); mem_value = (rt << al_offset * 8) | (mem_value & mask); break; } case LWC1: addr = rs + se_imm16; alu_out = ReadW(addr, instr); break; case LDC1: addr = rs + se_imm16; fp_out = ReadD(addr, instr); break; case SWC1: case SDC1: addr = rs + se_imm16; break; default: UNREACHABLE(); }; // ---------- Raise exceptions triggered. SignalExceptions(); // ---------- Execution. switch (op) { // ------------- Branch instructions. case BEQ: case BNE: case BLEZ: case BGTZ: // Branch instructions common part. execute_branch_delay_instruction = true; // Set next_pc. if (do_branch) { next_pc = current_pc + (imm16 << 2) + Instruction::kInstrSize; if (instr->IsLinkingInstruction()) { set_register(31, current_pc + 2* Instruction::kInstrSize); } } else { next_pc = current_pc + 2 * Instruction::kInstrSize; } break; // ------------- Arithmetic instructions. case ADDI: case ADDIU: case SLTI: case SLTIU: case ANDI: case ORI: case XORI: case LUI: set_register(rt_reg, alu_out); break; // ------------- Memory instructions. case LB: case LH: case LWL: case LW: case LBU: case LHU: case LWR: set_register(rt_reg, alu_out); break; case SB: WriteB(addr, static_cast<int8_t>(rt)); break; case SH: WriteH(addr, static_cast<uint16_t>(rt), instr); break; case SWL: WriteW(addr, mem_value, instr); break; case SW: WriteW(addr, rt, instr); break; case SWR: WriteW(addr, mem_value, instr); break; case LWC1: set_fpu_register(ft_reg, alu_out); break; case LDC1: set_fpu_register_double(ft_reg, fp_out); break; case SWC1: addr = rs + se_imm16; WriteW(addr, get_fpu_register(ft_reg), instr); break; case SDC1: addr = rs + se_imm16; WriteD(addr, get_fpu_register_double(ft_reg), instr); break; default: break; }; if (execute_branch_delay_instruction) { // Execute branch delay slot // We don't check for end_sim_pc. First it should not be met as the current // pc is valid. Secondly a jump should always execute its branch delay slot. Instruction* branch_delay_instr = reinterpret_cast<Instruction*>(current_pc+Instruction::kInstrSize); BranchDelayInstructionDecode(branch_delay_instr); } // If needed update pc after the branch delay execution. if (next_pc != bad_ra) { set_pc(next_pc); } } // Type 3: instructions using a 26 bytes immediate. (eg: j, jal). void Simulator::DecodeTypeJump(Instruction* instr) { // Get current pc. int32_t current_pc = get_pc(); // Get unchanged bits of pc. int32_t pc_high_bits = current_pc & 0xf0000000; // Next pc. int32_t next_pc = pc_high_bits | (instr->Imm26Value() << 2); // Execute branch delay slot. // We don't check for end_sim_pc. First it should not be met as the current pc // is valid. Secondly a jump should always execute its branch delay slot. Instruction* branch_delay_instr = reinterpret_cast<Instruction*>(current_pc + Instruction::kInstrSize); BranchDelayInstructionDecode(branch_delay_instr); // Update pc and ra if necessary. // Do this after the branch delay execution. if (instr->IsLinkingInstruction()) { set_register(31, current_pc + 2 * Instruction::kInstrSize); } set_pc(next_pc); pc_modified_ = true; } // Executes the current instruction. void Simulator::InstructionDecode(Instruction* instr) { if (v8::internal::FLAG_check_icache) { CheckICache(isolate_->simulator_i_cache(), instr); } pc_modified_ = false; if (::v8::internal::FLAG_trace_sim) { disasm::NameConverter converter; disasm::Disassembler dasm(converter); // Use a reasonably large buffer. v8::internal::EmbeddedVector<char, 256> buffer; dasm.InstructionDecode(buffer, reinterpret_cast<byte*>(instr)); PrintF(" 0x%08x %s\n", reinterpret_cast<intptr_t>(instr), buffer.start()); } switch (instr->InstructionType()) { case Instruction::kRegisterType: DecodeTypeRegister(instr); break; case Instruction::kImmediateType: DecodeTypeImmediate(instr); break; case Instruction::kJumpType: DecodeTypeJump(instr); break; default: UNSUPPORTED(); } if (!pc_modified_) { set_register(pc, reinterpret_cast<int32_t>(instr) + Instruction::kInstrSize); } } void Simulator::Execute() { // Get the PC to simulate. Cannot use the accessor here as we need the // raw PC value and not the one used as input to arithmetic instructions. int program_counter = get_pc(); if (::v8::internal::FLAG_stop_sim_at == 0) { // Fast version of the dispatch loop without checking whether the simulator // should be stopping at a particular executed instruction. while (program_counter != end_sim_pc) { Instruction* instr = reinterpret_cast<Instruction*>(program_counter); icount_++; InstructionDecode(instr); program_counter = get_pc(); } } else { // FLAG_stop_sim_at is at the non-default value. Stop in the debugger when // we reach the particular instuction count. while (program_counter != end_sim_pc) { Instruction* instr = reinterpret_cast<Instruction*>(program_counter); icount_++; if (icount_ == ::v8::internal::FLAG_stop_sim_at) { MipsDebugger dbg(this); dbg.Debug(); } else { InstructionDecode(instr); } program_counter = get_pc(); } } } int32_t Simulator::Call(byte* entry, int argument_count, ...) { va_list parameters; va_start(parameters, argument_count); // Setup arguments. // First four arguments passed in registers. ASSERT(argument_count >= 4); set_register(a0, va_arg(parameters, int32_t)); set_register(a1, va_arg(parameters, int32_t)); set_register(a2, va_arg(parameters, int32_t)); set_register(a3, va_arg(parameters, int32_t)); // Remaining arguments passed on stack. int original_stack = get_register(sp); // Compute position of stack on entry to generated code. int entry_stack = (original_stack - (argument_count - 4) * sizeof(int32_t) - kCArgsSlotsSize); if (OS::ActivationFrameAlignment() != 0) { entry_stack &= -OS::ActivationFrameAlignment(); } // Store remaining arguments on stack, from low to high memory. intptr_t* stack_argument = reinterpret_cast<intptr_t*>(entry_stack); for (int i = 4; i < argument_count; i++) { stack_argument[i - 4 + kCArgSlotCount] = va_arg(parameters, int32_t); } va_end(parameters); set_register(sp, entry_stack); // Prepare to execute the code at entry. set_register(pc, reinterpret_cast<int32_t>(entry)); // Put down marker for end of simulation. The simulator will stop simulation // when the PC reaches this value. By saving the "end simulation" value into // the LR the simulation stops when returning to this call point. set_register(ra, end_sim_pc); // Remember the values of callee-saved registers. // The code below assumes that r9 is not used as sb (static base) in // simulator code and therefore is regarded as a callee-saved register. int32_t s0_val = get_register(s0); int32_t s1_val = get_register(s1); int32_t s2_val = get_register(s2); int32_t s3_val = get_register(s3); int32_t s4_val = get_register(s4); int32_t s5_val = get_register(s5); int32_t s6_val = get_register(s6); int32_t s7_val = get_register(s7); int32_t gp_val = get_register(gp); int32_t sp_val = get_register(sp); int32_t fp_val = get_register(fp); // Setup the callee-saved registers with a known value. To be able to check // that they are preserved properly across JS execution. int32_t callee_saved_value = icount_; set_register(s0, callee_saved_value); set_register(s1, callee_saved_value); set_register(s2, callee_saved_value); set_register(s3, callee_saved_value); set_register(s4, callee_saved_value); set_register(s5, callee_saved_value); set_register(s6, callee_saved_value); set_register(s7, callee_saved_value); set_register(gp, callee_saved_value); set_register(fp, callee_saved_value); // Start the simulation. Execute(); // Check that the callee-saved registers have been preserved. CHECK_EQ(callee_saved_value, get_register(s0)); CHECK_EQ(callee_saved_value, get_register(s1)); CHECK_EQ(callee_saved_value, get_register(s2)); CHECK_EQ(callee_saved_value, get_register(s3)); CHECK_EQ(callee_saved_value, get_register(s4)); CHECK_EQ(callee_saved_value, get_register(s5)); CHECK_EQ(callee_saved_value, get_register(s6)); CHECK_EQ(callee_saved_value, get_register(s7)); CHECK_EQ(callee_saved_value, get_register(gp)); CHECK_EQ(callee_saved_value, get_register(fp)); // Restore callee-saved registers with the original value. set_register(s0, s0_val); set_register(s1, s1_val); set_register(s2, s2_val); set_register(s3, s3_val); set_register(s4, s4_val); set_register(s5, s5_val); set_register(s6, s6_val); set_register(s7, s7_val); set_register(gp, gp_val); set_register(sp, sp_val); set_register(fp, fp_val); // Pop stack passed arguments. CHECK_EQ(entry_stack, get_register(sp)); set_register(sp, original_stack); int32_t result = get_register(v0); return result; } uintptr_t Simulator::PushAddress(uintptr_t address) { int new_sp = get_register(sp) - sizeof(uintptr_t); uintptr_t* stack_slot = reinterpret_cast<uintptr_t*>(new_sp); *stack_slot = address; set_register(sp, new_sp); return new_sp; } uintptr_t Simulator::PopAddress() { int current_sp = get_register(sp); uintptr_t* stack_slot = reinterpret_cast<uintptr_t*>(current_sp); uintptr_t address = *stack_slot; set_register(sp, current_sp + sizeof(uintptr_t)); return address; } #undef UNSUPPORTED } } // namespace v8::internal #endif // USE_SIMULATOR #endif // V8_TARGET_ARCH_MIPS
#include "leetcode.hpp" /* 1625. 执行操作后字典序最小的字符串 给你一个字符串 s 以及两个整数 a 和 b 。 其中,字符串 s 的长度为偶数,且仅由数字 0 到 9 组成。 你可以在 s 上按任意顺序多次执行下面两个操作之一: 累加: 将 a 加到 s 中所有下标为奇数的元素上(下标从 0 开始)。 数字一旦超过 9 就会变成 0,如此循环往复。 例如,s = "3456" 且 a = 5,则执行此操作后 s 变成 "3951"。 轮转: 将 s 向右轮转 b 位。 例如,s = "3456" 且 b = 1,则执行此操作后 s 变成 "6345"。 请你返回在 s 上执行上述操作任意次后可以得到的 字典序最小 的字符串。 如果两个字符串长度相同,那么字符串 a 字典序比字符串 b 小可以这样定义:在 a 和 b 出现不同的第一个位置上,字符串 a 中的字符出现在字母表中的时间早于 b 中的对应字符。例如,"0158” 字典序比 "0190" 小,因为不同的第一个位置是在第三个字符,显然 '5' 出现在 '9' 之前。 示例 1: 输入:s = "5525", a = 9, b = 2 输出:"2050" 解释:执行操作如下: 初态:"5525" 轮转:"2555" 累加:"2454" 累加:"2353" 轮转:"5323" 累加:"5222" 累加:"5121" 轮转:"2151" 累加:"2050"​​​​​​​​​​​​ 无法获得字典序小于 "2050" 的字符串。 示例 2: 输入:s = "74", a = 5, b = 1 输出:"24" 解释:执行操作如下: 初态:"74" 轮转:"47" 累加:"42" 轮转:"24"​​​​​​​​​​​​ 无法获得字典序小于 "24" 的字符串。 示例 3: 输入:s = "0011", a = 4, b = 2 输出:"0011" 解释:无法获得字典序小于 "0011" 的字符串。 示例 4: 输入:s = "43987654", a = 7, b = 3 输出:"00553311" 提示: 2 <= s.length <= 100 s.length 是偶数 s 仅由数字 0 到 9 组成 1 <= a <= 9 1 <= b <= s.length - 1 */ // https://leetcode-cn.com/problems/lexicographically-smallest-string-after-applying-operations/solution/bao-li-mei-xue-by-lucifer1004/ // 抄的 class Solution { int gcd(int a, int b) { int c; while (b) { c = a % b; a = b; b = c; } return a; } public: string findLexSmallestString(string s, int a, int b) { string ans = s; string t = s + s; int n = static_cast<int>(s.size()); int g = gcd(n, b); for (int i = 0; i < n; i += g) { // 奇数位置可以加 j 次 for (int j = 0; j <= 9; ++j) { // 偶数位置可以加 k 次 int k = g % 2 ? 9 : 0; for (; k >= 0; --k) { string q = t.substr(i, n); for (int m = 1; m < n; m += 2) q[m] = (char)((q[m] - '0' + a * j) % 10 + '0'); for (int m = 0; m < n; m += 2) q[m] = (char)((q[m] - '0' + a * k) % 10 + '0'); if (q < ans) ans.swap(q); } } } return ans; } }; int main() { Solution s; OutString(s.findLexSmallestString("5525", 9, 2)); OutString(s.findLexSmallestString("74", 5, 1)); OutString(s.findLexSmallestString("0011", 4, 2)); OutString(s.findLexSmallestString("43987654", 7, 3)); }
// Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2018 The PIVX developers // Copyright (c) 2019-2020 The ZNN developers // Copyright (c) 2021-2022 The FunCoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "init.h" #include "main.h" #include "addrman.h" #include "masternode-budget.h" #include "masternode-sync.h" #include "masternode.h" #include "masternodeman.h" #include "obfuscation.h" #include "util.h" #include <boost/filesystem.hpp> #include <boost/lexical_cast.hpp> CBudgetManager budget; CCriticalSection cs_budget; std::map<uint256, int64_t> askedForSourceProposalOrBudget; std::vector<CBudgetProposalBroadcast> vecImmatureBudgetProposals; std::vector<CFinalizedBudgetBroadcast> vecImmatureFinalizedBudgets; int nSubmittedFinalBudget; int GetBudgetPaymentCycleBlocks() { // Amount of blocks in a months period of time (using 1 minutes per) = (60*24*30) if (Params().NetworkID() == CBaseChainParams::MAIN) return 43200; //for testing purposes return 144; //ten times per day } bool IsBudgetCollateralValid(uint256 nTxCollateralHash, uint256 nExpectedHash, std::string& strError, int64_t& nTime, int& nConf, bool fBudgetFinalization) { CTransaction txCollateral; uint256 nBlockHash; if (!GetTransaction(nTxCollateralHash, txCollateral, nBlockHash, true)) { strError = strprintf("Can't find collateral tx %s", txCollateral.ToString()); LogPrint("mnbudget","CBudgetProposalBroadcast::IsBudgetCollateralValid - %s\n", strError); return false; } if (txCollateral.vout.size() < 1) return false; if (txCollateral.nLockTime != 0) return false; CScript findScript; findScript << OP_RETURN << ToByteVector(nExpectedHash); bool foundOpReturn = false; BOOST_FOREACH (const CTxOut o, txCollateral.vout) { if (!o.scriptPubKey.IsNormalPaymentScript() && !o.scriptPubKey.IsUnspendable()) { strError = strprintf("Invalid Script %s", txCollateral.ToString()); LogPrint("mnbudget","CBudgetProposalBroadcast::IsBudgetCollateralValid - %s\n", strError); return false; } if (fBudgetFinalization) { // Collateral for budget finalization // Note: there are still old valid budgets out there, but the check for the new 5 FUN finalization collateral // will also cover the old 50 FUN finalization collateral. LogPrint("mnbudget", "Final Budget: o.scriptPubKey(%s) == findScript(%s) ?\n", o.scriptPubKey.ToString(), findScript.ToString()); if (o.scriptPubKey == findScript) { LogPrint("mnbudget", "Final Budget: o.nValue(%ld) >= BUDGET_FEE_TX(%ld) ?\n", o.nValue, BUDGET_FEE_TX); if(o.nValue >= BUDGET_FEE_TX) { foundOpReturn = true; } } } else { // Collateral for normal budget proposal LogPrint("mnbudget", "Normal Budget: o.scriptPubKey(%s) == findScript(%s) ?\n", o.scriptPubKey.ToString(), findScript.ToString()); if (o.scriptPubKey == findScript) { LogPrint("mnbudget", "Normal Budget: o.nValue(%ld) >= PROPOSAL_FEE_TX(%ld) ?\n", o.nValue, PROPOSAL_FEE_TX); if(o.nValue >= PROPOSAL_FEE_TX) { foundOpReturn = true; } } } } if (!foundOpReturn) { strError = strprintf("Couldn't find opReturn %s in %s", nExpectedHash.ToString(), txCollateral.ToString()); LogPrint("mnbudget","CBudgetProposalBroadcast::IsBudgetCollateralValid - %s\n", strError); return false; } // RETRIEVE CONFIRMATIONS AND NTIME /* - nTime starts as zero and is passed-by-reference out of this function and stored in the external proposal - nTime is never validated via the hashing mechanism and comes from a full-validated source (the blockchain) */ int conf = GetIXConfirmations(nTxCollateralHash); if (nBlockHash != uint256(0)) { BlockMap::iterator mi = mapBlockIndex.find(nBlockHash); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (chainActive.Contains(pindex)) { conf += chainActive.Height() - pindex->nHeight + 1; nTime = pindex->nTime; } } } nConf = conf; //if we're syncing we won't have swiftTX information, so accept 1 confirmation if (conf >= Params().Budget_Fee_Confirmations()) { return true; } else { strError = strprintf("Collateral requires at least %d confirmations - %d confirmations", Params().Budget_Fee_Confirmations(), conf); LogPrint("mnbudget","CBudgetProposalBroadcast::IsBudgetCollateralValid - %s - %d confirmations\n", strError, conf); return false; } } void CBudgetManager::CheckOrphanVotes() { LOCK(cs); std::string strError = ""; std::map<uint256, CBudgetVote>::iterator it1 = mapOrphanMasternodeBudgetVotes.begin(); while (it1 != mapOrphanMasternodeBudgetVotes.end()) { if (budget.UpdateProposal(((*it1).second), NULL, strError)) { LogPrint("mnbudget","CBudgetManager::CheckOrphanVotes - Proposal/Budget is known, activating and removing orphan vote\n"); mapOrphanMasternodeBudgetVotes.erase(it1++); } else { ++it1; } } std::map<uint256, CFinalizedBudgetVote>::iterator it2 = mapOrphanFinalizedBudgetVotes.begin(); while (it2 != mapOrphanFinalizedBudgetVotes.end()) { if (budget.UpdateFinalizedBudget(((*it2).second), NULL, strError)) { LogPrint("mnbudget","CBudgetManager::CheckOrphanVotes - Proposal/Budget is known, activating and removing orphan vote\n"); mapOrphanFinalizedBudgetVotes.erase(it2++); } else { ++it2; } } LogPrint("mnbudget","CBudgetManager::CheckOrphanVotes - Done\n"); } void CBudgetManager::SubmitFinalBudget() { static int nSubmittedHeight = 0; // height at which final budget was submitted last time int nCurrentHeight; { TRY_LOCK(cs_main, locked); if (!locked) return; if (!chainActive.Tip()) return; nCurrentHeight = chainActive.Height(); } int nBlockStart = nCurrentHeight - nCurrentHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks(); if (nSubmittedHeight >= nBlockStart){ LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - nSubmittedHeight(=%ld) < nBlockStart(=%ld) condition not fulfilled.\n", nSubmittedHeight, nBlockStart); return; } // Submit final budget during the last 2 days (2880 blocks) before payment for Mainnet, about 9 minutes (9 blocks) for Testnet int finalizationWindow = ((GetBudgetPaymentCycleBlocks() / 30) * 2); if (Params().NetworkID() == CBaseChainParams::TESTNET) { // NOTE: 9 blocks for testnet is way to short to have any masternode submit an automatic vote on the finalized(!) budget, // because those votes are only submitted/relayed once every 56 blocks in CFinalizedBudget::AutoCheck() finalizationWindow = 64; // 56 + 4 finalization confirmations + 4 minutes buffer for propagation } int nFinalizationStart = nBlockStart - finalizationWindow; int nOffsetToStart = nFinalizationStart - nCurrentHeight; if (nBlockStart - nCurrentHeight > finalizationWindow) { LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Too early for finalization. Current block is %ld, next Superblock is %ld.\n", nCurrentHeight, nBlockStart); LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - First possible block for finalization: %ld. Last possible block for finalization: %ld. You have to wait for %ld block(s) until Budget finalization will be possible\n", nFinalizationStart, nBlockStart, nOffsetToStart); return; } std::vector<CBudgetProposal*> vBudgetProposals = budget.GetBudget(); std::string strBudgetName = "main"; std::vector<CTxBudgetPayment> vecTxBudgetPayments; for (unsigned int i = 0; i < vBudgetProposals.size(); i++) { CTxBudgetPayment txBudgetPayment; txBudgetPayment.nProposalHash = vBudgetProposals[i]->GetHash(); txBudgetPayment.payee = vBudgetProposals[i]->GetPayee(); txBudgetPayment.nAmount = vBudgetProposals[i]->GetAllotted(); vecTxBudgetPayments.push_back(txBudgetPayment); } if (vecTxBudgetPayments.size() < 1) { LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Found No Proposals For Period\n"); return; } CFinalizedBudgetBroadcast tempBudget(strBudgetName, nBlockStart, vecTxBudgetPayments, 0); if (mapSeenFinalizedBudgets.count(tempBudget.GetHash())) { LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Budget already exists - %s\n", tempBudget.GetHash().ToString()); nSubmittedHeight = nCurrentHeight; return; //already exists } //create fee tx CTransaction tx; uint256 txidCollateral; if (!mapCollateralTxids.count(tempBudget.GetHash())) { CWalletTx wtx; if (!pwalletMain->GetBudgetFinalizationCollateralTX(wtx, tempBudget.GetHash(), false)) { LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Can't make collateral transaction\n"); return; } // Get our change address CReserveKey reservekey(pwalletMain); // Send the tx to the network. Do NOT use SwiftTx, locking might need too much time to propagate, especially for testnet pwalletMain->CommitTransaction(wtx, reservekey, "NO-ix"); tx = (CTransaction)wtx; txidCollateral = tx.GetHash(); mapCollateralTxids.insert(make_pair(tempBudget.GetHash(), txidCollateral)); } else { txidCollateral = mapCollateralTxids[tempBudget.GetHash()]; } int conf = GetIXConfirmations(txidCollateral); CTransaction txCollateral; uint256 nBlockHash; if (!GetTransaction(txidCollateral, txCollateral, nBlockHash, true)) { LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Can't find collateral tx %s", txidCollateral.ToString()); return; } if (nBlockHash != uint256(0)) { BlockMap::iterator mi = mapBlockIndex.find(nBlockHash); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (chainActive.Contains(pindex)) { conf += chainActive.Height() - pindex->nHeight + 1; } } } /* Wait will we have 1 extra confirmation, otherwise some clients might reject this feeTX -- This function is tied to NewBlock, so we will propagate this budget while the block is also propagating */ if (conf < Params().Budget_Fee_Confirmations() + 1) { LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Collateral requires at least %d confirmations - %s - %d confirmations\n", Params().Budget_Fee_Confirmations() + 1, txidCollateral.ToString(), conf); return; } //create the proposal incase we're the first to make it CFinalizedBudgetBroadcast finalizedBudgetBroadcast(strBudgetName, nBlockStart, vecTxBudgetPayments, txidCollateral); std::string strError = ""; if (!finalizedBudgetBroadcast.IsValid(strError)) { LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Invalid finalized budget - %s \n", strError); return; } LOCK(cs); mapSeenFinalizedBudgets.insert(make_pair(finalizedBudgetBroadcast.GetHash(), finalizedBudgetBroadcast)); finalizedBudgetBroadcast.Relay(); budget.AddFinalizedBudget(finalizedBudgetBroadcast); nSubmittedHeight = nCurrentHeight; LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Done! %s\n", finalizedBudgetBroadcast.GetHash().ToString()); } // // CBudgetDB // CBudgetDB::CBudgetDB() { pathDB = GetDataDir() / "budget.dat"; strMagicMessage = "MasternodeBudget"; } bool CBudgetDB::Write(const CBudgetManager& objToSave) { LOCK(objToSave.cs); int64_t nStart = GetTimeMillis(); // serialize, checksum data up to that point, then append checksum CDataStream ssObj(SER_DISK, CLIENT_VERSION); ssObj << strMagicMessage; // masternode cache file specific magic message ssObj << FLATDATA(Params().MessageStart()); // network specific magic number ssObj << objToSave; uint256 hash = Hash(ssObj.begin(), ssObj.end()); ssObj << hash; // open output file, and associate with CAutoFile FILE* file = fopen(pathDB.string().c_str(), "wb"); CAutoFile fileout(file, SER_DISK, CLIENT_VERSION); if (fileout.IsNull()) return error("%s : Failed to open file %s", __func__, pathDB.string()); // Write and commit header, data try { fileout << ssObj; } catch (std::exception& e) { return error("%s : Serialize or I/O error - %s", __func__, e.what()); } fileout.fclose(); LogPrint("mnbudget","Written info to budget.dat %dms\n", GetTimeMillis() - nStart); return true; } CBudgetDB::ReadResult CBudgetDB::Read(CBudgetManager& objToLoad, bool fDryRun) { LOCK(objToLoad.cs); int64_t nStart = GetTimeMillis(); // open input file, and associate with CAutoFile FILE* file = fopen(pathDB.string().c_str(), "rb"); CAutoFile filein(file, SER_DISK, CLIENT_VERSION); if (filein.IsNull()) { error("%s : Failed to open file %s", __func__, pathDB.string()); return FileError; } // use file size to size memory buffer int fileSize = boost::filesystem::file_size(pathDB); int dataSize = fileSize - sizeof(uint256); // Don't try to resize to a negative number if file is small if (dataSize < 0) dataSize = 0; vector<unsigned char> vchData; vchData.resize(dataSize); uint256 hashIn; // read data and checksum from file try { filein.read((char*)&vchData[0], dataSize); filein >> hashIn; } catch (std::exception& e) { error("%s : Deserialize or I/O error - %s", __func__, e.what()); return HashReadError; } filein.fclose(); CDataStream ssObj(vchData, SER_DISK, CLIENT_VERSION); // verify stored checksum matches input data uint256 hashTmp = Hash(ssObj.begin(), ssObj.end()); if (hashIn != hashTmp) { error("%s : Checksum mismatch, data corrupted", __func__); return IncorrectHash; } unsigned char pchMsgTmp[4]; std::string strMagicMessageTmp; try { // de-serialize file header (masternode cache file specific magic message) and .. ssObj >> strMagicMessageTmp; // ... verify the message matches predefined one if (strMagicMessage != strMagicMessageTmp) { error("%s : Invalid masternode cache magic message", __func__); return IncorrectMagicMessage; } // de-serialize file header (network specific magic number) and .. ssObj >> FLATDATA(pchMsgTmp); // ... verify the network matches ours if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp))) { error("%s : Invalid network magic number", __func__); return IncorrectMagicNumber; } // de-serialize data into CBudgetManager object ssObj >> objToLoad; } catch (std::exception& e) { objToLoad.Clear(); error("%s : Deserialize or I/O error - %s", __func__, e.what()); return IncorrectFormat; } LogPrint("mnbudget","Loaded info from budget.dat %dms\n", GetTimeMillis() - nStart); LogPrint("mnbudget"," %s\n", objToLoad.ToString()); if (!fDryRun) { LogPrint("mnbudget","Budget manager - cleaning....\n"); objToLoad.CheckAndRemove(); LogPrint("mnbudget","Budget manager - result:\n"); LogPrint("mnbudget"," %s\n", objToLoad.ToString()); } return Ok; } void DumpBudgets() { int64_t nStart = GetTimeMillis(); CBudgetDB budgetdb; CBudgetManager tempBudget; LogPrint("mnbudget","Verifying budget.dat format...\n"); CBudgetDB::ReadResult readResult = budgetdb.Read(tempBudget, true); // there was an error and it was not an error on file opening => do not proceed if (readResult == CBudgetDB::FileError) LogPrint("mnbudget","Missing budgets file - budget.dat, will try to recreate\n"); else if (readResult != CBudgetDB::Ok) { LogPrint("mnbudget","Error reading budget.dat: "); if (readResult == CBudgetDB::IncorrectFormat) LogPrint("mnbudget","magic is ok but data has invalid format, will try to recreate\n"); else { LogPrint("mnbudget","file format is unknown or invalid, please fix it manually\n"); return; } } LogPrint("mnbudget","Writting info to budget.dat...\n"); budgetdb.Write(budget); LogPrint("mnbudget","Budget dump finished %dms\n", GetTimeMillis() - nStart); } bool CBudgetManager::AddFinalizedBudget(CFinalizedBudget& finalizedBudget) { std::string strError = ""; if (!finalizedBudget.IsValid(strError)) return false; if (mapFinalizedBudgets.count(finalizedBudget.GetHash())) { return false; } mapFinalizedBudgets.insert(make_pair(finalizedBudget.GetHash(), finalizedBudget)); return true; } bool CBudgetManager::AddProposal(CBudgetProposal& budgetProposal) { LOCK(cs); std::string strError = ""; if (!budgetProposal.IsValid(strError)) { LogPrint("mnbudget","CBudgetManager::AddProposal - invalid budget proposal - %s\n", strError); return false; } if (mapProposals.count(budgetProposal.GetHash())) { return false; } mapProposals.insert(make_pair(budgetProposal.GetHash(), budgetProposal)); LogPrint("mnbudget","CBudgetManager::AddProposal - proposal %s added\n", budgetProposal.GetName ().c_str ()); return true; } void CBudgetManager::CheckAndRemove() { int nHeight = 0; // Add some verbosity once loading blocks from files has finished { TRY_LOCK(cs_main, locked); if ((locked) && (chainActive.Tip() != NULL)) { CBlockIndex* pindexPrev = chainActive.Tip(); if (pindexPrev) { nHeight = pindexPrev->nHeight; } } } LogPrint("mnbudget", "CBudgetManager::CheckAndRemove at Height=%d\n", nHeight); map<uint256, CFinalizedBudget> tmpMapFinalizedBudgets; map<uint256, CBudgetProposal> tmpMapProposals; std::string strError = ""; LogPrint("mnbudget", "CBudgetManager::CheckAndRemove - mapFinalizedBudgets cleanup - size before: %d\n", mapFinalizedBudgets.size()); std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while (it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); pfinalizedBudget->fValid = pfinalizedBudget->IsValid(strError); if (!strError.empty ()) { LogPrint("mnbudget","CBudgetManager::CheckAndRemove - Invalid finalized budget: %s\n", strError); } else { LogPrint("mnbudget","CBudgetManager::CheckAndRemove - Found valid finalized budget: %s %s\n", pfinalizedBudget->strBudgetName.c_str(), pfinalizedBudget->nFeeTXHash.ToString().c_str()); } if (pfinalizedBudget->fValid) { pfinalizedBudget->AutoCheck(); tmpMapFinalizedBudgets.insert(make_pair(pfinalizedBudget->GetHash(), *pfinalizedBudget)); } ++it; } LogPrint("mnbudget", "CBudgetManager::CheckAndRemove - mapProposals cleanup - size before: %d\n", mapProposals.size()); std::map<uint256, CBudgetProposal>::iterator it2 = mapProposals.begin(); while (it2 != mapProposals.end()) { CBudgetProposal* pbudgetProposal = &((*it2).second); pbudgetProposal->fValid = pbudgetProposal->IsValid(strError); if (!strError.empty ()) { LogPrint("mnbudget","CBudgetManager::CheckAndRemove - Invalid budget proposal - %s\n", strError); strError = ""; } else { LogPrint("mnbudget","CBudgetManager::CheckAndRemove - Found valid budget proposal: %s %s\n", pbudgetProposal->strProposalName.c_str(), pbudgetProposal->nFeeTXHash.ToString().c_str()); } if (pbudgetProposal->fValid) { tmpMapProposals.insert(make_pair(pbudgetProposal->GetHash(), *pbudgetProposal)); } ++it2; } // Remove invalid entries by overwriting complete map mapFinalizedBudgets.swap(tmpMapFinalizedBudgets); mapProposals.swap(tmpMapProposals); // clang doesn't accept copy assignemnts :-/ // mapFinalizedBudgets = tmpMapFinalizedBudgets; // mapProposals = tmpMapProposals; LogPrint("mnbudget", "CBudgetManager::CheckAndRemove - mapFinalizedBudgets cleanup - size after: %d\n", mapFinalizedBudgets.size()); LogPrint("mnbudget", "CBudgetManager::CheckAndRemove - mapProposals cleanup - size after: %d\n", mapProposals.size()); LogPrint("mnbudget","CBudgetManager::CheckAndRemove - PASSED\n"); } void CBudgetManager::FillBlockPayee(CMutableTransaction& txNew, CAmount nFees, bool fProofOfStake) { LOCK(cs); CBlockIndex* pindexPrev = chainActive.Tip(); if (!pindexPrev) return; int nHighestCount = 0; CScript payee; CAmount nAmount = 0; // ------- Grab The Highest Count std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while (it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); if (pfinalizedBudget->GetVoteCount() > nHighestCount && pindexPrev->nHeight + 1 >= pfinalizedBudget->GetBlockStart() && pindexPrev->nHeight + 1 <= pfinalizedBudget->GetBlockEnd() && pfinalizedBudget->GetPayeeAndAmount(pindexPrev->nHeight + 1, payee, nAmount)) { nHighestCount = pfinalizedBudget->GetVoteCount(); } ++it; } CAmount blockValue = GetBlockValue(pindexPrev->nHeight + 1); if (fProofOfStake) { if (nHighestCount > 0) { unsigned int i = txNew.vout.size(); txNew.vout.resize(i + 1); txNew.vout[i].scriptPubKey = payee; txNew.vout[i].nValue = nAmount; CTxDestination address1; ExtractDestination(payee, address1); CBitcoinAddress address2(address1); LogPrint("mnbudget","CBudgetManager::FillBlockPayee - Budget payment to %s for %lld, nHighestCount = %d\n", address2.ToString(), nAmount, nHighestCount); } else { LogPrint("mnbudget","CBudgetManager::FillBlockPayee - No Budget payment, nHighestCount = %d\n", nHighestCount); } } else { //miners get the full amount on these blocks txNew.vout[0].nValue = blockValue; if (nHighestCount > 0) { txNew.vout.resize(2); //these are super blocks, so their value can be much larger than normal txNew.vout[1].scriptPubKey = payee; txNew.vout[1].nValue = nAmount; CTxDestination address1; ExtractDestination(payee, address1); CBitcoinAddress address2(address1); LogPrint("mnbudget","CBudgetManager::FillBlockPayee - Budget payment to %s for %lld\n", address2.ToString(), nAmount); } } } CFinalizedBudget* CBudgetManager::FindFinalizedBudget(uint256 nHash) { if (mapFinalizedBudgets.count(nHash)) return &mapFinalizedBudgets[nHash]; return NULL; } CBudgetProposal* CBudgetManager::FindProposal(const std::string& strProposalName) { //find the prop with the highest yes count int nYesCount = -99999; CBudgetProposal* pbudgetProposal = NULL; std::map<uint256, CBudgetProposal>::iterator it = mapProposals.begin(); while (it != mapProposals.end()) { if ((*it).second.strProposalName == strProposalName && (*it).second.GetYeas() > nYesCount) { pbudgetProposal = &((*it).second); nYesCount = pbudgetProposal->GetYeas(); } ++it; } if (nYesCount == -99999) return NULL; return pbudgetProposal; } CBudgetProposal* CBudgetManager::FindProposal(uint256 nHash) { LOCK(cs); if (mapProposals.count(nHash)) return &mapProposals[nHash]; return NULL; } bool CBudgetManager::IsBudgetPaymentBlock(int nBlockHeight) { int nHighestCount = -1; int nFivePercent = mnodeman.CountEnabled(ActiveProtocol()) / 20; std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while (it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); if (pfinalizedBudget->GetVoteCount() > nHighestCount && nBlockHeight >= pfinalizedBudget->GetBlockStart() && nBlockHeight <= pfinalizedBudget->GetBlockEnd()) { nHighestCount = pfinalizedBudget->GetVoteCount(); } ++it; } LogPrint("mnbudget","CBudgetManager::IsBudgetPaymentBlock() - nHighestCount: %lli, 5%% of Masternodes: %lli. Number of finalized budgets: %lli\n", nHighestCount, nFivePercent, mapFinalizedBudgets.size()); // If budget doesn't have 5% of the network votes, then we should pay a masternode instead if (nHighestCount > nFivePercent) return true; return false; } TrxValidationStatus CBudgetManager::IsTransactionValid(const CTransaction& txNew, int nBlockHeight) { LOCK(cs); TrxValidationStatus transactionStatus = TrxValidationStatus::InValid; int nHighestCount = 0; int nFivePercent = mnodeman.CountEnabled(ActiveProtocol()) / 20; std::vector<CFinalizedBudget*> ret; LogPrint("mnbudget","CBudgetManager::IsTransactionValid - checking %lli finalized budgets\n", mapFinalizedBudgets.size()); // ------- Grab The Highest Count std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while (it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); if (pfinalizedBudget->GetVoteCount() > nHighestCount && nBlockHeight >= pfinalizedBudget->GetBlockStart() && nBlockHeight <= pfinalizedBudget->GetBlockEnd()) { nHighestCount = pfinalizedBudget->GetVoteCount(); } ++it; } LogPrint("mnbudget","CBudgetManager::IsTransactionValid() - nHighestCount: %lli, 5%% of Masternodes: %lli mapFinalizedBudgets.size(): %ld\n", nHighestCount, nFivePercent, mapFinalizedBudgets.size()); /* If budget doesn't have 5% of the network votes, then we should pay a masternode instead */ if (nHighestCount < nFivePercent) return TrxValidationStatus::InValid; // check the highest finalized budgets (+/- 10% to assist in consensus) std::string strProposals = ""; int nCountThreshold = nHighestCount - mnodeman.CountEnabled(ActiveProtocol()) / 10; bool fThreshold = false; it = mapFinalizedBudgets.begin(); while (it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); strProposals = pfinalizedBudget->GetProposals(); LogPrint("mnbudget","CBudgetManager::IsTransactionValid - checking budget (%s) with blockstart %lli, blockend %lli, nBlockHeight %lli, votes %lli, nCountThreshold %lli\n", strProposals.c_str(), pfinalizedBudget->GetBlockStart(), pfinalizedBudget->GetBlockEnd(), nBlockHeight, pfinalizedBudget->GetVoteCount(), nCountThreshold); if (pfinalizedBudget->GetVoteCount() > nCountThreshold) { fThreshold = true; LogPrint("mnbudget","CBudgetManager::IsTransactionValid - GetVoteCount() > nCountThreshold passed\n"); if (nBlockHeight >= pfinalizedBudget->GetBlockStart() && nBlockHeight <= pfinalizedBudget->GetBlockEnd()) { LogPrint("mnbudget","CBudgetManager::IsTransactionValid - GetBlockStart() passed\n"); transactionStatus = pfinalizedBudget->IsTransactionValid(txNew, nBlockHeight); if (transactionStatus == TrxValidationStatus::Valid) { LogPrint("mnbudget","CBudgetManager::IsTransactionValid - pfinalizedBudget->IsTransactionValid() passed\n"); return TrxValidationStatus::Valid; } else { LogPrint("mnbudget","CBudgetManager::IsTransactionValid - pfinalizedBudget->IsTransactionValid() error\n"); } } else { LogPrint("mnbudget","CBudgetManager::IsTransactionValid - GetBlockStart() failed, budget is outside current payment cycle and will be ignored.\n"); } } ++it; } // If not enough masternodes autovoted for any of the finalized budgets pay a masternode instead if(!fThreshold) { transactionStatus = TrxValidationStatus::VoteThreshold; } // We looked through all of the known budgets return transactionStatus; } std::vector<CBudgetProposal*> CBudgetManager::GetAllProposals() { LOCK(cs); std::vector<CBudgetProposal*> vBudgetProposalRet; std::map<uint256, CBudgetProposal>::iterator it = mapProposals.begin(); while (it != mapProposals.end()) { (*it).second.CleanAndRemove(false); CBudgetProposal* pbudgetProposal = &((*it).second); vBudgetProposalRet.push_back(pbudgetProposal); ++it; } return vBudgetProposalRet; } // // Sort by votes, if there's a tie sort by their feeHash TX // struct sortProposalsByVotes { bool operator()(const std::pair<CBudgetProposal*, int>& left, const std::pair<CBudgetProposal*, int>& right) { if (left.second != right.second) return (left.second > right.second); return (left.first->nFeeTXHash > right.first->nFeeTXHash); } }; //Need to review this function std::vector<CBudgetProposal*> CBudgetManager::GetBudget() { LOCK(cs); // ------- Sort budgets by Yes Count std::vector<std::pair<CBudgetProposal*, int> > vBudgetPorposalsSort; std::map<uint256, CBudgetProposal>::iterator it = mapProposals.begin(); while (it != mapProposals.end()) { (*it).second.CleanAndRemove(false); vBudgetPorposalsSort.push_back(make_pair(&((*it).second), (*it).second.GetYeas() - (*it).second.GetNays())); ++it; } std::sort(vBudgetPorposalsSort.begin(), vBudgetPorposalsSort.end(), sortProposalsByVotes()); // ------- Grab The Budgets In Order std::vector<CBudgetProposal*> vBudgetProposalsRet; CAmount nBudgetAllocated = 0; CBlockIndex* pindexPrev = chainActive.Tip(); if (pindexPrev == NULL) return vBudgetProposalsRet; int nBlockStart = pindexPrev->nHeight - pindexPrev->nHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks(); int nBlockEnd = nBlockStart + GetBudgetPaymentCycleBlocks() - 1; CAmount nTotalBudget = GetTotalBudget(nBlockStart); std::vector<std::pair<CBudgetProposal*, int> >::iterator it2 = vBudgetPorposalsSort.begin(); while (it2 != vBudgetPorposalsSort.end()) { CBudgetProposal* pbudgetProposal = (*it2).first; LogPrint("mnbudget","CBudgetManager::GetBudget() - Processing Budget %s\n", pbudgetProposal->strProposalName.c_str()); //prop start/end should be inside this period if (pbudgetProposal->fValid && pbudgetProposal->nBlockStart <= nBlockStart && pbudgetProposal->nBlockEnd >= nBlockEnd && pbudgetProposal->GetYeas() - pbudgetProposal->GetNays() > mnodeman.CountEnabled(ActiveProtocol()) / 10 && pbudgetProposal->IsEstablished()) { LogPrint("mnbudget","CBudgetManager::GetBudget() - Check 1 passed: valid=%d | %ld <= %ld | %ld >= %ld | Yeas=%d Nays=%d Count=%d | established=%d\n", pbudgetProposal->fValid, pbudgetProposal->nBlockStart, nBlockStart, pbudgetProposal->nBlockEnd, nBlockEnd, pbudgetProposal->GetYeas(), pbudgetProposal->GetNays(), mnodeman.CountEnabled(ActiveProtocol()) / 10, pbudgetProposal->IsEstablished()); if (pbudgetProposal->GetAmount() + nBudgetAllocated <= nTotalBudget) { pbudgetProposal->SetAllotted(pbudgetProposal->GetAmount()); nBudgetAllocated += pbudgetProposal->GetAmount(); vBudgetProposalsRet.push_back(pbudgetProposal); LogPrint("mnbudget","CBudgetManager::GetBudget() - Check 2 passed: Budget added\n"); } else { pbudgetProposal->SetAllotted(0); LogPrint("mnbudget","CBudgetManager::GetBudget() - Check 2 failed: no amount allotted\n"); } } else { LogPrint("mnbudget","CBudgetManager::GetBudget() - Check 1 failed: valid=%d | %ld <= %ld | %ld >= %ld | Yeas=%d Nays=%d Count=%d | established=%d\n", pbudgetProposal->fValid, pbudgetProposal->nBlockStart, nBlockStart, pbudgetProposal->nBlockEnd, nBlockEnd, pbudgetProposal->GetYeas(), pbudgetProposal->GetNays(), mnodeman.CountEnabled(ActiveProtocol()) / 10, pbudgetProposal->IsEstablished()); } ++it2; } return vBudgetProposalsRet; } // Sort by votes, if there's a tie sort by their feeHash TX struct sortFinalizedBudgetsByVotes { bool operator()(const std::pair<CFinalizedBudget*, int>& left, const std::pair<CFinalizedBudget*, int>& right) { if (left.second != right.second) return left.second > right.second; return (left.first->nFeeTXHash > right.first->nFeeTXHash); } }; std::vector<CFinalizedBudget*> CBudgetManager::GetFinalizedBudgets() { LOCK(cs); std::vector<CFinalizedBudget*> vFinalizedBudgetsRet; std::vector<std::pair<CFinalizedBudget*, int> > vFinalizedBudgetsSort; // ------- Grab The Budgets In Order std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin(); while (it != mapFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); vFinalizedBudgetsSort.push_back(make_pair(pfinalizedBudget, pfinalizedBudget->GetVoteCount())); ++it; } std::sort(vFinalizedBudgetsSort.begin(), vFinalizedBudgetsSort.end(), sortFinalizedBudgetsByVotes()); std::vector<std::pair<CFinalizedBudget*, int> >::iterator it2 = vFinalizedBudgetsSort.begin(); while (it2 != vFinalizedBudgetsSort.end()) { vFinalizedBudgetsRet.push_back((*it2).first); ++it2; } return vFinalizedBudgetsRet; } std::vector<CPaymentWinner> CBudgetManager::GetRequiredPayments (int nBlockHeight) { LOCK (cs); std::vector<CPaymentWinner> vPaymentWinners; std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin (); while (it != mapFinalizedBudgets.end ()) { CFinalizedBudget* pfinalizedBudget = &((*it).second); if ((nBlockHeight >= pfinalizedBudget->GetBlockStart ()) && (nBlockHeight <= pfinalizedBudget->GetBlockEnd ())) { CTxBudgetPayment payment; if (pfinalizedBudget->GetBudgetPaymentByBlock (nBlockHeight, payment)) { CPaymentWinner paymentWinner; paymentWinner.strAddress = payment.nProposalHash.ToString (); vPaymentWinners.push_back (paymentWinner); } else LogPrint ("mnbudget","CBudgetManager::GetRequiredPaymentsString - Couldn't find budget payment for block %d\n", nBlockHeight); } ++it; } return vPaymentWinners; } CAmount CBudgetManager::GetTotalBudget(int nHeight) { if (chainActive.Tip() == NULL) return 0; if (Params().NetworkID() == CBaseChainParams::TESTNET) { CAmount nSubsidy = 500 * COIN; return ((nSubsidy / 100) * 10) * 146; } //get block value and calculate from that /*CAmount nSubsidy = 0; if (nHeight <= Params().LAST_POW_BLOCK() && nHeight >= 151200) { nSubsidy = 50 * COIN; } else if (nHeight <= 302399 && nHeight > Params().LAST_POW_BLOCK()) { nSubsidy = 50 * COIN; } else if (nHeight <= 345599 && nHeight >= 302400) { nSubsidy = 45 * COIN; } else if (nHeight <= 388799 && nHeight >= 345600) { nSubsidy = 40 * COIN; } else if (nHeight <= 431999 && nHeight >= 388800) { nSubsidy = 35 * COIN; } else if (nHeight <= 475199 && nHeight >= 432000) { nSubsidy = 30 * COIN; } else if (nHeight <= 518399 && nHeight >= 475200) { nSubsidy = 25 * COIN; } else if (nHeight <= 561599 && nHeight >= 518400) { nSubsidy = 20 * COIN; } else if (nHeight <= 604799 && nHeight >= 561600) { nSubsidy = 15 * COIN; } else if (nHeight <= 647999 && nHeight >= 604800) { nSubsidy = 10 * COIN; } else if (nHeight >= Params().Zerocoin_Block_V2_Start()) { nSubsidy = 10 * COIN; } else { nSubsidy = 5 * COIN; }*/ // Amount of blocks in a months period of time (using 1 minutes per) = (60*24*30) /* if (nHeight <= 172800) { return 648000 * COIN; } else {*/ return 1 * COIN; //return ((nSubsidy / 100) * 10) * 1440 * 30; //} } void CBudgetManager::NewBlock() { TRY_LOCK(cs, fBudgetNewBlock); if (!fBudgetNewBlock) return; if (masternodeSync.RequestedMasternodeAssets <= MASTERNODE_SYNC_BUDGET) return; if (strBudgetMode == "suggest") { //suggest the budget we see SubmitFinalBudget(); } //this function should be called 1/14 blocks, allowing up to 100 votes per day on all proposals if (chainActive.Height() % 14 != 0) return; // incremental sync with our peers if (masternodeSync.IsSynced()) { LogPrint("mnbudget","CBudgetManager::NewBlock - incremental sync started\n"); if (chainActive.Height() % 1440 == rand() % 1440) { ClearSeen(); ResetSync(); } LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) if (pnode->nVersion >= ActiveProtocol()) Sync(pnode, 0, true); MarkSynced(); } CheckAndRemove(); //remove invalid votes once in a while (we have to check the signatures and validity of every vote, somewhat CPU intensive) LogPrint("mnbudget","CBudgetManager::NewBlock - askedForSourceProposalOrBudget cleanup - size: %d\n", askedForSourceProposalOrBudget.size()); std::map<uint256, int64_t>::iterator it = askedForSourceProposalOrBudget.begin(); while (it != askedForSourceProposalOrBudget.end()) { if ((*it).second > GetTime() - (60 * 60 * 24)) { ++it; } else { askedForSourceProposalOrBudget.erase(it++); } } LogPrint("mnbudget","CBudgetManager::NewBlock - mapProposals cleanup - size: %d\n", mapProposals.size()); std::map<uint256, CBudgetProposal>::iterator it2 = mapProposals.begin(); while (it2 != mapProposals.end()) { (*it2).second.CleanAndRemove(false); ++it2; } LogPrint("mnbudget","CBudgetManager::NewBlock - mapFinalizedBudgets cleanup - size: %d\n", mapFinalizedBudgets.size()); std::map<uint256, CFinalizedBudget>::iterator it3 = mapFinalizedBudgets.begin(); while (it3 != mapFinalizedBudgets.end()) { (*it3).second.CleanAndRemove(false); ++it3; } LogPrint("mnbudget","CBudgetManager::NewBlock - vecImmatureBudgetProposals cleanup - size: %d\n", vecImmatureBudgetProposals.size()); std::vector<CBudgetProposalBroadcast>::iterator it4 = vecImmatureBudgetProposals.begin(); while (it4 != vecImmatureBudgetProposals.end()) { std::string strError = ""; int nConf = 0; if (!IsBudgetCollateralValid((*it4).nFeeTXHash, (*it4).GetHash(), strError, (*it4).nTime, nConf)) { ++it4; continue; } if (!(*it4).IsValid(strError)) { LogPrint("mnbudget","mprop (immature) - invalid budget proposal - %s\n", strError); it4 = vecImmatureBudgetProposals.erase(it4); continue; } CBudgetProposal budgetProposal((*it4)); if (AddProposal(budgetProposal)) { (*it4).Relay(); } LogPrint("mnbudget","mprop (immature) - new budget - %s\n", (*it4).GetHash().ToString()); it4 = vecImmatureBudgetProposals.erase(it4); } LogPrint("mnbudget","CBudgetManager::NewBlock - vecImmatureFinalizedBudgets cleanup - size: %d\n", vecImmatureFinalizedBudgets.size()); std::vector<CFinalizedBudgetBroadcast>::iterator it5 = vecImmatureFinalizedBudgets.begin(); while (it5 != vecImmatureFinalizedBudgets.end()) { std::string strError = ""; int nConf = 0; if (!IsBudgetCollateralValid((*it5).nFeeTXHash, (*it5).GetHash(), strError, (*it5).nTime, nConf, true)) { ++it5; continue; } if (!(*it5).IsValid(strError)) { LogPrint("mnbudget","fbs (immature) - invalid finalized budget - %s\n", strError); it5 = vecImmatureFinalizedBudgets.erase(it5); continue; } LogPrint("mnbudget","fbs (immature) - new finalized budget - %s\n", (*it5).GetHash().ToString()); CFinalizedBudget finalizedBudget((*it5)); if (AddFinalizedBudget(finalizedBudget)) { (*it5).Relay(); } it5 = vecImmatureFinalizedBudgets.erase(it5); } LogPrint("mnbudget","CBudgetManager::NewBlock - PASSED\n"); } void CBudgetManager::ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv) { // lite mode is not supported if (fLiteMode) return; if (!masternodeSync.IsBlockchainSynced()) return; LOCK(cs_budget); if (strCommand == "mnvs") { //Masternode vote sync uint256 nProp; vRecv >> nProp; if (Params().NetworkID() == CBaseChainParams::MAIN) { if (nProp == 0) { if (pfrom->HasFulfilledRequest("mnvs")) { LogPrint("mnbudget","mnvs - peer already asked me for the list\n"); Misbehaving(pfrom->GetId(), 20); return; } pfrom->FulfilledRequest("mnvs"); } } Sync(pfrom, nProp); LogPrint("mnbudget", "mnvs - Sent Masternode votes to peer %i\n", pfrom->GetId()); } if (strCommand == "mprop") { //Masternode Proposal CBudgetProposalBroadcast budgetProposalBroadcast; vRecv >> budgetProposalBroadcast; if (mapSeenMasternodeBudgetProposals.count(budgetProposalBroadcast.GetHash())) { masternodeSync.AddedBudgetItem(budgetProposalBroadcast.GetHash()); return; } std::string strError = ""; int nConf = 0; if (!IsBudgetCollateralValid(budgetProposalBroadcast.nFeeTXHash, budgetProposalBroadcast.GetHash(), strError, budgetProposalBroadcast.nTime, nConf)) { LogPrint("mnbudget","Proposal FeeTX is not valid - %s - %s\n", budgetProposalBroadcast.nFeeTXHash.ToString(), strError); if (nConf >= 1) vecImmatureBudgetProposals.push_back(budgetProposalBroadcast); return; } mapSeenMasternodeBudgetProposals.insert(make_pair(budgetProposalBroadcast.GetHash(), budgetProposalBroadcast)); if (!budgetProposalBroadcast.IsValid(strError)) { LogPrint("mnbudget","mprop - invalid budget proposal - %s\n", strError); return; } CBudgetProposal budgetProposal(budgetProposalBroadcast); if (AddProposal(budgetProposal)) { budgetProposalBroadcast.Relay(); } masternodeSync.AddedBudgetItem(budgetProposalBroadcast.GetHash()); LogPrint("mnbudget","mprop - new budget - %s\n", budgetProposalBroadcast.GetHash().ToString()); //We might have active votes for this proposal that are valid now CheckOrphanVotes(); } if (strCommand == "mvote") { //Masternode Vote CBudgetVote vote; vRecv >> vote; vote.fValid = true; if (mapSeenMasternodeBudgetVotes.count(vote.GetHash())) { masternodeSync.AddedBudgetItem(vote.GetHash()); return; } CMasternode* pmn = mnodeman.Find(vote.vin); if (pmn == NULL) { LogPrint("mnbudget","mvote - unknown masternode - vin: %s\n", vote.vin.prevout.hash.ToString()); mnodeman.AskForMN(pfrom, vote.vin); return; } mapSeenMasternodeBudgetVotes.insert(make_pair(vote.GetHash(), vote)); if (!vote.SignatureValid(true)) { if (masternodeSync.IsSynced()) { LogPrintf("CBudgetManager::ProcessMessage() : mvote - signature invalid\n"); Misbehaving(pfrom->GetId(), 20); } // it could just be a non-synced masternode mnodeman.AskForMN(pfrom, vote.vin); return; } std::string strError = ""; if (UpdateProposal(vote, pfrom, strError)) { vote.Relay(); masternodeSync.AddedBudgetItem(vote.GetHash()); } LogPrint("mnbudget","mvote - new budget vote for budget %s - %s\n", vote.nProposalHash.ToString(), vote.GetHash().ToString()); } if (strCommand == "fbs") { //Finalized Budget Suggestion CFinalizedBudgetBroadcast finalizedBudgetBroadcast; vRecv >> finalizedBudgetBroadcast; if (mapSeenFinalizedBudgets.count(finalizedBudgetBroadcast.GetHash())) { masternodeSync.AddedBudgetItem(finalizedBudgetBroadcast.GetHash()); return; } std::string strError = ""; int nConf = 0; if (!IsBudgetCollateralValid(finalizedBudgetBroadcast.nFeeTXHash, finalizedBudgetBroadcast.GetHash(), strError, finalizedBudgetBroadcast.nTime, nConf, true)) { LogPrint("mnbudget","fbs - Finalized Budget FeeTX is not valid - %s - %s\n", finalizedBudgetBroadcast.nFeeTXHash.ToString(), strError); if (nConf >= 1) vecImmatureFinalizedBudgets.push_back(finalizedBudgetBroadcast); return; } mapSeenFinalizedBudgets.insert(make_pair(finalizedBudgetBroadcast.GetHash(), finalizedBudgetBroadcast)); if (!finalizedBudgetBroadcast.IsValid(strError)) { LogPrint("mnbudget","fbs - invalid finalized budget - %s\n", strError); return; } LogPrint("mnbudget","fbs - new finalized budget - %s\n", finalizedBudgetBroadcast.GetHash().ToString()); CFinalizedBudget finalizedBudget(finalizedBudgetBroadcast); if (AddFinalizedBudget(finalizedBudget)) { finalizedBudgetBroadcast.Relay(); } masternodeSync.AddedBudgetItem(finalizedBudgetBroadcast.GetHash()); //we might have active votes for this budget that are now valid CheckOrphanVotes(); } if (strCommand == "fbvote") { //Finalized Budget Vote CFinalizedBudgetVote vote; vRecv >> vote; vote.fValid = true; if (mapSeenFinalizedBudgetVotes.count(vote.GetHash())) { masternodeSync.AddedBudgetItem(vote.GetHash()); return; } CMasternode* pmn = mnodeman.Find(vote.vin); if (pmn == NULL) { LogPrint("mnbudget", "fbvote - unknown masternode - vin: %s\n", vote.vin.prevout.hash.ToString()); mnodeman.AskForMN(pfrom, vote.vin); return; } mapSeenFinalizedBudgetVotes.insert(make_pair(vote.GetHash(), vote)); if (!vote.SignatureValid(true)) { if (masternodeSync.IsSynced()) { LogPrintf("CBudgetManager::ProcessMessage() : fbvote - signature invalid\n"); Misbehaving(pfrom->GetId(), 20); } // it could just be a non-synced masternode mnodeman.AskForMN(pfrom, vote.vin); return; } std::string strError = ""; if (UpdateFinalizedBudget(vote, pfrom, strError)) { vote.Relay(); masternodeSync.AddedBudgetItem(vote.GetHash()); LogPrint("mnbudget","fbvote - new finalized budget vote - %s\n", vote.GetHash().ToString()); } else { LogPrint("mnbudget","fbvote - rejected finalized budget vote - %s - %s\n", vote.GetHash().ToString(), strError); } } } bool CBudgetManager::PropExists(uint256 nHash) { if (mapProposals.count(nHash)) return true; return false; } //mark that a full sync is needed void CBudgetManager::ResetSync() { LOCK(cs); std::map<uint256, CBudgetProposalBroadcast>::iterator it1 = mapSeenMasternodeBudgetProposals.begin(); while (it1 != mapSeenMasternodeBudgetProposals.end()) { CBudgetProposal* pbudgetProposal = FindProposal((*it1).first); if (pbudgetProposal && pbudgetProposal->fValid) { //mark votes std::map<uint256, CBudgetVote>::iterator it2 = pbudgetProposal->mapVotes.begin(); while (it2 != pbudgetProposal->mapVotes.end()) { (*it2).second.fSynced = false; ++it2; } } ++it1; } std::map<uint256, CFinalizedBudgetBroadcast>::iterator it3 = mapSeenFinalizedBudgets.begin(); while (it3 != mapSeenFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = FindFinalizedBudget((*it3).first); if (pfinalizedBudget && pfinalizedBudget->fValid) { //send votes std::map<uint256, CFinalizedBudgetVote>::iterator it4 = pfinalizedBudget->mapVotes.begin(); while (it4 != pfinalizedBudget->mapVotes.end()) { (*it4).second.fSynced = false; ++it4; } } ++it3; } } void CBudgetManager::MarkSynced() { LOCK(cs); /* Mark that we've sent all valid items */ std::map<uint256, CBudgetProposalBroadcast>::iterator it1 = mapSeenMasternodeBudgetProposals.begin(); while (it1 != mapSeenMasternodeBudgetProposals.end()) { CBudgetProposal* pbudgetProposal = FindProposal((*it1).first); if (pbudgetProposal && pbudgetProposal->fValid) { //mark votes std::map<uint256, CBudgetVote>::iterator it2 = pbudgetProposal->mapVotes.begin(); while (it2 != pbudgetProposal->mapVotes.end()) { if ((*it2).second.fValid) (*it2).second.fSynced = true; ++it2; } } ++it1; } std::map<uint256, CFinalizedBudgetBroadcast>::iterator it3 = mapSeenFinalizedBudgets.begin(); while (it3 != mapSeenFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = FindFinalizedBudget((*it3).first); if (pfinalizedBudget && pfinalizedBudget->fValid) { //mark votes std::map<uint256, CFinalizedBudgetVote>::iterator it4 = pfinalizedBudget->mapVotes.begin(); while (it4 != pfinalizedBudget->mapVotes.end()) { if ((*it4).second.fValid) (*it4).second.fSynced = true; ++it4; } } ++it3; } } void CBudgetManager::Sync(CNode* pfrom, uint256 nProp, bool fPartial) { LOCK(cs); /* Sync with a client on the network -- This code checks each of the hash maps for all known budget proposals and finalized budget proposals, then checks them against the budget object to see if they're OK. If all checks pass, we'll send it to the peer. */ int nInvCount = 0; std::map<uint256, CBudgetProposalBroadcast>::iterator it1 = mapSeenMasternodeBudgetProposals.begin(); while (it1 != mapSeenMasternodeBudgetProposals.end()) { CBudgetProposal* pbudgetProposal = FindProposal((*it1).first); if (pbudgetProposal && pbudgetProposal->fValid && (nProp == 0 || (*it1).first == nProp)) { pfrom->PushInventory(CInv(MSG_BUDGET_PROPOSAL, (*it1).second.GetHash())); nInvCount++; //send votes std::map<uint256, CBudgetVote>::iterator it2 = pbudgetProposal->mapVotes.begin(); while (it2 != pbudgetProposal->mapVotes.end()) { if ((*it2).second.fValid) { if ((fPartial && !(*it2).second.fSynced) || !fPartial) { pfrom->PushInventory(CInv(MSG_BUDGET_VOTE, (*it2).second.GetHash())); nInvCount++; } } ++it2; } } ++it1; } pfrom->PushMessage("ssc", MASTERNODE_SYNC_BUDGET_PROP, nInvCount); LogPrint("mnbudget", "CBudgetManager::Sync - sent %d items\n", nInvCount); nInvCount = 0; std::map<uint256, CFinalizedBudgetBroadcast>::iterator it3 = mapSeenFinalizedBudgets.begin(); while (it3 != mapSeenFinalizedBudgets.end()) { CFinalizedBudget* pfinalizedBudget = FindFinalizedBudget((*it3).first); if (pfinalizedBudget && pfinalizedBudget->fValid && (nProp == 0 || (*it3).first == nProp)) { pfrom->PushInventory(CInv(MSG_BUDGET_FINALIZED, (*it3).second.GetHash())); nInvCount++; //send votes std::map<uint256, CFinalizedBudgetVote>::iterator it4 = pfinalizedBudget->mapVotes.begin(); while (it4 != pfinalizedBudget->mapVotes.end()) { if ((*it4).second.fValid) { if ((fPartial && !(*it4).second.fSynced) || !fPartial) { pfrom->PushInventory(CInv(MSG_BUDGET_FINALIZED_VOTE, (*it4).second.GetHash())); nInvCount++; } } ++it4; } } ++it3; } pfrom->PushMessage("ssc", MASTERNODE_SYNC_BUDGET_FIN, nInvCount); LogPrint("mnbudget", "CBudgetManager::Sync - sent %d items\n", nInvCount); } bool CBudgetManager::UpdateProposal(CBudgetVote& vote, CNode* pfrom, std::string& strError) { LOCK(cs); if (!mapProposals.count(vote.nProposalHash)) { if (pfrom) { // only ask for missing items after our syncing process is complete -- // otherwise we'll think a full sync succeeded when they return a result if (!masternodeSync.IsSynced()) return false; LogPrint("mnbudget","CBudgetManager::UpdateProposal - Unknown proposal %d, asking for source proposal\n", vote.nProposalHash.ToString()); mapOrphanMasternodeBudgetVotes[vote.nProposalHash] = vote; if (!askedForSourceProposalOrBudget.count(vote.nProposalHash)) { pfrom->PushMessage("mnvs", vote.nProposalHash); askedForSourceProposalOrBudget[vote.nProposalHash] = GetTime(); } } strError = "Proposal not found!"; return false; } return mapProposals[vote.nProposalHash].AddOrUpdateVote(vote, strError); } bool CBudgetManager::UpdateFinalizedBudget(CFinalizedBudgetVote& vote, CNode* pfrom, std::string& strError) { LOCK(cs); if (!mapFinalizedBudgets.count(vote.nBudgetHash)) { if (pfrom) { // only ask for missing items after our syncing process is complete -- // otherwise we'll think a full sync succeeded when they return a result if (!masternodeSync.IsSynced()) return false; LogPrint("mnbudget","CBudgetManager::UpdateFinalizedBudget - Unknown Finalized Proposal %s, asking for source budget\n", vote.nBudgetHash.ToString()); mapOrphanFinalizedBudgetVotes[vote.nBudgetHash] = vote; if (!askedForSourceProposalOrBudget.count(vote.nBudgetHash)) { pfrom->PushMessage("mnvs", vote.nBudgetHash); askedForSourceProposalOrBudget[vote.nBudgetHash] = GetTime(); } } strError = "Finalized Budget " + vote.nBudgetHash.ToString() + " not found!"; return false; } LogPrint("mnbudget","CBudgetManager::UpdateFinalizedBudget - Finalized Proposal %s added\n", vote.nBudgetHash.ToString()); return mapFinalizedBudgets[vote.nBudgetHash].AddOrUpdateVote(vote, strError); } CBudgetProposal::CBudgetProposal() { strProposalName = "unknown"; nBlockStart = 0; nBlockEnd = 0; nAmount = 0; nTime = 0; fValid = true; } CBudgetProposal::CBudgetProposal(std::string strProposalNameIn, std::string strURLIn, int nBlockStartIn, int nBlockEndIn, CScript addressIn, CAmount nAmountIn, uint256 nFeeTXHashIn) { strProposalName = strProposalNameIn; strURL = strURLIn; nBlockStart = nBlockStartIn; nBlockEnd = nBlockEndIn; address = addressIn; nAmount = nAmountIn; nFeeTXHash = nFeeTXHashIn; fValid = true; } CBudgetProposal::CBudgetProposal(const CBudgetProposal& other) { strProposalName = other.strProposalName; strURL = other.strURL; nBlockStart = other.nBlockStart; nBlockEnd = other.nBlockEnd; address = other.address; nAmount = other.nAmount; nTime = other.nTime; nFeeTXHash = other.nFeeTXHash; mapVotes = other.mapVotes; fValid = true; } bool CBudgetProposal::IsValid(std::string& strError, bool fCheckCollateral) { if (GetNays() - GetYeas() > mnodeman.CountEnabled(ActiveProtocol()) / 10) { strError = "Proposal " + strProposalName + ": Active removal"; return false; } if (nBlockStart < 0) { strError = "Invalid Proposal"; return false; } if (nBlockEnd < nBlockStart) { strError = "Proposal " + strProposalName + ": Invalid nBlockEnd (end before start)"; return false; } if (nAmount < 10 * COIN) { strError = "Proposal " + strProposalName + ": Invalid nAmount"; return false; } if (address == CScript()) { strError = "Proposal " + strProposalName + ": Invalid Payment Address"; return false; } if (fCheckCollateral) { int nConf = 0; if (!IsBudgetCollateralValid(nFeeTXHash, GetHash(), strError, nTime, nConf)) { strError = "Proposal " + strProposalName + ": Invalid collateral"; return false; } } /* TODO: There might be an issue with multisig in the coinbase on mainnet, we will add support for it in a future release. */ if (address.IsPayToScriptHash()) { strError = "Proposal " + strProposalName + ": Multisig is not currently supported."; return false; } //if proposal doesn't gain traction within 2 weeks, remove it // nTime not being saved correctly // -- TODO: We should keep track of the last time the proposal was valid, if it's invalid for 2 weeks, erase it // if(nTime + (60*60*24*2) < GetAdjustedTime()) { // if(GetYeas()-GetNays() < (mnodeman.CountEnabled(ActiveProtocol())/10)) { // strError = "Not enough support"; // return false; // } // } //can only pay out 10% of the possible coins (min value of coins) if (nAmount > budget.GetTotalBudget(nBlockStart)) { strError = "Proposal " + strProposalName + ": Payment more than max"; return false; } CBlockIndex* pindexPrev = chainActive.Tip(); if (pindexPrev == NULL) { strError = "Proposal " + strProposalName + ": Tip is NULL"; return true; } // Calculate maximum block this proposal will be valid, which is start of proposal + (number of payments * cycle) int nProposalEnd = GetBlockStart() + (GetBudgetPaymentCycleBlocks() * GetTotalPaymentCount()); // if (GetBlockEnd() < pindexPrev->nHeight - GetBudgetPaymentCycleBlocks() / 2) { if(nProposalEnd < pindexPrev->nHeight){ strError = "Proposal " + strProposalName + ": Invalid nBlockEnd (" + std::to_string(nProposalEnd) + ") < current height (" + std::to_string(pindexPrev->nHeight) + ")"; return false; } return true; } bool CBudgetProposal::AddOrUpdateVote(CBudgetVote& vote, std::string& strError) { std::string strAction = "New vote inserted:"; LOCK(cs); uint256 hash = vote.vin.prevout.GetHash(); if (mapVotes.count(hash)) { if (mapVotes[hash].nTime > vote.nTime) { strError = strprintf("new vote older than existing vote - %s\n", vote.GetHash().ToString()); LogPrint("mnbudget", "CBudgetProposal::AddOrUpdateVote - %s\n", strError); return false; } if (vote.nTime - mapVotes[hash].nTime < BUDGET_VOTE_UPDATE_MIN) { strError = strprintf("time between votes is too soon - %s - %lli sec < %lli sec\n", vote.GetHash().ToString(), vote.nTime - mapVotes[hash].nTime,BUDGET_VOTE_UPDATE_MIN); LogPrint("mnbudget", "CBudgetProposal::AddOrUpdateVote - %s\n", strError); return false; } strAction = "Existing vote updated:"; } if (vote.nTime > GetTime() + (60 * 60)) { strError = strprintf("new vote is too far ahead of current time - %s - nTime %lli - Max Time %lli\n", vote.GetHash().ToString(), vote.nTime, GetTime() + (60 * 60)); LogPrint("mnbudget", "CBudgetProposal::AddOrUpdateVote - %s\n", strError); return false; } mapVotes[hash] = vote; LogPrint("mnbudget", "CBudgetProposal::AddOrUpdateVote - %s %s\n", strAction.c_str(), vote.GetHash().ToString().c_str()); return true; } // If masternode voted for a proposal, but is now invalid -- remove the vote void CBudgetProposal::CleanAndRemove(bool fSignatureCheck) { std::map<uint256, CBudgetVote>::iterator it = mapVotes.begin(); while (it != mapVotes.end()) { (*it).second.fValid = (*it).second.SignatureValid(fSignatureCheck); ++it; } } double CBudgetProposal::GetRatio() { int yeas = 0; int nays = 0; std::map<uint256, CBudgetVote>::iterator it = mapVotes.begin(); while (it != mapVotes.end()) { if ((*it).second.nVote == VOTE_YES) yeas++; if ((*it).second.nVote == VOTE_NO) nays++; ++it; } if (yeas + nays == 0) return 0.0f; return ((double)(yeas) / (double)(yeas + nays)); } int CBudgetProposal::GetYeas() { int ret = 0; std::map<uint256, CBudgetVote>::iterator it = mapVotes.begin(); while (it != mapVotes.end()) { if ((*it).second.nVote == VOTE_YES && (*it).second.fValid) ret++; ++it; } return ret; } int CBudgetProposal::GetNays() { int ret = 0; std::map<uint256, CBudgetVote>::iterator it = mapVotes.begin(); while (it != mapVotes.end()) { if ((*it).second.nVote == VOTE_NO && (*it).second.fValid) ret++; ++it; } return ret; } int CBudgetProposal::GetAbstains() { int ret = 0; std::map<uint256, CBudgetVote>::iterator it = mapVotes.begin(); while (it != mapVotes.end()) { if ((*it).second.nVote == VOTE_ABSTAIN && (*it).second.fValid) ret++; ++it; } return ret; } int CBudgetProposal::GetBlockStartCycle() { //end block is half way through the next cycle (so the proposal will be removed much after the payment is sent) return nBlockStart - nBlockStart % GetBudgetPaymentCycleBlocks(); } int CBudgetProposal::GetBlockCurrentCycle() { CBlockIndex* pindexPrev = chainActive.Tip(); if (pindexPrev == NULL) return -1; if (pindexPrev->nHeight >= GetBlockEndCycle()) return -1; return pindexPrev->nHeight - pindexPrev->nHeight % GetBudgetPaymentCycleBlocks(); } int CBudgetProposal::GetBlockEndCycle() { // Right now single payment proposals have nBlockEnd have a cycle too early! // switch back if it break something else // end block is half way through the next cycle (so the proposal will be removed much after the payment is sent) // return nBlockEnd - GetBudgetPaymentCycleBlocks() / 2; // End block is half way through the next cycle (so the proposal will be removed much after the payment is sent) return nBlockEnd; } int CBudgetProposal::GetTotalPaymentCount() { return (GetBlockEndCycle() - GetBlockStartCycle()) / GetBudgetPaymentCycleBlocks(); } int CBudgetProposal::GetRemainingPaymentCount() { // If this budget starts in the future, this value will be wrong int nPayments = (GetBlockEndCycle() - GetBlockCurrentCycle()) / GetBudgetPaymentCycleBlocks() - 1; // Take the lowest value return std::min(nPayments, GetTotalPaymentCount()); } CBudgetProposalBroadcast::CBudgetProposalBroadcast(std::string strProposalNameIn, std::string strURLIn, int nPaymentCount, CScript addressIn, CAmount nAmountIn, int nBlockStartIn, uint256 nFeeTXHashIn) { strProposalName = strProposalNameIn; strURL = strURLIn; nBlockStart = nBlockStartIn; int nCycleStart = nBlockStart - nBlockStart % GetBudgetPaymentCycleBlocks(); // Right now single payment proposals have nBlockEnd have a cycle too early! // switch back if it break something else // calculate the end of the cycle for this vote, add half a cycle (vote will be deleted after that block) // nBlockEnd = nCycleStart + GetBudgetPaymentCycleBlocks() * nPaymentCount + GetBudgetPaymentCycleBlocks() / 2; // Calculate the end of the cycle for this vote, vote will be deleted after next cycle nBlockEnd = nCycleStart + (GetBudgetPaymentCycleBlocks() + 1) * nPaymentCount; address = addressIn; nAmount = nAmountIn; nFeeTXHash = nFeeTXHashIn; } void CBudgetProposalBroadcast::Relay() { CInv inv(MSG_BUDGET_PROPOSAL, GetHash()); RelayInv(inv); } CBudgetVote::CBudgetVote() { vin = CTxIn(); nProposalHash = 0; nVote = VOTE_ABSTAIN; nTime = 0; fValid = true; fSynced = false; } CBudgetVote::CBudgetVote(CTxIn vinIn, uint256 nProposalHashIn, int nVoteIn) { vin = vinIn; nProposalHash = nProposalHashIn; nVote = nVoteIn; nTime = GetAdjustedTime(); fValid = true; fSynced = false; } void CBudgetVote::Relay() { CInv inv(MSG_BUDGET_VOTE, GetHash()); RelayInv(inv); } bool CBudgetVote::Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode) { // Choose coins to use CPubKey pubKeyCollateralAddress; CKey keyCollateralAddress; std::string errorMessage; std::string strMessage = vin.prevout.ToStringShort() + nProposalHash.ToString() + boost::lexical_cast<std::string>(nVote) + boost::lexical_cast<std::string>(nTime); if (!obfuScationSigner.SignMessage(strMessage, errorMessage, vchSig, keyMasternode)) { LogPrint("mnbudget","CBudgetVote::Sign - Error upon calling SignMessage"); return false; } if (!obfuScationSigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, errorMessage)) { LogPrint("mnbudget","CBudgetVote::Sign - Error upon calling VerifyMessage"); return false; } return true; } bool CBudgetVote::SignatureValid(bool fSignatureCheck) { std::string errorMessage; std::string strMessage = vin.prevout.ToStringShort() + nProposalHash.ToString() + boost::lexical_cast<std::string>(nVote) + boost::lexical_cast<std::string>(nTime); CMasternode* pmn = mnodeman.Find(vin); if (pmn == NULL) { if (fDebug){ LogPrint("mnbudget","CBudgetVote::SignatureValid() - Unknown Masternode - %s\n", vin.prevout.hash.ToString()); } return false; } if (!fSignatureCheck) return true; if (!obfuScationSigner.VerifyMessage(pmn->pubKeyMasternode, vchSig, strMessage, errorMessage)) { LogPrint("mnbudget","CBudgetVote::SignatureValid() - Verify message failed\n"); return false; } return true; } CFinalizedBudget::CFinalizedBudget() { strBudgetName = ""; nBlockStart = 0; vecBudgetPayments.clear(); mapVotes.clear(); nFeeTXHash = 0; nTime = 0; fValid = true; fAutoChecked = false; } CFinalizedBudget::CFinalizedBudget(const CFinalizedBudget& other) { strBudgetName = other.strBudgetName; nBlockStart = other.nBlockStart; vecBudgetPayments = other.vecBudgetPayments; mapVotes = other.mapVotes; nFeeTXHash = other.nFeeTXHash; nTime = other.nTime; fValid = true; fAutoChecked = false; } bool CFinalizedBudget::AddOrUpdateVote(CFinalizedBudgetVote& vote, std::string& strError) { LOCK(cs); uint256 hash = vote.vin.prevout.GetHash(); std::string strAction = "New vote inserted:"; if (mapVotes.count(hash)) { if (mapVotes[hash].nTime > vote.nTime) { strError = strprintf("new vote older than existing vote - %s\n", vote.GetHash().ToString()); LogPrint("mnbudget", "CFinalizedBudget::AddOrUpdateVote - %s\n", strError); return false; } if (vote.nTime - mapVotes[hash].nTime < BUDGET_VOTE_UPDATE_MIN) { strError = strprintf("time between votes is too soon - %s - %lli sec < %lli sec\n", vote.GetHash().ToString(), vote.nTime - mapVotes[hash].nTime,BUDGET_VOTE_UPDATE_MIN); LogPrint("mnbudget", "CFinalizedBudget::AddOrUpdateVote - %s\n", strError); return false; } strAction = "Existing vote updated:"; } if (vote.nTime > GetTime() + (60 * 60)) { strError = strprintf("new vote is too far ahead of current time - %s - nTime %lli - Max Time %lli\n", vote.GetHash().ToString(), vote.nTime, GetTime() + (60 * 60)); LogPrint("mnbudget", "CFinalizedBudget::AddOrUpdateVote - %s\n", strError); return false; } mapVotes[hash] = vote; LogPrint("mnbudget", "CFinalizedBudget::AddOrUpdateVote - %s %s\n", strAction.c_str(), vote.GetHash().ToString().c_str()); return true; } //evaluate if we should vote for this. Masternode only void CFinalizedBudget::AutoCheck() { LOCK(cs); CBlockIndex* pindexPrev = chainActive.Tip(); if (!pindexPrev) return; LogPrint("mnbudget","CFinalizedBudget::AutoCheck - %lli - %d\n", pindexPrev->nHeight, fAutoChecked); if (!fMasterNode || fAutoChecked) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck fMasterNode=%d fAutoChecked=%d\n", fMasterNode, fAutoChecked); return; } // Do this 1 in 4 blocks -- spread out the voting activity // -- this function is only called every fourteenth block, so this is really 1 in 56 blocks if (rand() % 4 != 0) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck - waiting\n"); return; } fAutoChecked = true; //we only need to check this once if (strBudgetMode == "auto") //only vote for exact matches { std::vector<CBudgetProposal*> vBudgetProposals = budget.GetBudget(); for (unsigned int i = 0; i < vecBudgetPayments.size(); i++) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck Budget-Payments - nProp %d %s\n", i, vecBudgetPayments[i].nProposalHash.ToString()); LogPrint("mnbudget","CFinalizedBudget::AutoCheck Budget-Payments - Payee %d %s\n", i, vecBudgetPayments[i].payee.ToString()); LogPrint("mnbudget","CFinalizedBudget::AutoCheck Budget-Payments - nAmount %d %lli\n", i, vecBudgetPayments[i].nAmount); } for (unsigned int i = 0; i < vBudgetProposals.size(); i++) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck Budget-Proposals - nProp %d %s\n", i, vBudgetProposals[i]->GetHash().ToString()); LogPrint("mnbudget","CFinalizedBudget::AutoCheck Budget-Proposals - Payee %d %s\n", i, vBudgetProposals[i]->GetPayee().ToString()); LogPrint("mnbudget","CFinalizedBudget::AutoCheck Budget-Proposals - nAmount %d %lli\n", i, vBudgetProposals[i]->GetAmount()); } if (vBudgetProposals.size() == 0) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck - No Budget-Proposals found, aborting\n"); return; } if (vBudgetProposals.size() != vecBudgetPayments.size()) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck - Budget-Proposal length (%ld) doesn't match Budget-Payment length (%ld).\n", vBudgetProposals.size(), vecBudgetPayments.size()); return; } for (unsigned int i = 0; i < vecBudgetPayments.size(); i++) { if (i > vBudgetProposals.size() - 1) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck - Proposal size mismatch, i=%d > (vBudgetProposals.size() - 1)=%d\n", i, vBudgetProposals.size() - 1); return; } if (vecBudgetPayments[i].nProposalHash != vBudgetProposals[i]->GetHash()) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck - item #%d doesn't match %s %s\n", i, vecBudgetPayments[i].nProposalHash.ToString(), vBudgetProposals[i]->GetHash().ToString()); return; } // if(vecBudgetPayments[i].payee != vBudgetProposals[i]->GetPayee()){ -- triggered with false positive if (vecBudgetPayments[i].payee.ToString() != vBudgetProposals[i]->GetPayee().ToString()) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck - item #%d payee doesn't match %s %s\n", i, vecBudgetPayments[i].payee.ToString(), vBudgetProposals[i]->GetPayee().ToString()); return; } if (vecBudgetPayments[i].nAmount != vBudgetProposals[i]->GetAmount()) { LogPrint("mnbudget","CFinalizedBudget::AutoCheck - item #%d payee doesn't match %lli %lli\n", i, vecBudgetPayments[i].nAmount, vBudgetProposals[i]->GetAmount()); return; } } LogPrint("mnbudget","CFinalizedBudget::AutoCheck - Finalized Budget Matches! Submitting Vote.\n"); SubmitVote(); } } // If masternode voted for a proposal, but is now invalid -- remove the vote void CFinalizedBudget::CleanAndRemove(bool fSignatureCheck) { std::map<uint256, CFinalizedBudgetVote>::iterator it = mapVotes.begin(); while (it != mapVotes.end()) { (*it).second.fValid = (*it).second.SignatureValid(fSignatureCheck); ++it; } } CAmount CFinalizedBudget::GetTotalPayout() { CAmount ret = 0; for (unsigned int i = 0; i < vecBudgetPayments.size(); i++) { ret += vecBudgetPayments[i].nAmount; } return ret; } std::string CFinalizedBudget::GetProposals() { LOCK(cs); std::string ret = ""; BOOST_FOREACH (CTxBudgetPayment& budgetPayment, vecBudgetPayments) { CBudgetProposal* pbudgetProposal = budget.FindProposal(budgetPayment.nProposalHash); std::string token = budgetPayment.nProposalHash.ToString(); if (pbudgetProposal) token = pbudgetProposal->GetName(); if (ret == "") { ret = token; } else { ret += "," + token; } } return ret; } std::string CFinalizedBudget::GetStatus() { std::string retBadHashes = ""; std::string retBadPayeeOrAmount = ""; for (int nBlockHeight = GetBlockStart(); nBlockHeight <= GetBlockEnd(); nBlockHeight++) { CTxBudgetPayment budgetPayment; if (!GetBudgetPaymentByBlock(nBlockHeight, budgetPayment)) { LogPrint("mnbudget","CFinalizedBudget::GetStatus - Couldn't find budget payment for block %lld\n", nBlockHeight); continue; } CBudgetProposal* pbudgetProposal = budget.FindProposal(budgetPayment.nProposalHash); if (!pbudgetProposal) { if (retBadHashes == "") { retBadHashes = "Unknown proposal hash! Check this proposal before voting: " + budgetPayment.nProposalHash.ToString(); } else { retBadHashes += "," + budgetPayment.nProposalHash.ToString(); } } else { if (pbudgetProposal->GetPayee() != budgetPayment.payee || pbudgetProposal->GetAmount() != budgetPayment.nAmount) { if (retBadPayeeOrAmount == "") { retBadPayeeOrAmount = "Budget payee/nAmount doesn't match our proposal! " + budgetPayment.nProposalHash.ToString(); } else { retBadPayeeOrAmount += "," + budgetPayment.nProposalHash.ToString(); } } } } if (retBadHashes == "" && retBadPayeeOrAmount == "") return "OK"; return retBadHashes + retBadPayeeOrAmount; } bool CFinalizedBudget::IsValid(std::string& strError, bool fCheckCollateral) { // All(!) finalized budgets have the name "main", so get some additional information about them std::string strProposals = GetProposals(); // Must be the correct block for payment to happen (once a month) if (nBlockStart % GetBudgetPaymentCycleBlocks() != 0) { strError = "Invalid BlockStart"; return false; } // The following 2 checks check the same (basically if vecBudgetPayments.size() > 100) if (GetBlockEnd() - nBlockStart > 100) { strError = "Invalid BlockEnd"; return false; } if ((int)vecBudgetPayments.size() > 100) { strError = "Invalid budget payments count (too many)"; return false; } if (strBudgetName == "") { strError = "Invalid Budget Name"; return false; } if (nBlockStart == 0) { strError = "Budget " + strBudgetName + " (" + strProposals + ") Invalid BlockStart == 0"; return false; } if (nFeeTXHash == 0) { strError = "Budget " + strBudgetName + " (" + strProposals + ") Invalid FeeTx == 0"; return false; } // Can only pay out 10% of the possible coins (min value of coins) if (GetTotalPayout() > budget.GetTotalBudget(nBlockStart)) { strError = "Budget " + strBudgetName + " (" + strProposals + ") Invalid Payout (more than max)"; return false; } std::string strError2 = ""; if (fCheckCollateral) { int nConf = 0; if (!IsBudgetCollateralValid(nFeeTXHash, GetHash(), strError2, nTime, nConf, true)) { { strError = "Budget " + strBudgetName + " (" + strProposals + ") Invalid Collateral : " + strError2; return false; } } } // Remove obsolete finalized budgets after some time CBlockIndex* pindexPrev = chainActive.Tip(); if (pindexPrev == NULL) return true; // Get start of current budget-cycle int nCurrentHeight = chainActive.Height(); int nBlockStart = nCurrentHeight - nCurrentHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks(); // Remove budgets where the last payment (from max. 100) ends before 2 budget-cycles before the current one int nMaxAge = nBlockStart - (2 * GetBudgetPaymentCycleBlocks()); if (GetBlockEnd() < nMaxAge) { strError = strprintf("Budget " + strBudgetName + " (" + strProposals + ") (ends at block %ld) too old and obsolete", GetBlockEnd()); return false; } return true; } bool CFinalizedBudget::IsPaidAlready(uint256 nProposalHash, int nBlockHeight) { // Remove budget-payments from former/future payment cycles map<uint256, int>::iterator it = mapPayment_History.begin(); int nPaidBlockHeight = 0; uint256 nOldProposalHash; for(it = mapPayment_History.begin(); it != mapPayment_History.end(); /* No incrementation needed */ ) { nPaidBlockHeight = (*it).second; if((nPaidBlockHeight < GetBlockStart()) || (nPaidBlockHeight > GetBlockEnd())) { nOldProposalHash = (*it).first; LogPrint("mnbudget", "CFinalizedBudget::IsPaidAlready - Budget Proposal %s, Block %d from old cycle deleted\n", nOldProposalHash.ToString().c_str(), nPaidBlockHeight); mapPayment_History.erase(it++); } else { ++it; } } // Now that we only have payments from the current payment cycle check if this budget was paid already if(mapPayment_History.count(nProposalHash) == 0) { // New proposal payment, insert into map for checks with later blocks from this cycle mapPayment_History.insert(std::pair<uint256, int>(nProposalHash, nBlockHeight)); LogPrint("mnbudget", "CFinalizedBudget::IsPaidAlready - Budget Proposal %s, Block %d added to payment history\n", nProposalHash.ToString().c_str(), nBlockHeight); return false; } // This budget was paid already -> reject transaction so it gets paid to a masternode instead return true; } TrxValidationStatus CFinalizedBudget::IsTransactionValid(const CTransaction& txNew, int nBlockHeight) { TrxValidationStatus transactionStatus = TrxValidationStatus::InValid; int nCurrentBudgetPayment = nBlockHeight - GetBlockStart(); if (nCurrentBudgetPayment < 0) { LogPrint("mnbudget","CFinalizedBudget::IsTransactionValid - Invalid block - height: %d start: %d\n", nBlockHeight, GetBlockStart()); return TrxValidationStatus::InValid; } if (nCurrentBudgetPayment > (int)vecBudgetPayments.size() - 1) { LogPrint("mnbudget","CFinalizedBudget::IsTransactionValid - Invalid last block - current budget payment: %d of %d\n", nCurrentBudgetPayment + 1, (int)vecBudgetPayments.size()); return TrxValidationStatus::InValid; } bool paid = false; BOOST_FOREACH (CTxOut out, txNew.vout) { LogPrint("mnbudget","CFinalizedBudget::IsTransactionValid - nCurrentBudgetPayment=%d, payee=%s == out.scriptPubKey=%s, amount=%ld == out.nValue=%ld\n", nCurrentBudgetPayment, vecBudgetPayments[nCurrentBudgetPayment].payee.ToString().c_str(), out.scriptPubKey.ToString().c_str(), vecBudgetPayments[nCurrentBudgetPayment].nAmount, out.nValue); if (vecBudgetPayments[nCurrentBudgetPayment].payee == out.scriptPubKey && vecBudgetPayments[nCurrentBudgetPayment].nAmount == out.nValue) { // Check if this proposal was paid already. If so, pay a masternode instead paid = IsPaidAlready(vecBudgetPayments[nCurrentBudgetPayment].nProposalHash, nBlockHeight); if(paid) { LogPrint("mnbudget","CFinalizedBudget::IsTransactionValid - Double Budget Payment of %d for proposal %d detected. Paying a masternode instead.\n", vecBudgetPayments[nCurrentBudgetPayment].nAmount, vecBudgetPayments[nCurrentBudgetPayment].nProposalHash.Get32()); // No matter what we've found before, stop all checks here. In future releases there might be more than one budget payment // per block, so even if the first one was not paid yet this one disables all budget payments for this block. transactionStatus = TrxValidationStatus::DoublePayment; break; } else { transactionStatus = TrxValidationStatus::Valid; LogPrint("mnbudget","CFinalizedBudget::IsTransactionValid - Found valid Budget Payment of %d for proposal %d\n", vecBudgetPayments[nCurrentBudgetPayment].nAmount, vecBudgetPayments[nCurrentBudgetPayment].nProposalHash.Get32()); } } } if (transactionStatus == TrxValidationStatus::InValid) { CTxDestination address1; ExtractDestination(vecBudgetPayments[nCurrentBudgetPayment].payee, address1); CBitcoinAddress address2(address1); LogPrint("mnbudget","CFinalizedBudget::IsTransactionValid - Missing required payment - %s: %d c: %d\n", address2.ToString(), vecBudgetPayments[nCurrentBudgetPayment].nAmount, nCurrentBudgetPayment); } return transactionStatus; } void CFinalizedBudget::SubmitVote() { CPubKey pubKeyMasternode; CKey keyMasternode; std::string errorMessage; if (!obfuScationSigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode)) { LogPrint("mnbudget","CFinalizedBudget::SubmitVote - Error upon calling SetKey\n"); return; } CFinalizedBudgetVote vote(activeMasternode.vin, GetHash()); if (!vote.Sign(keyMasternode, pubKeyMasternode)) { LogPrint("mnbudget","CFinalizedBudget::SubmitVote - Failure to sign."); return; } std::string strError = ""; if (budget.UpdateFinalizedBudget(vote, NULL, strError)) { LogPrint("mnbudget","CFinalizedBudget::SubmitVote - new finalized budget vote - %s\n", vote.GetHash().ToString()); budget.mapSeenFinalizedBudgetVotes.insert(make_pair(vote.GetHash(), vote)); vote.Relay(); } else { LogPrint("mnbudget","CFinalizedBudget::SubmitVote : Error submitting vote - %s\n", strError); } } CFinalizedBudgetBroadcast::CFinalizedBudgetBroadcast() { strBudgetName = ""; nBlockStart = 0; vecBudgetPayments.clear(); mapVotes.clear(); vchSig.clear(); nFeeTXHash = 0; } CFinalizedBudgetBroadcast::CFinalizedBudgetBroadcast(const CFinalizedBudget& other) { strBudgetName = other.strBudgetName; nBlockStart = other.nBlockStart; BOOST_FOREACH (CTxBudgetPayment out, other.vecBudgetPayments) vecBudgetPayments.push_back(out); mapVotes = other.mapVotes; nFeeTXHash = other.nFeeTXHash; } CFinalizedBudgetBroadcast::CFinalizedBudgetBroadcast(std::string strBudgetNameIn, int nBlockStartIn, std::vector<CTxBudgetPayment> vecBudgetPaymentsIn, uint256 nFeeTXHashIn) { strBudgetName = strBudgetNameIn; nBlockStart = nBlockStartIn; BOOST_FOREACH (CTxBudgetPayment out, vecBudgetPaymentsIn) vecBudgetPayments.push_back(out); mapVotes.clear(); nFeeTXHash = nFeeTXHashIn; } void CFinalizedBudgetBroadcast::Relay() { CInv inv(MSG_BUDGET_FINALIZED, GetHash()); RelayInv(inv); } CFinalizedBudgetVote::CFinalizedBudgetVote() { vin = CTxIn(); nBudgetHash = 0; nTime = 0; vchSig.clear(); fValid = true; fSynced = false; } CFinalizedBudgetVote::CFinalizedBudgetVote(CTxIn vinIn, uint256 nBudgetHashIn) { vin = vinIn; nBudgetHash = nBudgetHashIn; nTime = GetAdjustedTime(); vchSig.clear(); fValid = true; fSynced = false; } void CFinalizedBudgetVote::Relay() { CInv inv(MSG_BUDGET_FINALIZED_VOTE, GetHash()); RelayInv(inv); } bool CFinalizedBudgetVote::Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode) { // Choose coins to use CPubKey pubKeyCollateralAddress; CKey keyCollateralAddress; std::string errorMessage; std::string strMessage = vin.prevout.ToStringShort() + nBudgetHash.ToString() + boost::lexical_cast<std::string>(nTime); if (!obfuScationSigner.SignMessage(strMessage, errorMessage, vchSig, keyMasternode)) { LogPrint("mnbudget","CFinalizedBudgetVote::Sign - Error upon calling SignMessage"); return false; } if (!obfuScationSigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, errorMessage)) { LogPrint("mnbudget","CFinalizedBudgetVote::Sign - Error upon calling VerifyMessage"); return false; } return true; } bool CFinalizedBudgetVote::SignatureValid(bool fSignatureCheck) { std::string errorMessage; std::string strMessage = vin.prevout.ToStringShort() + nBudgetHash.ToString() + boost::lexical_cast<std::string>(nTime); CMasternode* pmn = mnodeman.Find(vin); if (pmn == NULL) { LogPrint("mnbudget","CFinalizedBudgetVote::SignatureValid() - Unknown Masternode %s\n", strMessage); return false; } if (!fSignatureCheck) return true; if (!obfuScationSigner.VerifyMessage(pmn->pubKeyMasternode, vchSig, strMessage, errorMessage)) { LogPrint("mnbudget","CFinalizedBudgetVote::SignatureValid() - Verify message failed %s %s\n", strMessage, errorMessage); return false; } return true; } std::string CBudgetManager::ToString() const { std::ostringstream info; info << "Proposals: " << (int)mapProposals.size() << ", Budgets: " << (int)mapFinalizedBudgets.size() << ", Seen Budgets: " << (int)mapSeenMasternodeBudgetProposals.size() << ", Seen Budget Votes: " << (int)mapSeenMasternodeBudgetVotes.size() << ", Seen Final Budgets: " << (int)mapSeenFinalizedBudgets.size() << ", Seen Final Budget Votes: " << (int)mapSeenFinalizedBudgetVotes.size(); return info.str(); }
/*! @file */ #include "StdAfx.h" #include "CNative.h" //! 空っぽにする void CNative::Clear() { this->_GetMemory()->_SetRawLength(0); }
#include "duckdb/common/operator/subtract.hpp" #include "duckdb/common/operator/add.hpp" #include "duckdb/common/limits.hpp" #include "duckdb/common/types/value.hpp" #include "duckdb/common/types/interval.hpp" #include "duckdb/common/types/hugeint.hpp" #include <limits> using namespace std; namespace duckdb { //===--------------------------------------------------------------------===// // - [subtract] //===--------------------------------------------------------------------===// template <> float SubtractOperator::Operation(float left, float right) { auto result = left - right; if (!Value::FloatIsValid(result)) { throw OutOfRangeException("Overflow in subtraction of float!"); } return result; } template <> double SubtractOperator::Operation(double left, double right) { auto result = left - right; if (!Value::DoubleIsValid(result)) { throw OutOfRangeException("Overflow in subtraction of double!"); } return result; } template <> interval_t SubtractOperator::Operation(interval_t left, interval_t right) { interval_t result; result.months = left.months - right.months; result.days = left.days - right.days; result.msecs = left.msecs - right.msecs; return result; } template <> date_t SubtractOperator::Operation(date_t left, interval_t right) { right.months = -right.months; right.days = -right.days; right.msecs = -right.msecs; return AddOperator::Operation<date_t, interval_t, date_t>(left, right); } template <> timestamp_t SubtractOperator::Operation(timestamp_t left, interval_t right) { right.months = -right.months; right.days = -right.days; right.msecs = -right.msecs; return AddOperator::Operation<timestamp_t, interval_t, timestamp_t>(left, right); } template <> interval_t SubtractOperator::Operation(timestamp_t left, timestamp_t right) { return Interval::GetDifference(left, right); } //===--------------------------------------------------------------------===// // - [subtract] with overflow check //===--------------------------------------------------------------------===// struct OverflowCheckedSubtract { template <class SRCTYPE, class UTYPE> static inline bool Operation(SRCTYPE left, SRCTYPE right, SRCTYPE &result) { UTYPE uresult = SubtractOperator::Operation<UTYPE, UTYPE, UTYPE>(UTYPE(left), UTYPE(right)); if (uresult < NumericLimits<SRCTYPE>::Minimum() || uresult > NumericLimits<SRCTYPE>::Maximum()) { return false; } result = SRCTYPE(uresult); return true; } }; template <> bool TrySubtractOperator::Operation(int8_t left, int8_t right, int8_t &result) { return OverflowCheckedSubtract::Operation<int8_t, int16_t>(left, right, result); } template <> bool TrySubtractOperator::Operation(int16_t left, int16_t right, int16_t &result) { return OverflowCheckedSubtract::Operation<int16_t, int32_t>(left, right, result); } template <> bool TrySubtractOperator::Operation(int32_t left, int32_t right, int32_t &result) { return OverflowCheckedSubtract::Operation<int32_t, int64_t>(left, right, result); } template <> bool TrySubtractOperator::Operation(int64_t left, int64_t right, int64_t &result) { #if (__GNUC__ >= 5) || defined(__clang__) if (__builtin_sub_overflow(left, right, &result)) { return false; } // FIXME: this check can be removed if we get rid of NullValue<T> if (result == std::numeric_limits<int64_t>::min()) { return false; } #else if (right < 0) { if (NumericLimits<int64_t>::Maximum() + right < left) { return false; } } else { if (NumericLimits<int64_t>::Minimum() + right > left) { return false; } } result = left - right; #endif return true; } //===--------------------------------------------------------------------===// // subtract decimal with overflow check //===--------------------------------------------------------------------===// template<class T, T min, T max> bool TryDecimalSubtractTemplated(T left, T right, T &result) { if (right < 0) { if (max + right < left) { return false; } } else { if (min + right > left) { return false; } } result = left - right; return true; } template <> bool TryDecimalSubtract::Operation(int16_t left, int16_t right, int16_t &result) { return TryDecimalSubtractTemplated<int16_t, -9999, 9999>(left, right, result); } template <> bool TryDecimalSubtract::Operation(int32_t left, int32_t right, int32_t &result) { return TryDecimalSubtractTemplated<int32_t, -999999999, 999999999>(left, right, result); } template <> bool TryDecimalSubtract::Operation(int64_t left, int64_t right, int64_t &result) { return TryDecimalSubtractTemplated<int64_t, -999999999999999999, 999999999999999999>(left, right, result); } template <> bool TryDecimalSubtract::Operation(hugeint_t left, hugeint_t right, hugeint_t &result) { result = left - right; if (result <= -Hugeint::PowersOfTen[38] || result >= Hugeint::PowersOfTen[38]) { return false; } return true; } template <> hugeint_t DecimalSubtractOverflowCheck::Operation(hugeint_t left, hugeint_t right) { hugeint_t result; if (!TryDecimalSubtract::Operation(left, right, result)) { throw OutOfRangeException("Overflow in subtract of DECIMAL(38) (%s - %s);", left.ToString(), right.ToString()); } return result; } //===--------------------------------------------------------------------===// // subtract time operator //===--------------------------------------------------------------------===// template <> dtime_t SubtractTimeOperator::Operation(dtime_t left, interval_t right) { right.msecs = -right.msecs; return AddTimeOperator::Operation<dtime_t, interval_t, dtime_t>(left, right); } } // namespace duckdb
// // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/boostorg/beast // //------------------------------------------------------------------------------ // // Example: HTTP SSL server, asynchronous // //------------------------------------------------------------------------------ // #include "server_certificate.hpp" // #include <boost/beast/core.hpp> // #include <boost/beast/http.hpp> // #include <boost/beast/ssl.hpp> // #include <boost/beast/version.hpp> // #include <boost/asio/dispatch.hpp> // #include <boost/asio/strand.hpp> // #include <boost/config.hpp> // #include <algorithm> // #include <cstdlib> // #include <functional> // #include <iostream> // #include <memory> // #include <string> // #include <thread> // #include <vector> // namespace beast = boost::beast; // from <boost/beast.hpp> // namespace http = beast::http; // from <boost/beast/http.hpp> // namespace net = boost::asio; // from <boost/asio.hpp> // namespace ssl = boost::asio::ssl; // from <boost/asio/ssl.hpp> // using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp> // // Return a reasonable mime type based on the extension of a file. // beast::string_view // mime_type(beast::string_view path) // { // using beast::iequals; // auto const ext = [&path] // { // auto const pos = path.rfind("."); // if(pos == beast::string_view::npos) // return beast::string_view{}; // return path.substr(pos); // }(); // if(iequals(ext, ".htm")) return "text/html"; // if(iequals(ext, ".html")) return "text/html"; // if(iequals(ext, ".php")) return "text/html"; // if(iequals(ext, ".css")) return "text/css"; // if(iequals(ext, ".txt")) return "text/plain"; // if(iequals(ext, ".js")) return "application/javascript"; // if(iequals(ext, ".json")) return "application/json"; // if(iequals(ext, ".xml")) return "application/xml"; // if(iequals(ext, ".swf")) return "application/x-shockwave-flash"; // if(iequals(ext, ".flv")) return "video/x-flv"; // if(iequals(ext, ".png")) return "image/png"; // if(iequals(ext, ".jpe")) return "image/jpeg"; // if(iequals(ext, ".jpeg")) return "image/jpeg"; // if(iequals(ext, ".jpg")) return "image/jpeg"; // if(iequals(ext, ".gif")) return "image/gif"; // if(iequals(ext, ".bmp")) return "image/bmp"; // if(iequals(ext, ".ico")) return "image/vnd.microsoft.icon"; // if(iequals(ext, ".tiff")) return "image/tiff"; // if(iequals(ext, ".tif")) return "image/tiff"; // if(iequals(ext, ".svg")) return "image/svg+xml"; // if(iequals(ext, ".svgz")) return "image/svg+xml"; // return "application/text"; // } // // Append an HTTP rel-path to a local filesystem path. // // The returned path is normalized for the platform. // std::string // path_cat( // beast::string_view base, // beast::string_view path) // { // if(base.empty()) // return std::string(path); // std::string result(base); // #ifdef BOOST_MSVC // char constexpr path_separator = '\\'; // if(result.back() == path_separator) // result.resize(result.size() - 1); // result.append(path.data(), path.size()); // for(auto& c : result) // if(c == '/') // c = path_separator; // #else // char constexpr path_separator = '/'; // if(result.back() == path_separator) // result.resize(result.size() - 1); // result.append(path.data(), path.size()); // #endif // return result; // } // // This function produces an HTTP response for the given // // request. The type of the response object depends on the // // contents of the request, so the interface requires the // // caller to pass a generic lambda for receiving the response. // template< // class Body, class Allocator, // class Send> // void // handle_request( // beast::string_view doc_root, // http::request<Body, http::basic_fields<Allocator>>&& req, // Send&& send) // { // // Returns a bad request response // auto const bad_request = // [&req](beast::string_view why) // { // http::response<http::string_body> res{http::status::bad_request, req.version()}; // res.set(http::field::server, BOOST_BEAST_VERSION_STRING); // res.set(http::field::content_type, "text/html"); // res.keep_alive(req.keep_alive()); // res.body() = std::string(why); // res.prepare_payload(); // return res; // }; // // Returns a not found response // auto const not_found = // [&req](beast::string_view target) // { // http::response<http::string_body> res{http::status::not_found, req.version()}; // res.set(http::field::server, BOOST_BEAST_VERSION_STRING); // res.set(http::field::content_type, "text/html"); // res.keep_alive(req.keep_alive()); // res.body() = "The resource '" + std::string(target) + "' was not found."; // res.prepare_payload(); // return res; // }; // // Returns a server error response // auto const server_error = // [&req](beast::string_view what) // { // http::response<http::string_body> res{http::status::internal_server_error, req.version()}; // res.set(http::field::server, BOOST_BEAST_VERSION_STRING); // res.set(http::field::content_type, "text/html"); // res.keep_alive(req.keep_alive()); // res.body() = "An error occurred: '" + std::string(what) + "'"; // res.prepare_payload(); // return res; // }; // // Make sure we can handle the method // if( req.method() != http::verb::get && // req.method() != http::verb::head) // return send(bad_request("Unknown HTTP-method")); // // Request path must be absolute and not contain "..". // if( req.target().empty() || // req.target()[0] != '/' || // req.target().find("..") != beast::string_view::npos) // return send(bad_request("Illegal request-target")); // // Build the path to the requested file // std::string path = path_cat(doc_root, req.target()); // if(req.target().back() == '/') // path.append("index.html"); // // Attempt to open the file // beast::error_code ec; // http::file_body::value_type body; // body.open(path.c_str(), beast::file_mode::scan, ec); // // Handle the case where the file doesn't exist // if(ec == beast::errc::no_such_file_or_directory) // return send(not_found(req.target())); // // Handle an unknown error // if(ec) // return send(server_error(ec.message())); // // Cache the size since we need it after the move // auto const size = body.size(); // // Respond to HEAD request // if(req.method() == http::verb::head) // { // http::response<http::empty_body> res{http::status::ok, req.version()}; // res.set(http::field::server, BOOST_BEAST_VERSION_STRING); // res.set(http::field::content_type, mime_type(path)); // res.content_length(size); // res.keep_alive(req.keep_alive()); // return send(std::move(res)); // } // // Respond to GET request // http::response<http::file_body> res{ // std::piecewise_construct, // std::make_tuple(std::move(body)), // std::make_tuple(http::status::ok, req.version())}; // res.set(http::field::server, BOOST_BEAST_VERSION_STRING); // res.set(http::field::content_type, mime_type(path)); // res.content_length(size); // res.keep_alive(req.keep_alive()); // return send(std::move(res)); // } // //------------------------------------------------------------------------------ // // Report a failure // void // fail(beast::error_code ec, char const* what) // { // // ssl::error::stream_truncated, also known as an SSL "short read", // // indicates the peer closed the connection without performing the // // required closing handshake (for example, Google does this to // // improve performance). Generally this can be a security issue, // // but if your communication protocol is self-terminated (as // // it is with both HTTP and WebSocket) then you may simply // // ignore the lack of close_notify. // // // // https://github.com/boostorg/beast/issues/38 // // // // https://security.stackexchange.com/questions/91435/how-to-handle-a-malicious-ssl-tls-shutdown // // // // When a short read would cut off the end of an HTTP message, // // Beast returns the error beast::http::error::partial_message. // // Therefore, if we see a short read here, it has occurred // // after the message has been completed, so it is safe to ignore it. // if(ec == net::ssl::error::stream_truncated) // return; // std::cerr << what << ": " << ec.message() << "\n"; // } // // Handles an HTTP server connection // class session : public std::enable_shared_from_this<session> // { // // This is the C++11 equivalent of a generic lambda. // // The function object is used to send an HTTP message. // struct send_lambda // { // session& self_; // explicit // send_lambda(session& self) // : self_(self) // { // } // template<bool isRequest, class Body, class Fields> // void // operator()(http::message<isRequest, Body, Fields>&& msg) const // { // // The lifetime of the message has to extend // // for the duration of the async operation so // // we use a shared_ptr to manage it. // auto sp = std::make_shared< // http::message<isRequest, Body, Fields>>(std::move(msg)); // // Store a type-erased version of the shared // // pointer in the class to keep it alive. // self_.res_ = sp; // // Write the response // http::async_write( // self_.stream_, // *sp, // beast::bind_front_handler( // &session::on_write, // self_.shared_from_this(), // sp->need_eof())); // } // }; // beast::ssl_stream<beast::tcp_stream> stream_; // beast::flat_buffer buffer_; // std::shared_ptr<std::string const> doc_root_; // http::request<http::string_body> req_; // std::shared_ptr<void> res_; // send_lambda lambda_; // public: // // Take ownership of the socket // explicit // session( // tcp::socket&& socket, // ssl::context& ctx, // std::shared_ptr<std::string const> const& doc_root) // : stream_(std::move(socket), ctx) // , doc_root_(doc_root) // , lambda_(*this) // { // } // // Start the asynchronous operation // void // run() // { // // We need to be executing within a strand to perform async operations // // on the I/O objects in this session. Although not strictly necessary // // for single-threaded contexts, this example code is written to be // // thread-safe by default. // net::dispatch( // stream_.get_executor(), // beast::bind_front_handler( // &session::on_run, // shared_from_this())); // } // void // on_run() // { // // Set the timeout. // beast::get_lowest_layer(stream_).expires_after( // std::chrono::seconds(30)); // // Perform the SSL handshake // stream_.async_handshake( // ssl::stream_base::server, // beast::bind_front_handler( // &session::on_handshake, // shared_from_this())); // } // void // on_handshake(beast::error_code ec) // { // if(ec) // return fail(ec, "handshake"); // do_read(); // } // void // do_read() // { // // Make the request empty before reading, // // otherwise the operation behavior is undefined. // req_ = {}; // // Set the timeout. // beast::get_lowest_layer(stream_).expires_after(std::chrono::seconds(30)); // // Read a request // http::async_read(stream_, buffer_, req_, // beast::bind_front_handler( // &session::on_read, // shared_from_this())); // } // void // on_read( // beast::error_code ec, // std::size_t bytes_transferred) // { // boost::ignore_unused(bytes_transferred); // // This means they closed the connection // if(ec == http::error::end_of_stream) // return do_close(); // if(ec) // return fail(ec, "read"); // // Send the response // handle_request(*doc_root_, std::move(req_), lambda_); // } // void // on_write( // bool close, // beast::error_code ec, // std::size_t bytes_transferred) // { // boost::ignore_unused(bytes_transferred); // if(ec) // return fail(ec, "write"); // if(close) // { // // This means we should close the connection, usually because // // the response indicated the "Connection: close" semantic. // return do_close(); // } // // We're done with the response so delete it // res_ = nullptr; // // Read another request // do_read(); // } // void // do_close() // { // // Set the timeout. // beast::get_lowest_layer(stream_).expires_after(std::chrono::seconds(30)); // // Perform the SSL shutdown // stream_.async_shutdown( // beast::bind_front_handler( // &session::on_shutdown, // shared_from_this())); // } // void // on_shutdown(beast::error_code ec) // { // if(ec) // return fail(ec, "shutdown"); // // At this point the connection is closed gracefully // } // }; // //------------------------------------------------------------------------------ // // Accepts incoming connections and launches the sessions // class listener : public std::enable_shared_from_this<listener> // { // net::io_context& ioc_; // ssl::context& ctx_; // tcp::acceptor acceptor_; // std::shared_ptr<std::string const> doc_root_; // public: // listener( // net::io_context& ioc, // ssl::context& ctx, // tcp::endpoint endpoint, // std::shared_ptr<std::string const> const& doc_root) // : ioc_(ioc) // , ctx_(ctx) // , acceptor_(ioc) // , doc_root_(doc_root) // { // beast::error_code ec; // // Open the acceptor // acceptor_.open(endpoint.protocol(), ec); // if(ec) // { // fail(ec, "open"); // return; // } // // Allow address reuse // acceptor_.set_option(net::socket_base::reuse_address(true), ec); // if(ec) // { // fail(ec, "set_option"); // return; // } // // Bind to the server address // acceptor_.bind(endpoint, ec); // if(ec) // { // fail(ec, "bind"); // return; // } // // Start listening for connections // acceptor_.listen( // net::socket_base::max_listen_connections, ec); // if(ec) // { // fail(ec, "listen"); // return; // } // } // // Start accepting incoming connections // void // run() // { // do_accept(); // } // private: // void // do_accept() // { // // The new connection gets its own strand // acceptor_.async_accept( // net::make_strand(ioc_), // beast::bind_front_handler( // &listener::on_accept, // shared_from_this())); // } // void // on_accept(beast::error_code ec, tcp::socket socket) // { // if(ec) // { // fail(ec, "accept"); // } // else // { // // Create the session and run it // std::make_shared<session>( // std::move(socket), // ctx_, // doc_root_)->run(); // } // // Accept another connection // do_accept(); // } // }; //------------------------------------------------------------------------------ int main(int argc, char* argv[]) { // // Check command line arguments. // if (argc != 5) // { // std::cerr << // "Usage: http-server-async-ssl <address> <port> <doc_root> <threads>\n" << // "Example:\n" << // " http-server-async-ssl 0.0.0.0 8080 . 1\n"; // return EXIT_FAILURE; // } // auto const address = net::ip::make_address(argv[1]); // auto const port = static_cast<unsigned short>(std::atoi(argv[2])); // auto const doc_root = std::make_shared<std::string>(argv[3]); // auto const threads = std::max<int>(1, std::atoi(argv[4])); // // The io_context is required for all I/O // net::io_context ioc{threads}; // // The SSL context is required, and holds certificates // ssl::context ctx{ssl::context::tlsv12}; // // This holds the self-signed certificate used by the server // load_server_certificate(ctx); // // Create and launch a listening port // std::make_shared<listener>( // ioc, // ctx, // tcp::endpoint{address, port}, // doc_root)->run(); // // Run the I/O service on the requested number of threads // std::vector<std::thread> v; // v.reserve(threads - 1); // for(auto i = threads - 1; i > 0; --i) // v.emplace_back( // [&ioc] // { // ioc.run(); // }); // ioc.run(); }
#include <vector> #include <string> class Car { public: Car (const std::string& mark, const std::string& number, int fuel, int engineVolume, int speed): m_mark(mark), m_number(number), m_fuel(fuel), m_engineVolume (engineVolume), m_speed(speed) {} std::string getNumber() const {return m_number;} bool emptyFuel() const {return m_fuel==0;} int getFuel() const {return m_fuel;} void fuel (int fuel) {m_fuel+=fuel;} int getSpeed() const { return m_speed; } void setSpeed (int speed) { if(speed>=0) m_speed = speed; } std::string info()const { return mark + " " + number + " fuel: " + std::to_string(fuel); } private: std::string m_mark; std::string m_number; int m_fuel; int m_engineVolume; int m_speed; }; //Класс для автопарка class AutoPark { public: void addCar (const Car& car); bool removeCar (const std::string& number); void fuelCar (const std::string& number, int fuel); static void carInfo(const Car &car); Car* getCar(int distance); ~AutoPark() { for (Car*& car:m_cars) { delete car; car = nullptr; } } static AutoPark* createAutoPark (int count); private: std::vector<Car*> m_cars; }; void Car::addCar(const Car& car) { if (car.emptyFuel()) m_cars.push_back(&car); else throw std::invalid_argument("Car is not empty"); } bool Car::removeCar (const std::string& number) { for (auto & it = storage.begin(); it != storage.end(); ++it) if ((*it)->getNumber() == number) { storage.erase(it); return true; } return false; } void Car::fuelCar (const std::string& number, int fuel) { for (Car* car: m_cars) { if (car->getNumber() == number) { car->fuel (fuel); return; } } std::cout << "No car found" <<std::endl; // better throw } Car* Car::getCar(int distance) { for (Car* car: m_cars) { if (car->getNumber() == number) { car->fuel (fuel); return; } } return nullptr; } AutoPark* AutoPark::createAutoPark (int count) { AutoPark* park = new AutoPark; for (int i=0; i<count; i++) { Car * car = new Car("Volvo", std::to_string(i+1), 0, 100, 120); park.addCar (car); } return park; } //×èòàòü: óêàçàòåëè è ññûëêè, ãåòòåðû è ñåòòåðû
#include "BehaviourCreator.h" #include "ConditionCreator.h" #include "ConstraintCreator.h" #include <alica_tests/ConstraintTestPlanDummySolver.h> #include <alica_tests/TestWorldModel.h> #include "UtilityFunctionCreator.h" #include <communication/AlicaDummyCommunication.h> #include <engine/AlicaClock.h> #include <engine/AlicaContext.h> #include <engine/AlicaEngine.h> #include <gtest/gtest.h> #include <ros/ros.h> #include <csetjmp> #include <csignal> #include <string> #include <yaml-cpp/yaml.h> #include "test_alica.h" namespace alica { namespace { class AlicaTestYamlConfig : public AlicaTestFixture { const char *getMasterPlanName() const override { return "MasterPlan"; }; void TestBody() override { this->SetUp(); }; }; } void printNode(const YAML::Node& node, int depth) { for (YAML::const_iterator it = node.begin(); it != node.end(); ++it){ std::cerr << std::string(depth * 2, ' '); if (it->second.IsScalar()) { std::cerr << it->first << ": " << it->second << std::endl; } else { std::cerr << it->first << std::endl; printNode(it->second, depth + 1); } } } TEST_F(AlicaTestYamlConfig, CheckConfigInitialization) { SetUp(); const YAML::Node& node = ac->getConfig(); printNode(node, 0); //Check if config has been initialized correctly EXPECT_EQ(false, node["Local"]["IsGoalie"].as<bool>()); EXPECT_EQ(9, node["Local"]["ID"].as<int>()); EXPECT_EQ(3000.0f, node["Local"]["MaxTranslation"].as<float>()); EXPECT_EQ(30, node["Alica"]["EngineFrequency"].as<int>()); EXPECT_EQ("plans", node["Alica"]["PlanDir"].as<std::string>()); EXPECT_EQ(45, node["Alica"]["CycleDetection"]["HistorySize"].as<int>()); } } //namespace alica
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Author: jefftk@google.com (Jeff Kaufman) #include "ngx_rewrite_options.h" extern "C" { #include <ngx_config.h> #include <ngx_core.h> #include <ngx_http.h> } #include "ngx_pagespeed.h" #include "ngx_rewrite_driver_factory.h" #include "net/instaweb/public/version.h" #include "net/instaweb/rewriter/public/file_load_policy.h" #include "net/instaweb/rewriter/public/rewrite_options.h" #include "net/instaweb/system/public/system_caches.h" #include "net/instaweb/util/public/message_handler.h" #include "net/instaweb/util/public/timer.h" namespace net_instaweb { namespace { const char kStatisticsPath[] = "StatisticsPath"; const char kGlobalStatisticsPath[] = "GlobalStatisticsPath"; const char kConsolePath[] = "ConsolePath"; const char kMessagesPath[] = "MessagesPath"; const char kAdminPath[] = "AdminPath"; const char kGlobalAdminPath[] = "GlobalAdminPath"; // These options are copied from mod_instaweb.cc, where APACHE_CONFIG_OPTIONX // indicates that they can not be set at the directory/location level. They set // options in the RewriteDriverFactory, so they're entirely global and do not // appear in RewriteOptions. They are not alphabetized on purpose, but rather // left in the same order as in mod_instaweb.cc in case we end up needing to // compare. // TODO(oschaaf): this duplication is a short term solution. const char* const server_only_options[] = { "FetcherTimeoutMs", "FetchProxy", "ForceCaching", "GeneratedFilePrefix", "ImgMaxRewritesAtOnce", "InheritVHostConfig", "InstallCrashHandler", "MessageBufferSize", "NumRewriteThreads", "NumExpensiveRewriteThreads", "StaticAssetPrefix", "TrackOriginalContentLength", "UsePerVHostStatistics", // TODO(anupama): What to do about "No longer used" "BlockingRewriteRefererUrls", "CreateSharedMemoryMetadataCache", "LoadFromFile", "LoadFromFileMatch", "LoadFromFileRule", "LoadFromFileRuleMatch", "UseNativeFetcher" }; // Options that can only be used in the main (http) option scope. const char* const main_only_options[] = { "UseNativeFetcher" }; } // namespace RewriteOptions::Properties* NgxRewriteOptions::ngx_properties_ = NULL; NgxRewriteOptions::NgxRewriteOptions(const StringPiece& description, ThreadSystem* thread_system) : SystemRewriteOptions(description, thread_system) { Init(); } NgxRewriteOptions::NgxRewriteOptions(ThreadSystem* thread_system) : SystemRewriteOptions(thread_system) { Init(); } void NgxRewriteOptions::Init() { DCHECK(ngx_properties_ != NULL) << "Call NgxRewriteOptions::Initialize() before construction"; clear_inherited_scripts_ = false; InitializeOptions(ngx_properties_); } void NgxRewriteOptions::AddProperties() { // Nginx-specific options. add_ngx_option( "", &NgxRewriteOptions::statistics_path_, "nsp", kStatisticsPath, kServerScope, "Set the statistics path. Ex: /ngx_pagespeed_statistics"); add_ngx_option( "", &NgxRewriteOptions::global_statistics_path_, "ngsp", kGlobalStatisticsPath, kProcessScope, "Set the global statistics path. Ex: /ngx_pagespeed_global_statistics"); add_ngx_option( "", &NgxRewriteOptions::console_path_, "ncp", kConsolePath, kServerScope, "Set the console path. Ex: /pagespeed_console"); add_ngx_option( "", &NgxRewriteOptions::messages_path_, "nmp", kMessagesPath, kServerScope, "Set the messages path. Ex: /ngx_pagespeed_message"); add_ngx_option( "", &NgxRewriteOptions::admin_path_, "nap", kAdminPath, kServerScope, "Set the admin path. Ex: /pagespeed_admin"); add_ngx_option( "", &NgxRewriteOptions::global_admin_path_, "ngap", kGlobalAdminPath, kProcessScope, "Set the global admin path. Ex: /pagespeed_global_admin"); MergeSubclassProperties(ngx_properties_); // Default properties are global but to set them the current API requires // a RewriteOptions instance and we're in a static method. NgxRewriteOptions dummy_config(NULL); dummy_config.set_default_x_header_value(kModPagespeedVersion); } void NgxRewriteOptions::Initialize() { if (Properties::Initialize(&ngx_properties_)) { SystemRewriteOptions::Initialize(); AddProperties(); } } void NgxRewriteOptions::Terminate() { if (Properties::Terminate(&ngx_properties_)) { SystemRewriteOptions::Terminate(); } } bool NgxRewriteOptions::IsDirective(StringPiece config_directive, StringPiece compare_directive) { return StringCaseEqual(config_directive, compare_directive); } RewriteOptions::OptionScope NgxRewriteOptions::GetOptionScope( StringPiece option_name) { ngx_uint_t i; ngx_uint_t size = sizeof(main_only_options) / sizeof(char*); for (i = 0; i < size; i++) { if (StringCaseEqual(main_only_options[i], option_name)) { return kProcessScopeStrict; } } size = sizeof(server_only_options) / sizeof(char*); for (i = 0; i < size; i++) { if (StringCaseEqual(server_only_options[i], option_name)) { return kServerScope; } } // This could be made more efficient if RewriteOptions provided a map allowing // access of options by their name. It's not too much of a worry at present // since this is just during initialization. for (OptionBaseVector::const_iterator it = all_options().begin(); it != all_options().end(); ++it) { RewriteOptions::OptionBase* option = *it; if (option->option_name() == option_name) { // We treat kProcessScope as kProcessScopeStrict, failing to start if an // option is out of place. return option->scope() == kProcessScope ? kProcessScopeStrict : option->scope(); } } return kDirectoryScope; } RewriteOptions::OptionSettingResult NgxRewriteOptions::ParseAndSetOptions0( StringPiece directive, GoogleString* msg, MessageHandler* handler) { if (IsDirective(directive, "on")) { set_enabled(RewriteOptions::kEnabledOn); } else if (IsDirective(directive, "off")) { set_enabled(RewriteOptions::kEnabledOff); } else if (IsDirective(directive, "unplugged")) { set_enabled(RewriteOptions::kEnabledUnplugged); } else { return RewriteOptions::kOptionNameUnknown; } return RewriteOptions::kOptionOk; } RewriteOptions::OptionSettingResult NgxRewriteOptions::ParseAndSetOptionFromName1( StringPiece name, StringPiece arg, GoogleString* msg, MessageHandler* handler) { // FileCachePath needs error checking. if (StringCaseEqual(name, kFileCachePath)) { if (!StringCaseStartsWith(arg, "/")) { *msg = "must start with a slash"; return RewriteOptions::kOptionValueInvalid; } } return SystemRewriteOptions::ParseAndSetOptionFromName1( name, arg, msg, handler); } template <class DriverFactoryT> RewriteOptions::OptionSettingResult ParseAndSetOptionHelper( StringPiece option_value, DriverFactoryT* driver_factory, void (DriverFactoryT::*set_option_method)(bool)) { bool parsed_value; if (StringCaseEqual(option_value, "on") || StringCaseEqual(option_value, "true")) { parsed_value = true; } else if (StringCaseEqual(option_value, "off") || StringCaseEqual(option_value, "false")) { parsed_value = false; } else { return RewriteOptions::kOptionValueInvalid; } (driver_factory->*set_option_method)(parsed_value); return RewriteOptions::kOptionOk; } namespace { const char* ps_error_string_for_option( ngx_pool_t* pool, StringPiece directive, StringPiece warning) { GoogleString msg = StrCat("\"", directive, "\" ", warning); char* s = string_piece_to_pool_string(pool, msg); if (s == NULL) { return "failed to allocate memory"; } return s; } } // namespace // Very similar to apache/mod_instaweb::ParseDirective. const char* NgxRewriteOptions::ParseAndSetOptions( StringPiece* args, int n_args, ngx_pool_t* pool, MessageHandler* handler, NgxRewriteDriverFactory* driver_factory, RewriteOptions::OptionScope scope, ngx_conf_t* cf, bool compile_scripts) { CHECK_GE(n_args, 1); StringPiece directive = args[0]; // Remove initial "ModPagespeed" if there is one. StringPiece mod_pagespeed("ModPagespeed"); if (StringCaseStartsWith(directive, mod_pagespeed)) { directive.remove_prefix(mod_pagespeed.size()); } if (GetOptionScope(directive) > scope) { return ps_error_string_for_option( pool, directive, "cannot be set at this scope."); } ScriptLine* script_line; script_line = NULL; // Only allow script variable support for LoadFromFile for now. // Note that LoadFromFile should not be scriptable on wildcard hosts, // as browsers might be able to manipulate its natural use-case: $http_host. if (!StringCaseStartsWith(directive, "LoadFromFile")) { compile_scripts = false; } if (n_args == 1 && StringCaseEqual(directive, "ClearInheritedScripts")) { clear_inherited_scripts_ = true; return NGX_CONF_OK; } if (compile_scripts) { CHECK(cf != NULL); int i; // Skip the first arg which is always 'pagespeed' for (i = 1; i < n_args; i++) { ngx_str_t script_source; script_source.len = args[i].as_string().length(); std::string tmp = args[i].as_string(); script_source.data = reinterpret_cast<u_char*>( const_cast<char*>(tmp.c_str())); if (ngx_http_script_variables_count(&script_source) > 0) { ngx_http_script_compile_t* sc = reinterpret_cast<ngx_http_script_compile_t*>( ngx_pcalloc(cf->pool, sizeof(ngx_http_script_compile_t))); sc->cf = cf; sc->source = &script_source; sc->lengths = reinterpret_cast<ngx_array_t**>( ngx_pcalloc(cf->pool, sizeof(ngx_array_t*))); sc->values = reinterpret_cast<ngx_array_t**>( ngx_pcalloc(cf->pool, sizeof(ngx_array_t*))); sc->variables = 1; sc->complete_lengths = 1; sc->complete_values = 1; if (ngx_http_script_compile(sc) != NGX_OK) { return ps_error_string_for_option( pool, directive, "Failed to compile script variables"); } else { if (script_line == NULL) { script_line = new ScriptLine(args, n_args, scope); } script_line->AddScriptAndArgIndex(sc, i); } } } if (script_line != NULL) { script_lines_.push_back(RefCountedPtr<ScriptLine>(script_line)); // We have found script variables in the current configuration line, and // prepared the associated rewriteoptions for that. // We will defer parsing, validation and processing of this line to // request time. That means we are done handling this configuration line. return NGX_CONF_OK; } } GoogleString msg; OptionSettingResult result; if (n_args == 1) { result = ParseAndSetOptions0(directive, &msg, handler); } else if (n_args == 2) { StringPiece arg = args[1]; // TODO(morlovich): Remove these special hacks, and handle these via // ParseAndSetOptionFromEnum1. if (IsDirective(directive, "UsePerVHostStatistics")) { result = ParseAndSetOptionHelper<NgxRewriteDriverFactory>( arg, driver_factory, &NgxRewriteDriverFactory::set_use_per_vhost_statistics); } else if (IsDirective(directive, "InstallCrashHandler")) { result = ParseAndSetOptionHelper<NgxRewriteDriverFactory>( arg, driver_factory, &NgxRewriteDriverFactory::set_install_crash_handler); } else if (IsDirective(directive, "MessageBufferSize")) { int message_buffer_size; bool ok = StringToInt(arg.as_string(), &message_buffer_size); if (ok && message_buffer_size >= 0) { driver_factory->set_message_buffer_size(message_buffer_size); result = RewriteOptions::kOptionOk; } else { result = RewriteOptions::kOptionValueInvalid; } } else if (IsDirective(directive, "UseNativeFetcher")) { result = ParseAndSetOptionHelper<NgxRewriteDriverFactory>( arg, driver_factory, &NgxRewriteDriverFactory::set_use_native_fetcher); } else if (IsDirective(directive, "RateLimitBackgroundFetches")) { result = ParseAndSetOptionHelper<NgxRewriteDriverFactory>( arg, driver_factory, &NgxRewriteDriverFactory::set_rate_limit_background_fetches); } else if (IsDirective(directive, "ForceCaching")) { result = ParseAndSetOptionHelper<SystemRewriteDriverFactory>( arg, driver_factory, &SystemRewriteDriverFactory::set_force_caching); } else if (IsDirective(directive, "ListOutstandingUrlsOnError")) { result = ParseAndSetOptionHelper<SystemRewriteDriverFactory>( arg, driver_factory, &SystemRewriteDriverFactory::list_outstanding_urls_on_error); } else if (IsDirective(directive, "TrackOriginalContentLength")) { result = ParseAndSetOptionHelper<SystemRewriteDriverFactory>( arg, driver_factory, &SystemRewriteDriverFactory::set_track_original_content_length); } else if (IsDirective(directive, "StaticAssetPrefix")) { driver_factory->set_static_asset_prefix(arg); result = RewriteOptions::kOptionOk; } else if (StringCaseEqual("ProcessScriptVariables", args[0])) { if (scope == RewriteOptions::kProcessScopeStrict) { if (StringCaseEqual(arg, "on")) { if (driver_factory->SetProcessScriptVariables(true)) { result = RewriteOptions::kOptionOk; } else { return const_cast<char*>( "pagespeed ProcessScriptVariables: can only be set once"); } } else if (StringCaseEqual(arg, "off")) { if (driver_factory->SetProcessScriptVariables(false)) { result = RewriteOptions::kOptionOk; } else { return const_cast<char*>( "pagespeed ProcessScriptVariables: can only be set once"); } } else { return const_cast<char*>( "pagespeed ProcessScriptVariables: invalid value"); } } else { return const_cast<char*>( "ProcessScriptVariables is only allowed at the top level"); } } else { result = ParseAndSetOptionFromName1(directive, arg, &msg, handler); } } else if (n_args == 3) { // Short-term special handling, until this moves to common code. // TODO(morlovich): Clean this up. if (StringCaseEqual(directive, "CreateSharedMemoryMetadataCache")) { int64 kb = 0; if (!StringToInt64(args[2], &kb) || kb < 0) { result = RewriteOptions::kOptionValueInvalid; msg = "size_kb must be a positive 64-bit integer"; } else { bool ok = driver_factory->caches()->CreateShmMetadataCache( args[1].as_string(), kb, &msg); result = ok ? kOptionOk : kOptionValueInvalid; } } else { result = ParseAndSetOptionFromName2(directive, args[1], args[2], &msg, handler); } } else if (n_args == 4) { result = ParseAndSetOptionFromName3( directive, args[1], args[2], args[3], &msg, handler); } else { return ps_error_string_for_option( pool, directive, "not recognized or too many arguments"); } switch (result) { case RewriteOptions::kOptionOk: return NGX_CONF_OK; case RewriteOptions::kOptionNameUnknown: return ps_error_string_for_option( pool, directive, "not recognized or too many arguments"); case RewriteOptions::kOptionValueInvalid: { GoogleString full_directive; for (int i = 0 ; i < n_args ; i++) { StrAppend(&full_directive, i == 0 ? "" : " ", args[i]); } return ps_error_string_for_option(pool, full_directive, msg); } } CHECK(false); return NULL; } // Execute all entries in the script_lines vector, and hand the result off to // ParseAndSetOptions to obtain the final option values. bool NgxRewriteOptions::ExecuteScriptVariables( ngx_http_request_t* r, MessageHandler* handler, NgxRewriteDriverFactory* driver_factory) { bool script_error = false; if (script_lines_.size() > 0) { std::vector<RefCountedPtr<ScriptLine> >::iterator it; for (it = script_lines_.begin() ; it != script_lines_.end(); ++it) { ScriptLine* script_line = it->get(); StringPiece args[NGX_PAGESPEED_MAX_ARGS]; std::vector<ScriptArgIndex*>::iterator cs_it; int i; for (i = 0; i < script_line->n_args(); i++) { args[i] = script_line->args()[i]; } for (cs_it = script_line->data().begin(); cs_it != script_line->data().end(); cs_it++) { ngx_http_script_compile_t* script; ngx_array_t* values; ngx_array_t* lengths; ngx_str_t value; script = (*cs_it)->script(); lengths = *script->lengths; values = *script->values; if (ngx_http_script_run(r, &value, lengths->elts, 0, values->elts) == NULL) { handler->Message(kError, "ngx_http_script_run error"); script_error = true; break; } else { args[(*cs_it)->index()] = str_to_string_piece(value); } } const char* status = ParseAndSetOptions(args, script_line->n_args(), r->pool, handler, driver_factory, script_line->scope(), NULL /*cf*/, false /*compile scripts*/); if (status != NULL) { script_error = true; handler->Message(kWarning, "Error setting option value from script: '%s'", status); break; } } } if (script_error) { handler->Message(kWarning, "Script error(s) in configuration, disabling optimization"); set_enabled(RewriteOptions::kEnabledOff); return false; } return true; } void NgxRewriteOptions::CopyScriptLinesTo( NgxRewriteOptions* destination) const { destination->script_lines_ = script_lines_; } void NgxRewriteOptions::AppendScriptLinesTo( NgxRewriteOptions* destination) const { destination->script_lines_.insert(destination->script_lines_.end(), script_lines_.begin(), script_lines_.end()); } NgxRewriteOptions* NgxRewriteOptions::Clone() const { NgxRewriteOptions* options = new NgxRewriteOptions( StrCat("cloned from ", description()), thread_system()); this->CopyScriptLinesTo(options); options->Merge(*this); return options; } void NgxRewriteOptions::Merge(const RewriteOptions& src) { SystemRewriteOptions::Merge(src); } const NgxRewriteOptions* NgxRewriteOptions::DynamicCast( const RewriteOptions* instance) { return dynamic_cast<const NgxRewriteOptions*>(instance); } NgxRewriteOptions* NgxRewriteOptions::DynamicCast(RewriteOptions* instance) { return dynamic_cast<NgxRewriteOptions*>(instance); } } // namespace net_instaweb
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.Collections.Generic.ICollection`1 #include "System/Collections/Generic/ICollection_1.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" #include "beatsaber-hook/shared/utils/typedefs-array.hpp" #include "beatsaber-hook/shared/utils/typedefs-string.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: List`1<T> template<typename T> class List_1; // Forward declaring type: IEnumerator`1<T> template<typename T> class IEnumerator_1; } // Forward declaring namespace: System::Net::Http::Headers namespace System::Net::Http::Headers { // Forward declaring type: HttpHeaders class HttpHeaders; // Forward declaring type: HeaderInfo class HeaderInfo; } // Forward declaring namespace: System::Collections namespace System::Collections { // Forward declaring type: IEnumerator class IEnumerator; } // Forward declaring namespace: System namespace System { // Forward declaring type: Predicate`1<T> template<typename T> class Predicate_1; } // Completed forward declares // Type namespace: System.Net.Http.Headers namespace System::Net::Http::Headers { // Forward declaring type: HttpHeaderValueCollection`1<T> template<typename T> class HttpHeaderValueCollection_1; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE_GENERIC_CLASS(::System::Net::Http::Headers::HttpHeaderValueCollection_1, "System.Net.Http.Headers", "HttpHeaderValueCollection`1"); // Type namespace: System.Net.Http.Headers namespace System::Net::Http::Headers { // WARNING Size may be invalid! // Autogenerated type: System.Net.Http.Headers.HttpHeaderValueCollection`1 // [TokenAttribute] Offset: FFFFFFFF template<typename T> class HttpHeaderValueCollection_1 : public ::Il2CppObject/*, public ::System::Collections::Generic::ICollection_1<T>*/ { public: #ifdef USE_CODEGEN_FIELDS public: #else #ifdef CODEGEN_FIELD_ACCESSIBILITY CODEGEN_FIELD_ACCESSIBILITY: #else protected: #endif #endif // private readonly System.Collections.Generic.List`1<T> list // Size: 0x8 // Offset: 0x0 ::System::Collections::Generic::List_1<T>* list; // Field size check static_assert(sizeof(::System::Collections::Generic::List_1<T>*) == 0x8); // private readonly System.Net.Http.Headers.HttpHeaders headers // Size: 0x8 // Offset: 0x0 ::System::Net::Http::Headers::HttpHeaders* headers; // Field size check static_assert(sizeof(::System::Net::Http::Headers::HttpHeaders*) == 0x8); // private readonly System.Net.Http.Headers.HeaderInfo headerInfo // Size: 0x8 // Offset: 0x0 ::System::Net::Http::Headers::HeaderInfo* headerInfo; // Field size check static_assert(sizeof(::System::Net::Http::Headers::HeaderInfo*) == 0x8); // private System.Collections.Generic.List`1<System.String> invalidValues // Size: 0x8 // Offset: 0x0 ::System::Collections::Generic::List_1<::StringW>* invalidValues; // Field size check static_assert(sizeof(::System::Collections::Generic::List_1<::StringW>*) == 0x8); public: // Creating interface conversion operator: operator ::System::Collections::Generic::ICollection_1<T> operator ::System::Collections::Generic::ICollection_1<T>() noexcept { return *reinterpret_cast<::System::Collections::Generic::ICollection_1<T>*>(this); } // Autogenerated instance field getter // Get instance field: private readonly System.Collections.Generic.List`1<T> list ::System::Collections::Generic::List_1<T>*& dyn_list() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Net::Http::Headers::HttpHeaderValueCollection_1::dyn_list"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "list"))->offset; return *reinterpret_cast<::System::Collections::Generic::List_1<T>**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private readonly System.Net.Http.Headers.HttpHeaders headers ::System::Net::Http::Headers::HttpHeaders*& dyn_headers() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Net::Http::Headers::HttpHeaderValueCollection_1::dyn_headers"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "headers"))->offset; return *reinterpret_cast<::System::Net::Http::Headers::HttpHeaders**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private readonly System.Net.Http.Headers.HeaderInfo headerInfo ::System::Net::Http::Headers::HeaderInfo*& dyn_headerInfo() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Net::Http::Headers::HttpHeaderValueCollection_1::dyn_headerInfo"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "headerInfo"))->offset; return *reinterpret_cast<::System::Net::Http::Headers::HeaderInfo**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Collections.Generic.List`1<System.String> invalidValues ::System::Collections::Generic::List_1<::StringW>*& dyn_invalidValues() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Net::Http::Headers::HttpHeaderValueCollection_1::dyn_invalidValues"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "invalidValues"))->offset; return *reinterpret_cast<::System::Collections::Generic::List_1<::StringW>**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // public System.Int32 get_Count() // Offset: 0xFFFFFFFFFFFFFFFF int get_Count() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Net::Http::Headers::HttpHeaderValueCollection_1::get_Count"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Count", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method); } // System.Collections.Generic.List`1<System.String> get_InvalidValues() // Offset: 0xFFFFFFFFFFFFFFFF ::System::Collections::Generic::List_1<::StringW>* get_InvalidValues() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Net::Http::Headers::HttpHeaderValueCollection_1::get_InvalidValues"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_InvalidValues", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::Generic::List_1<::StringW>*, false>(this, ___internal__method); } // public System.Boolean get_IsReadOnly() // Offset: 0xFFFFFFFFFFFFFFFF bool get_IsReadOnly() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Net::Http::Headers::HttpHeaderValueCollection_1::get_IsReadOnly"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_IsReadOnly", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method); } // System.Void .ctor(System.Net.Http.Headers.HttpHeaders headers, System.Net.Http.Headers.HeaderInfo headerInfo) // Offset: 0xFFFFFFFFFFFFFFFF template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static HttpHeaderValueCollection_1<T>* New_ctor(::System::Net::Http::Headers::HttpHeaders* headers, ::System::Net::Http::Headers::HeaderInfo* headerInfo) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Net::Http::Headers::HttpHeaderValueCollection_1::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<HttpHeaderValueCollection_1<T>*, creationType>(headers, headerInfo))); } // public System.Void Add(T item) // Offset: 0xFFFFFFFFFFFFFFFF void Add(T item) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Net::Http::Headers::HttpHeaderValueCollection_1::Add"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Add", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(item)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, item); } // System.Void AddRange(System.Collections.Generic.List`1<T> values) // Offset: 0xFFFFFFFFFFFFFFFF void AddRange(::System::Collections::Generic::List_1<T>* values) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Net::Http::Headers::HttpHeaderValueCollection_1::AddRange"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "AddRange", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(values)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, values); } // System.Void AddInvalidValue(System.String invalidValue) // Offset: 0xFFFFFFFFFFFFFFFF void AddInvalidValue(::StringW invalidValue) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Net::Http::Headers::HttpHeaderValueCollection_1::AddInvalidValue"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "AddInvalidValue", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(invalidValue)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, invalidValue); } // public System.Void Clear() // Offset: 0xFFFFFFFFFFFFFFFF void Clear() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Net::Http::Headers::HttpHeaderValueCollection_1::Clear"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Clear", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method); } // public System.Boolean Contains(T item) // Offset: 0xFFFFFFFFFFFFFFFF bool Contains(T item) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Net::Http::Headers::HttpHeaderValueCollection_1::Contains"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Contains", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(item)}))); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, item); } // public System.Void CopyTo(T[] array, System.Int32 arrayIndex) // Offset: 0xFFFFFFFFFFFFFFFF void CopyTo(::ArrayW<T> array, int arrayIndex) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Net::Http::Headers::HttpHeaderValueCollection_1::CopyTo"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "CopyTo", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(array), ::il2cpp_utils::ExtractType(arrayIndex)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, array, arrayIndex); } // public System.Boolean Remove(T item) // Offset: 0xFFFFFFFFFFFFFFFF bool Remove(T item) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Net::Http::Headers::HttpHeaderValueCollection_1::Remove"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Remove", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(item)}))); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, item); } // public System.Collections.Generic.IEnumerator`1<T> GetEnumerator() // Offset: 0xFFFFFFFFFFFFFFFF ::System::Collections::Generic::IEnumerator_1<T>* GetEnumerator() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Net::Http::Headers::HttpHeaderValueCollection_1::GetEnumerator"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "GetEnumerator", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::Generic::IEnumerator_1<T>*, false>(this, ___internal__method); } // private System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() // Offset: 0xFFFFFFFFFFFFFFFF ::System::Collections::IEnumerator* System_Collections_IEnumerable_GetEnumerator() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Net::Http::Headers::HttpHeaderValueCollection_1::System.Collections.IEnumerable.GetEnumerator"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "System.Collections.IEnumerable.GetEnumerator", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::IEnumerator*, false>(this, ___internal__method); } // T Find(System.Predicate`1<T> predicate) // Offset: 0xFFFFFFFFFFFFFFFF T Find(::System::Predicate_1<T>* predicate) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Net::Http::Headers::HttpHeaderValueCollection_1::Find"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Find", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(predicate)}))); return ::il2cpp_utils::RunMethodRethrow<T, false>(this, ___internal__method, predicate); } // public override System.String ToString() // Offset: 0xFFFFFFFFFFFFFFFF // Implemented from: System.Object // Base method: System.String Object::ToString() ::StringW ToString() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Net::Http::Headers::HttpHeaderValueCollection_1::ToString"); auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "ToString", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(this, ___internal__method); } }; // System.Net.Http.Headers.HttpHeaderValueCollection`1 // Could not write size check! Type: System.Net.Http.Headers.HttpHeaderValueCollection`1 is generic, or has no fields that are valid for size checks! } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "mbr-device.h" #include <fuchsia/hardware/block/c/banjo.h> #include <fuchsia/hardware/block/partition/c/banjo.h> #include <inttypes.h> #include <lib/ddk/debug.h> #include <lib/ddk/device.h> #include <lib/ddk/driver.h> #include <lib/sync/completion.h> #include <lib/zx/vmo.h> #include <string.h> #include <zircon/assert.h> #include <zircon/compiler.h> #include <zircon/errors.h> #include <zircon/hw/gpt.h> #include <zircon/status.h> #include <zircon/threads.h> #include <zircon/types.h> #include <algorithm> #include <memory> #include <utility> #include <fbl/alloc_checker.h> #include <fbl/string.h> #include <fbl/vector.h> #include <gpt/c/gpt.h> #include "mbr.h" #include "src/devices/block/drivers/mbr/mbr_bind.h" namespace { // ATTN: MBR supports 8 bit partition types instead of GUIDs. Here we define // mappings between partition type and GUIDs that zircon understands. When // the MBR driver receives a request for the type GUID, we lie and return the // a mapping from partition type to type GUID. const uint8_t kDataGuid[GPT_GUID_LEN] = GUID_DATA_VALUE; const uint8_t kSysGuid[GPT_GUID_LEN] = GUID_SYSTEM_VALUE; const uint8_t kMicrosoftDataGuid[GPT_GUID_LEN] = GPT_MICROSOFT_BASIC_DATA_TYPE_GUID; const uint8_t kSupportedPartitionTypes[] = { mbr::kPartitionTypeFuchsiaData, mbr::kPartitionTypeFuchsiaSys, mbr::kPartitionTypeFat12, mbr::kPartitionTypeFat16, mbr::kPartitionTypeFat16B, mbr::kPartitionTypeFat16LBA, mbr::kPartitionTypeFat32, mbr::kPartitionTypeFat32LBA, }; constexpr uint32_t DivRoundUp(uint32_t n, uint32_t d) { return (n + (d - 1)) / d; } zx_status_t MbrReadHeader(const ddk::BlockProtocolClient& parent_proto, mbr::Mbr* mbr_out, block_info_t* block_info_out, size_t* block_op_size_out) { parent_proto.Query(block_info_out, block_op_size_out); fbl::AllocChecker ac; std::unique_ptr<char[]> raw(new (&ac) char[*block_op_size_out]); if (!ac.check()) { return ZX_ERR_NO_MEMORY; } auto* bop = reinterpret_cast<block_op_t*>(raw.get()); // We need to read at least 512B to parse the MBR. Determine if we should // read the device's block size or we should ready exactly 512B. uint32_t iosize = 0; if (block_info_out->block_size >= mbr::kMbrSize) { iosize = block_info_out->block_size; } else { // Make sure we're reading some multiple of the block size. iosize = DivRoundUp(mbr::kMbrSize, block_info_out->block_size) * block_info_out->block_size; } zx::vmo vmo; auto status = zx::vmo::create(iosize, 0, &vmo); if (status != ZX_OK) { zxlogf(ERROR, "mbr: cannot allocate vmo: %s", zx_status_get_string(status)); return status; } sync_completion_t read_complete; bop->command = BLOCK_OP_READ; bop->rw.vmo = vmo.get(); bop->rw.length = iosize / block_info_out->block_size; bop->rw.offset_dev = 0; bop->rw.offset_vmo = 0; zxlogf(TRACE, "mbr: Reading header from parent block device"); parent_proto.Queue( bop, [](void* cookie, zx_status_t status, block_op_t* bop) { bop->command = status; sync_completion_signal(static_cast<sync_completion_t*>(cookie)); }, &read_complete); sync_completion_wait(&read_complete, ZX_TIME_INFINITE); if ((status = bop->command) != ZX_OK) { zxlogf(ERROR, "mbr: could not read mbr from device: %s", zx_status_get_string(status)); return status; } uint8_t buffer[mbr::kMbrSize]; if ((status = vmo.read(buffer, 0, sizeof(buffer))) != ZX_OK) { zxlogf(ERROR, "mbr: Failed to read MBR header: %s", zx_status_get_string(status)); return status; } if ((status = mbr::Parse(buffer, sizeof(buffer), mbr_out)) != ZX_OK) { zxlogf(ERROR, "mbr: Failed to parse MBR: %s", zx_status_get_string(status)); return status; } return ZX_OK; } } // namespace namespace mbr { bool MbrDevice::SupportsPartitionType(uint8_t partition_type) { return std::end(kSupportedPartitionTypes) != std::find(std::begin(kSupportedPartitionTypes), std::end(kSupportedPartitionTypes), partition_type); } void MbrDevice::BlockImplQuery(block_info_t* info_out, size_t* block_op_size_out) { *info_out = info_; *block_op_size_out = block_op_size_; } void MbrDevice::BlockImplQueue(block_op_t* operation, block_impl_queue_callback completion_cb, void* cookie) { switch (operation->command & BLOCK_OP_MASK) { case BLOCK_OP_READ: case BLOCK_OP_WRITE: { size_t blocks = operation->rw.length; size_t max = partition_.num_sectors; // Ensure that the request is in-bounds if ((operation->rw.offset_dev >= max) || ((max - operation->rw.offset_dev) < blocks)) { completion_cb(cookie, ZX_ERR_OUT_OF_RANGE, operation); return; } // Adjust for partition starting block operation->rw.offset_dev += partition_.start_sector_lba; break; } case BLOCK_OP_FLUSH: break; default: completion_cb(cookie, ZX_ERR_NOT_SUPPORTED, operation); return; } parent_protocol_.Queue(operation, completion_cb, cookie); } zx_status_t MbrDevice::BlockPartitionGetGuid(guidtype_t guid_type, guid_t* out_guid) { if (guid_type != GUIDTYPE_TYPE) { return ZX_ERR_NOT_SUPPORTED; } switch (partition_.type) { case kPartitionTypeFuchsiaData: { memcpy(out_guid, kDataGuid, BLOCK_GUID_LEN); return ZX_OK; } case kPartitionTypeFuchsiaSys: { memcpy(out_guid, kSysGuid, BLOCK_GUID_LEN); return ZX_OK; } case kPartitionTypeFat12: case kPartitionTypeFat16: case kPartitionTypeFat16B: case kPartitionTypeFat16LBA: case kPartitionTypeFat32: case kPartitionTypeFat32LBA: { memcpy(out_guid, kMicrosoftDataGuid, BLOCK_GUID_LEN); return ZX_OK; } default: { zxlogf(ERROR, "mbr: Partition type 0x%02x unsupported", partition_.type); return ZX_ERR_NOT_SUPPORTED; } } } zx_status_t MbrDevice::BlockPartitionGetName(char* out_name, size_t capacity) { if (capacity < GPT_NAME_LEN) { return ZX_ERR_BUFFER_TOO_SMALL; } strlcpy(out_name, name_.c_str(), capacity); return ZX_OK; } void MbrDevice::DdkRelease() { delete this; } zx_off_t MbrDevice::DdkGetSize() { // TODO: use query() results, *but* fvm returns different query and getsize // results, and the latter are dynamic... return device_get_size(parent_); } zx_status_t MbrDevice::DdkGetProtocol(uint32_t proto_id, void* out) { auto* proto = static_cast<ddk::AnyProtocol*>(out); switch (proto_id) { case ZX_PROTOCOL_BLOCK_IMPL: { proto->ops = &block_impl_protocol_ops_; proto->ctx = this; return ZX_OK; } case ZX_PROTOCOL_BLOCK_PARTITION: { proto->ops = &block_partition_protocol_ops_; proto->ctx = this; return ZX_OK; } default: return ZX_ERR_NOT_SUPPORTED; } } zx_status_t MbrDevice::Create(zx_device_t* parent, fbl::Vector<std::unique_ptr<MbrDevice>>* devices_out) { if (parent == nullptr || devices_out == nullptr) { return ZX_ERR_INVALID_ARGS; } ddk::BlockProtocolClient parent_proto(parent); if (!parent_proto.is_valid()) { zxlogf(ERROR, "mbr: ERROR: Parent device does not support ZX_PROTOCOL_BLOCK"); return ZX_ERR_NOT_SUPPORTED; } Mbr mbr; block_info_t block_info; size_t block_op_size; zx_status_t status; if ((status = MbrReadHeader(parent_proto, &mbr, &block_info, &block_op_size)) != ZX_OK) { return status; } // Parse the partitions out of the MBR. fbl::AllocChecker ac; for (unsigned i = 0; i < std::size(mbr.partitions); ++i) { const auto& entry = mbr.partitions[i]; if (entry.type == kPartitionTypeNone) { // This partition entry is empty and does not refer to a partition, skip it. continue; } if (entry.type == kPartitionTypeGptProtective && i == 0) { // If the first partition on the disk has type '0xee', this MBR is not a real MBR, // and we should refuse to bind to it. return ZX_ERR_NOT_SUPPORTED; } zxlogf(INFO, "mbr: found partition, entry = %d, type = 0x%02X, start = %u, length = 0x%X", i + 1, entry.type, entry.start_sector_lba, entry.num_sectors); if (!MbrDevice::SupportsPartitionType(entry.type)) { zxlogf(WARNING, "mbr: Not mounting partition %d, unsupported type 0x%02x", i, entry.type); continue; } char name[16]; snprintf(name, sizeof(name), "part-%03u", i); block_info_t info = block_info; info.block_count = entry.num_sectors; auto device = fbl::make_unique_checked<MbrDevice>(&ac, parent, name, entry, info, block_op_size); if (!ac.check()) { zxlogf(ERROR, "mbr: Failed to allocate partition device"); return ZX_ERR_NO_MEMORY; } devices_out->push_back(std::move(device), &ac); if (!ac.check()) { zxlogf(ERROR, "mbr: Failed to allocate partition device"); return ZX_ERR_NO_MEMORY; } } return ZX_OK; } zx_status_t MbrDevice::Bind(std::unique_ptr<MbrDevice> device) { if (device.get() == nullptr) { return ZX_ERR_INVALID_ARGS; } zx_status_t status; if ((status = device->DdkAdd(device->Name().c_str())) != ZX_OK) { zxlogf(ERROR, "mbr: Failed to add partition device: %s", zx_status_get_string(status)); return status; } // devmgr owns the device now that it's bound __UNUSED auto* dummy = device.release(); return ZX_OK; } } // namespace mbr namespace { zx_status_t CreateAndBind(void* ctx, zx_device_t* parent) { fbl::Vector<std::unique_ptr<mbr::MbrDevice>> devices; fbl::AllocChecker ac; devices.reserve(mbr::kMbrNumPartitions, &ac); if (!ac.check()) { zxlogf(ERROR, "mbr: Failed to allocate devices container"); return ZX_ERR_NO_MEMORY; } zx_status_t status; if ((status = mbr::MbrDevice::Create(parent, &devices)) != ZX_OK) { return status; } for (auto& device : devices) { if (device != nullptr) { if ((status = mbr::MbrDevice::Bind(std::move(device))) != ZX_OK) { return status; } } } return ZX_OK; } } // namespace zx_driver_ops_t MbrDriverOps = []() { zx_driver_ops_t ops = {}; ops.version = DRIVER_OPS_VERSION; ops.bind = CreateAndBind; return ops; }(); ZIRCON_DRIVER(mbr, MbrDriverOps, "zircon", "0.1");
// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*- // // Vector.cpp: Rcpp R/C++ interface class library -- Vector unit tests // // Copyright (C) 2012 - 2015 Dirk Eddelbuettel and Romain Francois // // This file is part of Rcpp. // // Rcpp is free software: you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // Rcpp is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Rcpp. If not, see <http://www.gnu.org/licenses/>. #include <climits> #include <Rcpp.h> #include <sstream> using namespace Rcpp ; inline double square( double x){ return x*x; } // [[Rcpp::export]] RawVector raw_(){ RawVector x(10) ; for( int i=0; i<10; i++) x[i] = (Rbyte)i ; return x ; } // [[Rcpp::export]] RawVector raw_REALSXP( RawVector x ){ for( int i=0; i<x.size(); i++) { x[i] = x[i]*2 ; } return x ; } // [[Rcpp::export]] ExpressionVector expression_(){ ExpressionVector x(2) ; x[0] = Symbol( "rnorm" ) ; x[1] = Rf_lcons( Symbol("rnorm"), Rf_cons( Rf_ScalarReal(10.0), R_NilValue) ) ; return x ; } // [[Rcpp::export]] ExpressionVector expression_variadic(){ ExpressionVector x(2) ; x[0] = Symbol( "rnorm" ) ; x[1] = Language( "rnorm", 10.0 ) ; return x ; } // [[Rcpp::export]] ExpressionVector expression_parse(){ ExpressionVector code( "local( { y <- sample(1:10); sort(y) })" ) ; return code ; } // [[Rcpp::export]] ExpressionVector expression_parseerror(){ ExpressionVector code( "rnorm(" ) ; return code ; } // [[Rcpp::export]] SEXP expression_eval(){ ExpressionVector code( "local( { y <- sample(1:10); sort(y) })" ) ; return code.eval() ; } // [[Rcpp::export]] SEXP expression_evalenv( Environment env){ ExpressionVector code( "sort(x)" ) ; return code.eval(env) ; } // [[Rcpp::export]] ComplexVector complex_(){ ComplexVector x(10) ; Rcomplex rc ; for( int i=0; i<10; i++) { rc.r = rc.i = i + 0.0 ; x[i] = rc ; } return x ; } // [[Rcpp::export]] ComplexVector complex_CPLXSXP( ComplexVector x ){ int nn = x.size(); for( int i=0; i<nn; i++) { x[i].r = x[i].r*2 ; x[i].i = x[i].i*2 ; } return x ; } // [[Rcpp::export]] ComplexVector complex_INTSXP( SEXP vec ){ ComplexVector x(vec); int nn = x.size(); IntegerVector tmp(nn, 2.0); ComplexVector tmp1(tmp); x = x * tmp1; return x ; } // [[Rcpp::export]] ComplexVector complex_REALSXP(SEXP vec){ ComplexVector x(vec); int nn = x.size(); NumericVector tmp(nn, 3.0); ComplexVector tmp1(tmp); x = x * tmp1; return x ; } // [[Rcpp::export]] IntegerVector integer_ctor(){ IntegerVector x(10) ; for( int i=0; i<10; i++) x[i] = i ; return x ; } // [[Rcpp::export]] IntegerVector integer_INTSXP(SEXP vec){ IntegerVector x(vec) ; for( int i=0; i<x.size(); i++) { x[i] = x[i]*2 ; } return x ; } // [[Rcpp::export]] IntegerVector integer_dimension_ctor_1(){ return IntegerVector( Dimension( 5 ) ) ; } // [[Rcpp::export]] IntegerVector integer_dimension_ctor_2(){ return IntegerVector( Dimension( 5, 5 ) ) ; } // [[Rcpp::export]] IntegerVector integer_dimension_ctor_3(){ return IntegerVector( Dimension( 2, 3, 4) ) ; } // [[Rcpp::export]] IntegerVector integer_range_ctor_1(){ int x[] = { 0, 1, 2, 3 } ; IntegerVector y( x, x+4 ) ; return y; } // [[Rcpp::export]] IntegerVector integer_range_ctor_2(){ std::vector<int> vec(4) ; for( size_t i = 0; i<4; i++) vec[i] = i; IntegerVector y( vec.begin(), vec.end() ) ; return y; } // [[Rcpp::export]] IntegerVector integer_names_set(){ IntegerVector y(2) ; std::vector<std::string> names(2) ; names[0] = "foo" ; names[1] = "bar" ; y.names() = names ; return y ; } // [[Rcpp::export]] CharacterVector integer_names_get( IntegerVector y ){ return y.names() ; } // [[Rcpp::export]] int integer_names_indexing( IntegerVector y ){ return y["foo"] ; } // [[Rcpp::export]] IntegerVector integer_push_back( IntegerVector y ){ y.push_back( 5 ) ; return y ; } // [[Rcpp::export]] IntegerVector integer_push_front( IntegerVector y ){ y.push_front( 5 ) ; return y ; } // [[Rcpp::export]] IntegerVector integer_insert( IntegerVector y){ y.insert( 0, 5 ) ; y.insert( 2, 7 ) ; return y ; } // [[Rcpp::export]] IntegerVector integer_erase( IntegerVector y ){ y.erase(2) ; return y ; } // [[Rcpp::export]] List integer_erase_range( IntegerVector x, IntegerVector y ){ x.erase(x.begin()+5, x.end()-1 ); y.erase(y.begin()+5, y.end()-1 ); return List::create( x, y ) ; } // [[Rcpp::export]] List integer_erase_range_2( IntegerVector x, IntegerVector y ){ IntegerVector::iterator it = x.begin()+1 ; while( it != x.end() ){ it = x.erase(it) ; } it = y.begin() + 1 ; while( it != y.end() ){ it = y.erase(it) ; } return List::create( x, y ) ; } // [[Rcpp::export]] List List_erase_range_2( List x, List y ){ List::iterator it = x.begin()+1 ; while( it != x.end() ){ it = x.erase(it) ; } it = y.begin() + 1 ; while( it != y.end() ){ it = y.erase(it) ; } return List::create( x, y ) ; } // [[Rcpp::export]] IntegerVector integer_erase2( IntegerVector y ){ y.erase(1,2) ; return y ; } // [[Rcpp::export]] IntegerVector integer_fill( IntegerVector y ){ y.fill(10) ; return y ; } // [[Rcpp::export]] IntegerVector integer_zero(){ return IntegerVector(0); } // [[Rcpp::export]] IntegerVector integer_create_zero(){ return IntegerVector::create(); } // [[Rcpp::export]] List integer_create_(){ List output(2); output[0] = IntegerVector::create( 10, 20 ) ; output[1] = IntegerVector::create( _["foo"] = 20, _["bar"] = 30 ) ; return output ; } // [[Rcpp::export]] IntegerVector integer_clone_( IntegerVector vec ){ IntegerVector dolly = clone( vec ) ; for( size_t i=0; i<10; i++){ dolly[i] = 10 - i ; } return dolly ; } // [[Rcpp::export]] NumericVector numeric_(){ NumericVector x(10) ; for( int i=0; i<10; i++) x[i] = i ; return x ; } // [[Rcpp::export]] NumericVector numeric_REALSXP( SEXP vec){ NumericVector x(vec) ; for( int i=0; i<x.size(); i++) { x[i] = x[i]*2.0 ; } return x ; } // [[Rcpp::export]] IntegerVector numeric_import(){ std::vector<int> v(10) ; for( int i=0; i<10; i++) v[i] = i ; return IntegerVector::import( v.begin(), v.end() ) ; } // [[Rcpp::export]] NumericVector numeric_importtransform(){ std::vector<double> v(10) ; for( int i=0; i<10; i++) v[i] = i ; return NumericVector::import_transform( v.begin(), v.end(), square ) ; } // [[Rcpp::export]] List list_ctor(){ List x(10) ; for( int i=0; i<10; i++) x[i] = Rf_ScalarInteger( i * 2) ; return x ; } // [[Rcpp::export]] List list_template_(){ List x(4) ; x[0] = "foo" ; x[1] = 10 ; x[2] = 10.2 ; x[3] = false; return x ; } // [[Rcpp::export]] List list_VECSXP_( SEXP vec){ List x(vec) ; return x ; } // [[Rcpp::export]] List list_matrix_indexing_1( List m ){ List out(4) ; for( size_t i=0 ; i<4; i++){ out[i] = m(i,i) ; } return out ; } // [[Rcpp::export]] List list_matrix_indexing_2( GenericVector m ){ for(size_t i=0 ; i<4; i++){ m(i,i) = "foo" ; } return m ; } // [[Rcpp::export]] List list_Dimension_constructor_1(){ return List( Dimension( 5 ) ) ; } // [[Rcpp::export]] List list_Dimension_constructor_2(){ return List( Dimension( 5, 5 ) ); } // [[Rcpp::export]] List list_Dimension_constructor_3(){ return List( Dimension( 2, 3, 4) ) ; } // [[Rcpp::export]] List list_iterator_( List input, Function fun){ List output( input.size() ) ; std::transform( input.begin(), input.end(), output.begin(), fun ) ; output.names() = input.names() ; return output ; } // [[Rcpp::export]] int list_name_indexing( List df ){ IntegerVector df_x = df["x"] ; int res = std::accumulate( df_x.begin(), df_x.end(), 0 ) ; return res ; } // [[Rcpp::export]] List list_push_back(List list){ list.push_back( 10 ) ; list.push_back( "bar", "foo" ) ; return list ; } // [[Rcpp::export]] List list_push_front( List list ){ list.push_front( 10 ) ; list.push_front( "bar", "foo" ) ; return list ; } // [[Rcpp::export]] List list_erase( List list ){ list.erase( list.begin() ) ; return list ; } // [[Rcpp::export]] List list_erase_range( List list ){ list.erase( 0, 2 ) ; return list ; } // [[Rcpp::export]] List list_implicit_push_back(){ List list ; list["foo"] = 10 ; list["bar" ] = "foobar" ; return list ; } // [[Rcpp::export]] List list_create_(){ List output(2); output[0] = List::create( 10, "foo" ) ; output[1] = List::create( _["foo"] = 10, _["bar"] = true ) ; return output ; } // [[Rcpp::export]] List list_stdcomplex(){ std::vector< std::complex<double> > v_double(10) ; std::vector< std::complex<float> > v_float(10) ; return List::create( _["float"] = v_float, _["double"] = v_double ) ; } // [[Rcpp::export]] CharacterVector character_ctor(){ CharacterVector x(10) ; for( int i=0; i<10; i++) x[i] = "foo" ; return x ; } // [[Rcpp::export]] std::string character_STRSXP_( SEXP vec ){ CharacterVector x(vec) ; std::string st = "" ; for( int i=0; i<x.size(); i++) { st += x[i] ; } return st ; } // [[Rcpp::export]] CharacterVector character_plusequals(){ CharacterVector x(2) ; x[0] = "foo" ; x[1] = "bar" ; x[0] += "bar" ; x[1] += x[0] ; return x ; } // [[Rcpp::export]] CharacterVector character_matrix_indexing( CharacterVector m ){ std::string trace; for( size_t i=0 ; i<4; i++){ trace += m(i,i) ; } return wrap( trace ) ; } // [[Rcpp::export]] CharacterVector character_matrix_indexing_lhs( CharacterVector m ){ for( size_t i=0 ; i<4; i++){ m(i,i) = "foo" ; } return m ; } // [[Rcpp::export]] CharacterVector character_matrix_row_iteration_incr( CharacterMatrix m ){ std::string pasted_row; CharacterMatrix::Row row(m(1, _)); CharacterMatrix::Row::iterator i_row(row.begin()); for( size_t i=0 ; i<4; i++){ pasted_row += *i_row++; } return wrap( pasted_row ) ; } // [[Rcpp::export]] CharacterVector character_matrix_row_iteration_decr( CharacterMatrix m ){ std::string pasted_row; CharacterMatrix::Row row(m(1, _)); CharacterMatrix::Row::iterator i_row(row.end()); i_row--; // Step back from 'one past the end' to 'last element'. // Only copy the last three elements, to avoid creating an invalid // 'one before the beginning' iterator: for( size_t i=0 ; i<3; i++){ pasted_row += *i_row--; } return wrap( pasted_row ) ; } // [[Rcpp::export]] CharacterVector character_assign1(){ const char* x[] = { "foo", "bar", "bling", "boom" } ; CharacterVector y ; y.assign( x, x+4 ) ; return y; } // [[Rcpp::export]] CharacterVector character_assign2(){ std::vector<std::string> vec(4) ; vec[0] = "foo"; vec[1] = "bar"; vec[2] = "bling"; vec[3] = "boom" ; CharacterVector y ; y.assign( vec.begin(), vec.end() ) ; return y; } // [[Rcpp::export]] CharacterVector character_range_ctor1(){ const char* x[] = { "foo", "bar", "bling", "boom" } ; CharacterVector y( x, x+4 ) ; return y; } // [[Rcpp::export]] CharacterVector character_range_ctor2(){ std::vector<std::string> vec(4) ; vec[0] = "foo"; vec[1] = "bar"; vec[2] = "bling"; vec[3] = "boom" ; CharacterVector y( vec.begin(), vec.end() ) ; return y; } // [[Rcpp::export]] CharacterVector character_dimension_ctor1(){ return CharacterVector( Dimension( 5 ) ) ; } // [[Rcpp::export]] CharacterVector character_dimension_ctor2(){ return CharacterVector( Dimension( 5, 5 ) ) ; } // [[Rcpp::export]] CharacterVector character_dimension_ctor3(){ return CharacterVector( Dimension( 2, 3, 4) ) ; } // [[Rcpp::export]] std::string character_iterator1( CharacterVector letters ){ std::string res ; CharacterVector::iterator first = letters.begin() ; CharacterVector::iterator last = letters.end() ; while( first != last ){ res += *first ; ++first ; } return res ; } // [[Rcpp::export]] std::string character_iterator2( CharacterVector letters ){ std::string res(std::accumulate(letters.begin(), letters.end(), std::string())); return res ; } // [[Rcpp::export]] CharacterVector character_reverse( CharacterVector y ){ std::reverse( y.begin(), y.end() ) ; return y ; } // [[Rcpp::export]] std::string character_names_indexing( CharacterVector y ){ std::string foo( y["foo"] ) ; return foo ; } // [[Rcpp::export]] List character_listOf( List ll ){ CharacterVector cv1 = ll["foo"]; CharacterVector cv2 = ll["bar"]; std::string rv1 = std::string(cv1[0]) + cv1[1] + cv1[2]; std::string rv2 = std::string(cv2[0]) + cv2[1] + cv2[2]; return List::create(_["foo"] = rv1, _["bar"] = rv2); } // [[Rcpp::export]] int character_find_(CharacterVector y){ CharacterVector::iterator it = std::find( y.begin(), y.end(), "foo" ) ; return std::distance( y.begin(), it ); } // [[Rcpp::export]] List character_create_(){ List output(2); output[0] = CharacterVector::create( "foo", "bar" ) ; output[1] = CharacterVector::create( _["foo"] = "bar", _["bar"] = "foo" ) ; return output ; } // [[Rcpp::export]] List complex_binary_sugar(ComplexVector xx, ComplexVector yy){ return List::create( _["+"] = xx + yy, _["-"] = xx - yy, _["*"] = xx * yy, _["/"] = xx / yy ) ; } // [[Rcpp::export]] List List_extract( List input ){ bool a = input[0] ; int b = input[1] ; return List::create(a, b) ; } // [[Rcpp::export]] CharacterVector factors( CharacterVector s){ return s; } // [[Rcpp::export]] IntegerVector IntegerVector_int_init(){ IntegerVector x(2,4) ; return x ; } // [[Rcpp::export]] bool containsElementNamed( List l, CharacterVector n){ return l.containsElementNamed(n[0]); } // [[Rcpp::export]] List CharacterVectorEqualityOperator( CharacterVector x, CharacterVector y){ int n = x.size() ; LogicalVector eq(n), neq(n); for( int i=0; i<n; i++){ eq[i] = x[i] == y[i] ; neq[i] = x[i] != y[i] ; } return List::create(eq, neq) ; } // [[Rcpp::export]] List List_rep_ctor(IntegerVector x){ return List(3, x) ; } // [[Rcpp::export]] int stdVectorDouble(std::vector<double> x) { return x.size(); } // [[Rcpp::export]] int stdVectorDoubleConst(const std::vector<double> x) { return x.size(); } // [[Rcpp::export]] int stdVectorDoubleRef(std::vector<double> & x) { return x.size(); } // [[Rcpp::export]] int stdVectorDoubleConstRef(const std::vector<double> & x) { return x.size(); } // [[Rcpp::export]] int stdVectorInt(std::vector<int> x) { return x.size(); } // [[Rcpp::export]] int stdVectorIntConst(const std::vector<int> x) { return x.size(); } // [[Rcpp::export]] int stdVectorIntRef(std::vector<int> & x) { return x.size(); } // [[Rcpp::export]] int stdVectorIntConstRef(const std::vector<int> & x) { return x.size(); } // [[Rcpp::export]] std::string character_vector_const_proxy(const CharacterVector& str){ char* cstr = (char*) str[0] ; std::string res ; res += cstr ; return cstr ; } // [[Rcpp::export]] CharacterVector CharacterVector_test_const_proxy(const CharacterVector x){ CharacterVector out( x.size() ) ; for( int i=0; i<x.size(); i++){ out[i] = x[i] ; } return out ; } // [[Rcpp::export]] NumericVector sort_numeric(NumericVector x) { return x.sort(); } // [[Rcpp::export]] IntegerVector sort_integer(IntegerVector x) { return x.sort(); } // [[Rcpp::export]] CharacterVector sort_character(CharacterVector x) { return x.sort(); } // [[Rcpp::export]] LogicalVector sort_logical(LogicalVector x) { return x.sort(); } // [[Rcpp::export]] List list_sexp_assign(SEXP x) { List L; L = x; return L; } // [[Rcpp::export]] bool logical_vector_from_bool() { return true; } // [[Rcpp::export]] LogicalVector logical_vector_from_bool_assign() { LogicalVector result = true; return result; } // [[Rcpp::export]] void no_op(int major) { int minor = 1; } // [[Rcpp::export]] int noprotect_vector( Vector<REALSXP, NoProtectStorage> x){ return x.size() ; } // [[Rcpp::export]] int noprotect_matrix( Matrix<REALSXP, NoProtectStorage> x){ return x.nrow() ; } // [[Rcpp::export]] int vec_access_with_bounds_checking(const IntegerVector x, int index) { return x.at(index); } // [[Rcpp::export]] String vec_print_numeric(NumericVector v) { std::ostringstream buf; buf << v; return buf.str(); } // [[Rcpp::export]] String vec_print_character(CharacterVector v) { std::ostringstream buf; buf << v; return buf.str(); } // [[Rcpp::export]] String vec_print_integer(IntegerVector v) { std::ostringstream buf; buf << v; return buf.str(); }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "frame.h" #include <zxtest/zxtest.h> #include <vector> #include "fcs.h" namespace { TEST(FrameTestCase, SerializeFrameEmpty) { const std::vector<uint8_t> information = {}; const std::vector<uint8_t> expect = { 0x7e, 0xff, 0x7d, 0x23, 0xc2, 0x23, 0xeb, 0x3c, 0x7e, }; const ppp::FrameView frame(ppp::Protocol::ChallengeHandshakeAuthentication, information); const std::vector<uint8_t> raw_frame = ppp::SerializeFrame(frame); ASSERT_EQ(raw_frame.size(), expect.size()); ASSERT_BYTES_EQ(raw_frame.data(), expect.data(), expect.size()); } TEST(FrameTestCase, SerializeFrameNoEscape) { const std::vector<uint8_t> information = {0x89, 0xab, 0xde}; const std::vector<uint8_t> expect = { 0x7e, 0xff, 0x7d, 0x23, 0xc0, 0x23, 0x89, 0xab, 0xde, 0x7d, 0x37, 0x7d, 0x2b, 0x7e, }; const ppp::FrameView frame(ppp::Protocol::PasswordAuthentication, information); const std::vector<uint8_t> raw_frame = ppp::SerializeFrame(frame); ASSERT_EQ(raw_frame.size(), expect.size()); ASSERT_BYTES_EQ(raw_frame.data(), expect.data(), expect.size()); } TEST(FrameTestCase, SerializeFrameEscapeFlagSequence) { const std::vector<uint8_t> information = {0xaa, 0x7e, 0xaa}; const std::vector<uint8_t> expect = { 0x7e, 0xff, 0x7d, 0x23, 0x80, 0x57, 0xaa, 0x7d, 0x5e, 0xaa, 0xe3, 0x7d, 0x3a, 0x7e, }; const ppp::FrameView frame(ppp::Protocol::Ipv6Control, information); const std::vector<uint8_t> raw_frame = ppp::SerializeFrame(frame); ASSERT_EQ(raw_frame.size(), expect.size()); ASSERT_BYTES_EQ(raw_frame.data(), expect.data(), expect.size()); } TEST(FrameTestCase, SerializeFrameEscapeEscaped) { const std::vector<uint8_t> information = {0x7d, 0x5e}; const std::vector<uint8_t> expect = { 0x7e, 0xff, 0x7d, 0x23, 0x7d, 0x20, 0x21, 0x7d, 0x5d, 0x5e, 0xc9, 0xb5, 0x7e, }; const ppp::FrameView frame(ppp::Protocol::Ipv4, information); const std::vector<uint8_t> raw_frame = ppp::SerializeFrame(frame); ASSERT_EQ(raw_frame.size(), expect.size()); ASSERT_BYTES_EQ(raw_frame.data(), expect.data(), expect.size()); } TEST(FrameTestCase, SerializeFrameEscapeAll) { const std::vector<uint8_t> information = {0x7e, 0x7e, 0x7e, 0x7d, 0x7d, 0x7d}; const std::vector<uint8_t> expect = { 0x7e, 0xff, 0x7d, 0x23, 0xc0, 0x25, 0x7d, 0x5e, 0x7d, 0x5e, 0x7d, 0x5e, 0x7d, 0x5d, 0x7d, 0x5d, 0x7d, 0x5d, 0x6c, 0x43, 0x7e, }; const ppp::FrameView frame(ppp::Protocol::LinkQualityReport, information); const std::vector<uint8_t> raw_frame = ppp::SerializeFrame(frame); ASSERT_EQ(raw_frame.size(), expect.size()); ASSERT_BYTES_EQ(raw_frame.data(), expect.data(), expect.size()); } TEST(FrameTestCase, DeserializeFrameEmpty) { const std::vector<uint8_t> raw_frame = { 0x7e, 0xff, 0x7d, 0x23, 0xc2, 0x23, 0xeb, 0x3c, 0x7e, }; const std::vector<uint8_t> expect_information = {}; const ppp::Protocol expect_protocol = ppp::Protocol::ChallengeHandshakeAuthentication; auto result = ppp::DeserializeFrame(raw_frame); ASSERT_TRUE(result.is_ok()); const auto frame = result.take_value(); ASSERT_EQ(frame.protocol, expect_protocol); ASSERT_EQ(frame.information.size(), expect_information.size()); ASSERT_BYTES_EQ(frame.information.data(), expect_information.data(), expect_information.size()); } TEST(FrameTestCase, DeserializeFrameNoEscape) { const std::vector<uint8_t> raw_frame = { 0x7e, 0xff, 0x7d, 0x23, 0xc0, 0x23, 0x89, 0xab, 0xde, 0x7d, 0x37, 0x7d, 0x2b, 0x7e, }; const std::vector<uint8_t> expect_information = {0x89, 0xab, 0xde}; const ppp::Protocol expect_protocol = ppp::Protocol::PasswordAuthentication; auto result = ppp::DeserializeFrame(raw_frame); ASSERT_TRUE(result.is_ok()); const auto frame = result.take_value(); ASSERT_EQ(frame.protocol, expect_protocol); ASSERT_EQ(frame.information.size(), expect_information.size()); ASSERT_BYTES_EQ(frame.information.data(), expect_information.data(), expect_information.size()); } TEST(FrameTestCase, DeserializeFrameEscapeFlagSequence) { const std::vector<uint8_t> raw_frame = { 0x7e, 0xff, 0x7d, 0x23, 0x80, 0x57, 0xaa, 0x7d, 0x5e, 0xaa, 0xe3, 0x7d, 0x3a, 0x7e, }; const std::vector<uint8_t> expect_information = {0xaa, 0x7e, 0xaa}; const ppp::Protocol expect_protocol = ppp::Protocol::Ipv6Control; auto result = ppp::DeserializeFrame(raw_frame); ASSERT_TRUE(result.is_ok()); const auto frame = result.take_value(); ASSERT_EQ(frame.protocol, expect_protocol); ASSERT_EQ(frame.information.size(), expect_information.size()); ASSERT_BYTES_EQ(frame.information.data(), expect_information.data(), expect_information.size()); } TEST(FrameTestCase, DeserializeFrameEscapeEscaped) { const std::vector<uint8_t> raw_frame = { 0x7e, 0xff, 0x7d, 0x23, 0x7d, 0x20, 0x21, 0x7d, 0x5d, 0x5e, 0xc9, 0xb5, 0x7e, }; const std::vector<uint8_t> expect_information = {0x7d, 0x5e}; const ppp::Protocol expect_protocol = ppp::Protocol::Ipv4; auto result = ppp::DeserializeFrame(raw_frame); ASSERT_TRUE(result.is_ok()); const auto frame = result.take_value(); ASSERT_EQ(frame.protocol, expect_protocol); ASSERT_EQ(frame.information.size(), expect_information.size()); ASSERT_BYTES_EQ(frame.information.data(), expect_information.data(), expect_information.size()); } TEST(FrameTestCase, DeserializeFrameEscapeAll) { const std::vector<uint8_t> raw_frame = { 0x7e, 0xff, 0x7d, 0x23, 0xc0, 0x25, 0x7d, 0x5e, 0x7d, 0x5e, 0x7d, 0x5e, 0x7d, 0x5d, 0x7d, 0x5d, 0x7d, 0x5d, 0x6c, 0x43, 0x7e, }; const std::vector<uint8_t> expect_information = {0x7e, 0x7e, 0x7e, 0x7d, 0x7d, 0x7d}; const ppp::Protocol expect_protocol = ppp::Protocol::LinkQualityReport; auto result = ppp::DeserializeFrame(raw_frame); ASSERT_TRUE(result.is_ok()); const auto frame = result.take_value(); ASSERT_EQ(frame.protocol, expect_protocol); ASSERT_EQ(frame.information.size(), expect_information.size()); ASSERT_BYTES_EQ(frame.information.data(), expect_information.data(), expect_information.size()); } TEST(FrameTestCase, DeserializeFrameTooSmall) { const std::vector<uint8_t> raw_frame = { 0x7e, 0xff, 0x7d, 0x23, 0xc2, 0xeb, 0x3c, 0x7e, }; auto result = ppp::DeserializeFrame(raw_frame); ASSERT_TRUE(result.is_error()); ASSERT_EQ(result.error(), ppp::DeserializationError::FormatInvalid); } TEST(FrameTestCase, DeserializeFrameMissingOpenFlag) { const std::vector<uint8_t> raw_frame = { 0xff, 0x7d, 0x23, 0xc2, 0x23, 0xaa, 0xeb, 0x3c, 0x7e, }; auto result = ppp::DeserializeFrame(raw_frame); ASSERT_TRUE(result.is_error()); ASSERT_EQ(result.error(), ppp::DeserializationError::FormatInvalid); } TEST(FrameTestCase, DeserializeFrameMissingCloseFlag) { const std::vector<uint8_t> raw_frame = { 0x7e, 0xff, 0x7d, 0x23, 0xc2, 0x23, 0xaa, 0xeb, 0x3c, }; auto result = ppp::DeserializeFrame(raw_frame); ASSERT_TRUE(result.is_error()); ASSERT_EQ(result.error(), ppp::DeserializationError::FormatInvalid); } TEST(FrameTestCase, DeserializeFrameBadAddress) { const std::vector<uint8_t> raw_frame = { 0x7e, 0x7d, 0x20, 0x7d, 0x23, 0xc2, 0x23, 0xeb, 0x3c, 0x7e, }; auto result = ppp::DeserializeFrame(raw_frame); ASSERT_TRUE(result.is_error()); ASSERT_EQ(result.error(), ppp::DeserializationError::UnrecognizedAddress); } TEST(FrameTestCase, DeserializeFrameBadControl) { const std::vector<uint8_t> raw_frame = { 0x7e, 0xff, 0x7d, 0x20, 0xc2, 0x23, 0xeb, 0x3c, 0x7e, }; auto result = ppp::DeserializeFrame(raw_frame); ASSERT_TRUE(result.is_error()); ASSERT_EQ(result.error(), ppp::DeserializationError::UnrecognizedControl); } TEST(FrameTestCase, DeserializeFrameBadFrameCheckSequence) { const std::vector<uint8_t> raw_frame = { 0x7e, 0xff, 0x7d, 0x23, 0xc2, 0x23, 0x7d, 0x20, 0x7d, 0x20, 0x7e, }; auto result = ppp::DeserializeFrame(raw_frame); ASSERT_TRUE(result.is_error()); ASSERT_EQ(result.error(), ppp::DeserializationError::FailedFrameCheckSequence); } } // namespace
/*! * \copyright Copyright (c) 2018 Governikus GmbH & Co. KG, Germany */ #include "DiagnosisItem.h" using namespace governikus; DiagnosisItem::DiagnosisItem(const QString& pText) : QObject() , QEnableSharedFromThis() , mText(pText) , mChildren() { } const QString& DiagnosisItem::getText() const { return mText; } void DiagnosisItem::addChild(const QSharedPointer<DiagnosisItem>& pChild) { mChildren << pChild; pChild->setParent(sharedFromThis()); } void DiagnosisItem::setParent(const QSharedPointer<DiagnosisItem>& pParent) { mParent = pParent; } void DiagnosisItem::clearChildren() { mChildren.clear(); } const QSharedPointer<DiagnosisItem> DiagnosisItem::getChild(int pRow) const { return mChildren.at(pRow); } int DiagnosisItem::childCount() const { return mChildren.length(); } QSharedPointer<DiagnosisItem> DiagnosisItem::parentItem() { return mParent; } int DiagnosisItem::row() const { if (!mParent.isNull()) { return mParent->getIndexOf(this); } return 0; } int DiagnosisItem::getIndexOf(const DiagnosisItem* pChild) const { for (int i = 0; i < mChildren.length(); ++i) { auto child = mChildren.at(i); if (child.data() == pChild) { return i; } } return -1; } void DiagnosisItem::appendPlaintextContent(QStringList& pOutput, const QString& pPrefix) { pOutput << pPrefix + getText(); const QString childPrefix = pPrefix + QLatin1Char(' '); for (const auto& child : qAsConst(mChildren)) { child->appendPlaintextContent(pOutput, childPrefix); } }
#include <bits/stdc++.h> #define vi vector<int> #define pi pair<int,int> #define vii vector<pi> #define ll long long using namespace std; int main() { #ifndef ONLINE_JUDGE freopen("/home/shiva/Learning/1.txt", "r", stdin); freopen("/home/shiva/Learning/2.txt", "w", stdout); #endif ios::sync_with_stdio(false); cin.tie(0); ll t, n; cin >> t; bool flag = false; while (t--) { flag = false; cin >> n; ll start = 1, end = sqrt(n), ss, ee; if ((end * end) == n) cout << "Yes\n"; else { while (start <= end) { ss = start * start; ee = end * end; if (ss + ee == n){cout << "Yes\n"; flag=true; break;} else if (ss + ee < n) start++; else end--; } if(!flag) cout<<"No\n"; } } }
/* Copyright (c) 2019 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License, * attached with Common Clause Condition 1.0, found in the LICENSES directory. */ #include "base/Base.h" #include "graph/FetchVerticesExecutor.h" #include "meta/SchemaProviderIf.h" #include "dataman/SchemaWriter.h" namespace nebula { namespace graph { FetchVerticesExecutor::FetchVerticesExecutor(Sentence *sentence, ExecutionContext *ectx) : TraverseExecutor(ectx, "fetch_vertices") { sentence_ = dynamic_cast<FetchVerticesSentence*>(sentence); } Status FetchVerticesExecutor::prepare() { return Status::OK(); } Status FetchVerticesExecutor::prepareVids() { Status status = Status::OK(); if (sentence_->isRef()) { fromType_ = kRef; auto *expr = sentence_->ref(); if (expr->isInputExpression()) { auto *iexpr = dynamic_cast<InputPropertyExpression*>(expr); colname_ = iexpr->prop(); inputsPtr_ = inputs_.get(); } else if (expr->isVariableExpression()) { auto *vexpr = dynamic_cast<VariablePropertyExpression*>(expr); auto varname = vexpr->alias(); colname_ = vexpr->prop(); bool existing = false; inputsPtr_ = ectx()->variableHolder()->get(*varname, &existing); if (!existing) { return Status::Error("Variable `%s' not defined", varname->c_str()); } } else { // should never come to here. // only support input and variable yet. LOG(ERROR) << "Unknown kind of expression."; return Status::Error("Unknown kind of expression."); } if (colname_ != nullptr && *colname_ == "*") { return Status::Error("Cant not use `*' to reference a vertex id column."); } if (inputsPtr_ == nullptr || !inputsPtr_->hasData()) { return Status::OK(); } status = checkIfDuplicateColumn(); if (!status.ok()) { return status; } auto vidsStatus = inputsPtr_->getDistinctVIDs(*colname_); if (!vidsStatus.ok()) { return std::move(vidsStatus).status(); } vids_ = std::move(vidsStatus).value(); return Status::OK(); } else { fromType_ = kInstantExpr; std::unordered_set<VertexID> uniqID; for (auto *expr : sentence_->vidList()) { expr->setContext(expCtx_.get()); status = expr->prepare(); if (!status.ok()) { break; } Getters getters; auto value = expr->eval(getters); if (!value.ok()) { return value.status(); } auto v = value.value(); if (!Expression::isInt(v)) { status = Status::Error("Vertex ID should be of type integer"); break; } auto valInt = Expression::asInt(v); if (distinct_) { auto result = uniqID.emplace(valInt); if (result.second) { vids_.emplace_back(valInt); } } else { vids_.emplace_back(valInt); } } } return status; } Status FetchVerticesExecutor::prepareTags() { Status status = Status::OK(); auto* tags = sentence_->tags(); if (tags == nullptr) { LOG(ERROR) << "tags shall never be null"; return Status::Error("tags shall never be null"); } auto tagNames = tags->labels(); if (tagNames.empty()) { LOG(ERROR) << "tags shall never be empty"; return Status::Error("tags shall never be empty"); } if (tagNames.size() == 1 && *tagNames[0] == "*") { auto tagsStatus = ectx()->schemaManager()->getAllTag(spaceId_); if (!tagsStatus.ok()) { return tagsStatus.status(); } for (auto& tagName : std::move(tagsStatus).value()) { auto tagIdStatus = ectx()->schemaManager()->toTagID(spaceId_, tagName); if (!tagIdStatus.ok()) { return tagIdStatus.status(); } auto tagId = tagIdStatus.value(); tagNames_.push_back(tagName); tagIds_.push_back(tagId); auto result = tagNameSet_.emplace(tagName); if (!result.second) { return Status::Error(folly::sformat("tag({}) was dup", tagName)); } } } else { for (auto tagName : tagNames) { auto tagStatus = ectx()->schemaManager()->toTagID(spaceId_, *tagName); if (!tagStatus.ok()) { return tagStatus.status(); } auto tagId = tagStatus.value(); tagNames_.push_back(*tagName); tagIds_.push_back(tagId); auto result = tagNameSet_.emplace(*tagName); if (!result.second) { return Status::Error(folly::sformat("tag({}) was dup", *tagName)); } } } return status; } Status FetchVerticesExecutor::prepareYield() { colNames_.emplace_back("VertexID"); colTypes_.emplace_back(nebula::cpp2::SupportedType::VID); if (yieldClause_ == nullptr) { // determine which columns to return after received response from storage. for (unsigned i = 0; i < tagNames_.size(); i++) { auto& tagName = tagNames_[i]; auto tagId = tagIds_[i]; std::shared_ptr<const meta::SchemaProviderIf> tagSchema = ectx()->schemaManager()->getTagSchema(spaceId_, tagId); if (tagSchema == nullptr) { return Status::Error("No tag schema for %s", tagName.c_str()); } for (auto iter = tagSchema->begin(); iter != tagSchema->end(); ++iter) { auto *prop = iter->getName(); storage::cpp2::PropDef pd; pd.owner = storage::cpp2::PropOwner::SOURCE; pd.name = prop; pd.id.set_tag_id(tagId); props_.emplace_back(std::move(pd)); } } } else { for (auto *col : yieldClause_->columns()) { if (!col->getFunName().empty()) { return Status::SyntaxError("Do not support aggregated query with fetch prop on."); } if (col->expr()->isInputExpression()) { auto *inputExpr = dynamic_cast<InputPropertyExpression*>(col->expr()); auto *colName = inputExpr->prop(); if (*colName == "*") { auto colNames = inputsPtr_->getColNames(); for (auto &prop : colNames) { Expression *expr = new InputPropertyExpression(new std::string(prop)); auto *column = new YieldColumn(expr); yieldColsHolder_.addColumn(column); yields_.emplace_back(column); colNames_.emplace_back(column->toString()); colTypes_.emplace_back(nebula::cpp2::SupportedType::UNKNOWN); expCtx_->addInputProp(prop); } continue; } } else if (col->expr()->isVariableExpression()) { auto *variableExpr = dynamic_cast<VariablePropertyExpression*>(col->expr()); auto *colName = variableExpr->prop(); if (*colName == "*") { auto colNames = inputsPtr_->getColNames(); for (auto &prop : colNames) { auto *alias = new std::string(*(variableExpr->alias())); Expression *expr = new VariablePropertyExpression(alias, new std::string(prop)); auto *column = new YieldColumn(expr); yieldColsHolder_.addColumn(column); yields_.emplace_back(column); colNames_.emplace_back(column->toString()); colTypes_.emplace_back(nebula::cpp2::SupportedType::UNKNOWN); expCtx_->addInputProp(prop); } continue; } } yields_.emplace_back(col); col->expr()->setContext(expCtx_.get()); Status status = col->expr()->prepare(); if (!status.ok()) { return status; } if (col->alias() == nullptr) { colNames_.emplace_back(col->expr()->toString()); } else { colNames_.emplace_back(*col->alias()); } auto type = calculateExprType(col->expr()); colTypes_.emplace_back(type); VLOG(1) << "type: " << static_cast<int64_t>(colTypes_.back()); } if (expCtx_->hasSrcTagProp() || expCtx_->hasDstTagProp()) { return Status::SyntaxError( "tag.prop and edgetype.prop are supported in fetch sentence."); } auto aliasProps = expCtx_->aliasProps(); for (auto &pair : aliasProps) { auto& tagName = pair.first; auto& prop = pair.second; if (tagNameSet_.find(tagName) == tagNameSet_.end()) { return Status::SyntaxError( "Near [%s.%s], tag should be declared in `ON' clause first.", tagName.c_str(), prop.c_str()); } auto tagStatus = ectx()->schemaManager()->toTagID(spaceId_, tagName); if (!tagStatus.ok()) { return tagStatus.status(); } auto tagId = tagStatus.value(); std::shared_ptr<const meta::SchemaProviderIf> tagSchema = ectx()->schemaManager()->getTagSchema(spaceId_, tagId); if (tagSchema == nullptr) { return Status::Error("No tag schema for %s", tagName.c_str()); } if (tagSchema->getFieldIndex(prop) == -1) { return Status::Error( "`%s' is not a prop of `%s'", tagName.c_str(), prop.c_str()); } storage::cpp2::PropDef pd; pd.owner = storage::cpp2::PropOwner::SOURCE; pd.name = prop; pd.id.set_tag_id(tagId); props_.emplace_back(std::move(pd)); } } return Status::OK(); } Status FetchVerticesExecutor::prepareClauses() { DCHECK(sentence_ != nullptr); spaceId_ = ectx()->rctx()->session()->space(); expCtx_ = std::make_unique<ExpressionContext>(); expCtx_->setStorageClient(ectx()->getStorageClient()); expCtx_->setSpace(spaceId_); Status status; do { status = checkIfGraphSpaceChosen(); if (!status.ok()) { break; } yieldClause_ = sentence_->yieldClause(); if (yieldClause_ != nullptr) { distinct_ = yieldClause_->isDistinct(); } status = prepareVids(); if (!status.ok()) { break; } status = prepareTags(); if (!status.ok()) { break; } status = prepareYield(); if (!status.ok()) { break; } } while (false); if (!status.ok()) { LOG(ERROR) << "Preparing failed: " << status; return status; } return status; } void FetchVerticesExecutor::onEmptyInputs() { if (onResult_) { auto outputs = std::make_unique<InterimResult>(std::move(colNames_)); onResult_(std::move(outputs)); } else if (resp_ == nullptr) { resp_ = std::make_unique<cpp2::ExecutionResponse>(); resp_->set_column_names(std::move(colNames_)); } doFinish(Executor::ProcessControl::kNext); } void FetchVerticesExecutor::execute() { auto status = prepareClauses(); if (!status.ok()) { doError(std::move(status)); return; } if (vids_.empty()) { LOG(WARNING) << "Empty vids"; onEmptyInputs(); return; } fetchVertices(); } void FetchVerticesExecutor::fetchVertices() { auto future = ectx()->getStorageClient()->getVertexProps( spaceId_, vids_, std::move(props_)); auto *runner = ectx()->rctx()->runner(); auto cb = [this] (RpcResponse &&result) mutable { auto completeness = result.completeness(); if (completeness == 0) { doError(Status::Error("Get tag props failed")); return; } else if (completeness != 100) { LOG(INFO) << "Get vertices partially failed: " << completeness << "%"; for (auto &error : result.failedParts()) { LOG(ERROR) << "part: " << error.first << "error code: " << static_cast<int>(error.second); } ectx()->addWarningMsg("Fetch vertices executor was partially performed"); } processResult(std::move(result)); }; auto error = [this] (auto &&e) { auto msg = folly::stringPrintf("Get tag props exception: %s.", e.what().c_str()); LOG(ERROR) << msg; doError(Status::Error(std::move(msg))); }; std::move(future).via(runner).thenValue(cb).thenError(error); } void FetchVerticesExecutor::processResult(RpcResponse &&result) { auto all = result.responses(); std::shared_ptr<SchemaWriter> outputSchema; std::unique_ptr<RowSetWriter> rsWriter; size_t num = 0; for (auto &resp : all) { num += resp.vertices.size(); } if (num == 0) { finishExecution(std::move(rsWriter)); return; } std::unordered_map<VertexID, std::map<TagID, RowReader>> dataMap; dataMap.reserve(num); std::unordered_map<TagID, std::shared_ptr<const meta::SchemaProviderIf>> tagSchemaMap; std::set<TagID> tagIdSet; for (auto &resp : all) { if (!resp.__isset.vertices || resp.vertices.empty()) { continue; } auto *vertexSchema = resp.get_vertex_schema(); if (vertexSchema != nullptr) { std::transform(vertexSchema->cbegin(), vertexSchema->cend(), std::inserter(tagSchemaMap, tagSchemaMap.begin()), [](auto &s) { return std::make_pair( s.first, std::make_shared<ResultSchemaProvider>(s.second)); }); } for (auto &vdata : resp.vertices) { if (!vdata.__isset.tag_data || vdata.tag_data.empty()) { continue; } for (auto& tagData : vdata.tag_data) { auto& data = tagData.data; VertexID vid = vdata.vertex_id; TagID tagId = tagData.tag_id; if (tagSchemaMap.find(tagId) == tagSchemaMap.end()) { auto ver = RowReader::getSchemaVer(data); if (ver < 0) { LOG(ERROR) << "Found schema version negative " << ver; doError(Status::Error("Found schema version negative: %d", ver)); return; } auto schema = ectx()->schemaManager()->getTagSchema(spaceId_, tagId, ver); if (schema == nullptr) { VLOG(3) << "Schema not found for tag id: " << tagId; // Ignore the bad data. continue; } tagSchemaMap[tagId] = schema; } auto vschema = tagSchemaMap[tagId]; auto vreader = RowReader::getRowReader(data, vschema); dataMap[vid].emplace(std::make_pair(tagId, std::move(vreader))); tagIdSet.insert(tagId); } } } if (yieldClause_ == nullptr) { for (TagID tagId : tagIdSet) { auto tagSchema = tagSchemaMap[tagId]; auto tagFound = ectx()->schemaManager()->toTagName(spaceId_, tagId); if (!tagFound.ok()) { VLOG(3) << "Tag name not found for tag id: " << tagId; // Ignore the bad data. continue; } auto tagName = std::move(tagFound).value(); for (auto iter = tagSchema->begin(); iter != tagSchema->end(); ++iter) { auto *ref = new std::string(""); auto *alias = new std::string(tagName); auto *prop = iter->getName(); Expression *expr = new AliasPropertyExpression(ref, alias, new std::string(prop)); auto *column = new YieldColumn(expr); yieldColsHolder_.addColumn(column); yields_.emplace_back(column); colNames_.emplace_back(expr->toString()); colTypes_.emplace_back(nebula::cpp2::SupportedType::UNKNOWN); } } } if (fromType_ == kRef) { if (inputsPtr_ == nullptr) { LOG(ERROR) << "inputs is nullptr."; doError(Status::Error("inputs is nullptr.")); return; } auto visitor = [&, this] (const RowReader *reader) -> Status { VertexID vid = 0; auto rc = reader->getVid(*colname_, vid); if (rc != ResultType::SUCCEEDED) { return Status::Error("Column `%s' not found", colname_->c_str()); } if (dataMap.find(vid) == dataMap.end() && !expCtx_->hasInputProp()) { return Status::OK(); } // if yield input not empty, create empty item and keep on going. auto& ds = dataMap[vid]; std::vector<VariantType> record; record.emplace_back(VariantType(vid)); auto schema = reader->getSchema().get(); Getters getters; getters.getVariableProp = [&] (const std::string &prop) -> OptVariantType { return Collector::getProp(schema, prop, reader); }; getters.getInputProp = [&] (const std::string &prop) -> OptVariantType { return Collector::getProp(schema, prop, reader); }; getters.getAliasProp = [&] (const std::string& tagName, const std::string &prop) -> OptVariantType { auto tagIdStatus = ectx()->schemaManager()->toTagID(spaceId_, tagName); if (!tagIdStatus.ok()) { return tagIdStatus.status(); } TagID tagId = std::move(tagIdStatus).value(); auto tagIter = ds.find(tagId); if (tagIter != ds.end()) { auto vreader = tagIter->second.get(); auto vschema = vreader->getSchema().get(); return Collector::getProp(vschema, prop, vreader); } else { auto ts = ectx()->schemaManager()->getTagSchema(spaceId_, tagId); if (ts == nullptr) { return Status::Error("No tag schema for %s", tagName.c_str()); } return RowReader::getDefaultProp(ts.get(), prop); } }; for (auto *column : yields_) { auto *expr = column->expr(); auto value = expr->eval(getters); if (!value.ok()) { return value.status(); } record.emplace_back(std::move(value).value()); } if (outputSchema == nullptr) { outputSchema = std::make_shared<SchemaWriter>(); rsWriter = std::make_unique<RowSetWriter>(outputSchema); auto getSchemaStatus = Collector::getSchema( record, colNames_, colTypes_, outputSchema.get()); if (!getSchemaStatus.ok()) { return getSchemaStatus; } } auto writer = std::make_unique<RowWriter>(outputSchema); for (auto& value : record) { auto status = Collector::collect(value, writer.get()); if (!status.ok()) { return status; } } rsWriter->addRow(*writer); return Status::OK(); }; Status status = inputsPtr_->applyTo(visitor); if (!status.ok()) { LOG(ERROR) << "inputs visit failed. " << status.toString(); doError(status); return; } } else { for (auto vid : vids_) { auto iter = dataMap.find(vid); if (iter == dataMap.end()) { continue; } if (dataMap.find(vid) == dataMap.end()) { continue; } auto& ds = dataMap[vid]; std::vector<VariantType> record; record.emplace_back(VariantType(vid)); Getters getters; getters.getAliasProp = [&] (const std::string& tagName, const std::string &prop) -> OptVariantType { auto tagIdStatus = ectx()->schemaManager()->toTagID(spaceId_, tagName); if (!tagIdStatus.ok()) { return tagIdStatus.status(); } TagID tagId = std::move(tagIdStatus).value(); auto tagIter = ds.find(tagId); if (tagIter != ds.end()) { auto vreader = tagIter->second.get(); auto vschema = vreader->getSchema().get(); return Collector::getProp(vschema, prop, vreader); } else { auto ts = ectx()->schemaManager()->getTagSchema(spaceId_, tagId); if (ts == nullptr) { return Status::Error("No tag schema for %s", tagName.c_str()); } return RowReader::getDefaultProp(ts.get(), prop); } }; for (auto *column : yields_) { auto *expr = column->expr(); auto value = expr->eval(getters); if (!value.ok()) { doError(value.status()); return; } record.emplace_back(std::move(value).value()); } if (outputSchema == nullptr) { outputSchema = std::make_shared<SchemaWriter>(); rsWriter = std::make_unique<RowSetWriter>(outputSchema); auto getSchemaStatus = Collector::getSchema( record, colNames_, colTypes_, outputSchema.get()); if (!getSchemaStatus.ok()) { doError(getSchemaStatus); return; } } auto writer = std::make_unique<RowWriter>(outputSchema); for (auto& value : record) { auto status = Collector::collect(value, writer.get()); if (!status.ok()) { doError(status); return; } } rsWriter->addRow(*writer); } } finishExecution(std::move(rsWriter)); } void FetchVerticesExecutor::setupResponse(cpp2::ExecutionResponse &resp) { if (resp_ == nullptr) { resp_ = std::make_unique<cpp2::ExecutionResponse>(); resp_->set_column_names(std::move(colNames_)); } resp = std::move(*resp_); } void FetchVerticesExecutor::finishExecution(std::unique_ptr<RowSetWriter> rsWriter) { auto outputs = std::make_unique<InterimResult>(std::move(colNames_)); if (rsWriter != nullptr) { outputs->setInterim(std::move(rsWriter)); } if (onResult_) { onResult_(std::move(outputs)); } else { resp_ = std::make_unique<cpp2::ExecutionResponse>(); auto colNames = outputs->getColNames(); resp_->set_column_names(std::move(colNames)); if (outputs->hasData()) { auto ret = outputs->getRows(); if (!ret.ok()) { LOG(ERROR) << "Get rows failed: " << ret.status(); doError(std::move(ret).status()); return; } resp_->set_rows(std::move(ret).value()); } } doFinish(Executor::ProcessControl::kNext); } } // namespace graph } // namespace nebula
//===-- AMDGPUSubtarget.cpp - AMDGPU Subtarget Information ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // /// \file /// \brief Implements the AMDGPU specific subclass of TargetSubtarget. // //===----------------------------------------------------------------------===// #include "AMDGPUSubtarget.h" #include "R600ISelLowering.h" #include "R600InstrInfo.h" #include "R600MachineScheduler.h" #include "SIISelLowering.h" #include "SIInstrInfo.h" #include "SIMachineFunctionInfo.h" #include "llvm/ADT/SmallString.h" #include "llvm/CodeGen/MachineScheduler.h" using namespace llvm; #define DEBUG_TYPE "amdgpu-subtarget" #define GET_SUBTARGETINFO_ENUM #define GET_SUBTARGETINFO_TARGET_DESC #define GET_SUBTARGETINFO_CTOR #include "AMDGPUGenSubtargetInfo.inc" AMDGPUSubtarget & AMDGPUSubtarget::initializeSubtargetDependencies(StringRef TT, StringRef GPU, StringRef FS) { // Determine default and user-specified characteristics // On SI+, we want FP64 denormals to be on by default. FP32 denormals can be // enabled, but some instructions do not respect them and they run at the // double precision rate, so don't enable by default. // // We want to be able to turn these off, but making this a subtarget feature // for SI has the unhelpful behavior that it unsets everything else if you // disable it. SmallString<256> FullFS("+promote-alloca,+fp64-denormals,"); FullFS += FS; if (GPU == "" && Triple(TT).getArch() == Triple::amdgcn) GPU = "SI"; ParseSubtargetFeatures(GPU, FullFS); // FIXME: I don't think think Evergreen has any useful support for // denormals, but should be checked. Should we issue a warning somewhere // if someone tries to enable these? if (getGeneration() <= AMDGPUSubtarget::NORTHERN_ISLANDS) { FP32Denormals = false; FP64Denormals = false; } return *this; } AMDGPUSubtarget::AMDGPUSubtarget(StringRef TT, StringRef GPU, StringRef FS, TargetMachine &TM) : AMDGPUGenSubtargetInfo(TT, GPU, FS), DevName(GPU), Is64bit(false), DumpCode(false), R600ALUInst(false), HasVertexCache(false), TexVTXClauseSize(0), Gen(AMDGPUSubtarget::R600), FP64(false), FP64Denormals(false), FP32Denormals(false), FastFMAF32(false), CaymanISA(false), FlatAddressSpace(false), EnableIRStructurizer(true), EnablePromoteAlloca(false), EnableIfCvt(true), EnableLoadStoreOpt(false), WavefrontSize(0), CFALUBug(false), LocalMemorySize(0), EnableVGPRSpilling(false), FrameLowering(TargetFrameLowering::StackGrowsUp, 64 * 16, // Maximum stack alignment (long16) 0), InstrItins(getInstrItineraryForCPU(GPU)), TargetTriple(TT) { initializeSubtargetDependencies(TT, GPU, FS); if (getGeneration() <= AMDGPUSubtarget::NORTHERN_ISLANDS) { InstrInfo.reset(new R600InstrInfo(*this)); TLInfo.reset(new R600TargetLowering(TM, *this)); } else { InstrInfo.reset(new SIInstrInfo(*this)); TLInfo.reset(new SITargetLowering(TM, *this)); } } unsigned AMDGPUSubtarget::getStackEntrySize() const { assert(getGeneration() <= NORTHERN_ISLANDS); switch(getWavefrontSize()) { case 16: return 8; case 32: return hasCaymanISA() ? 4 : 8; case 64: return 4; default: llvm_unreachable("Illegal wavefront size."); } } unsigned AMDGPUSubtarget::getAmdKernelCodeChipID() const { switch(getGeneration()) { default: llvm_unreachable("ChipID unknown"); case SEA_ISLANDS: return 12; } } bool AMDGPUSubtarget::isVGPRSpillingEnabled( const SIMachineFunctionInfo *MFI) const { return MFI->getShaderType() == ShaderType::COMPUTE || EnableVGPRSpilling; } void AMDGPUSubtarget::overrideSchedPolicy(MachineSchedPolicy &Policy, MachineInstr *begin, MachineInstr *end, unsigned NumRegionInstrs) const { if (getGeneration() >= SOUTHERN_ISLANDS) { // Track register pressure so the scheduler can try to decrease // pressure once register usage is above the threshold defined by // SIRegisterInfo::getRegPressureSetLimit() Policy.ShouldTrackPressure = true; // Enabling both top down and bottom up scheduling seems to give us less // register spills than just using one of these approaches on its own. Policy.OnlyTopDown = false; Policy.OnlyBottomUp = false; } }
/*++ Copyright (c) 1995-1996 Microsoft Corporation Module Name : Context.cxx Abstract: The file contains the implementation of the Context object. A context job is an object which stored in the logging request queue. Author: Terence Kwan ( terryk ) 18-Sep-1996 Project: IIS Logging 3.0 --*/ #include "precomp.hxx" #include "comlog.hxx" #include "iiscnfg.h" // // statics // CRITICAL_SECTION COMLOG_CONTEXT::sm_listLock; LIST_ENTRY COMLOG_CONTEXT::sm_ContextListHead; CHAR g_pszResFromGetComputerName [MAX_PATH] =""; VOID COMLOG_CONTEXT::LoadPluginModules( VOID ) /*++ Routine Description: load all the plugin module from the metabase Arguments: None. Return Value: None --*/ { DWORD cb; MB mb( (IMDCOM*) m_pvIMDCOM ); PCHAR p; CLSID clsid; WCHAR buf[MAX_PATH]; BUFFER szLoadOrder(1024); PCHAR pEnd; DWORD dwLogType; DWORD nPlugins = 0; PPLUGIN_NODE pluginNode; LPUNKNOWN punk; ILogPluginEx *pComponent; bool fExtended; HRESULT hr ; // // get the config information from the metabase // LockExclusive( ); if ( !mb.Open(m_strMetabasePath.QueryStr()) ) { DBGPRINTF((DBG_CONTEXT,"Unable to open MB path %s[err %x]\n", m_strMetabasePath.QueryStr(), GetLastError())); goto exit; } // // If logging disabled, bail out // if ( mb.GetDword( "", MD_LOG_TYPE, IIS_MD_UT_SERVER, &dwLogType)) { if ( dwLogType == MD_LOG_TYPE_DISABLED ) { DBGPRINTF((DBG_CONTEXT,"Logging disabled\n")); goto exit; } } // // Read the plugin order list // retry: cb = szLoadOrder.QuerySize( ); if ( !mb.GetString( "", MD_LOG_PLUGIN_ORDER, IIS_MD_UT_SERVER, (PCHAR)szLoadOrder.QueryPtr( ), &cb )) { DWORD err = GetLastError(); if ( err == ERROR_INSUFFICIENT_BUFFER ) { DBGPRINTF((DBG_CONTEXT,"Buff Too Small[%d] need[%d]\n", szLoadOrder.QuerySize(), cb )); if ( cb > szLoadOrder.QuerySize( ) ) { szLoadOrder.Resize( cb ); goto retry; } } DBGPRINTF((DBG_CONTEXT,"Error getting pluginOrder[err %x]\n", err)); mb.Close(); goto exit; } mb.Close(); // // Parse it // pEnd = (PCHAR)szLoadOrder.QueryPtr( ); for ( p = pEnd; pEnd != NULL; p = pEnd + 1 ) { if ( *p == '\0' ) { break; } // // pEnd will point to the next entry // pEnd = strchr(p, ','); if ( pEnd != NULL ) { *pEnd = '\0'; } // // p points to the CLSID // DBGPRINTF((DBG_CONTEXT,"Got Logging clsid %s\n",p)); if ( !TsIsNtServer() ) { // // odbc not allowed // if ( _stricmp(p,ODBCLOG_CLSID) == 0 ) { DBGPRINTF((DBG_CONTEXT,"ODBC logging not allowed for NTW\n")); continue; } } // // convert string to CLSID // mbstowcs( (WCHAR *)buf, p, MAX_PATH); hr = CLSIDFromString( buf, &clsid ); if (FAILED(hr)) { // // cannot convert string // DBGPRINTF((DBG_CONTEXT,"Cannot convert string to CLSID: %s\n",p)); continue; } hr = CoCreateInstance( clsid, NULL, CLSCTX_INPROC_SERVER, IID_IUnknown, (void **)&punk ); if (FAILED(hr)) { // // cannot convert string // DBGPRINTF((DBG_CONTEXT,"Cannot create instance: %s\n",p)); continue; } hr = punk->QueryInterface(IID_ILogPluginEx, (void **)&pComponent); if (SUCCEEDED(hr)) { fExtended = true; } else { fExtended = false; // // Try getting the older interface // hr = punk->QueryInterface(IID_ILogPlugin, (void **)&pComponent); } punk->Release(); if (FAILED(hr)) { DBGPRINTF((DBG_CONTEXT,"Unable to get the Extended or the Standard Plugin Interface.\n")); continue; } // // Add the component // pluginNode = (PPLUGIN_NODE)LocalAlloc( 0, sizeof(PLUGIN_NODE) ); if ( pluginNode == NULL ) { pComponent->Release( ); continue; } pluginNode->pComponent = pComponent; pluginNode->fSupportsExtendedInterface = fExtended; nPlugins++; InsertTailList(&m_pluginList, &pluginNode->ListEntry); // // Is this the default? // if ( _stricmp(p,EXTLOG_CLSID) == 0 ) { m_fDefault = TRUE; DBGPRINTF((DBG_CONTEXT,"Logging Extended[%d]\n", m_fDefault)); } } if ( nPlugins > 1 ) { m_fDefault = FALSE; } exit: Unlock( ); return; } // COMLOG_CONTEXT::LoadPlugInModules VOID COMLOG_CONTEXT::ReleasePluginModules( VOID ) { PLIST_ENTRY listEntry; PPLUGIN_NODE pluginModule; LockExclusive( ); m_fDefault = FALSE; while ( !IsListEmpty(&m_pluginList) ) { listEntry = RemoveHeadList( &m_pluginList ); pluginModule = (PPLUGIN_NODE)CONTAINING_RECORD( listEntry, PLUGIN_NODE, ListEntry ); pluginModule->pComponent->Release( ); LocalFree( pluginModule ); } Unlock( ); return; } // COMLOG_CONTEXT::ReleasePlugInModules COMLOG_CONTEXT::COMLOG_CONTEXT( LPCSTR pszInstanceName, LPCSTR pszMetabasePath, LPVOID pvIMDCOM ) : m_fDefault (FALSE), m_pvIMDCOM (pvIMDCOM) /*++ Routine Description: Constructor for clapi context object Arguments: pszInstanceName - name of the instance Return Value: --*/ { DWORD cbComputerNameSize = sizeof(g_pszResFromGetComputerName); MB mb( (IMDCOM*) m_pvIMDCOM ); InitializeListHead( &m_pluginList ); InitializeListHead( &m_PublicListEntry); m_strInstanceName.Copy(pszInstanceName); m_strMetabasePath.Copy(pszMetabasePath); if (g_pszResFromGetComputerName[0]==0) { if ( !GetComputerName( g_pszResFromGetComputerName, &cbComputerNameSize) ) { strcpy(g_pszResFromGetComputerName,"<Server>"); } } m_strComputerName.Copy(g_pszResFromGetComputerName); // // Add into the global list // EnterCriticalSection( &COMLOG_CONTEXT::sm_listLock ); InsertTailList( &COMLOG_CONTEXT::sm_ContextListHead, &m_ContextListEntry ); LeaveCriticalSection( &COMLOG_CONTEXT::sm_listLock ); // // Load all the plugin modules // LoadPluginModules( ); return; } // COMLOG_CONTEXT::COMLOG COMLOG_CONTEXT::~COMLOG_CONTEXT() /*++ Routine Description: destructor Arguments: Return Value: --*/ { PLIST_ENTRY listEntry; PInetLogPublic pPublic; EnterCriticalSection( &COMLOG_CONTEXT::sm_listLock ); LockExclusive(); RemoveEntryList(&m_ContextListEntry); ReleasePluginModules(); for ( listEntry = m_PublicListEntry.Flink; listEntry != &m_PublicListEntry; listEntry = listEntry->Flink ) { pPublic = (PInetLogPublic)CONTAINING_RECORD( listEntry, CInetLogPublic, m_ListEntry ); pPublic->m_pContext = NULL; } Unlock(); LeaveCriticalSection( &COMLOG_CONTEXT::sm_listLock ); } // COMLOG_CONTEXT::~COMLOG() VOID COMLOG_CONTEXT::LogInformation( PINETLOG_INFORMATION pLogInfo ) { PLIST_ENTRY listEntry; PPLUGIN_NODE plugin; CInetLogInformation inetLog; LockShared(); if ( m_pluginList.Flink != &m_pluginList ) { // logging is enabled inetLog.CanonicalizeLogRecord( pLogInfo, m_strInstanceName.QueryStr(), m_strComputerName.QueryStr(), m_fDefault ); for ( listEntry = m_pluginList.Flink; listEntry != &m_pluginList; listEntry = listEntry->Flink ) { plugin = (PPLUGIN_NODE)CONTAINING_RECORD( listEntry, PLUGIN_NODE, ListEntry ); plugin->pComponent->LogInformation( &inetLog ); } } Unlock(); } // COMLOG_CONTEXT::LogInformation VOID COMLOG_CONTEXT::LogInformation( IInetLogInformation *pLogObj ) { PLIST_ENTRY listEntry; PPLUGIN_NODE plugin; LockShared(); if ( m_pluginList.Flink != &m_pluginList ) { // logging is enabled for ( listEntry = m_pluginList.Flink; listEntry != &m_pluginList; listEntry = listEntry->Flink ) { plugin = (PPLUGIN_NODE)CONTAINING_RECORD( listEntry, PLUGIN_NODE, ListEntry ); plugin->pComponent->LogInformation( pLogObj ); } } Unlock(); } // COMLOG_CONTEXT::LogInformation VOID COMLOG_CONTEXT::LogCustomInformation( IN DWORD cCount, IN PCUSTOM_LOG_DATA pCustomLogData, IN LPSTR szHeaderSuffix ) { // // This function is supported only if the extended interface was found on the plugin // PLIST_ENTRY listEntry; PPLUGIN_NODE plugin; LockShared(); for ( listEntry = m_pluginList.Flink; listEntry != &m_pluginList; listEntry = listEntry->Flink ) { plugin = (PPLUGIN_NODE)CONTAINING_RECORD( listEntry, PLUGIN_NODE, ListEntry ); if (plugin->fSupportsExtendedInterface) { plugin->pComponent->LogCustomInformation( cCount, pCustomLogData, szHeaderSuffix); } } Unlock(); } // COMLOG_CONTEXT::LogCustomInformation VOID COMLOG_CONTEXT::NotifyChange( VOID ) { TerminateLog(); ReleasePluginModules( ); LoadPluginModules( ); InitializeLog( m_strInstanceName.QueryStr(), m_strMetabasePath.QueryStr(), (CHAR*)m_pvIMDCOM ); } // COMLOG_CONTEXT::NotifyChange VOID COMLOG_CONTEXT::GetConfig( IN INETLOG_CONFIGURATIONA *pConfigInfo ) { // // just return the first configuration information // PLIST_ENTRY listEntry; PPLUGIN_NODE plugin; LockShared( ); listEntry = m_pluginList.Flink; if (listEntry != &m_pluginList){ plugin = (PPLUGIN_NODE)CONTAINING_RECORD( listEntry, PLUGIN_NODE, ListEntry ); plugin->pComponent->GetConfig( sizeof(INETLOG_CONFIGURATIONA), (BYTE *)pConfigInfo); Unlock( ); return; } // // No Log // Unlock( ); pConfigInfo->inetLogType = INET_LOG_DISABLED; return; } // GetConfig VOID COMLOG_CONTEXT::SetConfig( IN INETLOG_CONFIGURATIONA *pConfigInfo ) { // // check the log type and call the proper setconfig function // MB mb( (IMDCOM*) m_pvIMDCOM ); // // NTW restrictions // if ( (pConfigInfo->inetLogType == INET_LOG_TO_SQL) && !TsIsNtServer() ) { return; } if ( !mb.Open( m_strMetabasePath.QueryStr(), METADATA_PERMISSION_READ | METADATA_PERMISSION_WRITE )) { return; } // // Release all // ReleasePluginModules( ); switch (pConfigInfo->inetLogType) { case INET_LOG_TO_FILE: switch (pConfigInfo->u.logFile.ilFormat) { case INET_LOG_FORMAT_INTERNET_STD: mb.SetString("", MD_LOG_PLUGIN_ORDER, IIS_MD_UT_SERVER, ASCLOG_CLSID ); break; case INET_LOG_FORMAT_NCSA: mb.SetString("", MD_LOG_PLUGIN_ORDER, IIS_MD_UT_SERVER, NCSALOG_CLSID ); break; case INET_LOG_FORMAT_EXTENDED: mb.SetString("", MD_LOG_PLUGIN_ORDER, IIS_MD_UT_SERVER, EXTLOG_CLSID ); mb.SetDword( "", MD_LOGEXT_FIELD_MASK, IIS_MD_UT_SERVER, pConfigInfo->u.logFile.dwFieldMask ); break; default: DBGPRINTF((DBG_CONTEXT,"SetConfig: Invalid Format type %d\n", pConfigInfo->inetLogType)); goto no_log; } mb.SetDword( "", MD_LOGFILE_PERIOD, IIS_MD_UT_SERVER, pConfigInfo->u.logFile.ilPeriod ); if (pConfigInfo->u.logFile.ilPeriod == INET_LOG_PERIOD_NONE ) { mb.SetDword( "", MD_LOGFILE_TRUNCATE_SIZE, IIS_MD_UT_SERVER, pConfigInfo-> u.logFile.cbSizeForTruncation ); } mb.SetString( "", MD_LOGFILE_DIRECTORY, IIS_MD_UT_SERVER, pConfigInfo->u.logFile.rgchLogFileDirectory ); mb.SetDword( "", MD_LOG_TYPE, IIS_MD_UT_SERVER, MD_LOG_TYPE_ENABLED ); break; case INET_LOG_TO_SQL: mb.SetString("", MD_LOG_PLUGIN_ORDER, IIS_MD_UT_SERVER, ODBCLOG_CLSID ); mb.SetString( "", MD_LOGSQL_DATA_SOURCES, IIS_MD_UT_SERVER, pConfigInfo->u.logSql.rgchDataSource ); mb.SetString( "", MD_LOGSQL_TABLE_NAME, IIS_MD_UT_SERVER, pConfigInfo->u.logSql.rgchTableName ); mb.SetString( "", MD_LOGSQL_USER_NAME, IIS_MD_UT_SERVER, pConfigInfo->u.logSql.rgchUserName ); mb.SetString( "", MD_LOGSQL_PASSWORD, IIS_MD_UT_SERVER, pConfigInfo->u.logSql.rgchPassword, METADATA_INHERIT|METADATA_SECURE ); mb.SetDword( "", MD_LOG_TYPE, IIS_MD_UT_SERVER, MD_LOG_TYPE_ENABLED ); break; case INET_LOG_DISABLED: default: goto no_log; } exit: mb.Save(); mb.Close(); return; no_log: mb.SetString( "", MD_LOG_PLUGIN_ORDER, IIS_MD_UT_SERVER, "" ); mb.SetDword( "", MD_LOG_TYPE, IIS_MD_UT_SERVER, MD_LOG_TYPE_DISABLED ); goto exit; } // COMLOG_CONTEXT::SetConfig VOID COMLOG_CONTEXT::QueryExtraLogFields( PDWORD pcbSize, PCHAR pszLogFields ) { PLIST_ENTRY listEntry; PPLUGIN_NODE plugin; LockShared( ); listEntry = m_pluginList.Flink; if (listEntry != &m_pluginList){ plugin = (PPLUGIN_NODE)CONTAINING_RECORD( listEntry, PLUGIN_NODE, ListEntry ); plugin->pComponent->QueryExtraLoggingFields( pcbSize, pszLogFields ); // // handle just the 1st component // Unlock( ); return; } Unlock( ); *pcbSize = 0; *pszLogFields = '\0'; return; } // COMLOG_CONTEXT::QueryExtraLogFields VOID COMLOG_CONTEXT::InitializeLog( LPCSTR pszInstanceName, LPCSTR pszMetabasePath, LPVOID ) { PLIST_ENTRY listEntry; PPLUGIN_NODE plugin; LockExclusive(); for ( listEntry = m_pluginList.Flink; listEntry != &m_pluginList; listEntry = listEntry->Flink ) { plugin = (PPLUGIN_NODE)CONTAINING_RECORD( listEntry, PLUGIN_NODE, ListEntry ); plugin->pComponent->InitializeLog( pszInstanceName, pszMetabasePath, (PCHAR)m_pvIMDCOM ); if ( m_fDefault ) { INETLOG_CONFIGURATIONA config; m_fDefault = FALSE; if ( SUCCEEDED( plugin->pComponent->GetConfig( sizeof(config), (PBYTE)&config ) ) ) { if ( (config.u.logFile.ilFormat == INET_LOG_FORMAT_EXTENDED) && (config.u.logFile.dwFieldMask == DEFAULT_EXTLOG_FIELDS) ) { m_fDefault = TRUE; } } } } Unlock(); } // COMLOG_CONTEXT::InitializeLog VOID COMLOG_CONTEXT::TerminateLog( VOID ) { PLIST_ENTRY listEntry; PPLUGIN_NODE plugin; LockExclusive( ); for ( listEntry = m_pluginList.Flink; listEntry != &m_pluginList; listEntry = listEntry->Flink ) { plugin = (PPLUGIN_NODE)CONTAINING_RECORD( listEntry, PLUGIN_NODE, ListEntry ); plugin->pComponent->TerminateLog( ); } Unlock( ); } // COMLOG_CONTEXT::TerminateLog
/* * * Copyright (c) 2021 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "qvCHIP.h" #include "AppConfig.h" #include "AppEvent.h" #include "AppTask.h" #include "OnboardingCodesUtil.h" #include "Server.h" #include "attribute-storage.h" #include "gen/attribute-id.h" #include "gen/attribute-type.h" #include "gen/cluster-id.h" #include "Service.h" #include <setup_payload/QRCodeSetupPayloadGenerator.h> #include <setup_payload/SetupPayload.h> using namespace chip::TLV; using namespace chip::DeviceLayer; #include <platform/CHIPDeviceLayer.h> #if CHIP_ENABLE_OPENTHREAD #include <platform/OpenThread/OpenThreadUtils.h> #include <platform/ThreadStackManager.h> #include <platform/qpg6100/ThreadStackManagerImpl.h> #define JOINER_START_TRIGGER_TIMEOUT 1500 #endif #define FACTORY_RESET_TRIGGER_TIMEOUT 3000 #define FACTORY_RESET_CANCEL_WINDOW_TIMEOUT 3000 #define APP_TASK_STACK_SIZE (2048) #define APP_TASK_PRIORITY 2 #define APP_EVENT_QUEUE_SIZE 10 static TaskHandle_t sAppTaskHandle; static QueueHandle_t sAppEventQueue; static bool sIsThreadProvisioned = false; static bool sIsThreadEnabled = false; static bool sHaveBLEConnections = false; static bool sHaveServiceConnectivity = false; AppTask AppTask::sAppTask; int AppTask::StartAppTask() { sAppEventQueue = xQueueCreate(APP_EVENT_QUEUE_SIZE, sizeof(AppEvent)); if (sAppEventQueue == NULL) { ChipLogError(NotSpecified, "Failed to allocate app event queue"); return CHIP_ERROR_NO_MEMORY; } // Start App task. if (xTaskCreate(AppTaskMain, "APP", APP_TASK_STACK_SIZE / sizeof(StackType_t), NULL, 1, &sAppTaskHandle) != pdPASS) { return CHIP_ERROR_NO_MEMORY; } return CHIP_NO_ERROR; } int AppTask::Init() { CHIP_ERROR err = CHIP_NO_ERROR; ChipLogProgress(NotSpecified, "Current Firmware Version: %s", CHIP_DEVICE_CONFIG_DEVICE_FIRMWARE_REVISION); err = LightingMgr().Init(); if (err != CHIP_NO_ERROR) { ChipLogError(NotSpecified, "LightingMgr().Init() failed"); return err; } LightingMgr().SetCallbacks(ActionInitiated, ActionCompleted); // Subscribe with our button callback to the qvCHIP button handler. qvCHIP_SetBtnCallback(ButtonEventHandler); // Init ZCL Data Model InitServer(); UpdateClusterState(); ConfigurationMgr().LogDeviceConfig(); PrintOnboardingCodes(chip::RendezvousInformationFlags(chip::RendezvousInformationFlag::kBLE)); return err; } void AppTask::AppTaskMain(void * pvParameter) { int err; AppEvent event; uint64_t mLastChangeTimeUS = 0; err = sAppTask.Init(); if (err != CHIP_NO_ERROR) { ChipLogError(NotSpecified, "AppTask.Init() failed"); // appError(err); } ChipLogProgress(NotSpecified, "App Task started"); SetDeviceName("QPG6100LightingDemo._chip._udp.local."); while (true) { BaseType_t eventReceived = xQueueReceive(sAppEventQueue, &event, pdMS_TO_TICKS(10)); while (eventReceived == pdTRUE) { sAppTask.DispatchEvent(&event); eventReceived = xQueueReceive(sAppEventQueue, &event, 0); } // Collect connectivity and configuration state from the CHIP stack. Because // the CHIP event loop is being run in a separate task, the stack must be // locked while these values are queried. However we use a non-blocking // lock request (TryLockCHIPStack()) to avoid blocking other UI activities // when the CHIP task is busy (e.g. with a long crypto operation). if (PlatformMgr().TryLockChipStack()) { sIsThreadProvisioned = ConnectivityMgr().IsThreadProvisioned(); sIsThreadEnabled = ConnectivityMgr().IsThreadEnabled(); sHaveBLEConnections = (ConnectivityMgr().NumBLEConnections() != 0); sHaveServiceConnectivity = ConnectivityMgr().HaveServiceConnectivity(); PlatformMgr().UnlockChipStack(); } // Update the status LED if factory reset has not been initiated. // // If system has "full connectivity", keep the LED On constantly. // // If thread and service provisioned, but not attached to the thread network // yet OR no connectivity to the service OR subscriptions are not fully // established THEN blink the LED Off for a short period of time. // // If the system has ble connection(s) uptill the stage above, THEN blink // the LEDs at an even rate of 100ms. // // Otherwise, blink the LED ON for a very short time. if (sAppTask.mFunction != kFunction_FactoryReset) { // Consider the system to be "fully connected" if it has service // connectivity if (sHaveServiceConnectivity) { qvCHIP_LedSet(SYSTEM_STATE_LED, true); } else if (sIsThreadProvisioned && sIsThreadEnabled) { qvCHIP_LedBlink(SYSTEM_STATE_LED, 950, 50); } else if (sHaveBLEConnections) { qvCHIP_LedBlink(SYSTEM_STATE_LED, 100, 100); } else { qvCHIP_LedBlink(SYSTEM_STATE_LED, 50, 950); } } uint64_t nowUS = chip::System::Layer::GetClock_Monotonic(); uint64_t nextChangeTimeUS = mLastChangeTimeUS + 5 * 1000 * 1000UL; if (nowUS > nextChangeTimeUS) { PublishService(); mLastChangeTimeUS = nowUS; } } } void AppTask::LightingActionEventHandler(AppEvent * aEvent) { LightingManager::Action_t action; if (aEvent->Type == AppEvent::kEventType_Button) { if (LightingMgr().IsTurnedOn()) { action = LightingManager::OFF_ACTION; } else { action = LightingManager::ON_ACTION; } LightingMgr().InitiateAction(action, 0, 0, 0); } if (aEvent->Type == AppEvent::kEventType_Level && aEvent->ButtonEvent.Action != 0) { uint8_t val = 0x0; val = LightingMgr().GetLevel() == 0x7f ? 0x1 : 0x7f; action = LightingManager::LEVEL_ACTION; LightingMgr().InitiateAction(action, 0, 1, &val); } return; } void AppTask::ButtonEventHandler(uint8_t btnIdx, bool btnPressed) { ChipLogProgress(NotSpecified, "ButtonEventHandler %d, %d", btnIdx, btnPressed); if (btnIdx != APP_ON_OFF_BUTTON && btnIdx != APP_FUNCTION_BUTTON && btnIdx != APP_LEVEL_BUTTON) { return; } AppEvent button_event = {}; button_event.Type = AppEvent::kEventType_Button; button_event.ButtonEvent.ButtonIdx = btnIdx; button_event.ButtonEvent.Action = btnPressed; if (btnIdx == APP_ON_OFF_BUTTON && btnPressed == true) { button_event.Handler = LightingActionEventHandler; sAppTask.PostEvent(&button_event); } else if (btnIdx == APP_LEVEL_BUTTON) { button_event.Type = AppEvent::kEventType_Level; button_event.Handler = LightingActionEventHandler; sAppTask.PostEvent(&button_event); } else if (btnIdx == APP_FUNCTION_BUTTON) { button_event.Type = AppEvent::kEventType_Level; button_event.Handler = FunctionHandler; sAppTask.PostEvent(&button_event); } } void AppTask::TimerEventHandler(chip::System::Layer * aLayer, void * aAppState, chip::System::Error aError) { AppEvent event; event.Type = AppEvent::kEventType_Timer; event.TimerEvent.Context = aAppState; event.Handler = FunctionTimerEventHandler; sAppTask.PostEvent(&event); } void AppTask::FunctionTimerEventHandler(AppEvent * aEvent) { if (aEvent->Type != AppEvent::kEventType_Timer) { return; } // If we reached here, the button was held past FACTORY_RESET_TRIGGER_TIMEOUT, // initiate factory reset if (sAppTask.mFunctionTimerActive && sAppTask.mFunction == kFunction_SoftwareUpdate) { #if CHIP_ENABLE_OPENTHREAD ChipLogProgress(NotSpecified, "Release button now to Start Thread Joiner"); ChipLogProgress(NotSpecified, "Hold to trigger Factory Reset"); sAppTask.mFunction = kFunction_Joiner; sAppTask.StartTimer(FACTORY_RESET_TRIGGER_TIMEOUT); } else if (sAppTask.mFunctionTimerActive && sAppTask.mFunction == kFunction_Joiner) { #endif ChipLogProgress(NotSpecified, "Factory Reset Triggered. Release button within %ums to cancel.", FACTORY_RESET_CANCEL_WINDOW_TIMEOUT); // Start timer for FACTORY_RESET_CANCEL_WINDOW_TIMEOUT to allow user to // cancel, if required. sAppTask.StartTimer(FACTORY_RESET_CANCEL_WINDOW_TIMEOUT); sAppTask.mFunction = kFunction_FactoryReset; // Turn off all LEDs before starting blink to make sure blink is // co-ordinated. qvCHIP_LedSet(SYSTEM_STATE_LED, false); qvCHIP_LedBlink(SYSTEM_STATE_LED, 500, 500); } else if (sAppTask.mFunctionTimerActive && sAppTask.mFunction == kFunction_FactoryReset) { // Actually trigger Factory Reset sAppTask.mFunction = kFunction_NoneSelected; ConfigurationMgr().InitiateFactoryReset(); } } void AppTask::FunctionHandler(AppEvent * aEvent) { if (aEvent->ButtonEvent.ButtonIdx != APP_FUNCTION_BUTTON) { return; } // To trigger software update: press the APP_FUNCTION_BUTTON button briefly (< // FACTORY_RESET_TRIGGER_TIMEOUT) To initiate factory reset: press the // APP_FUNCTION_BUTTON for FACTORY_RESET_TRIGGER_TIMEOUT + // FACTORY_RESET_CANCEL_WINDOW_TIMEOUT All LEDs start blinking after // FACTORY_RESET_TRIGGER_TIMEOUT to signal factory reset has been initiated. // To cancel factory reset: release the APP_FUNCTION_BUTTON once all LEDs // start blinking within the FACTORY_RESET_CANCEL_WINDOW_TIMEOUT if (aEvent->ButtonEvent.Action == true) { if (!sAppTask.mFunctionTimerActive && sAppTask.mFunction == kFunction_NoneSelected) { #if CHIP_ENABLE_OPENTHREAD sAppTask.StartTimer(JOINER_START_TRIGGER_TIMEOUT); #else sAppTask.StartTimer(FACTORY_RESET_TRIGGER_TIMEOUT); #endif sAppTask.mFunction = kFunction_SoftwareUpdate; } } else { // If the button was released before factory reset got initiated, trigger a // software update. if (sAppTask.mFunctionTimerActive && sAppTask.mFunction == kFunction_SoftwareUpdate) { sAppTask.CancelTimer(); sAppTask.mFunction = kFunction_NoneSelected; ChipLogError(NotSpecified, "Software Update currently not supported."); } #if CHIP_ENABLE_OPENTHREAD else if (sAppTask.mFunctionTimerActive && sAppTask.mFunction == kFunction_Joiner) { sAppTask.CancelTimer(); sAppTask.mFunction = kFunction_NoneSelected; CHIP_ERROR error = ThreadStackMgr().JoinerStart(); ChipLogProgress(NotSpecified, "Thread joiner triggered: %s", chip::ErrorStr(error)); } #endif else if (sAppTask.mFunctionTimerActive && sAppTask.mFunction == kFunction_FactoryReset) { sAppTask.CancelTimer(); // Change the function to none selected since factory reset has been // canceled. sAppTask.mFunction = kFunction_NoneSelected; ChipLogProgress(NotSpecified, "Factory Reset has been Canceled"); } } } void AppTask::CancelTimer() { SystemLayer.CancelTimer(TimerEventHandler, this); mFunctionTimerActive = false; } void AppTask::StartTimer(uint32_t aTimeoutInMs) { CHIP_ERROR err; SystemLayer.CancelTimer(TimerEventHandler, this); err = SystemLayer.StartTimer(aTimeoutInMs, TimerEventHandler, this); SuccessOrExit(err); mFunctionTimerActive = true; exit: if (err != CHIP_NO_ERROR) { ChipLogError(NotSpecified, "StartTimer failed %s: ", chip::ErrorStr(err)); } } void AppTask::ActionInitiated(LightingManager::Action_t aAction) { // Placeholder for light action if (aAction == LightingManager::ON_ACTION) { ChipLogProgress(NotSpecified, "Light goes on"); } else if (aAction == LightingManager::OFF_ACTION) { ChipLogProgress(NotSpecified, "Light goes off "); } } void AppTask::ActionCompleted(LightingManager::Action_t aAction) { // Placeholder for light action completed if (aAction == LightingManager::ON_ACTION) { ChipLogProgress(NotSpecified, "Light On Action has been completed"); } else if (aAction == LightingManager::OFF_ACTION) { ChipLogProgress(NotSpecified, "Light Off Action has been completed"); } if (sAppTask.mSyncClusterToButtonAction) { sAppTask.UpdateClusterState(); sAppTask.mSyncClusterToButtonAction = false; } } void AppTask::PostEvent(const AppEvent * aEvent) { if (sAppEventQueue != NULL) { if (!xQueueSend(sAppEventQueue, aEvent, 1)) { ChipLogError(NotSpecified, "Failed to post event to app task event queue"); } } } void AppTask::DispatchEvent(AppEvent * aEvent) { if (aEvent->Handler) { aEvent->Handler(aEvent); } else { ChipLogError(NotSpecified, "Event received with no handler. Dropping event."); } } void AppTask::UpdateClusterState(void) { uint8_t newValue = !LightingMgr().IsTurnedOn(); // write the new on/off value EmberAfStatus status = emberAfWriteAttribute(1, ZCL_ON_OFF_CLUSTER_ID, ZCL_ON_OFF_ATTRIBUTE_ID, CLUSTER_MASK_SERVER, (uint8_t *) &newValue, ZCL_BOOLEAN_ATTRIBUTE_TYPE); if (status != EMBER_ZCL_STATUS_SUCCESS) { ChipLogError(NotSpecified, "ERR: updating on/off %x", status); } ChipLogProgress(NotSpecified, "UpdateClusterState"); newValue = LightingMgr().GetLevel(); // TODO understand well enough to implement the level cluster ZCL_CURRENT_LEVEL_ATTRIBUTE_ID status = emberAfWriteAttribute(1, ZCL_LEVEL_CONTROL_CLUSTER_ID, ZCL_CURRENT_LEVEL_ATTRIBUTE_ID, CLUSTER_MASK_SERVER, (uint8_t *) &newValue, ZCL_DATA8_ATTRIBUTE_TYPE); if (status != EMBER_ZCL_STATUS_SUCCESS) { ChipLogError(NotSpecified, "ERR: updating level %x", status); } }
/* ///////////////////////////////////////////////////////////////////////// * File: test/scratch/test.scratch.be.speech/test.scratch.be.speech.cpp * * Purpose: C++ example program for Pantheios. Demonstrates: * * - use of custom severity level information for tabbing output * - definition of a custom back-end that supports tabbed output * - use of pantheios::logputs() in bail-out conditions * * Created: 31st August 2006 * Updated: 6th August 2012 * * www: http://www.pantheios.org/ * * License: This source code is placed into the public domain 2006 * by Synesis Software Pty Ltd. There are no restrictions * whatsoever to your use of the software. * * This software is provided "as is", and any warranties, * express or implied, of any kind and for any purpose, are * disclaimed. * * ////////////////////////////////////////////////////////////////////// */ /* This inclusion required for suppressing warnings during NoX (No eXception-support) configurations. */ #include <pantheios/util/test/compiler_warnings_suppression.first_include.h> /* Pantheios Header Files */ #include <pantheios/pantheios.hpp> #include <pantheios/backend.h> #include <pantheios/implicit_link/core.h> #include <pantheios/implicit_link/fe.simple.h> #include <pantheios/implicit_link/be.lrsplit.h> #include <pantheios/implicit_link/bel.WindowsConsole.h> #include <pantheios/implicit_link/bec.speech.WithCallback.h> #include <pantheios/backends/bec.speech.h> /* Standard C/C++ Header Files */ #include <exception> // for std::exception #include <string> // for std::string #include <stdio.h> // for fprintf() #include <stdlib.h> // for exit codes #include <string.h> // for memset() #include <pantheios/util/test/compiler_warnings_suppression.last_include.h> /* ////////////////////////////////////////////////////////////////////// */ // Define the fe.simple process identity, so that it links when using fe.simple PANTHEIOS_EXTERN_C PAN_CHAR_T const PANTHEIOS_FE_PROCESS_IDENTITY[] = PANTHEIOS_LITERAL_STRING("test.scratch.speech"); /* ////////////////////////////////////////////////////////////////////// */ //PANTHEIOS_BE_DEFINE_BE_FUNCTIONS(speech) PANTHEIOS_BE_DEFINE_BER_FUNCTIONS(speech) PANTHEIOS_CALL(void) pantheios_be_speech_getAppInit(int backEndId, pan_be_speech_init_t* init) /* throw() */ { // init->flags |= PANTHEIOS_BE_SPEECH_F_SYNCHRONOUS; // init->flags |= PANTHEIOS_BE_SPEECH_F_PURGE_BEFORE_SPEAK; // init->flags |= PANTHEIOS_BE_SPEECH_F_SPEAK_PUNCTUATION; // init->flags |= PANTHEIOS_BE_SPEECH_F_SYNCHRONOUS_ON_CRITICAL; } /* ////////////////////////////////////////////////////////////////////// */ int main() { DWORD shortPause = 1250; try { // pantheios::log(pantheios::notice, "Hello"); // ::Sleep(shortPause); // pantheios::log(pantheios::notice(2), "Hello"); // ::Sleep(shortPause); // pantheios::log(pantheios::notice(2), "Hello, boys. This is your daddy, telling you to turn around and eat your dinner. Now!"); // ::Sleep(shortPause); short s = SHRT_MIN; unsigned short us = USHRT_MAX; int i = INT_MIN; unsigned int ui = UINT_MAX; long l = LONG_MIN; unsigned long ul = ULONG_MAX; #if 0 // Log a short in decimal; Output: "s: [-32768]" pantheios::log_NOTICE("s: [", pantheios::integer(s), "]"); ::Sleep(shortPause); // Log a unsigned short as hexadecimal; Output: "us: [ffff]" pantheios::log_NOTICE("us: [", pantheios::integer(us, pantheios::fmt::hex), "]"); ::Sleep(shortPause); // Log an int, into a width of 20; Output: "i: [-2147483648 ]" pantheios::log_NOTICE("i: [", pantheios::integer(i, -20), "]"); ::Sleep(shortPause); // Log an unsigned int as hexadecimal with 0x prefix; Output: "ui: [0xffffffff]" pantheios::log_NOTICE("ui: [", pantheios::integer(ui, pantheios::fmt::hex | pantheios::fmt::zeroXPrefix), "]"); ::Sleep(shortPause); // Log a long; Output: "l: [ -2147483648]" pantheios::log_NOTICE("l: [", pantheios::integer(l, 20), "]"); ::Sleep(shortPause); // Log an unsigned long; Output: "ul: [4294967295]" pantheios::log_NOTICE("ul: [", pantheios::integer(ul), "]"); ::Sleep(shortPause); #else /* ? 0 */ pantheios::log_NOTICE("Hi!"); ::Sleep(shortPause); pantheios::log_NOTICE("This is your logger, calling."); ::Sleep(shortPause); pantheios::log_NOTICE("Here come some diagnostic logging statements ..."); ::Sleep(shortPause); #endif /* 0 */ pantheios::log_DEBUG("just being pedantic"); ::Sleep(shortPause); pantheios::log_INFORMATIONAL("you can ignore this"); ::Sleep(shortPause); pantheios::log_NOTICE("this is noteworthy"); ::Sleep(shortPause); pantheios::log_WARNING("there may be a problem"); ::Sleep(shortPause); pantheios::log_ERROR("there is a problem"); ::Sleep(shortPause); pantheios::log_CRITICAL("there is a serious problem"); ::Sleep(shortPause); pantheios::log_ALERT("there is a very serious problem"); ::Sleep(shortPause); pantheios::log_EMERGENCY("aargh! I'm operating in contradiction to my design!"); ::Sleep(90000); return EXIT_SUCCESS; } catch(std::bad_alloc &) { pantheios::log_CRITICAL("out of memory"); } catch(std::exception &x) { pantheios::log_ALERT("Exception: ", x); } catch(...) { pantheios::logputs(pantheios::emergency, "Unexpected unknown error"); } return EXIT_FAILURE; } /* ////////////////////////////////////////////////////////////////////// */
#include<bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; long long dp[n + 1]; bool vis[n + 1]; memset(vis, false, sizeof(0)); function<long long(int)> fibo = [&](int n) { auto &ans = dp[n]; auto &seen = vis[n]; if (!seen) { seen = true; if (n <= 1) { ans = n; return ans; } ans = fibo(n - 1) + fibo(n - 2); } return ans; }; long long x = fibo(n); for (int i = 0; i < n; i++) { cout << dp[i] << "\n"; } }
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkCompareImageSliceTestHelper.h" #include "mitkCoreObjectFactory.h" #include "mitkExtractImageFilter.h" #include "mitkOverwriteSliceImageFilter.h" #include <mitkIOUtil.h> unsigned int CompareImageSliceTestHelper::m_Dimension0 = 0; unsigned int CompareImageSliceTestHelper::m_Dimension1 = 0; unsigned int CompareImageSliceTestHelper::m_SliceDimension = 0; unsigned int CompareImageSliceTestHelper::m_SliceIndex = 0; bool CompareImageSliceTestHelper::m_ComparisonResult = false; mitk::Image *CompareImageSliceTestHelper::m_SliceImage = nullptr; class mitkOverwriteSliceImageFilterTestClass { public: static void Test3D(mitk::OverwriteSliceImageFilter *filter, mitk::Image *image, unsigned int &numberFailed) { assert(filter); assert(image); filter->SetInput(image); unsigned int initialNumberFailed = numberFailed; bool exception = false; // first extract slices and rewrite them for (unsigned int sliceDimension = 0; sliceDimension < 3; ++sliceDimension) { mitk::ExtractImageFilter::Pointer extractor = mitk::ExtractImageFilter::New(); extractor->SetInput(image); extractor->SetSliceDimension(sliceDimension); extractor->SetSliceIndex(2); // third slice in that direction try { extractor->Update(); } catch (...) { if (sliceDimension < 3) { // probably no sliceindex 2 there or extractor just doesn't work (check the corresponding test) std::cout << " (WW) Couldn't extract slice number 3 from a 3D image. This could be a problem if the image " "is not only two slices big." << std::endl; continue; } else { continue; // good } } mitk::Image::Pointer slice = extractor->GetOutput()->Clone(); filter->SetSliceDimension(sliceDimension); filter->SetSliceIndex(1); // second slice in that direction filter->SetSliceImage(slice); try { filter->Update(); // try to overwrite } catch (...) { if (sliceDimension < 3) { ++numberFailed; std::cerr << " (EE) Couln't overwrite a slice with data from a neigbor in a " << image->GetDimension() << "-dimensional image, sliceDimension " << sliceDimension << " sliceIndex 1-2." << "(l. " << __LINE__ << ")" << std::endl; } else { // this was expected and is nice to see continue; } } mitk::Image::Pointer output = filter->GetOutput(); if (output.IsNull()) { ++numberFailed; std::cerr << " (EE) Overwrite filter has output nullptr and gave no exception for an " << image->GetDimension() << "-dimensional image, sliceDimension " << sliceDimension << " sliceIndex 1-2." << "(l. " << __LINE__ << ")" << std::endl; continue; } if (!CompareImageSliceTestHelper::CompareSlice(image, sliceDimension, 1, slice)) { ++numberFailed; std::cerr << " (EE) Overwriting a slice seemed to work, but the pixels are not correct for an " << image->GetDimension() << "-dimensional image, sliceDimension " << sliceDimension << " sliceIndex 1-2." << "(l. " << __LINE__ << ")" << std::endl; } // try inserting at a position outside the image filter->SetSliceDimension(sliceDimension); filter->SetSliceIndex(image->GetDimension(sliceDimension)); // last possible slice index + 1 filter->SetSliceImage(slice); exception = false; try { filter->Update(); // try to overwrite } catch (...) { exception = true; } if (!exception) { ++numberFailed; std::cerr << " (EE) Inserting a slice outside the 3D volume did NOT throw an exception for an " << image->GetDimension() << "-dimensional image, sliceDimension " << sliceDimension << " sliceIndex 1-2." << "(l. " << __LINE__ << ")" << std::endl; } mitk::Image::Pointer originalSlice = slice; // now test slices that just don't fit (slice too big) { unsigned int dim[] = {slice->GetDimension(0) + 2, slice->GetDimension(1) + 2}; slice = mitk::Image::New(); slice->Initialize(mitk::MakeScalarPixelType<signed int>(), 2, dim); unsigned int i; mitk::ImageWriteAccessor accessor(slice); auto *p = (signed int *)accessor.GetData(); unsigned int size = dim[0] * dim[1]; for (i = 0; i < size; ++i, ++p) *p = (signed int)i; // try to insert this bad slice filter->SetSliceImage(slice); exception = false; try { filter->Update(); // try to overwrite } catch (...) { exception = true; } if (!exception) { ++numberFailed; std::cerr << " (EE) Trying to insert a slice of bad dimensions (larger) did NOT throw an exception in an " << image->GetDimension() << "-dimensional image, sliceDimension " << sliceDimension << " sliceIndex 1-2." << "(l. " << __LINE__ << ")" << std::endl; } } // now test slices that just don't fit (slice too small) { slice = originalSlice; if ((slice->GetDimension(0) < 3) || (slice->GetDimension(1) < 3)) continue; // not possible shrink the image much further unsigned int dim[] = {slice->GetDimension(0) - 2, slice->GetDimension(1) - 2}; slice = mitk::Image::New(); slice->Initialize(mitk::MakeScalarPixelType<signed int>(), 2, dim); unsigned int i; mitk::ImageWriteAccessor accessor(slice); auto *p = (signed int *)accessor.GetData(); unsigned int size = dim[0] * dim[1]; for (i = 0; i < size; ++i, ++p) *p = (signed int)i; // try to insert this bad slice filter->SetSliceImage(slice); exception = false; try { filter->Update(); // try to overwrite } catch (...) { exception = true; } if (!exception) { ++numberFailed; std::cerr << " (EE) Trying to insert a slice of bad dimensions (smaller) did NOT throw an exception in an " << image->GetDimension() << "-dimensional image, sliceDimension " << sliceDimension << " sliceIndex 1-2." << "(l. " << __LINE__ << ")" << std::endl; } } } if (numberFailed == initialNumberFailed) { std::cout << " (II) Overwriting works nicely (gives result, pixels are good) " << image->GetDimension() << "-dimensional image." << "(l. " << __LINE__ << ")" << std::endl; } } static void Test2D(mitk::OverwriteSliceImageFilter *filter, mitk::Image *image, unsigned int &numberFailed) { assert(filter); assert(image); filter->SetInput(image); filter->SetSliceImage(image); bool exception = false; try { filter->Update(); } catch (...) { exception = true; } if (!exception) { std::cerr << " (EE) Using OverwriteImageFilter for 2D -> 2D did not throw an exception " << "(l. " << __LINE__ << ")" << std::endl; } unsigned int initialNumberFailed = numberFailed; if (numberFailed == initialNumberFailed) { std::cout << " (II) Overwriting works nicely (gives result, pixels are good) " << image->GetDimension() << "-dimensional image." << "(l. " << __LINE__ << ")" << std::endl; } } static void TestOtherD(mitk::OverwriteSliceImageFilter *filter, mitk::Image *image, unsigned int &numberFailed) { assert(filter); assert(image); filter->SetInput(image); filter->SetSliceImage(image); bool exception = false; try { filter->Update(); } catch (...) { exception = true; } if (!exception) { std::cerr << " (EE) Using OverwriteImageFilter did not throw an exception " << "(l. " << __LINE__ << ")" << std::endl; } unsigned int initialNumberFailed = numberFailed; if (numberFailed == initialNumberFailed) { std::cout << " (II) Overwriting works nicely (gives result, pixels are good) " << image->GetDimension() << "-dimensional image." << "(l. " << __LINE__ << ")" << std::endl; } } }; /// ctest entry point int mitkOverwriteSliceImageFilterTest(int argc, char *argv[]) { // one big variable to tell if anything went wrong unsigned int numberFailed(0); // need one parameter (image filename) if (argc == 0) { std::cerr << "No file specified [FAILED]" << std::endl; return EXIT_FAILURE; } // load the image mitk::Image::Pointer image = nullptr; try { MITK_INFO << "Testing with parameter '" << argv[1] << "'"; std::string pathToImage(argv[1]); image = mitk::IOUtil::Load<mitk::Image>(pathToImage); if (image.IsNull()) { MITK_INFO << "File not an image - test will not be applied"; return EXIT_FAILURE; } } catch (itk::ExceptionObject &ex) { ++numberFailed; std::cerr << "Exception: " << ex << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << " (II) Could load image." << std::endl; std::cout << "Testing filter instantiation" << std::endl; // instantiation mitk::OverwriteSliceImageFilter::Pointer filter = mitk::OverwriteSliceImageFilter::New(); if (filter.IsNotNull()) { std::cout << " (II) Instantiation works." << std::endl; } else { ++numberFailed; std::cout << "Test failed, and it's the ugliest one!" << std::endl; return EXIT_FAILURE; } // some real work if (image->GetDimension() == 2) { mitkOverwriteSliceImageFilterTestClass::Test2D(filter, image, numberFailed); } else if (image->GetDimension() == 3) { mitkOverwriteSliceImageFilterTestClass::Test3D(filter, image, numberFailed); } else { mitkOverwriteSliceImageFilterTestClass::TestOtherD(filter, image, numberFailed); } std::cout << "Testing filter destruction" << std::endl; // freeing filter = nullptr; std::cout << " (II) Freeing works." << std::endl; if (numberFailed > 0) { std::cerr << numberFailed << " tests failed." << std::endl; return EXIT_FAILURE; } else { std::cout << "PASSED all tests." << std::endl; return EXIT_SUCCESS; } }
/* Copyright (C) Renata P. Baptista & Vinicius M. de Pinho - All Rights Reserved * Unauthorized copying of this file, via any medium is strictly prohibited * Proprietary and confidential * Written by: Renata P. Baptista <rpbaptista@poli.ufrj.br * Vinicius M. de Pinho <viniciusmesquita@poli.ufrj.br> * * December 2016 * * Electronic and Computing Engineering Department (DEL) * Polytechnic School (Poli) * Federal University of Rio de Janeiro (UFRJ) * Course: Programming Languages - 2016.2 * Professor: Miguel Elias Mitre Campista */ #include "funcoes.h" using namespace std; PerlInterpreter *my_perl; //-------------------------------------- // verifica se existe arquivo de bd na pasta bool fexists(const string& filename) { ifstream ifile(filename.c_str()); return (bool)ifile; } //-------------------------------------- // verifica se existe arquivo de bd na pasta void verificarExistenciaBD (void) { bool existeBD; existeBD = fexists ("bd.txt"); if (!existeBD) { incluirMateriaNova (SEM_BD); } return; } //-------------------------------------- char* string_as_array(string* str) { return str->empty() ? NULL : &*str->begin(); } string nomePl = "plmain.pl"; string espacoBranco = ""; char* nomePlchar = string_as_array(&(nomePl)); char* espacoBrancoChar = string_as_array(&(espacoBranco)); //-------------------------------------- unsigned mostrarMenu (void) { system ("clear"); unsigned opcao; cout << "# BEM VINDO AO SEU GERENCIADOR DE NOTAS FAVORITO 2.0 \n" << endl; cout << "# DESENVOLVIDO POR: RENATA BAPTISTA E VINICIUS MESQUITA \n\n" << endl; cout << "# Suas opcoes: \n" << endl; cout << "# 1. Visualizar o banco de dados inteiro. \n" << endl; cout << "# 2. Visualizar todas as disciplinas no banco de dados. \n" << endl; cout << "# 3. Buscar os criterios de avaliacao de uma disciplina. \n" << endl; cout << "# 4. Calcular as estatisticas de uma disciplina. \n" << endl; cout << "# 5. Buscar as estatisticas de um discente. \n" << endl; cout << "# 6. Adicionar nova materia. \n" << endl; cout << "# 7. Sair do programa. \n\n" << endl; cout << "Digite sua opcao: "; try { cin >> opcao; cin.ignore(); if (opcao < 1 || opcao > NUM_OPCOES || cin.fail()) {throw OPCAO_ERRADA;} } catch (int opt) { unsigned opcao = 0; while (opcao < 1 || opcao > NUM_OPCOES) { cout << "Opcao incorreta, entre com uma opcao valida." << endl; cout << "Nova opcao: "; cin >> opcao; } } return opcao; } //opcao 1 //-------------------------------------- void visualizarBD (void) { char *my_argv[] = { espacoBrancoChar, nomePlchar }; //criacao de um interpretador my_perl = perl_alloc(); perl_construct(my_perl); PL_exit_flags |= PERL_EXIT_DESTRUCT_END; perl_parse(my_perl, NULL, 2, my_argv, (char **)NULL); perl_run(my_perl); dSP; ENTER; SAVETMPS; PUSHMARK(SP); PUTBACK; int count = call_pv("lerBancoDeDados",G_SCALAR); //count valores retornados SPAGAIN; PUTBACK; FREETMPS; LEAVE; perl_destruct(my_perl); perl_free(my_perl); //termino return; } //opcao 2 //-------------------------------------- void visualizarMaterias (void) { string materiaDesejada; system("clear"); int n = materiaDesejada.length() + 1; char argMateria[n]; for (int i=0; i<n; ++i){ argMateria[i] = materiaDesejada[i]; } char *my_argv[] = { espacoBrancoChar, nomePlchar }; //criacao de um interpretador my_perl = perl_alloc(); perl_construct(my_perl); PL_exit_flags |= PERL_EXIT_DESTRUCT_END; perl_parse(my_perl, NULL, 2, my_argv, (char **)NULL); perl_run(my_perl); dSP; ENTER; SAVETMPS; PUSHMARK(SP); XPUSHs(sv_2mortal(newSVpv(argMateria, 0))); PUTBACK; int count = call_pv("mostrarMaterias", G_SCALAR); //count valores retornados SPAGAIN; PUTBACK; FREETMPS; LEAVE; perl_destruct(my_perl); perl_free(my_perl); //termino return; } //opcao 3 //-------------------------------------- void criterioAvaliacao (void) { string materiaDesejada; system("clear"); visualizarMaterias (); cout << "Para qual materia voce deseja ver os criterios?" << endl; try { getline (cin, materiaDesejada); if (materiaDesejada.empty()){ throw STRING_VAZIA; } } catch (int opt) { unsigned opcao = 0; while (materiaDesejada.empty()) { cout << "Para qual materia voce deseja ver os criterios?" << endl; cout << "Nova opcao: "; getline (cin, materiaDesejada); } } // mudando o de string pra char * int n = materiaDesejada.length() + 1; char argMateria[n]; for (int i=0; i<n; ++i){ argMateria[i] = materiaDesejada[i]; } char *my_argv[] = { espacoBrancoChar, nomePlchar }; //criacao de um interpretador my_perl = perl_alloc(); perl_construct(my_perl); PL_exit_flags |= PERL_EXIT_DESTRUCT_END; perl_parse(my_perl, NULL, 2, my_argv, (char **)NULL); perl_run(my_perl); dSP; ENTER; SAVETMPS; PUSHMARK(SP); XPUSHs(sv_2mortal(newSVpv(argMateria, 0))); PUTBACK; int count = call_pv("buscaCriterioAvaliacaoDeUmaMateria", G_SCALAR); //count valores retornados SPAGAIN; PUTBACK; FREETMPS; LEAVE; perl_destruct(my_perl); perl_free(my_perl); //termino return; } //opcao 4 //-------------------------------------- void estatisticasMateria (void) { string materiaDesejada; system("clear"); visualizarMaterias (); cout << "Para qual materia voce deseja ver as estatisticas?" << endl; try { getline (cin, materiaDesejada); if (materiaDesejada.empty()){ throw STRING_VAZIA; } } catch (int opt) { unsigned opcao = 0; while (materiaDesejada.empty()) { cout << "Para qual materia voce deseja ver as estatisticas? "; getline (cin, materiaDesejada); } } // mudando o de string pra char * int n = materiaDesejada.length() + 1; char argMateria[n]; for (int i=0; i<n; ++i){ argMateria[i] = materiaDesejada[i]; } char *my_argv[] = { espacoBrancoChar, nomePlchar }; //criacao de um interpretador my_perl = perl_alloc(); perl_construct(my_perl); PL_exit_flags |= PERL_EXIT_DESTRUCT_END; perl_parse(my_perl, NULL, 2, my_argv, (char **)NULL); perl_run(my_perl); dSP; ENTER; SAVETMPS; PUSHMARK(SP); XPUSHs(sv_2mortal(newSVpv(argMateria, 0))); PUTBACK; int count = call_pv("estatisticaDeUmaMateria", G_SCALAR); //count valores retornados SPAGAIN; PUTBACK; FREETMPS; LEAVE; perl_destruct(my_perl); perl_free(my_perl); //termino return; } //opcao 5 //-------------------------------------- void estatisticasDiscente (void) { string alunoDesejado; system("clear"); cout << "Para qual discente voce deseja ver as estatisticas? " << endl; try { getline (cin, alunoDesejado); if (alunoDesejado.empty()){ throw STRING_VAZIA; } } catch (int opt) { unsigned opcao = 0; while (alunoDesejado.empty()) { cout << "Para qual discente voce deseja ver as estatisticas? "; getline (cin, alunoDesejado); } } // mudando o de string pra char * int n = alunoDesejado.length() + 1; char argAluno[n]; for (int i=0; i<n; ++i){ argAluno[i] = alunoDesejado[i]; } char *my_argv[] = { espacoBrancoChar, nomePlchar }; //criacao de um interpretador my_perl = perl_alloc(); perl_construct(my_perl); PL_exit_flags |= PERL_EXIT_DESTRUCT_END; perl_parse(my_perl, NULL, 2, my_argv, (char **)NULL); perl_run(my_perl); dSP; ENTER; SAVETMPS; PUSHMARK(SP); XPUSHs(sv_2mortal(newSVpv(argAluno, 0))); PUTBACK; int count = call_pv("estatisticaDeUmAluno", G_SCALAR); //count valores retornados SPAGAIN; PUTBACK; FREETMPS; LEAVE; perl_destruct(my_perl); perl_free(my_perl); //termino return; } //opcao 6 //-------------------------------------- void incluirMateriaNova (int bd) { system ("clear"); string nomeMateria, nomeProfessor; int qtdAlunos, qtdAvaliacoes; float notaMinima; if (bd == SEM_BD) { cout << "\n Seja bem-vindo pela primeira vez ao seu gerenciador de notas favorito!" << endl; cout << "\n E necessario criar um banco de dados novo! Comece cadastrando uma disciplina: \n\n" << endl; } cout << "Qual o nome da materia? "; try { getline (cin, nomeMateria); if (nomeMateria.empty()){ throw STRING_VAZIA; } } catch (int opt) { unsigned opcao = 0; while (nomeMateria.empty()) { cout << "Qual o nome da materia? "; getline (cin, nomeMateria); } } cout << "Qual o nome do professor? "; try { getline (cin, nomeProfessor); if (nomeProfessor.empty()){ throw STRING_VAZIA; } } catch (int opt) { unsigned opcao = 0; while (nomeProfessor.empty()) { cout << "Qual o nome do professor? "; getline (cin, nomeProfessor); } } cout << "Qual eh a nota minima para aprovacao? "; cin >> notaMinima; cout << "Quantos alunos existem na disciplina? "; cin >> qtdAlunos; cout << "Quantas avaliacoes foram aplicadas? "; cin >> qtdAvaliacoes; cout << "\n"; Materia materia(nomeMateria, nomeProfessor, notaMinima, qtdAlunos, qtdAvaliacoes); perl_incluirMateriaNova(&materia); return; } //-------------------------------------- /* char * transformarStringEmChar (string palavra){ int n = palavra.length() + 1; char temp[n]; for (int i=0; i<palavra.length(); ++i){ temp[i] = palavra[i]; } temp[n-1] = '\0'; return temp; }*/ //-------------------------------------- void perl_incluirMateriaNova(Materia * materia) { string nomeMateria = materia->getNomeMateria(); //char * argNomeMateria; int n = nomeMateria.length() + 1; char argNomeMateria[n]; for (int i=0; i<n; ++i){ argNomeMateria[i] = nomeMateria[i]; } //argNomeMateria[n-1] = '\0'; cout << argNomeMateria; string nomeProfessor = materia->getNomeProfessor(); n = nomeProfessor.length() + 1; char argNomeProf[n]; for (int i=0; i<n; ++i){ argNomeProf[i] = nomeProfessor[i]; } float notaMinima = materia->getNotaMinima(); int qtdAlunos = materia->getQtdAlunos (); int qtdAvaliacoes = materia->getQtdAvaliacoes (); float arrayPesos [qtdAvaliacoes]; float matrizNotas [qtdAlunos][qtdAvaliacoes]; string arrayAlunos [qtdAlunos]; vector<float> vPesos = materia->getPesosProvas(); int j = 0; for (vector<float>::iterator it = vPesos.begin(); it != vPesos.end(); ++it) { arrayPesos[j] = *it; j++; } vector <Aluno> vAlunos = materia->getAlunosMateria(); for (int j = 0; j < qtdAlunos; j++) { for (int i = 0; i < qtdAvaliacoes; i++) { matrizNotas [j][i] = (vAlunos.at(j)).getNotasProvas().at(i); } } for (int j = 0; j < qtdAlunos; j++) { arrayAlunos[j] = (vAlunos.at(j)).getNomeAlunos(); } //---------INTERACAO COM PERL //prep argumentos vetoriais char *my_argv[] = { espacoBrancoChar, nomePlchar }; my_perl = perl_alloc(); perl_construct(my_perl); PL_exit_flags |= PERL_EXIT_DESTRUCT_END; perl_parse(my_perl, NULL, 2, my_argv, (char **)NULL); perl_run(my_perl); AV *argArrayPesos = newAV(); for (int i=0; i < qtdAvaliacoes; i++){ av_store(argArrayPesos, (SSize_t) i, newSVnv(arrayPesos[i])); } AV *argArrayAlunos = newAV(); for (int i=0; i < qtdAlunos; i++){ n = arrayAlunos[i].length() + 1; char aux[n]; for (int j=0; j<n; ++j){ aux[j] = arrayAlunos[i][j]; } av_store(argArrayAlunos, (SSize_t) i, newSVpv(aux,0)); } AV *array2 = newAV(); for (int j=0; j < qtdAlunos; j++){ AV *array = newAV(); for (int i=0; i < qtdAvaliacoes; i++){ av_store(array, (SSize_t) i, newSVnv(matrizNotas[j][i])); } SV *reference; reference = newRV_noinc((SV *) array); av_push(array2, reference); } dSP; ENTER; SAVETMPS; PUSHMARK(SP); XPUSHs(sv_2mortal(newSVpv(argNomeMateria, 0))); XPUSHs(sv_2mortal(newSVpv(argNomeProf, 0))); XPUSHs(sv_2mortal(newSVnv(notaMinima))); XPUSHs(sv_2mortal(newSViv(qtdAlunos))); XPUSHs(sv_2mortal(newSViv(qtdAvaliacoes))); XPUSHs(sv_2mortal(newRV_noinc((SV*)argArrayPesos))); XPUSHs(sv_2mortal(newRV_noinc((SV*)argArrayAlunos))); XPUSHs(sv_2mortal(newRV_noinc((SV*)array2))); PUTBACK; int count = call_pv("criarNovaMateria", G_SCALAR); //count valores retornados SPAGAIN; PUTBACK; FREETMPS; LEAVE; perl_destruct(my_perl); perl_free(my_perl); return; } //opcao 7 //-------------------------------------- void sairPrograma () { system ("clear"); cout << "\n\n\tVoce esta saindo do programa! \n\n"; exit (OK); }
/* * Copyright 2019 The Project Oak Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "oak/client/authorization_bearer_token_metadata.h" #include <map> #include "oak/common/policy.h" namespace oak { AuthorizationBearerTokenMetadata::AuthorizationBearerTokenMetadata( const std::string& authorization_bearer_token) : authorization_bearer_token_(authorization_bearer_token) {} grpc::Status AuthorizationBearerTokenMetadata::GetMetadata( grpc::string_ref service_url, grpc::string_ref method_name, const grpc::AuthContext& channel_auth_context, std::multimap<grpc::string, grpc::string>* metadata) { metadata->insert( std::make_pair(kOakAuthorizationBearerTokenGrpcMetadataKey, authorization_bearer_token_)); return grpc::Status::OK; } } // namespace oak
#ifndef AETHER_BOX_HPP #define AETHER_BOX_HPP #include "Aether/base/Texture.hpp" namespace Aether { /** * @brief A Box is a rectangle outline with no fill. * @note This element can not have the texture generation deferred yet! */ class Box : public Texture { private: /** @brief Size of border */ unsigned int border_; /** @brief Radius of each corner (draws rounded rectangle when > 0) */ unsigned int cornerRadius_; /** @brief Generate a box surface */ void generateSurface(); public: /** * @brief Construct a new Box object * * @param x x-coordinate of start position offset * @param y y-coordinate of start position offset * @param w width of box * @param h height of box * @param b border thickness * @param r corner radius */ Box(int x, int y, int w, int h, unsigned int b = 1, unsigned int r = 0); /** * @brief Get the border thickness of box * * @return border thickness */ unsigned int border(); /** * @brief Set the border thickness of box * * @param b new border thickness */ void setBorder(unsigned int b); /** * @brief Get the current corner radius for box * * @return corner radius */ unsigned int cornerRadius(); /** * @brief Set the corner radius for box * * @param r new corner radius */ void setCornerRadius(unsigned int r); /** * @brief Adjust box size * * @param w new width of box * @param h new height of box */ void setBoxSize(int w, int h); }; }; #endif
#pragma once #include <memory> namespace krakoa { template<typename T> using Multi_Ptr = std::shared_ptr<T>; template<typename T> using Weak_Ptr = std::weak_ptr<T>; template<typename T> using Solo_Ptr = std::unique_ptr<T>; template<typename T, typename ...Ts, class = std::enable_if_t<std::is_constructible_v<T, Ts...>>> Solo_Ptr<T> Make_Solo(Ts&& ...params) { return std::make_unique<T>(std::forward<Ts>(params)...); } template<typename T, typename ...Ts, class = std::enable_if_t<std::is_constructible_v<T, Ts...>>> Multi_Ptr<T> Make_Multi(Ts&& ...params) { return std::make_shared<T>(std::forward<Ts>(params)...); } }
/* * Independent parallel updates benchmark * for various containers */ #include "../bench.h" #include <libdash.h> #include <dash/Coarray.h> #include <array> #include <vector> #include <deque> #include <iostream> #include <iomanip> #include <unistd.h> using namespace std; #ifndef TYPE #define TYPE int #endif typedef dash::util::Timer< dash::util::TimeMeasure::Clock > Timer; typedef dash::CSRPattern< 1, dash::ROW_MAJOR, int > PatternType; typedef dash::Array< TYPE, int, PatternType > ArrayType; typedef dash::Coarray<TYPE[]> CoarrType; template<typename Iter> void init_values(Iter begin, Iter end, unsigned); void init_values(ArrayType & a, unsigned); template<typename Iter> bool validate(Iter begin, Iter end, unsigned, unsigned); bool validate(ArrayType & a, unsigned, unsigned); double test_dash_pattern(ArrayType & a, unsigned, unsigned); double test_dash_global_iter(ArrayType & a, unsigned, unsigned); double test_dash_local_global_iter(ArrayType & a, unsigned, unsigned); double test_dash_local_iter(ArrayType & a, unsigned, unsigned); double test_dash_local_subscript(ArrayType & a, unsigned, unsigned); double test_dash_local_pointer(ArrayType & a, unsigned, unsigned); double test_dash_coarr_l_subscript(CoarrType & a, unsigned, unsigned); double test_stl_vector(unsigned, unsigned); double test_stl_deque(unsigned, unsigned); double test_raw_array(unsigned, unsigned); void perform_test(unsigned ELEM_PER_UNIT, unsigned REPEAT); double gups( /// Number of units unsigned N, /// Duration in microseconds double useconds, /// Elements per unit unsigned ELEM_PER_UNIT, /// Number of iterations unsigned REPEAT) { double num_updates = static_cast<double>(N * ELEM_PER_UNIT * REPEAT); // kilo-updates / usecs = giga-updates / sec return (num_updates / 1000.0f) / useconds; } int main(int argc, char * argv[]) { dash::init(&argc, &argv); dash::util::BenchmarkParams bench_params("bench.01.igups"); bench_params.set_output_width(72); bench_params.print_header(); bench_params.print_pinning(); Timer::Calibrate(0); std::deque<std::pair<int, int>> tests; tests.push_back({0 , 0}); // this prints the header tests.push_back({4 , 100000}); tests.push_back({16 , 10000}); tests.push_back({64 , 10000}); tests.push_back({256 , 10000}); tests.push_back({1024 , 1000}); tests.push_back({4096 , 1000}); tests.push_back({4 * 4096 , 100}); tests.push_back({16 * 4096 , 100}); tests.push_back({64 * 4096 , 50}); tests.push_back({128 * 4096 , 20}); tests.push_back({256 * 4096 , 10}); tests.push_back({512 * 4096 , 10}); for (auto test : tests) { perform_test(test.first, test.second); } dash::finalize(); return 0; } void perform_test( unsigned ELEM_PER_UNIT, unsigned REPEAT) { auto num_units = dash::size(); if (ELEM_PER_UNIT == 0) { if (dash::myid() == 0) { cout << std::setw(10) << "elem/unit"; cout << "," << std::setw(10) << "iterations"; cout << "," << std::setw(11) << "pat"; cout << "," << std::setw(11) << "g_it"; cout << "," << std::setw(11) << "l_g_it"; cout << "," << std::setw(11) << "l_it"; cout << "," << std::setw(11) << "l[]"; cout << "," << std::setw(11) << "l*"; cout << "," << std::setw(11) << "stl vector"; cout << "," << std::setw(11) << "stl deque"; cout << "," << std::setw(11) << "raw array"; cout << "," << std::setw(11) << "coarr l[]"; cout << endl; } return; } std::vector<unsigned> local_sizes; for (size_t u = 0; u < num_units; ++u) { local_sizes.push_back(ELEM_PER_UNIT); } double t0, t1, t2, t3, t4, t5, t6, t7, t8, t9; PatternType pat(local_sizes); { ArrayType arr0(pat); test_dash_pattern(arr0, ELEM_PER_UNIT, REPEAT); t0 = test_dash_pattern(arr0, ELEM_PER_UNIT, REPEAT); } { ArrayType arr1(pat); test_dash_global_iter(arr1, ELEM_PER_UNIT, REPEAT); t1 = test_dash_global_iter(arr1, ELEM_PER_UNIT, REPEAT); } { ArrayType arr2(pat); test_dash_local_global_iter(arr2, ELEM_PER_UNIT, REPEAT); t2 = test_dash_local_global_iter(arr2, ELEM_PER_UNIT, REPEAT); } { ArrayType arr3(pat); test_dash_local_iter(arr3, ELEM_PER_UNIT, REPEAT); t3 = test_dash_local_iter(arr3, ELEM_PER_UNIT, REPEAT); } { ArrayType arr4(pat); test_dash_local_subscript(arr4, ELEM_PER_UNIT, REPEAT); t4 = test_dash_local_subscript(arr4, ELEM_PER_UNIT, REPEAT); } { ArrayType arr5(pat); test_dash_local_pointer(arr5, ELEM_PER_UNIT, REPEAT); t5 = test_dash_local_pointer(arr5, ELEM_PER_UNIT, REPEAT); } { t6 = test_stl_vector(ELEM_PER_UNIT, REPEAT); } { t7 = test_stl_deque(ELEM_PER_UNIT, REPEAT); } { t8 = test_raw_array(ELEM_PER_UNIT, REPEAT); } { CoarrType coarr(ELEM_PER_UNIT); test_dash_coarr_l_subscript(coarr, ELEM_PER_UNIT, REPEAT); t9 = test_dash_coarr_l_subscript(coarr, ELEM_PER_UNIT, REPEAT); } dash::barrier(); if (dash::myid() == 0) { double gups0 = gups(num_units, t0, ELEM_PER_UNIT, REPEAT); double gups1 = gups(num_units, t1, ELEM_PER_UNIT, REPEAT); double gups2 = gups(num_units, t2, ELEM_PER_UNIT, REPEAT); double gups3 = gups(num_units, t3, ELEM_PER_UNIT, REPEAT); double gups4 = gups(num_units, t4, ELEM_PER_UNIT, REPEAT); double gups5 = gups(num_units, t5, ELEM_PER_UNIT, REPEAT); double gups6 = gups(num_units, t6, ELEM_PER_UNIT, REPEAT); double gups7 = gups(num_units, t7, ELEM_PER_UNIT, REPEAT); double gups8 = gups(num_units, t8, ELEM_PER_UNIT, REPEAT); double gups9 = gups(num_units, t9, ELEM_PER_UNIT, REPEAT); cout << std::setw(10) << ELEM_PER_UNIT; cout << "," << std::setw(10) << REPEAT; cout << "," << std::setw(11) << std::fixed << std::setprecision(4) << gups0; cout << "," << std::setw(11) << std::fixed << std::setprecision(4) << gups1; cout << "," << std::setw(11) << std::fixed << std::setprecision(4) << gups2; cout << "," << std::setw(11) << std::fixed << std::setprecision(4) << gups3; cout << "," << std::setw(11) << std::fixed << std::setprecision(4) << gups4; cout << "," << std::setw(11) << std::fixed << std::setprecision(4) << gups5; cout << "," << std::setw(11) << std::fixed << std::setprecision(4) << gups6; cout << "," << std::setw(11) << std::fixed << std::setprecision(4) << gups7; cout << "," << std::setw(11) << std::fixed << std::setprecision(4) << gups8; cout << "," << std::setw(11) << std::fixed << std::setprecision(4) << gups9; cout << endl; } } void init_values( ArrayType & a, unsigned ELEM_PER_UNIT) { if (dash::myid() == 0) { init_values(a.begin(), a.end(), ELEM_PER_UNIT); } dash::Team::All().barrier(); } template<typename Iter> void init_values( Iter begin, Iter end, unsigned ELEM_PER_UNIT) { auto i = 0; for (auto it = begin; it != end; ++it, ++i) { *it = i; } } template<typename Iter> bool validate( Iter begin, Iter end, unsigned ELEM_PER_UNIT, unsigned REPEAT) { typedef typename ArrayType::value_type value_t; bool valid = true; auto i = 0; for (auto it = begin; it != end; ++it, ++i) { value_t expected = i + REPEAT; value_t value = *it; if (value != expected) { valid = false; cerr << "Validation failed: " << "array[" << i << "] == " << value << " != " << expected << " -- elements/unit: " << ELEM_PER_UNIT << endl; break; } } return valid; } bool validate( ArrayType & arr, unsigned ELEM_PER_UNIT, unsigned REPEAT) { arr.barrier(); if (dash::myid() == 0) { return validate( arr.begin(), arr.end(), ELEM_PER_UNIT, REPEAT); } return true; } double test_dash_pattern( ArrayType & a, unsigned ELEM_PER_UNIT, unsigned REPEAT) { typedef typename ArrayType::index_type index_t; typedef typename ArrayType::size_type extent_t; init_values(a, ELEM_PER_UNIT); const PatternType & pattern = a.pattern(); typename ArrayType::local_type loc = a.local; Timer timer; for (unsigned i = 0; i < REPEAT; ++i) { for (extent_t g_idx = 0; g_idx < a.size(); ++g_idx) { auto local_pos = pattern.local(g_idx); auto unit_id = local_pos.unit; auto l_index = local_pos.index; if (unit_id == pattern.team().myid()) { ++loc[l_index]; } } } auto time_elapsed = timer.Elapsed(); validate( a, ELEM_PER_UNIT, REPEAT); return time_elapsed; } double test_dash_global_iter( ArrayType & a, unsigned ELEM_PER_UNIT, unsigned REPEAT) { typedef typename ArrayType::value_type value_t; typedef typename ArrayType::pattern_type pattern_t; init_values(a, ELEM_PER_UNIT); Timer timer; for (unsigned i = 0; i < REPEAT; ++i) { for (auto it = a.begin(); it != a.end(); ++it) { value_t * local_ptr = it.local(); if (local_ptr != nullptr) { ++(*local_ptr); } } } auto time_elapsed = timer.Elapsed(); validate( a, ELEM_PER_UNIT, REPEAT); return time_elapsed; } double test_dash_local_global_iter( ArrayType & a, unsigned ELEM_PER_UNIT, unsigned REPEAT) { typedef typename ArrayType::value_type value_t; typedef typename ArrayType::pattern_type pattern_t; init_values(a, ELEM_PER_UNIT); // Global offset of first local element: auto l_begin_gidx = a.pattern().lbegin(); auto l_git = a.begin() + l_begin_gidx; auto const l_gend = l_git + ELEM_PER_UNIT; // Iterate over local elements but use global iterator to dereference // elements. Timer timer; for (unsigned i = 0; i < REPEAT; ++i) { for (auto it = l_git; it != l_gend; ++it) { value_t * local_ptr = it.local(); if (local_ptr != nullptr) { ++(*local_ptr); } } } auto time_elapsed = timer.Elapsed(); validate( a, ELEM_PER_UNIT, REPEAT); return time_elapsed; } double test_dash_local_iter( ArrayType & a, unsigned ELEM_PER_UNIT, unsigned REPEAT) { init_values(a, ELEM_PER_UNIT); Timer timer; const auto & lend = a.lend(); for (unsigned i = 0; i < REPEAT; ++i) { for (auto it = a.lbegin(); it != lend; ++it) { ++(*it); } } auto time_elapsed = timer.Elapsed(); validate( a, ELEM_PER_UNIT, REPEAT); return time_elapsed; } double test_dash_local_subscript( ArrayType & a, unsigned ELEM_PER_UNIT, unsigned REPEAT) { init_values(a, ELEM_PER_UNIT); Timer timer; typename ArrayType::local_type loc = a.local; for (unsigned i = 0; i < REPEAT; ++i) { for (unsigned j = 0; j < ELEM_PER_UNIT; ++j) { ++loc[j]; } } auto time_elapsed = timer.Elapsed(); validate( a, ELEM_PER_UNIT, REPEAT); return time_elapsed; } double test_dash_local_pointer( ArrayType & a, unsigned ELEM_PER_UNIT, unsigned REPEAT) { init_values(a, ELEM_PER_UNIT); Timer timer; auto lbegin = a.lbegin(); auto lend = a.lend(); for (unsigned i = 0; i < REPEAT; ++i) { for (unsigned j = 0; j < ELEM_PER_UNIT; ++j) { ++lbegin[j]; } } auto time_elapsed = timer.Elapsed(); validate( a, ELEM_PER_UNIT, REPEAT); return time_elapsed; } double test_dash_coarr_l_subscript( CoarrType & a, unsigned ELEM_PER_UNIT, unsigned REPEAT) { init_values(a.lbegin(), a.lend(), ELEM_PER_UNIT); Timer timer; for (unsigned i = 0; i < REPEAT; ++i) { for (unsigned j = 0; j < ELEM_PER_UNIT; ++j) { ++a[j]; // local coarr access } } auto time_elapsed = timer.Elapsed(); validate( a.lbegin(), a.lend(), ELEM_PER_UNIT, REPEAT); return time_elapsed; } double test_stl_vector( unsigned ELEM_PER_UNIT, unsigned REPEAT) { std::vector<TYPE> arr(ELEM_PER_UNIT); init_values(arr.begin(), arr.end(), ELEM_PER_UNIT); Timer timer; for (unsigned i = 0; i < REPEAT; ++i) { for (unsigned j = 0; j < ELEM_PER_UNIT; ++j) { ++arr[j]; } } auto time_elapsed = timer.Elapsed(); validate( arr.begin(), arr.end(), ELEM_PER_UNIT, REPEAT ); return time_elapsed; } double test_stl_deque( unsigned ELEM_PER_UNIT, unsigned REPEAT) { std::deque<TYPE> arr(ELEM_PER_UNIT); init_values(arr.begin(), arr.end(), ELEM_PER_UNIT); Timer timer; for (unsigned i = 0; i < REPEAT; ++i) { for (unsigned j = 0; j < ELEM_PER_UNIT; ++j) { arr[j]++; } } auto time_elapsed = timer.Elapsed(); validate( arr.begin(), arr.end(), ELEM_PER_UNIT, REPEAT); return time_elapsed; } double test_raw_array( unsigned ELEM_PER_UNIT, unsigned REPEAT) { TYPE * arr = new TYPE[ELEM_PER_UNIT]; init_values( arr, arr + ELEM_PER_UNIT, ELEM_PER_UNIT); Timer timer; for (unsigned i = 0; i < REPEAT; i++) { for (unsigned j = 0; j < ELEM_PER_UNIT; j++) { arr[j]++; } } auto time_elapsed = timer.Elapsed(); validate( arr, arr + ELEM_PER_UNIT, ELEM_PER_UNIT, REPEAT); delete[] arr; return time_elapsed; }
#include "pch.h" #include "Rtp.h" #include <sodium.h> namespace winrt::Unicord::Universal::Voice::Interop { void Rtp::EncodeHeader(uint16_t sequence, uint32_t timestamp, uint32_t ssrc, gsl::span<uint8_t> target) { if (target.size() < HEADER_SIZE) { throw hresult_invalid_argument(); } target[0] = RTP_NO_EXTENSION; target[1] = RTP_VERSION; // reverse_copy from big endian to little endian std::reverse_copy((uint8_t*)&sequence, (uint8_t*)&sequence + sizeof sequence, &target[2]); std::reverse_copy((uint8_t*)&timestamp, (uint8_t*)&timestamp + sizeof timestamp, &target[4]); std::reverse_copy((uint8_t*)&ssrc, (uint8_t*)&ssrc + sizeof ssrc, &target[8]); } bool Rtp::IsRtpHeader(array_view<const uint8_t> data) { if (data.size() < HEADER_SIZE) return false; if ((data[0] != RTP_NO_EXTENSION && data[0] != RTP_EXTENSION) || data[1] != RTP_VERSION) return false; return true; } void Rtp::DecodeHeader(array_view<const uint8_t> source, uint16_t& sequence, uint32_t& timestamp, uint32_t& ssrc, bool& has_extension) { if (!IsRtpHeader(source)) throw hresult_invalid_argument(); has_extension = source[0] == RTP_EXTENSION; // reverse_copy from big endian to little endian std::reverse_copy(&source[2], &source[2 + sizeof sequence], (uint8_t*)&sequence); std::reverse_copy(&source[4], &source[4 + sizeof timestamp], (uint8_t*)&timestamp); std::reverse_copy(&source[8], &source[8 + sizeof ssrc], (uint8_t*)&ssrc); } void Rtp::GetDataFromPacket(array_view<const uint8_t> source, array_view<const uint8_t> &destination, EncryptionMode mode) { switch (mode) { case XSalsa20_Poly1305: destination = array_view(source.begin() + HEADER_SIZE, source.end()); break; case XSalsa20_Poly1305_Suffix: destination = array_view(source.begin() + HEADER_SIZE, source.end() - crypto_secretbox_xsalsa20poly1305_NONCEBYTES); break; case XSalsa20_Poly1305_Lite: destination = array_view(source.begin() + HEADER_SIZE, source.end() - 4); break; default: throw hresult_invalid_argument(); } } int Rtp::CalculatePacketSize(uint32_t encrypted_length, EncryptionMode encryption_mode) { } }
/* //@HEADER // ************************************************************************ // // KokkosKernels 0.9: Linear Algebra and Graph Kernels // Copyright 2017 Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Questions? Contact Siva Rajamanickam (srajama@sandia.gov) // // ************************************************************************ //@HEADER */ #define KOKKOSKERNELS_IMPL_COMPILE_LIBRARY true #include "KokkosKernels_config.h" #if defined (KOKKOSKERNELS_INST_KOKKOS_COMPLEX_DOUBLE_) \ && defined (KOKKOSKERNELS_INST_LAYOUTLEFT) \ && defined (KOKKOSKERNELS_INST_EXECSPACE_THREADS) \ && defined (KOKKOSKERNELS_INST_MEMSPACE_HOSTSPACE) \ && defined (KOKKOSKERNELS_INST_MEMSPACE_HOSTSPACE) \ && defined (KOKKOSKERNELS_INST_ORDINAL_INT64_T) \ && defined (KOKKOSKERNELS_INST_OFFSET_INT) #include "KokkosSparse_gauss_seidel_spec.hpp" namespace KokkosSparse { namespace Impl { KOKKOSSPARSE_GAUSS_SEIDEL_NUMERIC_ETI_SPEC_INST(Kokkos::complex<double>, int64_t, int, Kokkos::LayoutLeft, Kokkos::Threads, Kokkos::HostSpace, Kokkos::HostSpace) } // Impl } // KokkosSparse #endif
#include "Vector3.h" #include "CornDirectX.h" #include <cmath> #include <algorithm> #include <iterator> Vector3::Vector3(const nlohmann::json& vectorJson) { x = vectorJson[0].get<float>(); y = vectorJson[1].get<float>(); z = vectorJson[2].get<float>(); } Vector3::Vector3(float x, float y, float z) { this->x = x; this->y = y; this->z = z; } const float& Vector3::operator[](unsigned index) const { return _numbers[index]; } float& Vector3::operator[](unsigned index) { return _numbers[index]; } bool Vector3::operator==(const Vector3& vec) const { return (x == vec.x && y == vec.y && z == vec.z); } bool Vector3::operator!=(const Vector3& vec) const { return (x != vec.x || y != vec.y || z != vec.z); } Vector3& Vector3::operator=(const Vector3& vec) { std::copy(std::begin(vec._numbers), std::end(vec._numbers), std::begin(_numbers)); return *this; } Vector3 Vector3::operator+(const Vector3& vec) const { return this->Add(vec); } Vector3 Vector3::operator-(const Vector3& vec) const { return this->Subtract(vec); } Vector3 Vector3::operator*(const float& scalar) const { return Vector3(x * scalar, y * scalar, z * scalar); } Vector3 Vector3::operator/(const float& scalar) const { return Vector3(x / scalar, y / scalar, z / scalar); } Vector3 Vector3::operator*(const Matrix4& matrix) const { return this->Mul(matrix); } Vector3& Vector3::operator+=(const Vector3& vec) { return *this = this->Add(vec); } Vector3& Vector3::operator-=(const Vector3& vec) { return *this = this->Subtract(vec); } Vector3& Vector3::operator*=(const float& scalar) { return *this = this->Mul(scalar); } Vector3& Vector3::operator/=(const float& scalar) { return *this = this->Div(scalar); } Vector3 Vector3::Add(const Vector3& vec) const { return Vector3(x + vec.x, y + vec.y, z + vec.z); } Vector3 Vector3::Subtract(const Vector3& vec) const { return Vector3(x - vec.x, y - vec.y, z - vec.z); } float Vector3::Dot(const Vector3& vec) const { return (x * vec.x) + (y * vec.y) + (z * vec.z); } Vector3 Vector3::GetUnitVector() const { float mag = GetMagnitude(); if (mag == 0) return Vector3(); return Div(mag); } Vector3 Vector3::Div(const float& scalar) const { return Vector3(x / scalar, y / scalar, z / scalar); } Vector3 Vector3::Mul(const float& scalar) const { return Vector3(x * scalar, y * scalar, z * scalar); } Vector3 Vector3::Mul(const Matrix4& matrix) const { float vec4[4]; vec4[0] = x; vec4[1] = y; vec4[2] = z; vec4[3] = 1; Vector3 rValue; for (unsigned col = 0; col < 4; col++) for (unsigned row = 0; row < 4; row++) { rValue[col] += vec4[row] * matrix[row][col]; } return rValue; } Vector3 Vector3::Round() { return Vector3(std::roundf(x), std::roundf(y), std::roundf(z)); } float Vector3::GetMagnitude() const { return sqrt(GetPow2Magnitude()); } float Vector3::GetPow2Magnitude() const { return (x * x) + (y * y) + (z * z); } D3DXVECTOR3 Vector3::ConvertToDxVector() const { return D3DXVECTOR3(x, y, z); }
/* * Copyright (c) 2018 MariaDB Corporation Ab * * Use of this software is governed by the Business Source License included * in the LICENSE.TXT file and at www.mariadb.com/bsl11. * * Change Date: 2025-05-25 * * On the date above, in accordance with the Business Source License, use * of this software will be governed by version 2 or later of the General * Public License. */ #pragma once /** * @file core/maxscale/filter.h - The private filter interface */ #include <maxscale/filter.hh> #include <memory> #include <mutex> /** * The definition of a filter from the configuration file. * This is basically the link between a plugin to load and the * options to pass to that plugin. */ // TODO: Make this a class struct FilterDef : public MXS_FILTER_DEF { FilterDef(std::string name, std::string module, MXS_FILTER_OBJECT* object, MXS_FILTER* instance, mxs::ConfigParameters* params); ~FilterDef(); std::string name; /**< The Filter name */ std::string module; /**< The module to load */ mxs::ConfigParameters parameters; /**< The filter parameters */ MXS_FILTER* filter; /**< The runtime filter */ MXS_FILTER_OBJECT* obj; /**< The "MODULE_OBJECT" for the filter */ }; typedef std::shared_ptr<FilterDef> SFilterDef; SFilterDef filter_alloc(const char* name, const char* module, mxs::ConfigParameters* params); void filter_free(const SFilterDef& filter); int filter_standard_parameter(const char* name); // Find the internal filter representation SFilterDef filter_find(const char* name); /** * Check if a filter uses a server or a service * * @param target The target to check * * @return The list of filters that depend on the given target */ std::vector<SFilterDef> filter_depends_on_target(const mxs::Target* target); /** * Check if filter can be destroyed * * A filter can be destroyed if no service uses it. * * @param filter Filter to check * * @return True if filter can be destroyed */ bool filter_can_be_destroyed(const SFilterDef& filter); /** * Destroy a filter * * @param filter Filter to destroy */ void filter_destroy(const SFilterDef& filter); /** * Destroy all filters */ void filter_destroy_instances(); /** * @brief Persist filter configuration into a stream * * This converts the static configuration of the filter into an INI format file. * * @param filter Filter to persist * @param os Stream where filter is serialized * * @return The output stream */ std::ostream& filter_persist(const SFilterDef& filter, std::ostream& os); /** * @brief Convert a filter to JSON * * @param filter Filter to convert * @param host Hostname of this server * * @return Filter converted to JSON format */ json_t* filter_to_json(const SFilterDef& filter, const char* host); /** * @brief Convert all filters into JSON * * @param host Hostname of this server * * @return A JSON array containing all filters */ json_t* filter_list_to_json(const char* host);
#include <cstdint> #include <iomanip> #include <iostream> #include <random> #include <string> #include <vector> #include "tuner_api.h" #if defined(_MSC_VER) const std::string kernelFilePrefix = ""; #else const std::string kernelFilePrefix = "../"; #endif #if KTT_CUDA_EXAMPLE const std::string defaultKernelFile = kernelFilePrefix + "../examples/cltune-gemm/gemm.cu"; const std::string defaultReferenceKernelFile = kernelFilePrefix + "../examples/cltune-gemm/gemm_reference.cu"; const auto computeAPI = ktt::ComputeAPI::CUDA; #elif KTT_OPENCL_EXAMPLE const std::string defaultKernelFile = kernelFilePrefix + "../examples/cltune-gemm/gemm.cl"; const std::string defaultReferenceKernelFile = kernelFilePrefix + "../examples/cltune-gemm/gemm_reference.cl"; const auto computeAPI = ktt::ComputeAPI::OpenCL; #endif #define RAPID_TEST 0 #define USE_PROFILING 0 // Helper function to determine whether or not 'a' is a multiple of 'b' bool IsMultiple(const size_t a, const size_t b) { return ((a / b) * b == a) ? true : false; }; int main(int argc, char** argv) { // Initialize platform and device index ktt::PlatformIndex platformIndex = 0; ktt::DeviceIndex deviceIndex = 0; std::string kernelFile = defaultKernelFile; std::string referenceKernelFile = defaultReferenceKernelFile; if (argc >= 2) { platformIndex = std::stoul(std::string(argv[1])); if (argc >= 3) { deviceIndex = std::stoul(std::string(argv[2])); if (argc >= 4) { kernelFile = std::string(argv[3]); if (argc >= 5) { referenceKernelFile = std::string(argv[4]); } } } } // Declare data variables #if USE_PROFILING == 0 const uint32_t kSizeM = 2048; const uint32_t kSizeN = 2048; const uint32_t kSizeK = 2048; #else const uint32_t kSizeM = 2048/2; const uint32_t kSizeN = 2048/2; const uint32_t kSizeK = 2048/2; #endif const ktt::DimensionVector ndRangeDimensions(kSizeM, kSizeN); const ktt::DimensionVector workGroupDimensions; const ktt::DimensionVector referenceWorkGroupDimensions(8, 8); // Initialize data std::random_device device; std::default_random_engine engine(device()); std::uniform_real_distribution<float> distribution(-2.0f, 2.0f); std::vector<float> mat_a(kSizeM * kSizeK); std::vector<float> mat_b(kSizeN * kSizeK); std::vector<float> mat_c(kSizeM * kSizeN); for (uint32_t i = 0; i < kSizeM * kSizeK; i++) mat_a.at(i) = distribution(engine); for (uint32_t i = 0; i < kSizeN * kSizeK; i++) mat_b.at(i) = distribution(engine); for (uint32_t i = 0; i < kSizeM * kSizeN; i++) mat_c.at(i) = 0.0f; // Create tuner object for chosen platform and device ktt::Tuner tuner(platformIndex, deviceIndex, computeAPI); tuner.setGlobalSizeType(ktt::GlobalSizeType::OpenCL); tuner.setPrintingTimeUnit(ktt::TimeUnit::Microseconds); #if USE_PROFILING == 1 printf("Executing with profiling switched ON.\n"); tuner.setKernelProfiling(true); #endif // Add two kernels to tuner, one of the kernels acts as reference kernel ktt::KernelId kernelId = tuner.addKernelFromFile(kernelFile, "gemm_fast", ndRangeDimensions, workGroupDimensions); ktt::KernelId referenceKernelId = tuner.addKernelFromFile(referenceKernelFile, "gemm_reference", ndRangeDimensions, referenceWorkGroupDimensions); tuner.addParameter(kernelId, "MWG", {16, 32, 64, 128}); tuner.addParameter(kernelId, "NWG", {16, 32, 64, 128}); tuner.addParameter(kernelId, "KWG", {16, 32}); tuner.addParameter(kernelId, "MDIMC", {8, 16, 32}); tuner.addParameter(kernelId, "NDIMC", {8, 16, 32}); tuner.addParameter(kernelId, "MDIMA", {8, 16, 32}); tuner.addParameter(kernelId, "NDIMB", {8, 16, 32}); tuner.addParameter(kernelId, "KWI", {2, 8}); if (computeAPI == ktt::ComputeAPI::OpenCL) { tuner.addParameter(kernelId, "VWM", {1, 2, 4, 8}); tuner.addParameter(kernelId, "VWN", {1, 2, 4, 8}); } else { tuner.addParameter(kernelId, "VWM", {1, 2, 4}); tuner.addParameter(kernelId, "VWN", {1, 2, 4}); } tuner.addParameter(kernelId, "STRM", {0, 1}); tuner.addParameter(kernelId, "STRN", {0, 1}); tuner.addParameter(kernelId, "SA", {0, 1}); tuner.addParameter(kernelId, "SB", {0, 1}); tuner.addParameter(kernelId, "PRECISION", {32}); // Add kernel dimension modifiers based on added tuning parameters auto globalModifier = [](const size_t size, const std::vector<size_t>& vector) {return size * vector.at(0) / vector.at(1);}; tuner.setThreadModifier(kernelId, ktt::ModifierType::Global, ktt::ModifierDimension::X, std::vector<std::string>{"MDIMC", "MWG"}, globalModifier); tuner.setThreadModifier(kernelId, ktt::ModifierType::Global, ktt::ModifierDimension::Y, std::vector<std::string>{"NDIMC", "NWG"}, globalModifier); tuner.setThreadModifier(kernelId, ktt::ModifierType::Local, ktt::ModifierDimension::X, "MDIMC", ktt::ModifierAction::Multiply); tuner.setThreadModifier(kernelId, ktt::ModifierType::Local, ktt::ModifierDimension::Y, "NDIMC", ktt::ModifierAction::Multiply); // Add all arguments utilized by kernels ktt::ArgumentId kSizeMId = tuner.addArgumentScalar(kSizeM); ktt::ArgumentId kSizeNId = tuner.addArgumentScalar(kSizeN); ktt::ArgumentId kSizeKId = tuner.addArgumentScalar(kSizeK); ktt::ArgumentId matAId = tuner.addArgumentVector(mat_a, ktt::ArgumentAccessType::ReadOnly); ktt::ArgumentId matBId = tuner.addArgumentVector(mat_b, ktt::ArgumentAccessType::ReadOnly); ktt::ArgumentId matCId = tuner.addArgumentVector(mat_c, ktt::ArgumentAccessType::WriteOnly); #if RAPID_TEST == 1 tuner.persistArgument(matAId, true); tuner.persistArgument(matBId, true); tuner.persistArgument(matCId, true); #endif // Add conditions // Sets constraints: Set-up the constraints functions to use. The constraints require a function // object (in this case a lambda) which takes a vector of tuning parameter values and returns // a boolean value whether or not the tuning configuration is legal. In this case, the helper // function 'IsMultiple' is employed for convenience. In the calls to 'AddConstraint' below, the // vector of parameter names (as strings) matches the input integer vector of the lambda's. auto MultipleOfX = [](const std::vector<size_t>& v) {return IsMultiple(v[0], v[1]);}; auto MultipleOfXMulY = [](const std::vector<size_t>& v) {return IsMultiple(v[0], v[1] * v[2]);}; auto MultipleOfXMulYDivZ = [](const std::vector<size_t>& v) {return IsMultiple(v[0], (v[1] * v[2]) / v[3]);}; // Sets constraints: Requirement for unrolling the KWG loop tuner.addConstraint(kernelId, {"KWG", "KWI"}, MultipleOfX); // Sets constraints: Required for integer MWI and NWI tuner.addConstraint(kernelId, {"MWG", "MDIMC", "VWM"}, MultipleOfXMulY); tuner.addConstraint(kernelId, {"NWG", "NDIMC", "VWN"}, MultipleOfXMulY); // Sets constraints: Required for integer MWIA and NWIB tuner.addConstraint(kernelId, {"MWG", "MDIMA", "VWM"}, MultipleOfXMulY); tuner.addConstraint(kernelId, {"NWG", "NDIMB", "VWN"}, MultipleOfXMulY); // Sets constraints: KWG has to be a multiple of KDIMA = ((MDIMC*NDIMC)/(MDIMA)) and KDIMB = (...) tuner.addConstraint(kernelId, {"KWG", "MDIMC", "NDIMC", "MDIMA"}, MultipleOfXMulYDivZ); tuner.addConstraint(kernelId, {"KWG", "MDIMC", "NDIMC", "NDIMB"}, MultipleOfXMulYDivZ); // Set kernel arguments for both tuned kernel and reference kernel, order of arguments is important tuner.setKernelArguments(kernelId, std::vector<ktt::ArgumentId>{kSizeMId, kSizeNId, kSizeKId, matAId, matBId, matCId}); tuner.setKernelArguments(referenceKernelId, std::vector<ktt::ArgumentId>{kSizeMId, kSizeNId, kSizeKId, matAId, matBId, matCId}); #if RAPID_TEST == 0 // Specify custom tolerance threshold for validation of floating point arguments. Default threshold is 1e-4. tuner.setValidationMethod(ktt::ValidationMethod::SideBySideComparison, 0.001); // Set reference kernel which validates results provided by tuned kernel, provide list of arguments which will be validated tuner.setReferenceKernel(kernelId, referenceKernelId, std::vector<ktt::ParameterPair>{}, std::vector<ktt::ArgumentId>{matCId}); #endif // Launch kernel tuning tuner.tuneKernel(kernelId); // Print tuning results to standard output and to output.csv file tuner.printResult(kernelId, std::cout, ktt::PrintFormat::Verbose); tuner.printResult(kernelId, "gemm_output.csv", ktt::PrintFormat::CSV); return 0; };
/** * Copyright 2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/runtime/kernel/arm/fp32/addn_fp32.h" #include "src/kernel_registry.h" #include "src/runtime/kernel/arm/fp32/arithmetic_fp32.h" #include "include/errorcode.h" #include "src/runtime/runtime_api.h" using mindspore::kernel::KERNEL_ARCH::kCPU; using mindspore::lite::KernelRegistrar; using mindspore::lite::RET_ERROR; using mindspore::lite::RET_NULL_PTR; using mindspore::lite::RET_OK; using mindspore::schema::PrimitiveType_AddN; namespace mindspore::kernel { namespace { int AddNLaunch(void *cdata, int task_id) { if (cdata == nullptr) { MS_LOG(ERROR) << "Input cdata is nullptr!"; return RET_NULL_PTR; } auto kernel = reinterpret_cast<AddNCPUKernel *>(cdata); return kernel->AddNParallelRun(task_id); } } // namespace int AddNCPUKernel::Init() { return RET_OK; } int AddNCPUKernel::ReSize() { return RET_OK; } int AddNCPUKernel::AddNParallelRun(int thread_id) { int count_per_thread = UP_DIV(elements_num_, op_parameter_->thread_num_); int count = MSMIN(count_per_thread, static_cast<int>(elements_num_ - thread_id * count_per_thread)); auto stride = count_per_thread * thread_id; auto ret = ElementAdd(in1_addr_ + stride, in2_addr_ + stride, out_addr_ + stride, count); if (ret != NNACL_OK) { MS_LOG(ERROR) << "ElementAdd fail! ret: " << ret; return RET_ERROR; } return RET_OK; } int AddNCPUKernel::Run() { elements_num_ = out_tensors_[0]->ElementsNum(); auto input0_data = reinterpret_cast<float *>(in_tensors_[0]->MutableData()); auto input1_data = reinterpret_cast<float *>(in_tensors_[1]->MutableData()); auto output_data = reinterpret_cast<float *>(out_tensors_[0]->MutableData()); if (static_cast<int>(elements_num_) < op_parameter_->thread_num_) { if (in_tensors_[0]->shape() == in_tensors_[1]->shape()) { ElementAdd(input0_data, input1_data, output_data, elements_num_); } else { ArithmeticParameter param; param.in_elements_num0_ = in_tensors_[0]->ElementsNum(); param.in_elements_num1_ = in_tensors_[1]->ElementsNum(); param.out_elements_num_ = out_tensors_[0]->ElementsNum(); param.broadcasting_ = true; ElementOptAdd(input0_data, input1_data, output_data, elements_num_, &param); } for (size_t i = 2; i < in_tensors_.size(); ++i) { if (in_tensors_[i]->shape() == out_tensors_[0]->shape()) { ElementAdd(reinterpret_cast<float *>(in_tensors_[i]->MutableData()), output_data, output_data, elements_num_); } else { ArithmeticParameter param; param.in_elements_num0_ = in_tensors_[i]->ElementsNum(); param.in_elements_num1_ = out_tensors_[0]->ElementsNum(); param.out_elements_num_ = out_tensors_[0]->ElementsNum(); param.broadcasting_ = true; ElementOptAdd(reinterpret_cast<float *>(in_tensors_[i]->MutableData()), output_data, output_data, elements_num_, &param); } } return RET_OK; } in1_addr_ = input0_data; in2_addr_ = input1_data; out_addr_ = output_data; auto ret = ParallelLaunch(this->context_->thread_pool_, AddNLaunch, this, op_parameter_->thread_num_); if (ret != RET_OK) { MS_LOG(ERROR) << "addn launch fail!ret: " << ret; return RET_ERROR; } for (size_t i = 2; i < in_tensors_.size(); ++i) { in1_addr_ = reinterpret_cast<float *>(in_tensors_[i]->MutableData()); in2_addr_ = output_data; ret = ParallelLaunch(this->context_->thread_pool_, AddNLaunch, this, op_parameter_->thread_num_); if (ret != RET_OK) { MS_LOG(ERROR) << "addn launch fail!ret: " << ret << ", input index: " << i; return RET_ERROR; } } return RET_OK; } kernel::LiteKernel *CpuAddNFp32KernelCreator(const std::vector<lite::Tensor *> &inputs, const std::vector<lite::Tensor *> &outputs, OpParameter *op_parameter, const lite::InnerContext *ctx, const kernel::KernelKey &desc, const mindspore::lite::PrimitiveC *primitive) { if (op_parameter == nullptr) { MS_LOG(ERROR) << "Input op_parameter is nullptr!"; return nullptr; } if (ctx == nullptr) { MS_LOG(ERROR) << "Input context is nullptr!"; free(op_parameter); return nullptr; } MS_ASSERT(desc.type == schema::PrimitiveType_AddN); op_parameter->thread_num_ = ctx->thread_num_; auto *kernel = new (std::nothrow) AddNCPUKernel(op_parameter, inputs, outputs, ctx, primitive); if (kernel == nullptr) { MS_LOG(ERROR) << "new AddNCPUKernel fail!"; free(op_parameter); return nullptr; } auto ret = kernel->Init(); if (ret != RET_OK) { MS_LOG(ERROR) << "Init kernel failed! name: " << op_parameter->name_ << ", type: " << schema::EnumNamePrimitiveType(static_cast<schema::PrimitiveType>(op_parameter->type_)); delete kernel; return nullptr; } return kernel; } REG_KERNEL(kCPU, kNumberTypeFloat32, PrimitiveType_AddN, CpuAddNFp32KernelCreator) } // namespace mindspore::kernel
#include <iostream> #include <vector> using namespace std; int knapsack01(int *weight, int *prices, int n, int c) { // base case: if (n == 0 || c == 0) return 0; // recursive case: int inc = 0, exc = 0; // if we include the last item if (weight[n - 1] <= c) inc = prices[n - 1] + knapsack01(weight, prices, n - 1, c - weight[n - 1]); // if we exclude the last item exc = knapsack01(weight, prices, n - 1, c); return max(inc, exc); } int main() { int weight[] = {1, 2, 3, 5}; int prices[] = {40, 20, 30, 100}; int n = 4; int capacity = 7; cout << knapsack01(weight, prices, n, capacity) << endl; return 0; }
#include <algorithm> #include <cassert> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <iostream> #include <sstream> #include <string> #include <vector> using namespace std; int m, n; const int mod = 1000000009; int choose[51][51]; long long fastexp(long long n, long long k) { long long ret = 1; while (k > 0) { if (k&1) { ret = ret*n%mod; } n = n*n%mod; k >>= 1; } return ret; } int dp[51][51]; int calc(int h1, int w1, int h2, int w2, int H) { memset(dp, 0, sizeof dp); dp[h2][w1] = 1; for (int i=h2-1; i>=0; --i) { for (int j=0; j<=w1; ++j) { dp[i][j] = 0; for (int k=0; k<=w1-j; ++k) { long long add = choose[w1-j][k]*fastexp(H, w1-j-k)%mod*fastexp(H+1, j + (i<h1 ? w2-w1 : 0))%mod; if (k==0 && i<h1) { add -= fastexp(H, (i<h1 ? w2 : w1)); if (add < 0) { add += mod; } } dp[i][j] = (dp[i][j] + add*dp[i+1][j+k]%mod)%mod; } } } return dp[0][0]; } class AxonometricProjection { public: int howManyWays(vector <int> R, vector <int> C) { m = R.size(); n = C.size(); sort(R.begin(), R.end()); sort(C.begin(), C.end()); if (R.back() != C.back()) { return 0; } choose[0][0] = 1; for (int i=1; i<51; ++i) { choose[i][0] = choose[i][i] = 1; for (int j=1; j<i; ++j) { choose[i][j] = (choose[i-1][j-1] + choose[i-1][j]) % mod; } } long long sol = 1; for (int iter=0; iter<2; ++iter) { for (int i=0; i<m; ++i) { if (i==0 || R[i]!=R[i-1]) { pair<vector<int>::iterator, vector<int>::iterator> range = equal_range(C.begin(), C.end(), R[i]); int j = range.first - C.begin(); int h1 = upper_bound(R.begin(), R.end(), R[i]) - R.begin() - i; assert(h1 > 0); int w1 = range.second - range.first; int h2 = (w1==0 ? h1 : m-i); int w2 = n - j; if (!iter || w1==0) { sol = sol*calc(h1, w1, h2, w2, R[i])%mod; } } } R.swap(C); swap(m, n); } return sol; } };
//================================================================================================== /** EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT **/ //================================================================================================== #include <eve/function/round.hpp> #include <eve/constant/valmin.hpp> #include <eve/constant/valmax.hpp> #include <tts/tests/range.hpp> #include "measures.hpp" #include "producers.hpp" #include <cmath> TTS_CASE_TPL("wide random check on round", EVE_TYPE) { using v_t = eve::element_type_t<T>; if constexpr(eve::floating_value<T>) { auto std_round = tts::vectorize<T>( [](auto e) { return std::nearbyint(e); } ); eve::exhaustive_producer<T> p(eve::valmin(eve::as<v_t>())+1, eve::valmax(eve::as<v_t>())); TTS_RANGE_CHECK(p, std_round, eve::round); } else { auto std_round = tts::vectorize<T>( [](auto e) { return e; } ); eve::exhaustive_producer<T> p(eve::valmin(eve::as<v_t>()), eve::valmax(eve::as<v_t>())); TTS_RANGE_CHECK(p, std_round, eve::round); } }
#include "pch.h" #include "RHICommandList.h" RHICommandListExecutor gRHICommandList; RHICommandListImmediate& RHICommandListExecutor::GetImmediateCommandList() { return gRHICommandList.ImmediateCommandList; }
#include <ast/AssertStatementNode.h> using namespace PythonCoreNative::RunTime::Parser::AST; using namespace PythonCoreNative::RunTime::Parser; AssertStatementNode::AssertStatementNode( unsigned int start, unsigned int end, std::shared_ptr<Token> op1, std::shared_ptr<ExpressionNode> left, std::shared_ptr<Token> op2, std::shared_ptr<ExpressionNode> right ) : StatementNode(start, end) { mOp1 = op1; mLeft = left; mOp2 = op2; mRight = right; } std::shared_ptr<Token> AssertStatementNode::GetOperator1() { return mOp1; } std::shared_ptr<ExpressionNode> AssertStatementNode::GetLeft() { return mLeft; } std::shared_ptr<Token> AssertStatementNode::GetOperator2() { return mOp2; } std::shared_ptr<ExpressionNode> AssertStatementNode::GetRight() { return mRight; }
#include <H4l/OverlapRemoval.h> #include "xAODEgamma/ElectronxAODHelpers.h" #include <iostream> #include <TVector2.h> using namespace std; void OverlapRemoval::applyOverlapRemoval( xAOD::ElectronContainer *m_el_pass, xAOD::MuonContainer *m_mu_pass, xAOD::JetContainer *m_j_pass, bool debug) { // set true for all for (const auto& electron: *m_el_pass) { dec_passOR(*electron) = dec_signal(*electron); } for (const auto& muon: *m_mu_pass) { dec_passOR(*muon) = dec_signal(*muon); } for (const auto& jet: *m_j_pass) { dec_passOR(*jet) = dec_signal(*jet); } // e-e overlap for (int ie1 = 0; ie1 < (int) m_el_pass->size() - 1; ie1++) { if (! dec_passOR(*((*m_el_pass)[ie1]))) continue; const xAOD::TrackParticle* track_1 = xAOD::EgammaHelpers::getOriginalTrackParticleFromGSF(m_el_pass->at(ie1)->trackParticle()); float e1_d0 = (float) track_1->d0(); float e1_z0 = (float) track_1->z0(); float e1_theta = (float) track_1->theta(); float e1_phi = (float) track_1->phi(); float e1_qOverP = (float) track_1->qOverP(); float e1_et = (float) (*m_el_pass)[ie1]->caloCluster()->et(); float e1_eta = (float) (*m_el_pass)[ie1]->caloCluster()->eta(); for (int ie2 = ie1 + 1; ie2 < (int) m_el_pass->size(); ie2++) { if (! dec_passOR(*((*m_el_pass)[ie2]))) continue; const xAOD::TrackParticle* track_2 = xAOD::EgammaHelpers::getOriginalTrackParticleFromGSF(m_el_pass->at(ie2)->trackParticle()); float e2_d0 = (float) track_2->d0(); float e2_z0 = (float) track_2->z0(); float e2_theta = (float) track_2->theta(); float e2_phi = (float) track_2->phi(); float e2_qOverP = (float) track_2->qOverP(); float e2_et = (float) (*m_el_pass)[ie2]->caloCluster()->et(); float e2_eta = (float) (*m_el_pass)[ie2]->caloCluster()->eta(); float d_eta = fabs(e1_eta - e2_eta); float d_phi = TVector2::Phi_mpi_pi(e1_phi - e2_phi); if ((e1_d0 == e2_d0 && e1_z0 == e2_z0 && e1_theta == e2_theta && e1_phi == e2_phi && e1_qOverP == e2_qOverP) || (d_eta < 3 * 0.025 && d_phi < 5 * 0.025)) { if (e1_et < e2_et){ dec_passOR(*((*m_el_pass)[ie1])) = false; } else { dec_passOR(*((*m_el_pass)[ie2])) = false; } } } } // e-mu overlap for (int ie = 0; ie < (int) m_el_pass->size(); ie++) { if (! dec_passOR(*((*m_el_pass)[ie]))) continue; const xAOD::TrackParticle* track_ele = xAOD::EgammaHelpers::getOriginalTrackParticleFromGSF(m_el_pass->at(ie)->trackParticle()); float e_phi = (float) track_ele->phi(); float e_eta = (float) track_ele->eta(); for (auto mu_iter = m_mu_pass->begin(); mu_iter != m_mu_pass->end(); ++mu_iter) { if(! dec_passOR(**mu_iter) ) continue; if((*mu_iter)->muonType() == xAOD::Muon::MuonType::MuonStandAlone) continue; float cb_phi = (float)(*mu_iter)->trackParticle(xAOD::Muon::InnerDetectorTrackParticle)->phi(); float cb_theta = (float)(*mu_iter)->trackParticle(xAOD::Muon::InnerDetectorTrackParticle)->theta(); float cb_eta = (float) -1.0 * log(tan(cb_theta/2.0)); float d_eta = fabs(e_eta - cb_eta); float d_phi =TVector2::Phi_mpi_pi(e_phi - cb_phi); float d_R = sqrt(d_eta*d_eta + d_phi*d_phi); if (d_R < 0.02){ if((*mu_iter)->muonType() != xAOD::Muon::MuonType::Combined && (*mu_iter)->muonType() != xAOD::Muon::MuonType::SegmentTagged){ dec_passOR(*((*m_el_pass)[ie])) = false; } if((*mu_iter)->muonType() == xAOD::Muon::MuonType::CaloTagged){ dec_passOR(**mu_iter) = false; } } } } // j-e overlap for (int ij = 0; ij < (int) m_j_pass->size(); ij++) { if (! dec_passOR(*((*m_j_pass)[ij])) ) continue; float j_eta = (*m_j_pass)[ij]->jetP4(xAOD::JetEMScaleMomentum).eta(); float j_phi = (*m_j_pass)[ij]->jetP4(xAOD::JetEMScaleMomentum).phi(); for (int ie = 0; ie < (int) m_el_pass->size(); ie++) { if (! dec_passOR(*((*m_el_pass)[ie])) || ! dec_signal(*((*m_el_pass)[ie]))) continue; float e_phi = (float) (*m_el_pass)[ie]->trackParticle()->phi(); float e_eta = (float) (*m_el_pass)[ie]->trackParticle()->eta(); float d_eta = fabs(e_eta - j_eta); float d_phi = TVector2::Phi_mpi_pi(e_phi - j_phi); float d_R = sqrt(d_eta*d_eta + d_phi*d_phi); if (d_R < 0.2){ dec_passOR(*((*m_j_pass)[ij])) = false; } } } }
//===- STLExtrasTest.cpp - Unit tests for STL extras ----------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "llvm/ADT/STLExtras.h" #include "gtest/gtest.h" #include <list> #include <vector> using namespace llvm; namespace { int f(rank<0>) { return 0; } int f(rank<1>) { return 1; } int f(rank<2>) { return 2; } int f(rank<4>) { return 4; } TEST(STLExtrasTest, Rank) { // We shouldn't get ambiguities and should select the overload of the same // rank as the argument. EXPECT_EQ(0, f(rank<0>())); EXPECT_EQ(1, f(rank<1>())); EXPECT_EQ(2, f(rank<2>())); // This overload is missing so we end up back at 2. EXPECT_EQ(2, f(rank<3>())); // But going past 3 should work fine. EXPECT_EQ(4, f(rank<4>())); // And we can even go higher and just fall back to the last overload. EXPECT_EQ(4, f(rank<5>())); EXPECT_EQ(4, f(rank<6>())); } TEST(STLExtrasTest, EnumerateLValue) { // Test that a simple LValue can be enumerated and gives correct results with // multiple types, including the empty container. std::vector<char> foo = {'a', 'b', 'c'}; typedef std::pair<std::size_t, char> CharPairType; std::vector<CharPairType> CharResults; for (auto X : llvm::enumerate(foo)) { CharResults.emplace_back(X.index(), X.value()); } ASSERT_EQ(3u, CharResults.size()); EXPECT_EQ(CharPairType(0u, 'a'), CharResults[0]); EXPECT_EQ(CharPairType(1u, 'b'), CharResults[1]); EXPECT_EQ(CharPairType(2u, 'c'), CharResults[2]); // Test a const range of a different type. typedef std::pair<std::size_t, int> IntPairType; std::vector<IntPairType> IntResults; const std::vector<int> bar = {1, 2, 3}; for (auto X : llvm::enumerate(bar)) { IntResults.emplace_back(X.index(), X.value()); } ASSERT_EQ(3u, IntResults.size()); EXPECT_EQ(IntPairType(0u, 1), IntResults[0]); EXPECT_EQ(IntPairType(1u, 2), IntResults[1]); EXPECT_EQ(IntPairType(2u, 3), IntResults[2]); // Test an empty range. IntResults.clear(); const std::vector<int> baz{}; for (auto X : llvm::enumerate(baz)) { IntResults.emplace_back(X.index(), X.value()); } EXPECT_TRUE(IntResults.empty()); } TEST(STLExtrasTest, EnumerateModifyLValue) { // Test that you can modify the underlying entries of an lvalue range through // the enumeration iterator. std::vector<char> foo = {'a', 'b', 'c'}; for (auto X : llvm::enumerate(foo)) { ++X.value(); } EXPECT_EQ('b', foo[0]); EXPECT_EQ('c', foo[1]); EXPECT_EQ('d', foo[2]); } TEST(STLExtrasTest, EnumerateRValueRef) { // Test that an rvalue can be enumerated. typedef std::pair<std::size_t, int> PairType; std::vector<PairType> Results; auto Enumerator = llvm::enumerate(std::vector<int>{1, 2, 3}); for (auto X : llvm::enumerate(std::vector<int>{1, 2, 3})) { Results.emplace_back(X.index(), X.value()); } ASSERT_EQ(3u, Results.size()); EXPECT_EQ(PairType(0u, 1), Results[0]); EXPECT_EQ(PairType(1u, 2), Results[1]); EXPECT_EQ(PairType(2u, 3), Results[2]); } TEST(STLExtrasTest, EnumerateModifyRValue) { // Test that when enumerating an rvalue, modification still works (even if // this isn't terribly useful, it at least shows that we haven't snuck an // extra const in there somewhere. typedef std::pair<std::size_t, char> PairType; std::vector<PairType> Results; for (auto X : llvm::enumerate(std::vector<char>{'1', '2', '3'})) { ++X.value(); Results.emplace_back(X.index(), X.value()); } ASSERT_EQ(3u, Results.size()); EXPECT_EQ(PairType(0u, '2'), Results[0]); EXPECT_EQ(PairType(1u, '3'), Results[1]); EXPECT_EQ(PairType(2u, '4'), Results[2]); } template <bool B> struct CanMove {}; template <> struct CanMove<false> { CanMove(CanMove &&) = delete; CanMove() = default; CanMove(const CanMove &) = default; }; template <bool B> struct CanCopy {}; template <> struct CanCopy<false> { CanCopy(const CanCopy &) = delete; CanCopy() = default; CanCopy(CanCopy &&) = default; }; template <bool Moveable, bool Copyable> class Counted : CanMove<Moveable>, CanCopy<Copyable> { int &C; int &M; int &D; public: explicit Counted(int &C, int &M, int &D) : C(C), M(M), D(D) {} Counted(const Counted &O) : CanCopy<Copyable>(O), C(O.C), M(O.M), D(O.D) { ++C; } Counted(Counted &&O) : CanMove<Moveable>(std::move(O)), C(O.C), M(O.M), D(O.D) { ++M; } ~Counted() { ++D; } }; template <bool Moveable, bool Copyable> struct Range : Counted<Moveable, Copyable> { using Counted<Moveable, Copyable>::Counted; int *begin() { return nullptr; } int *end() { return nullptr; } }; TEST(STLExtrasTest, EnumerateLifetimeSemanticsPRValue) { int Copies = 0; int Moves = 0; int Destructors = 0; { auto E = enumerate(Range<true, false>(Copies, Moves, Destructors)); (void)E; // Doesn't compile. rvalue ranges must be moveable. // auto E2 = enumerate(Range<false, true>(Copies, Moves, Destructors)); EXPECT_EQ(0, Copies); EXPECT_EQ(1, Moves); EXPECT_EQ(1, Destructors); } EXPECT_EQ(0, Copies); EXPECT_EQ(1, Moves); EXPECT_EQ(2, Destructors); } TEST(STLExtrasTest, EnumerateLifetimeSemanticsRValue) { // With an rvalue, it should not be destroyed until the end of the scope. int Copies = 0; int Moves = 0; int Destructors = 0; { Range<true, false> R(Copies, Moves, Destructors); { auto E = enumerate(std::move(R)); (void)E; // Doesn't compile. rvalue ranges must be moveable. // auto E2 = enumerate(Range<false, true>(Copies, Moves, Destructors)); EXPECT_EQ(0, Copies); EXPECT_EQ(1, Moves); EXPECT_EQ(0, Destructors); } EXPECT_EQ(0, Copies); EXPECT_EQ(1, Moves); EXPECT_EQ(1, Destructors); } EXPECT_EQ(0, Copies); EXPECT_EQ(1, Moves); EXPECT_EQ(2, Destructors); } TEST(STLExtrasTest, EnumerateLifetimeSemanticsLValue) { // With an lvalue, it should not be destroyed even after the end of the scope. // lvalue ranges need be neither copyable nor moveable. int Copies = 0; int Moves = 0; int Destructors = 0; { Range<false, false> R(Copies, Moves, Destructors); { auto E = enumerate(R); (void)E; EXPECT_EQ(0, Copies); EXPECT_EQ(0, Moves); EXPECT_EQ(0, Destructors); } EXPECT_EQ(0, Copies); EXPECT_EQ(0, Moves); EXPECT_EQ(0, Destructors); } EXPECT_EQ(0, Copies); EXPECT_EQ(0, Moves); EXPECT_EQ(1, Destructors); } TEST(STLExtrasTest, ApplyTuple) { auto T = std::make_tuple(1, 3, 7); auto U = llvm::apply_tuple( [](int A, int B, int C) { return std::make_tuple(A - B, B - C, C - A); }, T); EXPECT_EQ(-2, std::get<0>(U)); EXPECT_EQ(-4, std::get<1>(U)); EXPECT_EQ(6, std::get<2>(U)); auto V = llvm::apply_tuple( [](int A, int B, int C) { return std::make_tuple(std::make_pair(A, char('A' + A)), std::make_pair(B, char('A' + B)), std::make_pair(C, char('A' + C))); }, T); EXPECT_EQ(std::make_pair(1, 'B'), std::get<0>(V)); EXPECT_EQ(std::make_pair(3, 'D'), std::get<1>(V)); EXPECT_EQ(std::make_pair(7, 'H'), std::get<2>(V)); } class apply_variadic { static int apply_one(int X) { return X + 1; } static char apply_one(char C) { return C + 1; } static StringRef apply_one(StringRef S) { return S.drop_back(); } public: template <typename... Ts> auto operator()(Ts &&... Items) { return std::make_tuple(apply_one(Items)...); } }; TEST(STLExtrasTest, ApplyTupleVariadic) { auto Items = std::make_tuple(1, llvm::StringRef("Test"), 'X'); auto Values = apply_tuple(apply_variadic(), Items); EXPECT_EQ(2, std::get<0>(Values)); EXPECT_EQ("Tes", std::get<1>(Values)); EXPECT_EQ('Y', std::get<2>(Values)); } TEST(STLExtrasTest, CountAdaptor) { std::vector<int> v; v.push_back(1); v.push_back(2); v.push_back(1); v.push_back(4); v.push_back(3); v.push_back(2); v.push_back(1); EXPECT_EQ(3, count(v, 1)); EXPECT_EQ(2, count(v, 2)); EXPECT_EQ(1, count(v, 3)); EXPECT_EQ(1, count(v, 4)); } TEST(STLExtrasTest, for_each) { std::vector<int> v{0, 1, 2, 3, 4}; int count = 0; llvm::for_each(v, [&count](int) { ++count; }); EXPECT_EQ(5, count); } TEST(STLExtrasTest, ToVector) { std::vector<char> v = {'a', 'b', 'c'}; auto Enumerated = to_vector<4>(enumerate(v)); ASSERT_EQ(3u, Enumerated.size()); for (size_t I = 0; I < v.size(); ++I) { EXPECT_EQ(I, Enumerated[I].index()); EXPECT_EQ(v[I], Enumerated[I].value()); } auto EnumeratedImplicitSize = to_vector(enumerate(v)); ASSERT_EQ(3u, EnumeratedImplicitSize.size()); for (size_t I = 0; I < v.size(); ++I) { EXPECT_EQ(I, EnumeratedImplicitSize[I].index()); EXPECT_EQ(v[I], EnumeratedImplicitSize[I].value()); } } TEST(STLExtrasTest, ConcatRange) { std::vector<int> Expected = {1, 2, 3, 4, 5, 6, 7, 8}; std::vector<int> Test; std::vector<int> V1234 = {1, 2, 3, 4}; std::list<int> L56 = {5, 6}; SmallVector<int, 2> SV78 = {7, 8}; // Use concat across different sized ranges of different types with different // iterators. for (int &i : concat<int>(V1234, L56, SV78)) Test.push_back(i); EXPECT_EQ(Expected, Test); // Use concat between a temporary, an L-value, and an R-value to make sure // complex lifetimes work well. Test.clear(); for (int &i : concat<int>(std::vector<int>(V1234), L56, std::move(SV78))) Test.push_back(i); EXPECT_EQ(Expected, Test); } TEST(STLExtrasTest, PartitionAdaptor) { std::vector<int> V = {1, 2, 3, 4, 5, 6, 7, 8}; auto I = partition(V, [](int i) { return i % 2 == 0; }); ASSERT_EQ(V.begin() + 4, I); // Sort the two halves as partition may have messed with the order. llvm::sort(V.begin(), I); llvm::sort(I, V.end()); EXPECT_EQ(2, V[0]); EXPECT_EQ(4, V[1]); EXPECT_EQ(6, V[2]); EXPECT_EQ(8, V[3]); EXPECT_EQ(1, V[4]); EXPECT_EQ(3, V[5]); EXPECT_EQ(5, V[6]); EXPECT_EQ(7, V[7]); } TEST(STLExtrasTest, EraseIf) { std::vector<int> V = {1, 2, 3, 4, 5, 6, 7, 8}; erase_if(V, [](int i) { return i % 2 == 0; }); EXPECT_EQ(4u, V.size()); EXPECT_EQ(1, V[0]); EXPECT_EQ(3, V[1]); EXPECT_EQ(5, V[2]); EXPECT_EQ(7, V[3]); } TEST(STLExtrasTest, AppendRange) { auto AppendVals = {3}; std::vector<int> V = {1, 2}; append_range(V, AppendVals); EXPECT_EQ(1, V[0]); EXPECT_EQ(2, V[1]); EXPECT_EQ(3, V[2]); } namespace some_namespace { struct some_struct { std::vector<int> data; std::string swap_val; }; std::vector<int>::const_iterator begin(const some_struct &s) { return s.data.begin(); } std::vector<int>::const_iterator end(const some_struct &s) { return s.data.end(); } void swap(some_struct &lhs, some_struct &rhs) { // make swap visible as non-adl swap would even seem to // work with std::swap which defaults to moving lhs.swap_val = "lhs"; rhs.swap_val = "rhs"; } } // namespace some_namespace TEST(STLExtrasTest, ADLTest) { some_namespace::some_struct s{{1, 2, 3, 4, 5}, ""}; some_namespace::some_struct s2{{2, 4, 6, 8, 10}, ""}; EXPECT_EQ(*adl_begin(s), 1); EXPECT_EQ(*(adl_end(s) - 1), 5); adl_swap(s, s2); EXPECT_EQ(s.swap_val, "lhs"); EXPECT_EQ(s2.swap_val, "rhs"); int count = 0; llvm::for_each(s, [&count](int) { ++count; }); EXPECT_EQ(5, count); } TEST(STLExtrasTest, EmptyTest) { std::vector<void*> V; EXPECT_TRUE(llvm::empty(V)); V.push_back(nullptr); EXPECT_FALSE(llvm::empty(V)); std::initializer_list<int> E = {}; std::initializer_list<int> NotE = {7, 13, 42}; EXPECT_TRUE(llvm::empty(E)); EXPECT_FALSE(llvm::empty(NotE)); auto R0 = make_range(V.begin(), V.begin()); EXPECT_TRUE(llvm::empty(R0)); auto R1 = make_range(V.begin(), V.end()); EXPECT_FALSE(llvm::empty(R1)); } TEST(STLExtrasTest, DropBeginTest) { SmallVector<int, 5> vec{0, 1, 2, 3, 4}; for (int n = 0; n < 5; ++n) { int i = n; for (auto &v : drop_begin(vec, n)) { EXPECT_EQ(v, i); i += 1; } EXPECT_EQ(i, 5); } } TEST(STLExtrasTest, DropBeginDefaultTest) { SmallVector<int, 5> vec{0, 1, 2, 3, 4}; int i = 1; for (auto &v : drop_begin(vec)) { EXPECT_EQ(v, i); i += 1; } EXPECT_EQ(i, 5); } TEST(STLExtrasTest, EarlyIncrementTest) { std::list<int> L = {1, 2, 3, 4}; auto EIR = make_early_inc_range(L); auto I = EIR.begin(); auto EI = EIR.end(); EXPECT_NE(I, EI); EXPECT_EQ(1, *I); #if LLVM_ENABLE_ABI_BREAKING_CHECKS #ifndef NDEBUG // Repeated dereferences are not allowed. EXPECT_DEATH(*I, "Cannot dereference"); // Comparison after dereference is not allowed. EXPECT_DEATH((void)(I == EI), "Cannot compare"); EXPECT_DEATH((void)(I != EI), "Cannot compare"); #endif #endif ++I; EXPECT_NE(I, EI); #if LLVM_ENABLE_ABI_BREAKING_CHECKS #ifndef NDEBUG // You cannot increment prior to dereference. EXPECT_DEATH(++I, "Cannot increment"); #endif #endif EXPECT_EQ(2, *I); #if LLVM_ENABLE_ABI_BREAKING_CHECKS #ifndef NDEBUG // Repeated dereferences are not allowed. EXPECT_DEATH(*I, "Cannot dereference"); #endif #endif // Inserting shouldn't break anything. We should be able to keep dereferencing // the currrent iterator and increment. The increment to go to the "next" // iterator from before we inserted. L.insert(std::next(L.begin(), 2), -1); ++I; EXPECT_EQ(3, *I); // Erasing the front including the current doesn't break incrementing. L.erase(L.begin(), std::prev(L.end())); ++I; EXPECT_EQ(4, *I); ++I; EXPECT_EQ(EIR.end(), I); } // A custom iterator that returns a pointer when dereferenced. This is used to // test make_early_inc_range with iterators that do not return a reference on // dereferencing. struct CustomPointerIterator : public iterator_adaptor_base<CustomPointerIterator, std::list<int>::iterator, std::forward_iterator_tag> { using base_type = iterator_adaptor_base<CustomPointerIterator, std::list<int>::iterator, std::forward_iterator_tag>; explicit CustomPointerIterator(std::list<int>::iterator I) : base_type(I) {} // Retrieve a pointer to the current int. int *operator*() const { return &*base_type::wrapped(); } }; // Make sure make_early_inc_range works with iterators that do not return a // reference on dereferencing. The test is similar to EarlyIncrementTest, but // uses CustomPointerIterator. TEST(STLExtrasTest, EarlyIncrementTestCustomPointerIterator) { std::list<int> L = {1, 2, 3, 4}; auto CustomRange = make_range(CustomPointerIterator(L.begin()), CustomPointerIterator(L.end())); auto EIR = make_early_inc_range(CustomRange); auto I = EIR.begin(); auto EI = EIR.end(); EXPECT_NE(I, EI); EXPECT_EQ(&*L.begin(), *I); #if LLVM_ENABLE_ABI_BREAKING_CHECKS #ifndef NDEBUG // Repeated dereferences are not allowed. EXPECT_DEATH(*I, "Cannot dereference"); // Comparison after dereference is not allowed. EXPECT_DEATH((void)(I == EI), "Cannot compare"); EXPECT_DEATH((void)(I != EI), "Cannot compare"); #endif #endif ++I; EXPECT_NE(I, EI); #if LLVM_ENABLE_ABI_BREAKING_CHECKS #ifndef NDEBUG // You cannot increment prior to dereference. EXPECT_DEATH(++I, "Cannot increment"); #endif #endif EXPECT_EQ(&*std::next(L.begin()), *I); #if LLVM_ENABLE_ABI_BREAKING_CHECKS #ifndef NDEBUG // Repeated dereferences are not allowed. EXPECT_DEATH(*I, "Cannot dereference"); #endif #endif // Inserting shouldn't break anything. We should be able to keep dereferencing // the currrent iterator and increment. The increment to go to the "next" // iterator from before we inserted. L.insert(std::next(L.begin(), 2), -1); ++I; EXPECT_EQ(&*std::next(L.begin(), 3), *I); // Erasing the front including the current doesn't break incrementing. L.erase(L.begin(), std::prev(L.end())); ++I; EXPECT_EQ(&*L.begin(), *I); ++I; EXPECT_EQ(EIR.end(), I); } TEST(STLExtrasTest, splat) { std::vector<int> V; EXPECT_FALSE(is_splat(V)); V.push_back(1); EXPECT_TRUE(is_splat(V)); V.push_back(1); V.push_back(1); EXPECT_TRUE(is_splat(V)); V.push_back(2); EXPECT_FALSE(is_splat(V)); } TEST(STLExtrasTest, to_address) { int *V1 = new int; EXPECT_EQ(V1, to_address(V1)); // Check fancy pointer overload for unique_ptr std::unique_ptr<int> V2 = std::make_unique<int>(0); EXPECT_EQ(V2.get(), llvm::to_address(V2)); V2.reset(V1); EXPECT_EQ(V1, llvm::to_address(V2)); V2.release(); // Check fancy pointer overload for shared_ptr std::shared_ptr<int> V3 = std::make_shared<int>(0); std::shared_ptr<int> V4 = V3; EXPECT_EQ(V3.get(), V4.get()); EXPECT_EQ(V3.get(), llvm::to_address(V3)); EXPECT_EQ(V4.get(), llvm::to_address(V4)); V3.reset(V1); EXPECT_EQ(V1, llvm::to_address(V3)); } TEST(STLExtrasTest, partition_point) { std::vector<int> V = {1, 3, 5, 7, 9}; // Range version. EXPECT_EQ(V.begin() + 3, partition_point(V, [](unsigned X) { return X < 7; })); EXPECT_EQ(V.begin(), partition_point(V, [](unsigned X) { return X < 1; })); EXPECT_EQ(V.end(), partition_point(V, [](unsigned X) { return X < 50; })); } TEST(STLExtrasTest, hasSingleElement) { const std::vector<int> V0 = {}, V1 = {1}, V2 = {1, 2}; const std::vector<int> V10(10); EXPECT_EQ(hasSingleElement(V0), false); EXPECT_EQ(hasSingleElement(V1), true); EXPECT_EQ(hasSingleElement(V2), false); EXPECT_EQ(hasSingleElement(V10), false); } TEST(STLExtrasTest, hasNItems) { const std::list<int> V0 = {}, V1 = {1}, V2 = {1, 2}; const std::list<int> V3 = {1, 3, 5}; EXPECT_TRUE(hasNItems(V0, 0)); EXPECT_FALSE(hasNItems(V0, 2)); EXPECT_TRUE(hasNItems(V1, 1)); EXPECT_FALSE(hasNItems(V1, 2)); EXPECT_TRUE(hasNItems(V3.begin(), V3.end(), 3, [](int x) { return x < 10; })); EXPECT_TRUE(hasNItems(V3.begin(), V3.end(), 0, [](int x) { return x > 10; })); EXPECT_TRUE(hasNItems(V3.begin(), V3.end(), 2, [](int x) { return x < 5; })); } TEST(STLExtras, hasNItemsOrMore) { const std::list<int> V0 = {}, V1 = {1}, V2 = {1, 2}; const std::list<int> V3 = {1, 3, 5}; EXPECT_TRUE(hasNItemsOrMore(V1, 1)); EXPECT_FALSE(hasNItemsOrMore(V1, 2)); EXPECT_TRUE(hasNItemsOrMore(V2, 1)); EXPECT_TRUE(hasNItemsOrMore(V2, 2)); EXPECT_FALSE(hasNItemsOrMore(V2, 3)); EXPECT_TRUE(hasNItemsOrMore(V3, 3)); EXPECT_FALSE(hasNItemsOrMore(V3, 4)); EXPECT_TRUE( hasNItemsOrMore(V3.begin(), V3.end(), 3, [](int x) { return x < 10; })); EXPECT_FALSE( hasNItemsOrMore(V3.begin(), V3.end(), 3, [](int x) { return x > 10; })); EXPECT_TRUE( hasNItemsOrMore(V3.begin(), V3.end(), 2, [](int x) { return x < 5; })); } TEST(STLExtras, hasNItemsOrLess) { const std::list<int> V0 = {}, V1 = {1}, V2 = {1, 2}; const std::list<int> V3 = {1, 3, 5}; EXPECT_TRUE(hasNItemsOrLess(V0, 0)); EXPECT_TRUE(hasNItemsOrLess(V0, 1)); EXPECT_TRUE(hasNItemsOrLess(V0, 2)); EXPECT_FALSE(hasNItemsOrLess(V1, 0)); EXPECT_TRUE(hasNItemsOrLess(V1, 1)); EXPECT_TRUE(hasNItemsOrLess(V1, 2)); EXPECT_FALSE(hasNItemsOrLess(V2, 0)); EXPECT_FALSE(hasNItemsOrLess(V2, 1)); EXPECT_TRUE(hasNItemsOrLess(V2, 2)); EXPECT_TRUE(hasNItemsOrLess(V2, 3)); EXPECT_FALSE(hasNItemsOrLess(V3, 0)); EXPECT_FALSE(hasNItemsOrLess(V3, 1)); EXPECT_FALSE(hasNItemsOrLess(V3, 2)); EXPECT_TRUE(hasNItemsOrLess(V3, 3)); EXPECT_TRUE(hasNItemsOrLess(V3, 4)); EXPECT_TRUE( hasNItemsOrLess(V3.begin(), V3.end(), 1, [](int x) { return x == 1; })); EXPECT_TRUE( hasNItemsOrLess(V3.begin(), V3.end(), 2, [](int x) { return x < 5; })); EXPECT_TRUE( hasNItemsOrLess(V3.begin(), V3.end(), 5, [](int x) { return x < 5; })); EXPECT_FALSE( hasNItemsOrLess(V3.begin(), V3.end(), 2, [](int x) { return x < 10; })); } TEST(STLExtras, MoveRange) { class Foo { bool A; public: Foo() : A(true) {} Foo(const Foo &) = delete; Foo(Foo &&Other) : A(Other.A) { Other.A = false; } Foo &operator=(const Foo &) = delete; Foo &operator=(Foo &&Other) { if (this != &Other) { A = Other.A; Other.A = false; } return *this; } operator bool() const { return A; } }; SmallVector<Foo, 4U> V1, V2, V3, V4; auto HasVal = [](const Foo &Item) { return static_cast<bool>(Item); }; auto Build = [&] { SmallVector<Foo, 4U> Foos; Foos.resize(4U); return Foos; }; V1.resize(4U); EXPECT_TRUE(llvm::all_of(V1, HasVal)); llvm::move(V1, std::back_inserter(V2)); // Ensure input container is same size, but its contents were moved out. EXPECT_EQ(V1.size(), 4U); EXPECT_TRUE(llvm::none_of(V1, HasVal)); // Ensure output container has the contents of the input container. EXPECT_EQ(V2.size(), 4U); EXPECT_TRUE(llvm::all_of(V2, HasVal)); llvm::move(std::move(V2), std::back_inserter(V3)); EXPECT_TRUE(llvm::none_of(V2, HasVal)); EXPECT_EQ(V3.size(), 4U); EXPECT_TRUE(llvm::all_of(V3, HasVal)); llvm::move(Build(), std::back_inserter(V4)); EXPECT_EQ(V4.size(), 4U); EXPECT_TRUE(llvm::all_of(V4, HasVal)); } TEST(STLExtras, Unique) { std::vector<int> V = {1, 5, 5, 4, 3, 3, 3}; auto I = llvm::unique(V, [](int a, int b) { return a == b; }); EXPECT_EQ(I, V.begin() + 4); EXPECT_EQ(1, V[0]); EXPECT_EQ(5, V[1]); EXPECT_EQ(4, V[2]); EXPECT_EQ(3, V[3]); } TEST(STLExtrasTest, MakeVisitorOneCallable) { auto IdentityLambda = [](auto X) { return X; }; auto IdentityVisitor = makeVisitor(IdentityLambda); EXPECT_EQ(IdentityLambda(1), IdentityVisitor(1)); EXPECT_EQ(IdentityLambda(2.0f), IdentityVisitor(2.0f)); EXPECT_TRUE((std::is_same<decltype(IdentityLambda(IdentityLambda)), decltype(IdentityLambda)>::value)); EXPECT_TRUE((std::is_same<decltype(IdentityVisitor(IdentityVisitor)), decltype(IdentityVisitor)>::value)); } TEST(STLExtrasTest, MakeVisitorTwoCallables) { auto Visitor = makeVisitor([](int) { return 0; }, [](std::string) { return 1; }); EXPECT_EQ(Visitor(42), 0); EXPECT_EQ(Visitor("foo"), 1); } TEST(STLExtrasTest, MakeVisitorCallableMultipleOperands) { auto Second = makeVisitor([](int I, float F) { return F; }, [](float F, int I) { return I; }); EXPECT_EQ(Second(1.f, 1), 1); EXPECT_EQ(Second(1, 1.f), 1.f); } TEST(STLExtrasTest, MakeVisitorDefaultCase) { { auto Visitor = makeVisitor([](int I) { return I + 100; }, [](float F) { return F * 2; }, [](auto) { return -1; }); EXPECT_EQ(Visitor(24), 124); EXPECT_EQ(Visitor(2.f), 4.f); EXPECT_EQ(Visitor(2.), -1); EXPECT_EQ(Visitor(Visitor), -1); } { auto Visitor = makeVisitor([](auto) { return -1; }, [](int I) { return I + 100; }, [](float F) { return F * 2; }); EXPECT_EQ(Visitor(24), 124); EXPECT_EQ(Visitor(2.f), 4.f); EXPECT_EQ(Visitor(2.), -1); EXPECT_EQ(Visitor(Visitor), -1); } } template <bool Moveable, bool Copyable> struct Functor : Counted<Moveable, Copyable> { using Counted<Moveable, Copyable>::Counted; void operator()() {} }; TEST(STLExtrasTest, MakeVisitorLifetimeSemanticsPRValue) { int Copies = 0; int Moves = 0; int Destructors = 0; { auto V = makeVisitor(Functor<true, false>(Copies, Moves, Destructors)); (void)V; EXPECT_EQ(0, Copies); EXPECT_EQ(1, Moves); EXPECT_EQ(1, Destructors); } EXPECT_EQ(0, Copies); EXPECT_EQ(1, Moves); EXPECT_EQ(2, Destructors); } TEST(STLExtrasTest, MakeVisitorLifetimeSemanticsRValue) { int Copies = 0; int Moves = 0; int Destructors = 0; { Functor<true, false> F(Copies, Moves, Destructors); { auto V = makeVisitor(std::move(F)); (void)V; EXPECT_EQ(0, Copies); EXPECT_EQ(1, Moves); EXPECT_EQ(0, Destructors); } EXPECT_EQ(0, Copies); EXPECT_EQ(1, Moves); EXPECT_EQ(1, Destructors); } EXPECT_EQ(0, Copies); EXPECT_EQ(1, Moves); EXPECT_EQ(2, Destructors); } TEST(STLExtrasTest, MakeVisitorLifetimeSemanticsLValue) { int Copies = 0; int Moves = 0; int Destructors = 0; { Functor<true, true> F(Copies, Moves, Destructors); { auto V = makeVisitor(F); (void)V; EXPECT_EQ(1, Copies); EXPECT_EQ(0, Moves); EXPECT_EQ(0, Destructors); } EXPECT_EQ(1, Copies); EXPECT_EQ(0, Moves); EXPECT_EQ(1, Destructors); } EXPECT_EQ(1, Copies); EXPECT_EQ(0, Moves); EXPECT_EQ(2, Destructors); } TEST(STLExtrasTest, AllOfZip) { std::vector<int> v1 = {0, 4, 2, 1}; std::vector<int> v2 = {1, 4, 3, 6}; EXPECT_TRUE(all_of_zip(v1, v2, [](int v1, int v2) { return v1 <= v2; })); EXPECT_FALSE(all_of_zip(v1, v2, [](int L, int R) { return L < R; })); // Triple vectors std::vector<int> v3 = {1, 6, 5, 7}; EXPECT_EQ(true, all_of_zip(v1, v2, v3, [](int a, int b, int c) { return a <= b && b <= c; })); EXPECT_EQ(false, all_of_zip(v1, v2, v3, [](int a, int b, int c) { return a < b && b < c; })); // Shorter vector should fail even with an always-true predicate. std::vector<int> v_short = {1, 4}; EXPECT_EQ(false, all_of_zip(v1, v_short, [](int, int) { return true; })); EXPECT_EQ(false, all_of_zip(v1, v2, v_short, [](int, int, int) { return true; })); } TEST(STLExtrasTest, TypesAreDistinct) { EXPECT_TRUE((llvm::TypesAreDistinct<>::value)); EXPECT_TRUE((llvm::TypesAreDistinct<int>::value)); EXPECT_FALSE((llvm::TypesAreDistinct<int, int>::value)); EXPECT_TRUE((llvm::TypesAreDistinct<int, float>::value)); EXPECT_FALSE((llvm::TypesAreDistinct<int, float, int>::value)); EXPECT_TRUE((llvm::TypesAreDistinct<int, float, double>::value)); EXPECT_FALSE((llvm::TypesAreDistinct<int, float, double, float>::value)); EXPECT_TRUE((llvm::TypesAreDistinct<int, int *>::value)); EXPECT_TRUE((llvm::TypesAreDistinct<int, int &>::value)); EXPECT_TRUE((llvm::TypesAreDistinct<int, int &&>::value)); EXPECT_TRUE((llvm::TypesAreDistinct<int, const int>::value)); } TEST(STLExtrasTest, FirstIndexOfType) { EXPECT_EQ((llvm::FirstIndexOfType<int, int>::value), 0u); EXPECT_EQ((llvm::FirstIndexOfType<int, int, int>::value), 0u); EXPECT_EQ((llvm::FirstIndexOfType<int, float, int>::value), 1u); EXPECT_EQ((llvm::FirstIndexOfType<int const *, float, int, int const *, const int>::value), 2u); } TEST(STLExtrasTest, TypeAtIndex) { EXPECT_TRUE((std::is_same<int, llvm::TypeAtIndex<0, int>>::value)); EXPECT_TRUE((std::is_same<int, llvm::TypeAtIndex<0, int, float>>::value)); EXPECT_TRUE((std::is_same<float, llvm::TypeAtIndex<1, int, float>>::value)); EXPECT_TRUE( (std::is_same<float, llvm::TypeAtIndex<1, int, float, double>>::value)); EXPECT_TRUE( (std::is_same<float, llvm::TypeAtIndex<1, int, float, double>>::value)); EXPECT_TRUE( (std::is_same<double, llvm::TypeAtIndex<2, int, float, double>>::value)); } } // namespace
// This file has been automatically generated by the Unreal Header Implementation tool #include "FGProceduralStaticMeshActor.h" #if WITH_EDITOR void AFGProceduralStaticMeshActor::PreEditChange( UProperty* PropertyThatWillChange){ } void AFGProceduralStaticMeshActor::PostEditChangeProperty( FPropertyChangedEvent& propertyChangedEvent){ } void AFGProceduralStaticMeshActor::PostEditMove( bool bFinished){ } #endif #if WITH_EDITOR void AFGProceduralStaticMeshActor::PaintBucket_Add(){ } void AFGProceduralStaticMeshActor::PaintBucket_Remove(){ } float AFGProceduralStaticMeshActor::GetMeshArea( const FVector& origin, const FVector& extent) const{ return float(); } void AFGProceduralStaticMeshActor::GetRandomTraceInBounds( const FVector& origin, const FVector& extent, FVector& out_start, FVector& out_end) const{ } #endif #if WITH_EDITORONLY_DATA #endif
#include "Pcre2Base.h" #include "flags/Compile.h" Pcre2Base::Pcre2Base() : _regex_string("") { _regex_compiled = NULL; _match_data = NULL; _mcontext = NULL; _jit_stack = NULL; compileFlags = 0; matchFlags = 0; } void Pcre2Base::__construct(Php::Parameters &p) { if (p.size() > 1 && !p[1].isNull()) compileFlags |= p[1].numericValue(); else compileFlags |= (int64_t) Php::ini_get(EXT_NAME ".default_compile_flags").numericValue(); if (p.size() > 2 && !p[2].isNull()) matchFlags |= p[2].numericValue(); else matchFlags |= (int64_t) Php::ini_get(EXT_NAME ".default_match_flags").numericValue(); if (p.size() > 0 && !p[0].isNull() && p[0] != "") { p.resize(1); compile(p); } } void Pcre2Base::compile(Php::Parameters &p) { if (p.size() > 0 && !p[0].isNull()) _regex_string = p[0].rawValue(); if (p.size() > 1 && !p[1].isNull()) compileFlags = p[1].numericValue(); if (p.size() > 2 && !p[2].isNull()) matchFlags = p[2].numericValue(); if (_regex_string == "") throw Php::Exception("regular expression string cannot be empty"); int errorcode; PCRE2_SIZE erroroffset; _regex_compiled = pcre2_compile( (PCRE2_SPTR) _regex_string.c_str(), PCRE2_ZERO_TERMINATED, (uint32_t) compileFlags, &errorcode, &erroroffset, NULL // match context ); if (_regex_compiled == NULL) { PCRE2_UCHAR eMessage[256]; pcre2_get_error_message(errorcode, eMessage, sizeof(eMessage)); char eOut[1024]; std::snprintf(eOut, sizeof(eOut), "PCRE2 compilation failed at offset %d: %s", (int) erroroffset, eMessage); throw Php::Exception(eOut); } _match_data = pcre2_match_data_create_from_pattern(_regex_compiled, NULL); _mcontext = pcre2_match_context_create(NULL); if (_mcontext == NULL) throw Php::Exception("match context returned null, could not obtain memory"); // Apply JIT option if (compileFlags & Flags::Compile::JIT) { int32_t jitError = pcre2_jit_compile(_regex_compiled, PCRE2_JIT_COMPLETE); if (jitError) { PCRE2_UCHAR eMessage[256]; pcre2_get_error_message(jitError, eMessage, sizeof(eMessage)); throw Php::Exception((const char *) eMessage); } _jit_stack = pcre2_jit_stack_create( (PCRE2_SIZE) Php::ini_get(EXT_NAME ".jit_stack_min").numericValue() * 1024, (PCRE2_SIZE) Php::ini_get(EXT_NAME ".jit_stack_max").numericValue() * 1024 * 1024, NULL); if (_jit_stack == NULL) throw Php::Exception("an error occurred when creating JIT stack"); pcre2_jit_stack_assign(_mcontext, NULL, _jit_stack); } } void Pcre2Base::setRegex(Php::Parameters &p) { if (p[0].stringValue() == "") throw Php::Exception("regular expression string cannot be empty"); _regex_string = p[0].stringValue(); if (p.size() > 1 && !p[1].isNull()) { compileFlags = p[1].numericValue(); } } Php::Value Pcre2Base::getRegex() const { return _regex_string; } void Pcre2Base::__destruct() { if (_mcontext != NULL) { pcre2_match_context_free(_mcontext); _mcontext = NULL; } if (_jit_stack != NULL) { pcre2_jit_stack_free(_jit_stack); _jit_stack = NULL; } if (_match_data != NULL) { pcre2_match_data_free(_match_data); _match_data = NULL; } if (_regex_compiled != NULL) { pcre2_code_free(_regex_compiled); _regex_compiled = NULL; } _regex_string.clear(); _regex_string.shrink_to_fit(); } Pcre2Base::~Pcre2Base() { pcre2_match_context_free(_mcontext); pcre2_jit_stack_free(_jit_stack); pcre2_match_data_free(_match_data); pcre2_code_free(_regex_compiled); } Php::Value whatAmI() { return "extension"; }
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <algorithm> #include <iostream> #include <map> #include <set> #include <string> #include <vector> #include <mesos/attributes.hpp> #include <mesos/type_utils.hpp> #include <mesos/authentication/http/basic_authenticator_factory.hpp> #include <mesos/log/log.hpp> #include <mesos/state/log.hpp> #include <mesos/state/protobuf.hpp> #include <mesos/state/storage.hpp> #include <process/clock.hpp> #include <process/gmock.hpp> #include <process/gtest.hpp> #include <process/pid.hpp> #include <process/process.hpp> #include <stout/bytes.hpp> #include <stout/stopwatch.hpp> #include <stout/uuid.hpp> #include <stout/tests/utils.hpp> #include "common/protobuf_utils.hpp" #include "log/replica.hpp" #include "log/tool/initialize.hpp" #include "master/flags.hpp" #include "master/maintenance.hpp" #include "master/master.hpp" #include "master/quota.hpp" #include "master/registrar.hpp" #include "master/weights.hpp" #include "tests/mesos.hpp" using namespace mesos::internal::master; using namespace process; using mesos::log::Log; using mesos::internal::log::Replica; using std::cout; using std::endl; using std::map; using std::set; using std::string; using std::vector; using process::Clock; using process::Owned; using process::http::OK; using process::http::Response; using process::http::Unauthorized; using google::protobuf::RepeatedPtrField; using mesos::internal::protobuf::maintenance::createMachineList; using mesos::internal::protobuf::maintenance::createSchedule; using mesos::internal::protobuf::maintenance::createUnavailability; using mesos::internal::protobuf::maintenance::createWindow; using testing::_; using testing::DoAll; using testing::Eq; using testing::Return; using ::testing::WithParamInterface; namespace mesos { namespace internal { namespace tests { namespace quota = mesos::internal::master::quota; namespace weights = mesos::internal::master::weights; namespace authentication = process::http::authentication; using namespace mesos::maintenance; using namespace mesos::quota; using namespace mesos::internal::master::maintenance; using namespace mesos::internal::master::quota; using namespace mesos::internal::master::weights; using mesos::http::authentication::BasicAuthenticatorFactory; using mesos::state::LogStorage; using mesos::state::Storage; using mesos::state::protobuf::State; using state::Entry; static vector<WeightInfo> getWeightInfos( const hashmap<string, double>& weights) { vector<WeightInfo> weightInfos; foreachpair (const string& role, double weight, weights) { WeightInfo weightInfo; weightInfo.set_role(role); weightInfo.set_weight(weight); weightInfos.push_back(weightInfo); } return weightInfos; } // TODO(xujyan): This class copies code from LogStateTest. It would // be nice to find a common location for log related base tests when // there are more uses of it. class RegistrarTestBase : public TemporaryDirectoryTest { public: RegistrarTestBase() : log(NULL), storage(NULL), state(NULL), replica2(NULL) {} protected: virtual void SetUp() { TemporaryDirectoryTest::SetUp(); // For initializing the replicas. log::tool::Initialize initializer; string path1 = os::getcwd() + "/.log1"; string path2 = os::getcwd() + "/.log2"; initializer.flags.path = path1; initializer.execute(); initializer.flags.path = path2; initializer.execute(); // Only create the replica for 'path2' (i.e., the second replica) // as the first replica will be created when we create a Log. replica2 = new Replica(path2); set<UPID> pids; pids.insert(replica2->pid()); log = new Log(2, path1, pids); storage = new LogStorage(log); state = new State(storage); // Compensate for slow CI machines / VMs. flags.registry_store_timeout = Seconds(10); master.CopyFrom(protobuf::createMasterInfo(UPID("master@127.0.0.1:5050"))); SlaveID id; id.set_value("1"); SlaveInfo info; info.set_hostname("localhost"); info.mutable_id()->CopyFrom(id); slave.CopyFrom(info); } virtual void TearDown() { delete state; delete storage; delete log; delete replica2; TemporaryDirectoryTest::TearDown(); } Log* log; Storage* storage; State* state; Replica* replica2; MasterInfo master; SlaveInfo slave; Flags flags; }; class RegistrarTest : public RegistrarTestBase, public WithParamInterface<bool> { protected: virtual void SetUp() { RegistrarTestBase::SetUp(); flags.registry_strict = GetParam(); } }; // The Registrar tests are parameterized by "strictness". INSTANTIATE_TEST_CASE_P(Strict, RegistrarTest, ::testing::Bool()); TEST_P(RegistrarTest, Recover) { Registrar registrar(flags, state); // Operations preceding recovery will fail. AWAIT_EXPECT_FAILED( registrar.apply(Owned<Operation>(new AdmitSlave(slave)))); AWAIT_EXPECT_FAILED( registrar.apply(Owned<Operation>(new ReadmitSlave(slave)))); AWAIT_EXPECT_FAILED( registrar.apply(Owned<Operation>(new RemoveSlave(slave)))); Future<Registry> registry = registrar.recover(master); // Before waiting for the recovery to complete, invoke some // operations to ensure they do not fail. Future<bool> admit = registrar.apply( Owned<Operation>(new AdmitSlave(slave))); Future<bool> readmit = registrar.apply( Owned<Operation>(new ReadmitSlave(slave))); Future<bool> remove = registrar.apply( Owned<Operation>(new RemoveSlave(slave))); AWAIT_READY(registry); EXPECT_EQ(master, registry.get().master().info()); AWAIT_TRUE(admit); AWAIT_TRUE(readmit); AWAIT_TRUE(remove); } TEST_P(RegistrarTest, Admit) { Registrar registrar(flags, state); AWAIT_READY(registrar.recover(master)); AWAIT_TRUE(registrar.apply(Owned<Operation>(new AdmitSlave(slave)))); if (flags.registry_strict) { AWAIT_FALSE(registrar.apply(Owned<Operation>(new AdmitSlave(slave)))); } else { AWAIT_TRUE(registrar.apply(Owned<Operation>(new AdmitSlave(slave)))); } } TEST_P(RegistrarTest, Readmit) { Registrar registrar(flags, state); AWAIT_READY(registrar.recover(master)); SlaveInfo info1; info1.set_hostname("localhost"); SlaveID id1; id1.set_value("1"); info1.mutable_id()->CopyFrom(id1); SlaveID id2; id2.set_value("2"); SlaveInfo info2; info2.set_hostname("localhost"); info2.mutable_id()->CopyFrom(id2); AWAIT_TRUE(registrar.apply(Owned<Operation>(new AdmitSlave(info1)))); AWAIT_TRUE(registrar.apply(Owned<Operation>(new ReadmitSlave(info1)))); if (flags.registry_strict) { AWAIT_FALSE(registrar.apply(Owned<Operation>(new ReadmitSlave(info2)))); } else { AWAIT_TRUE(registrar.apply(Owned<Operation>(new ReadmitSlave(info2)))); } } TEST_P(RegistrarTest, Remove) { Registrar registrar(flags, state); AWAIT_READY(registrar.recover(master)); SlaveInfo info1; info1.set_hostname("localhost"); SlaveID id1; id1.set_value("1"); info1.mutable_id()->CopyFrom(id1); SlaveID id2; id2.set_value("2"); SlaveInfo info2; info2.set_hostname("localhost"); info2.mutable_id()->CopyFrom(id2); SlaveID id3; id3.set_value("3"); SlaveInfo info3; info3.set_hostname("localhost"); info3.mutable_id()->CopyFrom(id3); AWAIT_TRUE(registrar.apply(Owned<Operation>(new AdmitSlave(info1)))); AWAIT_TRUE(registrar.apply(Owned<Operation>(new AdmitSlave(info2)))); AWAIT_TRUE(registrar.apply(Owned<Operation>(new AdmitSlave(info3)))); AWAIT_TRUE(registrar.apply(Owned<Operation>(new RemoveSlave(info1)))); if (flags.registry_strict) { AWAIT_FALSE(registrar.apply(Owned<Operation>(new RemoveSlave(info1)))); } else { AWAIT_TRUE(registrar.apply(Owned<Operation>(new RemoveSlave(info1)))); } AWAIT_TRUE(registrar.apply(Owned<Operation>(new AdmitSlave(info1)))); AWAIT_TRUE(registrar.apply(Owned<Operation>(new RemoveSlave(info2)))); if (flags.registry_strict) { AWAIT_FALSE(registrar.apply(Owned<Operation>(new RemoveSlave(info2)))); } else { AWAIT_TRUE(registrar.apply(Owned<Operation>(new RemoveSlave(info2)))); } AWAIT_TRUE(registrar.apply(Owned<Operation>(new RemoveSlave(info3)))); if (flags.registry_strict) { AWAIT_FALSE(registrar.apply(Owned<Operation>(new RemoveSlave(info3)))); } else { AWAIT_TRUE(registrar.apply(Owned<Operation>(new RemoveSlave(info3)))); } } // NOTE: For the following tests, the state of the registrar can // only be viewed once per instantiation of the registrar. // To check the result of each operation, we must re-construct // the registrar, which is done by putting the code into scoped blocks. // TODO(josephw): Consider refactoring these maintenance operation tests // to use a helper function for each un-named scoped block. // For example: // MaintenanceTest(flags, state, [=](const Registry& registry) { // // Checks and operations. i.e.: // EXPECT_EQ(1, registry.get().schedules().size()); // }); // Adds maintenance schedules to the registry, one machine at a time. // Then removes machines from the schedule. TEST_P(RegistrarTest, UpdateMaintenanceSchedule) { // Machine definitions used in this test. MachineID machine1; machine1.set_ip("0.0.0.1"); MachineID machine2; machine2.set_hostname("2"); MachineID machine3; machine3.set_hostname("3"); machine3.set_ip("0.0.0.3"); Unavailability unavailability = createUnavailability(Clock::now()); { // Prepare the registrar. Registrar registrar(flags, state); AWAIT_READY(registrar.recover(master)); // Schedule one machine for maintenance. maintenance::Schedule schedule = createSchedule( {createWindow({machine1}, unavailability)}); AWAIT_READY(registrar.apply( Owned<Operation>(new UpdateSchedule(schedule)))); } { // Check that one schedule and one machine info was made. Registrar registrar(flags, state); Future<Registry> registry = registrar.recover(master); AWAIT_READY(registry); EXPECT_EQ(1, registry.get().schedules().size()); EXPECT_EQ(1, registry.get().schedules(0).windows().size()); EXPECT_EQ(1, registry.get().schedules(0).windows(0).machine_ids().size()); EXPECT_EQ(1, registry.get().machines().machines().size()); EXPECT_EQ( MachineInfo::DRAINING, registry.get().machines().machines(0).info().mode()); // Extend the schedule by one machine (in a different window). maintenance::Schedule schedule = createSchedule({ createWindow({machine1}, unavailability), createWindow({machine2}, unavailability)}); AWAIT_READY(registrar.apply( Owned<Operation>(new UpdateSchedule(schedule)))); } { // Check that both machines are part of maintenance. Registrar registrar(flags, state); Future<Registry> registry = registrar.recover(master); AWAIT_READY(registry); EXPECT_EQ(1, registry.get().schedules().size()); EXPECT_EQ(2, registry.get().schedules(0).windows().size()); EXPECT_EQ(1, registry.get().schedules(0).windows(0).machine_ids().size()); EXPECT_EQ(1, registry.get().schedules(0).windows(1).machine_ids().size()); EXPECT_EQ(2, registry.get().machines().machines().size()); EXPECT_EQ( MachineInfo::DRAINING, registry.get().machines().machines(1).info().mode()); // Extend a window by one machine. maintenance::Schedule schedule = createSchedule({ createWindow({machine1}, unavailability), createWindow({machine2, machine3}, unavailability)}); AWAIT_READY(registrar.apply( Owned<Operation>(new UpdateSchedule(schedule)))); } { // Check that all three machines are included. Registrar registrar(flags, state); Future<Registry> registry = registrar.recover(master); AWAIT_READY(registry); EXPECT_EQ(1, registry.get().schedules().size()); EXPECT_EQ(2, registry.get().schedules(0).windows().size()); EXPECT_EQ(1, registry.get().schedules(0).windows(0).machine_ids().size()); EXPECT_EQ(2, registry.get().schedules(0).windows(1).machine_ids().size()); EXPECT_EQ(3, registry.get().machines().machines().size()); EXPECT_EQ( MachineInfo::DRAINING, registry.get().machines().machines(2).info().mode()); // Rearrange the schedule into one window. maintenance::Schedule schedule = createSchedule( {createWindow({machine1, machine2, machine3}, unavailability)}); AWAIT_READY(registrar.apply( Owned<Operation>(new UpdateSchedule(schedule)))); } { // Check that the machine infos are unchanged, but the schedule is. Registrar registrar(flags, state); Future<Registry> registry = registrar.recover(master); AWAIT_READY(registry); EXPECT_EQ(1, registry.get().schedules().size()); EXPECT_EQ(1, registry.get().schedules(0).windows().size()); EXPECT_EQ(3, registry.get().schedules(0).windows(0).machine_ids().size()); EXPECT_EQ(3, registry.get().machines().machines().size()); EXPECT_EQ( MachineInfo::DRAINING, registry.get().machines().machines(0).info().mode()); EXPECT_EQ( MachineInfo::DRAINING, registry.get().machines().machines(1).info().mode()); EXPECT_EQ( MachineInfo::DRAINING, registry.get().machines().machines(2).info().mode()); // Delete one machine from the schedule. maintenance::Schedule schedule = createSchedule( {createWindow({machine2, machine3}, unavailability)}); AWAIT_READY(registrar.apply( Owned<Operation>(new UpdateSchedule(schedule)))); } { // Check that one machine info is removed. Registrar registrar(flags, state); Future<Registry> registry = registrar.recover(master); AWAIT_READY(registry); EXPECT_EQ(1, registry.get().schedules().size()); EXPECT_EQ(1, registry.get().schedules(0).windows().size()); EXPECT_EQ(2, registry.get().schedules(0).windows(0).machine_ids().size()); EXPECT_EQ(2, registry.get().machines().machines().size()); // Delete all machines from the schedule. maintenance::Schedule schedule; AWAIT_READY(registrar.apply( Owned<Operation>(new UpdateSchedule(schedule)))); } { // Check that all statuses are removed. Registrar registrar(flags, state); Future<Registry> registry = registrar.recover(master); AWAIT_READY(registry); EXPECT_EQ(1, registry.get().schedules().size()); EXPECT_EQ(0, registry.get().schedules(0).windows().size()); EXPECT_EQ(0, registry.get().machines().machines().size()); } } // Creates a schedule and properly starts maintenance. TEST_P(RegistrarTest, StartMaintenance) { // Machine definitions used in this test. MachineID machine1; machine1.set_ip("0.0.0.1"); MachineID machine2; machine2.set_hostname("2"); MachineID machine3; machine3.set_hostname("3"); machine3.set_ip("0.0.0.3"); Unavailability unavailability = createUnavailability(Clock::now()); { // Prepare the registrar. Registrar registrar(flags, state); AWAIT_READY(registrar.recover(master)); // Schedule two machines for maintenance. maintenance::Schedule schedule = createSchedule( {createWindow({machine1, machine2}, unavailability)}); AWAIT_READY(registrar.apply( Owned<Operation>(new UpdateSchedule(schedule)))); // Transition machine two into `DOWN` mode. RepeatedPtrField<MachineID> machines = createMachineList({machine2}); AWAIT_READY(registrar.apply( Owned<Operation>(new StartMaintenance(machines)))); } { // Check that machine two is down. Registrar registrar(flags, state); Future<Registry> registry = registrar.recover(master); AWAIT_READY(registry); EXPECT_EQ(2, registry.get().machines().machines().size()); EXPECT_EQ( MachineInfo::DRAINING, registry.get().machines().machines(0).info().mode()); EXPECT_EQ( MachineInfo::DOWN, registry.get().machines().machines(1).info().mode()); // Schedule three machines for maintenance. maintenance::Schedule schedule = createSchedule( {createWindow({machine1, machine2, machine3}, unavailability)}); AWAIT_READY(registrar.apply( Owned<Operation>(new UpdateSchedule(schedule)))); // Deactivate the two `DRAINING` machines. RepeatedPtrField<MachineID> machines = createMachineList({machine1, machine3}); AWAIT_READY(registrar.apply( Owned<Operation>(new StartMaintenance(machines)))); } { // Check that all machines are down. Registrar registrar(flags, state); Future<Registry> registry = registrar.recover(master); AWAIT_READY(registry); EXPECT_EQ(3, registry.get().machines().machines().size()); EXPECT_EQ( MachineInfo::DOWN, registry.get().machines().machines(0).info().mode()); EXPECT_EQ( MachineInfo::DOWN, registry.get().machines().machines(1).info().mode()); EXPECT_EQ( MachineInfo::DOWN, registry.get().machines().machines(2).info().mode()); } } // Creates a schedule and properly starts and stops maintenance. TEST_P(RegistrarTest, StopMaintenance) { // Machine definitions used in this test. MachineID machine1; machine1.set_ip("0.0.0.1"); MachineID machine2; machine2.set_hostname("2"); MachineID machine3; machine3.set_hostname("3"); machine3.set_ip("0.0.0.3"); Unavailability unavailability = createUnavailability(Clock::now()); { // Prepare the registrar. Registrar registrar(flags, state); AWAIT_READY(registrar.recover(master)); // Schdule three machines for maintenance. maintenance::Schedule schedule = createSchedule({ createWindow({machine1, machine2}, unavailability), createWindow({machine3}, unavailability)}); AWAIT_READY(registrar.apply( Owned<Operation>(new UpdateSchedule(schedule)))); // Transition machine three into `DOWN` mode. RepeatedPtrField<MachineID> machines = createMachineList({machine3}); AWAIT_READY(registrar.apply( Owned<Operation>(new StartMaintenance(machines)))); // Transition machine three into `UP` mode. AWAIT_READY(registrar.apply( Owned<Operation>(new StopMaintenance(machines)))); } { // Check that machine three and the window were removed. Registrar registrar(flags, state); Future<Registry> registry = registrar.recover(master); AWAIT_READY(registry); EXPECT_EQ(1, registry.get().schedules().size()); EXPECT_EQ(1, registry.get().schedules(0).windows().size()); EXPECT_EQ(2, registry.get().schedules(0).windows(0).machine_ids().size()); EXPECT_EQ(2, registry.get().machines().machines().size()); EXPECT_EQ( MachineInfo::DRAINING, registry.get().machines().machines(0).info().mode()); EXPECT_EQ( MachineInfo::DRAINING, registry.get().machines().machines(1).info().mode()); // Transition machine one and two into `DOWN` mode. RepeatedPtrField<MachineID> machines = createMachineList({machine1, machine2}); AWAIT_READY(registrar.apply( Owned<Operation>(new StartMaintenance(machines)))); // Transition all machines into `UP` mode. AWAIT_READY(registrar.apply( Owned<Operation>(new StopMaintenance(machines)))); } { // Check that the schedule is now empty. Registrar registrar(flags, state); Future<Registry> registry = registrar.recover(master); AWAIT_READY(registry); EXPECT_EQ(0, registry.get().schedules().size()); EXPECT_EQ(0, registry.get().machines().machines().size()); } } // Tests that adding and updating quotas in the registry works properly. TEST_P(RegistrarTest, UpdateQuota) { const string ROLE1 = "role1"; const string ROLE2 = "role2"; // NOTE: `quotaResources1` yields a collection with two `Resource` // objects once converted to `RepeatedPtrField`. Resources quotaResources1 = Resources::parse("cpus:1;mem:1024").get(); Resources quotaResources2 = Resources::parse("cpus:2").get(); // Prepare `QuotaInfo` protobufs used in the test. QuotaInfo quota1; quota1.set_role(ROLE1); quota1.mutable_guarantee()->CopyFrom(quotaResources1); Option<Error> validateError1 = quota::validation::quotaInfo(quota1); EXPECT_NONE(validateError1); QuotaInfo quota2; quota2.set_role(ROLE2); quota2.mutable_guarantee()->CopyFrom(quotaResources1); Option<Error> validateError2 = quota::validation::quotaInfo(quota2); EXPECT_NONE(validateError2); { // Prepare the registrar; see the comment above why we need to do this in // every scope. Registrar registrar(flags, state); Future<Registry> registry = registrar.recover(master); AWAIT_READY(registry); // Store quota for a role without quota. AWAIT_TRUE(registrar.apply(Owned<Operation>(new UpdateQuota(quota1)))); } { Registrar registrar(flags, state); Future<Registry> registry = registrar.recover(master); AWAIT_READY(registry); // Check that the recovered quota matches the one we stored. ASSERT_EQ(1, registry.get().quotas().size()); EXPECT_EQ(ROLE1, registry.get().quotas(0).info().role()); ASSERT_EQ(2, registry.get().quotas(0).info().guarantee().size()); Resources storedResources(registry.get().quotas(0).info().guarantee()); EXPECT_EQ(quotaResources1, storedResources); // Change quota for `ROLE1`. quota1.mutable_guarantee()->CopyFrom(quotaResources2); // Update the only stored quota. AWAIT_TRUE(registrar.apply(Owned<Operation>(new UpdateQuota(quota1)))); } { Registrar registrar(flags, state); Future<Registry> registry = registrar.recover(master); AWAIT_READY(registry); // Check that the recovered quota matches the one we updated. ASSERT_EQ(1, registry.get().quotas().size()); EXPECT_EQ(ROLE1, registry.get().quotas(0).info().role()); ASSERT_EQ(1, registry.get().quotas(0).info().guarantee().size()); Resources storedResources(registry.get().quotas(0).info().guarantee()); EXPECT_EQ(quotaResources2, storedResources); // Store one more quota for a role without quota. AWAIT_TRUE(registrar.apply(Owned<Operation>(new UpdateQuota(quota2)))); } { Registrar registrar(flags, state); Future<Registry> registry = registrar.recover(master); AWAIT_READY(registry); // Check that the recovered quotas match those we stored previously. // NOTE: We assume quota messages are stored in order they have // been added. // TODO(alexr): Consider removing dependency on the order. ASSERT_EQ(2, registry.get().quotas().size()); EXPECT_EQ(ROLE1, registry.get().quotas(0).info().role()); ASSERT_EQ(1, registry.get().quotas(0).info().guarantee().size()); EXPECT_EQ(ROLE2, registry.get().quotas(1).info().role()); ASSERT_EQ(2, registry.get().quotas(1).info().guarantee().size()); Resources storedResources(registry.get().quotas(1).info().guarantee()); EXPECT_EQ(quotaResources1, storedResources); // Change quota for `role2`. quota2.mutable_guarantee()->CopyFrom(quotaResources2); // Update quota for `role2` in presence of multiple quotas. AWAIT_TRUE(registrar.apply(Owned<Operation>(new UpdateQuota(quota2)))); } { Registrar registrar(flags, state); Future<Registry> registry = registrar.recover(master); AWAIT_READY(registry); // Check that the recovered quotas match those we stored and updated // previously. // NOTE: We assume quota messages are stored in order they have been // added and update does not change the order. // TODO(alexr): Consider removing dependency on the order. ASSERT_EQ(2, registry.get().quotas().size()); EXPECT_EQ(ROLE1, registry.get().quotas(0).info().role()); ASSERT_EQ(1, registry.get().quotas(0).info().guarantee().size()); Resources storedResources1(registry.get().quotas(0).info().guarantee()); EXPECT_EQ(quotaResources2, storedResources1); EXPECT_EQ(ROLE2, registry.get().quotas(1).info().role()); ASSERT_EQ(1, registry.get().quotas(1).info().guarantee().size()); Resources storedResources2(registry.get().quotas(1).info().guarantee()); EXPECT_EQ(quotaResources2, storedResources2); } } // Tests removing quotas from the registry. TEST_P(RegistrarTest, RemoveQuota) { const string ROLE1 = "role1"; const string ROLE2 = "role2"; { // Prepare the registrar; see the comment above why we need to do this in // every scope. Registrar registrar(flags, state); Future<Registry> registry = registrar.recover(master); AWAIT_READY(registry); // NOTE: `quotaResources` yields a collection with two `Resource` // objects once converted to `RepeatedPtrField`. Resources quotaResources1 = Resources::parse("cpus:1;mem:1024").get(); Resources quotaResources2 = Resources::parse("cpus:2").get(); // Prepare `QuotaInfo` protobufs. QuotaInfo quota1; quota1.set_role(ROLE1); quota1.mutable_guarantee()->CopyFrom(quotaResources1); Option<Error> validateError1 = quota::validation::quotaInfo(quota1); EXPECT_NONE(validateError1); QuotaInfo quota2; quota2.set_role(ROLE2); quota2.mutable_guarantee()->CopyFrom(quotaResources2); Option<Error> validateError2 = quota::validation::quotaInfo(quota2); EXPECT_NONE(validateError2); AWAIT_TRUE(registrar.apply(Owned<Operation>(new UpdateQuota(quota1)))); AWAIT_TRUE(registrar.apply(Owned<Operation>(new UpdateQuota(quota2)))); } { Registrar registrar(flags, state); Future<Registry> registry = registrar.recover(master); AWAIT_READY(registry); // Check that the recovered quotas match those we stored previously. // NOTE: We assume quota messages are stored in order they have been // added. // TODO(alexr): Consider removing dependency on the order. ASSERT_EQ(2, registry.get().quotas().size()); EXPECT_EQ(ROLE1, registry.get().quotas(0).info().role()); EXPECT_EQ(ROLE2, registry.get().quotas(1).info().role()); // Remove quota for `role2`. AWAIT_TRUE(registrar.apply(Owned<Operation>(new RemoveQuota(ROLE2)))); } { Registrar registrar(flags, state); Future<Registry> registry = registrar.recover(master); AWAIT_READY(registry); // Check that there is only one quota left in the registry. ASSERT_EQ(1, registry.get().quotas().size()); EXPECT_EQ(ROLE1, registry.get().quotas(0).info().role()); // Remove quota for `ROLE1`. AWAIT_TRUE(registrar.apply(Owned<Operation>(new RemoveQuota(ROLE1)))); } { Registrar registrar(flags, state); Future<Registry> registry = registrar.recover(master); AWAIT_READY(registry); // Check that there are no more quotas at this point. ASSERT_EQ(0, registry.get().quotas().size()); } } // Tests that updating weights in the registry works properly. TEST_P(RegistrarTest, UpdateWeights) { const string ROLE1 = "role1"; double WEIGHT1 = 2.0; double UPDATED_WEIGHT1 = 1.0; const string ROLE2 = "role2"; double WEIGHT2 = 3.5; { // Prepare the registrar. Registrar registrar(flags, state); Future<Registry> registry = registrar.recover(master); AWAIT_READY(registry); ASSERT_EQ(0, registry.get().weights_size()); // Store the weight for 'ROLE1' previously without weight. hashmap<string, double> weights; weights[ROLE1] = WEIGHT1; vector<WeightInfo> weightInfos = getWeightInfos(weights); AWAIT_TRUE(registrar.apply( Owned<Operation>(new UpdateWeights(weightInfos)))); } { Registrar registrar(flags, state); Future<Registry> registry = registrar.recover(master); AWAIT_READY(registry); // Check that the recovered weights matches the weights we stored // previously. ASSERT_EQ(1, registry.get().weights_size()); EXPECT_EQ(ROLE1, registry.get().weights(0).info().role()); ASSERT_EQ(WEIGHT1, registry.get().weights(0).info().weight()); // Change weight for 'ROLE1', and store the weight for 'ROLE2'. hashmap<string, double> weights; weights[ROLE1] = UPDATED_WEIGHT1; weights[ROLE2] = WEIGHT2; vector<WeightInfo> weightInfos = getWeightInfos(weights); AWAIT_TRUE(registrar.apply( Owned<Operation>(new UpdateWeights(weightInfos)))); } { Registrar registrar(flags, state); Future<Registry> registry = registrar.recover(master); AWAIT_READY(registry); // Check that the recovered weights matches the weights we updated // previously. ASSERT_EQ(2, registry.get().weights_size()); EXPECT_EQ(ROLE1, registry.get().weights(0).info().role()); ASSERT_EQ(UPDATED_WEIGHT1, registry.get().weights(0).info().weight()); EXPECT_EQ(ROLE2, registry.get().weights(1).info().role()); ASSERT_EQ(WEIGHT2, registry.get().weights(1).info().weight()); } } TEST_P(RegistrarTest, Bootstrap) { // Run 1 readmits a slave that is not present. { Registrar registrar(flags, state); AWAIT_READY(registrar.recover(master)); // If not strict, we should be allowed to readmit the slave. if (flags.registry_strict) { AWAIT_FALSE(registrar.apply(Owned<Operation>(new ReadmitSlave(slave)))); } else { AWAIT_TRUE(registrar.apply(Owned<Operation>(new ReadmitSlave(slave)))); } } // Run 2 should see the slave if not strict. { Registrar registrar(flags, state); Future<Registry> registry = registrar.recover(master); AWAIT_READY(registry); if (flags.registry_strict) { EXPECT_EQ(0, registry.get().slaves().slaves().size()); } else { ASSERT_EQ(1, registry.get().slaves().slaves().size()); EXPECT_EQ(slave, registry.get().slaves().slaves(0).info()); } } } class MockStorage : public Storage { public: MOCK_METHOD1(get, Future<Option<Entry> >(const string&)); MOCK_METHOD2(set, Future<bool>(const Entry&, const UUID&)); MOCK_METHOD1(expunge, Future<bool>(const Entry&)); MOCK_METHOD0(names, Future<std::set<string>>()); }; TEST_P(RegistrarTest, FetchTimeout) { Clock::pause(); MockStorage storage; State state(&storage); Future<Nothing> get; EXPECT_CALL(storage, get(_)) .WillOnce(DoAll(FutureSatisfy(&get), Return(Future<Option<Entry> >()))); Registrar registrar(flags, &state); Future<Registry> recover = registrar.recover(master); AWAIT_READY(get); Clock::advance(flags.registry_fetch_timeout); AWAIT_FAILED(recover); Clock::resume(); // Ensure the registrar fails subsequent operations. AWAIT_FAILED(registrar.apply(Owned<Operation>(new AdmitSlave(slave)))); } TEST_P(RegistrarTest, StoreTimeout) { Clock::pause(); MockStorage storage; State state(&storage); Registrar registrar(flags, &state); EXPECT_CALL(storage, get(_)) .WillOnce(Return(None())); Future<Nothing> set; EXPECT_CALL(storage, set(_, _)) .WillOnce(DoAll(FutureSatisfy(&set), Return(Future<bool>()))); Future<Registry> recover = registrar.recover(master); AWAIT_READY(set); Clock::advance(flags.registry_store_timeout); AWAIT_FAILED(recover); Clock::resume(); // Ensure the registrar fails subsequent operations. AWAIT_FAILED(registrar.apply(Owned<Operation>(new AdmitSlave(slave)))); } TEST_P(RegistrarTest, Abort) { MockStorage storage; State state(&storage); Registrar registrar(flags, &state); EXPECT_CALL(storage, get(_)) .WillOnce(Return(None())); EXPECT_CALL(storage, set(_, _)) .WillOnce(Return(Future<bool>(true))) // Recovery. .WillOnce(Return(Future<bool>::failed("failure"))) // Failure. .WillRepeatedly(Return(Future<bool>(true))); // Success. AWAIT_READY(registrar.recover(master)); // Storage failure. AWAIT_FAILED(registrar.apply(Owned<Operation>(new AdmitSlave(slave)))); // The registrar should now be aborted! AWAIT_FAILED(registrar.apply(Owned<Operation>(new AdmitSlave(slave)))); } // Tests that requests to the '/registry' endpoint are authenticated when HTTP // authentication is enabled. TEST_P(RegistrarTest, Authentication) { const string AUTHENTICATION_REALM = "realm"; Credentials credentials; credentials.add_credentials()->CopyFrom(DEFAULT_CREDENTIAL); Try<authentication::Authenticator*> authenticator = BasicAuthenticatorFactory::create(AUTHENTICATION_REALM, credentials); ASSERT_SOME(authenticator); AWAIT_READY(authentication::setAuthenticator( AUTHENTICATION_REALM, Owned<authentication::Authenticator>(authenticator.get()))); Registrar registrar(flags, state, AUTHENTICATION_REALM); // Requests without credentials should be rejected. Future<Response> response = process::http::get(registrar.pid(), "registry"); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Unauthorized({}).status, response) << response.get().body; Credential badCredential; badCredential.set_principal("bad-principal"); badCredential.set_secret("bad-secret"); // Requests with bad credentials should be rejected. response = process::http::get( registrar.pid(), "registry", None(), createBasicAuthHeaders(badCredential)); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Unauthorized({}).status, response) << response.get().body; // Requests with good credentials should be permitted. response = process::http::get( registrar.pid(), "registry", None(), createBasicAuthHeaders(DEFAULT_CREDENTIAL)); AWAIT_EXPECT_RESPONSE_STATUS_EQ(OK().status, response) << response.get().body; AWAIT_READY(authentication::unsetAuthenticator(AUTHENTICATION_REALM)); } class Registrar_BENCHMARK_Test : public RegistrarTestBase, public WithParamInterface<size_t> {}; // The Registrar benchmark tests are parameterized by the number of slaves. INSTANTIATE_TEST_CASE_P( SlaveCount, Registrar_BENCHMARK_Test, ::testing::Values(10000U, 20000U, 30000U, 50000U)); TEST_P(Registrar_BENCHMARK_Test, Performance) { Registrar registrar(flags, state); AWAIT_READY(registrar.recover(master)); vector<SlaveInfo> infos; Attributes attributes = Attributes::parse("foo:bar;baz:quux"); Resources resources = Resources::parse("cpus(*):1.0;mem(*):512;disk(*):2048").get(); size_t slaveCount = GetParam(); // Create slaves. for (size_t i = 0; i < slaveCount; ++i) { // Simulate real slave information. SlaveInfo info; info.set_hostname("localhost"); info.mutable_id()->set_value( string("201310101658-2280333834-5050-48574-") + stringify(i)); info.mutable_resources()->MergeFrom(resources); info.mutable_attributes()->MergeFrom(attributes); infos.push_back(info); } // Admit slaves. Stopwatch watch; watch.start(); Future<bool> result; foreach (const SlaveInfo& info, infos) { result = registrar.apply(Owned<Operation>(new AdmitSlave(info))); } AWAIT_READY_FOR(result, Minutes(5)); LOG(INFO) << "Admitted " << slaveCount << " agents in " << watch.elapsed(); // Shuffle the slaves so we are readmitting them in random order ( // same as in production). std::random_shuffle(infos.begin(), infos.end()); // Readmit slaves. watch.start(); foreach (const SlaveInfo& info, infos) { result = registrar.apply(Owned<Operation>(new ReadmitSlave(info))); } AWAIT_READY_FOR(result, Minutes(5)); LOG(INFO) << "Readmitted " << slaveCount << " agents in " << watch.elapsed(); // Recover slaves. Registrar registrar2(flags, state); watch.start(); MasterInfo info; info.set_id("master"); info.set_ip(10000000); info.set_port(5050); Future<Registry> registry = registrar2.recover(info); AWAIT_READY(registry); LOG(INFO) << "Recovered " << slaveCount << " agents (" << Bytes(registry.get().ByteSize()) << ") in " << watch.elapsed(); // Shuffle the slaves so we are removing them in random order (same // as in production). std::random_shuffle(infos.begin(), infos.end()); // Remove slaves. watch.start(); foreach (const SlaveInfo& info, infos) { result = registrar2.apply(Owned<Operation>(new RemoveSlave(info))); } AWAIT_READY_FOR(result, Minutes(5)); cout << "Removed " << slaveCount << " agents in " << watch.elapsed() << endl; } } // namespace tests { } // namespace internal { } // namespace mesos {
// Copyright 2010-2017 Google // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include <limits> #include <memory> #include <string> #include <unordered_map> #include <utility> #include <vector> #include "ortools/base/commandlineflags.h" #include "ortools/base/hash.h" #include "ortools/base/integral_types.h" #include "ortools/base/logging.h" #include "ortools/base/port.h" #include "ortools/base/stringprintf.h" #include "ortools/base/timer.h" #include "ortools/linear_solver/linear_solver.h" #if defined(USE_CBC) #undef PACKAGE #undef VERSION #include "CbcConfig.h" #include "CbcMessage.hpp" #include "CbcModel.hpp" #include "CoinModel.hpp" #include "OsiClpSolverInterface.hpp" // Heuristics namespace operations_research { class CBCInterface : public MPSolverInterface { public: // Constructor that takes a name for the underlying glpk solver. explicit CBCInterface(MPSolver* const solver); ~CBCInterface() override; // ----- Reset ----- void Reset() override; // Sets the optimization direction (min/max). void SetOptimizationDirection(bool maximize) override; // ----- Solve ----- // Solve the problem using the parameter values specified. MPSolver::ResultStatus Solve(const MPSolverParameters& param) override; // TODO(user): separate the solve from the model extraction. virtual void ExtractModel() {} // Query problem type. bool IsContinuous() const override { return false; } bool IsLP() const override { return false; } bool IsMIP() const override { return true; } // Modify bounds. void SetVariableBounds(int var_index, double lb, double ub) override; void SetVariableInteger(int var_index, bool integer) override; void SetConstraintBounds(int row_index, double lb, double ub) override; // Add constraint incrementally. void AddRowConstraint(MPConstraint* const ct) override; // Add variable incrementally. void AddVariable(MPVariable* const var) override; // Change a coefficient in a constraint. void SetCoefficient(MPConstraint* const constraint, const MPVariable* const variable, double new_value, double old_value) override { sync_status_ = MUST_RELOAD; } // Clear a constraint from all its terms. void ClearConstraint(MPConstraint* const constraint) override { sync_status_ = MUST_RELOAD; } // Change a coefficient in the linear objective. void SetObjectiveCoefficient(const MPVariable* const variable, double coefficient) override { sync_status_ = MUST_RELOAD; } // Change the constant term in the linear objective. void SetObjectiveOffset(double value) override { sync_status_ = MUST_RELOAD; } // Clear the objective from all its terms. void ClearObjective() override { sync_status_ = MUST_RELOAD; } // Number of simplex iterations int64 iterations() const override; // Number of branch-and-bound nodes. Only available for discrete problems. int64 nodes() const override; // Best objective bound. Only available for discrete problems. double best_objective_bound() const override; // Returns the basis status of a row. MPSolver::BasisStatus row_status(int constraint_index) const override { LOG(FATAL) << "Basis status only available for continuous problems"; return MPSolver::FREE; } // Returns the basis status of a column. MPSolver::BasisStatus column_status(int variable_index) const override { LOG(FATAL) << "Basis status only available for continuous problems"; return MPSolver::FREE; } void ExtractNewVariables() override {} void ExtractNewConstraints() override {} void ExtractObjective() override {} std::string SolverVersion() const override { return "Cbc " CBC_VERSION; } // TODO(user): Maybe we should expose the CbcModel build from osi_ // instead, but a new CbcModel is built every time Solve is called, // so it is not possible right now. void* underlying_solver() override { return reinterpret_cast<void*>(&osi_); } private: // Reset best objective bound to +/- infinity depending on the // optimization direction. void ResetBestObjectiveBound(); // Set all parameters in the underlying solver. void SetParameters(const MPSolverParameters& param) override; // Set each parameter in the underlying solver. void SetRelativeMipGap(double value) override; void SetPrimalTolerance(double value) override; void SetDualTolerance(double value) override; void SetPresolveMode(int value) override; void SetScalingMode(int value) override; void SetLpAlgorithm(int value) override; OsiClpSolverInterface osi_; // TODO(user): remove and query number of iterations directly from CbcModel int64 iterations_; int64 nodes_; double best_objective_bound_; // Special way to handle the relative MIP gap parameter. double relative_mip_gap_; }; // ----- Solver ----- // Creates a LP/MIP instance with the specified name and minimization objective. CBCInterface::CBCInterface(MPSolver* const solver) : MPSolverInterface(solver), iterations_(0), nodes_(0), best_objective_bound_(-std::numeric_limits<double>::infinity()), relative_mip_gap_(MPSolverParameters::kDefaultRelativeMipGap) { osi_.setStrParam(OsiProbName, solver_->name_); osi_.setObjSense(1); } CBCInterface::~CBCInterface() {} // Reset the solver. void CBCInterface::Reset() { osi_.reset(); osi_.setObjSense(maximize_ ? -1 : 1); osi_.setStrParam(OsiProbName, solver_->name_); ResetExtractionInformation(); } void CBCInterface::ResetBestObjectiveBound() { if (maximize_) { best_objective_bound_ = std::numeric_limits<double>::infinity(); } else { best_objective_bound_ = -std::numeric_limits<double>::infinity(); } } void CBCInterface::SetOptimizationDirection(bool maximize) { InvalidateSolutionSynchronization(); if (sync_status_ == MODEL_SYNCHRONIZED) { osi_.setObjSense(maximize ? -1 : 1); } else { sync_status_ = MUST_RELOAD; } } namespace { // CBC adds a "dummy" variable with index 0 to represent the objective offset. int MPSolverVarIndexToCbcVarIndex(int var_index) { return var_index + 1; } } // namespace void CBCInterface::SetVariableBounds(int var_index, double lb, double ub) { InvalidateSolutionSynchronization(); if (sync_status_ == MODEL_SYNCHRONIZED) { osi_.setColBounds(MPSolverVarIndexToCbcVarIndex(var_index), lb, ub); } else { sync_status_ = MUST_RELOAD; } } void CBCInterface::SetVariableInteger(int var_index, bool integer) { InvalidateSolutionSynchronization(); // TODO(user) : Check if this is actually a change. if (sync_status_ == MODEL_SYNCHRONIZED) { if (integer) { osi_.setInteger(MPSolverVarIndexToCbcVarIndex(var_index)); } else { osi_.setContinuous(MPSolverVarIndexToCbcVarIndex(var_index)); } } else { sync_status_ = MUST_RELOAD; } } void CBCInterface::SetConstraintBounds(int index, double lb, double ub) { InvalidateSolutionSynchronization(); if (sync_status_ == MODEL_SYNCHRONIZED) { osi_.setRowBounds(index, lb, ub); } else { sync_status_ = MUST_RELOAD; } } void CBCInterface::AddRowConstraint(MPConstraint* const ct) { sync_status_ = MUST_RELOAD; } void CBCInterface::AddVariable(MPVariable* const var) { sync_status_ = MUST_RELOAD; } // Solve the LP/MIP. Returns true only if the optimal solution was revealed. // Returns the status of the search. MPSolver::ResultStatus CBCInterface::Solve(const MPSolverParameters& param) { // CBC requires unique variable and constraint names. By using Lookup*, we // generate variable and constraint indices and ensure the duplicate name // crash will happen here with a readable error message. if (!solver_->variables_.empty()) { solver_->LookupVariableOrNull(solver_->variables_[0]->name()); } if (!solver_->constraints_.empty()) { solver_->LookupConstraintOrNull(solver_->constraints_[0]->name()); } WallTimer timer; timer.Start(); // Note that CBC does not provide any incrementality. if (param.GetIntegerParam(MPSolverParameters::INCREMENTALITY) == MPSolverParameters::INCREMENTALITY_OFF) { Reset(); } // Special case if the model is empty since CBC is not able to // handle this special case by itself. if (solver_->variables_.empty() && solver_->constraints_.empty()) { sync_status_ = SOLUTION_SYNCHRONIZED; result_status_ = MPSolver::OPTIMAL; objective_value_ = solver_->Objective().offset(); best_objective_bound_ = solver_->Objective().offset(); return result_status_; } // Finish preparing the problem. // Define variables. switch (sync_status_) { case MUST_RELOAD: { Reset(); CoinModel build; // Create dummy variable for objective offset. build.addColumn(0, nullptr, nullptr, 1.0, 1.0, solver_->Objective().offset(), "dummy", false); const int nb_vars = solver_->variables_.size(); for (int i = 0; i < nb_vars; ++i) { MPVariable* const var = solver_->variables_[i]; set_variable_as_extracted(i, true); const double obj_coeff = solver_->Objective().GetCoefficient(var); if (var->name().empty()) { build.addColumn(0, nullptr, nullptr, var->lb(), var->ub(), obj_coeff, nullptr, var->integer()); } else { build.addColumn(0, nullptr, nullptr, var->lb(), var->ub(), obj_coeff, var->name().c_str(), var->integer()); } } // Define constraints. int max_row_length = 0; for (int i = 0; i < solver_->constraints_.size(); ++i) { MPConstraint* const ct = solver_->constraints_[i]; set_constraint_as_extracted(i, true); if (ct->coefficients_.size() > max_row_length) { max_row_length = ct->coefficients_.size(); } } std::unique_ptr<int[]> indices(new int[max_row_length]); std::unique_ptr<double[]> coefs(new double[max_row_length]); for (int i = 0; i < solver_->constraints_.size(); ++i) { MPConstraint* const ct = solver_->constraints_[i]; const int size = ct->coefficients_.size(); int j = 0; for (const auto& entry : ct->coefficients_) { const int index = MPSolverVarIndexToCbcVarIndex(entry.first->index()); indices[j] = index; coefs[j] = entry.second; j++; } if (ct->name().empty()) { build.addRow(size, indices.get(), coefs.get(), ct->lb(), ct->ub()); } else { build.addRow(size, indices.get(), coefs.get(), ct->lb(), ct->ub(), ct->name().c_str()); } } osi_.loadFromCoinModel(build); break; } case MODEL_SYNCHRONIZED: { break; } case SOLUTION_SYNCHRONIZED: { break; } } // Changing optimization direction through OSI so that the model file // (written through OSI) has the correct optimization duration. osi_.setObjSense(maximize_ ? -1 : 1); sync_status_ = MODEL_SYNCHRONIZED; VLOG(1) << absl::StrFormat("Model built in %.3f seconds.", timer.Get()); ResetBestObjectiveBound(); // Solve CbcModel model(osi_); // Set log level. CoinMessageHandler message_handler; model.passInMessageHandler(&message_handler); if (quiet_) { message_handler.setLogLevel(0, 0); // Coin messages message_handler.setLogLevel(1, 0); // Clp messages message_handler.setLogLevel(2, 0); // Presolve messages message_handler.setLogLevel(3, 0); // Cgl messages } else { message_handler.setLogLevel(0, 1); // Coin messages message_handler.setLogLevel(1, 0); // Clp messages message_handler.setLogLevel(2, 0); // Presolve messages message_handler.setLogLevel(3, 1); // Cgl messages } // Time limit. if (solver_->time_limit() != 0) { VLOG(1) << "Setting time limit = " << solver_->time_limit() << " ms."; model.setMaximumSeconds(solver_->time_limit_in_secs()); } // And solve. timer.Restart(); // Here we use the default function from the command-line CBC solver. // This enables to activate all the features and get the same performance // as the CBC stand-alone executable. The syntax is ugly, however. SetParameters(param); // Always turn presolve on (it's the CBC default and it consistently // improves performance). model.setTypePresolve(0); // Special way to set the relative MIP gap parameter as it cannot be set // through callCbc. model.setAllowableFractionGap(relative_mip_gap_); // NOTE: Trailing space is required to avoid buffer overflow in cbc. int return_status = callCbc("-solve ", model); const int kBadReturnStatus = 777; CHECK_NE(kBadReturnStatus, return_status); // Should never happen according // to the CBC source VLOG(1) << absl::StrFormat("Solved in %.3f seconds.", timer.Get()); // Check the status: optimal, infeasible, etc. int tmp_status = model.status(); VLOG(1) << "cbc result status: " << tmp_status; /* Final status of problem (info from cbc/.../CbcSolver.cpp, See http://cs?q="cbc+status"+file:CbcSolver.cpp) Some of these can be found out by is...... functions -1 before branchAndBound 0 finished - check isProvenOptimal or isProvenInfeasible to see if solution found (or check value of best solution) 1 stopped - on maxnodes, maxsols, maxtime 2 difficulties so run was abandoned (5 event user programmed event occurred) */ switch (tmp_status) { case 0: // Order of tests counts; if model.isContinuousUnbounded() returns true, // then so does model.isProvenInfeasible()! if (model.isProvenOptimal()) { result_status_ = MPSolver::OPTIMAL; } else if (model.isContinuousUnbounded()) { result_status_ = MPSolver::UNBOUNDED; } else if (model.isProvenInfeasible()) { result_status_ = MPSolver::INFEASIBLE; } else { LOG(FATAL) << "Unknown solver status! Secondary status: " << model.secondaryStatus(); } break; case 1: if (model.bestSolution() != nullptr) { result_status_ = MPSolver::FEASIBLE; } else { result_status_ = MPSolver::NOT_SOLVED; } break; default: result_status_ = MPSolver::ABNORMAL; break; } if (result_status_ == MPSolver::OPTIMAL || result_status_ == MPSolver::FEASIBLE) { // Get the results objective_value_ = model.getObjValue(); VLOG(1) << "objective=" << objective_value_; const double* const values = model.bestSolution(); if (values != nullptr) { // if optimal or feasible solution is found. for (int i = 0; i < solver_->variables_.size(); ++i) { MPVariable* const var = solver_->variables_[i]; const int var_index = MPSolverVarIndexToCbcVarIndex(var->index()); const double val = values[var_index]; var->set_solution_value(val); VLOG(3) << var->name() << "=" << val; } } else { VLOG(1) << "No feasible solution found."; } } iterations_ = model.getIterationCount(); nodes_ = model.getNodeCount(); best_objective_bound_ = model.getBestPossibleObjValue(); VLOG(1) << "best objective bound=" << best_objective_bound_; sync_status_ = SOLUTION_SYNCHRONIZED; return result_status_; } // ------ Query statistics on the solution and the solve ------ int64 CBCInterface::iterations() const { if (!CheckSolutionIsSynchronized()) return kUnknownNumberOfNodes; return iterations_; } int64 CBCInterface::nodes() const { if (!CheckSolutionIsSynchronized()) return kUnknownNumberOfIterations; return nodes_; } double CBCInterface::best_objective_bound() const { if (!CheckSolutionIsSynchronized() || !CheckBestObjectiveBoundExists()) { return trivial_worst_objective_bound(); } return best_objective_bound_; } // ----- Parameters ----- // The support for parameters in CBC is intentionally sparse. There is // a memory leak in callCbc that prevents to pass parameters through // it, so handling parameters would require an comprehensive rewrite // of the code. I will improve the parameter support only if there is // a relevant use case. void CBCInterface::SetParameters(const MPSolverParameters& param) { SetCommonParameters(param); SetMIPParameters(param); } void CBCInterface::SetRelativeMipGap(double value) { relative_mip_gap_ = value; } void CBCInterface::SetPrimalTolerance(double value) { // Skip the warning for the default value as it coincides with // the default value in CBC. if (value != MPSolverParameters::kDefaultPrimalTolerance) { SetUnsupportedDoubleParam(MPSolverParameters::PRIMAL_TOLERANCE); } } void CBCInterface::SetDualTolerance(double value) { // Skip the warning for the default value as it coincides with // the default value in CBC. if (value != MPSolverParameters::kDefaultDualTolerance) { SetUnsupportedDoubleParam(MPSolverParameters::DUAL_TOLERANCE); } } void CBCInterface::SetPresolveMode(int value) { switch (value) { case MPSolverParameters::PRESOLVE_ON: { // CBC presolve is always on. break; } default: { SetUnsupportedIntegerParam(MPSolverParameters::PRESOLVE); } } } void CBCInterface::SetScalingMode(int value) { SetUnsupportedIntegerParam(MPSolverParameters::SCALING); } void CBCInterface::SetLpAlgorithm(int value) { SetUnsupportedIntegerParam(MPSolverParameters::LP_ALGORITHM); } MPSolverInterface* BuildCBCInterface(MPSolver* const solver) { return new CBCInterface(solver); } } // namespace operations_research #endif // #if defined(USE_CBC)
// Copyright © 2017-2019 Trust Wallet. // // This file is part of Trust. The full Trust copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. #include "../PrivateKey.h" #include "../PublicKey.h" #include <TrezorCrypto/ecdsa.h> #include <TrezorCrypto/rand.h> #include <TrezorCrypto/secp256k1.h> #include <TrustWalletCore/TWPrivateKey.h> #include <exception> using namespace TW; struct TWPrivateKey *TWPrivateKeyCreate() { std::array<uint8_t, PrivateKey::size> bytes = {0}; random_buffer(bytes.data(), PrivateKey::size); if (!PrivateKey::isValid(bytes)) { // Under no circumstance return an invalid private key. We'd rather // crash. This also captures cases where the random generator fails // since we initialize the array to zeros, which is an invalid private // key. std::terminate(); } return new TWPrivateKey{ PrivateKey(std::move(bytes)) }; } struct TWPrivateKey *_Nullable TWPrivateKeyCreateWithData(TWData *_Nonnull data) { if (!TWPrivateKeyIsValid(data)) { return nullptr; } std::array<uint8_t, PrivateKey::size> bytes; TWDataCopyBytes(data, 0, TWPrivateKeySize, bytes.data()); return new TWPrivateKey{ PrivateKey(std::move(bytes)) }; } struct TWPrivateKey *_Nullable TWPrivateKeyCreateCopy(struct TWPrivateKey *_Nonnull key) { return new TWPrivateKey{ PrivateKey(key->impl.bytes) }; } void TWPrivateKeyDelete(struct TWPrivateKey *_Nonnull pk) { if (pk == nullptr) return; delete pk; } bool TWPrivateKeyIsValid(TWData *_Nonnull data) { // Check length if (TWDataSize(data) != TWPrivateKeySize) { return false; } // Check for zero address for (size_t i = 0; i < TWPrivateKeySize; i += 1) { if (TWDataGet(data, i) != 0) { return true; } } return false; } TWData *TWPrivateKeyData(struct TWPrivateKey *_Nonnull pk) { return TWDataCreateWithBytes(pk->impl.bytes.data(), TWPrivateKeySize); } struct TWPublicKey *_Nonnull TWPrivateKeyGetPublicKeyNist256p1(struct TWPrivateKey *_Nonnull pk) { return new TWPublicKey{ pk->impl.getPublicKey(TWPublicKeyTypeNIST256p1) }; } struct TWPublicKey *_Nonnull TWPrivateKeyGetPublicKeySecp256k1(struct TWPrivateKey *_Nonnull pk, bool compressed) { if (compressed) { return new TWPublicKey{ pk->impl.getPublicKey(TWPublicKeyTypeSECP256k1) }; } else { return new TWPublicKey{ pk->impl.getPublicKey(TWPublicKeyTypeSECP256k1Extended) }; } } struct TWPublicKey *_Nonnull TWPrivateKeyGetPublicKeyEd25519(struct TWPrivateKey *_Nonnull pk) { return new TWPublicKey{ pk->impl.getPublicKey(TWPublicKeyTypeED25519) }; } struct TWPublicKey *_Nonnull TWPrivateKeyGetPublicKeyEd25519Blake2b(struct TWPrivateKey *_Nonnull pk) { return new TWPublicKey{ pk->impl.getPublicKey(TWPublicKeyTypeED25519Blake2b) }; } TWData *TWPrivateKeySign(struct TWPrivateKey *_Nonnull pk, TWData *_Nonnull digest, enum TWCurve curve) { auto& d = *reinterpret_cast<const Data*>(digest); auto result = pk->impl.sign(d, curve); if (result.empty()) { return nullptr; } else { return TWDataCreateWithBytes(result.data(), result.size()); } } TWData *TWPrivateKeySignAsDER(struct TWPrivateKey *_Nonnull pk, TWData *_Nonnull digest, enum TWCurve curve) { auto& d = *reinterpret_cast<const Data*>(digest); auto result = pk->impl.signAsDER(d, curve); if (result.empty()) { return nullptr; } else { return TWDataCreateWithBytes(result.data(), result.size()); } } TWData *TWPrivateKeySignSchnorr(struct TWPrivateKey *_Nonnull pk, TWData *_Nonnull message, enum TWCurve curve) { auto& msg = *reinterpret_cast<const Data*>(message); auto result = pk->impl.signSchnorr(msg, curve); if (result.empty()) { return nullptr; } else { return TWDataCreateWithBytes(result.data(), result.size()); } }
/* * vk_shader.cpp - vulkan shader module * * Copyright (c) 2018 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: Wind Yuan <feng.yuan@intel.com> */ #include "vk_shader.h" #include "vk_device.h" #include "file.h" namespace XCam { VKShader::VKShader (SmartPtr<VKDevice> dev, VkShaderModule id, const char *name) : _device (dev) , _shader_id (id) , _shader_stage (VK_SHADER_STAGE_COMPUTE_BIT) { XCAM_IS_VALID_VK_ID (id); xcam_mem_clear (_name); if (name) strncpy (_name, name, XCAM_VK_NAME_LENGTH - 1); strncpy (_func_name, "main", XCAM_VK_NAME_LENGTH - 1); } VKShader::~VKShader () { if (XCAM_IS_VALID_VK_ID (_shader_id)) _device->destroy_shader_id (_shader_id); } void VKShader::set_func_name (const char *name) { XCAM_ASSERT (name); strncpy (_func_name, name, XCAM_VK_NAME_LENGTH - 1); } void VKShader::set_name (const char *name) { XCAM_ASSERT (name); strncpy (_name, name, XCAM_VK_NAME_LENGTH - 1); } }
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/gpu/fusion_merger.h" #include <algorithm> #include <vector> #include "absl/algorithm/container.h" #include "absl/strings/str_join.h" #include "tensorflow/compiler/xla/service/gpu/gpu_fusible.h" #include "tensorflow/compiler/xla/service/gpu/instruction_fusion.h" #include "tensorflow/compiler/xla/service/hlo_cost_analysis.h" #include "tensorflow/compiler/xla/service/llvm_ir/fused_ir_emitter.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/util.h" #include "tensorflow/core/lib/core/errors.h" namespace xla { namespace gpu { namespace { // Traverses users of tuple shape, adding leaf instructions to 'instructions'. void MaybeResolveTupleElements(HloInstruction* instruction, std::vector<HloInstruction*>* instructions) { if (instruction->shape().IsTuple()) { for (auto tuple_user : instruction->users()) { MaybeResolveTupleElements(tuple_user, instructions); } } else { instructions->push_back(instruction); } } // Returns the bytes read by fusion parameter 'param', by returning the byte // size of 'param' shape (or the cumulative byte sizes of all leaf tuple // elements if 'param' is tuple-shaped). // // In the special case where all users of 'param' (or all users of a leaf // tuple element if 'param' is tuple-shaped) are Slice instructions, the size // of each slice instruction is accumulated instead, to give a more accurate // value for bytes read. double CalculateBytesReadByFusionParameter(HloInstruction* param) { CHECK_EQ(HloOpcode::kParameter, param->opcode()); // Adds all leaf tuple elements to 'instructions' if 'param' is tuple-shaped. // Adds 'param' to 'instructions' otherwise. std::vector<HloInstruction*> instructions; MaybeResolveTupleElements(param, &instructions); // Iterate through 'instructions' accumulating byte sizes of each instruction // shape. For each 'instruction' in 'instructions', if all users of // 'instruction' are Slice instructions, accumulates the byte sizes of each // Slice for a more accurate estimate of bytes read. double bytes = 0.0; for (auto& instruction : instructions) { if (absl::c_all_of( instruction->users(), [](const HloInstruction* instruction) { return instruction->opcode() == HloOpcode::kSlice || instruction->opcode() == HloOpcode::kDynamicSlice; })) { // All users are slice: accumulate bytes of all user slice instructions. for (auto& user : instruction->users()) { bytes += ShapeUtil::ByteSizeOf(user->shape()); } } else { // Some users are not slice: accumulate full size of 'instruction'. bytes += ShapeUtil::ByteSizeOf(instruction->shape()); } } return bytes; } // Returns the bytes read by all fusion parameters of instruction 'fusion'. double CalculateBytesReadByFusionInstruction(HloInstruction* fusion) { double bytes = 0.0; for (auto* fused_instruction : fusion->fused_instructions()) { if (fused_instruction->opcode() != HloOpcode::kParameter) { continue; } bytes += CalculateBytesReadByFusionParameter(fused_instruction); } return bytes; } // Returns bytes transferred by instruction 'fusion', including the bytes // that would be read by all users. double GetCurrentBytesTransferred(HloInstruction* fusion) { CHECK_EQ(HloOpcode::kFusion, fusion->opcode()); const double bytes_read = CalculateBytesReadByFusionInstruction(fusion); double bytes_written = 0; if (fusion->IsMultiOutputFusion()) { for (auto& operand : fusion->fused_expression_root()->operands()) { bytes_written += ShapeUtil::ByteSizeOf(operand->shape()); } } else { bytes_written = ShapeUtil::ByteSizeOf(fusion->fused_expression_root()->shape()); } // Current bytes transferred (ignoring non 'fusion' user operands) is bytes // read and written by 'fusion', plus reads of size 'bytes_written' for each // user. return bytes_read + bytes_written * (fusion->user_count() + 1); } // Returns bytes transferred if 'fusion' were to be merged into its users. double GetMergedBytesTransferred(HloInstruction* fusion) { CHECK_EQ(HloOpcode::kFusion, fusion->opcode()); return CalculateBytesReadByFusionInstruction(fusion) * fusion->user_count(); } } // anonymous namespace // FusionInstructionMerger visits all fusion instructions in 'computation' // in post order, attempting to merge each into all of its users. // Accumulates and reports stats on successful/failed merge attempts. class FusionInstructionMerger { public: explicit FusionInstructionMerger(HloComputation* computation) : computation_(computation) {} Status Run(); bool changed() const { return changed_; } private: Status HandleFusion(HloInstruction* fusion); HloComputation* computation_; bool changed_ = false; // Fusion instruction merge stats. int total_visited_ = 0; int total_merged_ = 0; int num_fail_no_users_ = 0; int num_fail_not_loop_fusion_ = 0; int num_fail_merge_all_users_ = 0; int num_fail_expensive_fused_instruction_ = 0; int num_fail_net_bytes_transferred_ratio_ = 0; int num_fail_inefficient_fusion_emitter_ = 0; int num_fail_fusion_too_large_ = 0; TF_DISALLOW_COPY_AND_ASSIGN(FusionInstructionMerger); }; Status FusionInstructionMerger::Run() { for (auto* instruction : computation_->MakeInstructionPostOrder()) { if (instruction->opcode() == HloOpcode::kFusion) { TF_RETURN_IF_ERROR(HandleFusion(instruction)); } } VLOG(1) << "FusionInstructionMerger EXIT" << " computation: " << computation_->name() << " total_visited: " << total_visited_ << " total_merged: " << total_merged_ << " merge failures { " << " no_users: " << num_fail_no_users_ << " not_loop_fusion: " << num_fail_not_loop_fusion_ << " merge_all_users: " << num_fail_merge_all_users_ << " expensive_instruction: " << num_fail_expensive_fused_instruction_ << " net_bytes_transferred: " << num_fail_net_bytes_transferred_ratio_ << " inefficient_fusion_emitter: " << num_fail_inefficient_fusion_emitter_ << " fusion_too_large: " << num_fail_fusion_too_large_ << " }"; return Status::OK(); } Status FusionInstructionMerger::HandleFusion(HloInstruction* fusion) { ++total_visited_; // Skip 'fusion' instruction if there are no users into which we can merge. if (fusion->users().empty()) { VLOG(3) << "Not merging " << fusion->name() << ": Has no users."; ++num_fail_no_users_; return Status::OK(); } // Skip 'fusion' instruction if it is not a loop fusion. Library fusion // instructions match specific patterns, so they shouldn't be further fused. // Input fusion instructions need to be rooted at a particular HLO (e.g. // kReduce), so they shouldn't be further fused either. if (!fusion->IsLoopFusion()) { VLOG(3) << "Not merging " << fusion->name() << ": Is not loop fusion."; ++num_fail_not_loop_fusion_; return Status::OK(); } // Skip 'fusion' instruction if we cannot merge into all of its users. // Merging into all users enables the removal of 'fusion' from the // computation. if (!absl::c_all_of(fusion->users(), [&](const HloInstruction* user) { return user->opcode() == HloOpcode::kFusion && IsProducerConsumerFusible(*fusion, *user); })) { VLOG(3) << "Not merging " << fusion->name() << ": Some of its users are not loop/input fusion kernels."; ++num_fail_merge_all_users_; return Status::OK(); } // Skip 'fusion' instruction if any of its fused instructions are expensive. // This is done to avoid the duplication of expensive instructions, which // would occur if 'fusion' were merged into multiple users. // // If 'fusion' has just one user, then an earlier fusion pass chose not to // fuse this producer/comsumer pair (likely because of expensive instruction // re-use by the consumer), and so we honor that choice here as well. if (absl::c_any_of(fusion->fused_instructions(), [](const HloInstruction* instruction) { return instruction->opcode() != HloOpcode::kParameter && GpuInstructionFusion::IsExpensive(*instruction); })) { VLOG(3) << "Not merging " << fusion->name() << ": Contains one or more expensive instructions."; ++num_fail_expensive_fused_instruction_; return Status::OK(); } // Skip 'fusion' instruction if merging it into all users would result in a // net increase in bytes transferred (currently allowing the net bytes // transferred to be exceeded up to ~10% in exhange for eliminating the // overhead from a GPU kernel launch). const double current_bytes_transferred = GetCurrentBytesTransferred(fusion); const double merged_bytes_transferred = GetMergedBytesTransferred(fusion); const double merged_to_current_bytes_ratio = merged_bytes_transferred / std::max(1.0, current_bytes_transferred); if (merged_to_current_bytes_ratio > 1.10) { VLOG(3) << "Not merging " << fusion->name() << ": merged-to-current-bytes-ratio of " << merged_to_current_bytes_ratio << " is not favorable."; ++num_fail_net_bytes_transferred_ratio_; return Status::OK(); } // Skip 'fusion' instruction if merging it into at least one of the users // would cause too much code duplication because of inefficiencies in the // fusion emitter. // TODO(b/119692968): Remove this once the fusion emitter can handle arbitrary // fusion nodes. if (absl::c_any_of(fusion->users(), [fusion](const HloInstruction* user) { return FusedIrEmitter::IsFusedIrEmitterInefficient(/*consumer=*/user, /*producer=*/fusion); })) { VLOG(3) << "Not merging " << fusion->name() << ": Contains one or more users where fusing would cause " "inefficiencies in the fusion emitter."; ++num_fail_inefficient_fusion_emitter_; return Status::OK(); } // Skip 'fusion' instruction if merging it into at least one of the users // would make the fusion too big. if (absl::c_any_of(fusion->users(), [fusion](const HloInstruction* user) { return FusionWouldBeTooLarge(*fusion, *user); })) { VLOG(3) << "Not merging " << fusion->name() << ": Contains one or more users where fusing would cause " "the fusion to have too many parameters."; ++num_fail_fusion_too_large_; return Status::OK(); } // Merge fused instructions from 'fusion' into each user. std::vector<HloInstruction*> users = fusion->users(); for (HloInstruction* user : users) { user->MergeFusionInstruction(fusion); changed_ = true; } ++total_merged_; VLOG(2) << "Merged fusion instruction: " << fusion->name() << " merged_to_current_bytes_ratio: " << merged_to_current_bytes_ratio << " into users { " << absl::StrJoin(users, ", ", [](string* out, HloInstruction* user) { absl::StrAppend(out, user->name()); }) << " }"; // Remove 'fusion' instruction. CHECK_EQ(0, fusion->user_count()); return computation_->RemoveInstruction(fusion); } StatusOr<bool> FusionMerger::Run(HloModule* module) { bool changed = false; VLOG(2) << "FusionMerger for module: " << module->name(); for (auto* computation : module->MakeNonfusionComputations()) { VLOG(1) << "Before running FusionInstructionMerger for computation: " << computation->name(); XLA_VLOG_LINES(3, computation->ToString()); FusionInstructionMerger fusion_merger(computation); TF_RETURN_IF_ERROR(fusion_merger.Run()); changed |= fusion_merger.changed(); VLOG(1) << "After running FusionInstructionMerger for computation: " << computation->name() << " changed: " << changed; XLA_VLOG_LINES(3, computation->ToString()); } return changed; } } // namespace gpu } // namespace xla
/* Given an array A of integers and another non negative integer k, find if there exists 2 indices i and j such that A[i] - A[j] = k, i != j. Example : Input : A : [1 5 3] k : 2 Output : 1 as 3 - 1 = 2 Return 0 / 1 for this problem. See Expected Output https://www.interviewbit.com/problems/diffk-ii/ */ int Solution::diffPossible(const vector<int> &A, int B) { vector<int> input(A); sort(input.begin(), input.end()); auto p = 0, q = 0; auto size = input.size(); while (q < size) { if (p == q) ++q; else if (input[q]-input[p] == B && p!=q) return 1; else if (input[q]-input[p] < B) ++q; else if (input[q]-input[p] > B) ++p; } return 0; }
//===--- SILMem2Reg.cpp - Promotes AllocStacks to registers ---------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This pass promotes AllocStack instructions into virtual register // references. It only handles load, store and deallocation // instructions. The algorithm is based on: // // Sreedhar and Gao. A linear time algorithm for placing phi-nodes. POPL '95. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sil-mem2reg" #include "swift/AST/DiagnosticsSIL.h" #include "swift/Basic/GraphNodeWorklist.h" #include "swift/SIL/BasicBlockDatastructures.h" #include "swift/SIL/Dominance.h" #include "swift/SIL/Projection.h" #include "swift/SIL/SILBuilder.h" #include "swift/SIL/SILFunction.h" #include "swift/SIL/SILInstruction.h" #include "swift/SIL/SILModule.h" #include "swift/SIL/TypeLowering.h" #include "swift/SILOptimizer/Analysis/DominanceAnalysis.h" #include "swift/SILOptimizer/PassManager/Passes.h" #include "swift/SILOptimizer/PassManager/Transforms.h" #include "swift/SILOptimizer/Utils/CFGOptUtils.h" #include "swift/SILOptimizer/Utils/InstOptUtils.h" #include "swift/SILOptimizer/Utils/OwnershipOptUtils.h" #include "swift/SILOptimizer/Utils/ScopeOptUtils.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/Support/Debug.h" #include <algorithm> #include <queue> using namespace swift; using namespace swift::siloptimizer; STATISTIC(NumAllocStackFound, "Number of AllocStack found"); STATISTIC(NumAllocStackCaptured, "Number of AllocStack captured"); STATISTIC(NumInstRemoved, "Number of Instructions removed"); static bool shouldAddLexicalLifetime(AllocStackInst *asi); namespace { using DomTreeNode = llvm::DomTreeNodeBase<SILBasicBlock>; using DomTreeLevelMap = llvm::DenseMap<DomTreeNode *, unsigned>; /// A transient structure containing the values that are accessible in some /// context: coming into a block, going out of the block, or within a block /// (during promoteAllocationInBlock and removeSingleBlockAllocation). /// /// At block boundaries, these are phi arguments or initializationPoints. As we /// iterate over a block, a way to keep track of the current (running) value /// within a block. struct LiveValues { SILValue stored = SILValue(); SILValue borrow = SILValue(); SILValue copy = SILValue(); /// Create an instance of the minimum values required to replace a usage of an /// AllocStackInst. It consists of only one value. /// /// Whether the one value occupies the stored or the copy field depends on /// whether the alloc_stack is lexical. If it is lexical, then usages of the /// asi will be replaced with usages of the copy field; otherwise, those /// usages will be replaced with usages of the stored field. The /// implementation constructs an instance to match those requirements. static LiveValues toReplace(AllocStackInst *asi, SILValue replacement) { if (shouldAddLexicalLifetime(asi)) return {SILValue(), SILValue(), replacement}; return {replacement, SILValue(), SILValue()}; }; /// The value with which usages of the provided AllocStackInst should be /// replaced. /// /// For lexical AllocStackInsts, that is the copy made of the borrowed value. /// For those that are non-lexical, that is the value that was stored into the /// storage. SILValue replacement(AllocStackInst *asi) { return shouldAddLexicalLifetime(asi) ? copy : stored; }; }; /// A transient structure used only by promoteAllocationInBlock and /// removeSingleBlockAllocation. /// /// A pair of a CFG-position-relative value T and a boolean indicating whether /// the alloc_stack's storage is valid at the position where that value exists. template <typename T> struct StorageStateTracking { /// The value which exists at some CFG position. T value; /// Whether the stack storage is initialized at that position. bool isStorageValid; }; } // anonymous namespace //===----------------------------------------------------------------------===// // Utilities //===----------------------------------------------------------------------===// /// Make the specified instruction cease to be a user of its operands and add it /// to the list of instructions to delete. /// /// This both (1) removes the specified instruction from the list of users of /// its operands, avoiding disrupting logic that examines those users and (2) /// keeps the specified instruction in place, allowing it to be used for /// insertion until instructionsToDelete is culled. static void prepareForDeletion(SILInstruction *inst, SmallVectorImpl<SILInstruction *> &instructionsToDelete) { for (auto &operand : inst->getAllOperands()) { operand.set(SILUndef::get(operand.get()->getType(), *inst->getFunction())); } instructionsToDelete.push_back(inst); } static void replaceDestroy(DestroyAddrInst *dai, SILValue newValue, SILBuilderContext &ctx, InstructionDeleter &deleter, SmallVectorImpl<SILInstruction *> &instructionsToDelete) { SILFunction *f = dai->getFunction(); auto ty = dai->getOperand()->getType(); assert(ty.isLoadable(*f) && "Unexpected promotion of address-only type!"); assert(newValue || (ty.is<TupleType>() && ty.getAs<TupleType>()->getNumElements() == 0)); SILBuilderWithScope builder(dai, ctx); auto &typeLowering = f->getTypeLowering(ty); bool expand = shouldExpand(dai->getModule(), dai->getOperand()->getType().getObjectType()); using TypeExpansionKind = Lowering::TypeLowering::TypeExpansionKind; auto expansionKind = expand ? TypeExpansionKind::MostDerivedDescendents : TypeExpansionKind::None; typeLowering.emitLoweredDestroyValue(builder, dai->getLoc(), newValue, expansionKind); prepareForDeletion(dai, instructionsToDelete); } /// Promote a DebugValue w/ address value to a DebugValue of non-address value. static void promoteDebugValueAddr(DebugValueInst *dvai, SILValue value, SILBuilderContext &ctx, InstructionDeleter &deleter) { assert(dvai->getOperand()->getType().isLoadable(*dvai->getFunction()) && "Unexpected promotion of address-only type!"); assert(value && "Expected valid value"); // Avoid inserting the same debug_value twice. for (auto *use : value->getUses()) { if (auto *dvi = dyn_cast<DebugValueInst>(use->getUser())) { // Since we're not comparing di-expression in // SILDebugVariable::operator==(), it's necessary to distinguish // debug_value w/ normal values from that with address-type values. if (!dvi->hasAddrVal() && *dvi->getVarInfo() == *dvai->getVarInfo()) { deleter.forceDelete(dvai); return; } } } auto VarInfo = *dvai->getVarInfo(); // Drop op_deref if dvai is actually a debug_value instruction if (isa<DebugValueInst>(dvai)) { auto &DIExpr = VarInfo.DIExpr; if (DIExpr) DIExpr.eraseElement(DIExpr.element_begin()); } SILBuilderWithScope b(dvai, ctx); b.createDebugValue(dvai->getLoc(), value, std::move(VarInfo)); deleter.forceDelete(dvai); } /// Returns true if \p I is a load which loads from \p ASI. static bool isLoadFromStack(SILInstruction *i, AllocStackInst *asi) { if (!isa<LoadInst>(i)) return false; // Skip struct and tuple address projections. ValueBase *op = i->getOperand(0); while (op != asi) { if (!isa<UncheckedAddrCastInst>(op) && !isa<StructElementAddrInst>(op) && !isa<TupleElementAddrInst>(op)) return false; op = cast<SingleValueInstruction>(op)->getOperand(0); } return true; } /// Collects all load instructions which (transitively) use \p I as address. static void collectLoads(SILInstruction *i, SmallVectorImpl<LoadInst *> &foundLoads) { if (auto *load = dyn_cast<LoadInst>(i)) { foundLoads.push_back(load); return; } if (!isa<UncheckedAddrCastInst>(i) && !isa<StructElementAddrInst>(i) && !isa<TupleElementAddrInst>(i)) return; // Recursively search for other loads in the instruction's uses. for (auto *use : cast<SingleValueInstruction>(i)->getUses()) { collectLoads(use->getUser(), foundLoads); } } static void replaceLoad(LoadInst *li, SILValue newValue, AllocStackInst *asi, SILBuilderContext &ctx, InstructionDeleter &deleter, SmallVectorImpl<SILInstruction *> &instructionsToDelete) { ProjectionPath projections(newValue->getType()); SILValue op = li->getOperand(); SILBuilderWithScope builder(li, ctx); SILOptScope scope; while (op != asi) { assert(isa<UncheckedAddrCastInst>(op) || isa<StructElementAddrInst>(op) || isa<TupleElementAddrInst>(op) && "found instruction that should have been skipped in " "isLoadFromStack"); auto *inst = cast<SingleValueInstruction>(op); projections.push_back(Projection(inst)); op = inst->getOperand(0); } for (const auto &proj : llvm::reverse(projections)) { assert(proj.getKind() == ProjectionKind::BitwiseCast || proj.getKind() == ProjectionKind::Struct || proj.getKind() == ProjectionKind::Tuple); // struct_extract and tuple_extract expect guaranteed operand ownership // non-trivial RunningVal is owned. Insert borrow operation to convert them // to guaranteed! if (proj.getKind() == ProjectionKind::Struct || proj.getKind() == ProjectionKind::Tuple) { if (auto opVal = scope.borrowValue(li, newValue)) { assert(*opVal != newValue && "Valid value should be different from input value"); newValue = *opVal; } } newValue = proj.createObjectProjection(builder, li->getLoc(), newValue).get(); } op = li->getOperand(); // Replace users of the loaded value with `val` // If we have a load [copy], replace the users with copy_value of `val` if (li->getOwnershipQualifier() == LoadOwnershipQualifier::Copy) { li->replaceAllUsesWith(builder.createCopyValue(li->getLoc(), newValue)); } else { assert(!asi->getFunction()->hasOwnership() || newValue.getOwnershipKind() != OwnershipKind::Guaranteed); li->replaceAllUsesWith(newValue); } // Pop the scope so that we emit cleanups. std::move(scope).popAtEndOfScope(&*builder.getInsertionPoint()); // Delete the load prepareForDeletion(li, instructionsToDelete); while (op != asi && op->use_empty()) { assert(isa<UncheckedAddrCastInst>(op) || isa<StructElementAddrInst>(op) || isa<TupleElementAddrInst>(op)); auto *inst = cast<SingleValueInstruction>(op); SILValue next = inst->getOperand(0); deleter.forceDelete(inst); op = next; } } /// Create a tuple value for an empty tuple or a tuple of empty tuples. static SILValue createValueForEmptyTuple(SILType ty, SILInstruction *insertionPoint, SILBuilderContext &ctx) { auto tupleTy = ty.castTo<TupleType>(); SmallVector<SILValue, 4> elements; for (unsigned idx : range(tupleTy->getNumElements())) { SILType elementTy = ty.getTupleElementType(idx); elements.push_back( createValueForEmptyTuple(elementTy, insertionPoint, ctx)); } SILBuilderWithScope builder(insertionPoint, ctx); return builder.createTuple(insertionPoint->getLoc(), ty, elements); } /// Whether lexical lifetimes should be added for the values stored into the /// alloc_stack. static bool shouldAddLexicalLifetime(AllocStackInst *asi) { return asi->getFunction()->hasOwnership() && asi->getFunction() ->getModule() .getASTContext() .SILOpts.EnableExperimentalLexicalLifetimes && asi->isLexical() && !asi->getElementType().isTrivial(*asi->getFunction()); } /// Begin a lexical borrow scope for the value stored into the provided /// StoreInst after that instruction. /// /// The beginning of the scope looks like /// /// %lifetime = begin_borrow %original /// %copy = copy_value %lifetime static StorageStateTracking<LiveValues> beginLexicalLifetimeAfterStore(AllocStackInst *asi, StoreInst *si) { assert(shouldAddLexicalLifetime(asi)); BeginBorrowInst *bbi = nullptr; CopyValueInst *cvi = nullptr; SILBuilderWithScope::insertAfter(si, [&](SILBuilder &builder) { SILLocation loc = RegularLocation::getAutoGeneratedLocation(si->getLoc()); bbi = builder.createBeginBorrow(loc, si->getSrc(), /*isLexical*/ true); cvi = builder.createCopyValue(loc, bbi); }); StorageStateTracking<LiveValues> vals = {{si->getSrc(), bbi, cvi}, /*isStorageValid=*/true}; return vals; } /// End the lexical borrow scope described by the provided LiveValues struct /// before the specified instruction. /// /// The end of the scope looks like /// /// end_borrow %lifetime /// destroy_value %original /// /// These two instructions correspond to the following instructions that begin /// a lexical borrow scope: /// /// %lifetime = begin_borrow %original /// %copy = copy_value %lifetime static void endLexicalLifetimeBeforeInst(AllocStackInst *asi, SILInstruction *beforeInstruction, SILBuilderContext &ctx, LiveValues values) { assert(shouldAddLexicalLifetime(asi)); assert(beforeInstruction); auto builder = SILBuilderWithScope(beforeInstruction, ctx); SILLocation loc = RegularLocation::getAutoGeneratedLocation(beforeInstruction->getLoc()); builder.createEndBorrow(loc, values.borrow); builder.emitDestroyValueOperation(loc, values.stored); } //===----------------------------------------------------------------------===// // Single Stack Allocation Promotion //===----------------------------------------------------------------------===// namespace { /// Promotes a single AllocStackInst into registers.. class StackAllocationPromoter { using BlockSetVector = BasicBlockSetVector; template <typename Inst = SILInstruction> using BlockToInstMap = llvm::DenseMap<SILBasicBlock *, Inst *>; // Use a priority queue keyed on dominator tree level so that inserted nodes // are handled from the bottom of the dom tree upwards. using DomTreeNodePair = std::pair<DomTreeNode *, unsigned>; using NodePriorityQueue = std::priority_queue<DomTreeNodePair, SmallVector<DomTreeNodePair, 32>, llvm::less_second>; /// The AllocStackInst that we are handling. AllocStackInst *asi; /// The unique deallocation instruction. This value could be NULL if there are /// multiple deallocations. DeallocStackInst *dsi; /// Dominator info. DominanceInfo *domInfo; /// Map from dominator tree node to tree level. DomTreeLevelMap &domTreeLevels; /// The SIL builder used when creating new instructions during register /// promotion. SILBuilderContext &ctx; InstructionDeleter &deleter; /// Instructions that could not be deleted immediately with forceDelete until /// StackAllocationPromoter finishes its run. /// /// There are two reasons why an instruction might not be deleted: /// (1) new instructions are inserted before or after it /// (2) it ensures that an instruction remains used, preventing it from being /// deleted SmallVectorImpl<SILInstruction *> &instructionsToDelete; /// The last instruction in each block that initializes the storage that is /// not succeeded by an instruction that deinitializes it. /// /// The live-out values for every block can be derived from these. /// /// For non-lexical alloc_stacks, that is just a StoreInst. For lexical /// alloc_stacks, that is the StoreInst, a BeginBorrowInst of the /// value stored into the StoreInst and a CopyValueInst of the result of the /// BeginBorrowInst. BlockToInstMap<StoreInst> initializationPoints; /// The first instruction in each block that deinitializes the storage that is /// not preceeded by an instruction that initializes it. /// /// That includes: /// store /// destroy_addr /// load [take] /// /// Ending lexical lifetimes before these instructions is one way that the /// cross-block lexical lifetimes of initializationPoints can be ended in /// StackAllocationPromoter::endLexicalLifetime. BlockToInstMap<> deinitializationPoints; public: /// C'tor. StackAllocationPromoter( AllocStackInst *inputASI, DominanceInfo *inputDomInfo, DomTreeLevelMap &inputDomTreeLevels, SILBuilderContext &inputCtx, InstructionDeleter &deleter, SmallVectorImpl<SILInstruction *> &instructionsToDelete) : asi(inputASI), dsi(nullptr), domInfo(inputDomInfo), domTreeLevels(inputDomTreeLevels), ctx(inputCtx), deleter(deleter), instructionsToDelete(instructionsToDelete) { // Scan the users in search of a deallocation instruction. for (auto *use : asi->getUses()) { if (auto *foundDealloc = dyn_cast<DeallocStackInst>(use->getUser())) { // Don't record multiple dealloc instructions. if (dsi) { dsi = nullptr; break; } // Record the deallocation instruction. dsi = foundDealloc; } } } /// Promote the Allocation. void run(); private: /// Promote AllocStacks into SSA. void promoteAllocationToPhi(); /// Replace the dummy nodes with new block arguments. void addBlockArguments(BlockSetVector &phiBlocks); /// Check if \p phi is a proactively added phi by SILMem2Reg bool isProactivePhi(SILPhiArgument *phi, const BlockSetVector &phiBlocks); /// Check if \p proactivePhi is live. bool isNecessaryProactivePhi(SILPhiArgument *proactivePhi, const BlockSetVector &phiBlocks); /// Given a \p proactivePhi that is live, backward propagate liveness to /// other proactivePhis. void propagateLiveness(SILPhiArgument *proactivePhi, const BlockSetVector &phiBlocks, SmallPtrSetImpl<SILPhiArgument *> &livePhis); /// End the lexical borrow scope that is introduced for lexical alloc_stack /// instructions. void endLexicalLifetime(BlockSetVector &phiBlocks); /// Fix all of the branch instructions and the uses to use /// the AllocStack definitions (which include stores and Phis). void fixBranchesAndUses(BlockSetVector &blocks, BlockSetVector &liveBlocks); /// update the branch instructions with the new Phi argument. /// The blocks in \p PhiBlocks are blocks that define a value, \p Dest is /// the branch destination, and \p Pred is the predecessors who's branch we /// modify. void fixPhiPredBlock(BlockSetVector &phiBlocks, SILBasicBlock *dest, SILBasicBlock *pred); /// Get the values for this AllocStack variable that are flowing out of /// StartBB. Optional<LiveValues> getLiveOutValues(BlockSetVector &phiBlocks, SILBasicBlock *startBlock); /// Get the values for this AllocStack variable that are flowing out of /// StartBB or undef if there are none. LiveValues getEffectiveLiveOutValues(BlockSetVector &phiBlocks, SILBasicBlock *startBlock); /// Get the values for this AllocStack variable that are flowing into block. Optional<LiveValues> getLiveInValues(BlockSetVector &phiBlocks, SILBasicBlock *block); /// Get the values for this AllocStack variable that are flowing into block or /// undef if there are none. LiveValues getEffectiveLiveInValues(BlockSetVector &phiBlocks, SILBasicBlock *block); /// Prune AllocStacks usage in the function. Scan the function /// and remove in-block usage of the AllocStack. Leave only the first /// load and the last store. void pruneAllocStackUsage(); /// Promote all of the AllocStacks in a single basic block in one /// linear scan. This function deletes all of the loads and stores except /// for the first load and the last store. /// \returns the last StoreInst found, whose storage was not subsequently /// deinitialized StoreInst *promoteAllocationInBlock(SILBasicBlock *block); }; } // end of namespace StoreInst *StackAllocationPromoter::promoteAllocationInBlock( SILBasicBlock *blockPromotingWithin) { LLVM_DEBUG(llvm::dbgs() << "*** Promoting ASI in block: " << *asi); // RunningVal is the current value in the stack location. // We don't know the value of the alloca until we find the first store. Optional<StorageStateTracking<LiveValues>> runningVals; // Keep track of the last StoreInst that we found and the BeginBorrowInst and // CopyValueInst that we created in response if the alloc_stack was lexical. Optional<StorageStateTracking<StoreInst *>> lastStoreInst; /// Returns true if we have enough information to end the lifetime during /// promoteAllocationInBlock. /// /// The lifetime cannot be ended during this function's execution if we don't /// yet have enough information to end it. That occurs when the running /// values are from a load which was not preceeded by a store. In that case, /// the lifetime end will be added later, when we have enough information, /// namely the live in values, to end it. auto canEndLexicalLifetime = [](StorageStateTracking<LiveValues> values) -> bool { return values.value.borrow; }; // For all instructions in the block. for (auto bbi = blockPromotingWithin->begin(), bbe = blockPromotingWithin->end(); bbi != bbe;) { SILInstruction *inst = &*bbi; ++bbi; if (isLoadFromStack(inst, asi)) { assert(!runningVals || runningVals->isStorageValid); auto *li = cast<LoadInst>(inst); if (li->getOwnershipQualifier() == LoadOwnershipQualifier::Take) { if (shouldAddLexicalLifetime(asi)) { // End the lexical lifetime at a load [take]. The storage is no // longer keeping the value alive. if (runningVals && canEndLexicalLifetime(*runningVals)) { // End it right now if we have enough information. endLexicalLifetimeBeforeInst(asi, /*beforeInstruction=*/li, ctx, runningVals->value); } else { // If we dont't have enough information, end it endLexicalLifetime. assert(!deinitializationPoints[blockPromotingWithin]); deinitializationPoints[blockPromotingWithin] = li; } } if (runningVals) runningVals->isStorageValid = false; if (lastStoreInst) lastStoreInst->isStorageValid = false; } if (runningVals) { // If we are loading from the AllocStackInst and we already know the // content of the Alloca then use it. LLVM_DEBUG(llvm::dbgs() << "*** Promoting load: " << *li); replaceLoad(li, runningVals->value.replacement(asi), asi, ctx, deleter, instructionsToDelete); ++NumInstRemoved; } else if (li->getOperand() == asi && li->getOwnershipQualifier() != LoadOwnershipQualifier::Copy) { // If we don't know the content of the AllocStack then the loaded // value *is* the new value; // Don't use result of load [copy] as a RunningVal, it necessitates // additional logic for cleanup of consuming instructions of the result. // StackAllocationPromoter::fixBranchesAndUses will later handle it. LLVM_DEBUG(llvm::dbgs() << "*** First load: " << *li); runningVals = {LiveValues::toReplace(asi, /*replacement=*/li), /*isStorageValid=*/true}; } continue; } // Remove stores and record the value that we are saving as the running // value. if (auto *si = dyn_cast<StoreInst>(inst)) { if (si->getDest() != asi) continue; // If we see a store [assign], always convert it to a store [init]. This // simplifies further processing. if (si->getOwnershipQualifier() == StoreOwnershipQualifier::Assign) { if (runningVals) { assert(runningVals->isStorageValid); SILBuilderWithScope(si, ctx).createDestroyValue( si->getLoc(), runningVals->value.replacement(asi)); } else { SILBuilderWithScope localBuilder(si, ctx); auto *newLoad = localBuilder.createLoad(si->getLoc(), asi, LoadOwnershipQualifier::Take); localBuilder.createDestroyValue(si->getLoc(), newLoad); if (shouldAddLexicalLifetime(asi)) { assert(!deinitializationPoints[blockPromotingWithin]); deinitializationPoints[blockPromotingWithin] = si; } } si->setOwnershipQualifier(StoreOwnershipQualifier::Init); } // If we met a store before this one, delete it. if (lastStoreInst) { assert(lastStoreInst->value->getOwnershipQualifier() != StoreOwnershipQualifier::Assign && "store [assign] to the stack location should have been " "transformed to a store [init]"); LLVM_DEBUG(llvm::dbgs() << "*** Removing redundant store: " << lastStoreInst->value); ++NumInstRemoved; prepareForDeletion(lastStoreInst->value, instructionsToDelete); } auto oldRunningVals = runningVals; // The stored value is the new running value. runningVals = {LiveValues::toReplace(asi, /*replacement=*/si->getSrc()), /*isStorageValid=*/true}; // The current store is now the lastStoreInst (until we see // another). lastStoreInst = {si, /*isStorageValid=*/true}; if (shouldAddLexicalLifetime(asi)) { if (oldRunningVals && oldRunningVals->isStorageValid && canEndLexicalLifetime(*oldRunningVals)) { endLexicalLifetimeBeforeInst(asi, /*beforeInstruction=*/si, ctx, oldRunningVals->value); } runningVals = beginLexicalLifetimeAfterStore(asi, si); // Create a use of the newly created copy in order to keep phi pruning // from deleting our lifetime beginning instructions. SILBuilderWithScope::insertAfter( runningVals->value.copy->getDefiningInstruction(), [&](auto builder) { SILLocation loc = RegularLocation::getAutoGeneratedLocation(); auto *useOfCopy = builder.createCopyValue(loc, runningVals->value.copy); // Note that we don't call prepareToDelete useOfCopy because we // specifically want this instruction to remain a use of copy. instructionsToDelete.push_back(useOfCopy); }); } continue; } // Replace debug_value w/ address value with debug_value of // the promoted value. // if we have a valid value to use at this point. Otherwise we'll // promote this when we deal with hooking up phis. if (auto *dvi = DebugValueInst::hasAddrVal(inst)) { if (dvi->getOperand() == asi && runningVals) promoteDebugValueAddr(dvi, runningVals->value.replacement(asi), ctx, deleter); continue; } // Replace destroys with a release of the value. if (auto *dai = dyn_cast<DestroyAddrInst>(inst)) { if (dai->getOperand() == asi) { if (runningVals) { replaceDestroy(dai, runningVals->value.replacement(asi), ctx, deleter, instructionsToDelete); if (shouldAddLexicalLifetime(asi)) { endLexicalLifetimeBeforeInst(asi, /*beforeInstruction=*/dai, ctx, runningVals->value); } runningVals->isStorageValid = false; if (lastStoreInst) lastStoreInst->isStorageValid = false; } else { assert(!deinitializationPoints[blockPromotingWithin]); deinitializationPoints[blockPromotingWithin] = dai; } } continue; } if (auto *dvi = dyn_cast<DestroyValueInst>(inst)) { if (runningVals && dvi->getOperand() == runningVals->value.replacement(asi)) { // Reset LastStore. // So that we don't end up passing dead values as phi args in // StackAllocationPromoter::fixBranchesAndUses lastStoreInst = llvm::None; } } // Stop on deallocation. if (auto *dsi = dyn_cast<DeallocStackInst>(inst)) { if (dsi->getOperand() == asi) break; } } if (lastStoreInst && lastStoreInst->isStorageValid) { assert(lastStoreInst->value->getOwnershipQualifier() != StoreOwnershipQualifier::Assign && "store [assign] to the stack location should have been " "transformed to a store [init]"); LLVM_DEBUG(llvm::dbgs() << "*** Finished promotion. Last store: " << lastStoreInst->value); return lastStoreInst->value; } LLVM_DEBUG(llvm::dbgs() << "*** Finished promotion with no stores.\n"); return nullptr; } void StackAllocationPromoter::addBlockArguments(BlockSetVector &phiBlocks) { LLVM_DEBUG(llvm::dbgs() << "*** Adding new block arguments.\n"); for (auto *block : phiBlocks) { // The stored value. block->createPhiArgument(asi->getElementType(), OwnershipKind::Owned); if (shouldAddLexicalLifetime(asi)) { // The borrow scope. block->createPhiArgument(asi->getElementType(), OwnershipKind::Guaranteed); // The copy of the borrowed value. block->createPhiArgument(asi->getElementType(), OwnershipKind::Owned); } } } Optional<LiveValues> StackAllocationPromoter::getLiveOutValues(BlockSetVector &phiBlocks, SILBasicBlock *startBlock) { LLVM_DEBUG(llvm::dbgs() << "*** Searching for a value definition.\n"); // Walk the Dom tree in search of a defining value: for (DomTreeNode *domNode = domInfo->getNode(startBlock); domNode; domNode = domNode->getIDom()) { SILBasicBlock *domBlock = domNode->getBlock(); // If there is a store (that must come after the phi), use its value. BlockToInstMap<StoreInst>::iterator it = initializationPoints.find(domBlock); if (it != initializationPoints.end()) { auto *si = it->second; LLVM_DEBUG(llvm::dbgs() << "*** Found Store def " << si->getSrc()); SILValue stored = si->getSrc(); SILValue borrow = SILValue(); SILValue copy = SILValue(); if (shouldAddLexicalLifetime(asi)) { auto *bbi = cast<BeginBorrowInst>(&*std::next(si->getIterator())); borrow = bbi; auto *cvi = cast<CopyValueInst>(bbi->getNextInstruction()); copy = cvi; } LiveValues values = {stored, borrow, copy}; return values; } // If there is a Phi definition in this block: if (phiBlocks.contains(domBlock)) { // Return the dummy instruction that represents the new value that we will // add to the basic block. SILValue original; SILValue borrow; SILValue copy; if (shouldAddLexicalLifetime(asi)) { original = domBlock->getArgument(domBlock->getNumArguments() - 3); borrow = domBlock->getArgument(domBlock->getNumArguments() - 2); copy = domBlock->getArgument(domBlock->getNumArguments() - 1); } else { original = domBlock->getArgument(domBlock->getNumArguments() - 1); borrow = SILValue(); copy = SILValue(); } LLVM_DEBUG(llvm::dbgs() << "*** Found a dummy Phi def " << *original); LiveValues values = {original, borrow, copy}; return values; } // Move to the next dominating block. LLVM_DEBUG(llvm::dbgs() << "*** Walking up the iDOM.\n"); } LLVM_DEBUG(llvm::dbgs() << "*** Could not find a Def. Using Undef.\n"); return llvm::None; } LiveValues StackAllocationPromoter::getEffectiveLiveOutValues(BlockSetVector &phiBlocks, SILBasicBlock *startBlock) { if (auto values = getLiveOutValues(phiBlocks, startBlock)) { return *values; } auto *undef = SILUndef::get(asi->getElementType(), *asi->getFunction()); return {undef, undef, undef}; } Optional<LiveValues> StackAllocationPromoter::getLiveInValues(BlockSetVector &phiBlocks, SILBasicBlock *block) { // First, check if there is a Phi value in the current block. We know that // our loads happen before stores, so we need to first check for Phi nodes // in the first block, but stores first in all other stores in the idom // chain. if (phiBlocks.contains(block)) { LLVM_DEBUG(llvm::dbgs() << "*** Found a local Phi definition.\n"); SILValue original; SILValue borrow; SILValue copy; if (shouldAddLexicalLifetime(asi)) { original = block->getArgument(block->getNumArguments() - 3); borrow = block->getArgument(block->getNumArguments() - 2); copy = block->getArgument(block->getNumArguments() - 1); } else { original = block->getArgument(block->getNumArguments() - 1); borrow = SILValue(); copy = SILValue(); } LiveValues values = {original, borrow, copy}; return values; } if (block->pred_empty() || !domInfo->getNode(block)) return llvm::None; // No phi for this value in this block means that the value flowing // out of the immediate dominator reaches here. DomTreeNode *iDom = domInfo->getNode(block)->getIDom(); assert(iDom && "Attempt to get live-in value for alloc_stack in entry block!"); return getLiveOutValues(phiBlocks, iDom->getBlock()); } LiveValues StackAllocationPromoter::getEffectiveLiveInValues(BlockSetVector &phiBlocks, SILBasicBlock *block) { if (auto values = getLiveInValues(phiBlocks, block)) { return *values; } auto *undef = SILUndef::get(asi->getElementType(), *asi->getFunction()); return {undef, undef, undef}; } void StackAllocationPromoter::fixPhiPredBlock(BlockSetVector &phiBlocks, SILBasicBlock *destBlock, SILBasicBlock *predBlock) { TermInst *ti = predBlock->getTerminator(); LLVM_DEBUG(llvm::dbgs() << "*** Fixing the terminator " << ti << ".\n"); LiveValues def = getEffectiveLiveOutValues(phiBlocks, predBlock); LLVM_DEBUG(llvm::dbgs() << "*** Found the definition: " << *def.copy); llvm::SmallVector<SILValue> vals; vals.push_back(def.stored); if (shouldAddLexicalLifetime(asi)) { vals.push_back(def.borrow); vals.push_back(def.copy); } addArgumentsToBranch(vals, destBlock, ti); deleter.forceDelete(ti); } bool StackAllocationPromoter::isProactivePhi(SILPhiArgument *phi, const BlockSetVector &phiBlocks) { auto *phiBlock = phi->getParentBlock(); return phiBlocks.contains(phiBlock) && phi == phiBlock->getArgument(phiBlock->getNumArguments() - 1); } bool StackAllocationPromoter::isNecessaryProactivePhi( SILPhiArgument *proactivePhi, const BlockSetVector &phiBlocks) { assert(isProactivePhi(proactivePhi, phiBlocks)); for (auto *use : proactivePhi->getUses()) { auto *branch = dyn_cast<BranchInst>(use->getUser()); // A non-branch use is a necessary use if (!branch) return true; auto *destBB = branch->getDestBB(); auto opNum = use->getOperandNumber(); // A phi has a necessary use if it is used as a branch op for a // non-proactive phi if (!phiBlocks.contains(destBB) || (opNum != branch->getNumArgs() - 1)) return true; } return false; } void StackAllocationPromoter::propagateLiveness( SILPhiArgument *proactivePhi, const BlockSetVector &phiBlocks, SmallPtrSetImpl<SILPhiArgument *> &livePhis) { assert(isProactivePhi(proactivePhi, phiBlocks)); if (livePhis.contains(proactivePhi)) return; // If liveness has not been propagated, go over the incoming operands and mark // any operand values that are proactivePhis as live livePhis.insert(proactivePhi); SmallVector<SILValue, 4> incomingPhiVals; proactivePhi->getIncomingPhiValues(incomingPhiVals); for (auto &inVal : incomingPhiVals) { auto *inPhi = dyn_cast<SILPhiArgument>(inVal); if (!inPhi) continue; if (!isProactivePhi(inPhi, phiBlocks)) continue; propagateLiveness(inPhi, phiBlocks, livePhis); } } void StackAllocationPromoter::fixBranchesAndUses(BlockSetVector &phiBlocks, BlockSetVector &phiBlocksOut) { // First update uses of the value. SmallVector<LoadInst *, 4> collectedLoads; for (auto ui = asi->use_begin(), ue = asi->use_end(); ui != ue;) { auto *user = ui->getUser(); ++ui; bool removedUser = false; collectedLoads.clear(); collectLoads(user, collectedLoads); for (auto *li : collectedLoads) { LiveValues def; // If this block has no predecessors then nothing dominates it and // the instruction is unreachable. If the instruction we're // examining is a value, replace it with undef. Either way, delete // the instruction and move on. SILBasicBlock *loadBlock = li->getParent(); def = getEffectiveLiveInValues(phiBlocks, loadBlock); LLVM_DEBUG(llvm::dbgs() << "*** Replacing " << *li << " with Def " << def.replacement(asi)); // Replace the load with the definition that we found. replaceLoad(li, def.replacement(asi), asi, ctx, deleter, instructionsToDelete); removedUser = true; ++NumInstRemoved; } if (removedUser) continue; // If this block has no predecessors then nothing dominates it and // the instruction is unreachable. Delete the instruction and move // on. SILBasicBlock *userBlock = user->getParent(); if (auto *dvi = DebugValueInst::hasAddrVal(user)) { // Replace debug_value w/ address-type value with // a new debug_value w/ promoted value. auto def = getEffectiveLiveInValues(phiBlocks, userBlock); promoteDebugValueAddr(dvi, def.replacement(asi), ctx, deleter); ++NumInstRemoved; continue; } // Replace destroys with a release of the value. if (auto *dai = dyn_cast<DestroyAddrInst>(user)) { auto def = getEffectiveLiveInValues(phiBlocks, userBlock); replaceDestroy(dai, def.replacement(asi), ctx, deleter, instructionsToDelete); continue; } } // Now that all of the uses are fixed we can fix the branches that point // to the blocks with the added arguments. // For each Block with a new Phi argument: for (auto *block : phiBlocks) { // Fix all predecessors. for (auto pbbi = block->getPredecessorBlocks().begin(), pbbe = block->getPredecessorBlocks().end(); pbbi != pbbe;) { auto *predBlock = *pbbi; ++pbbi; assert(predBlock && "Invalid block!"); fixPhiPredBlock(phiBlocks, block, predBlock); } } // Fix ownership of proactively created non-trivial phis if (asi->getFunction()->hasOwnership() && !asi->getType().isTrivial(*asi->getFunction())) { SmallPtrSet<SILPhiArgument *, 4> livePhis; for (auto *block : phiBlocks) { auto *proactivePhi = cast<SILPhiArgument>( block->getArgument(block->getNumArguments() - 1)); // First, check if the proactively added phi is necessary by looking at // it's immediate uses. if (isNecessaryProactivePhi(proactivePhi, phiBlocks)) { // Backward propagate liveness to other dependent proactively added phis propagateLiveness(proactivePhi, phiBlocks, livePhis); } } // Go over all proactively added phis, and delete those that were not marked // live above. auto eraseLastPhiFromBlock = [](SILBasicBlock *block) { auto *phi = cast<SILPhiArgument>( block->getArgument(block->getNumArguments() - 1)); phi->replaceAllUsesWithUndef(); erasePhiArgument(block, block->getNumArguments() - 1); }; for (auto *block : phiBlocks) { auto *proactivePhi = cast<SILPhiArgument>( block->getArgument(block->getNumArguments() - 1)); if (!livePhis.contains(proactivePhi)) { eraseLastPhiFromBlock(block); if (shouldAddLexicalLifetime(asi)) { eraseLastPhiFromBlock(block); eraseLastPhiFromBlock(block); } } else { phiBlocksOut.insert(block); } } } else { for (auto *block : phiBlocks) phiBlocksOut.insert(block); } } /// End the lexical lifetimes that were introduced for storage to the /// alloc_stack and have not already been ended. /// /// Walk forward from the out-edge of each of the blocks which began but did not /// end a borrow scope. The scope must be ended if any of the following three /// conditions hold: /// /// Normally, we are relying on the invariant that the storage's /// deinitializations must jointly postdominate its initializations. That fact /// allows us to simply end scopes when memory is deinitialized. There is only /// one simple check to do: /// /// (1) A block deinitializes the storage before initializing it. /// /// These blocks and the relevant instruction within them are tracked by the /// deinitializationPoints map. /// /// If this were all we needed to do, we could just iterate over that map. /// /// The above invariant does not help us with unreachable terminators, however. /// Because it is valid to have the alloc_stack be initialized when exiting a /// function via an unreachable, we can't rely on the memory having been /// deinitialized. But we still need to ensure that borrow scopes are ended and /// values are destroyed before getting to an unreachable. /// /// (2.a) A block has as its terminator an UnreachableInst. /// /// (2.b) A block's single successor does not have live-in values. /// /// This can only happen if the successor is a CFG merge and all paths /// from here lead to unreachable. void StackAllocationPromoter::endLexicalLifetime(BlockSetVector &phiBlocks) { if (!shouldAddLexicalLifetime(asi)) return; // We need to separately consider and visit incoming unopened borrow scopes // and outgoing unclosed borrow scopes. The reason is that a walk should stop // on any path where it encounters an incoming unopened borrow scope but that // should _NOT_ count as a visit of outgoing unclosed borrow scopes. // // Without this distinction, a case like the following wouldn't be visited // properly: // // bb1: // %addr = alloc_stack // store %value to [init] %addr // br bb2 // bb2: // %value_2 = load [take] %addr // store %value_2 to [init] %addr // br bb3 // bb3: // destroy_addr %addr // dealloc_stack %addr // %r = tuple () // return %r // // Both bb1 and bb2 have cross-block initialization points. Suppose that we // visited bb1 first. We would see that it didn't have an incoming unopened // borrow scope (already, we can tell something is amiss that we're // considering this) and then add bb2 to the worklist--except it's already // there. Next we would visit bb2. We would see that it had an incoming // unopened borrow scope so we would close it. And then we'd be done. In // particular, we'd leave the scope that opens in bb2 unclosed. // // The root cause here is that it's important to stop walking when we hit a // scope close. Otherwise, we could keep walking down to blocks which don't // have live-in or live-out values. // // Visiting the incoming and outgoing edges works as follows in the above // example: The worklist is initialiized with {(bb1, ::Out), (bb2, ::Out)}. // When visiting (bb1, ::Out), we see that bb1 is neither unreachable nor // has exactly one successor without live-in values. So we add (bb2, ::In) to // the worklist. Next, we visit (bb2, ::Out). We see that it _also_ doesn't // have an unreachable terminator or a unique successor without live-in // values, so we add (bb3, ::In). Next, we visit (bb2, ::In). We see that // it _does_ have an incoming unopened borrow scope, so we close it and stop. // Finally, we visit (bb3, ::Out). We see that it too has an incoming // unopened borrow scope so we close it and stop. enum class AvailableValuesKind : uint8_t { In, Out }; using ScopeEndPosition = llvm::PointerIntPair<SILBasicBlock *, 1, AvailableValuesKind>; GraphNodeWorklist<ScopeEndPosition, 16> worklist; for (auto pair : initializationPoints) { worklist.insert({pair.getFirst(), AvailableValuesKind::Out}); } while (!worklist.empty()) { auto position = worklist.pop(); auto *bb = position.getPointer(); switch (position.getInt()) { case AvailableValuesKind::In: { if (auto *inst = deinitializationPoints[bb]) { auto values = getLiveInValues(phiBlocks, bb); endLexicalLifetimeBeforeInst(asi, /*beforeInstruction=*/inst, ctx, *values); continue; } worklist.insert({bb, AvailableValuesKind::Out}); break; } case AvailableValuesKind::Out: { bool terminatesInUnreachable = isa<UnreachableInst>(bb->getTerminator()); auto uniqueSuccessorLacksLiveInValues = [&]() -> bool { return bb->getSingleSuccessorBlock() && !getLiveInValues(phiBlocks, bb->getSingleSuccessorBlock()); }; if (terminatesInUnreachable || uniqueSuccessorLacksLiveInValues()) { auto values = getLiveOutValues(phiBlocks, bb); endLexicalLifetimeBeforeInst( asi, /*beforeInstruction=*/bb->getTerminator(), ctx, *values); continue; } for (auto *successor : bb->getSuccessorBlocks()) { worklist.insert({successor, AvailableValuesKind::In}); } break; } } } } void StackAllocationPromoter::pruneAllocStackUsage() { LLVM_DEBUG(llvm::dbgs() << "*** Pruning : " << *asi); BlockSetVector functionBlocks(asi->getFunction()); // Insert all of the blocks that asi is live in. for (auto *use : asi->getUses()) functionBlocks.insert(use->getUser()->getParent()); for (auto block : functionBlocks) if (auto si = promoteAllocationInBlock(block)) { // There was a final storee instruction which was not followed by an // instruction that deinitializes the memory. Record it as a cross-block // initialization point. initializationPoints[block] = si; } LLVM_DEBUG(llvm::dbgs() << "*** Finished pruning : " << *asi); } void StackAllocationPromoter::promoteAllocationToPhi() { LLVM_DEBUG(llvm::dbgs() << "*** Placing Phis for : " << *asi); // A list of blocks that will require new Phi values. BlockSetVector phiBlocks(asi->getFunction()); // The "piggy-bank" data-structure that we use for processing the dom-tree // bottom-up. NodePriorityQueue priorityQueue; // Collect all of the stores into the AllocStack. We know that at this point // we have at most one store per block. for (auto *use : asi->getUses()) { SILInstruction *user = use->getUser(); // We need to place Phis for this block. if (isa<StoreInst>(user)) { // If the block is in the dom tree (dominated by the entry block). if (auto *node = domInfo->getNode(user->getParent())) priorityQueue.push(std::make_pair(node, domTreeLevels[node])); } } LLVM_DEBUG(llvm::dbgs() << "*** Found: " << priorityQueue.size() << " Defs\n"); // A list of nodes for which we already calculated the dominator frontier. llvm::SmallPtrSet<DomTreeNode *, 32> visited; SmallVector<DomTreeNode *, 32> worklist; // Scan all of the definitions in the function bottom-up using the priority // queue. while (!priorityQueue.empty()) { DomTreeNodePair rootPair = priorityQueue.top(); priorityQueue.pop(); DomTreeNode *root = rootPair.first; unsigned rootLevel = rootPair.second; // Walk all dom tree children of Root, inspecting their successors. Only // J-edges, whose target level is at most Root's level are added to the // dominance frontier. worklist.clear(); worklist.push_back(root); while (!worklist.empty()) { DomTreeNode *node = worklist.pop_back_val(); SILBasicBlock *nodeBlock = node->getBlock(); // For all successors of the node: for (auto &nodeBlockSuccs : nodeBlock->getSuccessors()) { auto *successorNode = domInfo->getNode(nodeBlockSuccs); // Skip D-edges (edges that are dom-tree edges). if (successorNode->getIDom() == node) continue; // Ignore J-edges that point to nodes that are not smaller or equal // to the root level. unsigned succLevel = domTreeLevels[successorNode]; if (succLevel > rootLevel) continue; // Ignore visited nodes. if (!visited.insert(successorNode).second) continue; // If the new PHInode is not dominated by the allocation then it's dead. if (!domInfo->dominates(asi->getParent(), successorNode->getBlock())) continue; // If the new PHInode is properly dominated by the deallocation then it // is obviously a dead PHInode, so we don't need to insert it. if (dsi && domInfo->properlyDominates(dsi->getParent(), successorNode->getBlock())) continue; // The successor node is a new PHINode. If this is a new PHI node // then it may require additional definitions, so add it to the PQ. if (phiBlocks.insert(nodeBlockSuccs)) priorityQueue.push(std::make_pair(successorNode, succLevel)); } // Add the children in the dom-tree to the worklist. for (auto *child : node->children()) if (!visited.count(child)) worklist.push_back(child); } } // At this point we calculated the locations of all of the new Phi values. // Next, add the Phi values and promote all of the loads and stores into the // new locations. // Replace the dummy values with new block arguments. addBlockArguments(phiBlocks); // The blocks which still have new phis after fixBranchesAndUses runs. These // are not necessarily the same as phiBlocks because fixBranchesAndUses // removes superfluous proactive phis. BlockSetVector livePhiBlocks(asi->getFunction()); // Hook up the Phi nodes, loads, and debug_value_addr with incoming values. fixBranchesAndUses(phiBlocks, livePhiBlocks); endLexicalLifetime(livePhiBlocks); LLVM_DEBUG(llvm::dbgs() << "*** Finished placing Phis ***\n"); } void StackAllocationPromoter::run() { // Reduce the number of load/stores in the function to minimum. // After this phase we are left with up to one load and store // per block and the last store is recorded. pruneAllocStackUsage(); // Replace AllocStacks with Phi-nodes. promoteAllocationToPhi(); } //===----------------------------------------------------------------------===// // General Memory To Registers Impl //===----------------------------------------------------------------------===// namespace { /// Promote memory to registers class MemoryToRegisters { /// Lazily initialized map from DomTreeNode to DomTreeLevel. /// /// DomTreeLevelMap is a DenseMap implying that if we initialize it, we always /// will initialize a heap object with 64 objects. Thus by using an optional, /// computing this lazily, we only do this if we actually need to do so. Optional<DomTreeLevelMap> domTreeLevels; /// The function that we are optimizing. SILFunction &f; /// Dominators. DominanceInfo *domInfo; /// The builder context used when creating new instructions during register /// promotion. SILBuilderContext ctx; InstructionDeleter deleter; SmallVector<SILInstruction *, 32> instructionsToDelete; /// Returns the dom tree levels for the current function. Computes these /// lazily. DomTreeLevelMap &getDomTreeLevels() { // If we already computed our levels, just return it. if (auto &levels = domTreeLevels) { return *levels; } // Otherwise, emplace the map and compute it. domTreeLevels.emplace(); auto &levels = *domTreeLevels; SmallVector<DomTreeNode *, 32> worklist; DomTreeNode *rootNode = domInfo->getRootNode(); levels[rootNode] = 0; worklist.push_back(rootNode); while (!worklist.empty()) { DomTreeNode *domNode = worklist.pop_back_val(); unsigned childLevel = levels[domNode] + 1; for (auto *childNode : domNode->children()) { levels[childNode] = childLevel; worklist.push_back(childNode); } } return *domTreeLevels; } /// Check if the AllocStackInst \p ASI is only written into. bool isWriteOnlyAllocation(AllocStackInst *asi); /// Promote all of the AllocStacks in a single basic block in one /// linear scan. Note: This function deletes all of the users of the /// AllocStackInst, including the DeallocStackInst but it does not remove the /// AllocStackInst itself! void removeSingleBlockAllocation(AllocStackInst *asi); /// Attempt to promote the specified stack allocation, returning true if so /// or false if not. On success, all uses of the AllocStackInst have been /// removed, but the ASI itself is still in the program. bool promoteSingleAllocation(AllocStackInst *asi); public: /// C'tor MemoryToRegisters(SILFunction &inputFunc, DominanceInfo *inputDomInfo) : f(inputFunc), domInfo(inputDomInfo), ctx(inputFunc.getModule()) {} /// Promote memory to registers. Return True on change. bool run(); }; } // end anonymous namespace /// Returns true if \p I is an address of a LoadInst, skipping struct and /// tuple address projections. Sets \p singleBlock to null if the load (or /// it's address is not in \p singleBlock. /// This function looks for these patterns: /// 1. (load %ASI) /// 2. (load (struct_element_addr/tuple_element_addr/unchecked_addr_cast %ASI)) static bool isAddressForLoad(SILInstruction *load, SILBasicBlock *&singleBlock, bool &hasGuaranteedOwnership) { if (isa<LoadInst>(load)) { // SILMem2Reg is disabled when we find: // (load [take] (struct_element_addr/tuple_element_addr %ASI)) // struct_element_addr and tuple_element_addr are lowered into // struct_extract and tuple_extract and these SIL instructions have a // guaranteed ownership. For replacing load's users, we need an owned value. // We will need a new copy and destroy of the running val placed after the // last use. This is not implemented currently. if (hasGuaranteedOwnership && cast<LoadInst>(load)->getOwnershipQualifier() == LoadOwnershipQualifier::Take) { return false; } return true; } if (!isa<UncheckedAddrCastInst>(load) && !isa<StructElementAddrInst>(load) && !isa<TupleElementAddrInst>(load)) return false; if (isa<StructElementAddrInst>(load) || isa<TupleElementAddrInst>(load)) { hasGuaranteedOwnership = true; } // Recursively search for other (non-)loads in the instruction's uses. for (auto *use : cast<SingleValueInstruction>(load)->getUses()) { SILInstruction *user = use->getUser(); if (user->getParent() != singleBlock) singleBlock = nullptr; if (!isAddressForLoad(user, singleBlock, hasGuaranteedOwnership)) return false; } return true; } /// Returns true if \p I is a dead struct_element_addr or tuple_element_addr. static bool isDeadAddrProjection(SILInstruction *inst) { if (!isa<UncheckedAddrCastInst>(inst) && !isa<StructElementAddrInst>(inst) && !isa<TupleElementAddrInst>(inst)) return false; // Recursively search for uses which are dead themselves. for (auto UI : cast<SingleValueInstruction>(inst)->getUses()) { SILInstruction *II = UI->getUser(); if (!isDeadAddrProjection(II)) return false; } return true; } /// Returns true if this AllocStacks is captured. /// Sets \p inSingleBlock to true if all uses of \p ASI are in a single block. static bool isCaptured(AllocStackInst *asi, bool &inSingleBlock) { SILBasicBlock *singleBlock = asi->getParent(); // For all users of the AllocStack instruction. for (auto *use : asi->getUses()) { SILInstruction *user = use->getUser(); if (user->getParent() != singleBlock) singleBlock = nullptr; // Loads are okay. bool hasGuaranteedOwnership = false; if (isAddressForLoad(user, singleBlock, hasGuaranteedOwnership)) continue; // We can store into an AllocStack (but not the pointer). if (auto *si = dyn_cast<StoreInst>(user)) if (si->getDest() == asi) continue; // Deallocation is also okay, as are DebugValue w/ address value. We will // promote the latter into normal DebugValue. if (isa<DeallocStackInst>(user) || DebugValueInst::hasAddrVal(user)) continue; // Destroys of loadable types can be rewritten as releases, so // they are fine. if (auto *dai = dyn_cast<DestroyAddrInst>(user)) if (dai->getOperand()->getType().isLoadable(*dai->getFunction())) continue; // Other instructions are assumed to capture the AllocStack. LLVM_DEBUG(llvm::dbgs() << "*** AllocStack is captured by: " << *user); return true; } // None of the users capture the AllocStack. inSingleBlock = (singleBlock != nullptr); return false; } /// Returns true if the AllocStack is only stored into. bool MemoryToRegisters::isWriteOnlyAllocation(AllocStackInst *asi) { // For all users of the AllocStack: for (auto *use : asi->getUses()) { SILInstruction *user = use->getUser(); // It is okay to store into this AllocStack. if (auto *si = dyn_cast<StoreInst>(user)) if (!isa<AllocStackInst>(si->getSrc())) continue; // Deallocation is also okay. if (isa<DeallocStackInst>(user)) continue; // If we haven't already promoted the AllocStack, we may see // DebugValue uses. if (DebugValueInst::hasAddrVal(user)) continue; if (isDeadAddrProjection(user)) continue; // Can't do anything else with it. LLVM_DEBUG(llvm::dbgs() << "*** AllocStack has non-write use: " << *user); return false; } return true; } void MemoryToRegisters::removeSingleBlockAllocation(AllocStackInst *asi) { LLVM_DEBUG(llvm::dbgs() << "*** Promoting in-block: " << *asi); SILBasicBlock *parentBlock = asi->getParent(); // The default value of the AllocStack is NULL because we don't have // uninitialized variables in Swift. Optional<StorageStateTracking<LiveValues>> runningVals; // For all instructions in the block. for (auto bbi = parentBlock->begin(), bbe = parentBlock->end(); bbi != bbe;) { SILInstruction *inst = &*bbi; ++bbi; // Remove instructions that we are loading from. Replace the loaded value // with our running value. if (isLoadFromStack(inst, asi)) { if (!runningVals) { // Loading without a previous store is only acceptable if the type is // Void (= empty tuple) or a tuple of Voids. runningVals = { LiveValues::toReplace(asi, /*replacement=*/createValueForEmptyTuple( asi->getElementType(), inst, ctx)), /*isStorageValid=*/true}; } assert(runningVals && runningVals->isStorageValid); if (cast<LoadInst>(inst)->getOwnershipQualifier() == LoadOwnershipQualifier::Take) { if (shouldAddLexicalLifetime(asi)) { // End the lexical lifetime at a load [take]. The storage is no // longer keeping the value alive. endLexicalLifetimeBeforeInst(asi, /*beforeInstruction=*/inst, ctx, runningVals->value); } runningVals->isStorageValid = false; } replaceLoad(cast<LoadInst>(inst), runningVals->value.replacement(asi), asi, ctx, deleter, instructionsToDelete); ++NumInstRemoved; continue; } // Remove stores and record the value that we are saving as the running // value. if (auto *si = dyn_cast<StoreInst>(inst)) { if (si->getDest() == asi) { if (si->getOwnershipQualifier() == StoreOwnershipQualifier::Assign) { assert(runningVals && runningVals->isStorageValid); SILBuilderWithScope(si, ctx).createDestroyValue( si->getLoc(), runningVals->value.replacement(asi)); } auto oldRunningVals = runningVals; runningVals = {LiveValues::toReplace(asi, /*replacement=*/si->getSrc()), /*isStorageValid=*/true}; if (shouldAddLexicalLifetime(asi)) { if (oldRunningVals && oldRunningVals->isStorageValid) { endLexicalLifetimeBeforeInst(asi, /*beforeInstruction=*/si, ctx, oldRunningVals->value); } runningVals = beginLexicalLifetimeAfterStore(asi, si); } deleter.forceDelete(inst); ++NumInstRemoved; continue; } } // Replace debug_value w/ address value with debug_value of // the promoted value. if (auto *dvi = DebugValueInst::hasAddrVal(inst)) { if (dvi->getOperand() == asi) { if (runningVals) { promoteDebugValueAddr(dvi, runningVals->value.replacement(asi), ctx, deleter); } else { // Drop debug_value of uninitialized void values. assert(asi->getElementType().isVoid() && "Expected initialization of non-void type!"); deleter.forceDelete(dvi); } } continue; } // Replace destroys with a release of the value. if (auto *dai = dyn_cast<DestroyAddrInst>(inst)) { if (dai->getOperand() == asi) { assert(runningVals && runningVals->isStorageValid); replaceDestroy(dai, runningVals->value.replacement(asi), ctx, deleter, instructionsToDelete); if (shouldAddLexicalLifetime(asi)) { endLexicalLifetimeBeforeInst(asi, /*beforeInstruction=*/dai, ctx, runningVals->value); } runningVals->isStorageValid = false; } continue; } // Remove deallocation. if (auto *dsi = dyn_cast<DeallocStackInst>(inst)) { if (dsi->getOperand() == asi) { deleter.forceDelete(inst); NumInstRemoved++; // No need to continue scanning after deallocation. break; } } // Remove dead address instructions that may be uses of the allocation. auto *addrInst = dyn_cast<SingleValueInstruction>(inst); while (addrInst && addrInst->use_empty() && (isa<StructElementAddrInst>(addrInst) || isa<TupleElementAddrInst>(addrInst) || isa<UncheckedAddrCastInst>(addrInst))) { SILValue op = addrInst->getOperand(0); deleter.forceDelete(addrInst); ++NumInstRemoved; addrInst = dyn_cast<SingleValueInstruction>(op); } } if (runningVals && runningVals->isStorageValid && shouldAddLexicalLifetime(asi)) { // There is still valid storage after visiting all instructions in this // block which are the only instructions involving this alloc_stack. // This can only happen if all paths from this block end in unreachable. // // We need to end the lexical lifetime at the last possible location, either // just before an unreachable instruction or just before a branch to a block // that is not dominated by parentBlock. // Walk forward from parentBlock until finding blocks which either // (1) terminate in unreachable // (2) have successors which are not dominated by parentBlock GraphNodeWorklist<SILBasicBlock *, 2> worklist; worklist.initialize(parentBlock); while (auto *block = worklist.pop()) { auto *terminator = block->getTerminator(); if (isa<UnreachableInst>(terminator)) { endLexicalLifetimeBeforeInst(asi, /*beforeInstruction=*/terminator, ctx, runningVals->value); continue; } bool endedLifetime = false; for (auto *successor : block->getSuccessorBlocks()) { if (!domInfo->dominates(parentBlock, successor)) { endLexicalLifetimeBeforeInst(asi, /*beforeInstruction=*/terminator, ctx, runningVals->value); endedLifetime = true; break; } } if (endedLifetime) { continue; } for (auto *successor : block->getSuccessorBlocks()) { worklist.insert(successor); } } } } /// Attempt to promote the specified stack allocation, returning true if so /// or false if not. On success, this returns true and usually drops all of the /// uses of the AllocStackInst, but never deletes the ASI itself. Callers /// should check to see if the ASI is dead after this and remove it if so. bool MemoryToRegisters::promoteSingleAllocation(AllocStackInst *alloc) { LLVM_DEBUG(llvm::dbgs() << "*** Memory to register looking at: " << *alloc); ++NumAllocStackFound; // In OSSA, don't do Mem2Reg on non-trivial alloc_stack with dynamic_lifetime. if (alloc->hasDynamicLifetime() && f.hasOwnership() && !alloc->getType().isTrivial(f)) { return false; } // Don't handle captured AllocStacks. bool inSingleBlock = false; if (isCaptured(alloc, inSingleBlock)) { ++NumAllocStackCaptured; return false; } // Remove write-only AllocStacks. if (isWriteOnlyAllocation(alloc) && !shouldAddLexicalLifetime(alloc)) { deleter.forceDeleteWithUsers(alloc); LLVM_DEBUG(llvm::dbgs() << "*** Deleting store-only AllocStack: "<< *alloc); return true; } // For AllocStacks that are only used within a single basic blocks, use // the linear sweep to remove the AllocStack. if (inSingleBlock) { removeSingleBlockAllocation(alloc); LLVM_DEBUG(llvm::dbgs() << "*** Deleting single block AllocStackInst: " << *alloc); if (alloc->use_empty()) { deleter.forceDelete(alloc); } else { // Handle a corner case where the ASI still has uses: // This can come up if the source contains a withUnsafePointer where // the pointer escapes. It's illegal code but we should not crash. // Re-insert a dealloc_stack so that the verifier is happy. auto *next = alloc->getNextInstruction(); SILBuilderWithScope b(next, ctx); b.createDeallocStack(next->getLoc(), alloc); } return true; } LLVM_DEBUG(llvm::dbgs() << "*** Need to insert BB arguments for " << *alloc); // Promote this allocation, lazily computing dom tree levels for this function // if we have not done so yet. auto &domTreeLevels = getDomTreeLevels(); StackAllocationPromoter(alloc, domInfo, domTreeLevels, ctx, deleter, instructionsToDelete) .run(); // Make sure that all of the allocations were promoted into registers. assert(isWriteOnlyAllocation(alloc) && "Non-write uses left behind"); // ... and erase the allocation. deleter.forceDeleteWithUsers(alloc); return true; } bool MemoryToRegisters::run() { bool madeChange = false; if (f.getModule().getOptions().VerifyAll) f.verifyCriticalEdges(); for (auto &block : f) { // Don't waste time optimizing unreachable blocks. if (!domInfo->isReachableFromEntry(&block)) { continue; } for (SILInstruction *inst : deleter.updatingReverseRange(&block)) { auto *asi = dyn_cast<AllocStackInst>(inst); if (!asi) continue; if (promoteSingleAllocation(asi)) { for (auto *inst : instructionsToDelete) { deleter.forceDelete(inst); } instructionsToDelete.clear(); ++NumInstRemoved; madeChange = true; } } } return madeChange; } //===----------------------------------------------------------------------===// // Top Level Entrypoint //===----------------------------------------------------------------------===// namespace { class SILMem2Reg : public SILFunctionTransform { void run() override { SILFunction *f = getFunction(); LLVM_DEBUG(llvm::dbgs() << "** Mem2Reg on function: " << f->getName() << " **\n"); auto *da = PM->getAnalysis<DominanceAnalysis>(); bool madeChange = MemoryToRegisters(*f, da->get(f)).run(); if (madeChange) invalidateAnalysis(SILAnalysis::InvalidationKind::Instructions); } }; } // end anonymous namespace SILTransform *swift::createMem2Reg() { return new SILMem2Reg(); }
#include <QtGlobal> // Automatically generated by extract_strings.py #ifdef __GNUC__ #define UNUSED __attribute__((unused)) #else #define UNUSED #endif static const char UNUSED *gaon_strings[] = { QT_TRANSLATE_NOOP("gaon-core", "" "(1 = keep tx meta data e.g. account owner and payment request information, 2 " "= drop tx meta data)"), QT_TRANSLATE_NOOP("gaon-core", "" "-fallbackfee is set very high! This is the transaction fee you may pay when " "fee estimates are not available."), QT_TRANSLATE_NOOP("gaon-core", "" "-maxtxfee is set very high! Fees this large could be paid on a single " "transaction."), QT_TRANSLATE_NOOP("gaon-core", "" "-paytxfee is set very high! This is the transaction fee you will pay if you " "send a transaction."), QT_TRANSLATE_NOOP("gaon-core", "" "A fee rate (in %s/kB) that will be used when fee estimation has insufficient " "data (default: %s)"), QT_TRANSLATE_NOOP("gaon-core", "" "Accept relayed transactions received from whitelisted peers even when not " "relaying transactions (default: %d)"), QT_TRANSLATE_NOOP("gaon-core", "" "Allow JSON-RPC connections from specified source. Valid for <ip> are a " "single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or " "a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times"), QT_TRANSLATE_NOOP("gaon-core", "" "Bind to given address and always listen on it. Use [host]:port notation for " "IPv6"), QT_TRANSLATE_NOOP("gaon-core", "" "Bind to given address and whitelist peers connecting to it. Use [host]:port " "notation for IPv6"), QT_TRANSLATE_NOOP("gaon-core", "" "Bind to given address to listen for JSON-RPC connections. Use [host]:port " "notation for IPv6. This option can be specified multiple times (default: " "bind to all interfaces)"), QT_TRANSLATE_NOOP("gaon-core", "" "Cannot obtain a lock on data directory %s. Gaon Core is probably already " "running."), QT_TRANSLATE_NOOP("gaon-core", "" "Create new files with system default permissions, instead of umask 077 (only " "effective with disabled wallet functionality)"), QT_TRANSLATE_NOOP("gaon-core", "" "Delete all wallet transactions and only recover those parts of the " "blockchain through -rescan on startup"), QT_TRANSLATE_NOOP("gaon-core", "" "Disable all Gaon specific functionality (Masternodes, PrivateSend, " "InstantSend, Governance) (0-1, default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "" "Discover own IP addresses (default: 1 when listening and no -externalip or -" "proxy)"), QT_TRANSLATE_NOOP("gaon-core", "" "Distributed under the MIT software license, see the accompanying file " "COPYING or <http://www.opensource.org/licenses/mit-license.php>."), QT_TRANSLATE_NOOP("gaon-core", "" "Do not keep transactions in the mempool longer than <n> hours (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "" "Enable InstantSend, show confirmations for locked transactions (0-1, " "default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "" "Enable multiple PrivateSend mixing sessions per block, experimental (0-1, " "default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "" "Enable use of automated PrivateSend for funds stored in this wallet (0-1, " "default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "" "Error reading wallet.dat! All keys read correctly, but transaction data or " "address book entries might be missing or incorrect."), QT_TRANSLATE_NOOP("gaon-core", "" "Error: Listening for incoming connections failed (listen returned error %s)"), QT_TRANSLATE_NOOP("gaon-core", "" "Execute command when a relevant alert is received or we see a really long " "fork (%s in cmd is replaced by message)"), QT_TRANSLATE_NOOP("gaon-core", "" "Execute command when a wallet InstantSend transaction is successfully locked " "(%s in cmd is replaced by TxID)"), QT_TRANSLATE_NOOP("gaon-core", "" "Execute command when a wallet transaction changes (%s in cmd is replaced by " "TxID)"), QT_TRANSLATE_NOOP("gaon-core", "" "Execute command when the best block changes (%s in cmd is replaced by block " "hash)"), QT_TRANSLATE_NOOP("gaon-core", "" "Failed to create backup, file already exists! This could happen if you " "restarted wallet in less than 60 seconds. You can continue if you are ok " "with this."), QT_TRANSLATE_NOOP("gaon-core", "" "Fees (in %s/kB) smaller than this are considered zero fee for relaying, " "mining and transaction creation (default: %s)"), QT_TRANSLATE_NOOP("gaon-core", "" "Fees (in %s/kB) smaller than this are considered zero fee for transaction " "creation (default: %s)"), QT_TRANSLATE_NOOP("gaon-core", "" "Force relay of transactions from whitelisted peers even they violate local " "relay policy (default: %d)"), QT_TRANSLATE_NOOP("gaon-core", "" "Found unconfirmed denominated outputs, will wait till they confirm to " "continue."), QT_TRANSLATE_NOOP("gaon-core", "" "How thorough the block verification of -checkblocks is (0-4, default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "" "If <category> is not supplied or if <category> = 1, output all debugging " "information."), QT_TRANSLATE_NOOP("gaon-core", "" "If paytxfee is not set, include enough fee so transactions begin " "confirmation on average within n blocks (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "" "InstantSend doesn't support sending values that high yet. Transactions are " "currently limited to %1 GAON."), QT_TRANSLATE_NOOP("gaon-core", "" "InstantSend requires inputs with at least %d confirmations, you might need " "to wait a few minutes and try again."), QT_TRANSLATE_NOOP("gaon-core", "" "Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay " "fee of %s to prevent stuck transactions)"), QT_TRANSLATE_NOOP("gaon-core", "" "Maintain a full address index, used to query for the balance, txids and " "unspent outputs for addresses (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "" "Maintain a full spent index, used to query the spending txid and input index " "for an outpoint (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "" "Maintain a full transaction index, used by the getrawtransaction rpc call " "(default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "" "Maintain a timestamp index for block hashes, used to query blocks hashes by " "a range of timestamps (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "" "Maintain at most <n> connections to peers (temporary service connections " "excluded) (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "" "Maximum size of data in data carrier transactions we relay and mine " "(default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "" "Maximum total fees (in %s) to use in a single wallet transaction; setting " "this too low may abort large transactions (default: %s)"), QT_TRANSLATE_NOOP("gaon-core", "" "Name to construct url for KeePass entry that stores the wallet passphrase"), QT_TRANSLATE_NOOP("gaon-core", "" "Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "" "Output debugging information (default: %u, supplying <category> is optional)"), QT_TRANSLATE_NOOP("gaon-core", "" "Please check that your computer's date and time are correct! If your clock " "is wrong Gaon Core will not work properly."), QT_TRANSLATE_NOOP("gaon-core", "" "PrivateSend uses exact denominated amounts to send funds, you might simply " "need to anonymize some more coins."), QT_TRANSLATE_NOOP("gaon-core", "" "Provide liquidity to PrivateSend by infrequently mixing coins on a continual " "basis (0-100, default: %u, 1=very frequent, high fees, 100=very infrequent, " "low fees)"), QT_TRANSLATE_NOOP("gaon-core", "" "Prune configured below the minimum of %d MiB. Please use a higher number."), QT_TRANSLATE_NOOP("gaon-core", "" "Prune: last wallet synchronisation goes beyond pruned data. You need to -" "reindex (download the whole blockchain again in case of pruned node)"), QT_TRANSLATE_NOOP("gaon-core", "" "Query for peer addresses via DNS lookup, if low on addresses (default: 1 " "unless -connect)"), QT_TRANSLATE_NOOP("gaon-core", "" "Randomize credentials for every proxy connection. This enables Tor stream " "isolation (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "" "Reduce storage requirements by pruning (deleting) old blocks. This mode is " "incompatible with -txindex and -rescan. Warning: Reverting this setting " "requires re-downloading the entire blockchain. (default: 0 = disable pruning " "blocks, >%u = target size in MiB to use for block files)"), QT_TRANSLATE_NOOP("gaon-core", "" "Rescans are not possible in pruned mode. You will need to use -reindex which " "will download the whole blockchain again."), QT_TRANSLATE_NOOP("gaon-core", "" "Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"), QT_TRANSLATE_NOOP("gaon-core", "" "Set the number of script verification threads (%u to %d, 0 = auto, <0 = " "leave that many cores free, default: %d)"), QT_TRANSLATE_NOOP("gaon-core", "" "Set the number of threads for coin generation if enabled (-1 = all cores, " "default: %d)"), QT_TRANSLATE_NOOP("gaon-core", "" "Show N confirmations for a successfully locked transaction (0-9999, default: " "%u)"), QT_TRANSLATE_NOOP("gaon-core", "" "Specify full path to directory for automatic wallet backups (must exist)"), QT_TRANSLATE_NOOP("gaon-core", "" "Support filtering of blocks and transaction with bloom filters (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "" "The block database contains a block which appears to be from the future. " "This may be due to your computer's date and time being set incorrectly. Only " "rebuild the block database if you are sure that your computer's date and " "time are correct"), QT_TRANSLATE_NOOP("gaon-core", "" "The transaction amount is too small to send after the fee has been deducted"), QT_TRANSLATE_NOOP("gaon-core", "" "This is a pre-release test build - use at your own risk - do not use for " "mining or merchant applications"), QT_TRANSLATE_NOOP("gaon-core", "" "This product includes software developed by the OpenSSL Project for use in " "the OpenSSL Toolkit <https://www.openssl.org/> and cryptographic software " "written by Eric Young and UPnP software written by Thomas Bernard."), QT_TRANSLATE_NOOP("gaon-core", "" "Total length of network version string (%i) exceeds maximum length (%i). " "Reduce the number or size of uacomments."), QT_TRANSLATE_NOOP("gaon-core", "" "Tries to keep outbound traffic under the given target (in MiB per 24h), 0 = " "no limit (default: %d)"), QT_TRANSLATE_NOOP("gaon-core", "" "Unable to bind to %s on this computer. Gaon Core is probably already running."), QT_TRANSLATE_NOOP("gaon-core", "" "Unable to locate enough PrivateSend denominated funds for this transaction."), QT_TRANSLATE_NOOP("gaon-core", "" "Unable to locate enough PrivateSend non-denominated funds for this " "transaction that are not equal 1000 GAON."), QT_TRANSLATE_NOOP("gaon-core", "" "Unable to locate enough funds for this transaction that are not equal 1000 " "GAON."), QT_TRANSLATE_NOOP("gaon-core", "" "Unsupported argument -socks found. Setting SOCKS version isn't possible " "anymore, only SOCKS5 proxies are supported."), QT_TRANSLATE_NOOP("gaon-core", "" "Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/" "or -whitelistforcerelay."), QT_TRANSLATE_NOOP("gaon-core", "" "Use N separate masternodes for each denominated input to mix funds (2-16, " "default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "" "Use UPnP to map the listening port (default: 1 when listening and no -proxy)"), QT_TRANSLATE_NOOP("gaon-core", "" "Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: " "%s)"), QT_TRANSLATE_NOOP("gaon-core", "" "Username and hashed password for JSON-RPC connections. The field <userpw> " "comes in the format: <USERNAME>:<SALT>$<HASH>. A canonical python script is " "included in share/rpcuser. This option can be specified multiple times"), QT_TRANSLATE_NOOP("gaon-core", "" "WARNING! Failed to replenish keypool, please unlock your wallet to do so."), QT_TRANSLATE_NOOP("gaon-core", "" "WARNING: abnormally high number of blocks generated, %d blocks received in " "the last %d hours (%d expected)"), QT_TRANSLATE_NOOP("gaon-core", "" "WARNING: check your network connection, %d blocks received in the last %d " "hours (%d expected)"), QT_TRANSLATE_NOOP("gaon-core", "" "Wallet is locked, can't replenish keypool! Automatic backups and mixing are " "disabled, please unlock your wallet to replenish keypool."), QT_TRANSLATE_NOOP("gaon-core", "" "Warning: The network does not appear to fully agree! Some miners appear to " "be experiencing issues."), QT_TRANSLATE_NOOP("gaon-core", "" "Warning: Unknown block versions being mined! It's possible unknown rules are " "in effect"), QT_TRANSLATE_NOOP("gaon-core", "" "Warning: We do not appear to fully agree with our peers! You may need to " "upgrade, or other nodes may need to upgrade."), QT_TRANSLATE_NOOP("gaon-core", "" "Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as " "wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect " "you should restore from a backup."), QT_TRANSLATE_NOOP("gaon-core", "" "Whitelist peers connecting from the given netmask or IP address. Can be " "specified multiple times."), QT_TRANSLATE_NOOP("gaon-core", "" "Whitelisted peers cannot be DoS banned and their transactions are always " "relayed, even if they are already in the mempool, useful e.g. for a gateway"), QT_TRANSLATE_NOOP("gaon-core", "" "You must specify a masternodeprivkey in the configuration. Please see " "documentation for help."), QT_TRANSLATE_NOOP("gaon-core", "" "You need to rebuild the database using -reindex to go back to unpruned " "mode. This will redownload the entire blockchain"), QT_TRANSLATE_NOOP("gaon-core", "" "masternodeaddr option is deprecated. Please use masternode.conf to manage " "your remote masternodes."), QT_TRANSLATE_NOOP("gaon-core", "%s - %d confirmations"), QT_TRANSLATE_NOOP("gaon-core", "(%d could be used only on mainnet)"), QT_TRANSLATE_NOOP("gaon-core", "(default: %s)"), QT_TRANSLATE_NOOP("gaon-core", "(default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "(must be %d for mainnet)"), QT_TRANSLATE_NOOP("gaon-core", "-maxmempool must be at least %d MB"), QT_TRANSLATE_NOOP("gaon-core", "<category> can be:"), QT_TRANSLATE_NOOP("gaon-core", "Accept command line and JSON-RPC commands"), QT_TRANSLATE_NOOP("gaon-core", "Accept connections from outside (default: 1 if no -proxy or -connect)"), QT_TRANSLATE_NOOP("gaon-core", "Accept public REST requests (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "Activating best chain..."), QT_TRANSLATE_NOOP("gaon-core", "Add a node to connect to and attempt to keep the connection open"), QT_TRANSLATE_NOOP("gaon-core", "Allow DNS lookups for -addnode, -seednode and -connect"), QT_TRANSLATE_NOOP("gaon-core", "Already have that input."), QT_TRANSLATE_NOOP("gaon-core", "Always query for peer addresses via DNS lookup (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "Append comment to the user agent string"), QT_TRANSLATE_NOOP("gaon-core", "Attempt to recover private keys from a corrupt wallet.dat on startup"), QT_TRANSLATE_NOOP("gaon-core", "Automatic backups disabled"), QT_TRANSLATE_NOOP("gaon-core", "Automatically create Tor hidden service (default: %d)"), QT_TRANSLATE_NOOP("gaon-core", "Block creation options:"), QT_TRANSLATE_NOOP("gaon-core", "Can't denominate: no compatible inputs left."), QT_TRANSLATE_NOOP("gaon-core", "Can't find random Masternode."), QT_TRANSLATE_NOOP("gaon-core", "Can't mix while sync in progress."), QT_TRANSLATE_NOOP("gaon-core", "Cannot downgrade wallet"), QT_TRANSLATE_NOOP("gaon-core", "Cannot resolve -bind address: '%s'"), QT_TRANSLATE_NOOP("gaon-core", "Cannot resolve -externalip address: '%s'"), QT_TRANSLATE_NOOP("gaon-core", "Cannot resolve -whitebind address: '%s'"), QT_TRANSLATE_NOOP("gaon-core", "Cannot write default address"), QT_TRANSLATE_NOOP("gaon-core", "Collateral not valid."), QT_TRANSLATE_NOOP("gaon-core", "Connect only to the specified node(s)"), QT_TRANSLATE_NOOP("gaon-core", "Connect through SOCKS5 proxy"), QT_TRANSLATE_NOOP("gaon-core", "Connect to KeePassHttp on port <port> (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "Connect to a node to retrieve peer addresses, and disconnect"), QT_TRANSLATE_NOOP("gaon-core", "Connection options:"), QT_TRANSLATE_NOOP("gaon-core", "Copyright (C) 2009-%i The Bitcoin Core Developers"), QT_TRANSLATE_NOOP("gaon-core", "Copyright (C) 2014-%i The Dash Core Developers"), QT_TRANSLATE_NOOP("gaon-core", "Copyright (C) 2017-%i The Gaon Core Developers"), QT_TRANSLATE_NOOP("gaon-core", "Corrupted block database detected"), QT_TRANSLATE_NOOP("gaon-core", "Could not parse masternode.conf"), QT_TRANSLATE_NOOP("gaon-core", "Debugging/Testing options:"), QT_TRANSLATE_NOOP("gaon-core", "Do not load the wallet and disable wallet RPC calls"), QT_TRANSLATE_NOOP("gaon-core", "Do you want to rebuild the block database now?"), QT_TRANSLATE_NOOP("gaon-core", "Done loading"), QT_TRANSLATE_NOOP("gaon-core", "ERROR! Failed to create automatic backup"), QT_TRANSLATE_NOOP("gaon-core", "Enable publish hash block in <address>"), QT_TRANSLATE_NOOP("gaon-core", "Enable publish hash transaction (locked via InstantSend) in <address>"), QT_TRANSLATE_NOOP("gaon-core", "Enable publish hash transaction in <address>"), QT_TRANSLATE_NOOP("gaon-core", "Enable publish raw block in <address>"), QT_TRANSLATE_NOOP("gaon-core", "Enable publish raw transaction (locked via InstantSend) in <address>"), QT_TRANSLATE_NOOP("gaon-core", "Enable publish raw transaction in <address>"), QT_TRANSLATE_NOOP("gaon-core", "Enable the client to act as a masternode (0-1, default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "Enable transaction replacement in the memory pool (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "Entries are full."), QT_TRANSLATE_NOOP("gaon-core", "Error connecting to Masternode."), QT_TRANSLATE_NOOP("gaon-core", "Error initializing block database"), QT_TRANSLATE_NOOP("gaon-core", "Error initializing wallet database environment %s!"), QT_TRANSLATE_NOOP("gaon-core", "Error loading block database"), QT_TRANSLATE_NOOP("gaon-core", "Error loading wallet.dat"), QT_TRANSLATE_NOOP("gaon-core", "Error loading wallet.dat: Wallet corrupted"), QT_TRANSLATE_NOOP("gaon-core", "Error loading wallet.dat: Wallet requires newer version of Gaon Core"), QT_TRANSLATE_NOOP("gaon-core", "Error opening block database"), QT_TRANSLATE_NOOP("gaon-core", "Error reading from database, shutting down."), QT_TRANSLATE_NOOP("gaon-core", "Error"), QT_TRANSLATE_NOOP("gaon-core", "Error: A fatal internal error occurred, see debug.log for details"), QT_TRANSLATE_NOOP("gaon-core", "Error: Disk space is low!"), QT_TRANSLATE_NOOP("gaon-core", "Failed to create backup %s!"), QT_TRANSLATE_NOOP("gaon-core", "Failed to create backup, error: %s"), QT_TRANSLATE_NOOP("gaon-core", "Failed to delete backup, error: %s"), QT_TRANSLATE_NOOP("gaon-core", "Failed to listen on any port. Use -listen=0 if you want this."), QT_TRANSLATE_NOOP("gaon-core", "Failed to parse host:port string"), QT_TRANSLATE_NOOP("gaon-core", "Fee (in %s/kB) to add to transactions you send (default: %s)"), QT_TRANSLATE_NOOP("gaon-core", "Found enough users, signing ( waiting %s )"), QT_TRANSLATE_NOOP("gaon-core", "Found enough users, signing ..."), QT_TRANSLATE_NOOP("gaon-core", "Generate coins (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "How many blocks to check at startup (default: %u, 0 = all)"), QT_TRANSLATE_NOOP("gaon-core", "Importing..."), QT_TRANSLATE_NOOP("gaon-core", "Imports blocks from external blk000??.dat file on startup"), QT_TRANSLATE_NOOP("gaon-core", "Include IP addresses in debug output (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "Incompatible mode."), QT_TRANSLATE_NOOP("gaon-core", "Incompatible version."), QT_TRANSLATE_NOOP("gaon-core", "Incorrect or no genesis block found. Wrong datadir for network?"), QT_TRANSLATE_NOOP("gaon-core", "Information"), QT_TRANSLATE_NOOP("gaon-core", "Initialization sanity check failed. Gaon Core is shutting down."), QT_TRANSLATE_NOOP("gaon-core", "Input is not valid."), QT_TRANSLATE_NOOP("gaon-core", "InstantSend options:"), QT_TRANSLATE_NOOP("gaon-core", "Insufficient funds."), QT_TRANSLATE_NOOP("gaon-core", "Invalid -onion address: '%s'"), QT_TRANSLATE_NOOP("gaon-core", "Invalid -proxy address: '%s'"), QT_TRANSLATE_NOOP("gaon-core", "Invalid amount for -fallbackfee=<amount>: '%s'"), QT_TRANSLATE_NOOP("gaon-core", "Invalid amount for -maxtxfee=<amount>: '%s'"), QT_TRANSLATE_NOOP("gaon-core", "Invalid amount for -minrelaytxfee=<amount>: '%s'"), QT_TRANSLATE_NOOP("gaon-core", "Invalid amount for -mintxfee=<amount>: '%s'"), QT_TRANSLATE_NOOP("gaon-core", "Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"), QT_TRANSLATE_NOOP("gaon-core", "Invalid amount for -paytxfee=<amount>: '%s'"), QT_TRANSLATE_NOOP("gaon-core", "Invalid masternodeprivkey. Please see documenation."), QT_TRANSLATE_NOOP("gaon-core", "Invalid netmask specified in -whitelist: '%s'"), QT_TRANSLATE_NOOP("gaon-core", "Invalid port detected in masternode.conf"), QT_TRANSLATE_NOOP("gaon-core", "Invalid script detected."), QT_TRANSLATE_NOOP("gaon-core", "KeePassHttp id for the established association"), QT_TRANSLATE_NOOP("gaon-core", "KeePassHttp key for AES encrypted communication with KeePass"), QT_TRANSLATE_NOOP("gaon-core", "Keep N GAON anonymized (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "Keep at most <n> unconnectable transactions in memory (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "Keep the transaction memory pool below <n> megabytes (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "Last PrivateSend was too recent."), QT_TRANSLATE_NOOP("gaon-core", "Last successful PrivateSend action was too recent."), QT_TRANSLATE_NOOP("gaon-core", "Line: %d"), QT_TRANSLATE_NOOP("gaon-core", "Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"), QT_TRANSLATE_NOOP("gaon-core", "Listen for connections on <port> (default: %u or testnet: %u)"), QT_TRANSLATE_NOOP("gaon-core", "Loading addresses..."), QT_TRANSLATE_NOOP("gaon-core", "Loading block index..."), QT_TRANSLATE_NOOP("gaon-core", "Loading fullfiled requests cache..."), QT_TRANSLATE_NOOP("gaon-core", "Loading governance cache..."), QT_TRANSLATE_NOOP("gaon-core", "Loading masternode cache..."), QT_TRANSLATE_NOOP("gaon-core", "Loading masternode payment cache..."), QT_TRANSLATE_NOOP("gaon-core", "Loading wallet... (%3.2f %%)"), QT_TRANSLATE_NOOP("gaon-core", "Loading wallet..."), QT_TRANSLATE_NOOP("gaon-core", "Location of the auth cookie (default: data dir)"), QT_TRANSLATE_NOOP("gaon-core", "Lock is already in place."), QT_TRANSLATE_NOOP("gaon-core", "Lock masternodes from masternode configuration file (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "Make the wallet broadcast transactions"), QT_TRANSLATE_NOOP("gaon-core", "Masternode cache is empty, skipping payments and governance cache..."), QT_TRANSLATE_NOOP("gaon-core", "Masternode options:"), QT_TRANSLATE_NOOP("gaon-core", "Masternode queue is full."), QT_TRANSLATE_NOOP("gaon-core", "Masternode:"), QT_TRANSLATE_NOOP("gaon-core", "Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "Minimum bytes per sigop in transactions we relay and mine (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "Missing input transaction information."), QT_TRANSLATE_NOOP("gaon-core", "Mixing in progress..."), QT_TRANSLATE_NOOP("gaon-core", "Need to specify a port with -whitebind: '%s'"), QT_TRANSLATE_NOOP("gaon-core", "No Masternodes detected."), QT_TRANSLATE_NOOP("gaon-core", "No compatible Masternode found."), QT_TRANSLATE_NOOP("gaon-core", "No errors detected."), QT_TRANSLATE_NOOP("gaon-core", "No funds detected in need of denominating."), QT_TRANSLATE_NOOP("gaon-core", "No matching denominations found for mixing."), QT_TRANSLATE_NOOP("gaon-core", "Node relay options:"), QT_TRANSLATE_NOOP("gaon-core", "Non-standard public key detected."), QT_TRANSLATE_NOOP("gaon-core", "Not compatible with existing transactions."), QT_TRANSLATE_NOOP("gaon-core", "Not enough file descriptors available."), QT_TRANSLATE_NOOP("gaon-core", "Not enough funds to anonymize."), QT_TRANSLATE_NOOP("gaon-core", "Not in the Masternode list."), QT_TRANSLATE_NOOP("gaon-core", "Number of automatic wallet backups (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "Only connect to nodes in network <net> (ipv4, ipv6 or onion)"), QT_TRANSLATE_NOOP("gaon-core", "Options:"), QT_TRANSLATE_NOOP("gaon-core", "Password for JSON-RPC connections"), QT_TRANSLATE_NOOP("gaon-core", "Port: %d"), QT_TRANSLATE_NOOP("gaon-core", "Prepend debug output with timestamp (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "Print version and exit"), QT_TRANSLATE_NOOP("gaon-core", "PrivateSend is idle."), QT_TRANSLATE_NOOP("gaon-core", "PrivateSend options:"), QT_TRANSLATE_NOOP("gaon-core", "PrivateSend request complete:"), QT_TRANSLATE_NOOP("gaon-core", "PrivateSend request incomplete:"), QT_TRANSLATE_NOOP("gaon-core", "Prune cannot be configured with a negative value."), QT_TRANSLATE_NOOP("gaon-core", "Prune mode is incompatible with -txindex."), QT_TRANSLATE_NOOP("gaon-core", "Pruning blockstore..."), QT_TRANSLATE_NOOP("gaon-core", "RPC server options:"), QT_TRANSLATE_NOOP("gaon-core", "Rebuild block chain index from current blk000??.dat files on startup"), QT_TRANSLATE_NOOP("gaon-core", "Receive and display P2P network alerts (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "Reducing -maxconnections from %d to %d, because of system limitations."), QT_TRANSLATE_NOOP("gaon-core", "Relay and mine data carrier transactions (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "Relay non-P2SH multisig (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "Rescan the block chain for missing wallet transactions on startup"), QT_TRANSLATE_NOOP("gaon-core", "Rescanning..."), QT_TRANSLATE_NOOP("gaon-core", "Run in the background as a daemon and accept commands"), QT_TRANSLATE_NOOP("gaon-core", "Send trace/debug info to console instead of debug.log file"), QT_TRANSLATE_NOOP("gaon-core", "Send trace/debug info to debug.log file (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "Send transactions as zero-fee transactions if possible (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "Session not complete!"), QT_TRANSLATE_NOOP("gaon-core", "Session timed out."), QT_TRANSLATE_NOOP("gaon-core", "Set database cache size in megabytes (%d to %d, default: %d)"), QT_TRANSLATE_NOOP("gaon-core", "Set key pool size to <n> (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "Set maximum block size in bytes (default: %d)"), QT_TRANSLATE_NOOP("gaon-core", "Set minimum block size in bytes (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "Set the masternode private key"), QT_TRANSLATE_NOOP("gaon-core", "Set the number of threads to service RPC calls (default: %d)"), QT_TRANSLATE_NOOP("gaon-core", "Show all debugging options (usage: --help -help-debug)"), QT_TRANSLATE_NOOP("gaon-core", "Shrink debug.log file on client startup (default: 1 when no -debug)"), QT_TRANSLATE_NOOP("gaon-core", "Signing transaction failed"), QT_TRANSLATE_NOOP("gaon-core", "Specify configuration file (default: %s)"), QT_TRANSLATE_NOOP("gaon-core", "Specify connection timeout in milliseconds (minimum: 1, default: %d)"), QT_TRANSLATE_NOOP("gaon-core", "Specify data directory"), QT_TRANSLATE_NOOP("gaon-core", "Specify masternode configuration file (default: %s)"), QT_TRANSLATE_NOOP("gaon-core", "Specify pid file (default: %s)"), QT_TRANSLATE_NOOP("gaon-core", "Specify wallet file (within data directory)"), QT_TRANSLATE_NOOP("gaon-core", "Specify your own public address"), QT_TRANSLATE_NOOP("gaon-core", "Spend unconfirmed change when sending transactions (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "Submitted following entries to masternode: %u / %d"), QT_TRANSLATE_NOOP("gaon-core", "Submitted to masternode, waiting for more entries ( %u / %d ) %s"), QT_TRANSLATE_NOOP("gaon-core", "Submitted to masternode, waiting in queue %s"), QT_TRANSLATE_NOOP("gaon-core", "Synchronization failed"), QT_TRANSLATE_NOOP("gaon-core", "Synchronization finished"), QT_TRANSLATE_NOOP("gaon-core", "Synchronization pending..."), QT_TRANSLATE_NOOP("gaon-core", "Synchronizing governance objects..."), QT_TRANSLATE_NOOP("gaon-core", "Synchronizing masternode payments..."), QT_TRANSLATE_NOOP("gaon-core", "Synchronizing masternodes..."), QT_TRANSLATE_NOOP("gaon-core", "Synchronizing sporks..."), QT_TRANSLATE_NOOP("gaon-core", "The transaction amount is too small to pay the fee"), QT_TRANSLATE_NOOP("gaon-core", "This help message"), QT_TRANSLATE_NOOP("gaon-core", "This is experimental software."), QT_TRANSLATE_NOOP("gaon-core", "This is not a Masternode."), QT_TRANSLATE_NOOP("gaon-core", "Threshold for disconnecting misbehaving peers (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "Too many %f denominations, removing."), QT_TRANSLATE_NOOP("gaon-core", "Tor control port password (default: empty)"), QT_TRANSLATE_NOOP("gaon-core", "Tor control port to use if onion listening enabled (default: %s)"), QT_TRANSLATE_NOOP("gaon-core", "Transaction amount too small"), QT_TRANSLATE_NOOP("gaon-core", "Transaction amounts must be positive"), QT_TRANSLATE_NOOP("gaon-core", "Transaction created successfully."), QT_TRANSLATE_NOOP("gaon-core", "Transaction fees are too high."), QT_TRANSLATE_NOOP("gaon-core", "Transaction not valid."), QT_TRANSLATE_NOOP("gaon-core", "Transaction too large for fee policy"), QT_TRANSLATE_NOOP("gaon-core", "Transaction too large"), QT_TRANSLATE_NOOP("gaon-core", "Unable to bind to %s on this computer (bind returned error %s)"), QT_TRANSLATE_NOOP("gaon-core", "Unable to sign spork message, wrong key?"), QT_TRANSLATE_NOOP("gaon-core", "Unable to start HTTP server. See debug log for details."), QT_TRANSLATE_NOOP("gaon-core", "Unknown network specified in -onlynet: '%s'"), QT_TRANSLATE_NOOP("gaon-core", "Unknown response."), QT_TRANSLATE_NOOP("gaon-core", "Unknown state: id = %u"), QT_TRANSLATE_NOOP("gaon-core", "Unsupported argument -benchmark ignored, use -debug=bench."), QT_TRANSLATE_NOOP("gaon-core", "Unsupported argument -debugnet ignored, use -debug=net."), QT_TRANSLATE_NOOP("gaon-core", "Unsupported argument -tor found, use -onion."), QT_TRANSLATE_NOOP("gaon-core", "Upgrade wallet to latest format on startup"), QT_TRANSLATE_NOOP("gaon-core", "Use KeePass 2 integration using KeePassHttp plugin (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "Use UPnP to map the listening port (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "User Agent comment (%s) contains unsafe characters."), QT_TRANSLATE_NOOP("gaon-core", "Username for JSON-RPC connections"), QT_TRANSLATE_NOOP("gaon-core", "Value more than PrivateSend pool maximum allows."), QT_TRANSLATE_NOOP("gaon-core", "Verifying blocks..."), QT_TRANSLATE_NOOP("gaon-core", "Verifying wallet..."), QT_TRANSLATE_NOOP("gaon-core", "Very low number of keys left: %d"), QT_TRANSLATE_NOOP("gaon-core", "Wallet %s resides outside data directory %s"), QT_TRANSLATE_NOOP("gaon-core", "Wallet is locked."), QT_TRANSLATE_NOOP("gaon-core", "Wallet needed to be rewritten: restart Gaon Core to complete"), QT_TRANSLATE_NOOP("gaon-core", "Wallet options:"), QT_TRANSLATE_NOOP("gaon-core", "Wallet window title"), QT_TRANSLATE_NOOP("gaon-core", "Warning"), QT_TRANSLATE_NOOP("gaon-core", "Warning: unknown new rules activated (versionbit %i)"), QT_TRANSLATE_NOOP("gaon-core", "Wasn't able to create wallet backup folder %s!"), QT_TRANSLATE_NOOP("gaon-core", "Whether to operate in a blocks only mode (default: %u)"), QT_TRANSLATE_NOOP("gaon-core", "Will retry..."), QT_TRANSLATE_NOOP("gaon-core", "You need to rebuild the database using -reindex to change -txindex"), QT_TRANSLATE_NOOP("gaon-core", "Your entries added successfully."), QT_TRANSLATE_NOOP("gaon-core", "Your transaction was accepted into the pool!"), QT_TRANSLATE_NOOP("gaon-core", "Zapping all transactions from wallet..."), QT_TRANSLATE_NOOP("gaon-core", "ZeroMQ notification options:"), QT_TRANSLATE_NOOP("gaon-core", "no mixing available."), QT_TRANSLATE_NOOP("gaon-core", "see debug.log for details."), QT_TRANSLATE_NOOP("gaon-core", "wallet.dat corrupt, salvage failed"), };
#ifndef BOOST_MPL_REMOVE_IF_HPP_INCLUDED #define BOOST_MPL_REMOVE_IF_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2000-2004 // Copyright David Abrahams 2003-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Id: remove_if.hpp 49267 2008-10-11 06:19:02Z agurtovoy $ // $Date: 2008-10-11 02:19:02 -0400 (Sat, 11 Oct 2008) $ // $Revision: 49267 $ #include <boost/mpl/fold.hpp> #include <boost/mpl/reverse_fold.hpp> #include <boost/mpl/eval_if.hpp> #include <boost/mpl/identity.hpp> #include <boost/mpl/protect.hpp> #include <boost/mpl/lambda.hpp> #include <boost/mpl/apply.hpp> #include <boost/mpl/aux_/inserter_algorithm.hpp> namespace boost { namespace mpl { namespace aux { template< typename Pred, typename InsertOp > struct remove_if_helper { template< typename Sequence, typename U > struct apply { typedef typename eval_if< typename apply1<Pred,U>::type , identity<Sequence> , apply2<InsertOp,Sequence,U> >::type type; }; }; template< typename Sequence , typename Predicate , typename Inserter > struct remove_if_impl : fold< Sequence , typename Inserter::state , protect< aux::remove_if_helper< typename lambda<Predicate>::type , typename Inserter::operation > > > { }; template< typename Sequence , typename Predicate , typename Inserter > struct reverse_remove_if_impl : reverse_fold< Sequence , typename Inserter::state , protect< aux::remove_if_helper< typename lambda<Predicate>::type , typename Inserter::operation > > > { }; } // namespace aux BOOST_MPL_AUX_INSERTER_ALGORITHM_DEF(3, remove_if) }} #endif // BOOST_MPL_REMOVE_IF_HPP_INCLUDED
#include <iostream> #include <cmath> using namespace std; int N; long long B; long long shift(long long x) { return x ^ ((x>>1) + ((x%2) << (N-1))); } int main() { cin>>N>>B; long long start=0; for (int i=1; i<=N; i++) { int x; cin>>x; start+= x * pow(2, N-i); } long long cur=start; long long first_seen[65538]; for (long long ml=B; ml>0; ml--) { first_seen[cur]=ml; cur=shift(cur); if (first_seen[cur] != 0) { ml %= (first_seen[cur]-ml+1); } } for (int i=N-1; i>=0; i--) { cout<<(cur>>i)%2<<'\n'; } }
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/common_runtime/function.h" #include "tensorflow/core/framework/dataset.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/partial_tensor_shape.h" #include "tensorflow/core/framework/stats_aggregator.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/kernels/data/captured_function.h" #include "tensorflow/core/kernels/data/dataset_utils.h" #include "tensorflow/core/kernels/data/stats_utils.h" #include "tensorflow/core/lib/gtl/cleanup.h" #include "tensorflow/core/lib/random/random.h" #include "tensorflow/core/lib/strings/str_util.h" namespace tensorflow { namespace data { namespace { // See documentation in ../../ops/dataset_ops.cc for a high-level // description of the following op. class FilterDatasetOp : public UnaryDatasetOpKernel { public: explicit FilterDatasetOp(OpKernelConstruction* ctx) : UnaryDatasetOpKernel(ctx) { OP_REQUIRES_OK(ctx, FunctionMetadata::Create( ctx, "predicate", /*params=*/{}, &func_metadata_)); OP_REQUIRES(ctx, func_metadata_->short_circuit_info().indices.size() <= 1, errors::InvalidArgument( "predicate function has more than one return value.")); } void MakeDataset(OpKernelContext* ctx, DatasetBase* input, DatasetBase** output) override { std::unique_ptr<CapturedFunction> captured_func; OP_REQUIRES_OK( ctx, CapturedFunction::Create(ctx, func_metadata_, "other_arguments", &captured_func)); *output = new Dataset(ctx, input, std::move(captured_func)); } private: class Dataset : public DatasetBase { public: Dataset(OpKernelContext* ctx, const DatasetBase* input, std::unique_ptr<CapturedFunction> captured_func) : DatasetBase(DatasetContext(ctx)), input_(input), captured_func_(std::move(captured_func)) { input_->Ref(); } ~Dataset() override { input_->Unref(); } std::unique_ptr<IteratorBase> MakeIteratorInternal( const string& prefix) const override { return absl::make_unique<Iterator>( Iterator::Params{this, strings::StrCat(prefix, "::Filter")}); } const DataTypeVector& output_dtypes() const override { return input_->output_dtypes(); } const std::vector<PartialTensorShape>& output_shapes() const override { return input_->output_shapes(); } string DebugString() const override { return "FilterDatasetOp::Dataset"; } protected: Status AsGraphDefInternal(SerializationContext* ctx, DatasetGraphDefBuilder* b, Node** output) const override { Node* input_graph_node; TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_graph_node)); std::vector<Node*> other_arguments; DataTypeVector other_arguments_types; TF_RETURN_IF_ERROR(captured_func_->AddToGraph(ctx, b, &other_arguments, &other_arguments_types)); AttrValue f; b->BuildAttrValue(captured_func_->func(), &f); AttrValue other_arguments_types_attr; b->BuildAttrValue(other_arguments_types, &other_arguments_types_attr); TF_RETURN_IF_ERROR(b->AddDataset( this, {{0, input_graph_node}}, {{1, other_arguments}}, {{"predicate", f}, {"Targuments", other_arguments_types_attr}}, output)); return Status::OK(); } private: class Iterator : public DatasetIterator<Dataset> { public: explicit Iterator(const Params& params) : DatasetIterator<Dataset>(params), filtered_elements_(0), dropped_elements_(0) {} Status Initialize(IteratorContext* ctx) override { TF_RETURN_IF_ERROR( dataset()->input_->MakeIterator(ctx, prefix(), &input_impl_)); return dataset()->captured_func_->Instantiate( ctx, &instantiated_captured_func_); } Status GetNextInternal(IteratorContext* ctx, std::vector<Tensor>* out_tensors, bool* end_of_sequence) override { // NOTE(mrry): This method is thread-safe as long as // `input_impl_` and `f` are thread-safe. However, if multiple // threads enter this method, outputs may be observed in a // non-deterministic order. auto stats_aggregator = ctx->stats_aggregator(); bool matched; do { { tf_shared_lock l(mu_); if (!input_impl_) { *end_of_sequence = true; return Status::OK(); } TF_RETURN_IF_ERROR( input_impl_->GetNext(ctx, out_tensors, end_of_sequence)); } if (*end_of_sequence) { mutex_lock l(mu_); input_impl_.reset(); return Status::OK(); } std::vector<Tensor> result; TF_RETURN_IF_ERROR(instantiated_captured_func_->RunWithBorrowedArgs( ctx, *out_tensors, &result)); if (result.size() != 1 || result[0].dtype() != DT_BOOL || result[0].NumElements() != 1) { return errors::InvalidArgument( "Filter predicate `f` must return a scalar bool."); } matched = result[0].scalar<bool>()(); if (!matched) { // Clear the output tensor list since it didn't match. out_tensors->clear(); if (stats_aggregator) { mutex_lock l(mu_); dropped_elements_++; stats_aggregator->AddScalar( stats_utils::DroppedElementsScalarName( dataset()->node_name()), static_cast<float>(dropped_elements_), num_elements()); stats_aggregator->IncrementCounter(dataset()->node_name(), stats_utils::kDroppedElements, static_cast<float>(1)); } } } while (!matched); // TODO(shivaniagrawal): add ratio of dropped_elements and // filtered_elements as a histogram. if (stats_aggregator) { mutex_lock l(mu_); filtered_elements_++; stats_aggregator->AddScalar( stats_utils::FilterdElementsScalarName(dataset()->node_name()), static_cast<float>(filtered_elements_), num_elements()); stats_aggregator->IncrementCounter(dataset()->node_name(), stats_utils::kFilteredElements, static_cast<float>(1)); } *end_of_sequence = false; return Status::OK(); } protected: std::shared_ptr<model::Node> CreateNode( IteratorContext* ctx, model::Node::Args args) const override { return model::MakeUnknownRatioNode(std::move(args)); } Status SaveInternal(IteratorStateWriter* writer) override { mutex_lock l(mu_); if (input_impl_) TF_RETURN_IF_ERROR(SaveInput(writer, input_impl_)); else TF_RETURN_IF_ERROR( writer->WriteScalar(full_name("input_impls_empty"), "")); TF_RETURN_IF_ERROR(writer->WriteScalar(full_name("filtered_elements"), filtered_elements_)); TF_RETURN_IF_ERROR(writer->WriteScalar(full_name("dropped_elements"), dropped_elements_)); return Status::OK(); } Status RestoreInternal(IteratorContext* ctx, IteratorStateReader* reader) override { mutex_lock l(mu_); if (reader->Contains(full_name("input_impls_empty"))) input_impl_.reset(); else TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_)); TF_RETURN_IF_ERROR(reader->ReadScalar(full_name("filtered_elements"), &filtered_elements_)); TF_RETURN_IF_ERROR(reader->ReadScalar(full_name("dropped_elements"), &dropped_elements_)); return Status::OK(); } private: mutex mu_; std::unique_ptr<IteratorBase> input_impl_ GUARDED_BY(mu_); int64 filtered_elements_ GUARDED_BY(mu_); int64 dropped_elements_ GUARDED_BY(mu_); std::unique_ptr<InstantiatedCapturedFunction> instantiated_captured_func_; }; const DatasetBase* const input_; const std::unique_ptr<CapturedFunction> captured_func_; }; private: std::shared_ptr<FunctionMetadata> func_metadata_ = nullptr; }; REGISTER_KERNEL_BUILDER(Name("FilterDataset").Device(DEVICE_CPU), FilterDatasetOp); } // namespace } // namespace data } // namespace tensorflow
/* Copyright (c) 2003-2010 Sony Pictures Imageworks Inc., et al. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Sony Pictures Imageworks nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <algorithm> #include <cstdio> #include <cstring> #include <iterator> #include <OpenColorIO/OpenColorIO.h> #include "ops/Lut1D/Lut1DOp.h" #include "ops/Lut3D/Lut3DOp.h" #include "ParseUtils.h" #include "pystring/pystring.h" #include "transforms/FileTransform.h" /* http://doc.iridas.com/index.php/LUT_Formats #comments start with '#' #title is currently ignored, but it's not an error to enter one TITLE "title" #LUT_1D_SIZE M or #LUT_3D_SIZE M #where M is the size of the texture #a 3D texture has the size M x M x M #e.g. LUT_3D_SIZE 16 creates a 16 x 16 x 16 3D texture LUT_3D_SIZE 2 #Default input value range (domain) is 0.0 (black) to 1.0 (white) #Specify other min/max values to map the cube to any custom input #range you wish to use, for example if you're working with HDR data DOMAIN_MIN 0.0 0.0 0.0 DOMAIN_MAX 1.0 1.0 1.0 #for 1D textures, the data is simply a list of floating point values, #three per line, in RGB order #for 3D textures, the data is also RGB, and ordered in such a way #that the red coordinate changes fastest, then the green coordinate, #and finally, the blue coordinate changes slowest: 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0 0.0 1.0 1.0 0.0 0.0 0.0 1.0 1.0 0.0 1.0 0.0 1.0 1.0 1.0 1.0 1.0 #Note that the LUT data is not limited to any particular range #and can contain values under 0.0 and over 1.0 #The processing application might however still clip the #output values to the 0.0 - 1.0 range, depending on the internal #precision of that application's pipeline #IRIDAS applications generally use a floating point pipeline #with little or no clipping */ OCIO_NAMESPACE_ENTER { namespace { class LocalCachedFile : public CachedFile { public: LocalCachedFile () : has1D(false), has3D(false) { lut1D = Lut1D::Create(); lut3D = Lut3D::Create(); }; ~LocalCachedFile() {}; bool has1D; bool has3D; // TODO: Switch to the OpData classes. Lut1DRcPtr lut1D; Lut3DRcPtr lut3D; }; typedef OCIO_SHARED_PTR<LocalCachedFile> LocalCachedFileRcPtr; class LocalFileFormat : public FileFormat { public: ~LocalFileFormat() {}; void getFormatInfo(FormatInfoVec & formatInfoVec) const override; CachedFileRcPtr read( std::istream & istream, const std::string & fileName) const override; void bake(const Baker & baker, const std::string & formatName, std::ostream & ostream) const override; void buildFileOps(OpRcPtrVec & ops, const Config& config, const ConstContextRcPtr & context, CachedFileRcPtr untypedCachedFile, const FileTransform& fileTransform, TransformDirection dir) const override; private: static void ThrowErrorMessage(const std::string & error, const std::string & fileName, int line, const std::string & lineContent); }; void LocalFileFormat::ThrowErrorMessage(const std::string & error, const std::string & fileName, int line, const std::string & lineContent) { std::ostringstream os; os << "Error parsing Iridas .cube file ("; os << fileName; os << "). "; if (-1 != line) { os << "At line (" << line << "): '"; os << lineContent << "'. "; } os << error; throw Exception(os.str().c_str()); } void LocalFileFormat::getFormatInfo(FormatInfoVec & formatInfoVec) const { FormatInfo info; info.name = "iridas_cube"; info.extension = "cube"; info.capabilities = FORMAT_CAPABILITY_READ | FORMAT_CAPABILITY_BAKE; formatInfoVec.push_back(info); } CachedFileRcPtr LocalFileFormat::read( std::istream & istream, const std::string & fileName) const { // this shouldn't happen if(!istream) { throw Exception ("File stream empty when trying to read Iridas .cube LUT"); } // Parse the file std::vector<float> raw; int size3d[] = { 0, 0, 0 }; int size1d = 0; bool in1d = false; bool in3d = false; float domain_min[] = { 0.0f, 0.0f, 0.0f }; float domain_max[] = { 1.0f, 1.0f, 1.0f }; { std::string line; StringVec parts; std::vector<float> tmpfloats; int lineNumber = 0; while(nextline(istream, line)) { ++lineNumber; // All lines starting with '#' are comments if(pystring::startswith(line,"#")) continue; // Strip, lowercase, and split the line pystring::split(pystring::lower(pystring::strip(line)), parts); if(parts.empty()) continue; if(pystring::lower(parts[0]) == "title") { // Optional, and currently unhandled } else if(pystring::lower(parts[0]) == "lut_1d_size") { if(parts.size() != 2 || !StringToInt( &size1d, parts[1].c_str())) { ThrowErrorMessage( "Malformed LUT_1D_SIZE tag.", fileName, lineNumber, line); } raw.reserve(3*size1d); in1d = true; } else if(pystring::lower(parts[0]) == "lut_2d_size") { ThrowErrorMessage( "Unsupported tag: 'LUT_2D_SIZE'.", fileName, lineNumber, line); } else if(pystring::lower(parts[0]) == "lut_3d_size") { int size = 0; if(parts.size() != 2 || !StringToInt( &size, parts[1].c_str())) { ThrowErrorMessage( "Malformed LUT_3D_SIZE tag.", fileName, lineNumber, line); } size3d[0] = size; size3d[1] = size; size3d[2] = size; raw.reserve(3*size3d[0]*size3d[1]*size3d[2]); in3d = true; } else if(pystring::lower(parts[0]) == "domain_min") { if(parts.size() != 4 || !StringToFloat( &domain_min[0], parts[1].c_str()) || !StringToFloat( &domain_min[1], parts[2].c_str()) || !StringToFloat( &domain_min[2], parts[3].c_str())) { ThrowErrorMessage( "Malformed DOMAIN_MIN tag.", fileName, lineNumber, line); } } else if(pystring::lower(parts[0]) == "domain_max") { if(parts.size() != 4 || !StringToFloat( &domain_max[0], parts[1].c_str()) || !StringToFloat( &domain_max[1], parts[2].c_str()) || !StringToFloat( &domain_max[2], parts[3].c_str())) { ThrowErrorMessage( "Malformed DOMAIN_MAX tag.", fileName, lineNumber, line); } } else { // It must be a float triple! if(!StringVecToFloatVec(tmpfloats, parts) || tmpfloats.size() != 3) { ThrowErrorMessage( "Malformed color triples specified.", fileName, lineNumber, line); } for(int i=0; i<3; ++i) { raw.push_back(tmpfloats[i]); } } } } // Interpret the parsed data, validate LUT sizes LocalCachedFileRcPtr cachedFile = LocalCachedFileRcPtr(new LocalCachedFile()); if(in1d) { if(size1d != static_cast<int>(raw.size()/3)) { std::ostringstream os; os << "Incorrect number of lut1d entries. "; os << "Found " << raw.size() / 3; os << ", expected " << size1d << "."; ThrowErrorMessage( os.str().c_str(), fileName, -1, ""); } // Reformat 1D data if(size1d>0) { cachedFile->has1D = true; memcpy(cachedFile->lut1D->from_min, domain_min, 3*sizeof(float)); memcpy(cachedFile->lut1D->from_max, domain_max, 3*sizeof(float)); for(int channel=0; channel<3; ++channel) { cachedFile->lut1D->luts[channel].resize(size1d); for(int i=0; i<size1d; ++i) { cachedFile->lut1D->luts[channel][i] = raw[3*i+channel]; } } // 1e-5 rel error is a good threshold when float numbers near 0 // are written out with 6 decimal places of precision. This is // a bit aggressive, I.e., changes in the 6th decimal place will // be considered roundoff error, but changes in the 5th decimal // will be considered LUT 'intent'. // 1.0 // 1.000005 equal to 1.0 // 1.000007 equal to 1.0 // 1.000010 not equal // 0.0 // 0.000001 not equal cachedFile->lut1D->maxerror = 1e-5f; cachedFile->lut1D->errortype = Lut1D::ERROR_RELATIVE; } } else if(in3d) { cachedFile->has3D = true; if(size3d[0]*size3d[1]*size3d[2] != static_cast<int>(raw.size()/3)) { std::ostringstream os; os << "Incorrect number of 3D LUT entries. "; os << "Found " << raw.size() / 3 << ", expected "; os << size3d[0] * size3d[1] * size3d[2] << "."; ThrowErrorMessage( os.str().c_str(), fileName, -1, ""); } // Reformat 3D data memcpy(cachedFile->lut3D->from_min, domain_min, 3*sizeof(float)); memcpy(cachedFile->lut3D->from_max, domain_max, 3*sizeof(float)); cachedFile->lut3D->size[0] = size3d[0]; cachedFile->lut3D->size[1] = size3d[1]; cachedFile->lut3D->size[2] = size3d[2]; cachedFile->lut3D->lut = raw; } else { ThrowErrorMessage( "LUT type (1D/3D) unspecified.", fileName, -1, ""); } return cachedFile; } void LocalFileFormat::bake(const Baker & baker, const std::string & formatName, std::ostream & ostream) const { static const int DEFAULT_CUBE_SIZE = 32; if(formatName != "iridas_cube") { std::ostringstream os; os << "Unknown cube format name, '"; os << formatName << "'."; throw Exception(os.str().c_str()); } ConstConfigRcPtr config = baker.getConfig(); int cubeSize = baker.getCubeSize(); if(cubeSize==-1) cubeSize = DEFAULT_CUBE_SIZE; cubeSize = std::max(2, cubeSize); // smallest cube is 2x2x2 std::vector<float> cubeData; cubeData.resize(cubeSize*cubeSize*cubeSize*3); GenerateIdentityLut3D(&cubeData[0], cubeSize, 3, LUT3DORDER_FAST_RED); PackedImageDesc cubeImg(&cubeData[0], cubeSize*cubeSize*cubeSize, 1, 3); // Apply our conversion from the input space to the output space. ConstProcessorRcPtr inputToTarget; std::string looks = baker.getLooks(); if(!looks.empty()) { LookTransformRcPtr transform = LookTransform::Create(); transform->setLooks(looks.c_str()); transform->setSrc(baker.getInputSpace()); transform->setDst(baker.getTargetSpace()); inputToTarget = config->getProcessor(transform, TRANSFORM_DIR_FORWARD); } else { inputToTarget = config->getProcessor(baker.getInputSpace(), baker.getTargetSpace()); } ConstCPUProcessorRcPtr cpu = inputToTarget->getDefaultCPUProcessor(); cpu->apply(cubeImg); if(baker.getMetadata() != NULL) { std::string metadata = baker.getMetadata(); StringVec metadatavec; pystring::split(pystring::strip(metadata), metadatavec, "\n"); if(metadatavec.size() > 0) { for(size_t i = 0; i < metadatavec.size(); ++i) { ostream << "# " << metadatavec[i] << "\n"; } ostream << "\n"; } } ostream << "LUT_3D_SIZE " << cubeSize << "\n"; if(cubeSize < 2) { throw Exception("Internal cube size exception"); } // Set to a fixed 6 decimal precision ostream.setf(std::ios::fixed, std::ios::floatfield); ostream.precision(6); for(int i=0; i<cubeSize*cubeSize*cubeSize; ++i) { ostream << cubeData[3*i+0] << " " << cubeData[3*i+1] << " " << cubeData[3*i+2] << "\n"; } } void LocalFileFormat::buildFileOps(OpRcPtrVec & ops, const Config& /*config*/, const ConstContextRcPtr & /*context*/, CachedFileRcPtr untypedCachedFile, const FileTransform& fileTransform, TransformDirection dir) const { LocalCachedFileRcPtr cachedFile = DynamicPtrCast<LocalCachedFile>(untypedCachedFile); // This should never happen. if(!cachedFile) { std::ostringstream os; os << "Cannot build Iridas .cube Op. Invalid cache type."; throw Exception(os.str().c_str()); } TransformDirection newDir = CombineTransformDirections(dir, fileTransform.getDirection()); if(newDir == TRANSFORM_DIR_UNKNOWN) { std::ostringstream os; os << "Cannot build file format transform,"; os << " unspecified transform direction."; throw Exception(os.str().c_str()); } // TODO: INTERP_LINEAR should not be hard-coded. // Instead query 'highest' interpolation? // (right now, it's linear). If cubic is added, consider // using it if(newDir == TRANSFORM_DIR_FORWARD) { if(cachedFile->has1D) { CreateLut1DOp(ops, cachedFile->lut1D, INTERP_LINEAR, newDir); } if(cachedFile->has3D) { CreateLut3DOp(ops, cachedFile->lut3D, fileTransform.getInterpolation(), newDir); } } else if(newDir == TRANSFORM_DIR_INVERSE) { if(cachedFile->has3D) { CreateLut3DOp(ops, cachedFile->lut3D, fileTransform.getInterpolation(), newDir); } if(cachedFile->has1D) { CreateLut1DOp(ops, cachedFile->lut1D, INTERP_LINEAR, newDir); } } } } FileFormat * CreateFileFormatIridasCube() { return new LocalFileFormat(); } } OCIO_NAMESPACE_EXIT /////////////////////////////////////////////////////////////////////////////// #ifdef OCIO_UNIT_TEST namespace OCIO = OCIO_NAMESPACE; #include "UnitTest.h" #include <fstream> OCIO_ADD_TEST(FileFormatIridasCube, FormatInfo) { OCIO::FormatInfoVec formatInfoVec; OCIO::LocalFileFormat tester; tester.getFormatInfo(formatInfoVec); OCIO_CHECK_EQUAL(1, formatInfoVec.size()); OCIO_CHECK_EQUAL("iridas_cube", formatInfoVec[0].name); OCIO_CHECK_EQUAL("cube", formatInfoVec[0].extension); OCIO_CHECK_EQUAL(OCIO::FORMAT_CAPABILITY_READ | OCIO::FORMAT_CAPABILITY_BAKE, formatInfoVec[0].capabilities); } OCIO::LocalCachedFileRcPtr ReadIridasCube(const std::string & fileContent) { std::istringstream is; is.str(fileContent); // Read file OCIO::LocalFileFormat tester; const std::string SAMPLE_NAME("Memory File"); OCIO::CachedFileRcPtr cachedFile = tester.read(is, SAMPLE_NAME); return OCIO::DynamicPtrCast<OCIO::LocalCachedFile>(cachedFile); } OCIO_ADD_TEST(FileFormatIridasCube, ReadFailure) { { // Validate stream can be read with no error. // Then stream will be altered to introduce errors. const std::string SAMPLE_NO_ERROR = "LUT_3D_SIZE 2\n" "DOMAIN_MIN 0.0 0.0 0.0\n" "DOMAIN_MAX 1.0 1.0 1.0\n" "0.0 0.0 0.0\n" "1.0 0.0 0.0\n" "0.0 1.0 0.0\n" "1.0 1.0 0.0\n" "0.0 0.0 1.0\n" "1.0 0.0 1.0\n" "0.0 1.0 1.0\n" "1.0 1.0 1.0\n"; OCIO_CHECK_NO_THROW(ReadIridasCube(SAMPLE_NO_ERROR)); } { // Wrong LUT_3D_SIZE tag const std::string SAMPLE_ERROR = "LUT_3D_SIZE 2 2\n" "DOMAIN_MIN 0.0 0.0 0.0\n" "DOMAIN_MAX 1.0 1.0 1.0\n" "0.0 0.0 0.0\n" "1.0 0.0 0.0\n" "0.0 1.0 0.0\n" "1.0 1.0 0.0\n" "0.0 0.0 1.0\n" "1.0 0.0 1.0\n" "0.0 1.0 1.0\n" "1.0 1.0 1.0\n"; OCIO_CHECK_THROW_WHAT(ReadIridasCube(SAMPLE_ERROR), OCIO::Exception, "Malformed LUT_3D_SIZE tag"); } { // Wrong DOMAIN_MIN tag const std::string SAMPLE_ERROR = "LUT_3D_SIZE 2\n" "DOMAIN_MIN 0.0 0.0\n" "DOMAIN_MAX 1.0 1.0 1.0\n" "0.0 0.0 0.0\n" "1.0 0.0 0.0\n" "0.0 1.0 0.0\n" "1.0 1.0 0.0\n" "0.0 0.0 1.0\n" "1.0 0.0 1.0\n" "0.0 1.0 1.0\n" "1.0 1.0 1.0\n"; OCIO_CHECK_THROW_WHAT(ReadIridasCube(SAMPLE_ERROR), OCIO::Exception, "Malformed DOMAIN_MIN tag"); } { // Wrong DOMAIN_MAX tag const std::string SAMPLE_ERROR = "LUT_3D_SIZE 2\n" "DOMAIN_MIN 0.0 0.0 0.0\n" "DOMAIN_MAX 1.0 1.0 1.0 1.0\n" "0.0 0.0 0.0\n" "1.0 0.0 0.0\n" "0.0 1.0 0.0\n" "1.0 1.0 0.0\n" "0.0 0.0 1.0\n" "1.0 0.0 1.0\n" "0.0 1.0 1.0\n" "1.0 1.0 1.0\n"; OCIO_CHECK_THROW_WHAT(ReadIridasCube(SAMPLE_ERROR), OCIO::Exception, "Malformed DOMAIN_MAX tag"); } { // Unexpected tag const std::string SAMPLE_ERROR = "LUT_3D_SIZE 2\n" "DOMAIN_MIN 0.0 0.0 0.0\n" "DOMAIN_MAX 1.0 1.0 1.0\n" "WRONG_TAG\n" "0.0 0.0 0.0\n" "1.0 0.0 0.0\n" "0.0 1.0 0.0\n" "1.0 1.0 0.0\n" "0.0 0.0 1.0\n" "1.0 0.0 1.0\n" "0.0 1.0 1.0\n" "1.0 1.0 1.0\n"; OCIO_CHECK_THROW_WHAT(ReadIridasCube(SAMPLE_ERROR), OCIO::Exception, "Malformed color triples specified"); } { // Wrong number of entries const std::string SAMPLE_ERROR = "LUT_3D_SIZE 2\n" "DOMAIN_MIN 0.0 0.0 0.0\n" "DOMAIN_MAX 1.0 1.0 1.0\n" "0.0 0.0 0.0\n" "1.0 0.0 0.0\n" "0.0 1.0 0.0\n" "1.0 1.0 0.0\n" "0.0 0.0 1.0\n" "1.0 0.0 1.0\n" "0.0 1.0 1.0\n" "0.0 1.0 1.0\n" "0.0 1.0 1.0\n" "1.0 1.0 1.0\n"; OCIO_CHECK_THROW_WHAT(ReadIridasCube(SAMPLE_ERROR), OCIO::Exception, "Incorrect number of 3D LUT entries"); } } OCIO_ADD_TEST(FileFormatIridasCube, no_shaper) { // check baker output OCIO::ConfigRcPtr config = OCIO::Config::Create(); { OCIO::ColorSpaceRcPtr cs = OCIO::ColorSpace::Create(); cs->setName("lnf"); cs->setFamily("lnf"); config->addColorSpace(cs); config->setRole(OCIO::ROLE_REFERENCE, cs->getName()); } { OCIO::ColorSpaceRcPtr cs = OCIO::ColorSpace::Create(); cs->setName("target"); cs->setFamily("target"); config->addColorSpace(cs); } std::ostringstream bout; bout << "# Alexa conversion LUT, logc2video. Full in/full out." << "\n"; bout << "# created by alexalutconv (2.11)" << "\n"; bout << "" << "\n"; bout << "LUT_3D_SIZE 2" << "\n"; bout << "0.000000 0.000000 0.000000" << "\n"; bout << "1.000000 0.000000 0.000000" << "\n"; bout << "0.000000 1.000000 0.000000" << "\n"; bout << "1.000000 1.000000 0.000000" << "\n"; bout << "0.000000 0.000000 1.000000" << "\n"; bout << "1.000000 0.000000 1.000000" << "\n"; bout << "0.000000 1.000000 1.000000" << "\n"; bout << "1.000000 1.000000 1.000000" << "\n"; OCIO::BakerRcPtr baker = OCIO::Baker::Create(); baker->setConfig(config); std::ostringstream metadata; metadata << "Alexa conversion LUT, logc2video. Full in/full out." << "\n"; metadata << "created by alexalutconv (2.11)" << "\n"; baker->setMetadata(metadata.str().c_str()); baker->setFormat("iridas_cube"); baker->setInputSpace("lnf"); baker->setTargetSpace("target"); baker->setCubeSize(2); std::ostringstream output; baker->bake(output); // std::vector<std::string> osvec; pystring::splitlines(output.str(), osvec); std::vector<std::string> resvec; pystring::splitlines(bout.str(), resvec); OCIO_CHECK_EQUAL(osvec.size(), resvec.size()); for(unsigned int i = 0; i < resvec.size(); ++i) { OCIO_CHECK_EQUAL(osvec[i], resvec[i]); } } #endif // OCIO_UNIT_TEST
/****************************************************************************** * Copyright (C) 2012 by Jerome Maye * * jerome.maye@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the Lesser GNU General Public License as published by* * the Free Software Foundation; either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * Lesser GNU General Public License for more details. * * * * You should have received a copy of the Lesser GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************/ #include "aslam/backend/SparseCholeskyLinearSolverOptions.h" namespace aslam { namespace backend { /******************************************************************************/ /* Constructors and Destructor */ /******************************************************************************/ SparseCholeskyLinearSolverOptions::SparseCholeskyLinearSolverOptions() {} SparseCholeskyLinearSolverOptions::SparseCholeskyLinearSolverOptions( const SparseCholeskyLinearSolverOptions& /* other */) { } SparseCholeskyLinearSolverOptions& SparseCholeskyLinearSolverOptions::operator = (const SparseCholeskyLinearSolverOptions& other) { if (this != &other) { } return *this; } SparseCholeskyLinearSolverOptions::~SparseCholeskyLinearSolverOptions() { } } }
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/password_manager/core/browser/credential_manager_pending_prevent_silent_access_task.h" #include "base/test/task_environment.h" #include "components/password_manager/core/browser/test_password_store.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace password_manager { namespace { class CredentialManagerPendingPreventSilentAccessTaskDelegateMock : public CredentialManagerPendingPreventSilentAccessTaskDelegate { public: CredentialManagerPendingPreventSilentAccessTaskDelegateMock() = default; ~CredentialManagerPendingPreventSilentAccessTaskDelegateMock() override = default; MOCK_METHOD(PasswordStore*, GetProfilePasswordStore, (), (override)); MOCK_METHOD(PasswordStore*, GetAccountPasswordStore, (), (override)); MOCK_METHOD(void, DoneRequiringUserMediation, (), (override)); }; } // namespace class CredentialManagerPendingPreventSilentAccessTaskTest : public ::testing::Test { public: CredentialManagerPendingPreventSilentAccessTaskTest() { profile_store_ = new TestPasswordStore(IsAccountStore(false)); profile_store_->Init(/*prefs=*/nullptr); account_store_ = new TestPasswordStore(IsAccountStore(true)); account_store_->Init(/*prefs=*/nullptr); } ~CredentialManagerPendingPreventSilentAccessTaskTest() override = default; void TearDown() override { account_store_->ShutdownOnUIThread(); profile_store_->ShutdownOnUIThread(); // It's needed to cleanup the password store asynchronously. task_environment_.RunUntilIdle(); } protected: testing::NiceMock<CredentialManagerPendingPreventSilentAccessTaskDelegateMock> delegate_mock_; scoped_refptr<TestPasswordStore> profile_store_; scoped_refptr<TestPasswordStore> account_store_; private: base::test::TaskEnvironment task_environment_; }; TEST_F(CredentialManagerPendingPreventSilentAccessTaskTest, ProfileStoreOnly) { ON_CALL(delegate_mock_, GetProfilePasswordStore) .WillByDefault(testing::Return(profile_store_.get())); ON_CALL(delegate_mock_, GetAccountPasswordStore) .WillByDefault(testing::Return(nullptr)); CredentialManagerPendingPreventSilentAccessTask task(&delegate_mock_); task.AddOrigin(PasswordStore::FormDigest(PasswordForm::Scheme::kHtml, /*signon_realm=*/"www.example.com", GURL("www.example.com"))); // We are expecting results from only one store, delegate should be called // upon getting a response from the store. EXPECT_CALL(delegate_mock_, DoneRequiringUserMediation); task.OnGetPasswordStoreResultsFrom(profile_store_.get(), {}); } TEST_F(CredentialManagerPendingPreventSilentAccessTaskTest, ProfileAndAccountStores) { ON_CALL(delegate_mock_, GetProfilePasswordStore) .WillByDefault(testing::Return(profile_store_.get())); ON_CALL(delegate_mock_, GetAccountPasswordStore) .WillByDefault(testing::Return(account_store_.get())); CredentialManagerPendingPreventSilentAccessTask task(&delegate_mock_); task.AddOrigin(PasswordStore::FormDigest(PasswordForm::Scheme::kHtml, /*signon_realm=*/"www.example.com", GURL("www.example.com"))); // We are expecting results from 2 stores, the delegate shouldn't be called // until both stores respond. EXPECT_CALL(delegate_mock_, DoneRequiringUserMediation).Times(0); task.OnGetPasswordStoreResultsFrom(profile_store_.get(), {}); testing::Mock::VerifyAndClearExpectations(&delegate_mock_); EXPECT_CALL(delegate_mock_, DoneRequiringUserMediation); task.OnGetPasswordStoreResultsFrom(account_store_.get(), {}); } } // namespace password_manager
#include <fstream> #include <gtest/gtest.h> #include "Fixtures.h" #include "config.h" #include "utils.h" using namespace std; using json = nlohmann::json; using namespace SpiceQL; TEST_F(TestConfig, FunctionalTestConfigConstruct) { json megaConfig = testConfig.globalConf(); ASSERT_EQ(megaConfig.size(), 28); } TEST_F(TestConfig, FunctionalTestConfigEval) { fs::path dbPath = getMissionConfigFile("clem1"); ifstream i(dbPath); nlohmann::json conf; i >> conf; MockRepository mocks; mocks.OnCallFunc(ls).Return(paths); mocks.OnCallFunc(getDataDirectory).Return("/isis_data/"); json config_eval_res = testConfig.get(); json pointer_eval_res = testConfig.get("/clem1"); json::json_pointer pointer = "/clem1/ck/reconstructed/kernels"_json_pointer; int expected_number = 4; ASSERT_EQ(config_eval_res[pointer].size(), expected_number); ASSERT_EQ(pointer_eval_res[pointer].size(), expected_number); ASSERT_EQ(testConfig[pointer].size(), 1); pointer = "/clem1/ck/smithed/kernels"_json_pointer; expected_number = 1; ASSERT_EQ(config_eval_res[pointer].size(), expected_number); ASSERT_EQ(pointer_eval_res[pointer].size(), expected_number); ASSERT_EQ(testConfig[pointer].size(), expected_number); pointer = "/clem1/spk/reconstructed/kernels"_json_pointer; expected_number = 2; ASSERT_EQ(config_eval_res[pointer].size(), expected_number); ASSERT_EQ(pointer_eval_res[pointer].size(), expected_number); ASSERT_EQ(testConfig[pointer].size(), 1); pointer = "/clem1/fk/kernels"_json_pointer; expected_number = 1; ASSERT_EQ(config_eval_res[pointer].size(), expected_number); ASSERT_EQ(pointer_eval_res[pointer].size(), expected_number); ASSERT_EQ(testConfig[pointer].size(), expected_number); pointer = "/clem1/sclk/kernels"_json_pointer; expected_number = 2; ASSERT_EQ(config_eval_res[pointer].size(), expected_number); ASSERT_EQ(pointer_eval_res[pointer].size(), expected_number); ASSERT_EQ(testConfig[pointer].size(), 1); pointer = "/uvvis/ik/kernels"_json_pointer; expected_number = 1; ASSERT_EQ(config_eval_res[pointer].size(), expected_number); ASSERT_EQ(testConfig[pointer].size(), expected_number); pointer = "/uvvis/iak/kernels"_json_pointer; expected_number = 2; ASSERT_EQ(config_eval_res[pointer].size(), expected_number); ASSERT_EQ(testConfig[pointer].size(), 1); } TEST_F(TestConfig, FunctionalTestConfigGlobalEval) { fs::path dbPath = getMissionConfigFile("clem1"); ifstream i(dbPath); nlohmann::json conf; i >> conf; MockRepository mocks; mocks.OnCallFunc(ls).Return(paths); mocks.OnCallFunc(getDataDirectory).Return("/isis_data/"); testConfig.get(); json config_eval_res = testConfig.globalConf(); json::json_pointer pointer = "/clem1/ck/reconstructed/kernels"_json_pointer; int expected_number = 1; ASSERT_EQ(config_eval_res[pointer].size(), expected_number); pointer = "/clem1/ck/smithed/kernels"_json_pointer; expected_number = 1; ASSERT_EQ(config_eval_res[pointer].size(), expected_number); pointer = "/clem1/spk/reconstructed/kernels"_json_pointer; expected_number = 1; ASSERT_EQ(config_eval_res[pointer].size(), expected_number); pointer = "/clem1/fk/kernels"_json_pointer; expected_number = 1; ASSERT_EQ(config_eval_res[pointer].size(), expected_number); pointer = "/clem1/sclk/kernels"_json_pointer; expected_number = 1; ASSERT_EQ(config_eval_res[pointer].size(), expected_number); pointer = "/uvvis/ik/kernels"_json_pointer; expected_number = 1; ASSERT_EQ(config_eval_res[pointer].size(), expected_number); pointer = "/uvvis/iak/kernels"_json_pointer; expected_number = 1; ASSERT_EQ(config_eval_res[pointer].size(), expected_number); } TEST_F(TestConfig, FunctionalTestConfigAccessors) { Config base = testConfig["base"]; Config base_pointer = testConfig["/base"]; MockRepository mocks; mocks.OnCallFunc(SpiceQL::ls).Return(paths); EXPECT_EQ(base.get()["lsk"]["kernels"].at(0), "/isis_data/base/kernels/sclk/naif0001.tls"); EXPECT_EQ(base_pointer.get()["lsk"]["kernels"].at(0), "/isis_data/base/kernels/sclk/naif0001.tls"); } TEST_F(TestConfig, FunctionalTestsConfigKeySearch) { vector<json::json_pointer> pointers = {"/my/first/pointer"_json_pointer, "/my/second/pointer"_json_pointer}; MockRepository mocks; mocks.OnCallFunc(SpiceQL::findKeyInJson).Return(pointers); vector<string> res_pointers = testConfig.findKey("kernels", true); int i = 0; for (auto pointer : res_pointers) { EXPECT_EQ(pointer, pointers[i++]); } }
//===- unittests/BuildSystem/LaneBasedExecutionQueueTest.cpp --------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "llbuild/Basic/FileSystem.h" #include "llbuild/BuildSystem/BuildExecutionQueue.h" #include "TempDir.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/FileSystem.h" #include "gtest/gtest.h" #include <atomic> #include <condition_variable> #include <ctime> #include <mutex> using namespace llbuild; using namespace llbuild::basic; using namespace llbuild::buildsystem; namespace { class DummyDelegate : public BuildExecutionQueueDelegate { public: DummyDelegate() {} virtual void commandJobStarted(Command* command) override {} virtual void commandJobFinished(Command* command) override {} virtual void commandProcessStarted(Command* command, ProcessHandle handle) override {} virtual void commandProcessHadError(Command* command, ProcessHandle handle, const Twine& message) override {} virtual void commandProcessHadOutput(Command* command, ProcessHandle handle, StringRef data) override {} virtual void commandProcessFinished(Command* command, ProcessHandle handle, CommandResult result, int exitStatus) override {} }; TEST(LaneBasedExecutionQueueTest, basic) { DummyDelegate delegate; std::unique_ptr<FileSystem> fs = createLocalFileSystem(); TmpDir tempDir{"LaneBasedExecutionQueueTest"}; std::string outputFile = tempDir.str() + "/yes-output.txt"; auto queue = std::unique_ptr<BuildExecutionQueue>( createLaneBasedExecutionQueue(delegate, 2, /*environment=*/nullptr)); auto fn = [&outputFile, &queue](QueueJobContext* context) { queue->executeShellCommand(context, "yes >" + outputFile); }; queue->addJob(QueueJob((Command*)0x1, fn)); // Busy wait until `outputFile` appears which indicates that `yes` is // running. time_t start = ::time(NULL); while (fs->getFileInfo(outputFile).isMissing()) { if (::time(NULL) > start + 5) { // We can't fail gracefully because the `LaneBasedExecutionQueue` will // always wait for spawned processes to exit abort(); } } queue->cancelAllJobs(); queue.reset(); } TEST(LaneBasedExecutionQueueTest, exhaustsQueueAfterCancellation) { DummyDelegate delegate; auto queue = std::unique_ptr<BuildExecutionQueue>( createLaneBasedExecutionQueue(delegate, 1, /*environment=*/nullptr)); bool buildStarted { false }; std::condition_variable buildStartedCondition; std::mutex buildStartedMutex; std::atomic<int> executions { 0 }; auto fn = [&buildStarted, &buildStartedCondition, &buildStartedMutex, &executions, &queue](QueueJobContext* context) { executions++; if (queue) { queue->cancelAllJobs(); } std::unique_lock<std::mutex> lock(buildStartedMutex); buildStarted = true; buildStartedCondition.notify_all(); }; queue->addJob(QueueJob((Command*)0x1, fn)); queue->addJob(QueueJob((Command*)0x1, fn)); { std::unique_lock<std::mutex> lock(buildStartedMutex); while (!buildStarted) { buildStartedCondition.wait(lock); } } queue.reset(); // Busy wait until our executions are done, but also have a timeout in case they never finish time_t start = ::time(NULL); while (executions < 2) { if (::time(NULL) > start + 5) { break; } } EXPECT_EQ(executions, 2); } }
// Copyright (c) 2016-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <qt/paymentrequestplus.h> // this includes protobuf's port.h which defines its own bswap macos #include <qt/test/compattests.h> #include <compat/byteswap.h> void CompatTests::bswapTests() { // Sibling in dollar/src/test/bswap_tests.cpp uint16_t u1 = 0x1234; uint32_t u2 = 0x56789abc; uint64_t u3 = 0xdef0123456789abc; uint16_t e1 = 0x3412; uint32_t e2 = 0xbc9a7856; uint64_t e3 = 0xbc9a78563412f0de; QVERIFY(bswap_16(u1) == e1); QVERIFY(bswap_32(u2) == e2); QVERIFY(bswap_64(u3) == e3); }
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "mojo/public/cpp/platform/platform_channel.h" #include <cstddef> #include <cstdint> #include <string> #include "base/logging.h" #include "base/rand_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #if defined(OS_WIN) #include <windows.h> #include "base/win/scoped_handle.h" #elif defined(OS_FUCHSIA) #include <zircon/process.h> #include <zircon/processargs.h> #include <zircon/syscalls.h> #include "base/fuchsia/scoped_zx_handle.h" #elif defined(OS_POSIX) #include <fcntl.h> #include <sys/types.h> #include <unistd.h> #include "base/files/scoped_file.h" #include "base/posix/global_descriptors.h" #endif #if defined(OS_POSIX) && !defined(OS_NACL_SFI) #include <sys/socket.h> #elif defined(OS_NACL_SFI) #include "native_client/src/public/imc_syscalls.h" #endif namespace mojo { namespace { #if defined(OS_WIN) void CreateChannel(PlatformHandle* local_endpoint, PlatformHandle* remote_endpoint) { base::string16 pipe_name = base::UTF8ToUTF16(base::StringPrintf( "\\\\.\\pipe\\mojo.%lu.%lu.%I64u", ::GetCurrentProcessId(), ::GetCurrentThreadId(), base::RandUint64())); DWORD kOpenMode = PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE; const DWORD kPipeMode = PIPE_TYPE_BYTE | PIPE_READMODE_BYTE; *local_endpoint = PlatformHandle(base::win::ScopedHandle( ::CreateNamedPipeW(pipe_name.c_str(), kOpenMode, kPipeMode, 1, // Max instances. 4096, // Output buffer size. 4096, // Input buffer size. 5000, // Timeout in ms. nullptr))); // Default security descriptor. PCHECK(local_endpoint->is_valid()); const DWORD kDesiredAccess = GENERIC_READ | GENERIC_WRITE; // The SECURITY_ANONYMOUS flag means that the server side cannot impersonate // the client. DWORD kFlags = SECURITY_SQOS_PRESENT | SECURITY_ANONYMOUS; // Allow the handle to be inherited by child processes. SECURITY_ATTRIBUTES security_attributes = {sizeof(SECURITY_ATTRIBUTES), nullptr, TRUE}; *remote_endpoint = PlatformHandle(base::win::ScopedHandle( ::CreateFileW(pipe_name.c_str(), kDesiredAccess, 0, &security_attributes, OPEN_EXISTING, kFlags, nullptr))); PCHECK(remote_endpoint->is_valid()); // Since a client has connected, ConnectNamedPipe() should return zero and // GetLastError() should return ERROR_PIPE_CONNECTED. CHECK(!::ConnectNamedPipe(local_endpoint->GetHandle().Get(), nullptr)); PCHECK(::GetLastError() == ERROR_PIPE_CONNECTED); } #elif defined(OS_FUCHSIA) void CreateChannel(PlatformHandle* local_endpoint, PlatformHandle* remote_endpoint) { zx_handle_t handles[2] = {}; zx_status_t result = zx_channel_create(0, &handles[0], &handles[1]); CHECK_EQ(ZX_OK, result); *local_endpoint = PlatformHandle(base::ScopedZxHandle(handles[0])); *remote_endpoint = PlatformHandle(base::ScopedZxHandle(handles[1])); DCHECK(local_endpoint->is_valid()); DCHECK(remote_endpoint->is_valid()); } #elif defined(OS_POSIX) #if defined(OS_ANDROID) // Leave room for any other descriptors defined in content for example. // TODO(https://crbug.com/676442): Consider changing base::GlobalDescriptors to // generate a key when setting the file descriptor. constexpr int kAndroidClientHandleDescriptor = base::GlobalDescriptors::kBaseDescriptor + 10000; #else bool IsTargetDescriptorUsed(const base::FileHandleMappingVector& mapping, int target_fd) { for (size_t i = 0; i < mapping.size(); ++i) { if (mapping[i].second == target_fd) return true; } return false; } #endif void CreateChannel(PlatformHandle* local_endpoint, PlatformHandle* remote_endpoint) { int fds[2]; #if defined(OS_NACL_SFI) PCHECK(imc_socketpair(fds) == 0); #else PCHECK(socketpair(AF_UNIX, SOCK_STREAM, 0, fds) == 0); // Set non-blocking on both ends. PCHECK(fcntl(fds[0], F_SETFL, O_NONBLOCK) == 0); PCHECK(fcntl(fds[1], F_SETFL, O_NONBLOCK) == 0); #if defined(OS_MACOSX) // This turns off |SIGPIPE| when writing to a closed socket, causing the call // to fail with |EPIPE| instead. On Linux we have to use |send...()| with // |MSG_NOSIGNAL| instead, which is not supported on Mac. int no_sigpipe = 1; PCHECK(setsockopt(fds[0], SOL_SOCKET, SO_NOSIGPIPE, &no_sigpipe, sizeof(no_sigpipe)) == 0); PCHECK(setsockopt(fds[1], SOL_SOCKET, SO_NOSIGPIPE, &no_sigpipe, sizeof(no_sigpipe)) == 0); #endif // defined(OS_MACOSX) #endif // defined(OS_NACL_SFI) *local_endpoint = PlatformHandle(base::ScopedFD(fds[0])); *remote_endpoint = PlatformHandle(base::ScopedFD(fds[1])); DCHECK(local_endpoint->is_valid()); DCHECK(remote_endpoint->is_valid()); } #else #error "Unsupported platform." #endif } // namespace const char PlatformChannel::kHandleSwitch[] = "mojo-platform-channel-handle"; PlatformChannel::PlatformChannel() { PlatformHandle local_handle; PlatformHandle remote_handle; CreateChannel(&local_handle, &remote_handle); local_endpoint_ = PlatformChannelEndpoint(std::move(local_handle)); remote_endpoint_ = PlatformChannelEndpoint(std::move(remote_handle)); } PlatformChannel::PlatformChannel(PlatformChannel&& other) = default; PlatformChannel::~PlatformChannel() = default; PlatformChannel& PlatformChannel::operator=(PlatformChannel&& other) = default; void PlatformChannel::PrepareToPassRemoteEndpoint(HandlePassingInfo* info, std::string* value) { DCHECK(info); DCHECK(value); DCHECK(remote_endpoint_.is_valid()); #if defined(OS_WIN) info->push_back(remote_endpoint_.platform_handle().GetHandle().Get()); *value = base::NumberToString( HandleToLong(remote_endpoint_.platform_handle().GetHandle().Get())); #elif defined(OS_FUCHSIA) const uint32_t id = PA_HND(PA_USER0, 0); info->push_back({id, remote_endpoint_.platform_handle().GetHandle().get()}); *value = base::NumberToString(id); #elif defined(OS_ANDROID) int fd = remote_endpoint_.platform_handle().GetFD().get(); info->emplace_back(fd, kAndroidClientHandleDescriptor); *value = base::NumberToString(kAndroidClientHandleDescriptor); #elif defined(OS_POSIX) // Arbitrary sanity check to ensure the loop below terminates reasonably // quickly. CHECK_LT(info->size(), 1000u); // Find a suitable FD to map the remote endpoint handle to in the child // process. This has quadratic time complexity in the size of |*info|, but // |*info| should be very small and is usually empty. int target_fd = base::GlobalDescriptors::kBaseDescriptor; while (IsTargetDescriptorUsed(*info, target_fd)) ++target_fd; info->emplace_back(remote_endpoint_.platform_handle().GetFD().get(), target_fd); *value = base::NumberToString(target_fd); #endif } void PlatformChannel::PrepareToPassRemoteEndpoint( HandlePassingInfo* info, base::CommandLine* command_line) { std::string value; PrepareToPassRemoteEndpoint(info, &value); if (!value.empty()) command_line->AppendSwitchASCII(kHandleSwitch, value); } void PlatformChannel::RemoteProcessLaunched() { #if defined(OS_FUCHSIA) // Unlike other platforms, Fuchsia just transfers handle ownership to the // launcher process rather than duplicating it. DCHECK(remote_endpoint_.platform_handle().is_valid_handle()); ignore_result(remote_endpoint_.TakePlatformHandle().ReleaseHandle()); #else remote_endpoint_.reset(); #endif } // static PlatformChannelEndpoint PlatformChannel::RecoverPassedEndpointFromString( base::StringPiece value) { #if defined(OS_WIN) int handle_value = 0; if (value.empty() || !base::StringToInt(value, &handle_value)) { DLOG(ERROR) << "Invalid PlatformChannel endpoint string."; return PlatformChannelEndpoint(); } return PlatformChannelEndpoint( PlatformHandle(base::win::ScopedHandle(LongToHandle(handle_value)))); #elif defined(OS_FUCHSIA) unsigned int handle_value = 0; if (value.empty() || !base::StringToUint(value, &handle_value)) { DLOG(ERROR) << "Invalid PlatformChannel endpoint string."; return PlatformChannelEndpoint(); } return PlatformChannelEndpoint(PlatformHandle(base::ScopedZxHandle( zx_get_startup_handle(base::checked_cast<uint32_t>(handle_value))))); #elif defined(OS_ANDROID) base::GlobalDescriptors::Key key = -1; if (value.empty() || !base::StringToUint(value, &key)) { DLOG(ERROR) << "Invalid PlatformChannel endpoint string."; return PlatformChannelEndpoint(); } return PlatformChannelEndpoint(PlatformHandle( base::ScopedFD(base::GlobalDescriptors::GetInstance()->Get(key)))); #elif defined(OS_POSIX) int fd = -1; if (value.empty() || !base::StringToInt(value, &fd) || fd < base::GlobalDescriptors::kBaseDescriptor) { DLOG(ERROR) << "Invalid PlatformChannel endpoint string."; return PlatformChannelEndpoint(); } return PlatformChannelEndpoint(PlatformHandle(base::ScopedFD(fd))); #endif } // static PlatformChannelEndpoint PlatformChannel::RecoverPassedEndpointFromCommandLine( const base::CommandLine& command_line) { return RecoverPassedEndpointFromString( command_line.GetSwitchValueASCII(kHandleSwitch)); } } // namespace mojo
#pragma once #include <algorithm> #include <exception> #include <string> namespace hpx { namespace kokkos { namespace resiliency { namespace detail { struct resiliency_exception : public std::exception { std::string ex; resiliency_exception() : ex("Resiliency based exception occured.") { } resiliency_exception(std::string&& s) : ex(std::move(s)) { } const char* what() const throw() { return ex.data(); } }; }}}} // namespace hpx::kokkos::resiliency::detail namespace Kokkos { namespace Impl { namespace traits { template <typename ExecutionSpace, typename... Traits> struct RangePolicyBase { using execution_space = ExecutionSpace; using base_execution_space = typename execution_space::base_execution_space; using RangePolicy = Kokkos::RangePolicy<base_execution_space, Traits...>; using validator = typename execution_space::validator_type; }; }}} // namespace Kokkos::Impl::traits
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "core/common/common.h" #include "core/framework/data_types.h" #include "core/framework/data_types_internal.h" #include "core/framework/op_kernel.h" #include "Featurizers/TruncatedSVDFeaturizer.h" #include "Featurizers/../Archive.h" namespace NS = Microsoft::Featurizer; namespace onnxruntime { namespace featurizers { template <typename T> struct TruncatedSVDTransformerImpl { void operator()(OpKernelContext* ctx) const { using MatrixT = NS::RowMajMatrix<T>; using InputMatrixT = Eigen::Map<const MatrixT>; // Create the transformer Microsoft::Featurizer::Featurizers::TruncatedSVDTransformer<InputMatrixT> transformer( [ctx]() { const auto* state_tensor(ctx->Input<Tensor>(0)); const uint8_t* const state_data(state_tensor->Data<uint8_t>()); Microsoft::Featurizer::Archive archive(state_data, state_tensor->Shape().Size()); return Microsoft::Featurizer::Featurizers::TruncatedSVDTransformer<InputMatrixT>(archive); }()); // Get the input const auto* input_tensor(ctx->Input<Tensor>(1)); const T* input_data(input_tensor->template Data<T>()); // Matrix Eigen raw buffer mapping const auto input_dim_0 = input_tensor->Shape()[0]; const auto input_dim_1 = input_tensor->Shape()[1]; InputMatrixT input_matrix(input_data, input_dim_0, input_dim_1); // Prepare output shape which is [M, P] where P is the first dimension (rows) // of P matrix from the transformer const int64_t dim_0 = input_dim_0; const int64_t dim_1 = transformer.getEigenVectorColsNumber(); TensorShape output_shape({dim_0, dim_1}); auto* output_tensor(ctx->Output(0, output_shape)); T* output_data = output_tensor->template MutableData<T>(); Eigen::Map<MatrixT> output_matrix(output_data, dim_0, dim_1); std::function<void(MatrixT val)> callback; bool callback_allow = true; callback = [&output_matrix, callback_allow](MatrixT val) { ORT_ENFORCE(callback_allow, "callback function can only be called during execute() and special flush() when needed"); output_matrix = val; }; transformer.execute(input_matrix, callback); // The flush() does nothing but shows Featurizers concept callback_allow = false; transformer.flush(callback); } }; class TruncatedSVDTransformer final : public OpKernel { public: explicit TruncatedSVDTransformer(const OpKernelInfo& info) : OpKernel(info) { } Status Compute(OpKernelContext* ctx) const override { utils::MLTypeCallDispatcher<TruncatedSVDTransformerImpl, float, double> t_disp(ctx->Input<Tensor>(1)->GetElementType()); t_disp.Invoke(ctx); return Status::OK(); } }; ONNX_OPERATOR_KERNEL_EX( TruncatedSVDTransformer, kMSFeaturizersDomain, 1, kCpuExecutionProvider, KernelDefBuilder() .TypeConstraint("T0", DataTypeImpl::GetTensorType<uint8_t>()) .TypeConstraint("InputT", {DataTypeImpl::GetTensorType<float>(), DataTypeImpl::GetTensorType<double>()}), TruncatedSVDTransformer); } // namespace featurizers } // namespace onnxruntime
// Copyright (c) 2020-2021 The BIGKEYCOIN Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <blockfilter.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <cstdint> #include <optional> #include <string> #include <vector> FUZZ_TARGET(blockfilter) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const std::optional<BlockFilter> block_filter = ConsumeDeserializable<BlockFilter>(fuzzed_data_provider); if (!block_filter) { return; } { (void)block_filter->ComputeHeader(ConsumeUInt256(fuzzed_data_provider)); (void)block_filter->GetBlockHash(); (void)block_filter->GetEncodedFilter(); (void)block_filter->GetHash(); } { const BlockFilterType block_filter_type = block_filter->GetFilterType(); (void)BlockFilterTypeName(block_filter_type); } { const GCSFilter gcs_filter = block_filter->GetFilter(); (void)gcs_filter.GetN(); (void)gcs_filter.GetParams(); (void)gcs_filter.GetEncoded(); (void)gcs_filter.Match(ConsumeRandomLengthByteVector(fuzzed_data_provider)); GCSFilter::ElementSet element_set; LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 30000) { element_set.insert(ConsumeRandomLengthByteVector(fuzzed_data_provider)); } gcs_filter.MatchAny(element_set); } }
/* * Copyright 2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <thrift/lib/cpp/concurrency/PosixThreadFactory.h> #include <thrift/lib/cpp/concurrency/Exception.h> #include <thrift/lib/cpp/concurrency/Mutex.h> #include <thrift/lib/cpp/thrift_config.h> #if GOOGLE_PERFTOOLS_REGISTER_THREAD # include "base/Profiler.h" #endif #include <assert.h> #include <pthread.h> #include <sys/resource.h> #include <iostream> #include <boost/weak_ptr.hpp> #include <glog/logging.h> namespace apache { namespace thrift { namespace concurrency { using std::shared_ptr; using std::weak_ptr; const PosixThreadFactory::POLICY PosixThreadFactory::kDefaultPolicy; const PosixThreadFactory::PRIORITY PosixThreadFactory::kDefaultPriority; const int PosixThreadFactory::kDefaultStackSizeMB; // global set to track the ids of live threads. std::set<pthread_t> liveThreadIds; Mutex liveThreadIdMutex; void addLiveThreadId(pthread_t tid) { Guard g(liveThreadIdMutex); liveThreadIds.insert(tid); } void removeLiveThreadId(pthread_t tid) { Guard g(liveThreadIdMutex); liveThreadIds.erase(tid); } void getLiveThreadIds(std::set<pthread_t>* tids) { Guard g(liveThreadIdMutex); for (std::set<pthread_t>::const_iterator it = liveThreadIds.begin(); it != liveThreadIds.end(); ++it) { tids->insert(*it); } } // push our given name upstream into pthreads bool PthreadThread::updateName() { if (!pthread_ || name_.empty()) { return false; } return setPosixThreadName(pthread_, name_); } PthreadThread::PthreadThread(int policy, int priority, int stackSize, bool detached, shared_ptr<Runnable> runnable) : pthread_(0), state_(uninitialized), policy_(policy), priority_(priority), stackSize_(stackSize), detached_(detached) { this->Thread::runnable(runnable); } PthreadThread::~PthreadThread() { /* Nothing references this thread, if is is not detached, do a join now, otherwise the thread-id and, possibly, other resources will be leaked. */ if(!detached_) { try { join(); } catch(...) { // We're really hosed. } } removeLiveThreadId(pthread_); } void PthreadThread::start() { Guard g(stateLock_); if (state_ != uninitialized) { return; } pthread_attr_t thread_attr; if (pthread_attr_init(&thread_attr) != 0) { throw SystemResourceException("pthread_attr_init failed"); } if(pthread_attr_setdetachstate(&thread_attr, detached_ ? PTHREAD_CREATE_DETACHED : PTHREAD_CREATE_JOINABLE) != 0) { throw SystemResourceException("pthread_attr_setdetachstate failed"); } // Set thread stack size if (pthread_attr_setstacksize(&thread_attr, MB * stackSize_) != 0) { throw SystemResourceException("pthread_attr_setstacksize failed"); } // Create reference shared_ptr<PthreadThread>* selfRef = new shared_ptr<PthreadThread>(); *selfRef = self_.lock(); state_ = starting; if (pthread_create(&pthread_, &thread_attr, threadMain, (void*)selfRef) != 0) { throw SystemResourceException("pthread_create failed"); } // Now that we have a thread, we can set the name we've been given, if any. updateName(); addLiveThreadId(pthread_); } void PthreadThread::join() { Guard g(stateLock_); STATE join_state = state_; if (!detached_ && join_state != uninitialized) { void* ignore; /* XXX If join fails it is most likely due to the fact that the last reference was the thread itself and cannot join. This results in leaked threads and will eventually cause the process to run out of thread resources. We're beyond the point of throwing an exception. Not clear how best to handle this. */ int res = pthread_join(pthread_, &ignore); detached_ = (res == 0); if (res != 0) { LOG(ERROR) << "PthreadThread::join(): fail with code " << res; } } else { LOG(ERROR) << "PthreadThread::join(): detached thread"; } } Thread::id_t PthreadThread::getId() { return (Thread::id_t)pthread_; } shared_ptr<Runnable> PthreadThread::runnable() const { return Thread::runnable(); } void PthreadThread::runnable(shared_ptr<Runnable> value) { Thread::runnable(value); } void PthreadThread::weakRef(shared_ptr<PthreadThread> self) { assert(self.get() == this); self_ = weak_ptr<PthreadThread>(self); } bool PthreadThread::setName(const std::string& name) { Guard g(stateLock_); name_ = name; return updateName(); } void* PthreadThread::threadMain(void* arg) { shared_ptr<PthreadThread> thread = *(shared_ptr<PthreadThread>*)arg; delete reinterpret_cast<shared_ptr<PthreadThread>*>(arg); if (thread == nullptr) { return (void*)0; } #if GOOGLE_PERFTOOLS_REGISTER_THREAD ProfilerRegisterThread(); #endif // Using pthread_attr_setschedparam() at thread creation doesn't actually // change the new thread's priority for some reason... Other people on the // 'net also complain about it. The solution is to set priority inside the // new thread's threadMain. if (thread->policy_ == SCHED_FIFO || thread->policy_ == SCHED_RR) { struct sched_param sched_param; sched_param.sched_priority = thread->priority_; int err = pthread_setschedparam(pthread_self(), thread->policy_, &sched_param); if (err != 0) { VLOG(1) << "pthread_setschedparam failed (are you root?) with error " << err, strerror(err); } } else if (thread->policy_ == SCHED_OTHER) { if (setpriority(PRIO_PROCESS, 0, thread->priority_) != 0) { VLOG(1) << "setpriority failed (are you root?) with error " << errno, strerror(errno); } } thread->runnable()->run(); return (void*)0; } int PosixThreadFactory::Impl::toPthreadPolicy(POLICY policy) { switch (policy) { case OTHER: return SCHED_OTHER; case FIFO: return SCHED_FIFO; case ROUND_ROBIN: return SCHED_RR; } return SCHED_OTHER; } int PosixThreadFactory::Impl::toPthreadPriority( POLICY policy, PRIORITY priority) { int pthread_policy = toPthreadPolicy(policy); int min_priority = 0; int max_priority = 0; if (pthread_policy == SCHED_FIFO || pthread_policy == SCHED_RR) { #ifdef THRIFT_HAVE_SCHED_GET_PRIORITY_MIN min_priority = sched_get_priority_min(pthread_policy); #endif #ifdef THRIFT_HAVE_SCHED_GET_PRIORITY_MAX max_priority = sched_get_priority_max(pthread_policy); #endif } else if (pthread_policy == SCHED_OTHER) { min_priority = 19; max_priority = -20; } int quanta = HIGHEST - LOWEST; float stepsperquanta = (float)(max_priority - min_priority) / quanta; if (priority <= HIGHEST) { return (int)(min_priority + stepsperquanta * priority); } else { // should never get here for priority increments. assert(false); return (int)(min_priority + stepsperquanta * NORMAL); } } PosixThreadFactory::Impl::Impl( POLICY policy, PRIORITY priority, int stackSize, DetachState detached) : policy_(policy), priority_(priority), stackSize_(stackSize), detached_(detached) {} shared_ptr<Thread> PosixThreadFactory::Impl::newThread( const shared_ptr<Runnable>& runnable, PosixThreadFactory::DetachState detachState) const { shared_ptr<PthreadThread> result = shared_ptr<PthreadThread>( new PthreadThread(toPthreadPolicy(policy_), toPthreadPriority(policy_, priority_), stackSize_, detachState == DETACHED, runnable)); result->weakRef(result); runnable->thread(result); return result; } int PosixThreadFactory::Impl::getStackSize() const { return stackSize_; } void PosixThreadFactory::Impl::setStackSize(int value) { stackSize_ = value; } PosixThreadFactory::PRIORITY PosixThreadFactory::Impl::getPriority() const { return priority_; } /** * Sets priority. * * XXX * Need to handle incremental priorities properly. */ void PosixThreadFactory::Impl::setPriority(PRIORITY value) { priority_ = value; } PosixThreadFactory::DetachState PosixThreadFactory::Impl::getDetachState() const { return detached_; } void PosixThreadFactory::Impl::setDetachState(DetachState value) { detached_ = value; } Thread::id_t PosixThreadFactory::Impl::getCurrentThreadId() const { return static_cast<Thread::id_t>(pthread_self()); } PosixThreadFactory::PosixThreadFactory(POLICY policy, PRIORITY priority, int stackSize, bool detached) : impl_(new PosixThreadFactory::Impl(policy, priority, stackSize, detached ? DETACHED : ATTACHED)) { } PosixThreadFactory::PosixThreadFactory(DetachState detached) : impl_(new PosixThreadFactory::Impl(kDefaultPolicy, kDefaultPriority, kDefaultStackSizeMB, detached)) { } shared_ptr<Thread> PosixThreadFactory::newThread( const shared_ptr<Runnable>& runnable) const { return impl_->newThread(runnable, impl_->getDetachState()); } shared_ptr<Thread> PosixThreadFactory::newThread( const shared_ptr<Runnable>& runnable, DetachState detachState) const { return impl_->newThread(runnable, detachState); } int PosixThreadFactory::getStackSize() const { return impl_->getStackSize(); } void PosixThreadFactory::setStackSize(int value) { impl_->setStackSize(value); } PosixThreadFactory::PRIORITY PosixThreadFactory::getPriority() const { return impl_->getPriority(); } void PosixThreadFactory::setPriority(PosixThreadFactory::PRIORITY value) { impl_->setPriority(value); } bool PosixThreadFactory::isDetached() const { return impl_->getDetachState() == DETACHED; } void PosixThreadFactory::setDetached(bool value) { impl_->setDetachState(value ? DETACHED : ATTACHED); } void PosixThreadFactory::setDetached(DetachState value) { impl_->setDetachState(value); } Thread::id_t PosixThreadFactory::getCurrentThreadId() const { return impl_->getCurrentThreadId(); } }}} // apache::thrift::concurrency
#ifndef TNT_INDEX_IMPL_HPP #define TNT_INDEX_IMPL_HPP #include <tnt/core/index.hpp> #include <tnt/utils/testing.hpp> #include <iostream> namespace tnt { inline Index::Index() noexcept {} inline Index::Index(const Shape& shape) { this->loc = std::vector<int>(shape.num_axes(), 0); this->shape = shape; } inline bool Index::operator== (const Index& other) const noexcept { return this->loc == other.loc && this->shape == other.shape; } inline bool Index::operator!= (const Index& other) const noexcept { return this->loc != other.loc && this->shape == other.shape; } inline int Index::operator[] (int index) const { BOUNDS_CHECK("Index::operator[]", index, 0, this->shape.num_axes() - 1); return this->loc[index]; } inline int& Index::operator[] (int index) { BOUNDS_CHECK("Index::operator[]", index, 0, this->shape.num_axes() - 1); return this->loc[index]; } inline Index& Index::operator++ () noexcept { for (int i = this->num_axes() - 1; i >= 0; i--) { if ((++this->loc[i]) == this->shape[i]) { if (i == 0) // Special case, end of the index break; // Leave the index in an invalid state this->loc[i] = 0; } else { break; } } return *this; } TEST_CASE("Index::operator++()") { Index index(Shape{2, 2, 2}); REQUIRE((index.loc == std::vector<int>{0, 0, 0})); REQUIRE(((++index).loc == std::vector<int>{0, 0, 1})); REQUIRE(((++index).loc == std::vector<int>{0, 1, 0})); REQUIRE(((++index).loc == std::vector<int>{0, 1, 1})); REQUIRE(((++index).loc == std::vector<int>{1, 0, 0})); REQUIRE(((++index).loc == std::vector<int>{1, 0, 1})); REQUIRE(((++index).loc == std::vector<int>{1, 1, 0})); REQUIRE(((++index).loc == std::vector<int>{1, 1, 1})); REQUIRE(((++index).loc == std::vector<int>{2, 0, 0})); } inline Index Index::operator++ (int) noexcept { Index temp = *this; this->operator ++(); return temp; } TEST_CASE("Index::operator++(int)") { Index index(Shape{2, 2, 2}); REQUIRE((index.loc == std::vector<int>{0, 0, 0})); REQUIRE(((index++).loc == std::vector<int>{0, 0, 0})); REQUIRE(((index++).loc == std::vector<int>{0, 0, 1})); REQUIRE(((index++).loc == std::vector<int>{0, 1, 0})); REQUIRE(((index++).loc == std::vector<int>{0, 1, 1})); REQUIRE(((index++).loc == std::vector<int>{1, 0, 0})); REQUIRE(((index++).loc == std::vector<int>{1, 0, 1})); REQUIRE(((index++).loc == std::vector<int>{1, 1, 0})); REQUIRE(((index++).loc == std::vector<int>{1, 1, 1})); REQUIRE(((index).loc == std::vector<int>{2, 0, 0})); } inline int Index::num_axes() const noexcept { return this->shape.num_axes(); } TEST_CASE("Index::num_axes()") { REQUIRE(Index().num_axes() == 0); REQUIRE(Index(Shape{1}).num_axes() == 1); REQUIRE(Index(Shape{1, 1}).num_axes() == 2); REQUIRE(Index(Shape{1, 1, 1, 1}).num_axes() == 4); } inline int Index::distance(const Stride& stride) const { TNT_ASSERT(stride.num_axes() == this->shape.num_axes(), std::runtime_error("Error in Index::Distance(). Given stride has a different number of axes then the index")); int dist = 0; for (int i = 0; i < this->num_axes(); ++i) dist += this->loc[i] * stride[i]; return dist; } TEST_CASE("Index::distance(const Stride&)") { Index index(Shape{2, 2, 2}); index.loc = {1, 0, 1}; REQUIRE(index.distance(Stride{4, 4, 1}) == 5); REQUIRE(index.distance(Stride{1, 1, 1}) == 2); REQUIRE(index.distance(Stride{0, 0, 0}) == 0); REQUIRE(index.distance(Stride{2, 1, 2}) == 4); REQUIRE_THROWS(index.distance(Stride{2, 2})); } // ---------------------------------------------------------------------------- // Index Stream Operator TNT_EXPORT inline std::ostream& operator<<(std::ostream& stream, const Index& index) { if (index.num_axes() == 0) return stream << "Index: {}"; std::string output = "Index: {"; for (int dim : index.loc) output += std::to_string(dim) + ","; return stream << output.substr(0, output.size() - 1) + "}"; } } // namespace tnt #endif // TNT_INDEX_IMPL_HPP
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Vicente J. Botet Escriba 2017. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // ////////////////////////////////////////////////////////////////////////////// #ifndef JASEL_FUNDAMENTAL_V3_VALUE_OR_ERROR_TRANSFORM_HPP #define JASEL_FUNDAMENTAL_V3_VALUE_OR_ERROR_TRANSFORM_HPP #include <experimental/fundamental/v2/config.hpp> #include <experimental/fundamental/v3/value_or_error/value_or_error.hpp> #include <experimental/make.hpp> #include <experimental/meta.hpp> #include <experimental/type_traits.hpp> #include <experimental/type_constructible.hpp> #include <experimental/fundamental/v3/functor/functor.hpp> #include <utility> #include <functional> #include <iostream> namespace std { namespace experimental { inline namespace fundamental_v3 { namespace value_or_error { /** * functor::transform for TypeConstructible ValueOrError types */ template <class N, class F // todo add constraint on F //, class = enable_if_t< // is_value_or_error_v<remove_cvref_t<N>> // && is_type_constructible_v<remove_cvref_t<N>> //> > BOOST_CXX14_CONSTEXPR meta::invoke<TypeConstructor<remove_cvref_t<N>>, meta::ResultType<decay_t<F>, value_type_t<remove_cvref_t<N>>>> transform(N&& n, F&& f) { if (value_or_error::has_value(forward<N>(n))) { return make<TypeConstructor<remove_cvref_t<N>>>( JASEL_INVOKE(std::forward<F>(f), value_or_error::deref(forward<N>(n))) ); } return value_or_error::failure_value(forward<N>(n)); } struct as_functor: functor::mcd_transform { template <class T, class F> static constexpr auto transform(T&& x, F&& f) JASEL_DECLTYPE_RETURN_NOEXCEPT( value_or_error::transform(forward<T>(x), forward<F>(f)) ) }; } /** */ namespace functor { template <class N> struct traits<N, meta::when< is_value_or_error<N>::value && is_type_constructible<N>::value >> : value_or_error::as_functor {}; } }} } #endif // header
#pragma once #include <ice/base.hxx> namespace ice::render { class RenderDriver; class RenderDevice; class RenderSurface; class RenderSwapchain; class RenderQueue; class RenderCommands; class RenderFence; struct SurfaceInfo; struct RenderpassInfo; struct ResourceSetLayoutBinding; struct ResourceSetUpdateInfo; struct PipelineLayoutInfo; struct PipelineInfo; struct QueueFamilyInfo; struct QueueInfo; struct ShaderInfo; struct ImageInfo; struct ImageBarrier; struct SamplerInfo; struct BufferUpdateInfo; enum class [[nodiscard]] Framebuffer : ice::uptr; enum class [[nodiscard]] Renderpass : ice::uptr; enum class [[nodiscard]] ResourceSetLayout : ice::uptr; enum class [[nodiscard]] ResourceSet : ice::uptr; enum class [[nodiscard]] PipelineLayout : ice::uptr; enum class [[nodiscard]] Pipeline : ice::uptr; enum class [[nodiscard]] Shader : ice::uptr; enum class [[nodiscard]] Image : ice::uptr; enum class [[nodiscard]] Sampler : ice::uptr; enum class [[nodiscard]] Buffer : ice::uptr; enum class [[nodiscard]] CommandBuffer : ice::uptr; enum class [[nodiscard]] Semaphore : ice::uptr; enum class QueueID : ice::u32; enum class QueueFlags : ice::u32; enum class ImageFormat : ice::u32; enum class ImageLayout : ice::u32; enum class AttachmentType : ice::u32; enum class AccessFlags : ice::u32; enum class BufferType : ice::u32; enum class PipelineStage : ice::u32; enum class ShaderStageFlags : ice::u32; enum class CommandBufferType : ice::u32; enum class BarrierDependency : ice::u32; } // namespace ice::render
/* 王道考研 p54 */ #include <iostream> #include <stdio.h> #include <stack> using namespace std; char s[220]; int mat[][5] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, }; stack<int> op; stack<double> in; void getop(bool &reto, int &retn, int &i) { if(i==0 && op.empty()==true) { reto = true; retn = 0; return; } if(s[i] == '\0') { reto = true; retn = 0; return; } if(s[i]>='0' && s[i]<='9') reto = false; else { reto = true; switch(s[i]) { case '+': retn = 1; break; case '-': retn = 2; break; case '*': retn = 3; break; case '/': retn = 4; break; } i += 2; return; } retn = 0; for(; s[i]!=' '&&s[i]!='\0'; i++) { retn *= 10; retn += s[i] - '0'; } if(s[i] == ' ') i++; return; } int main() { cin>>s; return 0; }
#include <bits/stdc++.h> #include <math.h> #include <vector> #include <algorithm> using namespace std; int main() { long long int l,u,t,n,i,j,count=1,divisor=1,temp,c; vector<long long int>divcount; while (cin>>t) { while (t--) { cin>>l>>u; for(i=l;i<=u;i++) { count=0; for (j=1;j*j<=i;j++) { if (j*j==i) { count++; } else if (i%j==0) { count+=2; } } divcount.push_back(count); //cout<<count<<endl; } //std::sort(divcount.begin(),divcount.end(),greater<int>()); temp=*max_element(divcount.begin(),divcount.end()); //divcount.clear(); /*while(!divcount.empty()) { cout<<divcount.back()<<" "<<endl; divcount.pop_back(); }*/ for(i=l;i<=u;i++) { count=0; for (j=1;j*j<=i;j++) { if (j*j==i) { count++; } else if (i%j==0) { count+=2; } } if (count==temp) { c=i; break; } } cout<<"Between "<<l<<" and "<<u<<", "<<c<<" has a maximum of "<<temp<<" divisors."<<endl; } } return 0; }
#include <bits/stdc++.h> using namespace std; #define ll long long #define ld long double #define ar array #define _DEBUG #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; template <typename T> using oset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; #define vt vector #define pb push_back #define all(c) (c).begin(), (c).end() #define sz(x) (int)(x).size() #define F_OR(i, a, b, s) for (int i=(a); (s)>0?i<(b):i>(b); i+=(s)) #define F_OR1(e) F_OR(i, 0, e, 1) #define F_OR2(i, e) F_OR(i, 0, e, 1) #define F_OR3(i, b, e) F_OR(i, b, e, 1) #define F_OR4(i, b, e, s) F_OR(i, b, e, s) #define GET5(a, b, c, d, e, ...) e #define F_ORC(...) GET5(__VA_ARGS__, F_OR4, F_OR3, F_OR2, F_OR1) #define FOR(...) F_ORC(__VA_ARGS__)(__VA_ARGS__) #define EACH(x, a) for (auto& x: a) template<class T> bool umin(T& a, const T& b) { return b<a?a=b, 1:0; } template<class T> bool umax(T& a, const T& b) { return a<b?a=b, 1:0; } ll FIRSTTRUE(function<bool(ll)> f, ll lb, ll rb) { while(lb<rb) { ll mb=(lb+rb)/2; f(mb)?rb=mb:lb=mb+1; } return lb; } ll LASTTRUE(function<bool(ll)> f, ll lb, ll rb) { while(lb<rb) { ll mb=(lb+rb+1)/2; f(mb)?lb=mb:rb=mb-1; } return lb; } template<class A> void read(vt<A>& v); template<class A, size_t S> void read(ar<A, S>& a); template<class T> void read(T& x) { cin >> x; } void read(double& d) { string t; read(t); d=stod(t); } void read(long double& d) { string t; read(t); d=stold(t); } template<class H, class... T> void read(H& h, T&... t) { read(h); read(t...); } template<class A> void read(vt<A>& x) { EACH(a, x) read(a); } template<class A, size_t S> void read(array<A, S>& x) { EACH(a, x) read(a); } string to_string(char c) { return string(1, c); } string to_string(bool b) { return b?"true":"false"; } string to_string(const char* s) { return string(s); } string to_string(string s) { return s; } string to_string(vt<bool> v) { string res; FOR(sz(v)) res+=char('0'+v[i]); return res; } template<size_t S> string to_string(bitset<S> b) { string res; FOR(S) res+=char('0'+b[i]); return res; } template<class T> string to_string(T v) { bool f=1; string res; EACH(x, v) { if(!f) res+=' '; f=0; res+=to_string(x); } return res; } template<class A> void write(A x) { cout << to_string(x); } template<class H, class... T> void write(const H& h, const T&... t) { write(h); write(t...); } void print() { write("\n"); } template<class H, class... T> void print(const H& h, const T&... t) { write(h); if(sizeof...(t)) write(' '); print(t...); } void DBG() { cerr << "]" << endl; } template<class H, class... T> void DBG(H h, T... t) { cerr << to_string(h); if(sizeof...(t)) cerr << ", "; DBG(t...); } #ifdef _DEBUG #define dbg(...) cerr << "LINE(" << __LINE__ << ") -> [" << #__VA_ARGS__ << "]: [", DBG(__VA_ARGS__) #else #define dbg(...) 0 #endif template<class T> void offset(ll o, T& x) { x+=o; } template<class T> void offset(ll o, vt<T>& x) { EACH(a, x) offset(o, a); } template<class T, size_t S> void offset(ll o, ar<T, S>& x) { EACH(a, x) offset(o, a); } mt19937 mt_rng(chrono::steady_clock::now().time_since_epoch().count()); ll randint(ll a, ll b) { return uniform_int_distribution<ll>(a, b)(mt_rng); } template<class T, class U> void vti(vt<T> &v, U x, size_t n) { v=vt<T>(n, x); } template<class T, class U> void vti(vt<T> &v, U x, size_t n, size_t m...) { v=vt<T>(n); EACH(a, v) vti(a, x, m); } const int d4i[4]={-1, 0, 1, 0}, d4j[4]={0, 1, 0, -1}; const int d8i[8]={-1, -1, 0, 1, 1, 1, 0, -1}, d8j[8]={0, 1, 1, 1, 0, -1, -1, -1}; void solve() { int n; read(n); int f=0; int s=0; if (n==2){ f=2; n=0; } for(int i=1; i<=n/2; ++i){ int c=0; c+=pow(2, i); c+=pow(2, n-i+1); if (i&1) s+=c; else f+=c; } print(abs(f-s)); } int main() { ios::sync_with_stdio(0); cin.tie(0); int t=1; read(t); FOR(t) { //write("Case #", i+1, ": "); solve(); } }
/* ** ClanLib SDK ** Copyright (c) 1997-2020 The ClanLib Team ** ** This software is provided 'as-is', without any express or implied ** warranty. In no event will the authors be held liable for any damages ** arising from the use of this software. ** ** Permission is granted to anyone to use this software for any purpose, ** including commercial applications, and to alter it and redistribute it ** freely, subject to the following restrictions: ** ** 1. The origin of this software must not be misrepresented; you must not ** claim that you wrote the original software. If you use this software ** in a product, an acknowledgment in the product documentation would be ** appreciated but is not required. ** 2. Altered source versions must be plainly marked as such, and must not be ** misrepresented as being the original software. ** 3. This notice may not be removed or altered from any source distribution. ** ** Note: Some of the libraries ClanLib may link to may have additional ** requirements or restrictions. ** ** File Author(s): ** ** Mark Page */ #include "precomp.h" #include "program.h" #include "target.h" clan::ApplicationInstance<Program> clanapp; Program::Program() { #if defined(WIN32) && !defined(__MINGW32__) clan::D3DTarget::set_current(); #else clan::OpenGLTarget::set_current(); #endif target = clan::make_unique<Target>(Target::RenderTarget::legacy_gl); } bool Program::update() { Target::RenderTarget rt = target->render_target; target->run_demo(); if (target->quit) return false; if (target->render_target != rt) { rt = target->render_target; target.reset(); // This is important. Multiply Display targets cannot co-exist target = clan::make_unique<Target>(rt); } return true; }
// Copyright (C) 2018-2019 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <gtest/gtest.h> #include <string.h> #include <ie_builders.hpp> #include "builder_test.hpp" using namespace testing; using namespace InferenceEngine; class NetworkBuilderTest : public BuilderTestCommon { protected: std::vector<std::string> alexNetNames = { "in1", "mean", "conv1", "relu1", "norm1", "pool1", "conv2", "relu2", "norm2", "pool2", "conv3", "relu3", "conv4", "relu4", "conv5", "relu5", "pool5", "fc6", "relu6", "fc7", "relu7", "fc8", "prob", "sf_out" }; public: Builder::Network prepateAlexnetBuilder(Precision precision = Precision::FP32) { Context ctx; Builder::Network builder(ctx, "AlexNet"); idx_t weightsId, biasesId; idx_t layerId = builder.addLayer(Builder::InputLayer(alexNetNames[0]).setPort(Port({1,3, 227, 227}))); biasesId = builder.addLayer(Builder::ConstLayer("biases").setData(generateBlob(precision, {3}, Layout::C))); layerId = builder.addLayer({{layerId}}, Builder::ScaleShiftLayer(alexNetNames[1])); builder.connect({biasesId}, {layerId, 2}); weightsId = builder.addLayer(Builder::ConstLayer("weights").setData(generateBlob(precision, {96, 3, 11, 11}, Layout::OIHW))); biasesId = builder.addLayer(Builder::ConstLayer("biases").setData(generateBlob(precision, {96}, Layout::C))); layerId = builder.addLayer({{layerId}, {weightsId}, {biasesId}}, Builder::ConvolutionLayer(alexNetNames[2]).setKernel({11, 11}) .setStrides({4, 4}).setOutDepth(96)); layerId = builder.addLayer({{layerId}}, Builder::ReLULayer(alexNetNames[3])); layerId = builder.addLayer({{layerId}}, Builder::NormLayer(alexNetNames[4]).setAlpha(9.999999747378752e-05f).setBeta(0.75f).setSize(5).setAcrossMaps(true)); layerId = builder.addLayer({{layerId}}, Builder::PoolingLayer(alexNetNames[5]).setExcludePad(false).setKernel({3, 3}).setPaddingsBegin({0, 0}) .setPaddingsEnd({0, 0}).setPoolingType(Builder::PoolingLayer::PoolingType::MAX).setStrides({2, 2})); weightsId = builder.addLayer(Builder::ConstLayer("weights").setData(generateBlob(precision, {256, 96 / 2, 5, 5}, Layout::OIHW))); biasesId = builder.addLayer(Builder::ConstLayer("biases").setData(generateBlob(precision, {256}, Layout::C))); layerId = builder.addLayer({{layerId}, {weightsId}, {biasesId}}, Builder::ConvolutionLayer(alexNetNames[6]).setKernel({5, 5}).setStrides({1, 1}).setOutDepth(256) .setPaddingsBegin({2, 2}).setPaddingsEnd({2, 2}).setGroup(2).setDilation({1, 1})); layerId = builder.addLayer({{layerId}}, Builder::ReLULayer(alexNetNames[7])); layerId = builder.addLayer({{layerId}}, Builder::NormLayer(alexNetNames[8]).setAlpha(9.999999747378752e-05f).setBeta(0.75f).setSize(5).setAcrossMaps(true)); layerId = builder.addLayer({{layerId}}, Builder::PoolingLayer(alexNetNames[9]).setExcludePad(false).setKernel({3, 3}).setPaddingsBegin({0, 0}) .setPaddingsEnd({0, 0}).setPoolingType(Builder::PoolingLayer::PoolingType::MAX).setStrides({2, 2})); weightsId = builder.addLayer(Builder::ConstLayer("weights").setData(generateBlob(precision, {256, 384, 3, 3}, Layout::OIHW))); biasesId = builder.addLayer(Builder::ConstLayer("biases").setData(generateBlob(precision, {384}, Layout::C))); layerId = builder.addLayer({{layerId}, {weightsId}, {biasesId}}, Builder::ConvolutionLayer(alexNetNames[10]).setKernel({3, 3}) .setStrides({1, 1}).setOutDepth(384).setPaddingsBegin({1, 1}).setPaddingsEnd({1, 1}).setGroup(1).setDilation({1, 1})); layerId = builder.addLayer({{layerId}}, Builder::ReLULayer(alexNetNames[11])); weightsId = builder.addLayer(Builder::ConstLayer("weights").setData(generateBlob(precision, {384, 384 / 2, 3, 3}, Layout::OIHW))); biasesId = builder.addLayer(Builder::ConstLayer("biases").setData(generateBlob(precision, {384}, Layout::C))); layerId = builder.addLayer({{layerId}, {weightsId}, {biasesId}}, Builder::ConvolutionLayer(alexNetNames[12]).setKernel({3, 3}) .setStrides({1, 1}).setOutDepth(384).setPaddingsBegin({1, 1}).setPaddingsEnd({1, 1}).setGroup(2).setDilation({1, 1})); layerId = builder.addLayer({{layerId}}, Builder::ReLULayer(alexNetNames[13])); weightsId = builder.addLayer(Builder::ConstLayer("weights").setData(generateBlob(precision, {256, 384 / 2, 3, 3}, Layout::OIHW))); biasesId = builder.addLayer(Builder::ConstLayer("biases").setData(generateBlob(precision, {256}, Layout::C))); layerId = builder.addLayer({{layerId}, {weightsId}, {biasesId}}, Builder::ConvolutionLayer(alexNetNames[14]).setKernel({3, 3}) .setStrides({1, 1}).setOutDepth(256).setPaddingsBegin({1, 1}).setPaddingsEnd({1, 1}).setGroup(2).setDilation({1, 1})); layerId = builder.addLayer({{layerId}}, Builder::ReLULayer(alexNetNames[15])); layerId = builder.addLayer({{layerId}}, Builder::PoolingLayer(alexNetNames[16]).setExcludePad(false).setKernel({3, 3}).setPaddingsBegin({0, 0}) .setPaddingsEnd({0, 0}).setPoolingType(Builder::PoolingLayer::PoolingType::MAX).setStrides({2, 2})); weightsId = builder.addLayer(Builder::ConstLayer("weights").setData(generateBlob(precision, {4096, 256, 6, 6}, Layout::OIHW))); biasesId = builder.addLayer(Builder::ConstLayer("biases").setData(generateBlob(precision, {4096}, Layout::C))); layerId = builder.addLayer({{layerId}, {weightsId}, {biasesId}}, Builder::FullyConnectedLayer(alexNetNames[17]).setOutputNum(4096)); layerId = builder.addLayer({{layerId}}, Builder::ReLULayer(alexNetNames[18])); weightsId = builder.addLayer(Builder::ConstLayer("weights").setData(generateBlob(precision, {4096, 4096}, Layout::NC))); biasesId = builder.addLayer(Builder::ConstLayer("biases").setData(generateBlob(precision, {4096}, Layout::C))); layerId = builder.addLayer({{layerId}, {weightsId}, {biasesId}}, Builder::FullyConnectedLayer(alexNetNames[19]).setOutputNum(4096)); layerId = builder.addLayer({{layerId}}, Builder::ReLULayer(alexNetNames[20])); weightsId = builder.addLayer(Builder::ConstLayer("weights").setData(generateBlob(precision, {1000, 4096}, Layout::NC))); biasesId = builder.addLayer(Builder::ConstLayer("biases").setData(generateBlob(precision, {1000}, Layout::C))); layerId = builder.addLayer({{layerId}, {weightsId}, {biasesId}}, Builder::FullyConnectedLayer(alexNetNames[21]).setOutputNum(1000)); layerId = builder.addLayer({{layerId}}, Builder::SoftMaxLayer(alexNetNames[22]).setAxis(1)); idx_t outputId = builder.addLayer({PortInfo(layerId)}, Builder::OutputLayer(alexNetNames[23])); return builder; } const INetwork::CPtr createAlexnet() { return prepateAlexnetBuilder().build(); } void compareWithICNNNetwork(const INetwork& network, const ICNNNetwork& cnnNetwork) { for (const auto& layer : network) { auto connections = network.getLayerConnections(layer->getId()); CNNLayerPtr cnnLayer; StatusCode sts = cnnNetwork.getLayerByName(layer->getName().c_str(), cnnLayer, nullptr); if (sts != OK && (layer->getType() == "Output" || layer->getType() == "Const")) continue; else if (sts != OK) THROW_IE_EXCEPTION << "Cannot find CNNLayer by name: " << layer->getName(); // Output connections for (size_t i = 0; i < cnnLayer->outData.size(); i++) { for (const auto& it : cnnLayer->outData[i]->getInputTo()) { size_t j = 0; for (; j < it.second->insData.size(); j++) { auto lockedData = it.second->insData[j].lock(); if (lockedData && lockedData.get() == cnnLayer->outData[i].get()) { break; } } for (auto conIt = connections.begin(); conIt != connections.end(); conIt++) { const auto& inputPorts = network.getLayer(conIt->to().layerId())->getInputPorts(); idx_t realPortId(0); for (size_t q = 0; q < conIt->to().portId() && q < inputPorts.size(); q++) { if (inputPorts[q].getParameters().find("type") == inputPorts[q].getParameters().end()) realPortId++; } if (conIt->from().layerId() == layer->getId() && conIt->from().portId() == i && network.getLayer(conIt->to().layerId())->getName() == it.second->name && realPortId == j) { connections.erase(conIt); break; } } } } // Input connections for (size_t i = 0; i < cnnLayer->insData.size(); i++) { auto inData = cnnLayer->insData[i].lock(); if (!inData) continue; auto creatorLayer = inData->getCreatorLayer().lock(); if (!creatorLayer) continue; size_t j = 0; for (; j < creatorLayer->outData.size(); j++) { if (creatorLayer->outData[j] && creatorLayer->outData[j].get() == inData.get()) { break; } } for (auto conIt = connections.begin(); conIt != connections.end(); conIt++) { if (conIt->to().layerId() == layer->getId() && conIt->from().portId() == j && network.getLayer(conIt->from().layerId())->getName() == creatorLayer->name && conIt->to().portId() == i) { connections.erase(conIt); break; } } } if (connections.size() == 1 && network.getLayer(connections[0].to().layerId())->getType() == "Output") connections.erase(connections.begin()); bool connectionsConnected = true; for (const auto& connection : connections) { if (connection.to().layerId() != layer->getId()) { connectionsConnected = false; break; } const auto& port = layer->getInputPorts()[connection.to().portId()]; if (port.getParameters().find("type") == port.getParameters().end()) { connectionsConnected = false; break; } } if (!connectionsConnected) THROW_IE_EXCEPTION << "Not all connections were connected."; } } void compareICNNNetworks(const ICNNNetwork& newNetwork, const ICNNNetwork& oldNetwork) { IE_SUPPRESS_DEPRECATED_START CNNNetwork network((ICNNNetwork*)&newNetwork); IE_SUPPRESS_DEPRECATED_END if (newNetwork.layerCount() != oldNetwork.layerCount()) THROW_IE_EXCEPTION << "ICNNNetworks have different numbers of layers!"; for (const auto& layer : network) { CNNLayerPtr oldLayer; StatusCode sts = oldNetwork.getLayerByName(layer->name.c_str(), oldLayer, nullptr); bool success = sts == OK && layer->name == oldLayer->name && layer->type == oldLayer->type && layer->insData.size() == oldLayer->insData.size() && layer->outData.size() == oldLayer->outData.size() && layer->precision == oldLayer->precision; for (size_t i = 0; i < layer->insData.size() && success; i++) { auto lockedOldData = oldLayer->insData[i].lock(); auto lockedData = layer->insData[i].lock(); success = success && lockedOldData->getName() == lockedData->getName() && lockedOldData->getTensorDesc() == lockedData->getTensorDesc(); } for (size_t i = 0; i < layer->outData.size() && success; i++) { success = success && oldLayer->outData[i]->getName() == layer->outData[i]->getName() && oldLayer->outData[i]->getTensorDesc() == layer->outData[i]->getTensorDesc(); } if (!success) THROW_IE_EXCEPTION << "ICNNNetworks have different layers!"; } InputsDataMap newInput; OutputsDataMap newOutput; newNetwork.getInputsInfo(newInput); newNetwork.getOutputsInfo(newOutput); InputsDataMap oldInput; OutputsDataMap oldOutput; oldNetwork.getInputsInfo(oldInput); oldNetwork.getOutputsInfo(oldOutput); bool success = newInput.size() == oldInput.size(); for (const auto& it : newInput) { if (!success) break; success = success && oldInput.find(it.first) != oldInput.end(); } if (!success) THROW_IE_EXCEPTION << "ICNNNetworks have different inputs!"; success = newOutput.size() == oldOutput.size(); for (const auto& it : newOutput) { if (!success) break; success = success && oldOutput.find(it.first) != oldOutput.end(); } if (!success) THROW_IE_EXCEPTION << "ICNNNetworks have different outputs!"; } }; TEST_F(NetworkBuilderTest, checkReshapeAlexNet) { std::map<std::string, std::vector<SizeVector>> inPorts = { {alexNetNames[0], {}}, {alexNetNames[1], {{1, 3, 227, 227}}}, {alexNetNames[2], {{1, 3, 227, 227}}}, {alexNetNames[3], {{1, 96, 55, 55}}}, {alexNetNames[4], {{1, 96, 55, 55}}}, {alexNetNames[5], {{1, 96, 55, 55}}}, {alexNetNames[6], {{1, 96, 27, 27}}}, {alexNetNames[7], {{1, 256, 27, 27}}}, {alexNetNames[8], {{1, 256, 27, 27}}}, {alexNetNames[9], {{1, 256, 27, 27}}}, {alexNetNames[10], {{1, 256, 13, 13}}}, {alexNetNames[11], {{1, 384, 13, 13}}}, {alexNetNames[12], {{1, 384, 13, 13}}}, {alexNetNames[13], {{1, 384, 13, 13}}}, {alexNetNames[14], {{1, 384, 13, 13}}}, {alexNetNames[15], {{1, 256, 13, 13}}}, {alexNetNames[16], {{1, 256, 13, 13}}}, {alexNetNames[17], {{1, 256, 6, 6}}}, {alexNetNames[18], {{1, 4096}}}, {alexNetNames[19], {{1, 4096}}}, {alexNetNames[20], {{1, 4096}}}, {alexNetNames[21], {{1, 4096}}}, {alexNetNames[22], {{1, 1000}}}, {alexNetNames[23], {{1, 1000}}} }; std::map<std::string, std::vector<SizeVector>> outPorts = { {alexNetNames[0], {{1, 3, 227, 227}}}, {alexNetNames[1], {{1, 3, 227, 227}}}, {alexNetNames[2], {{1, 96, 55, 55}}}, {alexNetNames[3], {{1, 96, 55, 55}}}, {alexNetNames[4], {{1, 96, 55, 55}}}, {alexNetNames[5], {{1, 96, 27, 27}}}, {alexNetNames[6], {{1, 256, 27, 27}}}, {alexNetNames[7], {{1, 256, 27, 27}}}, {alexNetNames[8], {{1, 256, 27, 27}}}, {alexNetNames[9], {{1, 256, 13, 13}}}, {alexNetNames[10], {{1, 384, 13, 13}}}, {alexNetNames[11], {{1, 384, 13, 13}}}, {alexNetNames[12], {{1, 384, 13, 13}}}, {alexNetNames[13], {{1, 384, 13, 13}}}, {alexNetNames[14], {{1, 256, 13, 13}}}, {alexNetNames[15], {{1, 256, 13, 13}}}, {alexNetNames[16], {{1, 256, 6, 6}}}, {alexNetNames[17], {{1, 4096}}}, {alexNetNames[18], {{1, 4096}}}, {alexNetNames[19], {{1, 4096}}}, {alexNetNames[20], {{1, 4096}}}, {alexNetNames[21], {{1, 1000}}}, {alexNetNames[22], {{1, 1000}}}, {alexNetNames[23], {}} }; Builder::Network builder = prepateAlexnetBuilder(); for (const auto &layer : builder.getLayers()) { if (layer->getType() == "Input") { ASSERT_EQ(outPorts[layer->getName()][0], layer->getOutputPorts()[0].shape()); } else if (layer->getType() != "Const") { for (const auto &port : layer->getOutputPorts()) { ASSERT_TRUE(port.shape().empty()); } } } INetwork::CPtr graph; ASSERT_NO_THROW(graph = builder.build()); for (const auto &layer : *graph) { if (layer->getType() == "Const") continue; for (size_t i = 0; i < layer->getInputPorts().size(); i++) { if (layer->getInputPorts()[i].getParameters().find("type") != layer->getInputPorts()[i].getParameters().end()) continue; ASSERT_EQ(inPorts[layer->getName()][i], layer->getInputPorts()[i].shape()); } for (size_t i = 0; i < layer->getOutputPorts().size(); i++) { ASSERT_EQ(outPorts[layer->getName()][i], layer->getOutputPorts()[i].shape()); } } } TEST_F(NetworkBuilderTest, checkNoImplWithCorrectPorts) { Context ctx; Builder::Network builder(ctx, "TestAlexNet"); idx_t inId = builder.addLayer(Builder::InputLayer(alexNetNames[0]).setPort(Port({1,3, 227, 227}))); idx_t weightsId = builder.addLayer(Builder::ConstLayer("weights").setData(generateBlob(Precision::FP32, {96, 3, 11, 11}, Layout::OIHW))); idx_t biasesId = builder.addLayer(Builder::ConstLayer("biases").setData(generateBlob(Precision::FP32, {96}, Layout::C))); idx_t convId = builder.addLayer({{inId}, {weightsId}, {biasesId}}, Builder::ConvolutionLayer(alexNetNames[2]).setKernel({11, 11}) .setStrides({4, 4}).setOutDepth(96).setInputPort(Port({1,3, 227, 227})).setOutputPort(Port({1, 96, 55, 55}))); idx_t testLayerId = builder.addLayer({PortInfo(convId)}, Builder::Layer("TestLayer", "testPort") .setInputPorts({Port({1, 96, 55, 55})}).setOutputPorts({Port({1, 96, 55, 55})})); idx_t outputId = builder.addLayer({PortInfo(testLayerId)}, Builder::OutputLayer("out").setPort({Port({1, 96, 55, 55})})); ASSERT_NO_THROW(builder.build()); } TEST_F(NetworkBuilderTest, checkNoImplWithIncorrectPorts) { Context ctx; Builder::Network builder(ctx, "TestAlexNet"); idx_t inId = builder.addLayer(Builder::InputLayer(alexNetNames[0]).setPort(Port({1,3, 227, 227}))); idx_t weightsId = builder.addLayer(Builder::ConstLayer("weights").setData(generateBlob(Precision::FP32, {96, 3, 11, 11}, Layout::OIHW))); idx_t biasesId = builder.addLayer(Builder::ConstLayer("biases").setData(generateBlob(Precision::FP32, {96}, Layout::C))); idx_t convId = builder.addLayer({{inId}, {weightsId}, {biasesId}}, Builder::ConvolutionLayer(alexNetNames[2]).setKernel({11, 11}) .setStrides({4, 4}).setOutDepth(96).setInputPort(Port({1,3, 227, 227})).setOutputPort(Port({1, 96, 55, 55}))); ASSERT_THROW(builder.addLayer({PortInfo(convId)}, Builder::Layer("TestLayer", "testPort") .setInputPorts({Port({1, 3, 55, 55})}).setOutputPorts({Port({1, 96, 55, 55})})), InferenceEngine::details::InferenceEngineException); } TEST_F(NetworkBuilderTest, createNetworkIterator) { const INetwork::CPtr graph = createAlexnet(); ASSERT_NO_THROW(graph->begin()); } TEST_F(NetworkBuilderTest, checkNetworkSize) { const INetwork::CPtr graph = createAlexnet(); ASSERT_EQ(41, graph->size()); } TEST_F(NetworkBuilderTest, iterateNetworkForeach) { const INetwork::CPtr graph = createAlexnet(); size_t idx = 0; for (const auto& layer : *graph) { if (layer->getType() == "Const") continue; ASSERT_NE(idx, alexNetNames.size()); ASSERT_EQ(alexNetNames[idx], layer->getName()); idx++; } } TEST_F(NetworkBuilderTest, iterateNetworkFor) { const INetwork::CPtr graph = createAlexnet(); size_t idx = 0; for (auto it = graph->begin(); it != graph->end(); it++) { if ((*it)->getType() == "Const") continue; ASSERT_EQ(alexNetNames[idx], (*it)->getName()); idx++; } } TEST_F(NetworkBuilderTest, convertFromICNNNetwork) { std::string model = R"V0G0N( <net name="PVANET" version="2" batch="1"> <layers> <layer name="data" type="Input" precision="FP32" id="0"> <output> <port id="0"> <dim>1</dim> <dim>3</dim> <dim>544</dim> <dim>992</dim> </port> </output> </layer> <layer name="conv1_1_conv" type="Convolution" precision="FP32" id="2"> <convolution_data stride-x="2" stride-y="2" pad-x="3" pad-y="3" kernel-x="7" kernel-y="7" output="16" group="1"/> <input> <port id="2"> <dim>1</dim> <dim>3</dim> <dim>544</dim> <dim>992</dim> </port> </input> <output> <port id="3"> <dim>1</dim> <dim>16</dim> <dim>272</dim> <dim>496</dim> </port> </output> <weights offset="0" size="9408"/> <biases offset="9408" size="64"/> </layer> <layer name="conv1_1_neg" type="Power" precision="FP32" id="3"> <power_data power="1" scale="-1" shift="0"/> <input> <port id="4"> <dim>1</dim> <dim>16</dim> <dim>272</dim> <dim>496</dim> </port> </input> <output> <port id="5"> <dim>1</dim> <dim>16</dim> <dim>272</dim> <dim>496</dim> </port> </output> </layer> <layer name="conv1_1_concat" type="Concat" precision="FP32" id="4"> <concat_data axis="1"/> <input> <port id="6"> <dim>1</dim> <dim>16</dim> <dim>272</dim> <dim>496</dim> </port> <port id="7"> <dim>1</dim> <dim>16</dim> <dim>272</dim> <dim>496</dim> </port> </input> <output> <port id="8"> <dim>1</dim> <dim>32</dim> <dim>272</dim> <dim>496</dim> </port> </output> </layer> <layer name="conv1_1_scale" type="ScaleShift" precision="FP32" id="5"> <input> <port id="9"> <dim>1</dim> <dim>32</dim> <dim>272</dim> <dim>496</dim> </port> </input> <output> <port id="10"> <dim>1</dim> <dim>32</dim> <dim>272</dim> <dim>496</dim> </port> </output> <weights offset="9472" size="128"/> <biases offset="9600" size="128"/> </layer> <layer name="conv1_1_relu" type="ReLU" precision="FP32" id="6"> <data negative_slope="0" engine="caffe.ReLUParameter.DEFAULT"/> <input> <port id="11"> <dim>1</dim> <dim>32</dim> <dim>272</dim> <dim>496</dim> </port> </input> <output> <port id="12"> <dim>1</dim> <dim>32</dim> <dim>272</dim> <dim>496</dim> </port> </output> </layer> <layer name="pool1" type="Pooling" precision="FP32" id="7"> <pooling_data kernel-x="3" kernel-y="3" pad-x="0" pad-y="0" stride-x="2" stride-y="2" rounding-type="ceil" pool-method="max"/> <input> <port id="13"> <dim>1</dim> <dim>32</dim> <dim>272</dim> <dim>496</dim> </port> </input> <output> <port id="14"> <dim>1</dim> <dim>32</dim> <dim>136</dim> <dim>248</dim> </port> </output> </layer> </layers> <edges> <edge from-layer="0" from-port="0" to-layer="2" to-port="2"/> <edge from-layer="2" from-port="3" to-layer="3" to-port="4"/> <edge from-layer="2" from-port="3" to-layer="4" to-port="6"/> <edge from-layer="3" from-port="5" to-layer="4" to-port="7"/> <edge from-layer="4" from-port="8" to-layer="5" to-port="9"/> <edge from-layer="5" from-port="10" to-layer="6" to-port="11"/> <edge from-layer="6" from-port="12" to-layer="7" to-port="13"/> </edges> </net>)V0G0N"; InferenceEngine::CNNNetReader net_reader; ASSERT_NO_THROW(net_reader.ReadNetwork(model.data(), model.length())); InferenceEngine::TBlob<uint8_t> *weights = new InferenceEngine::TBlob<uint8_t>({ InferenceEngine::Precision::U8, {9728}, InferenceEngine::C }); weights->allocate(); fill_data((float *) weights->buffer(), weights->size() / sizeof(float)); InferenceEngine::TBlob<uint8_t>::Ptr weights_ptr = InferenceEngine::TBlob<uint8_t>::Ptr(weights); net_reader.SetWeights(weights_ptr); INetwork::CPtr network = Builder::Network(net_reader.getNetwork()).build(); try { compareWithICNNNetwork(*network, net_reader.getNetwork()); } catch (InferenceEngine::details::InferenceEngineException &ex) { FAIL() << ex.what(); } } TEST_F(NetworkBuilderTest, convertFromICNNNetworkToICNNNetwork) { std::string model = R"V0G0N( <net name="PVANET" version="2" batch="1"> <layers> <layer name="data" type="Input" precision="FP32" id="0"> <output> <port id="0"> <dim>1</dim> <dim>3</dim> <dim>544</dim> <dim>992</dim> </port> </output> </layer> <layer name="conv1_1_conv" type="Convolution" precision="FP32" id="2"> <convolution_data stride-x="2" stride-y="2" pad-x="3" pad-y="3" kernel-x="7" kernel-y="7" output="16" group="1"/> <input> <port id="2"> <dim>1</dim> <dim>3</dim> <dim>544</dim> <dim>992</dim> </port> </input> <output> <port id="3"> <dim>1</dim> <dim>16</dim> <dim>272</dim> <dim>496</dim> </port> </output> <weights offset="0" size="9408"/> <biases offset="9408" size="64"/> </layer> <layer name="conv1_1_neg" type="Power" precision="FP32" id="3"> <power_data power="1" scale="-1" shift="0"/> <input> <port id="4"> <dim>1</dim> <dim>16</dim> <dim>272</dim> <dim>496</dim> </port> </input> <output> <port id="5"> <dim>1</dim> <dim>16</dim> <dim>272</dim> <dim>496</dim> </port> </output> </layer> <layer name="conv1_1_concat" type="Concat" precision="FP32" id="4"> <concat_data axis="1"/> <input> <port id="6"> <dim>1</dim> <dim>16</dim> <dim>272</dim> <dim>496</dim> </port> <port id="7"> <dim>1</dim> <dim>16</dim> <dim>272</dim> <dim>496</dim> </port> </input> <output> <port id="8"> <dim>1</dim> <dim>32</dim> <dim>272</dim> <dim>496</dim> </port> </output> </layer> <layer name="conv1_1_scale" type="ScaleShift" precision="FP32" id="5"> <input> <port id="9"> <dim>1</dim> <dim>32</dim> <dim>272</dim> <dim>496</dim> </port> </input> <output> <port id="10"> <dim>1</dim> <dim>32</dim> <dim>272</dim> <dim>496</dim> </port> </output> <weights offset="9472" size="128"/> <biases offset="9600" size="128"/> </layer> <layer name="conv1_1_relu" type="ReLU" precision="FP32" id="6"> <data negative_slope="0" engine="caffe.ReLUParameter.DEFAULT"/> <input> <port id="11"> <dim>1</dim> <dim>32</dim> <dim>272</dim> <dim>496</dim> </port> </input> <output> <port id="12"> <dim>1</dim> <dim>32</dim> <dim>272</dim> <dim>496</dim> </port> </output> </layer> <layer name="pool1" type="Pooling" precision="FP32" id="7"> <pooling_data kernel-x="3" kernel-y="3" pad-x="0" pad-y="0" stride-x="2" stride-y="2" rounding-type="ceil" pool-method="max"/> <input> <port id="13"> <dim>1</dim> <dim>32</dim> <dim>272</dim> <dim>496</dim> </port> </input> <output> <port id="14"> <dim>1</dim> <dim>32</dim> <dim>136</dim> <dim>248</dim> </port> </output> </layer> </layers> <edges> <edge from-layer="0" from-port="0" to-layer="2" to-port="2"/> <edge from-layer="2" from-port="3" to-layer="3" to-port="4"/> <edge from-layer="2" from-port="3" to-layer="4" to-port="6"/> <edge from-layer="3" from-port="5" to-layer="4" to-port="7"/> <edge from-layer="4" from-port="8" to-layer="5" to-port="9"/> <edge from-layer="5" from-port="10" to-layer="6" to-port="11"/> <edge from-layer="6" from-port="12" to-layer="7" to-port="13"/> </edges> </net>)V0G0N"; InferenceEngine::CNNNetReader net_reader; ASSERT_NO_THROW(net_reader.ReadNetwork(model.data(), model.length())); InferenceEngine::TBlob<uint8_t> *weights = new InferenceEngine::TBlob<uint8_t>({ InferenceEngine::Precision::U8, {9728}, InferenceEngine::C }); weights->allocate(); fill_data((float *) weights->buffer(), weights->size() / sizeof(float)); InferenceEngine::TBlob<uint8_t>::Ptr weights_ptr = InferenceEngine::TBlob<uint8_t>::Ptr(weights); net_reader.SetWeights(weights_ptr); std::shared_ptr<ICNNNetwork> network = Builder::convertToICNNNetwork(Builder::Network(net_reader.getNetwork()).build()); try { compareICNNNetworks(*network, net_reader.getNetwork()); } catch (InferenceEngine::details::InferenceEngineException &ex) { FAIL() << ex.what(); } } TEST_F(NetworkBuilderTest, connectTwoNetworks) { std::string model = R"V0G0N( <net name="PVANET" version="2" batch="1"> <layers> <layer name="data" type="Input" precision="FP32" id="0"> <output> <port id="0"> <dim>1</dim> <dim>3</dim> <dim>544</dim> <dim>992</dim> </port> </output> </layer> <layer name="conv1_1_conv" type="Convolution" precision="FP32" id="2"> <convolution_data stride-x="2" stride-y="2" pad-x="3" pad-y="3" pad-r="3" pad-b="3" kernel-x="7" kernel-y="7" output="16" group="1"/> <input> <port id="2"> <dim>1</dim> <dim>3</dim> <dim>544</dim> <dim>992</dim> </port> </input> <output> <port id="3"> <dim>1</dim> <dim>16</dim> <dim>272</dim> <dim>496</dim> </port> </output> <weights offset="0" size="9408"/> <biases offset="9408" size="64"/> </layer> <layer name="conv1_1_neg" type="Power" precision="FP32" id="3"> <power_data power="1" scale="-1" shift="0"/> <input> <port id="4"> <dim>1</dim> <dim>16</dim> <dim>272</dim> <dim>496</dim> </port> </input> <output> <port id="5"> <dim>1</dim> <dim>16</dim> <dim>272</dim> <dim>496</dim> </port> </output> </layer> <layer name="conv1_1_concat" type="Concat" precision="FP32" id="4"> <concat_data axis="1"/> <input> <port id="6"> <dim>1</dim> <dim>16</dim> <dim>272</dim> <dim>496</dim> </port> <port id="7"> <dim>1</dim> <dim>16</dim> <dim>272</dim> <dim>496</dim> </port> </input> <output> <port id="8"> <dim>1</dim> <dim>32</dim> <dim>272</dim> <dim>496</dim> </port> </output> </layer> </layers> <edges> <edge from-layer="0" from-port="0" to-layer="2" to-port="2"/> <edge from-layer="2" from-port="3" to-layer="3" to-port="4"/> <edge from-layer="2" from-port="3" to-layer="4" to-port="6"/> <edge from-layer="3" from-port="5" to-layer="4" to-port="7"/> </edges> </net>)V0G0N"; InferenceEngine::CNNNetReader net_reader; ASSERT_NO_THROW(net_reader.ReadNetwork(model.data(), model.length())); InferenceEngine::TBlob<uint8_t> *weights = new InferenceEngine::TBlob<uint8_t>({ InferenceEngine::Precision::U8, {9472}, InferenceEngine::C }); weights->allocate(); fill_data((float *) weights->buffer(), weights->size() / sizeof(float)); InferenceEngine::TBlob<uint8_t>::Ptr weights_ptr = InferenceEngine::TBlob<uint8_t>::Ptr(weights); net_reader.SetWeights(weights_ptr); Builder::Network originalNetwork(net_reader.getNetwork()); Builder::Network addNetwork(net_reader.getNetwork()); // Find output idx_t lastLayerId(0); for (const auto& layer : originalNetwork.getLayers()) { if (layer->getType() != "Output") continue; const auto connections = originalNetwork.getLayerConnections(layer->getId()); ASSERT_EQ(1, connections.size()); ASSERT_EQ(layer->getId(), connections[0].to().layerId()); ASSERT_EQ(0, connections[0].from().portId()); lastLayerId = connections[0].from().layerId(); originalNetwork.disconnect(connections[0]); originalNetwork.removeLayer(layer->getId()); break; } std::map<idx_t, idx_t> oldNewId; for (const auto& layer : addNetwork) { if (layer->getType() == "Input") { oldNewId[layer->getId()] = lastLayerId; continue; } auto newLayer = layer; if (newLayer->getType() != "Const") { for (size_t i = 0; i < newLayer->getInputPorts().size(); i++) { newLayer->getInputPorts()[i].setData(std::make_shared<PortData>()); } for (size_t i = 0; i < newLayer->getOutputPorts().size(); i++) { newLayer->getOutputPorts()[i].setData(std::make_shared<PortData>()); } } oldNewId[layer->getId()] = originalNetwork.addLayer(*newLayer); const auto connections = addNetwork.getLayerConnections(layer->getId()); for (const auto& connection : connections) { if (oldNewId.find(connection.from().layerId()) == oldNewId.end() || oldNewId.find(connection.to().layerId()) == oldNewId.end()) continue; originalNetwork.connect({oldNewId[connection.from().layerId()], connection.from().portId()}, {oldNewId[connection.to().layerId()], connection.to().portId()}); } if (layer->getType() == "Convolution") { idx_t weightsId = originalNetwork.addLayer(Builder::ConstLayer("weights").setData(generateBlob(Precision::FP32, {16, 32, 7, 7}, Layout::OIHW))); for (const auto& connection : originalNetwork.getLayerConnections(oldNewId[layer->getId()])) { if (connection.to().layerId() != oldNewId[layer->getId()] || connection.to().portId() != 1) continue; originalNetwork.removeLayer(connection.from().layerId()); originalNetwork.disconnect(connection); } originalNetwork.connect({weightsId}, {oldNewId[layer->getId()], 1}); } } ASSERT_NO_THROW(originalNetwork.build()); } TEST_F(NetworkBuilderTest, createLayersWithTheSameNames) { InferenceEngine::Builder::Network netBuilder(""); // Connect conolutional layer with it's inputs and outputs. InferenceEngine::Builder::InputLayer inpLayer("data"); inpLayer.setPort(InferenceEngine::Port({1, 1, 10, 10})); auto inpLayerId = netBuilder.addLayer(inpLayer); // Create convolutional layer const size_t outCn = 1, inpCn = 1, kernelH = 3, kernelW = 3; InferenceEngine::Builder::ConvolutionLayer ieLayer("conv1"); ieLayer.setKernel({outCn, inpCn, kernelH, kernelW}); ieLayer.setStrides({1, 1, 1, 1}); ieLayer.setDilation({1, 1, 1, 1}); ieLayer.setPaddingsBegin({0, 0, 0, 0}); ieLayer.setPaddingsEnd({0, 0, 0, 0}); ieLayer.setGroup(1); ieLayer.setOutDepth(outCn); idx_t weightsId = netBuilder.addLayer(Builder::ConstLayer("weights").setData(generateBlob(Precision::FP32, {1, 1, 3, 3}, Layout::OIHW))); auto convLayerId = netBuilder.addLayer({{inpLayerId}, {weightsId}}, ieLayer); // Connect convolution layer with it's output InferenceEngine::Builder::OutputLayer outLayer("conv1"); auto convOutLayerId = netBuilder.addLayer({convLayerId}, outLayer); ASSERT_NE(netBuilder.getLayer(convLayerId)->getName(), netBuilder.getLayer(convOutLayerId)->getName()); InferenceEngine::Builder::ReLULayer reLULayer("relu1"); reLULayer.setNegativeSlope(0); auto reluLayerId = netBuilder.addLayer({convLayerId}, reLULayer); InferenceEngine::Builder::OutputLayer outReLULayer("relu1"); auto reluOutLayerId = netBuilder.addLayer({reluLayerId}, outReLULayer); ASSERT_NE(netBuilder.getLayer(reluLayerId)->getName(), netBuilder.getLayer(reluOutLayerId)->getName()); ASSERT_NO_THROW(netBuilder.build()); } TEST_F(NetworkBuilderTest, RemoveLayerAndBuild) { auto builder = prepateAlexnetBuilder(); builder.removeLayer(builder.getLayers()[2]->getId()); ASSERT_THROW(builder.build(), InferenceEngine::details::InferenceEngineException); } TEST_F(NetworkBuilderTest, CheckConnectionsData) { auto builder = prepateAlexnetBuilder(); for (const auto& connection : builder.getConnections()) { const auto srcPort = builder.getLayer(connection.from().layerId())->getOutputPorts()[connection.from().portId()]; const auto dstPort = builder.getLayer(connection.to().layerId())->getInputPorts()[connection.to().portId()]; ASSERT_EQ(srcPort.getData(), dstPort.getData()); } } TEST_F(NetworkBuilderTest, DocumentationExample) { // Create graph with name InferenceEngine::Builder::Network graph("Example1"); // Create network // In-place add input layer idx_t inputLayerId = graph.addLayer(Builder::InputLayer("in").setPort(Port({1, 3, 22, 22}))); // In-place add ReLU layer builder with a negative slope 0.1 and connect it with 0 output port of the Input layer builder // In this example layerId is equal new Input layer builder ID, port index isn't set because 0 is a default value ({layerId} == {layerId, 0}) idx_t relu1Id = graph.addLayer({{inputLayerId}}, Builder::ReLULayer("relu1").setNegativeSlope(0.1f)); // In-place add ScaleShift layer builder InferenceEngine::Blob::Ptr blobWithScaleShiftBiases = make_shared_blob<float>(TensorDesc(Precision::FP32, {3}, Layout::C)); blobWithScaleShiftBiases->allocate(); auto *data = blobWithScaleShiftBiases->buffer().as<float *>(); data[0] = 1; data[1] = 2; data[2] = 3; idx_t biasesId = graph.addLayer(Builder::ConstLayer("biases").setData(blobWithScaleShiftBiases)); idx_t scaleShiftId = graph.addLayer(Builder::ScaleShiftLayer("scaleShift1")); // Connect ScaleShift layer with relu1 graph.connect({relu1Id}, {scaleShiftId}); // Also port indexes could be defined (0 is default value) builder.connect({layerId, outPortIdx}, {scaleShiftId, inPortIdx}); graph.connect({biasesId}, {scaleShiftId, 2}); // Create ReLU layer with a negative slope 0.2 using generic layer builder and connect it with scaleShift idx_t relu2Id = graph.addLayer({{scaleShiftId}}, Builder::Layer("ReLU", "relu2").setParameters({{"negative_slope", 0.2f}}).setOutputPorts({Port()}).setInputPorts({Port()})); // All branches in the graph should be ended by Output layer. Let's create Output layer idx_t outId = graph.addLayer({{relu2Id, 0}}, Builder::OutputLayer("out")); // Build original network InferenceEngine::INetwork::CPtr finalNetwork = graph.build(); std::shared_ptr<InferenceEngine::ICNNNetwork> cnnNetwork = InferenceEngine::Builder::convertToICNNNetwork(finalNetwork); // Modify network // Remove relu2 layer from the topology std::vector<InferenceEngine::Connection> connections = graph.getLayerConnections(relu2Id); for (const auto& connection : connections) { graph.disconnect(connection); } graph.removeLayer(relu2Id); // Connect scaleShift1 and out graph.connect({scaleShiftId}, {outId}); // Build network without relu2 InferenceEngine::INetwork::CPtr changedNetwork = graph.build(); } TEST_F(NetworkBuilderTest, CreateFullyConnectedWithoutBiases) { Builder::Network builder("network"); Builder::FullyConnectedLayer fcBuilder("FullyConnected"); SizeVector inputDims = {1, 2, 16, 16}; // 1 KB idx_t layerId = builder.addLayer(Builder::InputLayer("input").setPort(Port(inputDims))); idx_t weightsId = builder.addLayer(Builder::ConstLayer("weights").setData(generateBlob(Precision::FP32, {1024, 2, 16, 16}, Layout::OIHW))); layerId = builder.addLayer({{layerId}, {weightsId} }, Builder::FullyConnectedLayer("FullyConnected").setOutputNum(1024 * 1)); builder.addLayer({PortInfo(layerId)}, Builder::OutputLayer("output")); ASSERT_NO_THROW(std::shared_ptr<InferenceEngine::ICNNNetwork> cnnNetwork = InferenceEngine::Builder::convertToICNNNetwork(builder.build())); } TEST_F(NetworkBuilderTest, CreateAndConvertNetworkWithoutWeightsWithConst) { Builder::Network builder("network"); idx_t layerId = builder.addLayer(Builder::InputLayer("input").setPort(Port({1, 1, 10, 10}))); layerId = builder.addLayer({layerId}, Builder::PoolingLayer("pool").setKernel({2, 2}).setStrides({2, 2}) .setPoolingType(Builder::PoolingLayer::PoolingType::MAX)); builder.addLayer({layerId}, Builder::OutputLayer("output")); layerId = builder.addLayer(Builder::ConstLayer("constWA").setData(generateBlob(Precision::FP16, {1}, Layout::C))); builder.addLayer({layerId}, Builder::OutputLayer("output_const")); auto cnnNetwork = InferenceEngine::CNNNetwork(InferenceEngine::Builder::convertToICNNNetwork(builder.build())); ASSERT_EQ(Precision::FP16, cnnNetwork.getPrecision()); } TEST_F(NetworkBuilderTest, CreateAndConvertNetworkWithoutWeights) { Builder::Network builder("network"); idx_t layerId = builder.addLayer(Builder::InputLayer("input").setPort(Port({1, 1, 10, 10}, Precision::FP16))); layerId = builder.addLayer({layerId}, Builder::PoolingLayer("pool").setKernel({2, 2}).setStrides({2, 2}) .setPoolingType(Builder::PoolingLayer::PoolingType::MAX)); builder.addLayer({layerId}, Builder::OutputLayer("output")); auto cnnNetwork = InferenceEngine::CNNNetwork(InferenceEngine::Builder::convertToICNNNetwork(builder.build())); ASSERT_EQ(Precision::FP16, cnnNetwork.getPrecision()); } TEST_F(NetworkBuilderTest, CreateAndNetworkWithPadLayer) { Builder::Network builder("network"); idx_t layerId = builder.addLayer(Builder::InputLayer("input").setPort(Port({1, 2, 3, 4}))); Builder::Layer padLayer("Pad", "padding"); padLayer.getParameters()["pads_begin"] = std::vector<int>({0, 0, 1, 1}); padLayer.getParameters()["pads_end"] = std::vector<int>({0, 0, 1, 1}); padLayer.getParameters()["pad_mode"] = std::string("constant"); padLayer.getParameters()["pad_value"] = 0; padLayer.setInputPorts(std::vector<InferenceEngine::Port>(1)); padLayer.setOutputPorts(std::vector<InferenceEngine::Port>(1)); layerId = builder.addLayer({layerId}, padLayer); builder.addLayer({layerId}, Builder::OutputLayer("output")); ASSERT_NO_THROW(InferenceEngine::CNNNetwork(InferenceEngine::Builder::convertToICNNNetwork(builder.build()))); } TEST_F(NetworkBuilderTest, CreateLSTMFromBuilder) { std::string model = R"V0G0N( <net name="LSTMTINet" precision="FP32" version="2" batch="1"> <layers> <layer name="Input0" precision="FP32" type="Input" id="0"> <output> <port id="0"> <dim>1</dim> <dim>3</dim> <dim>10</dim> </port> </output> </layer> <layer name="Input1" precision="FP32" type="Input" id="1"> <output> <port id="1"> <dim>1</dim> <dim>5</dim> </port> </output> </layer> <layer name="Input2" precision="FP32" type="Input" id="2"> <output> <port id="2"> <dim>1</dim> <dim>5</dim> </port> </output> </layer> <layer name="RNN3" precision="FP32" type="RNN" id="3"> <data axis="1" direction="Backward" hidden_size="5"></data> <input> <port id="3"> <dim>1</dim> <dim>3</dim> <dim>10</dim> </port> <port id="4"> <dim>1</dim> <dim>5</dim> </port> <port id="5"> <dim>1</dim> <dim>5</dim> </port> </input> <output> <port id="6"> <dim>1</dim> <dim>3</dim> <dim>5</dim> </port> <port id="7"> <dim>1</dim> <dim>5</dim> </port> <port id="8"> <dim>1</dim> <dim>5</dim> </port> </output> <weights offset="0" size="1200"></weights> <biases offset="1200" size="80"></biases> </layer> </layers> <edges> <edge from-layer="0" from-port="0" to-layer="3" to-port="3"></edge> <edge from-layer="1" from-port="1" to-layer="3" to-port="4"></edge> <edge from-layer="2" from-port="2" to-layer="3" to-port="5"></edge> </edges> </net> )V0G0N"; InferenceEngine::CNNNetReader net_reader; ASSERT_NO_THROW(net_reader.ReadNetwork(model.data(), model.length())); Builder::Network builder("LSTMTINet"); idx_t in0 = builder.addLayer(Builder::InputLayer("Input0").setPort(Port({1, 3, 10}))); idx_t in1 = builder.addLayer(Builder::InputLayer("Input1").setPort(Port({1, 5}))); idx_t in2 = builder.addLayer(Builder::InputLayer("Input2").setPort(Port({1, 5}))); idx_t weightId = builder.addLayer(Builder::ConstLayer("weights").setData(generateBlob(Precision::FP32, {300}, Layout::C))); idx_t biasesId = builder.addLayer(Builder::ConstLayer("biases").setData(generateBlob(Precision::FP32, {20}, Layout::C))); idx_t lstm = builder.addLayer({{in0}, {weightId}, {biasesId}}, Builder::LSTMSequenceLayer("RNN3") .setDirection("Backward") .setHiddenSize(5)); builder.getLayer(lstm)->getOutputPorts()[0].setShape({1, 3, 5}); builder.getLayer(lstm)->getOutputPorts()[1].setShape({1, 5}); builder.getLayer(lstm)->getOutputPorts()[2].setShape({1, 5}); builder.connect({in1}, {lstm, 4}); builder.connect({in2}, {lstm, 5}); builder.addLayer({{lstm, 0}}, Builder::OutputLayer("output0")); builder.addLayer({{lstm, 1}}, Builder::OutputLayer("output1")); builder.addLayer({{lstm, 2}}, Builder::OutputLayer("output2")); const auto network = Builder::convertToICNNNetwork(builder.build()); try { compareICNNNetworks(*network, net_reader.getNetwork()); } catch (InferenceEngine::details::InferenceEngineException &ex) { FAIL() << ex.what(); } } TEST_F(NetworkBuilderTest, Fp16AlexNetInputPrecision) { auto cnnNetwork = Builder::convertToICNNNetwork(prepateAlexnetBuilder(Precision::FP16).build()); OutputsDataMap outputs; InputsDataMap inputs; cnnNetwork->getInputsInfo(inputs); cnnNetwork->getOutputsInfo(outputs); auto input = inputs.begin()->second; auto output = outputs.begin()->second; ASSERT_EQ(Precision::FP32, input->getPrecision()); ASSERT_EQ(Precision::FP32, output->getPrecision()); } TEST_F(NetworkBuilderTest, CheckPreProcessAlexNet) { auto cnnNetwork = Builder::convertToICNNNetwork(createAlexnet()); InputsDataMap inputs; cnnNetwork->getInputsInfo(inputs); auto input = inputs.begin()->second; ASSERT_NE(input->getPreProcess().getResizeAlgorithm(), ResizeAlgorithm::RESIZE_BILINEAR); input->getPreProcess().setResizeAlgorithm(ResizeAlgorithm::RESIZE_BILINEAR); auto newCnnNetwork = Builder::convertToICNNNetwork(Builder::Network(*cnnNetwork).build()); newCnnNetwork->getInputsInfo(inputs); input = inputs.begin()->second; ASSERT_EQ(input->getPreProcess().getResizeAlgorithm(), ResizeAlgorithm::RESIZE_BILINEAR); } TEST_F(NetworkBuilderTest, ReshapeNetworkTest) { std::string model = R"V0G0N( <net name="Reshape" version="2" batch="1"> <layers> <layer name="data" type="Input" precision="FP32" id="0"> <output> <port id="0"> <dim>1</dim> <dim>1000</dim> <dim>1</dim> <dim>1</dim> </port> </output> </layer> <layer id="1" name="flatten" precision="FP32" type="Reshape"> <data axis="1"/> <input> <port id="0"> <dim>1</dim> <dim>1000</dim> <dim>1</dim> <dim>1</dim> </port> </input> <output> <port id="1"> <dim>1</dim> <dim>1000</dim> </port> </output> </layer> </layers> <edges> <edge from-layer="0" from-port="0" to-layer="1" to-port="0"/> </edges> </net>)V0G0N"; InferenceEngine::CNNNetReader net_reader; ASSERT_NO_THROW(net_reader.ReadNetwork(model.data(), model.length())); auto network = Builder::convertToICNNNetwork(Builder::Network(net_reader.getNetwork()).build()); CNNLayerPtr layer; network->getLayerByName("flatten", layer, nullptr); ASSERT_EQ(layer->outData[0]->getDims().size(), 2); try { compareICNNNetworks(*network, net_reader.getNetwork()); } catch (InferenceEngine::details::InferenceEngineException &ex) { FAIL() << ex.what(); } }
// This code contains NVIDIA Confidential Information and is disclosed to you // under a form of NVIDIA software license agreement provided separately to you. // // Notice // NVIDIA Corporation and its licensors retain all intellectual property and // proprietary rights in and to this software and related documentation and // any modifications thereto. Any use, reproduction, disclosure, or // distribution of this software and related documentation without an express // license agreement from NVIDIA Corporation is strictly prohibited. // // ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES // NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO // THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, // MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. // // Information and code furnished is believed to be accurate and reliable. // However, NVIDIA Corporation assumes no responsibility for the consequences of use of such // information or for any infringement of patents or other rights of third parties that may // result from its use. No license is granted by implication or otherwise under any patent // or patent rights of NVIDIA Corporation. Details are subject to change without notice. // This code supersedes and replaces all information previously supplied. // NVIDIA Corporation products are not authorized for use as critical // components in life support devices or systems without express written approval of // NVIDIA Corporation. // // Copyright (c) 2008-2014 NVIDIA Corporation. All rights reserved. #include <RendererConfig.h> #if defined(RENDERER_ENABLE_DIRECT3D11) #include "D3D11RendererDirectionalLight.h" using namespace SampleRenderer; D3D11RendererDirectionalLight::D3D11RendererDirectionalLight(D3D11Renderer& renderer, const RendererDirectionalLightDesc& desc) : RendererDirectionalLight(desc), m_renderer(renderer) { } D3D11RendererDirectionalLight::~D3D11RendererDirectionalLight(void) { } void D3D11RendererDirectionalLight::bind(PxU32 lightIndex) const { D3D11Renderer::D3D11ShaderEnvironment& shaderEnv = m_renderer.getShaderEnvironment(); if (lightIndex < RENDERER_MAX_LIGHTS) { convertToD3D11(shaderEnv.lightColor[lightIndex], m_color); shaderEnv.lightDirection[lightIndex] = m_direction; shaderEnv.lightIntensity[lightIndex] = m_intensity; shaderEnv.lightType[lightIndex] = RendererMaterial::PASS_DIRECTIONAL_LIGHT; shaderEnv.bindLight(lightIndex); } } #endif // #if defined(RENDERER_ENABLE_DIRECT3D11)
/*============================================================================= Copyright (c) 2011-2015 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef SPROUT_LIBS_ALGORITHM_TEST_ANY_OF_EQUAL_CPP #define SPROUT_LIBS_ALGORITHM_TEST_ANY_OF_EQUAL_CPP #include <sprout/algorithm/any_of_equal.hpp> #include <sprout/array.hpp> #include <sprout/container.hpp> #include <testspr/tools.hpp> namespace testspr { static void algorithm_any_of_equal_test() { using namespace sprout; { SPROUT_STATIC_CONSTEXPR auto arr1 = array<int, 10>{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}}; { SPROUT_STATIC_CONSTEXPR auto result = sprout::any_of_equal( sprout::begin(arr1), sprout::end(arr1), 10 ); TESTSPR_BOTH_ASSERT(result); } { SPROUT_STATIC_CONSTEXPR auto result = sprout::any_of_equal( sprout::begin(arr1), sprout::end(arr1), 11 ); TESTSPR_BOTH_ASSERT(!result); } { SPROUT_STATIC_CONSTEXPR auto result = sprout::any_of_equal( sprout::begin(arr1), sprout::begin(arr1) + 5, 10 ); TESTSPR_BOTH_ASSERT(!result); } { SPROUT_STATIC_CONSTEXPR auto result = sprout::any_of_equal( sprout::begin(arr1), sprout::begin(arr1) + 5, 11 ); TESTSPR_BOTH_ASSERT(!result); } { SPROUT_STATIC_CONSTEXPR auto result = sprout::any_of_equal( testspr::reduce_input(sprout::begin(arr1)), testspr::reduce_input(sprout::end(arr1)), 10 ); TESTSPR_BOTH_ASSERT(result); } { SPROUT_STATIC_CONSTEXPR auto result = sprout::any_of_equal( testspr::reduce_input(sprout::begin(arr1)), testspr::reduce_input(sprout::end(arr1)), 11 ); TESTSPR_BOTH_ASSERT(!result); } { SPROUT_STATIC_CONSTEXPR auto result = sprout::any_of_equal( testspr::reduce_input(sprout::begin(arr1)), testspr::reduce_input(sprout::begin(arr1) + 5), 10 ); TESTSPR_BOTH_ASSERT(!result); } { SPROUT_STATIC_CONSTEXPR auto result = sprout::any_of_equal( testspr::reduce_input(sprout::begin(arr1)), testspr::reduce_input(sprout::begin(arr1) + 5), 11 ); TESTSPR_BOTH_ASSERT(!result); } { SPROUT_STATIC_CONSTEXPR auto result = sprout::any_of_equal( testspr::reduce_random_access(sprout::begin(arr1)), testspr::reduce_random_access(sprout::end(arr1)), 10 ); TESTSPR_BOTH_ASSERT(result); } { SPROUT_STATIC_CONSTEXPR auto result = sprout::any_of_equal( testspr::reduce_random_access(sprout::begin(arr1)), testspr::reduce_random_access(sprout::end(arr1)), 11 ); TESTSPR_BOTH_ASSERT(!result); } { SPROUT_STATIC_CONSTEXPR auto result = sprout::any_of_equal( testspr::reduce_random_access(sprout::begin(arr1)), testspr::reduce_random_access(sprout::begin(arr1) + 5), 10 ); TESTSPR_BOTH_ASSERT(!result); } { SPROUT_STATIC_CONSTEXPR auto result = sprout::any_of_equal( testspr::reduce_random_access(sprout::begin(arr1)), testspr::reduce_random_access(sprout::begin(arr1) + 5), 11 ); TESTSPR_BOTH_ASSERT(!result); } } } } // namespace testspr #ifndef TESTSPR_CPP_INCLUDE # define TESTSPR_TEST_FUNCTION testspr::algorithm_any_of_equal_test # include <testspr/include_main.hpp> #endif #endif // #ifndef SPROUT_LIBS_ALGORITHM_TEST_ANY_OF_EQUAL_CPP
#include "DmsGame.h" #include "lib/rang.hpp" DmsGame::DmsGame() { constants = new DmsObject(); players = new DmsObject(); enemies = new DmsObject(); encounters = new DmsObject(); scenarios = new DmsObject(); } DmsGame::~DmsGame() { delete constants; delete players; delete enemies; delete encounters; delete scenarios; } void DmsGame::print(std::ostream &os) const { os << std::endl << rang::fgB::cyan << "CONSTANTS:" << rang::style::reset << rang::fg::reset << std::endl; constants->print(os, true); os << std::endl << rang::fgB::cyan << "PLAYERS:" << rang::style::reset << rang::fg::reset; players->print(os, false); os << std::endl << std::endl << rang::fgB::cyan << "ENEMIES:" << rang::style::reset << rang::fg::reset; enemies->print(os, false); os << std::endl << std::endl << rang::fgB::cyan << "ENCOUNTERS:" << rang::style::reset << rang::fg::reset; encounters->print(os, false); os << std::endl << std::endl << rang::fgB::cyan << "SCENARIOS:" << rang::style::reset << rang::fg::reset; scenarios->print(os, false); os << std::endl << std::endl; }
// Copyright (c) 2011-2016 The Harzcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "overviewpage.h" #include "ui_overviewpage.h" #include "harzcoinunits.h" #include "clientmodel.h" #include "guiconstants.h" #include "guiutil.h" #include "optionsmodel.h" #include "platformstyle.h" #include "transactionfilterproxy.h" #include "transactiontablemodel.h" #include "walletmodel.h" #include <QAbstractItemDelegate> #include <QPainter> #define DECORATION_SIZE 54 #define NUM_ITEMS 5 class TxViewDelegate : public QAbstractItemDelegate { Q_OBJECT public: TxViewDelegate(const PlatformStyle *_platformStyle, QObject *parent=nullptr): QAbstractItemDelegate(parent), unit(HarzcoinUnits::THALER), platformStyle(_platformStyle) { } inline void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const { painter->save(); QIcon icon = qvariant_cast<QIcon>(index.data(TransactionTableModel::RawDecorationRole)); QRect mainRect = option.rect; QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE)); int xspace = DECORATION_SIZE + 8; int ypad = 6; int halfheight = (mainRect.height() - 2*ypad)/2; QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight); QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight); icon = platformStyle->SingleColorIcon(icon); icon.paint(painter, decorationRect); QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime(); QString address = index.data(Qt::DisplayRole).toString(); qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong(); bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool(); QVariant value = index.data(Qt::ForegroundRole); QColor foreground = option.palette.color(QPalette::Text); if(value.canConvert<QBrush>()) { QBrush brush = qvariant_cast<QBrush>(value); foreground = brush.color(); } painter->setPen(foreground); QRect boundingRect; painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address, &boundingRect); if (index.data(TransactionTableModel::WatchonlyRole).toBool()) { QIcon iconWatchonly = qvariant_cast<QIcon>(index.data(TransactionTableModel::WatchonlyDecorationRole)); QRect watchonlyRect(boundingRect.right() + 5, mainRect.top()+ypad+halfheight, 16, halfheight); iconWatchonly.paint(painter, watchonlyRect); } if(amount < 0) { foreground = COLOR_NEGATIVE; } else if(!confirmed) { foreground = COLOR_UNCONFIRMED; } else { foreground = option.palette.color(QPalette::Text); } painter->setPen(foreground); QString amountText = HarzcoinUnits::formatWithUnit(unit, amount, true, HarzcoinUnits::separatorAlways); if(!confirmed) { amountText = QString("[") + amountText + QString("]"); } painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText); painter->setPen(option.palette.color(QPalette::Text)); painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date)); painter->restore(); } inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { return QSize(DECORATION_SIZE, DECORATION_SIZE); } int unit; const PlatformStyle *platformStyle; }; #include "overviewpage.moc" OverviewPage::OverviewPage(const PlatformStyle *platformStyle, QWidget *parent) : QWidget(parent), ui(new Ui::OverviewPage), clientModel(0), walletModel(0), currentBalance(-1), currentUnconfirmedBalance(-1), currentImmatureBalance(-1), currentWatchOnlyBalance(-1), currentWatchUnconfBalance(-1), currentWatchImmatureBalance(-1), txdelegate(new TxViewDelegate(platformStyle, this)) { ui->setupUi(this); // use a SingleColorIcon for the "out of sync warning" icon QIcon icon = platformStyle->SingleColorIcon(":/icons/warning"); icon.addPixmap(icon.pixmap(QSize(64,64), QIcon::Normal), QIcon::Disabled); // also set the disabled icon because we are using a disabled QPushButton to work around missing HiDPI support of QLabel (https://bugreports.qt.io/browse/QTBUG-42503) ui->labelTransactionsStatus->setIcon(icon); ui->labelWalletStatus->setIcon(icon); // Recent transactions ui->listTransactions->setItemDelegate(txdelegate); ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE)); ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2)); ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false); connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex))); // start with displaying the "out of sync" warnings showOutOfSyncWarning(true); connect(ui->labelWalletStatus, SIGNAL(clicked()), this, SLOT(handleOutOfSyncWarningClicks())); connect(ui->labelTransactionsStatus, SIGNAL(clicked()), this, SLOT(handleOutOfSyncWarningClicks())); } void OverviewPage::handleTransactionClicked(const QModelIndex &index) { if(filter) Q_EMIT transactionClicked(filter->mapToSource(index)); } void OverviewPage::handleOutOfSyncWarningClicks() { Q_EMIT outOfSyncWarningClicked(); } OverviewPage::~OverviewPage() { delete ui; } void OverviewPage::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance) { int unit = walletModel->getOptionsModel()->getDisplayUnit(); currentBalance = balance; currentUnconfirmedBalance = unconfirmedBalance; currentImmatureBalance = immatureBalance; currentWatchOnlyBalance = watchOnlyBalance; currentWatchUnconfBalance = watchUnconfBalance; currentWatchImmatureBalance = watchImmatureBalance; ui->labelBalance->setText(HarzcoinUnits::formatWithUnit(unit, balance, false, HarzcoinUnits::separatorAlways)); ui->labelUnconfirmed->setText(HarzcoinUnits::formatWithUnit(unit, unconfirmedBalance, false, HarzcoinUnits::separatorAlways)); ui->labelImmature->setText(HarzcoinUnits::formatWithUnit(unit, immatureBalance, false, HarzcoinUnits::separatorAlways)); ui->labelTotal->setText(HarzcoinUnits::formatWithUnit(unit, balance + unconfirmedBalance + immatureBalance, false, HarzcoinUnits::separatorAlways)); ui->labelWatchAvailable->setText(HarzcoinUnits::formatWithUnit(unit, watchOnlyBalance, false, HarzcoinUnits::separatorAlways)); ui->labelWatchPending->setText(HarzcoinUnits::formatWithUnit(unit, watchUnconfBalance, false, HarzcoinUnits::separatorAlways)); ui->labelWatchImmature->setText(HarzcoinUnits::formatWithUnit(unit, watchImmatureBalance, false, HarzcoinUnits::separatorAlways)); ui->labelWatchTotal->setText(HarzcoinUnits::formatWithUnit(unit, watchOnlyBalance + watchUnconfBalance + watchImmatureBalance, false, HarzcoinUnits::separatorAlways)); // only show immature (newly mined) balance if it's non-zero, so as not to complicate things // for the non-mining users bool showImmature = immatureBalance != 0; bool showWatchOnlyImmature = watchImmatureBalance != 0; // for symmetry reasons also show immature label when the watch-only one is shown ui->labelImmature->setVisible(showImmature || showWatchOnlyImmature); ui->labelImmatureText->setVisible(showImmature || showWatchOnlyImmature); ui->labelWatchImmature->setVisible(showWatchOnlyImmature); // show watch-only immature balance } // show/hide watch-only labels void OverviewPage::updateWatchOnlyLabels(bool showWatchOnly) { ui->labelSpendable->setVisible(showWatchOnly); // show spendable label (only when watch-only is active) ui->labelWatchonly->setVisible(showWatchOnly); // show watch-only label ui->lineWatchBalance->setVisible(showWatchOnly); // show watch-only balance separator line ui->labelWatchAvailable->setVisible(showWatchOnly); // show watch-only available balance ui->labelWatchPending->setVisible(showWatchOnly); // show watch-only pending balance ui->labelWatchTotal->setVisible(showWatchOnly); // show watch-only total balance if (!showWatchOnly) ui->labelWatchImmature->hide(); } void OverviewPage::setClientModel(ClientModel *model) { this->clientModel = model; if(model) { // Show warning if this is a prerelease version connect(model, SIGNAL(alertsChanged(QString)), this, SLOT(updateAlerts(QString))); updateAlerts(model->getStatusBarWarnings()); } } void OverviewPage::setWalletModel(WalletModel *model) { this->walletModel = model; if(model && model->getOptionsModel()) { // Set up transaction list filter.reset(new TransactionFilterProxy()); filter->setSourceModel(model->getTransactionTableModel()); filter->setLimit(NUM_ITEMS); filter->setDynamicSortFilter(true); filter->setSortRole(Qt::EditRole); filter->setShowInactive(false); filter->sort(TransactionTableModel::Date, Qt::DescendingOrder); ui->listTransactions->setModel(filter.get()); ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress); // Keep up to date with wallet setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(), model->getWatchBalance(), model->getWatchUnconfirmedBalance(), model->getWatchImmatureBalance()); connect(model, SIGNAL(balanceChanged(CAmount,CAmount,CAmount,CAmount,CAmount,CAmount)), this, SLOT(setBalance(CAmount,CAmount,CAmount,CAmount,CAmount,CAmount))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); updateWatchOnlyLabels(model->haveWatchOnly()); connect(model, SIGNAL(notifyWatchonlyChanged(bool)), this, SLOT(updateWatchOnlyLabels(bool))); } // update the display unit, to not use the default ("THALER") updateDisplayUnit(); } void OverviewPage::updateDisplayUnit() { if(walletModel && walletModel->getOptionsModel()) { if(currentBalance != -1) setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance, currentWatchOnlyBalance, currentWatchUnconfBalance, currentWatchImmatureBalance); // Update txdelegate->unit with the current unit txdelegate->unit = walletModel->getOptionsModel()->getDisplayUnit(); ui->listTransactions->update(); } } void OverviewPage::updateAlerts(const QString &warnings) { this->ui->labelAlerts->setVisible(!warnings.isEmpty()); this->ui->labelAlerts->setText(warnings); } void OverviewPage::showOutOfSyncWarning(bool fShow) { ui->labelWalletStatus->setVisible(fShow); ui->labelTransactionsStatus->setVisible(fShow); }
// Copyright (c) 2020 INRA Distributed under the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef ORG_VLEPROJECT_IRRITATOR_EXTERNAL_SOURCE_2021 #define ORG_VLEPROJECT_IRRITATOR_EXTERNAL_SOURCE_2021 #include <irritator/core.hpp> #include <array> #include <filesystem> #include <fstream> namespace irt::source { struct constant { double value; bool init(external_source& src) { src.type = 0; src.id = 0; src.data = &value; src.index = 0; return true; } bool operator()(external_source& src) { src.index = 0; return true; } }; struct binary_file { std::array<char, 1024 * 1024> buffer; std::filesystem::path file_path; std::ifstream ifs; sz buffer_size = 0; bool use_rewind = false; binary_file() = default; bool init(external_source& src) { src.type = 1; src.id = 0; if (!ifs) { ifs.open(file_path); if (!ifs) return false; } if (!read(src)) return false; return true; } bool operator()(external_source& src) { if (!ifs.good() && !use_rewind) return false; if (!ifs.good()) ifs.seekg(0); if (!read(src)) return false; return true; } private: bool read(external_source& src) { ifs.read(buffer.data(), std::size(buffer)); buffer_size = ifs.gcount(); if (buffer_size % 8 != 0) return false; src.data = reinterpret_cast<double*>(buffer.data()); src.index = 0; src.size = buffer_size / 8; return true; } }; struct text_file { std::array<double, 1024 * 1024 / 8> buffer; std::filesystem::path file_path; std::ifstream ifs; bool use_rewind = false; text_file() = default; bool init(external_source& src) { src.type = 2; src.id = 0; if (!ifs) { ifs.open(file_path); if (!ifs) return false; } if (!read(src)) return false; return true; } bool operator()(external_source& src) { if (!ifs.good() && !use_rewind) return false; if (!ifs.good()) ifs.seekg(0); if (!read(src)) return false; return true; } private: bool read(external_source& src) { size_t i = 0; for (; i < std::size(buffer) && ifs.good(); ++i) { if (!(ifs >> buffer[i])) break; } src.data = buffer.data(); src.index = 0; src.size = i; return true; } }; struct random_source { double* buffer = nullptr; sz size = 0; bool use_rewind; random_source() = default; ~random_source() noexcept { if (buffer) g_free_fn(buffer); } template<typename RandomGenerator, typename Distribution> bool init(const sz size_, RandomGenerator& gen, Distribution& dist) noexcept { if (!size_) return false; if (buffer) g_free_fn(buffer); size = 0; buffer = g_alloc_fn(sizeof(double) * size_); if (buffer) { std::generate_n(buffer, size, (*dist)(*gen)); size = size_; return true; } return false; } bool operator()(external_source& /*src*/) { if (!use_rewind) return false; size = 0; return true; } }; enum class random_file_type { binary, text, }; template<typename RandomGenerator, typename Distribution> inline int generate_random_file(std::ostream& os, RandomGenerator& gen, Distribution& dist, const std::size_t size, const random_file_type type) noexcept { switch (type) { case random_file_type::text: { if (!os) return -1; for (std::size_t sz = 0; sz < size; ++sz) if (!(os << dist(gen) << '\n')) return -2; } break; case random_file_type::binary: { if (!os) return -1; for (std::size_t sz = 0; sz < size; ++sz) { const double value = dist(gen); os.write(reinterpret_cast<const char*>(&value), sizeof(value)); } } break; } return 0; } } // namespace irt::source #endif
//////////////////////////////////////////////////////////// // // RubySFML - Ruby extension for the SFML library // Copyright (C) 2007 Sean O'Neil and Laurent Gomila // (sean.p.oneil@gmail.com and laurent.gom@gmail.com) // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it freely, // subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // //////////////////////////////////////////////////////////// #include <SFML/Window.hpp> #include "RubySFML.h" using namespace sf; VALUE g_cVideoMode; DECLARE_INT_RW(VideoMode, Width); DECLARE_INT_RW(VideoMode, Height); DECLARE_INT_RW(VideoMode, BitsPerPixel); void VideoMode_free(void *p) { delete (VideoMode *)p; } VALUE VideoMode_new(int argc, VALUE *argv, VALUE vClass) { VideoMode *ptr = new VideoMode(); VALUE tData = Data_Wrap_Struct(vClass, 0, VideoMode_free, ptr); rb_obj_call_init(tData, argc, argv); return tData; } static VALUE VideoMode_initialize(int argc, VALUE *argv, VALUE vSelf) { // Get C++ object pointer from vSelf VideoMode *pSelf; Data_Get_Struct(vSelf, VideoMode, pSelf); if(argc == 0) { // Nothing to initialize } else if(argc >= 2 && argc <= 3 && ISNUM(argv[0]) && ISNUM(argv[1]) && (argc < 3 || ISNUM(argv[2]))) { *pSelf = VideoMode(NUM2INT(argv[0]), NUM2INT(argv[1]), argc < 3 ? 32 : NUM2INT(argv[2])); } else rb_raise(rb_eTypeError, "wrong argument type(s)"); return vSelf; } static VALUE VideoMode_desktop(VALUE vClass) { DECLARE_OBJ_VAR(VideoMode, Desktop, VideoMode::GetDesktopMode()); return vDesktop; } // Ruby each iterator static VALUE VideoMode_each(VALUE vClass) { int nLength = VideoMode::GetModesCount(); for(int i=0; i<nLength; i++) { VideoMode mode = VideoMode::GetMode(i); DECLARE_PTR_VAR(VideoMode, Element, &mode); rb_yield(vElement); } return Qnil; } static VALUE VideoMode_isValid(VALUE vSelf) { // Get C++ object pointer from vSelf VideoMode *pSelf; Data_Get_Struct(vSelf, VideoMode, pSelf); return pSelf->IsValid() ? Qtrue : Qfalse; } static VALUE VideoMode_to_s(VALUE vSelf) { // Get C++ object pointer from vSelf VideoMode *pSelf; Data_Get_Struct(vSelf, VideoMode, pSelf); char szBuffer[256]; sprintf(szBuffer, "Width: %d, Height: %d, BPP: %d", pSelf->Width, pSelf->Height, pSelf->BitsPerPixel); return rb_str_new2(szBuffer); } void Init_VideoMode() { g_cVideoMode = rb_define_class_under(g_vModule, "VideoMode", rb_cObject); DEFINE_CLASS_METHOD(VideoMode, new, -1); DEFINE_INSTANCE_METHOD(VideoMode, initialize, -1); DEFINE_RW2(VideoMode, Width, width); DEFINE_RW2(VideoMode, Width, w); DEFINE_RW2(VideoMode, Height, height); DEFINE_RW2(VideoMode, Height, h); DEFINE_RW2(VideoMode, BitsPerPixel, bitsPerPixel); DEFINE_RW2(VideoMode, BitsPerPixel, bpp); DEFINE_CLASS_METHOD(VideoMode, each, 0); DEFINE_CLASS_METHOD(VideoMode, desktop, 0); DEFINE_INSTANCE_METHOD(VideoMode, isValid, 0); DEFINE_INSTANCE_METHOD(VideoMode, to_s, 0); }
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <algorithm> #include <memory> #include <vector> #include "absl/memory/memory.h" #include "absl/strings/ascii.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "tensorflow/compiler/tf2tensorrt/convert/convert_nodes.h" #include "tensorflow/compiler/tf2tensorrt/convert/utils.h" #include "tensorflow/compiler/tf2tensorrt/utils/trt_allocator.h" #include "tensorflow/compiler/tf2tensorrt/utils/trt_logger.h" #include "tensorflow/compiler/tf2tensorrt/utils/trt_lru_cache.h" #include "tensorflow/core/common_runtime/function.h" #include "tensorflow/core/common_runtime/graph_optimizer.h" #include "tensorflow/core/framework/function.h" #include "tensorflow/core/framework/graph_to_functiondef.h" #include "tensorflow/core/framework/node_def_builder.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/graph/algorithm.h" #include "tensorflow/core/graph/graph_constructor.h" #include "tensorflow/core/lib/core/refcount.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/mutex.h" #include "tensorflow/core/platform/stream_executor.h" #include "tensorflow/core/platform/thread_annotations.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/stream_executor/lib/statusor.h" #if GOOGLE_CUDA #if GOOGLE_TENSORRT #include "third_party/gpus/cuda/include/cuda_runtime_api.h" #include "third_party/tensorrt/NvInfer.h" namespace tensorflow { namespace tensorrt { static Logger logger; using absl::StrAppend; using absl::StrCat; using ::nvinfer1::IRuntime; using ::stream_executor::port::StatusOr; // A helper class to call done() when destructed for asynchronous execution. // Helps simultaneous execution of native and TRT engines. class AsyncHelper : public core::RefCounted { public: AsyncHelper(AsyncOpKernel::DoneCallback done) : done_(done) {} ~AsyncHelper() override { this->operator()(); } void operator()() { if (!called_) { done_(); called_ = true; } } private: AsyncOpKernel::DoneCallback done_; bool called_ = false; // Has `done_` been called? }; // This OP can construct TRTEngine on the fly and if construction of engine // fails, executes equivalent subgraph as a TensorFlow function. class TRTEngineOp : public AsyncOpKernel { public: explicit TRTEngineOp(OpKernelConstruction* context); void ComputeAsync(OpKernelContext* context, AsyncOpKernel::DoneCallback done) override; private: using CacheType = LRUCache<std::vector<TensorShape>, std::unique_ptr<EngineContext>, VectorTensorShapeHasher>; // Execute calibration void ExecuteCalibration(OpKernelContext* ctx, TRTEngineCacheResource* cache_res, AsyncHelper* helper); // Construct a function handle for executing native funcdef graph // These are the exact same function. Status ConstructFunctionHandle(FunctionLibraryRuntime* lib, const string& device_name); // Execute replaced native segment as function Op. void ExecuteNativeSegment(OpKernelContext* ctx, AsyncHelper* helper); // Execute the tensorrt engine. Returns whether we need to retry by running // the native segment. bool ExecuteTrtEngine(OpKernelContext* ctx, EngineContext* engine_context); // Allocate necessary resources for calibration Status AllocateCalibrationResources(OpKernelContext* ctx, TRTEngineCacheResource* cache_res); Status GetEngineCacheResource(OpKernelContext* ctx, TRTEngineCacheResource** cache_res); // Get engine for the input shape StatusOr<EngineContext*> GetEngine( const std::vector<TensorShape>& input_shapes, OpKernelContext* ctx, TRTEngineCacheResource* cache_res); // Verify that the input shapes are consistent and can be handled by this op. Status VerifyInputShapes(const std::vector<TensorShape>& shapes); // Return engine batch in cached_engne_batch_sizes_ which is closest to input // batch. Status GetEngineInputShapes( const CacheType& cache, const std::vector<TensorShape>& actual_input_shapes, std::vector<TensorShape>* engine_input_shapes); std::vector<string> input_nodes_; std::vector<string> output_nodes_; // serialized protobuf segment or trt engine depending on static_engine_ flag. string serialized_segment_; // The function for TF native execution of the segment. NameAttrList func_; // GraphDef representation of the segment. GraphDef segment_graph_; // Engine Precision mode. TrtPrecisionMode precision_mode_; // Whether engine is constructed during the conversion or needs to be // constructed from protobuf segment. bool static_engine_; // Whether to calibrate INT8 engine. bool calibration_mode_; // Maximum number of cached engines int max_cached_engines_; int64 workspace_size_; mutex engine_mutex_; FunctionLibraryRuntime::Handle func_handle_; // The finalized calibrator for inference. std::unique_ptr<TRTInt8Calibrator> calibrator_; // If true, create calibration graph for INT8 mode. Otherwise, we are using // user-provided quantization ranges. bool use_calibration_; }; #define TYPECASE(dt, X, Y) \ case dt: { \ return (void*)X->flat<EnumToDataType<dt>::Type>().data(); \ } void* GetTensorAddress(const Tensor* tensor_ptr) { auto tensor_type = tensor_ptr->dtype(); switch (tensor_type) { TYPECASE(DT_FLOAT, tensor_ptr, dest_ptr); TYPECASE(DT_HALF, tensor_ptr, dest_ptr); TYPECASE(DT_INT8, tensor_ptr, dest_ptr); TYPECASE(DT_INT32, tensor_ptr, dest_ptr); default: { LOG(ERROR) << "Unsupported Data type " << DataTypeString(tensor_type); return nullptr; } } } static Status FunctionDefToGraphDef(FunctionLibraryRuntime::Handle handle, FunctionLibraryRuntime* flib_runtime, GraphDef* graph_def) { const FunctionLibraryDefinition* flib_def = flib_runtime->GetFunctionLibraryDefinition(); const FunctionBody* fbody; fbody = flib_runtime->GetFunctionBody(handle); if (!fbody) { return errors::Internal( "Function body is null when converting from FuncDef to GraphDef."); } std::unique_ptr<Graph> graph(new Graph(flib_def)); CopyGraph(*fbody->graph, graph.get()); auto replace_name = [](const char* const prefix, string* name) { if (absl::StartsWith(*name, absl::AsciiStrToLower(prefix))) { name->replace(0, strlen(prefix), prefix); return true; } return false; }; graph->ToGraphDef(graph_def); // GraphToFunctionDef() will convert all the node names to lowercase. for (auto& node : *graph_def->mutable_node()) { if (!replace_name(IONamePrefixes::kInputPHName, node.mutable_name())) { if (replace_name(IONamePrefixes::kOutputPHName, node.mutable_name())) { // Instantiation of the function will append _RetVal to the node name, // need to remove it for backward compatibility. const char* const suffix_to_remove = "_RetVal"; if (absl::EndsWith(node.name(), suffix_to_remove)) { node.mutable_name()->erase(node.name().size() - strlen(suffix_to_remove)); } } } for (auto& input : *node.mutable_input()) { if (!replace_name(IONamePrefixes::kInputPHName, &input)) { replace_name(IONamePrefixes::kOutputPHName, &input); } } } return Status::OK(); } Status TRTEngineOp::ConstructFunctionHandle(FunctionLibraryRuntime* lib, const string& device_name) { VLOG(1) << "Constructing function handle"; if (lib == nullptr) { return errors::Internal("Context function library is null"); } FunctionLibraryRuntime::InstantiateOptions inst_ops; inst_ops.state_handle = ""; inst_ops.target = device_name; return lib->Instantiate(func_.name(), AttrSlice(&func_.attr()), inst_ops, &func_handle_); } TRTEngineOp::TRTEngineOp(OpKernelConstruction* context) : AsyncOpKernel(context) { // read serialized_engine OP_REQUIRES_OK(context, context->GetAttr("serialized_segment", &serialized_segment_)); OP_REQUIRES_OK(context, context->GetAttr("workspace_size_bytes", &workspace_size_)); OP_REQUIRES_OK(context, context->GetAttr("static_engine", &static_engine_)); VLOG(1) << "Constructing " << name(); string precision_string; OP_REQUIRES_OK(context, context->GetAttr("precision_mode", &precision_string)); string calibration_data; OP_REQUIRES_OK(context, context->GetAttr("calibration_data", &calibration_data)); OP_REQUIRES_OK(context, context->GetAttr("segment_func", &func_)); OP_REQUIRES(context, !func_.name().empty(), errors::InvalidArgument( "The TF function for the TRT segment could not be empty")); OP_REQUIRES_OK(context, TrtPrecisionModeFromName(precision_string, &precision_mode_)); OP_REQUIRES_OK(context, context->GetAttr("use_calibration", &use_calibration_)); func_handle_ = kInvalidHandle; if (!static_engine_) { FunctionLibraryRuntime* lib = context->function_library(); OP_REQUIRES_OK(context, ConstructFunctionHandle(lib, context->device()->name())); OP_REQUIRES_OK(context, FunctionDefToGraphDef(func_handle_, lib, &segment_graph_)); } // TODO(laigd): calibration_data is used in TF v1.x and we keep it only for // backward compatibility reasons. Remove it once all known users switch to // 2.0. calibration_mode_ = (use_calibration_ && precision_mode_ == TrtPrecisionMode::INT8 && calibration_data.empty()); if (!calibration_data.empty()) { calibrator_.reset(new TRTInt8Calibrator(calibration_data)); calibration_data.resize(0); } OP_REQUIRES_OK(context, context->GetAttr("max_cached_engines_count", &max_cached_engines_)); } void TRTEngineOp::ExecuteNativeSegment(OpKernelContext* ctx, AsyncHelper* helper) { std::vector<Tensor> inputs; std::vector<Tensor>* outputs = new std::vector<Tensor>(); if (func_handle_ == kInvalidHandle) { OP_REQUIRES_OK_ASYNC( ctx, ConstructFunctionHandle(ctx->function_library(), ctx->device()->name()), *helper); } auto lib = ctx->function_library(); FunctionLibraryRuntime::Options opts; opts.rendezvous = ctx->rendezvous(); opts.cancellation_manager = ctx->cancellation_manager(); opts.runner = ctx->runner(); inputs.reserve(ctx->num_inputs()); for (int i = 0; i < ctx->num_inputs(); i++) { inputs.push_back(ctx->input(i)); } helper->Ref(); // Increment count for calculating native graph VLOG(1) << "Executing native segment: " << name(); lib->Run(opts, func_handle_, inputs, outputs, [this, ctx, outputs, helper](const Status& s) { core::ScopedUnref sc(helper); OP_REQUIRES_OK_ASYNC(ctx, s, *helper); VLOG(1) << "Native Segment completed"; for (size_t t = 0; t < outputs->size(); ++t) { ctx->set_output(t, outputs->at(t)); } delete outputs; }); } void TRTEngineOp::ExecuteCalibration(OpKernelContext* ctx, TRTEngineCacheResource* cache_res, AsyncHelper* helper) { VLOG(1) << "Executing TRT calibration: " << name(); helper->Ref(); core::ScopedUnref sc(helper); CalibrationContext* calib_ctx = cache_res->calib_ctx_.get(); const int num_inputs = ctx->num_inputs(); // TODO(laigd): need to check that input shape matches. // Pass input data to calibrator std::unordered_map<string, void*> input_data; for (int i = 0; i < num_inputs; i++) { const Tensor& t = ctx->input(i); void* data_address = GetTensorAddress(&t); OP_REQUIRES_ASYNC(ctx, data_address, errors::InvalidArgument( "Unsupported data type encountered in input ", i), *helper); // Check the allocated buffer is sufficient for input const auto device_tensor = calib_ctx->device_tensors_.at(i).AccessTensor(ctx); CHECK_EQ(t.TotalBytes(), device_tensor->TotalBytes()); input_data.emplace(StrCat(IONamePrefixes::kInputPHName, i), data_address); } VLOG(2) << "Filled map for sending"; // copied from cuda_kernel_helper since it seems only valid in *.cu.cc files const cudaStream_t* stream = CHECK_NOTNULL( reinterpret_cast<const cudaStream_t*>(ctx->op_device_context() ->stream() ->implementation() ->GpuStreamMemberHack())); // If calibrator is terminated before, it means an error has occurred. // // Note: setBatch() will wait until TRTInt8Calibrator::getBatch() is called // the first time before proceeding, so if buildCudaEngine() returns an error, // it means getBatch() is never called, and the setBatch() here will hang // until setDone() is called later by the calibration thread in // AllocateCalibrationResources(). In that case, this setBatch() will always // be able to detect the error and return false. OP_REQUIRES_ASYNC(ctx, calib_ctx->calibrator_->setBatch(input_data, *stream), errors::Internal("Failed to feed calibration data"), *helper); VLOG(2) << "Passed calibration data"; ExecuteNativeSegment(ctx, helper); } Status TRTEngineOp::VerifyInputShapes(const std::vector<TensorShape>& shapes) { if (shapes.empty()) { return errors::InvalidArgument("Input shapes are empty, for ", name()); } if (shapes[0].dims() < 1) { return errors::InvalidArgument("Input shapes contain scalar, for ", name(), ": ", TensorShapeUtils::ShapeListString(shapes)); } const int batch_size = shapes[0].dim_size(0); for (const TensorShape& shape : shapes) { if (shape.dims() < 1 || batch_size != shape.dim_size(0)) { return errors::InvalidArgument( "Input shapes are inconsistent on the batch dimension, for ", name(), ": ", TensorShapeUtils::ShapeListString(shapes)); } } return Status::OK(); } bool AreShapesCompatible(const std::vector<TensorShape>& actual_shapes, const std::vector<TensorShape>& cached_shapes) { auto match_shape = [](const TensorShape& actual_shape, const TensorShape& cached_shape) { // Match the rank. if (actual_shape.dims() != cached_shape.dims()) return false; // Match the batch size. if (actual_shape.dim_size(0) > cached_shape.dim_size(0)) return false; // Match remaining dimensions. for (int i = 1; i < actual_shape.dims(); ++i) { if (actual_shape.dim_size(i) != cached_shape.dim_size(i)) return false; } return true; }; for (int i = 0; i < actual_shapes.size(); ++i) { if (!match_shape(actual_shapes[i], cached_shapes[i])) { return false; } } return true; } Status TRTEngineOp::GetEngineInputShapes( const CacheType& cache, const std::vector<TensorShape>& actual_input_shapes, std::vector<TensorShape>* engine_input_shapes) { // VerifyInputShapes() already ensured that all input shapes have same // batch size, and are not scalars. *engine_input_shapes = actual_input_shapes; int64 min_matched_batch_size = kint64max; for (const auto& pair : cache) { const std::vector<TensorShape>& cached_input_shapes = pair.first; // This should not happen, but just for safety. if (actual_input_shapes.size() != cached_input_shapes.size()) { return errors::InvalidArgument( "Input shape list size mismatch for ", name(), ", cached size: ", cached_input_shapes.size(), " vs. actual size: ", actual_input_shapes.size()); } if (AreShapesCompatible(actual_input_shapes, cached_input_shapes)) { const int cached_batch_size = cached_input_shapes[0].dim_size(0); if (min_matched_batch_size > cached_batch_size) { min_matched_batch_size = cached_batch_size; *engine_input_shapes = cached_input_shapes; } } } return Status::OK(); } void TRTEngineOp::ComputeAsync(OpKernelContext* ctx, AsyncOpKernel::DoneCallback done) { auto helper = new AsyncHelper(done); core::ScopedUnref sc(helper); // Get TRT resource. TRTEngineCacheResource* cache_res = nullptr; OP_REQUIRES_OK_ASYNC(ctx, GetEngineCacheResource(ctx, &cache_res), *helper); core::ScopedUnref unref_cache_res(cache_res); // Run calibration if in int8+calibration mode. // * Logic in TF 1.x: // - During conversion: calibration_mode_ is true and cache size is 0, so it // will run calibration. // - During inference: calibration_data will be set, so calibration_mode_ is // false and it won't trigger calibration. // * Logic in TF 2.0: // - During conversion: similar to 1.x. // - During inference: calibration_data will still be empty, but cache will // contain the the calibrated engine, so it won't trigger calibration. // // TODO(laigd): consider the following alternatives: // 1. Serialize the state (calibration or inference) using // TRTEngineInstance proto (or a new proto), so we know which mode we're // in and don't run calibration during inference (which is invalid). // 2. Reuse the calibration_data attribute or use a new attribute in the // NodeDef to indicate whether it's in calibration mode. if (calibration_mode_ && cache_res->cache_.size() == 0) { if (!cache_res->calib_ctx_) { // TODO(laigd): better encapsulation. mutex_lock lock(engine_mutex_); if (!cache_res->calib_ctx_) { OP_REQUIRES_OK_ASYNC(ctx, AllocateCalibrationResources(ctx, cache_res), *helper); } } // TODO(laigd): check that the input shapes match the shapes of the // persistent tensor in the calibration resource. ExecuteCalibration(ctx, cache_res, helper); return; } // Get shapes of inputs to engine. std::vector<TensorShape> input_shapes; input_shapes.reserve(ctx->num_inputs()); for (int i = 0; i < ctx->num_inputs(); ++i) { input_shapes.push_back(ctx->input(i).shape()); } OP_REQUIRES_OK_ASYNC(ctx, VerifyInputShapes(input_shapes), *helper); StatusOr<EngineContext*> status = GetEngine(input_shapes, ctx, cache_res); OP_REQUIRES_OK_ASYNC(ctx, status.status(), *helper); EngineContext* engine_context = status.ValueOrDie(); if (!engine_context->cuda_engine) { VLOG(1) << "Engine retrieval for input shapes: " << TensorShapeUtils::ShapeListString(input_shapes) << " failed. Running native segment for " << name(); ExecuteNativeSegment(ctx, helper); return; } const bool retry = ExecuteTrtEngine(ctx, engine_context); if (retry) { LOG(WARNING) << "Failed to execute engine, " << "retrying with native segment for " << name(); // Release any outputs that are allocated, ExecuteNativeSegment will // re-allocate them and fail if they are currently allocated. for (int i = 0; i < ctx->num_outputs(); i++) { ctx->release_output(i); } ExecuteNativeSegment(ctx, helper); return; } } bool TRTEngineOp::ExecuteTrtEngine(OpKernelContext* ctx, EngineContext* engine_context) { VLOG(1) << "Executing TRT engine: " << name(); auto& cuda_engine = engine_context->cuda_engine; const bool kRetry = true; // All inputs must have the same batch size, so just get it from the first // input. const int num_batch = ctx->input(0).shape().dim_size(0); const int num_binding = ctx->num_inputs() + ctx->num_outputs(); std::vector<void*> buffers(num_binding); for (int i = 0; i < ctx->num_inputs(); i++) { const string input_name = StrCat(IONamePrefixes::kInputPHName, i); const int binding_index = cuda_engine->getBindingIndex(input_name.c_str()); if (binding_index == -1) { const string msg = StrCat("Input node ", input_name, " not found, at ", name()); LOG(ERROR) << msg; ctx->SetStatus(errors::NotFound(msg)); return !kRetry; } const Tensor& input_tensor = ctx->input(i); const TensorShape& input_shape = input_tensor.shape(); if (num_batch != input_shape.dim_size(0)) { LOG(ERROR) << "Input data has inconsistent batch size: " << num_batch << " vs " << input_shape.dim_size(0); return kRetry; } auto dtype = cuda_engine->getBindingDataType(binding_index); switch (dtype) { case nvinfer1::DataType::kFLOAT: buffers[binding_index] = const_cast<float*>(input_tensor.flat<float>().data()); break; case nvinfer1::DataType::kHALF: buffers[binding_index] = const_cast<Eigen::half*>(input_tensor.flat<Eigen::half>().data()); break; case nvinfer1::DataType::kINT8: LOG(ERROR) << "INT8 inputs are not supported yet!"; return kRetry; case nvinfer1::DataType::kINT32: buffers[binding_index] = const_cast<int32*>(input_tensor.flat<int32>().data()); break; default: LOG(ERROR) << "Unknown TRT data type: " << static_cast<int>(dtype); return kRetry; } } for (int i = 0; i < ctx->num_outputs(); i++) { // Create an output tensor const string output_name = StrCat(IONamePrefixes::kOutputPHName, i); const int binding_index = cuda_engine->getBindingIndex(output_name.c_str()); Tensor* output_tensor = nullptr; TensorShape output_shape; if (binding_index != -1) { auto dims = cuda_engine->getBindingDimensions(binding_index); std::vector<int> trt_shape(dims.nbDims + 1); trt_shape[0] = num_batch; for (int j = 0; j < dims.nbDims; j++) trt_shape[j + 1] = dims.d[j]; auto status = TensorShapeUtils::MakeShape( trt_shape.data(), trt_shape.size(), &output_shape); if (!status.ok()) { LOG(ERROR) << "Failed to get output shape: " << status; return kRetry; } } else { const string msg = StrCat("Ouput node ", output_name, " not found, at ", name()); LOG(ERROR) << msg; ctx->SetStatus(errors::NotFound(msg)); return !kRetry; } auto status = ctx->allocate_output(i, output_shape, &output_tensor); if (!status.ok()) { LOG(ERROR) << "Allocating output failed with " << status; ctx->SetStatus(status); return kRetry; } auto dtype = cuda_engine->getBindingDataType(binding_index); switch (dtype) { case nvinfer1::DataType::kFLOAT: buffers[binding_index] = const_cast<float*>(output_tensor->flat<float>().data()); break; case nvinfer1::DataType::kHALF: buffers[binding_index] = const_cast<Eigen::half*>(output_tensor->flat<Eigen::half>().data()); break; case nvinfer1::DataType::kINT8: LOG(WARNING) << "int8 is not supported yet!"; return kRetry; case nvinfer1::DataType::kINT32: buffers[binding_index] = const_cast<int32*>(output_tensor->flat<int32>().data()); break; default: LOG(WARNING) << "Unknown TRT data type: " << static_cast<int>(dtype); return kRetry; } } // Copied from cuda_kernel_helper since it seems only valid in *.cu.cc files const cudaStream_t* stream = CHECK_NOTNULL( reinterpret_cast<const cudaStream_t*>(ctx->op_device_context() ->stream() ->implementation() ->GpuStreamMemberHack())); // nvinfer1::IExecutionContext::enqueue is not thread safe and we need a mutex // for it. mutex_lock lock(engine_context->mu); // TODO(jie): trt enqueue does not return error auto ret = engine_context->execution_context->enqueue(num_batch, &buffers[0], *stream, nullptr); if (!ret) { LOG(WARNING) << "Failed to enqueue batch for TRT engine: " << name(); return kRetry; } // Synchronization will be done by TF. return !kRetry; } Status TRTEngineOp::GetEngineCacheResource(OpKernelContext* ctx, TRTEngineCacheResource** cache_res) { // Canonicalize the op name by removing the scopes if any. This is mainly // because in TFv2, the function graph can be instantiated in various ways and // it'll insert scope names to the name of the TRTEngineOps, which will result // in many different engine caches if we use the instantiated op name // directly, but we still want all of them share the same cache (if they were // representing the same subgraph). absl::string_view resource_name = name(); size_t last_slash = resource_name.find_last_of('/'); if (last_slash != absl::string_view::npos) { resource_name.remove_prefix(last_slash + 1); } // Get engine cache. return ctx->resource_manager()->LookupOrCreate( std::string(kTfTrtContainerName), std::string(resource_name), cache_res, {[this, ctx](TRTEngineCacheResource** cr) -> Status { *cr = new TRTEngineCacheResource(ctx, this->max_cached_engines_); return Status::OK(); }}); } StatusOr<EngineContext*> TRTEngineOp::GetEngine( const std::vector<TensorShape>& input_shapes, OpKernelContext* ctx, TRTEngineCacheResource* cache_res) { static EngineContext empty_context; mutex_lock lock(engine_mutex_); // Using first input to get batch size is reliable - VerifyInputShapes() has // verified that. const int batch_size = input_shapes[0].dim_size(0); auto& cache = cache_res->cache_; auto allocator = cache_res->allocator_.get(); if (allocator == nullptr) { return &empty_context; } // Handle the static engine case. For static engines, the cache will have a // single element containing the only engine. if (static_engine_) { if (cache.size()) { if (AreShapesCompatible(input_shapes, cache.begin()->first)) { return cache.begin()->second.get(); } return &empty_context; } TrtUniquePtrType<IRuntime> infer(nvinfer1::createInferRuntime(logger)); infer->setGpuAllocator(allocator); TrtUniquePtrType<nvinfer1::ICudaEngine> static_engine( infer->deserializeCudaEngine(serialized_segment_.c_str(), serialized_segment_.size(), nullptr)); if (!static_engine) { return &empty_context; } auto raw_static_engine = static_engine.get(); const auto max_batch_size = raw_static_engine->getMaxBatchSize(); // Static engine will have max_batch_size for batch size so that all inputs // will map to this single engine. std::vector<TensorShape> engine_input_shapes(input_shapes); for (int i = 0; i < engine_input_shapes.size(); i++) { // TODO(tmorris): will all inputs have batch size as first dimension?? engine_input_shapes[i].set_dim(0, max_batch_size); } // TODO(laigd): here we assume engine_input_shapes matches the actual input // shapes of the engine, we should verify that. cache.emplace(engine_input_shapes, absl::make_unique<EngineContext>( std::move(static_engine), TrtUniquePtrType<nvinfer1::IExecutionContext>( raw_static_engine->createExecutionContext()))); // Runtime is safe to delete after engine creation VLOG(1) << "Size of serialized TRT engine: " << serialized_segment_.capacity(); string tmp; // Swap with temporary empty string to deallocate the CPU memory. serialized_segment_.swap(tmp); if (max_batch_size < batch_size) { return &empty_context; } return cache.at(engine_input_shapes).get(); } // static_engine_ // Handle the dynamic engine case. See if there is a compatible engine cached. std::vector<TensorShape> engine_input_shapes; TF_RETURN_IF_ERROR( GetEngineInputShapes(cache, input_shapes, &engine_input_shapes)); // If matched, use that engine. Otherwise, we will look in cache for that // exact shape and possibly create a new engine if it is not in cache. if (!cache.count(engine_input_shapes)) { TrtUniquePtrType<nvinfer1::ICudaEngine> engine; bool convert_successfully = false; LOG(INFO) << "Building a new TensorRT engine for " << name() << " with input shapes: " << TensorShapeUtils::ShapeListString(engine_input_shapes); // Convert to partial shapes std::vector<PartialTensorShape> partial_shapes(engine_input_shapes.begin(), engine_input_shapes.end()); // Up to this point, calibrator_ can never be empty, since otherwise it // means calibration_mode_ is true and this path won't get executed. auto status = convert::ConvertGraphDefToEngine( segment_graph_, precision_mode_, batch_size, workspace_size_, partial_shapes, &logger, allocator, calibrator_.get(), &engine, use_calibration_, &convert_successfully); if (!status.ok()) { LOG(WARNING) << "Engine creation for " << name() << " failed. " << "The native segment will be used instead. " << "Reason: " << status; // Store an empty engine in the cache for these input shapes so we don't // try to build the same failing engine again. cache.emplace(engine_input_shapes, absl::make_unique<EngineContext>()); return &empty_context; } TrtUniquePtrType<nvinfer1::IExecutionContext> exec_context( engine->createExecutionContext()); cache.emplace(engine_input_shapes, absl::make_unique<EngineContext>(std::move(engine), std::move(exec_context))); VLOG(1) << "Added new engine to cache of " << name() << ". Cache size: " << cache.size(); } return cache.at(engine_input_shapes).get(); } // TODO(hinsu): Move this allocation to CalibrationContext constructor, if // possible. Status TRTEngineOp::AllocateCalibrationResources( OpKernelContext* ctx, TRTEngineCacheResource* cache_res) { cache_res->calib_ctx_ = absl::make_unique<CalibrationContext>(); auto* cres = cache_res->calib_ctx_.get(); // Get the input shapes. const int batch_size = ctx->input(0).dim_size(0); const int num_inputs = ctx->num_inputs(); std::vector<TensorShape> shapes; cres->device_tensors_.resize(num_inputs); VLOG(1) << "Constructing calibrator"; for (int i = 0; i < num_inputs; i++) { // allocate workspace on device for inputs const Tensor& t = ctx->input(i); shapes.emplace_back(t.shape()); Tensor* device_tensor; TF_RETURN_IF_ERROR(ctx->allocate_persistent( t.dtype(), t.shape(), &cres->device_tensors_.at(i), &device_tensor)); CHECK_EQ(t.TotalBytes(), device_tensor->TotalBytes()); void* device_address = GetTensorAddress(device_tensor); if (device_address == nullptr) { return errors::InvalidArgument( "Unsupported data type encountered in input ", i); } cres->device_buffers_.emplace( StrCat(IONamePrefixes::kInputPHName, i), std::pair<void*, size_t>(device_address, device_tensor->TotalBytes())); } cres->calibrator_.reset( new TRTInt8Calibrator(cres->device_buffers_, batch_size, name())); const int platform_gpu_id = ctx->device()->tensorflow_gpu_device_info()->gpu_id; if (platform_gpu_id < 0) { LOG(ERROR) << "Can't get gpu_device_info from context->device()"; return errors::InvalidArgument( "Context->device doesn't contain device info!"); } cache_res->Ref(); cres->thr_.reset(new std::thread([this, cres, shapes, platform_gpu_id, cache_res]() { core::ScopedUnref sc(cache_res); VLOG(1) << "Starting calibration thread on device " << platform_gpu_id << ", Calibration Resource @ " << cres; auto err = cudaSetDevice(platform_gpu_id); if (err != cudaSuccess) { // TODO(aaroey): should return error here. LOG(ERROR) << "Couldn't set cuda device to " << platform_gpu_id << " in calibration thread"; } std::vector<PartialTensorShape> partial_shapes(shapes.begin(), shapes.end()); // ConvertGraphDefToEngine() will try to build the engine. This thread // will loop inside buildCudaEngine() consuming the calibration data // that is set by the TF op, and drive the builder until calibrator // returns false. Engine is discarded after calibration table is // generated // // TODO(aaroey): maybe setting the max batch size using the python // calibration wrapper class. auto s = convert::ConvertGraphDefToEngine( this->segment_graph_, TrtPrecisionMode::INT8, cres->calibrator_->getBatchSize(), this->workspace_size_, partial_shapes, &cache_res->GetLogger(), cache_res->allocator_.get(), cres->calibrator_.get(), &cres->engine_, /*use_calibration=*/true, /*convert_successfully=*/nullptr); if (!s.ok()) { LOG(ERROR) << "Calibration failed: " << s; cres->calibrator_->setDone(); // Ignore further pushes } else { // Transfer the ownership of the engine to the engine cache, so we can // dump it out during conversion for TF 2.0. mutex_lock lock(this->engine_mutex_); this->calibrator_ = std::move(cres->calibrator_); TrtUniquePtrType<nvinfer1::IExecutionContext> exec_context( cres->engine_->createExecutionContext()); cache_res->cache_.emplace( shapes, absl::make_unique<EngineContext>(std::move(cres->engine_), std::move(exec_context))); } VLOG(1) << "Calibration loop terminated " << this->name(); })); VLOG(1) << "initialized calibrator resource"; return Status::OK(); } REGISTER_KERNEL_BUILDER(Name("TRTEngineOp").Device(DEVICE_GPU), TRTEngineOp); } // namespace tensorrt } // namespace tensorflow #endif // GOOGLE_TENSORRT #endif // GOOGLE_CUDA
/**************************************************************************** ** Meta object code from reading C++ file 'coincontroltreewidget.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.5.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../src/qt/coincontroltreewidget.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'coincontroltreewidget.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.5.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_CoinControlTreeWidget_t { QByteArrayData data[1]; char stringdata0[22]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_CoinControlTreeWidget_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_CoinControlTreeWidget_t qt_meta_stringdata_CoinControlTreeWidget = { { QT_MOC_LITERAL(0, 0, 21) // "CoinControlTreeWidget" }, "CoinControlTreeWidget" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_CoinControlTreeWidget[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount 0 // eod }; void CoinControlTreeWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { Q_UNUSED(_o); Q_UNUSED(_id); Q_UNUSED(_c); Q_UNUSED(_a); } const QMetaObject CoinControlTreeWidget::staticMetaObject = { { &QTreeWidget::staticMetaObject, qt_meta_stringdata_CoinControlTreeWidget.data, qt_meta_data_CoinControlTreeWidget, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *CoinControlTreeWidget::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *CoinControlTreeWidget::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_CoinControlTreeWidget.stringdata0)) return static_cast<void*>(const_cast< CoinControlTreeWidget*>(this)); return QTreeWidget::qt_metacast(_clname); } int CoinControlTreeWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QTreeWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; return _id; } QT_END_MOC_NAMESPACE
#ifndef LAYOUT_H #define LAYOUT_H namespace Layout { template<typename T> struct PictureSizeT { T width; T height; }; struct PictureMeta { const char * Name; const char * Id; const char * Colour; char16_t thumbnailSizes[3]; char NameLen; }; typedef PictureSizeT<char16_t> PictureSize; typedef PictureSizeT<double> PictureSizeDouble; struct Window { double width; double height; double scrollBar; double excess; }; extern "C"{ extern void calcScaleFactors(Window w, int offset=0,bool scrollSubtracted=false ); extern void genPicTbl(); extern Window wnd; } }; #endif
/* * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "traffic/size/RandomMSD.h" #include <factory/ObjectFactory.h> #include <cassert> #include "event/Simulator.h" RandomMSD::RandomMSD( const std::string& _name, const Component* _parent, Json::Value _settings) : MessageSizeDistribution(_name, _parent, _settings), minMessageSize_(_settings["min_message_size"].asUInt()), maxMessageSize_(_settings["max_message_size"].asUInt()), doDependent_(_settings.isMember("dependent_min_message_size") && _settings.isMember("dependent_max_message_size")), depMinMessageSize_(_settings["dependent_min_message_size"].asUInt()), depMaxMessageSize_(_settings["dependent_max_message_size"].asUInt()) { assert(minMessageSize_ > 0); assert(maxMessageSize_ > 0); assert(maxMessageSize_ >= minMessageSize_); if (doDependent_) { assert(depMinMessageSize_ > 0); assert(depMaxMessageSize_ > 0); assert(depMaxMessageSize_ >= depMinMessageSize_); } else { assert(_settings["dependent_min_message_size"].isNull()); assert(_settings["dependent_max_message_size"].isNull()); } } RandomMSD::~RandomMSD() {} u32 RandomMSD::minMessageSize() const { return minMessageSize_; } u32 RandomMSD::maxMessageSize() const { return maxMessageSize_; } u32 RandomMSD::nextMessageSize() { return gSim->rnd.nextU64(minMessageSize_, maxMessageSize_); } u32 RandomMSD::nextMessageSize(const Message* _msg) { if (doDependent_) { return gSim->rnd.nextU64(depMinMessageSize_, depMaxMessageSize_); } else { return nextMessageSize(); } } registerWithObjectFactory("random", MessageSizeDistribution, RandomMSD, MESSAGESIZEDISTRIBUTION_ARGS);
//============================================================================== // Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at x // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef BOOST_SIMD_TOOLBOX_REDUCTION_FUNCTIONS_SIMD_SSE_AVX_COMPARE_EQUAL_HPP_INCLUDED #define BOOST_SIMD_TOOLBOX_REDUCTION_FUNCTIONS_SIMD_SSE_AVX_COMPARE_EQUAL_HPP_INCLUDED #ifdef BOOST_SIMD_HAS_AVX_SUPPORT #include <boost/simd/toolbox/reduction/functions/compare_equal.hpp> #include <boost/simd/sdk/simd/logical.hpp> #include <boost/simd/sdk/meta/scalar_of.hpp> #include <boost/simd/include/constants/false.hpp> namespace boost { namespace simd { namespace ext { BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::compare_equal_, boost::simd::tag::avx_ , (A0) , ((simd_<double_<A0>,boost::simd::tag::avx_>)) ((simd_<double_<A0>,boost::simd::tag::avx_>)) ) { typedef typename meta::scalar_of<A0>::type sA0; typedef typename meta::as_logical<sA0>::type result_type; BOOST_SIMD_FUNCTOR_CALL_REPEAT(2) { return result_type(_mm256_movemask_pd(eq(a0,a1)) == 0X0F); } }; BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::compare_equal_, boost::simd::tag::avx_ , (A0) , ((simd_<single_<A0>,boost::simd::tag::avx_>)) ((simd_<single_<A0>,boost::simd::tag::avx_>)) ) { typedef typename meta::scalar_of<A0>::type sA0; typedef typename meta::as_logical<sA0>::type result_type; BOOST_SIMD_FUNCTOR_CALL_REPEAT(2) { return result_type(_mm256_movemask_ps(eq(a0,a1)) == 0X0FF); } }; BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::compare_equal_, boost::simd::tag::avx_ , (A0) , ((simd_<integer_<A0>,boost::simd::tag::avx_>)) ((simd_<integer_<A0>,boost::simd::tag::avx_>)) ) { typedef typename meta::scalar_of<A0>::type sA0; typedef typename meta::as_logical<sA0>::type result_type; BOOST_SIMD_FUNCTOR_CALL_REPEAT(2) { typedef typename dispatch::meta::scalar_of<A0>::type stype; typedef native < stype, boost::simd::tag::sse_> htype; htype a00 = _mm256_extractf128_si256(a0, 0); htype a10 = _mm256_extractf128_si256(a1, 0); if (!compare_equal(a00, a10)) { return False<result_type>(); } else { htype a01 = _mm256_extractf128_si256(a0, 1); htype a11 = _mm256_extractf128_si256(a1, 1); return compare_equal(a01, a11); } } }; } } } #endif #endif
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_POLYGON_SYMBOLIZER_HPP #define MAPNIK_POLYGON_SYMBOLIZER_HPP // mapnik #include <mapnik/color.hpp> #include <mapnik/config.hpp> #include <mapnik/symbolizer.hpp> #include <mapnik/gamma_method.hpp> namespace mapnik { struct MAPNIK_DECL polygon_symbolizer : public symbolizer_base { polygon_symbolizer(); explicit polygon_symbolizer(color const& fill); color const& get_fill() const; void set_fill(color const& fill); void set_opacity(double opacity); double get_opacity() const; void set_gamma(double gamma); double get_gamma() const; void set_gamma_method(gamma_method_e gamma_method); gamma_method_e get_gamma_method() const; private: color fill_; double opacity_; double gamma_; gamma_method_e gamma_method_; }; } #endif // MAPNIK_POLYGON_SYMBOLIZER_HPP
/* * Copyright 2019 The WebRTC Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "rtc_base/operations_chain.h" #include "rtc_base/checks.h" namespace rtc { OperationsChain::CallbackHandle::CallbackHandle( scoped_refptr<OperationsChain> operations_chain) : operations_chain_(std::move(operations_chain)) {} OperationsChain::CallbackHandle::~CallbackHandle() { #if RTC_DCHECK_IS_ON RTC_DCHECK(has_run_); #endif } void OperationsChain::CallbackHandle::OnOperationComplete() { #if RTC_DCHECK_IS_ON RTC_DCHECK(!has_run_); has_run_ = true; #endif // RTC_DCHECK_IS_ON operations_chain_->OnOperationComplete(); // We have no reason to keep the |operations_chain_| alive through reference // counting anymore. operations_chain_ = nullptr; } // static scoped_refptr<OperationsChain> OperationsChain::Create() { return new OperationsChain(); } OperationsChain::OperationsChain() : RefCountedObject() { RTC_DCHECK_RUN_ON(&sequence_checker_); } OperationsChain::~OperationsChain() { // Operations keep the chain alive through reference counting so this should // not be possible. The fact that the chain is empty makes it safe to // destroy the OperationsChain on any sequence. RTC_DCHECK(chained_operations_.empty()); } void OperationsChain::SetOnChainEmptyCallback( std::function<void()> on_chain_empty_callback) { RTC_DCHECK_RUN_ON(&sequence_checker_); on_chain_empty_callback_ = std::move(on_chain_empty_callback); } bool OperationsChain::IsEmpty() const { RTC_DCHECK_RUN_ON(&sequence_checker_); return chained_operations_.empty(); } std::function<void()> OperationsChain::CreateOperationsChainCallback() { return [handle = rtc::scoped_refptr<CallbackHandle>( new CallbackHandle(this))]() { handle->OnOperationComplete(); }; } void OperationsChain::OnOperationComplete() { RTC_DCHECK_RUN_ON(&sequence_checker_); // The front element is the operation that just completed, remove it. RTC_DCHECK(!chained_operations_.empty()); chained_operations_.pop(); // If there are any other operations chained, execute the next one. Otherwise, // invoke the "on chain empty" callback if it has been set. if (!chained_operations_.empty()) { chained_operations_.front()->Run(); } else if (on_chain_empty_callback_.has_value()) { on_chain_empty_callback_.value()(); } } } // namespace rtc
#include "CKCinematicNode.h" #include "File.h" #include "CKLogic.h" void CKCinematicNode::reflectMembers(MemberListener &r) { } void CKCinematicBloc::reflectMembers(MemberListener &r) { CKCinematicNode::reflectMembers(r); r.reflect(cbUnk0, "cbUnk0"); r.reflect(cbUnk1, "cbUnk1"); r.reflect(cbUnk2, "cbUnk2"); r.reflect(cbSceneData, "cbSceneData"); r.reflect(cbGroupBloc, "cbGroupBloc"); r.reflect(cbUnk5, "cbUnk5"); r.reflect(cbUnk6, "cbUnk6"); r.reflect(cbUnk7, "cbUnk7"); r.reflect(cbUnk8, "cbUnk8"); r.reflect(cbScene, "cbScene"); } void CKCinematicDoor::reflectMembers(MemberListener &r) { CKCinematicNode::reflectMembers(r); r.reflect(cdUnk0, "cdUnk0"); r.reflect(cdUnk1, "cdUnk1"); r.reflect(cdUnk2, "cdUnk2"); r.reflect(cdUnk3, "cdUnk3"); r.reflect(cdUnk4, "cdUnk4"); r.reflect(cdGroupBloc, "cdGroupBloc"); r.reflect(cdScene, "cdScene"); } void CKLogicalAnd::reflectMembers(MemberListener &r) { CKCinematicDoor::reflectMembers(r); } void CKLogicalOr::reflectMembers(MemberListener &r) { CKCinematicDoor::reflectMembers(r); } void CKRandLogicalDoor::reflectMembers(MemberListener &r) { CKCinematicDoor::reflectMembers(r); } void CKStartDoor::reflectMembers(MemberListener &r) { CKCinematicDoor::reflectMembers(r); } void CKGroupBlocCinematicBloc::reflectMembers(MemberListener &r) { CKCinematicBloc::reflectMembers(r); r.reflectSize<uint32_t>(gbSubnodes, "sizeFor_gbSubnodes"); r.reflect(gbSubnodes, "gbSubnodes"); r.reflect(gbFirstNode, "gbFirstNode"); r.reflect(gbSecondNode, "gbSecondNode"); } void CKStreamGroupBlocCinematicBloc::reflectMembers(MemberListener &r) { CKGroupBlocCinematicBloc::reflectMembers(r); r.reflect(sgbUnk0, "sgbUnk0"); r.reflect(sgbUnk1, "sgbUnk1"); } void CKStartEventCinematicBloc::reflectMembers(MemberListener &r) { CKCinematicBloc::reflectMembers(r); r.reflect(seEvtNode, "seEvtNode", this); }
const unsigned short draw_object[] PROGMEM = { 0x7ff,0xfff, 0x8257,0xda7, 0x8000,0x7ff, 0x8257,0x257, 0x87ff,0x0, 0x8da7,0x257, 0x8fff,0x7ff, 0x8da7,0xda7, 0x87ff,0xfff, };
#include "stdafx.h" #include "CpDibHelper.h" FJCpDibHelper::FJCpDibHelper(void) { } FJCpDibHelper::~FJCpDibHelper(void) { }
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/afs/model/ConfigurationStyleResult.h> #include <json/json.h> using namespace AlibabaCloud::Afs; using namespace AlibabaCloud::Afs::Model; ConfigurationStyleResult::ConfigurationStyleResult() : ServiceResult() {} ConfigurationStyleResult::ConfigurationStyleResult(const std::string &payload) : ServiceResult() { parse(payload); } ConfigurationStyleResult::~ConfigurationStyleResult() {} void ConfigurationStyleResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto codeDataNode = value["CodeData"]; if(!codeDataNode["Html"].isNull()) codeData_.html = codeDataNode["Html"].asString(); if(!codeDataNode["Net"].isNull()) codeData_.net = codeDataNode["Net"].asString(); if(!codeDataNode["Php"].isNull()) codeData_.php = codeDataNode["Php"].asString(); if(!codeDataNode["Python"].isNull()) codeData_.python = codeDataNode["Python"].asString(); if(!codeDataNode["Java"].isNull()) codeData_.java = codeDataNode["Java"].asString(); if(!codeDataNode["NodeJs"].isNull()) codeData_.nodeJs = codeDataNode["NodeJs"].asString(); if(!codeDataNode["NetUrl"].isNull()) codeData_.netUrl = codeDataNode["NetUrl"].asString(); if(!codeDataNode["PhpUrl"].isNull()) codeData_.phpUrl = codeDataNode["PhpUrl"].asString(); if(!codeDataNode["PythonUrl"].isNull()) codeData_.pythonUrl = codeDataNode["PythonUrl"].asString(); if(!codeDataNode["JavaUrl"].isNull()) codeData_.javaUrl = codeDataNode["JavaUrl"].asString(); if(!codeDataNode["NodeJsUrl"].isNull()) codeData_.nodeJsUrl = codeDataNode["NodeJsUrl"].asString(); if(!value["BizCode"].isNull()) bizCode_ = value["BizCode"].asString(); } ConfigurationStyleResult::CodeData ConfigurationStyleResult::getCodeData()const { return codeData_; } std::string ConfigurationStyleResult::getBizCode()const { return bizCode_; }
/* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Id: NOTATIONDatatypeValidator.hpp,v 1.1 2004/07/13 02:37:43 WangKeBo Exp $ * $Log: NOTATIONDatatypeValidator.hpp,v $ * Revision 1.1 2004/07/13 02:37:43 WangKeBo * Component implementation * * Revision 1.1.1.1 2002/02/01 22:22:42 peiyongz * sane_include * * Revision 1.5 2001/09/24 15:33:15 peiyongz * DTV Reorganization: virtual methods moved to *.cpp * * Revision 1.4 2001/09/20 15:14:47 peiyongz * DTV reorganization: inherit from AbstractStringVaildator * * Revision 1.3 2001/08/24 17:12:01 knoaman * Add support for anySimpleType. * Remove parameter 'baseValidator' from the virtual method 'newInstance'. * * Revision 1.2 2001/08/21 18:42:53 peiyongz * Bugzilla# 2816: cleanUp() declared with external linkage and called * before defined as inline * * Revision 1.1 2001/07/05 20:15:27 peiyongz * NOTATIONDatatypeValidator * */ #if !defined(NOTATION_DATATYPEVALIDATOR_HPP) #define NOTATION_DATATYPEVALIDATOR_HPP #include <xercesc/validators/datatype/AbstractStringValidator.hpp> class VALIDATORS_EXPORT NOTATIONDatatypeValidator : public AbstractStringValidator { public: // ----------------------------------------------------------------------- // Public ctor/dtor // ----------------------------------------------------------------------- /** @name Constructor. */ //@{ NOTATIONDatatypeValidator(); NOTATIONDatatypeValidator(DatatypeValidator* const baseValidator , RefHashTableOf<KVStringPair>* const facets , RefVectorOf<XMLCh>* const enums , const int finalSet); virtual ~NOTATIONDatatypeValidator(); //@} /** * Returns an instance of the base datatype validator class * Used by the DatatypeValidatorFactory. */ virtual DatatypeValidator* newInstance(RefHashTableOf<KVStringPair>* const facets , RefVectorOf<XMLCh>* const enums , const int finalSet); protected: virtual void assignAdditionalFacet(const XMLCh* const key , const XMLCh* const value); virtual void inheritAdditionalFacet(); virtual void checkAdditionalFacetConstraints() const; virtual void checkAdditionalFacet(const XMLCh* const content) const; virtual void checkValueSpace(const XMLCh* const content); virtual int getLength(const XMLCh* const content) const; private: // ----------------------------------------------------------------------- // Private data members // // Nil // ----------------------------------------------------------------------- }; /** * End of file NOTATIONDatatypeValidator.hpp */ #endif
/* Copyright (c) 2019 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License, * attached with Common Clause Condition 1.0, found in the LICENSES directory. */ #include "storage/StorageServer.h" #include <thrift/lib/cpp/concurrency/ThreadManager.h> #include "clients/storage/InternalStorageClient.h" #include "common/hdfs/HdfsCommandHelper.h" #include "common/meta/ServerBasedIndexManager.h" #include "common/meta/ServerBasedSchemaManager.h" #include "common/network/NetworkUtils.h" #include "common/thread/GenericThreadPool.h" #include "common/utils/Utils.h" #include "kvstore/PartManager.h" #include "storage/BaseProcessor.h" #include "storage/CompactionFilter.h" #include "storage/GraphStorageServiceHandler.h" #include "storage/InternalStorageServiceHandler.h" #include "storage/StorageAdminServiceHandler.h" #include "storage/StorageFlags.h" #include "storage/http/StorageHttpAdminHandler.h" #include "storage/http/StorageHttpDownloadHandler.h" #include "storage/http/StorageHttpIngestHandler.h" #include "storage/http/StorageHttpStatsHandler.h" #include "storage/transaction/TransactionManager.h" #include "version/Version.h" #include "webservice/Router.h" #include "webservice/WebService.h" DEFINE_int32(port, 44500, "Storage daemon listening port"); DEFINE_int32(num_io_threads, 16, "Number of IO threads"); DEFINE_int32(num_worker_threads, 32, "Number of workers"); DEFINE_int32(storage_http_thread_num, 3, "Number of storage daemon's http thread"); DEFINE_bool(local_config, false, "meta client will not retrieve latest configuration from meta"); namespace nebula { namespace storage { StorageServer::StorageServer(HostAddr localHost, std::vector<HostAddr> metaAddrs, std::vector<std::string> dataPaths, std::string walPath, std::string listenerPath) : localHost_(localHost), metaAddrs_(std::move(metaAddrs)), dataPaths_(std::move(dataPaths)), walPath_(std::move(walPath)), listenerPath_(std::move(listenerPath)) {} StorageServer::~StorageServer() { stop(); } std::unique_ptr<kvstore::KVStore> StorageServer::getStoreInstance() { kvstore::KVOptions options; options.dataPaths_ = dataPaths_; options.walPath_ = walPath_; options.listenerPath_ = listenerPath_; options.partMan_ = std::make_unique<kvstore::MetaServerBasedPartManager>(localHost_, metaClient_.get()); options.cffBuilder_ = std::make_unique<StorageCompactionFilterFactoryBuilder>(schemaMan_.get(), indexMan_.get()); options.schemaMan_ = schemaMan_.get(); if (FLAGS_store_type == "nebula") { auto nbStore = std::make_unique<kvstore::NebulaStore>( std::move(options), ioThreadPool_, localHost_, workers_); if (!(nbStore->init())) { LOG(ERROR) << "nebula store init failed"; return nullptr; } return nbStore; } else if (FLAGS_store_type == "hbase") { LOG(FATAL) << "HBase store has not been implemented"; } else { LOG(FATAL) << "Unknown store type \"" << FLAGS_store_type << "\""; } return nullptr; } bool StorageServer::initWebService() { LOG(INFO) << "Starting Storage HTTP Service"; hdfsHelper_ = std::make_unique<hdfs::HdfsCommandHelper>(); webWorkers_ = std::make_unique<nebula::thread::GenericThreadPool>(); webWorkers_->start(FLAGS_storage_http_thread_num, "http thread pool"); LOG(INFO) << "Http Thread Pool started"; webSvc_ = std::make_unique<WebService>(); auto& router = webSvc_->router(); router.get("/download").handler([this](web::PathParams&&) { auto* handler = new storage::StorageHttpDownloadHandler(); handler->init(hdfsHelper_.get(), webWorkers_.get(), kvstore_.get(), dataPaths_); return handler; }); router.get("/ingest").handler([this](web::PathParams&&) { auto handler = new nebula::storage::StorageHttpIngestHandler(); handler->init(kvstore_.get()); return handler; }); router.get("/admin").handler([this](web::PathParams&&) { return new storage::StorageHttpAdminHandler(schemaMan_.get(), kvstore_.get()); }); router.get("/rocksdb_stats").handler([](web::PathParams&&) { return new storage::StorageHttpStatsHandler(); }); auto status = webSvc_->start(); return status.ok(); } bool StorageServer::start() { ioThreadPool_ = std::make_shared<folly::IOThreadPoolExecutor>(FLAGS_num_io_threads); workers_ = apache::thrift::concurrency::PriorityThreadManager::newPriorityThreadManager( FLAGS_num_worker_threads, true /*stats*/); workers_->setNamePrefix("executor"); workers_->start(); // Meta client meta::MetaClientOptions options; options.localHost_ = localHost_; options.serviceName_ = ""; options.skipConfig_ = FLAGS_local_config; options.role_ = nebula::meta::cpp2::HostRole::STORAGE; // If listener path is specified, it will start as a listener if (!listenerPath_.empty()) { options.role_ = nebula::meta::cpp2::HostRole::LISTENER; } options.gitInfoSHA_ = gitInfoSha(); metaClient_ = std::make_unique<meta::MetaClient>(ioThreadPool_, metaAddrs_, options); if (!metaClient_->waitForMetadReady()) { LOG(ERROR) << "waitForMetadReady error!"; return false; } LOG(INFO) << "Init schema manager"; schemaMan_ = meta::ServerBasedSchemaManager::create(metaClient_.get()); LOG(INFO) << "Init index manager"; indexMan_ = meta::ServerBasedIndexManager::create(metaClient_.get()); LOG(INFO) << "Init kvstore"; kvstore_ = getStoreInstance(); if (nullptr == kvstore_) { LOG(ERROR) << "Init kvstore failed"; return false; } if (!initWebService()) { LOG(ERROR) << "Init webservice failed!"; return false; } taskMgr_ = AdminTaskManager::instance(); if (!taskMgr_->init()) { LOG(ERROR) << "Init task manager failed!"; return false; } env_ = std::make_unique<storage::StorageEnv>(); env_->kvstore_ = kvstore_.get(); env_->indexMan_ = indexMan_.get(); env_->schemaMan_ = schemaMan_.get(); env_->rebuildIndexGuard_ = std::make_unique<IndexGuard>(); env_->metaClient_ = metaClient_.get(); txnMan_ = std::make_unique<TransactionManager>(env_.get()); env_->txnMan_ = txnMan_.get(); env_->verticesML_ = std::make_unique<VerticesMemLock>(); env_->edgesML_ = std::make_unique<EdgesMemLock>(); storageThread_.reset(new std::thread([this] { try { auto handler = std::make_shared<GraphStorageServiceHandler>(env_.get()); storageServer_ = std::make_unique<apache::thrift::ThriftServer>(); storageServer_->setPort(FLAGS_port); storageServer_->setIdleTimeout(std::chrono::seconds(0)); storageServer_->setIOThreadPool(ioThreadPool_); storageServer_->setThreadManager(workers_); storageServer_->setStopWorkersOnStopListening(false); storageServer_->setInterface(std::move(handler)); ServiceStatus expected = STATUS_UNINITIALIZED; if (!storageSvcStatus_.compare_exchange_strong(expected, STATUS_RUNNING)) { LOG(ERROR) << "Impossible! How could it happen!"; return; } LOG(INFO) << "The storage service start on " << localHost_; storageServer_->serve(); // Will wait until the server shuts down } catch (const std::exception& e) { LOG(ERROR) << "Start storage service failed, error:" << e.what(); } storageSvcStatus_.store(STATUS_STTOPED); LOG(INFO) << "The storage service stopped"; })); adminThread_.reset(new std::thread([this] { try { auto handler = std::make_shared<StorageAdminServiceHandler>(env_.get()); auto adminAddr = Utils::getAdminAddrFromStoreAddr(localHost_); adminServer_ = std::make_unique<apache::thrift::ThriftServer>(); adminServer_->setPort(adminAddr.port); adminServer_->setIdleTimeout(std::chrono::seconds(0)); adminServer_->setIOThreadPool(ioThreadPool_); adminServer_->setThreadManager(workers_); adminServer_->setStopWorkersOnStopListening(false); adminServer_->setInterface(std::move(handler)); ServiceStatus expected = STATUS_UNINITIALIZED; if (!adminSvcStatus_.compare_exchange_strong(expected, STATUS_RUNNING)) { LOG(ERROR) << "Impossible! How could it happen!"; return; } LOG(INFO) << "The admin service start on " << adminAddr; adminServer_->serve(); // Will wait until the server shuts down } catch (const std::exception& e) { LOG(ERROR) << "Start admin service failed, error:" << e.what(); } adminSvcStatus_.store(STATUS_STTOPED); LOG(INFO) << "The admin service stopped"; })); internalStorageThread_.reset(new std::thread([this] { try { auto handler = std::make_shared<InternalStorageServiceHandler>(env_.get()); auto internalAddr = Utils::getInternalAddrFromStoreAddr(localHost_); internalStorageServer_ = std::make_unique<apache::thrift::ThriftServer>(); internalStorageServer_->setPort(internalAddr.port); internalStorageServer_->setIdleTimeout(std::chrono::seconds(0)); internalStorageServer_->setIOThreadPool(ioThreadPool_); internalStorageServer_->setThreadManager(workers_); internalStorageServer_->setStopWorkersOnStopListening(false); internalStorageServer_->setInterface(std::move(handler)); internalStorageSvcStatus_.store(STATUS_RUNNING); LOG(INFO) << "The internal storage service start(same with admin) on " << internalAddr; internalStorageServer_->serve(); // Will wait until the server shuts down } catch (const std::exception& e) { LOG(ERROR) << "Start internal storage service failed, error:" << e.what(); } internalStorageSvcStatus_.store(STATUS_STTOPED); LOG(INFO) << "The internal storage service stopped"; })); while (storageSvcStatus_.load() == STATUS_UNINITIALIZED || adminSvcStatus_.load() == STATUS_UNINITIALIZED || internalStorageSvcStatus_.load() == STATUS_UNINITIALIZED) { std::this_thread::sleep_for(std::chrono::microseconds(100)); } if (storageSvcStatus_.load() != STATUS_RUNNING || adminSvcStatus_.load() != STATUS_RUNNING || internalStorageSvcStatus_.load() != STATUS_RUNNING) { return false; } return true; } void StorageServer::waitUntilStop() { adminThread_->join(); storageThread_->join(); internalStorageThread_->join(); } void StorageServer::stop() { if (adminSvcStatus_.load() == ServiceStatus::STATUS_STTOPED && storageSvcStatus_.load() == ServiceStatus::STATUS_STTOPED && internalStorageSvcStatus_.load() == ServiceStatus::STATUS_STTOPED) { LOG(INFO) << "All services has been stopped"; return; } ServiceStatus adminExpected = ServiceStatus::STATUS_RUNNING; adminSvcStatus_.compare_exchange_strong(adminExpected, STATUS_STTOPED); ServiceStatus storageExpected = ServiceStatus::STATUS_RUNNING; storageSvcStatus_.compare_exchange_strong(storageExpected, STATUS_STTOPED); ServiceStatus interStorageExpected = ServiceStatus::STATUS_RUNNING; internalStorageSvcStatus_.compare_exchange_strong(interStorageExpected, STATUS_STTOPED); // kvstore need to stop back ground job before http server dctor if (kvstore_) { kvstore_->stop(); } webSvc_.reset(); if (taskMgr_) { taskMgr_->shutdown(); } if (metaClient_) { metaClient_->stop(); } if (kvstore_) { kvstore_.reset(); } if (adminServer_) { adminServer_->stop(); } if (internalStorageServer_) { internalStorageServer_->stop(); } if (storageServer_) { storageServer_->stop(); } } } // namespace storage } // namespace nebula
#pragma once #include <iostream> #define test_assert(x) \ if(!(x))\ {\ std::cout << "Test failed in\n" << __FILE__ << ":" << __LINE__ << "\ncondition \"" << #x << "\" is false" << std::endl;\ std::exit(-1);\ } #define test_assert_near(x,y, eps) test_assert(std::abs((x) - (y)) <= std::abs(eps) )
#include "config.h" #include <Arduino.h> #include <time.h> #include "gui.h" #include "ui/keyboard.h" #include "ui/message.h" #include "ui/loader.h" #include "ui/wifilist.h" #include "ui/navigationview.h" #include <WiFi.h> #include "string.h" #include <Ticker.h> #include "FS.h" #include "SD.h" #include "hardware/Wifi.h" #include "system/systemobject.h" #include "system/observable.h" #include "system/events.h" #include "ui/settings_view.h" #include "ui/wifisettings.h" #include "ui/signalk_settings.h" #include "ui/time_settings.h" #include "ui/watch_info.h" #include "ui/display_settings.h" #include "ui/wakeup_settings.h" #include "hardware/hardware.h" #include "system/async_dispatcher.h" #include <functional> #include "sounds/beep.h" #include "sounds/alert.h" #include "ui/ui_functions.h" /* In order to use std::bind to attach to method we need to use arguments placeholders that will map arguments to final method. * So in function setup_gui on line with attach_power_callback we just type _1 or _2 without whole namespace. */ using std::placeholders::_1; using std::placeholders::_2; LV_FONT_DECLARE(Geometr); LV_FONT_DECLARE(Ubuntu); LV_FONT_DECLARE(roboto70); LV_FONT_DECLARE(roboto30); LV_FONT_DECLARE(lv_font_montserrat_16); LV_FONT_DECLARE(lv_font_montserrat_22); LV_IMG_DECLARE(sk_status); LV_IMG_DECLARE(signalk_48px); LV_IMG_DECLARE(menu); LV_IMG_DECLARE(wifi_48px); LV_IMG_DECLARE(info_48px); LV_IMG_DECLARE(time_48px); LV_IMG_DECLARE(display_48px); LV_IMG_DECLARE(wakeup_48px); LV_IMG_DECLARE(step); LV_IMG_DECLARE(sk_statusbar_icon); const char *GUI_TAG = "GUI"; static void main_menu_event_cb(lv_obj_t *obj, lv_event_t event) { Gui *gui = (Gui *)obj->user_data; if (event == LV_EVENT_SHORT_CLICKED) { //! Event callback is in here gui->show_settings(); } } void Gui::setup_gui(WifiManager *wifi, SignalKSocket *socket, Hardware *hardware) { twatchsk::UI_Functions = new twatchsk::UIFunctions(this); wifiManager = wifi; ws_socket = socket; hardware_ = hardware; // attach power events to GUI hardware->attach_power_callback(std::bind(&Gui::on_power_event, this, _1, _2)); // Hardware class needs to know what is the screen timeout, wire it to Gui::get_screen_timeout func hardware->set_screen_timeout_func(std::bind(&Gui::get_screen_timeout, this)); lv_obj_t *scr = lv_scr_act(); // set the theme uint32_t flag = twatchsk::dark_theme_enabled ? LV_THEME_MATERIAL_FLAG_DARK : LV_THEME_MATERIAL_FLAG_LIGHT; LV_THEME_DEFAULT_INIT(lv_theme_get_color_primary(), lv_theme_get_color_secondary(), flag, // Initiate the theme lv_theme_get_font_small(), lv_theme_get_font_normal(), lv_theme_get_font_subtitle(), lv_theme_get_font_title()); bar = new StatusBar(); bar->setup(scr); // intialize status bar icons // battery/charge icon and battery percent batteryPercent_ = bar->create_text_icon(LV_SYMBOL_BATTERY_EMPTY "0%", StatusBarLocation::Right); update_battery_level(); // step counter icon and number of steps stepCounterIcon_ = bar->create_image_icon(&step, StatusBarLocation::Left); stepCounterSteps_ = bar->create_text_icon("0", StatusBarLocation::Left); // wifi status icon WifiIcon_ = bar->create_text_icon(LV_SYMBOL_WIFI, StatusBarLocation::Right, StatusBarIconStatus::Hidden); // signal k status icon SKIcon_ = bar->create_image_icon(&sk_statusbar_icon, StatusBarLocation::Right, StatusBarIconStatus::Hidden); // messages counter pendingMessagesIcon_ = bar->create_text_icon(LV_SYMBOL_BELL " 0", StatusBarLocation::Left, StatusBarIconStatus::Hidden); //! main static lv_style_t mainStyle; lv_style_init(&mainStyle); lv_style_set_radius(&mainStyle, LV_OBJ_PART_MAIN, 0); lv_style_set_border_width(&mainStyle, LV_OBJ_PART_MAIN, 0); mainBar = lv_tileview_create(scr, NULL); lv_obj_add_style(mainBar, LV_OBJ_PART_MAIN, &mainStyle); lv_obj_set_pos(mainBar, 0, bar->height()); // we need to update is_active_view_dynamic_ field mainBar->user_data = this; lv_obj_set_event_cb(mainBar, Gui::lv_mainbar_callback); watch_face = lv_cont_create(mainBar, NULL); lv_obj_add_style(watch_face, LV_OBJ_PART_MAIN, &mainStyle); lv_obj_set_pos(watch_face, 0, 0); lv_obj_set_size(watch_face, LV_HOR_RES, LV_VER_RES - bar->height()); lv_tileview_add_element(mainBar, watch_face); //! Time static lv_style_t timeStyle; // for minutes and hours lv_style_copy(&timeStyle, &mainStyle); lv_style_set_text_font(&timeStyle, LV_STATE_DEFAULT, &roboto70); watchNameLabel = lv_label_create(watch_face, NULL); lv_obj_set_style_local_text_font(watchNameLabel, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, &lv_font_montserrat_16); timeLabel = lv_label_create(watch_face, NULL); lv_obj_add_style(timeLabel, LV_OBJ_PART_MAIN, &timeStyle); static lv_style_t timeSuffixStyle; // for am/pm and seconds lv_style_copy(&timeSuffixStyle, &mainStyle); lv_style_set_text_font(&timeSuffixStyle, LV_STATE_DEFAULT, &roboto30); timeSuffixLabel = lv_label_create(watch_face, NULL); lv_obj_add_style(timeSuffixLabel, LV_OBJ_PART_MAIN, &timeSuffixStyle); secondsLabel = lv_label_create(watch_face, NULL); lv_obj_add_style(secondsLabel, LV_OBJ_PART_MAIN, &timeSuffixStyle); dayDateLabel = lv_label_create(watch_face, NULL); update_time(); menuBtn = lv_imgbtn_create(watch_face, NULL); lv_imgbtn_set_src(menuBtn, LV_BTN_STATE_RELEASED, &menu); lv_imgbtn_set_src(menuBtn, LV_BTN_STATE_PRESSED, &menu); lv_imgbtn_set_src(menuBtn, LV_BTN_STATE_CHECKED_RELEASED, &menu); lv_imgbtn_set_src(menuBtn, LV_BTN_STATE_CHECKED_PRESSED, &menu); twatchsk::update_imgbtn_color(menuBtn); // make the four little squares be the correct color for the theme lv_obj_align(menuBtn, watch_face, LV_ALIGN_OUT_BOTTOM_MID, 0, -100); menuBtn->user_data = this; lv_obj_set_event_cb(menuBtn, main_menu_event_cb); auto update_task = lv_task_create(lv_update_task, 1000, LV_TASK_PRIO_LOWEST, NULL); auto batery_update_task = lv_task_create(lv_battery_task, 30000, LV_TASK_PRIO_LOWEST, NULL); update_task->user_data = this; batery_update_task->user_data = this; dynamic_gui = new DynamicGui(); dynamic_gui->initialize(); int dynamic_view_count = 0; if (!dynamic_gui->load_file("/sk_view.json", mainBar, socket, dynamic_view_count)) { ESP_LOGW(GUI_TAG, "Failed to load dynamic views!"); } dynamic_view_count++; update_tiles_valid_points(dynamic_view_count); lv_tileview_set_valid_positions(mainBar, tile_valid_points, tile_valid_points_count); lv_tileview_set_edge_flash(mainBar, true); //setup guide arrows (left/right) to indicate swype direction arrow_left = lv_label_create(scr, NULL); lv_label_set_text(arrow_left, LV_SYMBOL_LEFT); lv_obj_set_pos(arrow_left, 9, bar->height() + 5); arrow_right = lv_label_create(scr, NULL); lv_obj_set_pos(arrow_right, LV_HOR_RES - 15, bar->height() + 5); lv_label_set_text(arrow_right, LV_SYMBOL_RIGHT); //show arrows after booting update_arrows_visibility(false, tile_valid_points_count > 1); } void Gui::update_tiles_valid_points(int count) { if (tile_valid_points != NULL) { free(tile_valid_points); tile_valid_points = NULL; tile_valid_points_count = 0; } tile_valid_points = (lv_point_t *)malloc(sizeof(lv_point_t) * count); for (int i = 0; i < count; i++) { tile_valid_points[i].x = i; tile_valid_points[i].y = 0; } tile_valid_points_count = count; } void Gui::update_step_counter(uint32_t counter) { char buf[20]; sprintf(buf, "%d", counter); stepCounterSteps_->set_text(buf); } void Gui::update_time() { time_t now; struct tm info; char buf[64]; char day_date_buf[32]; time(&now); localtime_r(&now, &info); lv_obj_align(watchNameLabel, NULL, LV_ALIGN_IN_TOP_MID, 0, 3); lv_label_set_text(watchNameLabel, get_watch_name()); lv_obj_align(timeLabel, NULL, LV_ALIGN_IN_TOP_MID, -23, 25); if (time_24hour_format) { lv_obj_set_hidden(timeSuffixLabel, true); strftime(buf, sizeof(buf), "%H:%M", &info); // see http://www.cplusplus.com/reference/ctime/strftime/ strftime(day_date_buf, sizeof(day_date_buf), "%a %e %b, %G", &info); // day/month format lv_obj_set_hidden(timeSuffixLabel, true); // hide the suffix label as it's not needed } else { lv_obj_set_hidden(timeSuffixLabel, false); strftime(buf, sizeof(buf), "%I:%M", &info); strftime(day_date_buf, sizeof(day_date_buf), "%a %b %e, %G", &info); // month/day format if (info.tm_hour > 12) { lv_label_set_text(timeSuffixLabel, "pm"); } else { lv_label_set_text(timeSuffixLabel, "am"); } lv_obj_align(timeSuffixLabel, timeLabel, LV_ALIGN_OUT_RIGHT_MID, 3, -22); } lv_label_set_text(this->timeLabel, buf); lv_obj_align(secondsLabel, timeLabel, LV_ALIGN_OUT_RIGHT_MID, 4, 13); lv_label_set_text_fmt(secondsLabel, ":%.2d", info.tm_sec); lv_obj_set_style_local_text_font(dayDateLabel, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, &lv_font_montserrat_22); lv_obj_align(dayDateLabel, watch_face, LV_ALIGN_OUT_BOTTOM_MID, 0, -30); lv_label_set_text(dayDateLabel, day_date_buf); } void Gui::update_battery_level() { TTGOClass *ttgo = TTGOClass::getWatch(); int level = ttgo->power->getBattPercentage(); char buff[10]; auto batterySymbol = LV_SYMBOL_BATTERY_FULL; if (ttgo->power->isChargeing()) { batterySymbol = LV_SYMBOL_CHARGE; } else { if (level > 80) { batterySymbol = LV_SYMBOL_BATTERY_3; } else if (level > 45) { batterySymbol = LV_SYMBOL_BATTERY_2; } else if (level > 20) { batterySymbol = LV_SYMBOL_BATTERY_1; } else { batterySymbol = LV_SYMBOL_BATTERY_EMPTY; } } sprintf(buff, "%s %d%%", batterySymbol, level); batteryPercent_->set_text(buff); } char *Gui::message_from_code(GuiMessageCode_t code) { switch (code) { case GuiMessageCode_t::GUI_WARN_SK_REJECTED: return LOC_SIGNALK_REQUEST_REJECTED; case GuiMessageCode_t::GUI_WARN_WIFI_DISCONNECTED: return LOC_WIFI_LOST_CONNECTION; case GuiMessageCode_t::GUI_WARN_WIFI_CONNECTION_FAILED: return LOC_WIFI_ASSOC_FAIL; case GuiMessageCode_t::GUI_WARN_SK_LOST_CONNECTION: return LOC_SIGNALK_CONNECTION_LOST; case GuiMessageCode_t::GUI_INFO_BATTERY_CHARGE_COMPLETE: return LOC_POWER_BATTERY_CHARGED; default: return NULL; }; } void Gui::on_power_event(PowerCode_t code, uint32_t arg) { if (code == PowerCode_t::POWER_LEAVE_LOW_POWER) { auto ttgo = TTGOClass::getWatch(); ttgo->bl->adjust(get_adjusted_display_brightness()); bar->dont_refresh(); update_step_counter(ttgo->bma->getCounter()); update_battery_level(); increment_wakeup_count(); bar->do_refresh(); switch (arg) { case WAKEUP_BUTTON: clear_temporary_screen_timeout(); // waking up with a button press - if the last timeout was temporary, clear it // hardware_->get_player()->play_raw_from_const("alert", beep_sound, beep_sound_len, 1); break; case WAKEUP_ACCELEROMETER: // waking up with double tap or tilt set_temporary_screen_timeout(2); break; // case WAKEUP_TOUCH: // not yet implemented // set_temporary_screen_timeout(2); // change this when it is implemented // break; default: clear_temporary_screen_timeout(); } update_gui(); lv_disp_trig_activity(NULL); // update subscriptions if we are on dynamic view if (is_active_view_dynamic_) { ws_socket->update_subscriptions(); } update_arrows_visibility(); } else if (code == PowerCode_t::POWER_CHARGING_ON) { update_battery_level(); } else if (code == PowerCode_t::POWER_CHARGING_OFF || code == PowerCode_t::POWER_CHARGING_DONE) { update_battery_level(); if (code == PowerCode_t::POWER_CHARGING_DONE) // notify user the watch is fully charged { post_gui_warning(GuiMessageCode_t::GUI_INFO_BATTERY_CHARGE_COMPLETE); } } else if (code == PowerCode_t::WALK_STEP_COUNTER_UPDATED) { update_step_counter(arg); } else if (code == PowerCode_t::DOUBLE_TAP_DETECTED) // while watch is awake - this switches between LIGHT and DARK theme { if (screen_timeout_is_temporary) // double-tap occurs during a quickie "time check" that resulted from a double-tap or tilt { clear_temporary_screen_timeout(); // leave the screen on for the normal timeout time, then change the theme } twatchsk::dark_theme_enabled = !twatchsk::dark_theme_enabled; uint32_t flag = twatchsk::dark_theme_enabled ? LV_THEME_MATERIAL_FLAG_DARK : LV_THEME_MATERIAL_FLAG_LIGHT; // Create a theme flag and set it to the new theme LV_THEME_DEFAULT_INIT(lv_theme_get_color_primary(), lv_theme_get_color_secondary(), flag, // Initiate the theme with the flag lv_theme_get_font_small(), lv_theme_get_font_normal(), lv_theme_get_font_subtitle(), lv_theme_get_font_title()); set_display_brightness(twatchsk::dark_theme_enabled ? 1 : 5); auto ttgo = TTGOClass::getWatch(); ttgo->bl->adjust(get_adjusted_display_brightness()); View::invoke_theme_changed(); // calls theme_changed() for every descendant of View class this->theme_changed(); // updates theme for status bar icons (because StatusBar is not a descendant of View class) if (View::get_active_views_count() == 0) // we're on the home screen, so save the new theme to SPIFFS immediately { // JD: commented out for now - causes crash :-/ /*twatchsk::run_async("GUI Settings save", [this]() { delay(100); this->save(); });*/ } else { gui_needs_saved = true; // flag to save the new theme to SPIFFS later, when NavigationView is closed } } } void Gui::lv_update_task(struct _lv_task_t *data) { Gui *gui = (Gui *)data->user_data; gui->update_gui(); } void Gui::update_gui() { update_time(); auto wifiStatus = wifiManager->get_status(); if (wifiStatus == WifiState_t::Wifi_Connected || wifiStatus == WifiState_t::Wifi_Connecting) { WifiIcon_->set_status(StatusBarIconStatus::Visible); } else if (wifiStatus == WifiState_t::Wifi_Disconnected) { WifiIcon_->set_status(StatusBarIconStatus::Warning); } else { WifiIcon_->set_status(StatusBarIconStatus::Hidden); } if (ws_socket->get_state() == WebsocketState_t::WS_Connected) { if (ws_socket->get_token_request_pending()) { SKIcon_->set_status(StatusBarIconStatus::Warning); } else { SKIcon_->set_status(StatusBarIconStatus::Visible); } dynamic_gui->update_online(true); } else { SKIcon_->set_status(StatusBarIconStatus::Hidden); dynamic_gui->update_online(false); } handle_gui_queue(); if(arrows_hide_at_time < millis()) { lv_obj_set_hidden(arrow_left, true); lv_obj_set_hidden(arrow_right, true); } } void Gui::handle_gui_queue() { GuiEvent_t event; while (read_gui_update(event)) { if (event.event_type == GuiEventType_t::GUI_SHOW_WARNING) { ESP_LOGI(GUI_TAG, "Show message %d, event=%d, message code=%d!", (int)event.argument, event.event_type, event.message_code); char *message = NULL; if (event.message_code != GuiMessageCode_t::NONE) // WIFI or SK connection message { message = message_from_code(event.message_code); } else // SK Server alarm/alert/warn/emergency, or MDNS-related error message { message = (char *)event.argument; } if (message != NULL) { // create and populate a new PendingMsg_t PendingMsg_t new_message; new_message.msg_text = message; if (event.message_code == GUI_WARN_WIFI_CONNECTION_FAILED || event.message_code == GUI_WARN_WIFI_DISCONNECTED) { new_message.msg_topic = Wifi_Problem; } new_message.msg_time = current_time(); new_message.msg_count = 1; if (pending_messages_.size() == 0) // list is empty { pending_messages_.push_back(new_message); // add it to the list hardware_->vibrate(300); // just a very brief vibration for each added message // Run beep hardware_->get_player()->play_raw_from_const("alert", beep_sound, beep_sound_len, 3); ESP_LOGI(GUI_TAG, "pending_messages_ empty, so msg added: %s, %s", new_message.msg_text.c_str(), new_message.msg_time.c_str()); } else { bool message_found = false; for (std::list<PendingMsg_t>::iterator it = pending_messages_.begin(); it != pending_messages_.end(); ++it) { if (new_message.msg_text == it->msg_text) // this message is already in the list { // update its time and count ESP_LOGI(GUI_TAG, "Msg is already in pending_messages_: %s, %s", new_message.msg_text.c_str(), new_message.msg_time.c_str()); it->msg_time = current_time(); it->msg_count++; // update the text on the screen to show the latest time and the new count and the new size of pending_messages it = pending_messages_.begin(); // get back to the first message in the list, which is the one currently being displayed String updated_text = it->msg_time + "\n(" + it->msg_count + "x) " + it->msg_text; lv_msgbox_set_text(msgBox, updated_text.c_str()); message_found = true; hardware_->vibrate(300); // just a very brief vibration for each added message hardware_->get_player()->play_raw_from_const("alert", beep_sound, beep_sound_len, alert_sound_default_repeat); break; } } if (!message_found) // it's not already in the list { pending_messages_.push_back(new_message); // add it to the list ESP_LOGI(GUI_TAG, "Msg added to pending_messages_: %s, %s", new_message.msg_text.c_str(), new_message.msg_time.c_str()); // update the unread-messages count on any currently-displayed message std::list<PendingMsg_t>::iterator it = pending_messages_.begin(); // get the first message - that's the one that's currently displayed String updated_text = // re-create the message text to reflect the new pending_messages_.size() it->msg_time + "\n(" + it->msg_count + "x) " + it->msg_text + "\n\n(" + (String)(pending_messages_.size() - 1) + LOC_UNREAD_MSGS + ")"; lv_msgbox_set_text(msgBox, updated_text.c_str()); // display the updated text on the currently-displayed message hardware_->vibrate(300); // vibrate for 300 ms (100 ms on, 100 ms off, 100 ms on) } } ESP_LOGI(GUI_TAG, "There are %d messages in pending_messages", pending_messages_.size()); update_pending_messages(); if (display_next_pending_message_) // if there is not already a message displayed { display_next_message(false); // false means "do not delete the first message before displaying the next one" } } } else if (event.event_type == GuiEventType_t::GUI_SK_DV_UPDATE) { StaticJsonDocument<512> update; auto result = deserializeJson(update, event.argument); if (result == DeserializationError::Ok) { auto path = update["path"].as<String>(); auto value = update["value"].as<JsonVariant>(); dynamic_gui->handle_signalk_update(path, value); } else { ESP_LOGI(GUI_TAG, "Unable to parse json, error=%s", result.c_str()); } } if (event.argument != NULL) { free(event.argument); } } } void Gui::lv_battery_task(struct _lv_task_t *data) { Gui *gui = (Gui *)data->user_data; gui->update_battery_level(); } void Gui::hide_status_bar(bool hidden) { bar->set_hidden(hidden); } void Gui::hide_main_bar(bool hidden) { lv_obj_set_hidden(mainBar, hidden); } uint8_t Gui::get_adjusted_display_brightness() { uint8_t adjusted_brightness = get_display_brightness(); if (adjusted_brightness == 1) { return 10; // minimum readable level in bright light } adjusted_brightness = (adjusted_brightness - 1) * 63; return adjusted_brightness; } void Gui::load_config_from_file(const JsonObject &json) { time_24hour_format = json["24hourformat"].as<bool>(); screen_timeout = json["screentimeout"].as<int>(); timezone_id = json["timezone"].as<int>(); display_brightness = json["brightness"].as<int>(); twatchsk::dark_theme_enabled = json["darktheme"].as<bool>(); char watchname[16] = ""; if (strcmp(watchname, json["watchname"].as<String>().c_str()) != 0) // saved name is not blank { strcpy(watch_name, json["watchname"].as<String>().c_str()); } else { strcpy(watch_name, "Set watch name"); } ESP_LOGI(GUI_TAG, "Loaded settings: 24hour=%d, ScreenTimeout=%d, TimezoneID=%d, Brightness=%d, DarkTheme=%d, WatchName=%s", time_24hour_format, screen_timeout, timezone_id, display_brightness, twatchsk::dark_theme_enabled, watch_name); } void Gui::save_config_to_file(JsonObject &json) { json["24hourformat"] = time_24hour_format; json["screentimeout"] = screen_timeout; json["timezone"] = timezone_id; json["brightness"] = display_brightness; json["darktheme"] = twatchsk::dark_theme_enabled; json["watchname"] = watch_name; } void Gui::theme_changed() { twatchsk::update_imgbtn_color(menuBtn); // make the four little squares be the correct color for the theme bar->theme_changed(); } void Gui::set_temporary_screen_timeout(int value) { if (!screen_timeout_is_temporary) { saved_screen_timeout = screen_timeout; screen_timeout = value; screen_timeout_is_temporary = true; } } void Gui::clear_temporary_screen_timeout() { if (screen_timeout_is_temporary) { screen_timeout = saved_screen_timeout; screen_timeout_is_temporary = false; } } void Gui::lv_mainbar_callback(lv_obj_t *obj, lv_event_t event) { if (event == LV_EVENT_VALUE_CHANGED) { Gui *gui = (Gui *)obj->user_data; lv_coord_t x, y; lv_tileview_get_tile_act(obj, &x, &y); ESP_LOGI(GUI_TAG, "Tile view is showing location %d,%d", x, y); gui->set_is_active_view_dynamic(x > 0); gui->update_arrows_visibility(); } } void Gui::set_is_active_view_dynamic(bool new_value) { if (is_active_view_dynamic_ != new_value) { // ESP_LOGI(GUI_TAG, "Active view is dynamic=%d", new_value); is_active_view_dynamic_ = new_value; if (new_value) { ws_socket->update_subscriptions(); } } } String Gui::current_time() { time_t now; struct tm info; char buf[64]; time(&now); localtime_r(&now, &info); if (time_24hour_format) { strftime(buf, sizeof(buf), "%H:%M", &info); } else { strftime(buf, sizeof(buf), "%I:%M", &info); if (info.tm_hour > 12) { strcat(buf, " pm"); } else { strcat(buf, " am"); } } String current_time_string = buf; return current_time_string; } void Gui::msg_box_callback(lv_obj_t *obj, lv_event_t event) { if (event == LV_EVENT_VALUE_CHANGED) { Gui *gui = (Gui *)obj->user_data; if (lv_msgbox_get_active_btn(obj) == 1) // 0 is the OK button, 1 is the Disable Wifi button { gui->wifiManager->off(); } gui->set_display_next_pending_message(true); // now that this message is being closed, it's OK to display the next one gui->display_next_message(true); // true means "delete the first message before displaying the next one" lv_msgbox_start_auto_close(obj, 0); gui->update_pending_messages(); } } void Gui::display_next_message(bool delete_first_message) { if (pending_messages_.size() > 0) { std::list<PendingMsg_t>::iterator it = pending_messages_.begin(); if (delete_first_message) // done only when a message was being displayed and has now been cleared from the screen by the user { ESP_LOGI(GUI_TAG, "Erasing the first message: %s", it->msg_text.c_str()); pending_messages_.erase(it); } if (pending_messages_.size() == 0) // it == pending_messages_.end() didn't work for some reason { ESP_LOGI(GUI_TAG, "Last message has been deleted"); } else // there is at least one message in pending_messages, so display it { it = pending_messages_.begin(); // doesn't work if "it" is not re-set to the first element like this ESP_LOGI(GUI_TAG, "Displaying the first message in pending_messages: %s", it->msg_text.c_str()); msgBox = lv_msgbox_create(lv_scr_act(), NULL); String full_text = it->msg_time + "\n(" + it->msg_count + "x) " + it->msg_text + "\n\n(" + (String)(pending_messages_.size() - 1) + LOC_UNREAD_MSGS + ")"; lv_msgbox_set_text(msgBox, full_text.c_str()); if (it->msg_topic == Wifi_Problem) { static const char *btns[] = {LOC_MESSAGEBOX_OK, LOC_MESSAGEBOX_DISABLE_WIFI, ""}; lv_msgbox_add_btns(msgBox, btns); // Jan: why does this have to be inside the if and the else? If I put it AFTER the else, compiler says btns is undefined. lv_btnmatrix_set_btn_width(lv_msgbox_get_btnmatrix(msgBox), 1, 2); // make "Disable Wifi" button (button 1) twice as wide as "OK" button (button 0) lv_obj_set_style_local_radius(msgBox, LV_MSGBOX_PART_BTN, LV_STATE_DEFAULT, 10); } else { static const char *btns[] = {LOC_MESSAGEBOX_OK, ""}; lv_msgbox_add_btns(msgBox, btns); lv_obj_set_style_local_radius(msgBox, LV_MSGBOX_PART_BTN, LV_STATE_DEFAULT, 10); } lv_obj_set_size(msgBox, 220, 260); lv_obj_align(msgBox, NULL, LV_ALIGN_CENTER, 0, 0); msgBox->user_data = this; lv_obj_set_event_cb(msgBox, msg_box_callback); display_next_pending_message_ = false; // so that only one is displayed at a time // trigger activity on main screen to avoid watch going to sleep right away, to ensure the message can be seen and read lv_disp_trig_activity(NULL); } } else { // hide pending messages icon ESP_LOGI(GUI_TAG, "No more pending messages to display"); } update_pending_messages(); } void Gui::update_pending_messages() { if (pending_messages_.size() > 0) { char buff[10]; sprintf(buff, "%s %d", LV_SYMBOL_BELL, pending_messages_.size()); pendingMessagesIcon_->set_text(buff); pendingMessagesIcon_->set_status(StatusBarIconStatus::Warning); } else { pendingMessagesIcon_->set_status(StatusBarIconStatus::Hidden); } } void Gui::show_settings() { hide_main_bar(true); auto gui = this; NavigationView *setupMenu = NULL; setupMenu = new NavigationView(LOC_SETTINGS_MENU, [setupMenu, gui]() { setupMenu->remove_from_active_list(); // because, for some reason, `delete setupMenu;` doesn't remove it from View::active_views_ delete setupMenu; gui->hide_main_bar(false); if (gui->get_gui_needs_saved()) { gui->save(); } gui->set_gui_needs_saved(false); }); setupMenu->add_tile(LOC_CLOCK_SETTINGS_MENU, &time_48px, false, [gui]() { auto timeSetting = new TimeSettings(TTGOClass::getWatch(), gui->get_sk_socket()); timeSetting->set_24hour_format(gui->get_time_24hour_format()); timeSetting->set_timezone_id(gui->get_timezone_id()); timeSetting->on_close([timeSetting, gui]() { bool need_to_save_gui = false; if (gui->get_time_24hour_format() != timeSetting->get_24hour_format()) { gui->set_time_24hour_format(timeSetting->get_24hour_format()); need_to_save_gui = true; } if (gui->get_timezone_id() != timeSetting->get_timezone_id()) { gui->set_timezone_id(timeSetting->get_timezone_id()); need_to_save_gui = true; } if (need_to_save_gui) { gui->save(); } delete timeSetting; }); timeSetting->show(lv_scr_act()); }); setupMenu->add_tile(LOC_DISPLAY_SETTINGS_MENU, &display_48px, false, [gui, setupMenu]() { auto displaySettings = new DisplaySettings(TTGOClass::getWatch(), gui->get_sk_socket()); // screen_timeout is saved to disk through GUI::screen_timeout. Retrieve it here: displaySettings->set_screen_timeout(gui->get_screen_timeout()); // display_setting is saved to disk through GUI::display_brightness. Retrieve it here: displaySettings->set_display_brightness(gui->get_display_brightness()); // Save the value of dark_theme_enabled before going into Display tile bool current_dark_theme_enabled = twatchsk::dark_theme_enabled; // Define the callback function (on_close()). If the value of any setting // changed while the Display tile was up, save it. displaySettings->on_close([displaySettings, gui, current_dark_theme_enabled, setupMenu]() { bool need_to_save = false; int new_timeout = displaySettings->get_screen_timeout(); if (gui->get_screen_timeout() != new_timeout && new_timeout >= 5) { gui->set_screen_timeout(new_timeout); need_to_save = true; } uint8_t new_brightness = displaySettings->get_display_brightness(); if (gui->get_display_brightness() != new_brightness && new_brightness > 0) { gui->set_display_brightness(new_brightness); need_to_save = true; } if (twatchsk::dark_theme_enabled != current_dark_theme_enabled) // dark_theme flag changed while in Display tile { need_to_save = true; ESP_LOGI(GUI_TAG, "Dark theme changed to %d", twatchsk::dark_theme_enabled); //update themes on GUI objects setupMenu->theme_changed(); gui->theme_changed(); } if (need_to_save) { gui->save(); } delete displaySettings; }); // show() does a few things, then calls show_internal(), which defines // the way this tile looks and acts. displaySettings->show(lv_scr_act()); }); setupMenu->add_tile(LOC_WIFI_SETTINGS_MENU, &wifi_48px, false, [gui]() { auto wifiSettings = new WifiSettings(gui->get_wifi_manager()); wifiSettings->on_close([wifiSettings]() { delete wifiSettings; }); wifiSettings->show(lv_scr_act()); }); setupMenu->add_tile(LOC_SIGNALK_SETTING_MENU, &signalk_48px, true, [gui]() { auto skSettings = new SignalKSettings(gui->get_sk_socket()); skSettings->on_close([skSettings]() { delete skSettings; }); skSettings->show(lv_scr_act()); }); setupMenu->add_tile(LOC_WAKEUP_SETTINGS_MENU, &wakeup_48px, false, [gui]() { auto wakeupSettings = new WakeupSettings(gui, gui->get_hardware()); wakeupSettings->on_close([wakeupSettings]() { delete wakeupSettings; }); wakeupSettings->show(lv_scr_act()); }); setupMenu->add_tile(LOC_WATCH_INFO_MENU, &info_48px, false, [gui]() { auto watchInfo = new WatchInfo(gui); // watch_name is saved to disk through GUI::watch_name. Retrieve it here: watchInfo->set_watch_name(gui->get_watch_name()); // Define the callback function (on_close()). If the watch name // changed while the Watch Info tile was up, save it. watchInfo->on_close([watchInfo, gui]() { char *new_watch_name = watchInfo->get_watch_name(); if (strcmp(new_watch_name, "") != 0 // new_watch_name isn't blank && strcmp(gui->get_watch_name(), new_watch_name) != 0) // and it has changed { gui->set_watch_name(new_watch_name); gui->save(); } delete watchInfo; }); // show() does a few things, then calls show_internal(), which defines // the way this tile looks and acts. watchInfo->show(lv_scr_act()); }); setupMenu->show(lv_scr_act()); } void Gui::show_home() { lv_tileview_set_tile_act(dynamic_gui->get_tile_view(), 0, 0, LV_ANIM_ON); } void Gui::toggle_wifi() { auto wifiStatus = wifiManager->get_status(); if(wifiStatus == WifiState_t::Wifi_Connected) { wifiManager->off(true); } else if(wifiStatus == WifiState_t::Wifi_Off) { wifiManager->on(); } } void Gui::update_arrows_visibility() { lv_coord_t x,y; lv_tileview_get_tile_act(mainBar, &x, &y); update_arrows_visibility(x > 0, x < (tile_valid_points_count-1)); } void Gui::update_arrows_visibility(bool left, bool right) { ESP_LOGI(GUI_TAG, "Arrows update left=%d, right=%d", left, right); lv_obj_set_hidden(arrow_left, !left); lv_obj_set_hidden(arrow_right, !right); arrows_hide_at_time = millis() + ARROWS_DISAPPEAR_TIME; } void Gui::hide_arrows_task_cb(lv_task_t*task) { auto gui = (Gui*)task->user_data; lv_obj_set_hidden(gui->arrow_left, true); lv_obj_set_hidden(gui->arrow_right, true); lv_task_del(task); ESP_LOGI(GUI_TAG, "Arrows are hidden."); }
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_PrimalInventoryBP_WaterWell_classes.hpp" namespace sdk { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function PrimalInventoryBP_WaterWell.PrimalInventoryBP_WaterWell_C.ExecuteUbergraph_PrimalInventoryBP_WaterWell struct UPrimalInventoryBP_WaterWell_C_ExecuteUbergraph_PrimalInventoryBP_WaterWell_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
// Copyright 2012 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "v8.h" #if defined(V8_TARGET_ARCH_X64) #include "x64/lithium-codegen-x64.h" #include "code-stubs.h" #include "stub-cache.h" namespace v8 { namespace internal { // When invoking builtins, we need to record the safepoint in the middle of // the invoke instruction sequence generated by the macro assembler. class SafepointGenerator : public CallWrapper { public: SafepointGenerator(LCodeGen* codegen, LPointerMap* pointers, Safepoint::DeoptMode mode) : codegen_(codegen), pointers_(pointers), deopt_mode_(mode) { } virtual ~SafepointGenerator() { } virtual void BeforeCall(int call_size) const { codegen_->EnsureSpaceForLazyDeopt(Deoptimizer::patch_size() - call_size); } virtual void AfterCall() const { codegen_->RecordSafepoint(pointers_, deopt_mode_); } private: LCodeGen* codegen_; LPointerMap* pointers_; Safepoint::DeoptMode deopt_mode_; }; #define __ masm()-> bool LCodeGen::GenerateCode() { HPhase phase("Z_Code generation", chunk()); ASSERT(is_unused()); status_ = GENERATING; // Open a frame scope to indicate that there is a frame on the stack. The // MANUAL indicates that the scope shouldn't actually generate code to set up // the frame (that is done in GeneratePrologue). FrameScope frame_scope(masm_, StackFrame::MANUAL); return GeneratePrologue() && GenerateBody() && GenerateDeferredCode() && GenerateJumpTable() && GenerateSafepointTable(); } void LCodeGen::FinishCode(Handle<Code> code) { ASSERT(is_done()); code->set_stack_slots(GetStackSlotCount()); code->set_safepoint_table_offset(safepoints_.GetCodeOffset()); PopulateDeoptimizationData(code); } void LCodeGen::Abort(const char* format, ...) { if (FLAG_trace_bailout) { SmartArrayPointer<char> name( info()->shared_info()->DebugName()->ToCString()); PrintF("Aborting LCodeGen in @\"%s\": ", *name); va_list arguments; va_start(arguments, format); OS::VPrint(format, arguments); va_end(arguments); PrintF("\n"); } status_ = ABORTED; } void LCodeGen::Comment(const char* format, ...) { if (!FLAG_code_comments) return; char buffer[4 * KB]; StringBuilder builder(buffer, ARRAY_SIZE(buffer)); va_list arguments; va_start(arguments, format); builder.AddFormattedList(format, arguments); va_end(arguments); // Copy the string before recording it in the assembler to avoid // issues when the stack allocated buffer goes out of scope. int length = builder.position(); Vector<char> copy = Vector<char>::New(length + 1); memcpy(copy.start(), builder.Finalize(), copy.length()); masm()->RecordComment(copy.start()); } bool LCodeGen::GeneratePrologue() { ASSERT(is_generating()); #ifdef DEBUG if (strlen(FLAG_stop_at) > 0 && info_->function()->name()->IsEqualTo(CStrVector(FLAG_stop_at))) { __ int3(); } #endif // Strict mode functions need to replace the receiver with undefined // when called as functions (without an explicit receiver // object). rcx is zero for method calls and non-zero for function // calls. if (!info_->is_classic_mode() || info_->is_native()) { Label ok; __ testq(rcx, rcx); __ j(zero, &ok, Label::kNear); // +1 for return address. int receiver_offset = (scope()->num_parameters() + 1) * kPointerSize; __ LoadRoot(kScratchRegister, Heap::kUndefinedValueRootIndex); __ movq(Operand(rsp, receiver_offset), kScratchRegister); __ bind(&ok); } __ push(rbp); // Caller's frame pointer. __ movq(rbp, rsp); __ push(rsi); // Callee's context. __ push(rdi); // Callee's JS function. // Reserve space for the stack slots needed by the code. int slots = GetStackSlotCount(); if (slots > 0) { if (FLAG_debug_code) { __ Set(rax, slots); __ movq(kScratchRegister, kSlotsZapValue, RelocInfo::NONE); Label loop; __ bind(&loop); __ push(kScratchRegister); __ decl(rax); __ j(not_zero, &loop); } else { __ subq(rsp, Immediate(slots * kPointerSize)); #ifdef _MSC_VER // On windows, you may not access the stack more than one page below // the most recently mapped page. To make the allocated area randomly // accessible, we write to each page in turn (the value is irrelevant). const int kPageSize = 4 * KB; for (int offset = slots * kPointerSize - kPageSize; offset > 0; offset -= kPageSize) { __ movq(Operand(rsp, offset), rax); } #endif } } // Possibly allocate a local context. int heap_slots = scope()->num_heap_slots() - Context::MIN_CONTEXT_SLOTS; if (heap_slots > 0) { Comment(";;; Allocate local context"); // Argument to NewContext is the function, which is still in rdi. __ push(rdi); if (heap_slots <= FastNewContextStub::kMaximumSlots) { FastNewContextStub stub(heap_slots); __ CallStub(&stub); } else { __ CallRuntime(Runtime::kNewFunctionContext, 1); } RecordSafepoint(Safepoint::kNoLazyDeopt); // Context is returned in both rax and rsi. It replaces the context // passed to us. It's saved in the stack and kept live in rsi. __ movq(Operand(rbp, StandardFrameConstants::kContextOffset), rsi); // Copy any necessary parameters into the context. int num_parameters = scope()->num_parameters(); for (int i = 0; i < num_parameters; i++) { Variable* var = scope()->parameter(i); if (var->IsContextSlot()) { int parameter_offset = StandardFrameConstants::kCallerSPOffset + (num_parameters - 1 - i) * kPointerSize; // Load parameter from stack. __ movq(rax, Operand(rbp, parameter_offset)); // Store it in the context. int context_offset = Context::SlotOffset(var->index()); __ movq(Operand(rsi, context_offset), rax); // Update the write barrier. This clobbers rax and rbx. __ RecordWriteContextSlot(rsi, context_offset, rax, rbx, kSaveFPRegs); } } Comment(";;; End allocate local context"); } // Trace the call. if (FLAG_trace) { __ CallRuntime(Runtime::kTraceEnter, 0); } return !is_aborted(); } bool LCodeGen::GenerateBody() { ASSERT(is_generating()); bool emit_instructions = true; for (current_instruction_ = 0; !is_aborted() && current_instruction_ < instructions_->length(); current_instruction_++) { LInstruction* instr = instructions_->at(current_instruction_); if (instr->IsLabel()) { LLabel* label = LLabel::cast(instr); emit_instructions = !label->HasReplacement(); } if (emit_instructions) { Comment(";;; @%d: %s.", current_instruction_, instr->Mnemonic()); instr->CompileToNative(this); } } EnsureSpaceForLazyDeopt(Deoptimizer::patch_size()); return !is_aborted(); } bool LCodeGen::GenerateJumpTable() { for (int i = 0; i < jump_table_.length(); i++) { __ bind(&jump_table_[i].label); __ Jump(jump_table_[i].address, RelocInfo::RUNTIME_ENTRY); } return !is_aborted(); } bool LCodeGen::GenerateDeferredCode() { ASSERT(is_generating()); if (deferred_.length() > 0) { for (int i = 0; !is_aborted() && i < deferred_.length(); i++) { LDeferredCode* code = deferred_[i]; __ bind(code->entry()); Comment(";;; Deferred code @%d: %s.", code->instruction_index(), code->instr()->Mnemonic()); code->Generate(); __ jmp(code->exit()); } } // Deferred code is the last part of the instruction sequence. Mark // the generated code as done unless we bailed out. if (!is_aborted()) status_ = DONE; return !is_aborted(); } bool LCodeGen::GenerateSafepointTable() { ASSERT(is_done()); safepoints_.Emit(masm(), GetStackSlotCount()); return !is_aborted(); } Register LCodeGen::ToRegister(int index) const { return Register::FromAllocationIndex(index); } XMMRegister LCodeGen::ToDoubleRegister(int index) const { return XMMRegister::FromAllocationIndex(index); } Register LCodeGen::ToRegister(LOperand* op) const { ASSERT(op->IsRegister()); return ToRegister(op->index()); } XMMRegister LCodeGen::ToDoubleRegister(LOperand* op) const { ASSERT(op->IsDoubleRegister()); return ToDoubleRegister(op->index()); } bool LCodeGen::IsInteger32Constant(LConstantOperand* op) const { return op->IsConstantOperand() && chunk_->LookupLiteralRepresentation(op).IsInteger32(); } bool LCodeGen::IsTaggedConstant(LConstantOperand* op) const { return op->IsConstantOperand() && chunk_->LookupLiteralRepresentation(op).IsTagged(); } int LCodeGen::ToInteger32(LConstantOperand* op) const { Handle<Object> value = chunk_->LookupLiteral(op); ASSERT(chunk_->LookupLiteralRepresentation(op).IsInteger32()); ASSERT(static_cast<double>(static_cast<int32_t>(value->Number())) == value->Number()); return static_cast<int32_t>(value->Number()); } double LCodeGen::ToDouble(LConstantOperand* op) const { Handle<Object> value = chunk_->LookupLiteral(op); return value->Number(); } Handle<Object> LCodeGen::ToHandle(LConstantOperand* op) const { Handle<Object> literal = chunk_->LookupLiteral(op); ASSERT(chunk_->LookupLiteralRepresentation(op).IsTagged()); return literal; } Operand LCodeGen::ToOperand(LOperand* op) const { // Does not handle registers. In X64 assembler, plain registers are not // representable as an Operand. ASSERT(op->IsStackSlot() || op->IsDoubleStackSlot()); int index = op->index(); if (index >= 0) { // Local or spill slot. Skip the frame pointer, function, and // context in the fixed part of the frame. return Operand(rbp, -(index + 3) * kPointerSize); } else { // Incoming parameter. Skip the return address. return Operand(rbp, -(index - 1) * kPointerSize); } } void LCodeGen::WriteTranslation(LEnvironment* environment, Translation* translation) { if (environment == NULL) return; // The translation includes one command per value in the environment. int translation_size = environment->values()->length(); // The output frame height does not include the parameters. int height = translation_size - environment->parameter_count(); WriteTranslation(environment->outer(), translation); int closure_id = DefineDeoptimizationLiteral(environment->closure()); switch (environment->frame_type()) { case JS_FUNCTION: translation->BeginJSFrame(environment->ast_id(), closure_id, height); break; case JS_CONSTRUCT: translation->BeginConstructStubFrame(closure_id, translation_size); break; case ARGUMENTS_ADAPTOR: translation->BeginArgumentsAdaptorFrame(closure_id, translation_size); break; default: UNREACHABLE(); } for (int i = 0; i < translation_size; ++i) { LOperand* value = environment->values()->at(i); // spilled_registers_ and spilled_double_registers_ are either // both NULL or both set. if (environment->spilled_registers() != NULL && value != NULL) { if (value->IsRegister() && environment->spilled_registers()[value->index()] != NULL) { translation->MarkDuplicate(); AddToTranslation(translation, environment->spilled_registers()[value->index()], environment->HasTaggedValueAt(i)); } else if ( value->IsDoubleRegister() && environment->spilled_double_registers()[value->index()] != NULL) { translation->MarkDuplicate(); AddToTranslation( translation, environment->spilled_double_registers()[value->index()], false); } } AddToTranslation(translation, value, environment->HasTaggedValueAt(i)); } } void LCodeGen::AddToTranslation(Translation* translation, LOperand* op, bool is_tagged) { if (op == NULL) { // TODO(twuerthinger): Introduce marker operands to indicate that this value // is not present and must be reconstructed from the deoptimizer. Currently // this is only used for the arguments object. translation->StoreArgumentsObject(); } else if (op->IsStackSlot()) { if (is_tagged) { translation->StoreStackSlot(op->index()); } else { translation->StoreInt32StackSlot(op->index()); } } else if (op->IsDoubleStackSlot()) { translation->StoreDoubleStackSlot(op->index()); } else if (op->IsArgument()) { ASSERT(is_tagged); int src_index = GetStackSlotCount() + op->index(); translation->StoreStackSlot(src_index); } else if (op->IsRegister()) { Register reg = ToRegister(op); if (is_tagged) { translation->StoreRegister(reg); } else { translation->StoreInt32Register(reg); } } else if (op->IsDoubleRegister()) { XMMRegister reg = ToDoubleRegister(op); translation->StoreDoubleRegister(reg); } else if (op->IsConstantOperand()) { Handle<Object> literal = chunk()->LookupLiteral(LConstantOperand::cast(op)); int src_index = DefineDeoptimizationLiteral(literal); translation->StoreLiteral(src_index); } else { UNREACHABLE(); } } void LCodeGen::CallCodeGeneric(Handle<Code> code, RelocInfo::Mode mode, LInstruction* instr, SafepointMode safepoint_mode, int argc) { EnsureSpaceForLazyDeopt(Deoptimizer::patch_size() - masm()->CallSize(code)); ASSERT(instr != NULL); LPointerMap* pointers = instr->pointer_map(); RecordPosition(pointers->position()); __ call(code, mode); RecordSafepointWithLazyDeopt(instr, safepoint_mode, argc); // Signal that we don't inline smi code before these stubs in the // optimizing code generator. if (code->kind() == Code::BINARY_OP_IC || code->kind() == Code::COMPARE_IC) { __ nop(); } } void LCodeGen::CallCode(Handle<Code> code, RelocInfo::Mode mode, LInstruction* instr) { CallCodeGeneric(code, mode, instr, RECORD_SIMPLE_SAFEPOINT, 0); } void LCodeGen::CallRuntime(const Runtime::Function* function, int num_arguments, LInstruction* instr) { ASSERT(instr != NULL); ASSERT(instr->HasPointerMap()); LPointerMap* pointers = instr->pointer_map(); RecordPosition(pointers->position()); __ CallRuntime(function, num_arguments); RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT, 0); } void LCodeGen::CallRuntimeFromDeferred(Runtime::FunctionId id, int argc, LInstruction* instr) { __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); __ CallRuntimeSaveDoubles(id); RecordSafepointWithRegisters( instr->pointer_map(), argc, Safepoint::kNoLazyDeopt); } void LCodeGen::RegisterEnvironmentForDeoptimization(LEnvironment* environment, Safepoint::DeoptMode mode) { if (!environment->HasBeenRegistered()) { // Physical stack frame layout: // -x ............. -4 0 ..................................... y // [incoming arguments] [spill slots] [pushed outgoing arguments] // Layout of the environment: // 0 ..................................................... size-1 // [parameters] [locals] [expression stack including arguments] // Layout of the translation: // 0 ........................................................ size - 1 + 4 // [expression stack including arguments] [locals] [4 words] [parameters] // |>------------ translation_size ------------<| int frame_count = 0; int jsframe_count = 0; for (LEnvironment* e = environment; e != NULL; e = e->outer()) { ++frame_count; if (e->frame_type() == JS_FUNCTION) { ++jsframe_count; } } Translation translation(&translations_, frame_count, jsframe_count); WriteTranslation(environment, &translation); int deoptimization_index = deoptimizations_.length(); int pc_offset = masm()->pc_offset(); environment->Register(deoptimization_index, translation.index(), (mode == Safepoint::kLazyDeopt) ? pc_offset : -1); deoptimizations_.Add(environment); } } void LCodeGen::DeoptimizeIf(Condition cc, LEnvironment* environment) { RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt); ASSERT(environment->HasBeenRegistered()); int id = environment->deoptimization_index(); Address entry = Deoptimizer::GetDeoptimizationEntry(id, Deoptimizer::EAGER); ASSERT(entry != NULL); if (entry == NULL) { Abort("bailout was not prepared"); return; } if (cc == no_condition) { __ Jump(entry, RelocInfo::RUNTIME_ENTRY); } else { // We often have several deopts to the same entry, reuse the last // jump entry if this is the case. if (jump_table_.is_empty() || jump_table_.last().address != entry) { jump_table_.Add(JumpTableEntry(entry)); } __ j(cc, &jump_table_.last().label); } } void LCodeGen::PopulateDeoptimizationData(Handle<Code> code) { int length = deoptimizations_.length(); if (length == 0) return; Handle<DeoptimizationInputData> data = factory()->NewDeoptimizationInputData(length, TENURED); Handle<ByteArray> translations = translations_.CreateByteArray(); data->SetTranslationByteArray(*translations); data->SetInlinedFunctionCount(Smi::FromInt(inlined_function_count_)); Handle<FixedArray> literals = factory()->NewFixedArray(deoptimization_literals_.length(), TENURED); for (int i = 0; i < deoptimization_literals_.length(); i++) { literals->set(i, *deoptimization_literals_[i]); } data->SetLiteralArray(*literals); data->SetOsrAstId(Smi::FromInt(info_->osr_ast_id())); data->SetOsrPcOffset(Smi::FromInt(osr_pc_offset_)); // Populate the deoptimization entries. for (int i = 0; i < length; i++) { LEnvironment* env = deoptimizations_[i]; data->SetAstId(i, Smi::FromInt(env->ast_id())); data->SetTranslationIndex(i, Smi::FromInt(env->translation_index())); data->SetArgumentsStackHeight(i, Smi::FromInt(env->arguments_stack_height())); data->SetPc(i, Smi::FromInt(env->pc_offset())); } code->set_deoptimization_data(*data); } int LCodeGen::DefineDeoptimizationLiteral(Handle<Object> literal) { int result = deoptimization_literals_.length(); for (int i = 0; i < deoptimization_literals_.length(); ++i) { if (deoptimization_literals_[i].is_identical_to(literal)) return i; } deoptimization_literals_.Add(literal); return result; } void LCodeGen::PopulateDeoptimizationLiteralsWithInlinedFunctions() { ASSERT(deoptimization_literals_.length() == 0); const ZoneList<Handle<JSFunction> >* inlined_closures = chunk()->inlined_closures(); for (int i = 0, length = inlined_closures->length(); i < length; i++) { DefineDeoptimizationLiteral(inlined_closures->at(i)); } inlined_function_count_ = deoptimization_literals_.length(); } void LCodeGen::RecordSafepointWithLazyDeopt( LInstruction* instr, SafepointMode safepoint_mode, int argc) { if (safepoint_mode == RECORD_SIMPLE_SAFEPOINT) { RecordSafepoint(instr->pointer_map(), Safepoint::kLazyDeopt); } else { ASSERT(safepoint_mode == RECORD_SAFEPOINT_WITH_REGISTERS); RecordSafepointWithRegisters( instr->pointer_map(), argc, Safepoint::kLazyDeopt); } } void LCodeGen::RecordSafepoint( LPointerMap* pointers, Safepoint::Kind kind, int arguments, Safepoint::DeoptMode deopt_mode) { ASSERT(kind == expected_safepoint_kind_); const ZoneList<LOperand*>* operands = pointers->GetNormalizedOperands(); Safepoint safepoint = safepoints_.DefineSafepoint(masm(), kind, arguments, deopt_mode); for (int i = 0; i < operands->length(); i++) { LOperand* pointer = operands->at(i); if (pointer->IsStackSlot()) { safepoint.DefinePointerSlot(pointer->index()); } else if (pointer->IsRegister() && (kind & Safepoint::kWithRegisters)) { safepoint.DefinePointerRegister(ToRegister(pointer)); } } if (kind & Safepoint::kWithRegisters) { // Register rsi always contains a pointer to the context. safepoint.DefinePointerRegister(rsi); } } void LCodeGen::RecordSafepoint(LPointerMap* pointers, Safepoint::DeoptMode deopt_mode) { RecordSafepoint(pointers, Safepoint::kSimple, 0, deopt_mode); } void LCodeGen::RecordSafepoint(Safepoint::DeoptMode deopt_mode) { LPointerMap empty_pointers(RelocInfo::kNoPosition); RecordSafepoint(&empty_pointers, deopt_mode); } void LCodeGen::RecordSafepointWithRegisters(LPointerMap* pointers, int arguments, Safepoint::DeoptMode deopt_mode) { RecordSafepoint(pointers, Safepoint::kWithRegisters, arguments, deopt_mode); } void LCodeGen::RecordPosition(int position) { if (position == RelocInfo::kNoPosition) return; masm()->positions_recorder()->RecordPosition(position); } void LCodeGen::DoLabel(LLabel* label) { if (label->is_loop_header()) { Comment(";;; B%d - LOOP entry", label->block_id()); } else { Comment(";;; B%d", label->block_id()); } __ bind(label->label()); current_block_ = label->block_id(); DoGap(label); } void LCodeGen::DoParallelMove(LParallelMove* move) { resolver_.Resolve(move); } void LCodeGen::DoGap(LGap* gap) { for (int i = LGap::FIRST_INNER_POSITION; i <= LGap::LAST_INNER_POSITION; i++) { LGap::InnerPosition inner_pos = static_cast<LGap::InnerPosition>(i); LParallelMove* move = gap->GetParallelMove(inner_pos); if (move != NULL) DoParallelMove(move); } } void LCodeGen::DoInstructionGap(LInstructionGap* instr) { DoGap(instr); } void LCodeGen::DoParameter(LParameter* instr) { // Nothing to do. } void LCodeGen::DoCallStub(LCallStub* instr) { ASSERT(ToRegister(instr->result()).is(rax)); switch (instr->hydrogen()->major_key()) { case CodeStub::RegExpConstructResult: { RegExpConstructResultStub stub; CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); break; } case CodeStub::RegExpExec: { RegExpExecStub stub; CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); break; } case CodeStub::SubString: { SubStringStub stub; CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); break; } case CodeStub::NumberToString: { NumberToStringStub stub; CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); break; } case CodeStub::StringAdd: { StringAddStub stub(NO_STRING_ADD_FLAGS); CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); break; } case CodeStub::StringCompare: { StringCompareStub stub; CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); break; } case CodeStub::TranscendentalCache: { TranscendentalCacheStub stub(instr->transcendental_type(), TranscendentalCacheStub::TAGGED); CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); break; } default: UNREACHABLE(); } } void LCodeGen::DoUnknownOSRValue(LUnknownOSRValue* instr) { // Nothing to do. } void LCodeGen::DoModI(LModI* instr) { if (instr->hydrogen()->HasPowerOf2Divisor()) { Register dividend = ToRegister(instr->InputAt(0)); int32_t divisor = HConstant::cast(instr->hydrogen()->right())->Integer32Value(); if (divisor < 0) divisor = -divisor; Label positive_dividend, done; __ testl(dividend, dividend); __ j(not_sign, &positive_dividend, Label::kNear); __ negl(dividend); __ andl(dividend, Immediate(divisor - 1)); __ negl(dividend); if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { __ j(not_zero, &done, Label::kNear); DeoptimizeIf(no_condition, instr->environment()); } else { __ jmp(&done, Label::kNear); } __ bind(&positive_dividend); __ andl(dividend, Immediate(divisor - 1)); __ bind(&done); } else { Label done, remainder_eq_dividend, slow, do_subtraction, both_positive; Register left_reg = ToRegister(instr->InputAt(0)); Register right_reg = ToRegister(instr->InputAt(1)); Register result_reg = ToRegister(instr->result()); ASSERT(left_reg.is(rax)); ASSERT(result_reg.is(rdx)); ASSERT(!right_reg.is(rax)); ASSERT(!right_reg.is(rdx)); // Check for x % 0. if (instr->hydrogen()->CheckFlag(HValue::kCanBeDivByZero)) { __ testl(right_reg, right_reg); DeoptimizeIf(zero, instr->environment()); } __ testl(left_reg, left_reg); __ j(zero, &remainder_eq_dividend, Label::kNear); __ j(sign, &slow, Label::kNear); __ testl(right_reg, right_reg); __ j(not_sign, &both_positive, Label::kNear); // The sign of the divisor doesn't matter. __ neg(right_reg); __ bind(&both_positive); // If the dividend is smaller than the nonnegative // divisor, the dividend is the result. __ cmpl(left_reg, right_reg); __ j(less, &remainder_eq_dividend, Label::kNear); // Check if the divisor is a PowerOfTwo integer. Register scratch = ToRegister(instr->TempAt(0)); __ movl(scratch, right_reg); __ subl(scratch, Immediate(1)); __ testl(scratch, right_reg); __ j(not_zero, &do_subtraction, Label::kNear); __ andl(left_reg, scratch); __ jmp(&remainder_eq_dividend, Label::kNear); __ bind(&do_subtraction); const int kUnfolds = 3; // Try a few subtractions of the dividend. __ movl(scratch, left_reg); for (int i = 0; i < kUnfolds; i++) { // Reduce the dividend by the divisor. __ subl(left_reg, right_reg); // Check if the dividend is less than the divisor. __ cmpl(left_reg, right_reg); __ j(less, &remainder_eq_dividend, Label::kNear); } __ movl(left_reg, scratch); // Slow case, using idiv instruction. __ bind(&slow); // Sign extend eax to edx. // (We are using only the low 32 bits of the values.) __ cdq(); // Check for (0 % -x) that will produce negative zero. if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { Label positive_left; Label done; __ testl(left_reg, left_reg); __ j(not_sign, &positive_left, Label::kNear); __ idivl(right_reg); // Test the remainder for 0, because then the result would be -0. __ testl(result_reg, result_reg); __ j(not_zero, &done, Label::kNear); DeoptimizeIf(no_condition, instr->environment()); __ bind(&positive_left); __ idivl(right_reg); __ bind(&done); } else { __ idivl(right_reg); } __ jmp(&done, Label::kNear); __ bind(&remainder_eq_dividend); __ movl(result_reg, left_reg); __ bind(&done); } } void LCodeGen::DoDivI(LDivI* instr) { LOperand* right = instr->InputAt(1); ASSERT(ToRegister(instr->result()).is(rax)); ASSERT(ToRegister(instr->InputAt(0)).is(rax)); ASSERT(!ToRegister(instr->InputAt(1)).is(rax)); ASSERT(!ToRegister(instr->InputAt(1)).is(rdx)); Register left_reg = rax; // Check for x / 0. Register right_reg = ToRegister(right); if (instr->hydrogen()->CheckFlag(HValue::kCanBeDivByZero)) { __ testl(right_reg, right_reg); DeoptimizeIf(zero, instr->environment()); } // Check for (0 / -x) that will produce negative zero. if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { Label left_not_zero; __ testl(left_reg, left_reg); __ j(not_zero, &left_not_zero, Label::kNear); __ testl(right_reg, right_reg); DeoptimizeIf(sign, instr->environment()); __ bind(&left_not_zero); } // Check for (-kMinInt / -1). if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) { Label left_not_min_int; __ cmpl(left_reg, Immediate(kMinInt)); __ j(not_zero, &left_not_min_int, Label::kNear); __ cmpl(right_reg, Immediate(-1)); DeoptimizeIf(zero, instr->environment()); __ bind(&left_not_min_int); } // Sign extend to rdx. __ cdq(); __ idivl(right_reg); // Deoptimize if remainder is not 0. __ testl(rdx, rdx); DeoptimizeIf(not_zero, instr->environment()); } void LCodeGen::DoMulI(LMulI* instr) { Register left = ToRegister(instr->InputAt(0)); LOperand* right = instr->InputAt(1); if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { __ movl(kScratchRegister, left); } bool can_overflow = instr->hydrogen()->CheckFlag(HValue::kCanOverflow); if (right->IsConstantOperand()) { int right_value = ToInteger32(LConstantOperand::cast(right)); if (right_value == -1) { __ negl(left); } else if (right_value == 0) { __ xorl(left, left); } else if (right_value == 2) { __ addl(left, left); } else if (!can_overflow) { // If the multiplication is known to not overflow, we // can use operations that don't set the overflow flag // correctly. switch (right_value) { case 1: // Do nothing. break; case 3: __ leal(left, Operand(left, left, times_2, 0)); break; case 4: __ shll(left, Immediate(2)); break; case 5: __ leal(left, Operand(left, left, times_4, 0)); break; case 8: __ shll(left, Immediate(3)); break; case 9: __ leal(left, Operand(left, left, times_8, 0)); break; case 16: __ shll(left, Immediate(4)); break; default: __ imull(left, left, Immediate(right_value)); break; } } else { __ imull(left, left, Immediate(right_value)); } } else if (right->IsStackSlot()) { __ imull(left, ToOperand(right)); } else { __ imull(left, ToRegister(right)); } if (can_overflow) { DeoptimizeIf(overflow, instr->environment()); } if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { // Bail out if the result is supposed to be negative zero. Label done; __ testl(left, left); __ j(not_zero, &done, Label::kNear); if (right->IsConstantOperand()) { if (ToInteger32(LConstantOperand::cast(right)) <= 0) { DeoptimizeIf(no_condition, instr->environment()); } } else if (right->IsStackSlot()) { __ orl(kScratchRegister, ToOperand(right)); DeoptimizeIf(sign, instr->environment()); } else { // Test the non-zero operand for negative sign. __ orl(kScratchRegister, ToRegister(right)); DeoptimizeIf(sign, instr->environment()); } __ bind(&done); } } void LCodeGen::DoBitI(LBitI* instr) { LOperand* left = instr->InputAt(0); LOperand* right = instr->InputAt(1); ASSERT(left->Equals(instr->result())); ASSERT(left->IsRegister()); if (right->IsConstantOperand()) { int right_operand = ToInteger32(LConstantOperand::cast(right)); switch (instr->op()) { case Token::BIT_AND: __ andl(ToRegister(left), Immediate(right_operand)); break; case Token::BIT_OR: __ orl(ToRegister(left), Immediate(right_operand)); break; case Token::BIT_XOR: __ xorl(ToRegister(left), Immediate(right_operand)); break; default: UNREACHABLE(); break; } } else if (right->IsStackSlot()) { switch (instr->op()) { case Token::BIT_AND: __ andl(ToRegister(left), ToOperand(right)); break; case Token::BIT_OR: __ orl(ToRegister(left), ToOperand(right)); break; case Token::BIT_XOR: __ xorl(ToRegister(left), ToOperand(right)); break; default: UNREACHABLE(); break; } } else { ASSERT(right->IsRegister()); switch (instr->op()) { case Token::BIT_AND: __ andl(ToRegister(left), ToRegister(right)); break; case Token::BIT_OR: __ orl(ToRegister(left), ToRegister(right)); break; case Token::BIT_XOR: __ xorl(ToRegister(left), ToRegister(right)); break; default: UNREACHABLE(); break; } } } void LCodeGen::DoShiftI(LShiftI* instr) { LOperand* left = instr->InputAt(0); LOperand* right = instr->InputAt(1); ASSERT(left->Equals(instr->result())); ASSERT(left->IsRegister()); if (right->IsRegister()) { ASSERT(ToRegister(right).is(rcx)); switch (instr->op()) { case Token::SAR: __ sarl_cl(ToRegister(left)); break; case Token::SHR: __ shrl_cl(ToRegister(left)); if (instr->can_deopt()) { __ testl(ToRegister(left), ToRegister(left)); DeoptimizeIf(negative, instr->environment()); } break; case Token::SHL: __ shll_cl(ToRegister(left)); break; default: UNREACHABLE(); break; } } else { int value = ToInteger32(LConstantOperand::cast(right)); uint8_t shift_count = static_cast<uint8_t>(value & 0x1F); switch (instr->op()) { case Token::SAR: if (shift_count != 0) { __ sarl(ToRegister(left), Immediate(shift_count)); } break; case Token::SHR: if (shift_count == 0 && instr->can_deopt()) { __ testl(ToRegister(left), ToRegister(left)); DeoptimizeIf(negative, instr->environment()); } else { __ shrl(ToRegister(left), Immediate(shift_count)); } break; case Token::SHL: if (shift_count != 0) { __ shll(ToRegister(left), Immediate(shift_count)); } break; default: UNREACHABLE(); break; } } } void LCodeGen::DoSubI(LSubI* instr) { LOperand* left = instr->InputAt(0); LOperand* right = instr->InputAt(1); ASSERT(left->Equals(instr->result())); if (right->IsConstantOperand()) { __ subl(ToRegister(left), Immediate(ToInteger32(LConstantOperand::cast(right)))); } else if (right->IsRegister()) { __ subl(ToRegister(left), ToRegister(right)); } else { __ subl(ToRegister(left), ToOperand(right)); } if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) { DeoptimizeIf(overflow, instr->environment()); } } void LCodeGen::DoConstantI(LConstantI* instr) { ASSERT(instr->result()->IsRegister()); __ Set(ToRegister(instr->result()), instr->value()); } void LCodeGen::DoConstantD(LConstantD* instr) { ASSERT(instr->result()->IsDoubleRegister()); XMMRegister res = ToDoubleRegister(instr->result()); double v = instr->value(); uint64_t int_val = BitCast<uint64_t, double>(v); // Use xor to produce +0.0 in a fast and compact way, but avoid to // do so if the constant is -0.0. if (int_val == 0) { __ xorps(res, res); } else { Register tmp = ToRegister(instr->TempAt(0)); __ Set(tmp, int_val); __ movq(res, tmp); } } void LCodeGen::DoConstantT(LConstantT* instr) { Handle<Object> value = instr->value(); if (value->IsSmi()) { __ Move(ToRegister(instr->result()), value); } else { __ LoadHeapObject(ToRegister(instr->result()), Handle<HeapObject>::cast(value)); } } void LCodeGen::DoJSArrayLength(LJSArrayLength* instr) { Register result = ToRegister(instr->result()); Register array = ToRegister(instr->InputAt(0)); __ movq(result, FieldOperand(array, JSArray::kLengthOffset)); } void LCodeGen::DoFixedArrayBaseLength(LFixedArrayBaseLength* instr) { Register result = ToRegister(instr->result()); Register array = ToRegister(instr->InputAt(0)); __ movq(result, FieldOperand(array, FixedArrayBase::kLengthOffset)); } void LCodeGen::DoElementsKind(LElementsKind* instr) { Register result = ToRegister(instr->result()); Register input = ToRegister(instr->InputAt(0)); // Load map into |result|. __ movq(result, FieldOperand(input, HeapObject::kMapOffset)); // Load the map's "bit field 2" into |result|. We only need the first byte. __ movzxbq(result, FieldOperand(result, Map::kBitField2Offset)); // Retrieve elements_kind from bit field 2. __ and_(result, Immediate(Map::kElementsKindMask)); __ shr(result, Immediate(Map::kElementsKindShift)); } void LCodeGen::DoValueOf(LValueOf* instr) { Register input = ToRegister(instr->InputAt(0)); Register result = ToRegister(instr->result()); ASSERT(input.is(result)); Label done; // If the object is a smi return the object. __ JumpIfSmi(input, &done, Label::kNear); // If the object is not a value type, return the object. __ CmpObjectType(input, JS_VALUE_TYPE, kScratchRegister); __ j(not_equal, &done, Label::kNear); __ movq(result, FieldOperand(input, JSValue::kValueOffset)); __ bind(&done); } void LCodeGen::DoDateField(LDateField* instr) { Register object = ToRegister(instr->InputAt(0)); Register result = ToRegister(instr->result()); Smi* index = instr->index(); Label runtime, done; ASSERT(object.is(result)); ASSERT(object.is(rax)); #ifdef DEBUG __ AbortIfSmi(object); __ CmpObjectType(object, JS_DATE_TYPE, kScratchRegister); __ Assert(equal, "Trying to get date field from non-date."); #endif if (index->value() == 0) { __ movq(result, FieldOperand(object, JSDate::kValueOffset)); } else { if (index->value() < JSDate::kFirstUncachedField) { ExternalReference stamp = ExternalReference::date_cache_stamp(isolate()); __ movq(kScratchRegister, stamp); __ cmpq(kScratchRegister, FieldOperand(object, JSDate::kCacheStampOffset)); __ j(not_equal, &runtime, Label::kNear); __ movq(result, FieldOperand(object, JSDate::kValueOffset + kPointerSize * index->value())); __ jmp(&done); } __ bind(&runtime); __ PrepareCallCFunction(2); #ifdef _WIN64 __ movq(rcx, object); __ movq(rdx, index, RelocInfo::NONE); #else __ movq(rdi, object); __ movq(rsi, index, RelocInfo::NONE); #endif __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2); __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); __ bind(&done); } } void LCodeGen::DoBitNotI(LBitNotI* instr) { LOperand* input = instr->InputAt(0); ASSERT(input->Equals(instr->result())); __ not_(ToRegister(input)); } void LCodeGen::DoThrow(LThrow* instr) { __ push(ToRegister(instr->InputAt(0))); CallRuntime(Runtime::kThrow, 1, instr); if (FLAG_debug_code) { Comment("Unreachable code."); __ int3(); } } void LCodeGen::DoAddI(LAddI* instr) { LOperand* left = instr->InputAt(0); LOperand* right = instr->InputAt(1); ASSERT(left->Equals(instr->result())); if (right->IsConstantOperand()) { __ addl(ToRegister(left), Immediate(ToInteger32(LConstantOperand::cast(right)))); } else if (right->IsRegister()) { __ addl(ToRegister(left), ToRegister(right)); } else { __ addl(ToRegister(left), ToOperand(right)); } if (instr->hydrogen()->CheckFlag(HValue::kCanOverflow)) { DeoptimizeIf(overflow, instr->environment()); } } void LCodeGen::DoArithmeticD(LArithmeticD* instr) { XMMRegister left = ToDoubleRegister(instr->InputAt(0)); XMMRegister right = ToDoubleRegister(instr->InputAt(1)); XMMRegister result = ToDoubleRegister(instr->result()); // All operations except MOD are computed in-place. ASSERT(instr->op() == Token::MOD || left.is(result)); switch (instr->op()) { case Token::ADD: __ addsd(left, right); break; case Token::SUB: __ subsd(left, right); break; case Token::MUL: __ mulsd(left, right); break; case Token::DIV: __ divsd(left, right); break; case Token::MOD: __ PrepareCallCFunction(2); __ movaps(xmm0, left); ASSERT(right.is(xmm1)); __ CallCFunction( ExternalReference::double_fp_operation(Token::MOD, isolate()), 2); __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); __ movaps(result, xmm0); break; default: UNREACHABLE(); break; } } void LCodeGen::DoArithmeticT(LArithmeticT* instr) { ASSERT(ToRegister(instr->InputAt(0)).is(rdx)); ASSERT(ToRegister(instr->InputAt(1)).is(rax)); ASSERT(ToRegister(instr->result()).is(rax)); BinaryOpStub stub(instr->op(), NO_OVERWRITE); CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); __ nop(); // Signals no inlined code. } int LCodeGen::GetNextEmittedBlock(int block) { for (int i = block + 1; i < graph()->blocks()->length(); ++i) { LLabel* label = chunk_->GetLabel(i); if (!label->HasReplacement()) return i; } return -1; } void LCodeGen::EmitBranch(int left_block, int right_block, Condition cc) { int next_block = GetNextEmittedBlock(current_block_); right_block = chunk_->LookupDestination(right_block); left_block = chunk_->LookupDestination(left_block); if (right_block == left_block) { EmitGoto(left_block); } else if (left_block == next_block) { __ j(NegateCondition(cc), chunk_->GetAssemblyLabel(right_block)); } else if (right_block == next_block) { __ j(cc, chunk_->GetAssemblyLabel(left_block)); } else { __ j(cc, chunk_->GetAssemblyLabel(left_block)); if (cc != always) { __ jmp(chunk_->GetAssemblyLabel(right_block)); } } } void LCodeGen::DoBranch(LBranch* instr) { int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); Representation r = instr->hydrogen()->value()->representation(); if (r.IsInteger32()) { Register reg = ToRegister(instr->InputAt(0)); __ testl(reg, reg); EmitBranch(true_block, false_block, not_zero); } else if (r.IsDouble()) { XMMRegister reg = ToDoubleRegister(instr->InputAt(0)); __ xorps(xmm0, xmm0); __ ucomisd(reg, xmm0); EmitBranch(true_block, false_block, not_equal); } else { ASSERT(r.IsTagged()); Register reg = ToRegister(instr->InputAt(0)); HType type = instr->hydrogen()->value()->type(); if (type.IsBoolean()) { __ CompareRoot(reg, Heap::kTrueValueRootIndex); EmitBranch(true_block, false_block, equal); } else if (type.IsSmi()) { __ SmiCompare(reg, Smi::FromInt(0)); EmitBranch(true_block, false_block, not_equal); } else { Label* true_label = chunk_->GetAssemblyLabel(true_block); Label* false_label = chunk_->GetAssemblyLabel(false_block); ToBooleanStub::Types expected = instr->hydrogen()->expected_input_types(); // Avoid deopts in the case where we've never executed this path before. if (expected.IsEmpty()) expected = ToBooleanStub::all_types(); if (expected.Contains(ToBooleanStub::UNDEFINED)) { // undefined -> false. __ CompareRoot(reg, Heap::kUndefinedValueRootIndex); __ j(equal, false_label); } if (expected.Contains(ToBooleanStub::BOOLEAN)) { // true -> true. __ CompareRoot(reg, Heap::kTrueValueRootIndex); __ j(equal, true_label); // false -> false. __ CompareRoot(reg, Heap::kFalseValueRootIndex); __ j(equal, false_label); } if (expected.Contains(ToBooleanStub::NULL_TYPE)) { // 'null' -> false. __ CompareRoot(reg, Heap::kNullValueRootIndex); __ j(equal, false_label); } if (expected.Contains(ToBooleanStub::SMI)) { // Smis: 0 -> false, all other -> true. __ Cmp(reg, Smi::FromInt(0)); __ j(equal, false_label); __ JumpIfSmi(reg, true_label); } else if (expected.NeedsMap()) { // If we need a map later and have a Smi -> deopt. __ testb(reg, Immediate(kSmiTagMask)); DeoptimizeIf(zero, instr->environment()); } const Register map = kScratchRegister; if (expected.NeedsMap()) { __ movq(map, FieldOperand(reg, HeapObject::kMapOffset)); if (expected.CanBeUndetectable()) { // Undetectable -> false. __ testb(FieldOperand(map, Map::kBitFieldOffset), Immediate(1 << Map::kIsUndetectable)); __ j(not_zero, false_label); } } if (expected.Contains(ToBooleanStub::SPEC_OBJECT)) { // spec object -> true. __ CmpInstanceType(map, FIRST_SPEC_OBJECT_TYPE); __ j(above_equal, true_label); } if (expected.Contains(ToBooleanStub::STRING)) { // String value -> false iff empty. Label not_string; __ CmpInstanceType(map, FIRST_NONSTRING_TYPE); __ j(above_equal, &not_string, Label::kNear); __ cmpq(FieldOperand(reg, String::kLengthOffset), Immediate(0)); __ j(not_zero, true_label); __ jmp(false_label); __ bind(&not_string); } if (expected.Contains(ToBooleanStub::HEAP_NUMBER)) { // heap number -> false iff +0, -0, or NaN. Label not_heap_number; __ CompareRoot(map, Heap::kHeapNumberMapRootIndex); __ j(not_equal, &not_heap_number, Label::kNear); __ xorps(xmm0, xmm0); __ ucomisd(xmm0, FieldOperand(reg, HeapNumber::kValueOffset)); __ j(zero, false_label); __ jmp(true_label); __ bind(&not_heap_number); } // We've seen something for the first time -> deopt. DeoptimizeIf(no_condition, instr->environment()); } } } void LCodeGen::EmitGoto(int block) { block = chunk_->LookupDestination(block); int next_block = GetNextEmittedBlock(current_block_); if (block != next_block) { __ jmp(chunk_->GetAssemblyLabel(block)); } } void LCodeGen::DoGoto(LGoto* instr) { EmitGoto(instr->block_id()); } inline Condition LCodeGen::TokenToCondition(Token::Value op, bool is_unsigned) { Condition cond = no_condition; switch (op) { case Token::EQ: case Token::EQ_STRICT: cond = equal; break; case Token::LT: cond = is_unsigned ? below : less; break; case Token::GT: cond = is_unsigned ? above : greater; break; case Token::LTE: cond = is_unsigned ? below_equal : less_equal; break; case Token::GTE: cond = is_unsigned ? above_equal : greater_equal; break; case Token::IN: case Token::INSTANCEOF: default: UNREACHABLE(); } return cond; } void LCodeGen::DoCmpIDAndBranch(LCmpIDAndBranch* instr) { LOperand* left = instr->InputAt(0); LOperand* right = instr->InputAt(1); int false_block = chunk_->LookupDestination(instr->false_block_id()); int true_block = chunk_->LookupDestination(instr->true_block_id()); Condition cc = TokenToCondition(instr->op(), instr->is_double()); if (left->IsConstantOperand() && right->IsConstantOperand()) { // We can statically evaluate the comparison. double left_val = ToDouble(LConstantOperand::cast(left)); double right_val = ToDouble(LConstantOperand::cast(right)); int next_block = EvalComparison(instr->op(), left_val, right_val) ? true_block : false_block; EmitGoto(next_block); } else { if (instr->is_double()) { // Don't base result on EFLAGS when a NaN is involved. Instead // jump to the false block. __ ucomisd(ToDoubleRegister(left), ToDoubleRegister(right)); __ j(parity_even, chunk_->GetAssemblyLabel(false_block)); } else { int32_t value; if (right->IsConstantOperand()) { value = ToInteger32(LConstantOperand::cast(right)); __ cmpl(ToRegister(left), Immediate(value)); } else if (left->IsConstantOperand()) { value = ToInteger32(LConstantOperand::cast(left)); if (right->IsRegister()) { __ cmpl(ToRegister(right), Immediate(value)); } else { __ cmpl(ToOperand(right), Immediate(value)); } // We transposed the operands. Reverse the condition. cc = ReverseCondition(cc); } else { if (right->IsRegister()) { __ cmpl(ToRegister(left), ToRegister(right)); } else { __ cmpl(ToRegister(left), ToOperand(right)); } } } EmitBranch(true_block, false_block, cc); } } void LCodeGen::DoCmpObjectEqAndBranch(LCmpObjectEqAndBranch* instr) { Register left = ToRegister(instr->InputAt(0)); Register right = ToRegister(instr->InputAt(1)); int false_block = chunk_->LookupDestination(instr->false_block_id()); int true_block = chunk_->LookupDestination(instr->true_block_id()); __ cmpq(left, right); EmitBranch(true_block, false_block, equal); } void LCodeGen::DoCmpConstantEqAndBranch(LCmpConstantEqAndBranch* instr) { Register left = ToRegister(instr->InputAt(0)); int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); __ cmpq(left, Immediate(instr->hydrogen()->right())); EmitBranch(true_block, false_block, equal); } void LCodeGen::DoIsNilAndBranch(LIsNilAndBranch* instr) { Register reg = ToRegister(instr->InputAt(0)); int false_block = chunk_->LookupDestination(instr->false_block_id()); // If the expression is known to be untagged or a smi, then it's definitely // not null, and it can't be a an undetectable object. if (instr->hydrogen()->representation().IsSpecialization() || instr->hydrogen()->type().IsSmi()) { EmitGoto(false_block); return; } int true_block = chunk_->LookupDestination(instr->true_block_id()); Heap::RootListIndex nil_value = instr->nil() == kNullValue ? Heap::kNullValueRootIndex : Heap::kUndefinedValueRootIndex; __ CompareRoot(reg, nil_value); if (instr->kind() == kStrictEquality) { EmitBranch(true_block, false_block, equal); } else { Heap::RootListIndex other_nil_value = instr->nil() == kNullValue ? Heap::kUndefinedValueRootIndex : Heap::kNullValueRootIndex; Label* true_label = chunk_->GetAssemblyLabel(true_block); Label* false_label = chunk_->GetAssemblyLabel(false_block); __ j(equal, true_label); __ CompareRoot(reg, other_nil_value); __ j(equal, true_label); __ JumpIfSmi(reg, false_label); // Check for undetectable objects by looking in the bit field in // the map. The object has already been smi checked. Register scratch = ToRegister(instr->TempAt(0)); __ movq(scratch, FieldOperand(reg, HeapObject::kMapOffset)); __ testb(FieldOperand(scratch, Map::kBitFieldOffset), Immediate(1 << Map::kIsUndetectable)); EmitBranch(true_block, false_block, not_zero); } } Condition LCodeGen::EmitIsObject(Register input, Label* is_not_object, Label* is_object) { ASSERT(!input.is(kScratchRegister)); __ JumpIfSmi(input, is_not_object); __ CompareRoot(input, Heap::kNullValueRootIndex); __ j(equal, is_object); __ movq(kScratchRegister, FieldOperand(input, HeapObject::kMapOffset)); // Undetectable objects behave like undefined. __ testb(FieldOperand(kScratchRegister, Map::kBitFieldOffset), Immediate(1 << Map::kIsUndetectable)); __ j(not_zero, is_not_object); __ movzxbl(kScratchRegister, FieldOperand(kScratchRegister, Map::kInstanceTypeOffset)); __ cmpb(kScratchRegister, Immediate(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE)); __ j(below, is_not_object); __ cmpb(kScratchRegister, Immediate(LAST_NONCALLABLE_SPEC_OBJECT_TYPE)); return below_equal; } void LCodeGen::DoIsObjectAndBranch(LIsObjectAndBranch* instr) { Register reg = ToRegister(instr->InputAt(0)); int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); Label* true_label = chunk_->GetAssemblyLabel(true_block); Label* false_label = chunk_->GetAssemblyLabel(false_block); Condition true_cond = EmitIsObject(reg, false_label, true_label); EmitBranch(true_block, false_block, true_cond); } Condition LCodeGen::EmitIsString(Register input, Register temp1, Label* is_not_string) { __ JumpIfSmi(input, is_not_string); Condition cond = masm_->IsObjectStringType(input, temp1, temp1); return cond; } void LCodeGen::DoIsStringAndBranch(LIsStringAndBranch* instr) { Register reg = ToRegister(instr->InputAt(0)); Register temp = ToRegister(instr->TempAt(0)); int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); Label* false_label = chunk_->GetAssemblyLabel(false_block); Condition true_cond = EmitIsString(reg, temp, false_label); EmitBranch(true_block, false_block, true_cond); } void LCodeGen::DoIsSmiAndBranch(LIsSmiAndBranch* instr) { int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); Condition is_smi; if (instr->InputAt(0)->IsRegister()) { Register input = ToRegister(instr->InputAt(0)); is_smi = masm()->CheckSmi(input); } else { Operand input = ToOperand(instr->InputAt(0)); is_smi = masm()->CheckSmi(input); } EmitBranch(true_block, false_block, is_smi); } void LCodeGen::DoIsUndetectableAndBranch(LIsUndetectableAndBranch* instr) { Register input = ToRegister(instr->InputAt(0)); Register temp = ToRegister(instr->TempAt(0)); int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); __ JumpIfSmi(input, chunk_->GetAssemblyLabel(false_block)); __ movq(temp, FieldOperand(input, HeapObject::kMapOffset)); __ testb(FieldOperand(temp, Map::kBitFieldOffset), Immediate(1 << Map::kIsUndetectable)); EmitBranch(true_block, false_block, not_zero); } void LCodeGen::DoStringCompareAndBranch(LStringCompareAndBranch* instr) { Token::Value op = instr->op(); int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); Handle<Code> ic = CompareIC::GetUninitialized(op); CallCode(ic, RelocInfo::CODE_TARGET, instr); Condition condition = TokenToCondition(op, false); __ testq(rax, rax); EmitBranch(true_block, false_block, condition); } static InstanceType TestType(HHasInstanceTypeAndBranch* instr) { InstanceType from = instr->from(); InstanceType to = instr->to(); if (from == FIRST_TYPE) return to; ASSERT(from == to || to == LAST_TYPE); return from; } static Condition BranchCondition(HHasInstanceTypeAndBranch* instr) { InstanceType from = instr->from(); InstanceType to = instr->to(); if (from == to) return equal; if (to == LAST_TYPE) return above_equal; if (from == FIRST_TYPE) return below_equal; UNREACHABLE(); return equal; } void LCodeGen::DoHasInstanceTypeAndBranch(LHasInstanceTypeAndBranch* instr) { Register input = ToRegister(instr->InputAt(0)); int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); Label* false_label = chunk_->GetAssemblyLabel(false_block); __ JumpIfSmi(input, false_label); __ CmpObjectType(input, TestType(instr->hydrogen()), kScratchRegister); EmitBranch(true_block, false_block, BranchCondition(instr->hydrogen())); } void LCodeGen::DoGetCachedArrayIndex(LGetCachedArrayIndex* instr) { Register input = ToRegister(instr->InputAt(0)); Register result = ToRegister(instr->result()); if (FLAG_debug_code) { __ AbortIfNotString(input); } __ movl(result, FieldOperand(input, String::kHashFieldOffset)); ASSERT(String::kHashShift >= kSmiTagSize); __ IndexFromHash(result, result); } void LCodeGen::DoHasCachedArrayIndexAndBranch( LHasCachedArrayIndexAndBranch* instr) { Register input = ToRegister(instr->InputAt(0)); int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); __ testl(FieldOperand(input, String::kHashFieldOffset), Immediate(String::kContainsCachedArrayIndexMask)); EmitBranch(true_block, false_block, equal); } // Branches to a label or falls through with the answer in the z flag. // Trashes the temp register. void LCodeGen::EmitClassOfTest(Label* is_true, Label* is_false, Handle<String> class_name, Register input, Register temp, Register temp2) { ASSERT(!input.is(temp)); ASSERT(!input.is(temp2)); ASSERT(!temp.is(temp2)); __ JumpIfSmi(input, is_false); if (class_name->IsEqualTo(CStrVector("Function"))) { // Assuming the following assertions, we can use the same compares to test // for both being a function type and being in the object type range. STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2); STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE == FIRST_SPEC_OBJECT_TYPE + 1); STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE == LAST_SPEC_OBJECT_TYPE - 1); STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE); __ CmpObjectType(input, FIRST_SPEC_OBJECT_TYPE, temp); __ j(below, is_false); __ j(equal, is_true); __ CmpInstanceType(temp, LAST_SPEC_OBJECT_TYPE); __ j(equal, is_true); } else { // Faster code path to avoid two compares: subtract lower bound from the // actual type and do a signed compare with the width of the type range. __ movq(temp, FieldOperand(input, HeapObject::kMapOffset)); __ movzxbl(temp2, FieldOperand(temp, Map::kInstanceTypeOffset)); __ subq(temp2, Immediate(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE)); __ cmpq(temp2, Immediate(LAST_NONCALLABLE_SPEC_OBJECT_TYPE - FIRST_NONCALLABLE_SPEC_OBJECT_TYPE)); __ j(above, is_false); } // Now we are in the FIRST-LAST_NONCALLABLE_SPEC_OBJECT_TYPE range. // Check if the constructor in the map is a function. __ movq(temp, FieldOperand(temp, Map::kConstructorOffset)); // Objects with a non-function constructor have class 'Object'. __ CmpObjectType(temp, JS_FUNCTION_TYPE, kScratchRegister); if (class_name->IsEqualTo(CStrVector("Object"))) { __ j(not_equal, is_true); } else { __ j(not_equal, is_false); } // temp now contains the constructor function. Grab the // instance class name from there. __ movq(temp, FieldOperand(temp, JSFunction::kSharedFunctionInfoOffset)); __ movq(temp, FieldOperand(temp, SharedFunctionInfo::kInstanceClassNameOffset)); // The class name we are testing against is a symbol because it's a literal. // The name in the constructor is a symbol because of the way the context is // booted. This routine isn't expected to work for random API-created // classes and it doesn't have to because you can't access it with natives // syntax. Since both sides are symbols it is sufficient to use an identity // comparison. ASSERT(class_name->IsSymbol()); __ Cmp(temp, class_name); // End with the answer in the z flag. } void LCodeGen::DoClassOfTestAndBranch(LClassOfTestAndBranch* instr) { Register input = ToRegister(instr->InputAt(0)); Register temp = ToRegister(instr->TempAt(0)); Register temp2 = ToRegister(instr->TempAt(1)); Handle<String> class_name = instr->hydrogen()->class_name(); int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); Label* true_label = chunk_->GetAssemblyLabel(true_block); Label* false_label = chunk_->GetAssemblyLabel(false_block); EmitClassOfTest(true_label, false_label, class_name, input, temp, temp2); EmitBranch(true_block, false_block, equal); } void LCodeGen::DoCmpMapAndBranch(LCmpMapAndBranch* instr) { Register reg = ToRegister(instr->InputAt(0)); int true_block = instr->true_block_id(); int false_block = instr->false_block_id(); __ Cmp(FieldOperand(reg, HeapObject::kMapOffset), instr->map()); EmitBranch(true_block, false_block, equal); } void LCodeGen::DoInstanceOf(LInstanceOf* instr) { InstanceofStub stub(InstanceofStub::kNoFlags); __ push(ToRegister(instr->InputAt(0))); __ push(ToRegister(instr->InputAt(1))); CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); Label true_value, done; __ testq(rax, rax); __ j(zero, &true_value, Label::kNear); __ LoadRoot(ToRegister(instr->result()), Heap::kFalseValueRootIndex); __ jmp(&done, Label::kNear); __ bind(&true_value); __ LoadRoot(ToRegister(instr->result()), Heap::kTrueValueRootIndex); __ bind(&done); } void LCodeGen::DoInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr) { class DeferredInstanceOfKnownGlobal: public LDeferredCode { public: DeferredInstanceOfKnownGlobal(LCodeGen* codegen, LInstanceOfKnownGlobal* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredInstanceOfKnownGlobal(instr_, &map_check_); } virtual LInstruction* instr() { return instr_; } Label* map_check() { return &map_check_; } private: LInstanceOfKnownGlobal* instr_; Label map_check_; }; DeferredInstanceOfKnownGlobal* deferred; deferred = new DeferredInstanceOfKnownGlobal(this, instr); Label done, false_result; Register object = ToRegister(instr->InputAt(0)); // A Smi is not an instance of anything. __ JumpIfSmi(object, &false_result); // This is the inlined call site instanceof cache. The two occurences of the // hole value will be patched to the last map/result pair generated by the // instanceof stub. Label cache_miss; // Use a temp register to avoid memory operands with variable lengths. Register map = ToRegister(instr->TempAt(0)); __ movq(map, FieldOperand(object, HeapObject::kMapOffset)); __ bind(deferred->map_check()); // Label for calculating code patching. Handle<JSGlobalPropertyCell> cache_cell = factory()->NewJSGlobalPropertyCell(factory()->the_hole_value()); __ movq(kScratchRegister, cache_cell, RelocInfo::GLOBAL_PROPERTY_CELL); __ cmpq(map, Operand(kScratchRegister, 0)); __ j(not_equal, &cache_miss, Label::kNear); // Patched to load either true or false. __ LoadRoot(ToRegister(instr->result()), Heap::kTheHoleValueRootIndex); #ifdef DEBUG // Check that the code size between patch label and patch sites is invariant. Label end_of_patched_code; __ bind(&end_of_patched_code); ASSERT(true); #endif __ jmp(&done); // The inlined call site cache did not match. Check for null and string // before calling the deferred code. __ bind(&cache_miss); // Null is not an instance of anything. __ CompareRoot(object, Heap::kNullValueRootIndex); __ j(equal, &false_result, Label::kNear); // String values are not instances of anything. __ JumpIfNotString(object, kScratchRegister, deferred->entry()); __ bind(&false_result); __ LoadRoot(ToRegister(instr->result()), Heap::kFalseValueRootIndex); __ bind(deferred->exit()); __ bind(&done); } void LCodeGen::DoDeferredInstanceOfKnownGlobal(LInstanceOfKnownGlobal* instr, Label* map_check) { { PushSafepointRegistersScope scope(this); InstanceofStub::Flags flags = static_cast<InstanceofStub::Flags>( InstanceofStub::kNoFlags | InstanceofStub::kCallSiteInlineCheck); InstanceofStub stub(flags); __ push(ToRegister(instr->InputAt(0))); __ PushHeapObject(instr->function()); static const int kAdditionalDelta = 10; int delta = masm_->SizeOfCodeGeneratedSince(map_check) + kAdditionalDelta; ASSERT(delta >= 0); __ push_imm32(delta); // We are pushing three values on the stack but recording a // safepoint with two arguments because stub is going to // remove the third argument from the stack before jumping // to instanceof builtin on the slow path. CallCodeGeneric(stub.GetCode(), RelocInfo::CODE_TARGET, instr, RECORD_SAFEPOINT_WITH_REGISTERS, 2); ASSERT(delta == masm_->SizeOfCodeGeneratedSince(map_check)); ASSERT(instr->HasDeoptimizationEnvironment()); LEnvironment* env = instr->deoptimization_environment(); safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index()); // Move result to a register that survives the end of the // PushSafepointRegisterScope. __ movq(kScratchRegister, rax); } __ testq(kScratchRegister, kScratchRegister); Label load_false; Label done; __ j(not_zero, &load_false); __ LoadRoot(rax, Heap::kTrueValueRootIndex); __ jmp(&done); __ bind(&load_false); __ LoadRoot(rax, Heap::kFalseValueRootIndex); __ bind(&done); } void LCodeGen::DoCmpT(LCmpT* instr) { Token::Value op = instr->op(); Handle<Code> ic = CompareIC::GetUninitialized(op); CallCode(ic, RelocInfo::CODE_TARGET, instr); Condition condition = TokenToCondition(op, false); Label true_value, done; __ testq(rax, rax); __ j(condition, &true_value, Label::kNear); __ LoadRoot(ToRegister(instr->result()), Heap::kFalseValueRootIndex); __ jmp(&done, Label::kNear); __ bind(&true_value); __ LoadRoot(ToRegister(instr->result()), Heap::kTrueValueRootIndex); __ bind(&done); } void LCodeGen::DoReturn(LReturn* instr) { if (FLAG_trace) { // Preserve the return value on the stack and rely on the runtime // call to return the value in the same register. __ push(rax); __ CallRuntime(Runtime::kTraceExit, 1); } __ movq(rsp, rbp); __ pop(rbp); __ Ret((GetParameterCount() + 1) * kPointerSize, rcx); } void LCodeGen::DoLoadGlobalCell(LLoadGlobalCell* instr) { Register result = ToRegister(instr->result()); __ LoadGlobalCell(result, instr->hydrogen()->cell()); if (instr->hydrogen()->RequiresHoleCheck()) { __ CompareRoot(result, Heap::kTheHoleValueRootIndex); DeoptimizeIf(equal, instr->environment()); } } void LCodeGen::DoLoadGlobalGeneric(LLoadGlobalGeneric* instr) { ASSERT(ToRegister(instr->global_object()).is(rax)); ASSERT(ToRegister(instr->result()).is(rax)); __ Move(rcx, instr->name()); RelocInfo::Mode mode = instr->for_typeof() ? RelocInfo::CODE_TARGET : RelocInfo::CODE_TARGET_CONTEXT; Handle<Code> ic = isolate()->builtins()->LoadIC_Initialize(); CallCode(ic, mode, instr); } void LCodeGen::DoStoreGlobalCell(LStoreGlobalCell* instr) { Register value = ToRegister(instr->value()); Handle<JSGlobalPropertyCell> cell_handle = instr->hydrogen()->cell(); // If the cell we are storing to contains the hole it could have // been deleted from the property dictionary. In that case, we need // to update the property details in the property dictionary to mark // it as no longer deleted. We deoptimize in that case. if (instr->hydrogen()->RequiresHoleCheck()) { // We have a temp because CompareRoot might clobber kScratchRegister. Register cell = ToRegister(instr->TempAt(0)); ASSERT(!value.is(cell)); __ movq(cell, cell_handle, RelocInfo::GLOBAL_PROPERTY_CELL); __ CompareRoot(Operand(cell, 0), Heap::kTheHoleValueRootIndex); DeoptimizeIf(equal, instr->environment()); // Store the value. __ movq(Operand(cell, 0), value); } else { // Store the value. __ movq(kScratchRegister, cell_handle, RelocInfo::GLOBAL_PROPERTY_CELL); __ movq(Operand(kScratchRegister, 0), value); } // Cells are always rescanned, so no write barrier here. } void LCodeGen::DoStoreGlobalGeneric(LStoreGlobalGeneric* instr) { ASSERT(ToRegister(instr->global_object()).is(rdx)); ASSERT(ToRegister(instr->value()).is(rax)); __ Move(rcx, instr->name()); Handle<Code> ic = (instr->strict_mode_flag() == kStrictMode) ? isolate()->builtins()->StoreIC_Initialize_Strict() : isolate()->builtins()->StoreIC_Initialize(); CallCode(ic, RelocInfo::CODE_TARGET_CONTEXT, instr); } void LCodeGen::DoLoadContextSlot(LLoadContextSlot* instr) { Register context = ToRegister(instr->context()); Register result = ToRegister(instr->result()); __ movq(result, ContextOperand(context, instr->slot_index())); if (instr->hydrogen()->RequiresHoleCheck()) { __ CompareRoot(result, Heap::kTheHoleValueRootIndex); if (instr->hydrogen()->DeoptimizesOnHole()) { DeoptimizeIf(equal, instr->environment()); } else { Label is_not_hole; __ j(not_equal, &is_not_hole, Label::kNear); __ LoadRoot(result, Heap::kUndefinedValueRootIndex); __ bind(&is_not_hole); } } } void LCodeGen::DoStoreContextSlot(LStoreContextSlot* instr) { Register context = ToRegister(instr->context()); Register value = ToRegister(instr->value()); Operand target = ContextOperand(context, instr->slot_index()); Label skip_assignment; if (instr->hydrogen()->RequiresHoleCheck()) { __ CompareRoot(target, Heap::kTheHoleValueRootIndex); if (instr->hydrogen()->DeoptimizesOnHole()) { DeoptimizeIf(equal, instr->environment()); } else { __ j(not_equal, &skip_assignment); } } __ movq(target, value); if (instr->hydrogen()->NeedsWriteBarrier()) { HType type = instr->hydrogen()->value()->type(); SmiCheck check_needed = type.IsHeapObject() ? OMIT_SMI_CHECK : INLINE_SMI_CHECK; int offset = Context::SlotOffset(instr->slot_index()); Register scratch = ToRegister(instr->TempAt(0)); __ RecordWriteContextSlot(context, offset, value, scratch, kSaveFPRegs, EMIT_REMEMBERED_SET, check_needed); } __ bind(&skip_assignment); } void LCodeGen::DoLoadNamedField(LLoadNamedField* instr) { Register object = ToRegister(instr->InputAt(0)); Register result = ToRegister(instr->result()); if (instr->hydrogen()->is_in_object()) { __ movq(result, FieldOperand(object, instr->hydrogen()->offset())); } else { __ movq(result, FieldOperand(object, JSObject::kPropertiesOffset)); __ movq(result, FieldOperand(result, instr->hydrogen()->offset())); } } void LCodeGen::EmitLoadFieldOrConstantFunction(Register result, Register object, Handle<Map> type, Handle<String> name) { LookupResult lookup(isolate()); type->LookupInDescriptors(NULL, *name, &lookup); ASSERT(lookup.IsFound() && (lookup.type() == FIELD || lookup.type() == CONSTANT_FUNCTION)); if (lookup.type() == FIELD) { int index = lookup.GetLocalFieldIndexFromMap(*type); int offset = index * kPointerSize; if (index < 0) { // Negative property indices are in-object properties, indexed // from the end of the fixed part of the object. __ movq(result, FieldOperand(object, offset + type->instance_size())); } else { // Non-negative property indices are in the properties array. __ movq(result, FieldOperand(object, JSObject::kPropertiesOffset)); __ movq(result, FieldOperand(result, offset + FixedArray::kHeaderSize)); } } else { Handle<JSFunction> function(lookup.GetConstantFunctionFromMap(*type)); __ LoadHeapObject(result, function); } } void LCodeGen::DoLoadNamedFieldPolymorphic(LLoadNamedFieldPolymorphic* instr) { Register object = ToRegister(instr->object()); Register result = ToRegister(instr->result()); int map_count = instr->hydrogen()->types()->length(); Handle<String> name = instr->hydrogen()->name(); if (map_count == 0) { ASSERT(instr->hydrogen()->need_generic()); __ Move(rcx, instr->hydrogen()->name()); Handle<Code> ic = isolate()->builtins()->LoadIC_Initialize(); CallCode(ic, RelocInfo::CODE_TARGET, instr); } else { Label done; for (int i = 0; i < map_count - 1; ++i) { Handle<Map> map = instr->hydrogen()->types()->at(i); Label next; __ Cmp(FieldOperand(object, HeapObject::kMapOffset), map); __ j(not_equal, &next, Label::kNear); EmitLoadFieldOrConstantFunction(result, object, map, name); __ jmp(&done, Label::kNear); __ bind(&next); } Handle<Map> map = instr->hydrogen()->types()->last(); __ Cmp(FieldOperand(object, HeapObject::kMapOffset), map); if (instr->hydrogen()->need_generic()) { Label generic; __ j(not_equal, &generic, Label::kNear); EmitLoadFieldOrConstantFunction(result, object, map, name); __ jmp(&done, Label::kNear); __ bind(&generic); __ Move(rcx, instr->hydrogen()->name()); Handle<Code> ic = isolate()->builtins()->LoadIC_Initialize(); CallCode(ic, RelocInfo::CODE_TARGET, instr); } else { DeoptimizeIf(not_equal, instr->environment()); EmitLoadFieldOrConstantFunction(result, object, map, name); } __ bind(&done); } } void LCodeGen::DoLoadNamedGeneric(LLoadNamedGeneric* instr) { ASSERT(ToRegister(instr->object()).is(rax)); ASSERT(ToRegister(instr->result()).is(rax)); __ Move(rcx, instr->name()); Handle<Code> ic = isolate()->builtins()->LoadIC_Initialize(); CallCode(ic, RelocInfo::CODE_TARGET, instr); } void LCodeGen::DoLoadFunctionPrototype(LLoadFunctionPrototype* instr) { Register function = ToRegister(instr->function()); Register result = ToRegister(instr->result()); // Check that the function really is a function. __ CmpObjectType(function, JS_FUNCTION_TYPE, result); DeoptimizeIf(not_equal, instr->environment()); // Check whether the function has an instance prototype. Label non_instance; __ testb(FieldOperand(result, Map::kBitFieldOffset), Immediate(1 << Map::kHasNonInstancePrototype)); __ j(not_zero, &non_instance, Label::kNear); // Get the prototype or initial map from the function. __ movq(result, FieldOperand(function, JSFunction::kPrototypeOrInitialMapOffset)); // Check that the function has a prototype or an initial map. __ CompareRoot(result, Heap::kTheHoleValueRootIndex); DeoptimizeIf(equal, instr->environment()); // If the function does not have an initial map, we're done. Label done; __ CmpObjectType(result, MAP_TYPE, kScratchRegister); __ j(not_equal, &done, Label::kNear); // Get the prototype from the initial map. __ movq(result, FieldOperand(result, Map::kPrototypeOffset)); __ jmp(&done, Label::kNear); // Non-instance prototype: Fetch prototype from constructor field // in the function's map. __ bind(&non_instance); __ movq(result, FieldOperand(result, Map::kConstructorOffset)); // All done. __ bind(&done); } void LCodeGen::DoLoadElements(LLoadElements* instr) { Register result = ToRegister(instr->result()); Register input = ToRegister(instr->InputAt(0)); __ movq(result, FieldOperand(input, JSObject::kElementsOffset)); if (FLAG_debug_code) { Label done, ok, fail; __ CompareRoot(FieldOperand(result, HeapObject::kMapOffset), Heap::kFixedArrayMapRootIndex); __ j(equal, &done, Label::kNear); __ CompareRoot(FieldOperand(result, HeapObject::kMapOffset), Heap::kFixedCOWArrayMapRootIndex); __ j(equal, &done, Label::kNear); Register temp((result.is(rax)) ? rbx : rax); __ push(temp); __ movq(temp, FieldOperand(result, HeapObject::kMapOffset)); __ movzxbq(temp, FieldOperand(temp, Map::kBitField2Offset)); __ and_(temp, Immediate(Map::kElementsKindMask)); __ shr(temp, Immediate(Map::kElementsKindShift)); __ cmpl(temp, Immediate(FAST_ELEMENTS)); __ j(equal, &ok, Label::kNear); __ cmpl(temp, Immediate(FIRST_EXTERNAL_ARRAY_ELEMENTS_KIND)); __ j(less, &fail, Label::kNear); __ cmpl(temp, Immediate(LAST_EXTERNAL_ARRAY_ELEMENTS_KIND)); __ j(less_equal, &ok, Label::kNear); __ bind(&fail); __ Abort("Check for fast or external elements failed"); __ bind(&ok); __ pop(temp); __ bind(&done); } } void LCodeGen::DoLoadExternalArrayPointer( LLoadExternalArrayPointer* instr) { Register result = ToRegister(instr->result()); Register input = ToRegister(instr->InputAt(0)); __ movq(result, FieldOperand(input, ExternalPixelArray::kExternalPointerOffset)); } void LCodeGen::DoAccessArgumentsAt(LAccessArgumentsAt* instr) { Register arguments = ToRegister(instr->arguments()); Register length = ToRegister(instr->length()); Register result = ToRegister(instr->result()); if (instr->index()->IsRegister()) { __ subl(length, ToRegister(instr->index())); } else { __ subl(length, ToOperand(instr->index())); } DeoptimizeIf(below_equal, instr->environment()); // There are two words between the frame pointer and the last argument. // Subtracting from length accounts for one of them add one more. __ movq(result, Operand(arguments, length, times_pointer_size, kPointerSize)); } void LCodeGen::DoLoadKeyedFastElement(LLoadKeyedFastElement* instr) { Register result = ToRegister(instr->result()); // Load the result. __ movq(result, BuildFastArrayOperand(instr->elements(), instr->key(), FAST_ELEMENTS, FixedArray::kHeaderSize - kHeapObjectTag)); // Check for the hole value. if (instr->hydrogen()->RequiresHoleCheck()) { __ CompareRoot(result, Heap::kTheHoleValueRootIndex); DeoptimizeIf(equal, instr->environment()); } } void LCodeGen::DoLoadKeyedFastDoubleElement( LLoadKeyedFastDoubleElement* instr) { XMMRegister result(ToDoubleRegister(instr->result())); int offset = FixedDoubleArray::kHeaderSize - kHeapObjectTag + sizeof(kHoleNanLower32); Operand hole_check_operand = BuildFastArrayOperand( instr->elements(), instr->key(), FAST_DOUBLE_ELEMENTS, offset); __ cmpl(hole_check_operand, Immediate(kHoleNanUpper32)); DeoptimizeIf(equal, instr->environment()); Operand double_load_operand = BuildFastArrayOperand( instr->elements(), instr->key(), FAST_DOUBLE_ELEMENTS, FixedDoubleArray::kHeaderSize - kHeapObjectTag); __ movsd(result, double_load_operand); } Operand LCodeGen::BuildFastArrayOperand( LOperand* elements_pointer, LOperand* key, ElementsKind elements_kind, uint32_t offset) { Register elements_pointer_reg = ToRegister(elements_pointer); int shift_size = ElementsKindToShiftSize(elements_kind); if (key->IsConstantOperand()) { int constant_value = ToInteger32(LConstantOperand::cast(key)); if (constant_value & 0xF0000000) { Abort("array index constant value too big"); } return Operand(elements_pointer_reg, constant_value * (1 << shift_size) + offset); } else { ScaleFactor scale_factor = static_cast<ScaleFactor>(shift_size); return Operand(elements_pointer_reg, ToRegister(key), scale_factor, offset); } } void LCodeGen::DoLoadKeyedSpecializedArrayElement( LLoadKeyedSpecializedArrayElement* instr) { ElementsKind elements_kind = instr->elements_kind(); Operand operand(BuildFastArrayOperand(instr->external_pointer(), instr->key(), elements_kind, 0)); if (elements_kind == EXTERNAL_FLOAT_ELEMENTS) { XMMRegister result(ToDoubleRegister(instr->result())); __ movss(result, operand); __ cvtss2sd(result, result); } else if (elements_kind == EXTERNAL_DOUBLE_ELEMENTS) { __ movsd(ToDoubleRegister(instr->result()), operand); } else { Register result(ToRegister(instr->result())); switch (elements_kind) { case EXTERNAL_BYTE_ELEMENTS: __ movsxbq(result, operand); break; case EXTERNAL_UNSIGNED_BYTE_ELEMENTS: case EXTERNAL_PIXEL_ELEMENTS: __ movzxbq(result, operand); break; case EXTERNAL_SHORT_ELEMENTS: __ movsxwq(result, operand); break; case EXTERNAL_UNSIGNED_SHORT_ELEMENTS: __ movzxwq(result, operand); break; case EXTERNAL_INT_ELEMENTS: __ movsxlq(result, operand); break; case EXTERNAL_UNSIGNED_INT_ELEMENTS: __ movl(result, operand); __ testl(result, result); // TODO(danno): we could be more clever here, perhaps having a special // version of the stub that detects if the overflow case actually // happens, and generate code that returns a double rather than int. DeoptimizeIf(negative, instr->environment()); break; case EXTERNAL_FLOAT_ELEMENTS: case EXTERNAL_DOUBLE_ELEMENTS: case FAST_ELEMENTS: case FAST_SMI_ONLY_ELEMENTS: case FAST_DOUBLE_ELEMENTS: case DICTIONARY_ELEMENTS: case NON_STRICT_ARGUMENTS_ELEMENTS: UNREACHABLE(); break; } } } void LCodeGen::DoLoadKeyedGeneric(LLoadKeyedGeneric* instr) { ASSERT(ToRegister(instr->object()).is(rdx)); ASSERT(ToRegister(instr->key()).is(rax)); Handle<Code> ic = isolate()->builtins()->KeyedLoadIC_Initialize(); CallCode(ic, RelocInfo::CODE_TARGET, instr); } void LCodeGen::DoArgumentsElements(LArgumentsElements* instr) { Register result = ToRegister(instr->result()); // Check for arguments adapter frame. Label done, adapted; __ movq(result, Operand(rbp, StandardFrameConstants::kCallerFPOffset)); __ Cmp(Operand(result, StandardFrameConstants::kContextOffset), Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)); __ j(equal, &adapted, Label::kNear); // No arguments adaptor frame. __ movq(result, rbp); __ jmp(&done, Label::kNear); // Arguments adaptor frame present. __ bind(&adapted); __ movq(result, Operand(rbp, StandardFrameConstants::kCallerFPOffset)); // Result is the frame pointer for the frame if not adapted and for the real // frame below the adaptor frame if adapted. __ bind(&done); } void LCodeGen::DoArgumentsLength(LArgumentsLength* instr) { Register result = ToRegister(instr->result()); Label done; // If no arguments adaptor frame the number of arguments is fixed. if (instr->InputAt(0)->IsRegister()) { __ cmpq(rbp, ToRegister(instr->InputAt(0))); } else { __ cmpq(rbp, ToOperand(instr->InputAt(0))); } __ movl(result, Immediate(scope()->num_parameters())); __ j(equal, &done, Label::kNear); // Arguments adaptor frame present. Get argument length from there. __ movq(result, Operand(rbp, StandardFrameConstants::kCallerFPOffset)); __ SmiToInteger32(result, Operand(result, ArgumentsAdaptorFrameConstants::kLengthOffset)); // Argument length is in result register. __ bind(&done); } void LCodeGen::DoApplyArguments(LApplyArguments* instr) { Register receiver = ToRegister(instr->receiver()); Register function = ToRegister(instr->function()); Register length = ToRegister(instr->length()); Register elements = ToRegister(instr->elements()); ASSERT(receiver.is(rax)); // Used for parameter count. ASSERT(function.is(rdi)); // Required by InvokeFunction. ASSERT(ToRegister(instr->result()).is(rax)); // If the receiver is null or undefined, we have to pass the global // object as a receiver to normal functions. Values have to be // passed unchanged to builtins and strict-mode functions. Label global_object, receiver_ok; // Do not transform the receiver to object for strict mode // functions. __ movq(kScratchRegister, FieldOperand(function, JSFunction::kSharedFunctionInfoOffset)); __ testb(FieldOperand(kScratchRegister, SharedFunctionInfo::kStrictModeByteOffset), Immediate(1 << SharedFunctionInfo::kStrictModeBitWithinByte)); __ j(not_equal, &receiver_ok, Label::kNear); // Do not transform the receiver to object for builtins. __ testb(FieldOperand(kScratchRegister, SharedFunctionInfo::kNativeByteOffset), Immediate(1 << SharedFunctionInfo::kNativeBitWithinByte)); __ j(not_equal, &receiver_ok, Label::kNear); // Normal function. Replace undefined or null with global receiver. __ CompareRoot(receiver, Heap::kNullValueRootIndex); __ j(equal, &global_object, Label::kNear); __ CompareRoot(receiver, Heap::kUndefinedValueRootIndex); __ j(equal, &global_object, Label::kNear); // The receiver should be a JS object. Condition is_smi = __ CheckSmi(receiver); DeoptimizeIf(is_smi, instr->environment()); __ CmpObjectType(receiver, FIRST_SPEC_OBJECT_TYPE, kScratchRegister); DeoptimizeIf(below, instr->environment()); __ jmp(&receiver_ok, Label::kNear); __ bind(&global_object); // TODO(kmillikin): We have a hydrogen value for the global object. See // if it's better to use it than to explicitly fetch it from the context // here. __ movq(receiver, ContextOperand(rsi, Context::GLOBAL_INDEX)); __ movq(receiver, FieldOperand(receiver, JSGlobalObject::kGlobalReceiverOffset)); __ bind(&receiver_ok); // Copy the arguments to this function possibly from the // adaptor frame below it. const uint32_t kArgumentsLimit = 1 * KB; __ cmpq(length, Immediate(kArgumentsLimit)); DeoptimizeIf(above, instr->environment()); __ push(receiver); __ movq(receiver, length); // Loop through the arguments pushing them onto the execution // stack. Label invoke, loop; // length is a small non-negative integer, due to the test above. __ testl(length, length); __ j(zero, &invoke, Label::kNear); __ bind(&loop); __ push(Operand(elements, length, times_pointer_size, 1 * kPointerSize)); __ decl(length); __ j(not_zero, &loop); // Invoke the function. __ bind(&invoke); ASSERT(instr->HasPointerMap() && instr->HasDeoptimizationEnvironment()); LPointerMap* pointers = instr->pointer_map(); RecordPosition(pointers->position()); SafepointGenerator safepoint_generator( this, pointers, Safepoint::kLazyDeopt); ParameterCount actual(rax); __ InvokeFunction(function, actual, CALL_FUNCTION, safepoint_generator, CALL_AS_METHOD); __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); } void LCodeGen::DoPushArgument(LPushArgument* instr) { LOperand* argument = instr->InputAt(0); EmitPushTaggedOperand(argument); } void LCodeGen::DoThisFunction(LThisFunction* instr) { Register result = ToRegister(instr->result()); __ LoadHeapObject(result, instr->hydrogen()->closure()); } void LCodeGen::DoContext(LContext* instr) { Register result = ToRegister(instr->result()); __ movq(result, rsi); } void LCodeGen::DoOuterContext(LOuterContext* instr) { Register context = ToRegister(instr->context()); Register result = ToRegister(instr->result()); __ movq(result, Operand(context, Context::SlotOffset(Context::PREVIOUS_INDEX))); } void LCodeGen::DoDeclareGlobals(LDeclareGlobals* instr) { __ push(rsi); // The context is the first argument. __ PushHeapObject(instr->hydrogen()->pairs()); __ Push(Smi::FromInt(instr->hydrogen()->flags())); CallRuntime(Runtime::kDeclareGlobals, 3, instr); } void LCodeGen::DoGlobalObject(LGlobalObject* instr) { Register result = ToRegister(instr->result()); __ movq(result, GlobalObjectOperand()); } void LCodeGen::DoGlobalReceiver(LGlobalReceiver* instr) { Register global = ToRegister(instr->global()); Register result = ToRegister(instr->result()); __ movq(result, FieldOperand(global, GlobalObject::kGlobalReceiverOffset)); } void LCodeGen::CallKnownFunction(Handle<JSFunction> function, int arity, LInstruction* instr, CallKind call_kind) { bool can_invoke_directly = !function->NeedsArgumentsAdaption() || function->shared()->formal_parameter_count() == arity; LPointerMap* pointers = instr->pointer_map(); RecordPosition(pointers->position()); if (can_invoke_directly) { __ LoadHeapObject(rdi, function); // Change context if needed. bool change_context = (info()->closure()->context() != function->context()) || scope()->contains_with() || (scope()->num_heap_slots() > 0); if (change_context) { __ movq(rsi, FieldOperand(rdi, JSFunction::kContextOffset)); } // Set rax to arguments count if adaption is not needed. Assumes that rax // is available to write to at this point. if (!function->NeedsArgumentsAdaption()) { __ Set(rax, arity); } // Invoke function. __ SetCallKind(rcx, call_kind); if (*function == *info()->closure()) { __ CallSelf(); } else { __ call(FieldOperand(rdi, JSFunction::kCodeEntryOffset)); } // Set up deoptimization. RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT, 0); } else { // We need to adapt arguments. SafepointGenerator generator( this, pointers, Safepoint::kLazyDeopt); ParameterCount count(arity); __ InvokeFunction(function, count, CALL_FUNCTION, generator, call_kind); } // Restore context. __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); } void LCodeGen::DoCallConstantFunction(LCallConstantFunction* instr) { ASSERT(ToRegister(instr->result()).is(rax)); CallKnownFunction(instr->function(), instr->arity(), instr, CALL_AS_METHOD); } void LCodeGen::DoDeferredMathAbsTaggedHeapNumber(LUnaryMathOperation* instr) { Register input_reg = ToRegister(instr->InputAt(0)); __ CompareRoot(FieldOperand(input_reg, HeapObject::kMapOffset), Heap::kHeapNumberMapRootIndex); DeoptimizeIf(not_equal, instr->environment()); Label done; Register tmp = input_reg.is(rax) ? rcx : rax; Register tmp2 = tmp.is(rcx) ? rdx : input_reg.is(rcx) ? rdx : rcx; // Preserve the value of all registers. PushSafepointRegistersScope scope(this); Label negative; __ movl(tmp, FieldOperand(input_reg, HeapNumber::kExponentOffset)); // Check the sign of the argument. If the argument is positive, just // return it. We do not need to patch the stack since |input| and // |result| are the same register and |input| will be restored // unchanged by popping safepoint registers. __ testl(tmp, Immediate(HeapNumber::kSignMask)); __ j(not_zero, &negative); __ jmp(&done); __ bind(&negative); Label allocated, slow; __ AllocateHeapNumber(tmp, tmp2, &slow); __ jmp(&allocated); // Slow case: Call the runtime system to do the number allocation. __ bind(&slow); CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0, instr); // Set the pointer to the new heap number in tmp. if (!tmp.is(rax)) { __ movq(tmp, rax); } // Restore input_reg after call to runtime. __ LoadFromSafepointRegisterSlot(input_reg, input_reg); __ bind(&allocated); __ movq(tmp2, FieldOperand(input_reg, HeapNumber::kValueOffset)); __ shl(tmp2, Immediate(1)); __ shr(tmp2, Immediate(1)); __ movq(FieldOperand(tmp, HeapNumber::kValueOffset), tmp2); __ StoreToSafepointRegisterSlot(input_reg, tmp); __ bind(&done); } void LCodeGen::EmitIntegerMathAbs(LUnaryMathOperation* instr) { Register input_reg = ToRegister(instr->InputAt(0)); __ testl(input_reg, input_reg); Label is_positive; __ j(not_sign, &is_positive); __ negl(input_reg); // Sets flags. DeoptimizeIf(negative, instr->environment()); __ bind(&is_positive); } void LCodeGen::DoMathAbs(LUnaryMathOperation* instr) { // Class for deferred case. class DeferredMathAbsTaggedHeapNumber: public LDeferredCode { public: DeferredMathAbsTaggedHeapNumber(LCodeGen* codegen, LUnaryMathOperation* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredMathAbsTaggedHeapNumber(instr_); } virtual LInstruction* instr() { return instr_; } private: LUnaryMathOperation* instr_; }; ASSERT(instr->InputAt(0)->Equals(instr->result())); Representation r = instr->hydrogen()->value()->representation(); if (r.IsDouble()) { XMMRegister scratch = xmm0; XMMRegister input_reg = ToDoubleRegister(instr->InputAt(0)); __ xorps(scratch, scratch); __ subsd(scratch, input_reg); __ andpd(input_reg, scratch); } else if (r.IsInteger32()) { EmitIntegerMathAbs(instr); } else { // Tagged case. DeferredMathAbsTaggedHeapNumber* deferred = new DeferredMathAbsTaggedHeapNumber(this, instr); Register input_reg = ToRegister(instr->InputAt(0)); // Smi check. __ JumpIfNotSmi(input_reg, deferred->entry()); __ SmiToInteger32(input_reg, input_reg); EmitIntegerMathAbs(instr); __ Integer32ToSmi(input_reg, input_reg); __ bind(deferred->exit()); } } void LCodeGen::DoMathFloor(LUnaryMathOperation* instr) { XMMRegister xmm_scratch = xmm0; Register output_reg = ToRegister(instr->result()); XMMRegister input_reg = ToDoubleRegister(instr->InputAt(0)); Label done; if (CpuFeatures::IsSupported(SSE4_1)) { CpuFeatures::Scope scope(SSE4_1); if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { // Deoptimize if minus zero. __ movq(output_reg, input_reg); __ subq(output_reg, Immediate(1)); DeoptimizeIf(overflow, instr->environment()); } __ roundsd(xmm_scratch, input_reg, Assembler::kRoundDown); __ cvttsd2si(output_reg, xmm_scratch); __ cmpl(output_reg, Immediate(0x80000000)); DeoptimizeIf(equal, instr->environment()); } else { // Deoptimize on negative inputs. __ xorps(xmm_scratch, xmm_scratch); // Zero the register. __ ucomisd(input_reg, xmm_scratch); DeoptimizeIf(below, instr->environment()); if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { // Check for negative zero. Label positive_sign; __ j(above, &positive_sign, Label::kNear); __ movmskpd(output_reg, input_reg); __ testq(output_reg, Immediate(1)); DeoptimizeIf(not_zero, instr->environment()); __ Set(output_reg, 0); __ jmp(&done); __ bind(&positive_sign); } // Use truncating instruction (OK because input is positive). __ cvttsd2si(output_reg, input_reg); // Overflow is signalled with minint. __ cmpl(output_reg, Immediate(0x80000000)); DeoptimizeIf(equal, instr->environment()); } __ bind(&done); } void LCodeGen::DoMathRound(LUnaryMathOperation* instr) { const XMMRegister xmm_scratch = xmm0; Register output_reg = ToRegister(instr->result()); XMMRegister input_reg = ToDoubleRegister(instr->InputAt(0)); Label done; // xmm_scratch = 0.5 __ movq(kScratchRegister, V8_INT64_C(0x3FE0000000000000), RelocInfo::NONE); __ movq(xmm_scratch, kScratchRegister); Label below_half; __ ucomisd(xmm_scratch, input_reg); // If input_reg is NaN, this doesn't jump. __ j(above, &below_half, Label::kNear); // input = input + 0.5 // This addition might give a result that isn't the correct for // rounding, due to loss of precision, but only for a number that's // so big that the conversion below will overflow anyway. __ addsd(xmm_scratch, input_reg); // Compute Math.floor(input). // Use truncating instruction (OK because input is positive). __ cvttsd2si(output_reg, xmm_scratch); // Overflow is signalled with minint. __ cmpl(output_reg, Immediate(0x80000000)); DeoptimizeIf(equal, instr->environment()); __ jmp(&done); __ bind(&below_half); if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { // Bailout if negative (including -0). __ movq(output_reg, input_reg); __ testq(output_reg, output_reg); DeoptimizeIf(negative, instr->environment()); } else { // Bailout if below -0.5, otherwise round to (positive) zero, even // if negative. // xmm_scrach = -0.5 __ movq(kScratchRegister, V8_INT64_C(0xBFE0000000000000), RelocInfo::NONE); __ movq(xmm_scratch, kScratchRegister); __ ucomisd(input_reg, xmm_scratch); DeoptimizeIf(below, instr->environment()); } __ xorl(output_reg, output_reg); __ bind(&done); } void LCodeGen::DoMathSqrt(LUnaryMathOperation* instr) { XMMRegister input_reg = ToDoubleRegister(instr->InputAt(0)); ASSERT(ToDoubleRegister(instr->result()).is(input_reg)); __ sqrtsd(input_reg, input_reg); } void LCodeGen::DoMathPowHalf(LUnaryMathOperation* instr) { XMMRegister xmm_scratch = xmm0; XMMRegister input_reg = ToDoubleRegister(instr->InputAt(0)); ASSERT(ToDoubleRegister(instr->result()).is(input_reg)); // Note that according to ECMA-262 15.8.2.13: // Math.pow(-Infinity, 0.5) == Infinity // Math.sqrt(-Infinity) == NaN Label done, sqrt; // Check base for -Infinity. According to IEEE-754, double-precision // -Infinity has the highest 12 bits set and the lowest 52 bits cleared. __ movq(kScratchRegister, V8_INT64_C(0xFFF0000000000000), RelocInfo::NONE); __ movq(xmm_scratch, kScratchRegister); __ ucomisd(xmm_scratch, input_reg); // Comparing -Infinity with NaN results in "unordered", which sets the // zero flag as if both were equal. However, it also sets the carry flag. __ j(not_equal, &sqrt, Label::kNear); __ j(carry, &sqrt, Label::kNear); // If input is -Infinity, return Infinity. __ xorps(input_reg, input_reg); __ subsd(input_reg, xmm_scratch); __ jmp(&done, Label::kNear); // Square root. __ bind(&sqrt); __ xorps(xmm_scratch, xmm_scratch); __ addsd(input_reg, xmm_scratch); // Convert -0 to +0. __ sqrtsd(input_reg, input_reg); __ bind(&done); } void LCodeGen::DoPower(LPower* instr) { Representation exponent_type = instr->hydrogen()->right()->representation(); // Having marked this as a call, we can use any registers. // Just make sure that the input/output registers are the expected ones. // Choose register conforming to calling convention (when bailing out). #ifdef _WIN64 Register exponent = rdx; #else Register exponent = rdi; #endif ASSERT(!instr->InputAt(1)->IsRegister() || ToRegister(instr->InputAt(1)).is(exponent)); ASSERT(!instr->InputAt(1)->IsDoubleRegister() || ToDoubleRegister(instr->InputAt(1)).is(xmm1)); ASSERT(ToDoubleRegister(instr->InputAt(0)).is(xmm2)); ASSERT(ToDoubleRegister(instr->result()).is(xmm3)); if (exponent_type.IsTagged()) { Label no_deopt; __ JumpIfSmi(exponent, &no_deopt); __ CmpObjectType(exponent, HEAP_NUMBER_TYPE, rcx); DeoptimizeIf(not_equal, instr->environment()); __ bind(&no_deopt); MathPowStub stub(MathPowStub::TAGGED); __ CallStub(&stub); } else if (exponent_type.IsInteger32()) { MathPowStub stub(MathPowStub::INTEGER); __ CallStub(&stub); } else { ASSERT(exponent_type.IsDouble()); MathPowStub stub(MathPowStub::DOUBLE); __ CallStub(&stub); } } void LCodeGen::DoRandom(LRandom* instr) { class DeferredDoRandom: public LDeferredCode { public: DeferredDoRandom(LCodeGen* codegen, LRandom* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredRandom(instr_); } virtual LInstruction* instr() { return instr_; } private: LRandom* instr_; }; DeferredDoRandom* deferred = new DeferredDoRandom(this, instr); // Having marked this instruction as a call we can use any // registers. ASSERT(ToDoubleRegister(instr->result()).is(xmm1)); // Choose the right register for the first argument depending on // calling convention. #ifdef _WIN64 ASSERT(ToRegister(instr->InputAt(0)).is(rcx)); Register global_object = rcx; #else ASSERT(ToRegister(instr->InputAt(0)).is(rdi)); Register global_object = rdi; #endif static const int kSeedSize = sizeof(uint32_t); STATIC_ASSERT(kPointerSize == 2 * kSeedSize); __ movq(global_object, FieldOperand(global_object, GlobalObject::kGlobalContextOffset)); static const int kRandomSeedOffset = FixedArray::kHeaderSize + Context::RANDOM_SEED_INDEX * kPointerSize; __ movq(rbx, FieldOperand(global_object, kRandomSeedOffset)); // rbx: FixedArray of the global context's random seeds // Load state[0]. __ movl(rax, FieldOperand(rbx, ByteArray::kHeaderSize)); // If state[0] == 0, call runtime to initialize seeds. __ testl(rax, rax); __ j(zero, deferred->entry()); // Load state[1]. __ movl(rcx, FieldOperand(rbx, ByteArray::kHeaderSize + kSeedSize)); // state[0] = 18273 * (state[0] & 0xFFFF) + (state[0] >> 16) // Only operate on the lower 32 bit of rax. __ movl(rdx, rax); __ andl(rdx, Immediate(0xFFFF)); __ imull(rdx, rdx, Immediate(18273)); __ shrl(rax, Immediate(16)); __ addl(rax, rdx); // Save state[0]. __ movl(FieldOperand(rbx, ByteArray::kHeaderSize), rax); // state[1] = 36969 * (state[1] & 0xFFFF) + (state[1] >> 16) __ movl(rdx, rcx); __ andl(rdx, Immediate(0xFFFF)); __ imull(rdx, rdx, Immediate(36969)); __ shrl(rcx, Immediate(16)); __ addl(rcx, rdx); // Save state[1]. __ movl(FieldOperand(rbx, ByteArray::kHeaderSize + kSeedSize), rcx); // Random bit pattern = (state[0] << 14) + (state[1] & 0x3FFFF) __ shll(rax, Immediate(14)); __ andl(rcx, Immediate(0x3FFFF)); __ addl(rax, rcx); __ bind(deferred->exit()); // Convert 32 random bits in rax to 0.(32 random bits) in a double // by computing: // ( 1.(20 0s)(32 random bits) x 2^20 ) - (1.0 x 2^20)). __ movl(rcx, Immediate(0x49800000)); // 1.0 x 2^20 as single. __ movd(xmm2, rcx); __ movd(xmm1, rax); __ cvtss2sd(xmm2, xmm2); __ xorps(xmm1, xmm2); __ subsd(xmm1, xmm2); } void LCodeGen::DoDeferredRandom(LRandom* instr) { __ PrepareCallCFunction(1); __ CallCFunction(ExternalReference::random_uint32_function(isolate()), 1); __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); // Return value is in rax. } void LCodeGen::DoMathLog(LUnaryMathOperation* instr) { ASSERT(ToDoubleRegister(instr->result()).is(xmm1)); TranscendentalCacheStub stub(TranscendentalCache::LOG, TranscendentalCacheStub::UNTAGGED); CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); } void LCodeGen::DoMathTan(LUnaryMathOperation* instr) { ASSERT(ToDoubleRegister(instr->result()).is(xmm1)); TranscendentalCacheStub stub(TranscendentalCache::TAN, TranscendentalCacheStub::UNTAGGED); CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); } void LCodeGen::DoMathCos(LUnaryMathOperation* instr) { ASSERT(ToDoubleRegister(instr->result()).is(xmm1)); TranscendentalCacheStub stub(TranscendentalCache::COS, TranscendentalCacheStub::UNTAGGED); CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); } void LCodeGen::DoMathSin(LUnaryMathOperation* instr) { ASSERT(ToDoubleRegister(instr->result()).is(xmm1)); TranscendentalCacheStub stub(TranscendentalCache::SIN, TranscendentalCacheStub::UNTAGGED); CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); } void LCodeGen::DoUnaryMathOperation(LUnaryMathOperation* instr) { switch (instr->op()) { case kMathAbs: DoMathAbs(instr); break; case kMathFloor: DoMathFloor(instr); break; case kMathRound: DoMathRound(instr); break; case kMathSqrt: DoMathSqrt(instr); break; case kMathPowHalf: DoMathPowHalf(instr); break; case kMathCos: DoMathCos(instr); break; case kMathSin: DoMathSin(instr); break; case kMathTan: DoMathTan(instr); break; case kMathLog: DoMathLog(instr); break; default: UNREACHABLE(); } } void LCodeGen::DoInvokeFunction(LInvokeFunction* instr) { ASSERT(ToRegister(instr->function()).is(rdi)); ASSERT(instr->HasPointerMap()); ASSERT(instr->HasDeoptimizationEnvironment()); LPointerMap* pointers = instr->pointer_map(); RecordPosition(pointers->position()); SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt); ParameterCount count(instr->arity()); __ InvokeFunction(rdi, count, CALL_FUNCTION, generator, CALL_AS_METHOD); __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); } void LCodeGen::DoCallKeyed(LCallKeyed* instr) { ASSERT(ToRegister(instr->key()).is(rcx)); ASSERT(ToRegister(instr->result()).is(rax)); int arity = instr->arity(); Handle<Code> ic = isolate()->stub_cache()->ComputeKeyedCallInitialize(arity); CallCode(ic, RelocInfo::CODE_TARGET, instr); __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); } void LCodeGen::DoCallNamed(LCallNamed* instr) { ASSERT(ToRegister(instr->result()).is(rax)); int arity = instr->arity(); RelocInfo::Mode mode = RelocInfo::CODE_TARGET; Handle<Code> ic = isolate()->stub_cache()->ComputeCallInitialize(arity, mode); __ Move(rcx, instr->name()); CallCode(ic, mode, instr); __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); } void LCodeGen::DoCallFunction(LCallFunction* instr) { ASSERT(ToRegister(instr->function()).is(rdi)); ASSERT(ToRegister(instr->result()).is(rax)); int arity = instr->arity(); CallFunctionStub stub(arity, NO_CALL_FUNCTION_FLAGS); CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); } void LCodeGen::DoCallGlobal(LCallGlobal* instr) { ASSERT(ToRegister(instr->result()).is(rax)); int arity = instr->arity(); RelocInfo::Mode mode = RelocInfo::CODE_TARGET_CONTEXT; Handle<Code> ic = isolate()->stub_cache()->ComputeCallInitialize(arity, mode); __ Move(rcx, instr->name()); CallCode(ic, mode, instr); __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); } void LCodeGen::DoCallKnownGlobal(LCallKnownGlobal* instr) { ASSERT(ToRegister(instr->result()).is(rax)); CallKnownFunction(instr->target(), instr->arity(), instr, CALL_AS_FUNCTION); } void LCodeGen::DoCallNew(LCallNew* instr) { ASSERT(ToRegister(instr->InputAt(0)).is(rdi)); ASSERT(ToRegister(instr->result()).is(rax)); CallConstructStub stub(NO_CALL_FUNCTION_FLAGS); __ Set(rax, instr->arity()); CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr); } void LCodeGen::DoCallRuntime(LCallRuntime* instr) { CallRuntime(instr->function(), instr->arity(), instr); } void LCodeGen::DoStoreNamedField(LStoreNamedField* instr) { Register object = ToRegister(instr->object()); Register value = ToRegister(instr->value()); int offset = instr->offset(); if (!instr->transition().is_null()) { __ Move(FieldOperand(object, HeapObject::kMapOffset), instr->transition()); } // Do the store. HType type = instr->hydrogen()->value()->type(); SmiCheck check_needed = type.IsHeapObject() ? OMIT_SMI_CHECK : INLINE_SMI_CHECK; if (instr->is_in_object()) { __ movq(FieldOperand(object, offset), value); if (instr->hydrogen()->NeedsWriteBarrier()) { Register temp = ToRegister(instr->TempAt(0)); // Update the write barrier for the object for in-object properties. __ RecordWriteField(object, offset, value, temp, kSaveFPRegs, EMIT_REMEMBERED_SET, check_needed); } } else { Register temp = ToRegister(instr->TempAt(0)); __ movq(temp, FieldOperand(object, JSObject::kPropertiesOffset)); __ movq(FieldOperand(temp, offset), value); if (instr->hydrogen()->NeedsWriteBarrier()) { // Update the write barrier for the properties array. // object is used as a scratch register. __ RecordWriteField(temp, offset, value, object, kSaveFPRegs, EMIT_REMEMBERED_SET, check_needed); } } } void LCodeGen::DoStoreNamedGeneric(LStoreNamedGeneric* instr) { ASSERT(ToRegister(instr->object()).is(rdx)); ASSERT(ToRegister(instr->value()).is(rax)); __ Move(rcx, instr->hydrogen()->name()); Handle<Code> ic = (instr->strict_mode_flag() == kStrictMode) ? isolate()->builtins()->StoreIC_Initialize_Strict() : isolate()->builtins()->StoreIC_Initialize(); CallCode(ic, RelocInfo::CODE_TARGET, instr); } void LCodeGen::DoStoreKeyedSpecializedArrayElement( LStoreKeyedSpecializedArrayElement* instr) { ElementsKind elements_kind = instr->elements_kind(); Operand operand(BuildFastArrayOperand(instr->external_pointer(), instr->key(), elements_kind, 0)); if (elements_kind == EXTERNAL_FLOAT_ELEMENTS) { XMMRegister value(ToDoubleRegister(instr->value())); __ cvtsd2ss(value, value); __ movss(operand, value); } else if (elements_kind == EXTERNAL_DOUBLE_ELEMENTS) { __ movsd(operand, ToDoubleRegister(instr->value())); } else { Register value(ToRegister(instr->value())); switch (elements_kind) { case EXTERNAL_PIXEL_ELEMENTS: case EXTERNAL_BYTE_ELEMENTS: case EXTERNAL_UNSIGNED_BYTE_ELEMENTS: __ movb(operand, value); break; case EXTERNAL_SHORT_ELEMENTS: case EXTERNAL_UNSIGNED_SHORT_ELEMENTS: __ movw(operand, value); break; case EXTERNAL_INT_ELEMENTS: case EXTERNAL_UNSIGNED_INT_ELEMENTS: __ movl(operand, value); break; case EXTERNAL_FLOAT_ELEMENTS: case EXTERNAL_DOUBLE_ELEMENTS: case FAST_ELEMENTS: case FAST_SMI_ONLY_ELEMENTS: case FAST_DOUBLE_ELEMENTS: case DICTIONARY_ELEMENTS: case NON_STRICT_ARGUMENTS_ELEMENTS: UNREACHABLE(); break; } } } void LCodeGen::DoBoundsCheck(LBoundsCheck* instr) { if (instr->length()->IsRegister()) { Register reg = ToRegister(instr->length()); if (FLAG_debug_code) { __ AbortIfNotZeroExtended(reg); } if (instr->index()->IsConstantOperand()) { __ cmpq(reg, Immediate(ToInteger32(LConstantOperand::cast(instr->index())))); } else { Register reg2 = ToRegister(instr->index()); if (FLAG_debug_code) { __ AbortIfNotZeroExtended(reg2); } __ cmpq(reg, reg2); } } else { if (instr->index()->IsConstantOperand()) { __ cmpq(ToOperand(instr->length()), Immediate(ToInteger32(LConstantOperand::cast(instr->index())))); } else { __ cmpq(ToOperand(instr->length()), ToRegister(instr->index())); } } DeoptimizeIf(below_equal, instr->environment()); } void LCodeGen::DoStoreKeyedFastElement(LStoreKeyedFastElement* instr) { Register value = ToRegister(instr->value()); Register elements = ToRegister(instr->object()); Register key = instr->key()->IsRegister() ? ToRegister(instr->key()) : no_reg; // Do the store. if (instr->key()->IsConstantOperand()) { ASSERT(!instr->hydrogen()->NeedsWriteBarrier()); LConstantOperand* const_operand = LConstantOperand::cast(instr->key()); int offset = ToInteger32(const_operand) * kPointerSize + FixedArray::kHeaderSize; __ movq(FieldOperand(elements, offset), value); } else { __ movq(FieldOperand(elements, key, times_pointer_size, FixedArray::kHeaderSize), value); } if (instr->hydrogen()->NeedsWriteBarrier()) { HType type = instr->hydrogen()->value()->type(); SmiCheck check_needed = type.IsHeapObject() ? OMIT_SMI_CHECK : INLINE_SMI_CHECK; // Compute address of modified element and store it into key register. __ lea(key, FieldOperand(elements, key, times_pointer_size, FixedArray::kHeaderSize)); __ RecordWrite(elements, key, value, kSaveFPRegs, EMIT_REMEMBERED_SET, check_needed); } } void LCodeGen::DoStoreKeyedFastDoubleElement( LStoreKeyedFastDoubleElement* instr) { XMMRegister value = ToDoubleRegister(instr->value()); Label have_value; __ ucomisd(value, value); __ j(parity_odd, &have_value); // NaN. __ Set(kScratchRegister, BitCast<uint64_t>( FixedDoubleArray::canonical_not_the_hole_nan_as_double())); __ movq(value, kScratchRegister); __ bind(&have_value); Operand double_store_operand = BuildFastArrayOperand( instr->elements(), instr->key(), FAST_DOUBLE_ELEMENTS, FixedDoubleArray::kHeaderSize - kHeapObjectTag); __ movsd(double_store_operand, value); } void LCodeGen::DoStoreKeyedGeneric(LStoreKeyedGeneric* instr) { ASSERT(ToRegister(instr->object()).is(rdx)); ASSERT(ToRegister(instr->key()).is(rcx)); ASSERT(ToRegister(instr->value()).is(rax)); Handle<Code> ic = (instr->strict_mode_flag() == kStrictMode) ? isolate()->builtins()->KeyedStoreIC_Initialize_Strict() : isolate()->builtins()->KeyedStoreIC_Initialize(); CallCode(ic, RelocInfo::CODE_TARGET, instr); } void LCodeGen::DoTransitionElementsKind(LTransitionElementsKind* instr) { Register object_reg = ToRegister(instr->object()); Register new_map_reg = ToRegister(instr->new_map_reg()); Handle<Map> from_map = instr->original_map(); Handle<Map> to_map = instr->transitioned_map(); ElementsKind from_kind = from_map->elements_kind(); ElementsKind to_kind = to_map->elements_kind(); Label not_applicable; __ Cmp(FieldOperand(object_reg, HeapObject::kMapOffset), from_map); __ j(not_equal, &not_applicable); __ movq(new_map_reg, to_map, RelocInfo::EMBEDDED_OBJECT); if (from_kind == FAST_SMI_ONLY_ELEMENTS && to_kind == FAST_ELEMENTS) { __ movq(FieldOperand(object_reg, HeapObject::kMapOffset), new_map_reg); // Write barrier. ASSERT_NE(instr->temp_reg(), NULL); __ RecordWriteField(object_reg, HeapObject::kMapOffset, new_map_reg, ToRegister(instr->temp_reg()), kDontSaveFPRegs); } else if (from_kind == FAST_SMI_ONLY_ELEMENTS && to_kind == FAST_DOUBLE_ELEMENTS) { Register fixed_object_reg = ToRegister(instr->temp_reg()); ASSERT(fixed_object_reg.is(rdx)); ASSERT(new_map_reg.is(rbx)); __ movq(fixed_object_reg, object_reg); CallCode(isolate()->builtins()->TransitionElementsSmiToDouble(), RelocInfo::CODE_TARGET, instr); } else if (from_kind == FAST_DOUBLE_ELEMENTS && to_kind == FAST_ELEMENTS) { Register fixed_object_reg = ToRegister(instr->temp_reg()); ASSERT(fixed_object_reg.is(rdx)); ASSERT(new_map_reg.is(rbx)); __ movq(fixed_object_reg, object_reg); CallCode(isolate()->builtins()->TransitionElementsDoubleToObject(), RelocInfo::CODE_TARGET, instr); } else { UNREACHABLE(); } __ bind(&not_applicable); } void LCodeGen::DoStringAdd(LStringAdd* instr) { EmitPushTaggedOperand(instr->left()); EmitPushTaggedOperand(instr->right()); StringAddStub stub(NO_STRING_CHECK_IN_STUB); CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); } void LCodeGen::DoStringCharCodeAt(LStringCharCodeAt* instr) { class DeferredStringCharCodeAt: public LDeferredCode { public: DeferredStringCharCodeAt(LCodeGen* codegen, LStringCharCodeAt* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredStringCharCodeAt(instr_); } virtual LInstruction* instr() { return instr_; } private: LStringCharCodeAt* instr_; }; DeferredStringCharCodeAt* deferred = new DeferredStringCharCodeAt(this, instr); StringCharLoadGenerator::Generate(masm(), ToRegister(instr->string()), ToRegister(instr->index()), ToRegister(instr->result()), deferred->entry()); __ bind(deferred->exit()); } void LCodeGen::DoDeferredStringCharCodeAt(LStringCharCodeAt* instr) { Register string = ToRegister(instr->string()); Register result = ToRegister(instr->result()); // TODO(3095996): Get rid of this. For now, we need to make the // result register contain a valid pointer because it is already // contained in the register pointer map. __ Set(result, 0); PushSafepointRegistersScope scope(this); __ push(string); // Push the index as a smi. This is safe because of the checks in // DoStringCharCodeAt above. STATIC_ASSERT(String::kMaxLength <= Smi::kMaxValue); if (instr->index()->IsConstantOperand()) { int const_index = ToInteger32(LConstantOperand::cast(instr->index())); __ Push(Smi::FromInt(const_index)); } else { Register index = ToRegister(instr->index()); __ Integer32ToSmi(index, index); __ push(index); } CallRuntimeFromDeferred(Runtime::kStringCharCodeAt, 2, instr); if (FLAG_debug_code) { __ AbortIfNotSmi(rax); } __ SmiToInteger32(rax, rax); __ StoreToSafepointRegisterSlot(result, rax); } void LCodeGen::DoStringCharFromCode(LStringCharFromCode* instr) { class DeferredStringCharFromCode: public LDeferredCode { public: DeferredStringCharFromCode(LCodeGen* codegen, LStringCharFromCode* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredStringCharFromCode(instr_); } virtual LInstruction* instr() { return instr_; } private: LStringCharFromCode* instr_; }; DeferredStringCharFromCode* deferred = new DeferredStringCharFromCode(this, instr); ASSERT(instr->hydrogen()->value()->representation().IsInteger32()); Register char_code = ToRegister(instr->char_code()); Register result = ToRegister(instr->result()); ASSERT(!char_code.is(result)); __ cmpl(char_code, Immediate(String::kMaxAsciiCharCode)); __ j(above, deferred->entry()); __ LoadRoot(result, Heap::kSingleCharacterStringCacheRootIndex); __ movq(result, FieldOperand(result, char_code, times_pointer_size, FixedArray::kHeaderSize)); __ CompareRoot(result, Heap::kUndefinedValueRootIndex); __ j(equal, deferred->entry()); __ bind(deferred->exit()); } void LCodeGen::DoDeferredStringCharFromCode(LStringCharFromCode* instr) { Register char_code = ToRegister(instr->char_code()); Register result = ToRegister(instr->result()); // TODO(3095996): Get rid of this. For now, we need to make the // result register contain a valid pointer because it is already // contained in the register pointer map. __ Set(result, 0); PushSafepointRegistersScope scope(this); __ Integer32ToSmi(char_code, char_code); __ push(char_code); CallRuntimeFromDeferred(Runtime::kCharFromCode, 1, instr); __ StoreToSafepointRegisterSlot(result, rax); } void LCodeGen::DoStringLength(LStringLength* instr) { Register string = ToRegister(instr->string()); Register result = ToRegister(instr->result()); __ movq(result, FieldOperand(string, String::kLengthOffset)); } void LCodeGen::DoInteger32ToDouble(LInteger32ToDouble* instr) { LOperand* input = instr->InputAt(0); ASSERT(input->IsRegister() || input->IsStackSlot()); LOperand* output = instr->result(); ASSERT(output->IsDoubleRegister()); if (input->IsRegister()) { __ cvtlsi2sd(ToDoubleRegister(output), ToRegister(input)); } else { __ cvtlsi2sd(ToDoubleRegister(output), ToOperand(input)); } } void LCodeGen::DoNumberTagI(LNumberTagI* instr) { LOperand* input = instr->InputAt(0); ASSERT(input->IsRegister() && input->Equals(instr->result())); Register reg = ToRegister(input); __ Integer32ToSmi(reg, reg); } void LCodeGen::DoNumberTagD(LNumberTagD* instr) { class DeferredNumberTagD: public LDeferredCode { public: DeferredNumberTagD(LCodeGen* codegen, LNumberTagD* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredNumberTagD(instr_); } virtual LInstruction* instr() { return instr_; } private: LNumberTagD* instr_; }; XMMRegister input_reg = ToDoubleRegister(instr->InputAt(0)); Register reg = ToRegister(instr->result()); Register tmp = ToRegister(instr->TempAt(0)); DeferredNumberTagD* deferred = new DeferredNumberTagD(this, instr); if (FLAG_inline_new) { __ AllocateHeapNumber(reg, tmp, deferred->entry()); } else { __ jmp(deferred->entry()); } __ bind(deferred->exit()); __ movsd(FieldOperand(reg, HeapNumber::kValueOffset), input_reg); } void LCodeGen::DoDeferredNumberTagD(LNumberTagD* instr) { // TODO(3095996): Get rid of this. For now, we need to make the // result register contain a valid pointer because it is already // contained in the register pointer map. Register reg = ToRegister(instr->result()); __ Move(reg, Smi::FromInt(0)); { PushSafepointRegistersScope scope(this); CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0, instr); // Ensure that value in rax survives popping registers. __ movq(kScratchRegister, rax); } __ movq(reg, kScratchRegister); } void LCodeGen::DoSmiTag(LSmiTag* instr) { ASSERT(instr->InputAt(0)->Equals(instr->result())); Register input = ToRegister(instr->InputAt(0)); ASSERT(!instr->hydrogen_value()->CheckFlag(HValue::kCanOverflow)); __ Integer32ToSmi(input, input); } void LCodeGen::DoSmiUntag(LSmiUntag* instr) { ASSERT(instr->InputAt(0)->Equals(instr->result())); Register input = ToRegister(instr->InputAt(0)); if (instr->needs_check()) { Condition is_smi = __ CheckSmi(input); DeoptimizeIf(NegateCondition(is_smi), instr->environment()); } __ SmiToInteger32(input, input); } void LCodeGen::EmitNumberUntagD(Register input_reg, XMMRegister result_reg, bool deoptimize_on_undefined, bool deoptimize_on_minus_zero, LEnvironment* env) { Label load_smi, done; // Smi check. __ JumpIfSmi(input_reg, &load_smi, Label::kNear); // Heap number map check. __ CompareRoot(FieldOperand(input_reg, HeapObject::kMapOffset), Heap::kHeapNumberMapRootIndex); if (deoptimize_on_undefined) { DeoptimizeIf(not_equal, env); } else { Label heap_number; __ j(equal, &heap_number, Label::kNear); __ CompareRoot(input_reg, Heap::kUndefinedValueRootIndex); DeoptimizeIf(not_equal, env); // Convert undefined to NaN. Compute NaN as 0/0. __ xorps(result_reg, result_reg); __ divsd(result_reg, result_reg); __ jmp(&done, Label::kNear); __ bind(&heap_number); } // Heap number to XMM conversion. __ movsd(result_reg, FieldOperand(input_reg, HeapNumber::kValueOffset)); if (deoptimize_on_minus_zero) { XMMRegister xmm_scratch = xmm0; __ xorps(xmm_scratch, xmm_scratch); __ ucomisd(xmm_scratch, result_reg); __ j(not_equal, &done, Label::kNear); __ movmskpd(kScratchRegister, result_reg); __ testq(kScratchRegister, Immediate(1)); DeoptimizeIf(not_zero, env); } __ jmp(&done, Label::kNear); // Smi to XMM conversion __ bind(&load_smi); __ SmiToInteger32(kScratchRegister, input_reg); __ cvtlsi2sd(result_reg, kScratchRegister); __ bind(&done); } void LCodeGen::DoDeferredTaggedToI(LTaggedToI* instr) { Label done, heap_number; Register input_reg = ToRegister(instr->InputAt(0)); // Heap number map check. __ CompareRoot(FieldOperand(input_reg, HeapObject::kMapOffset), Heap::kHeapNumberMapRootIndex); if (instr->truncating()) { __ j(equal, &heap_number, Label::kNear); // Check for undefined. Undefined is converted to zero for truncating // conversions. __ CompareRoot(input_reg, Heap::kUndefinedValueRootIndex); DeoptimizeIf(not_equal, instr->environment()); __ Set(input_reg, 0); __ jmp(&done, Label::kNear); __ bind(&heap_number); __ movsd(xmm0, FieldOperand(input_reg, HeapNumber::kValueOffset)); __ cvttsd2siq(input_reg, xmm0); __ Set(kScratchRegister, V8_UINT64_C(0x8000000000000000)); __ cmpq(input_reg, kScratchRegister); DeoptimizeIf(equal, instr->environment()); } else { // Deoptimize if we don't have a heap number. DeoptimizeIf(not_equal, instr->environment()); XMMRegister xmm_temp = ToDoubleRegister(instr->TempAt(0)); __ movsd(xmm0, FieldOperand(input_reg, HeapNumber::kValueOffset)); __ cvttsd2si(input_reg, xmm0); __ cvtlsi2sd(xmm_temp, input_reg); __ ucomisd(xmm0, xmm_temp); DeoptimizeIf(not_equal, instr->environment()); DeoptimizeIf(parity_even, instr->environment()); // NaN. if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { __ testl(input_reg, input_reg); __ j(not_zero, &done); __ movmskpd(input_reg, xmm0); __ andl(input_reg, Immediate(1)); DeoptimizeIf(not_zero, instr->environment()); } } __ bind(&done); } void LCodeGen::DoTaggedToI(LTaggedToI* instr) { class DeferredTaggedToI: public LDeferredCode { public: DeferredTaggedToI(LCodeGen* codegen, LTaggedToI* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredTaggedToI(instr_); } virtual LInstruction* instr() { return instr_; } private: LTaggedToI* instr_; }; LOperand* input = instr->InputAt(0); ASSERT(input->IsRegister()); ASSERT(input->Equals(instr->result())); Register input_reg = ToRegister(input); DeferredTaggedToI* deferred = new DeferredTaggedToI(this, instr); __ JumpIfNotSmi(input_reg, deferred->entry()); __ SmiToInteger32(input_reg, input_reg); __ bind(deferred->exit()); } void LCodeGen::DoNumberUntagD(LNumberUntagD* instr) { LOperand* input = instr->InputAt(0); ASSERT(input->IsRegister()); LOperand* result = instr->result(); ASSERT(result->IsDoubleRegister()); Register input_reg = ToRegister(input); XMMRegister result_reg = ToDoubleRegister(result); EmitNumberUntagD(input_reg, result_reg, instr->hydrogen()->deoptimize_on_undefined(), instr->hydrogen()->deoptimize_on_minus_zero(), instr->environment()); } void LCodeGen::DoDoubleToI(LDoubleToI* instr) { LOperand* input = instr->InputAt(0); ASSERT(input->IsDoubleRegister()); LOperand* result = instr->result(); ASSERT(result->IsRegister()); XMMRegister input_reg = ToDoubleRegister(input); Register result_reg = ToRegister(result); if (instr->truncating()) { // Performs a truncating conversion of a floating point number as used by // the JS bitwise operations. __ cvttsd2siq(result_reg, input_reg); __ movq(kScratchRegister, V8_INT64_C(0x8000000000000000), RelocInfo::NONE); __ cmpq(result_reg, kScratchRegister); DeoptimizeIf(equal, instr->environment()); } else { __ cvttsd2si(result_reg, input_reg); __ cvtlsi2sd(xmm0, result_reg); __ ucomisd(xmm0, input_reg); DeoptimizeIf(not_equal, instr->environment()); DeoptimizeIf(parity_even, instr->environment()); // NaN. if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) { Label done; // The integer converted back is equal to the original. We // only have to test if we got -0 as an input. __ testl(result_reg, result_reg); __ j(not_zero, &done, Label::kNear); __ movmskpd(result_reg, input_reg); // Bit 0 contains the sign of the double in input_reg. // If input was positive, we are ok and return 0, otherwise // deoptimize. __ andl(result_reg, Immediate(1)); DeoptimizeIf(not_zero, instr->environment()); __ bind(&done); } } } void LCodeGen::DoCheckSmi(LCheckSmi* instr) { LOperand* input = instr->InputAt(0); Condition cc = masm()->CheckSmi(ToRegister(input)); DeoptimizeIf(NegateCondition(cc), instr->environment()); } void LCodeGen::DoCheckNonSmi(LCheckNonSmi* instr) { LOperand* input = instr->InputAt(0); Condition cc = masm()->CheckSmi(ToRegister(input)); DeoptimizeIf(cc, instr->environment()); } void LCodeGen::DoCheckInstanceType(LCheckInstanceType* instr) { Register input = ToRegister(instr->InputAt(0)); __ movq(kScratchRegister, FieldOperand(input, HeapObject::kMapOffset)); if (instr->hydrogen()->is_interval_check()) { InstanceType first; InstanceType last; instr->hydrogen()->GetCheckInterval(&first, &last); __ cmpb(FieldOperand(kScratchRegister, Map::kInstanceTypeOffset), Immediate(static_cast<int8_t>(first))); // If there is only one type in the interval check for equality. if (first == last) { DeoptimizeIf(not_equal, instr->environment()); } else { DeoptimizeIf(below, instr->environment()); // Omit check for the last type. if (last != LAST_TYPE) { __ cmpb(FieldOperand(kScratchRegister, Map::kInstanceTypeOffset), Immediate(static_cast<int8_t>(last))); DeoptimizeIf(above, instr->environment()); } } } else { uint8_t mask; uint8_t tag; instr->hydrogen()->GetCheckMaskAndTag(&mask, &tag); if (IsPowerOf2(mask)) { ASSERT(tag == 0 || IsPowerOf2(tag)); __ testb(FieldOperand(kScratchRegister, Map::kInstanceTypeOffset), Immediate(mask)); DeoptimizeIf(tag == 0 ? not_zero : zero, instr->environment()); } else { __ movzxbl(kScratchRegister, FieldOperand(kScratchRegister, Map::kInstanceTypeOffset)); __ andb(kScratchRegister, Immediate(mask)); __ cmpb(kScratchRegister, Immediate(tag)); DeoptimizeIf(not_equal, instr->environment()); } } } void LCodeGen::DoCheckFunction(LCheckFunction* instr) { Register reg = ToRegister(instr->value()); Handle<JSFunction> target = instr->hydrogen()->target(); if (isolate()->heap()->InNewSpace(*target)) { Handle<JSGlobalPropertyCell> cell = isolate()->factory()->NewJSGlobalPropertyCell(target); __ movq(kScratchRegister, cell, RelocInfo::GLOBAL_PROPERTY_CELL); __ cmpq(reg, Operand(kScratchRegister, 0)); } else { __ Cmp(reg, target); } DeoptimizeIf(not_equal, instr->environment()); } void LCodeGen::DoCheckMapCommon(Register reg, Handle<Map> map, CompareMapMode mode, LEnvironment* env) { Label success; __ CompareMap(reg, map, &success, mode); DeoptimizeIf(not_equal, env); __ bind(&success); } void LCodeGen::DoCheckMap(LCheckMap* instr) { LOperand* input = instr->InputAt(0); ASSERT(input->IsRegister()); Register reg = ToRegister(input); Handle<Map> map = instr->hydrogen()->map(); DoCheckMapCommon(reg, map, instr->hydrogen()->mode(), instr->environment()); } void LCodeGen::DoClampDToUint8(LClampDToUint8* instr) { XMMRegister value_reg = ToDoubleRegister(instr->unclamped()); Register result_reg = ToRegister(instr->result()); Register temp_reg = ToRegister(instr->TempAt(0)); __ ClampDoubleToUint8(value_reg, xmm0, result_reg, temp_reg); } void LCodeGen::DoClampIToUint8(LClampIToUint8* instr) { ASSERT(instr->unclamped()->Equals(instr->result())); Register value_reg = ToRegister(instr->result()); __ ClampUint8(value_reg); } void LCodeGen::DoClampTToUint8(LClampTToUint8* instr) { ASSERT(instr->unclamped()->Equals(instr->result())); Register input_reg = ToRegister(instr->unclamped()); Register temp_reg = ToRegister(instr->TempAt(0)); XMMRegister temp_xmm_reg = ToDoubleRegister(instr->TempAt(1)); Label is_smi, done, heap_number; __ JumpIfSmi(input_reg, &is_smi); // Check for heap number __ Cmp(FieldOperand(input_reg, HeapObject::kMapOffset), factory()->heap_number_map()); __ j(equal, &heap_number, Label::kNear); // Check for undefined. Undefined is converted to zero for clamping // conversions. __ Cmp(input_reg, factory()->undefined_value()); DeoptimizeIf(not_equal, instr->environment()); __ movq(input_reg, Immediate(0)); __ jmp(&done, Label::kNear); // Heap number __ bind(&heap_number); __ movsd(xmm0, FieldOperand(input_reg, HeapNumber::kValueOffset)); __ ClampDoubleToUint8(xmm0, temp_xmm_reg, input_reg, temp_reg); __ jmp(&done, Label::kNear); // smi __ bind(&is_smi); __ SmiToInteger32(input_reg, input_reg); __ ClampUint8(input_reg); __ bind(&done); } void LCodeGen::DoCheckPrototypeMaps(LCheckPrototypeMaps* instr) { Register reg = ToRegister(instr->TempAt(0)); Handle<JSObject> holder = instr->holder(); Handle<JSObject> current_prototype = instr->prototype(); // Load prototype object. __ LoadHeapObject(reg, current_prototype); // Check prototype maps up to the holder. while (!current_prototype.is_identical_to(holder)) { DoCheckMapCommon(reg, Handle<Map>(current_prototype->map()), ALLOW_ELEMENT_TRANSITION_MAPS, instr->environment()); current_prototype = Handle<JSObject>(JSObject::cast(current_prototype->GetPrototype())); // Load next prototype object. __ LoadHeapObject(reg, current_prototype); } // Check the holder map. DoCheckMapCommon(reg, Handle<Map>(current_prototype->map()), ALLOW_ELEMENT_TRANSITION_MAPS, instr->environment()); } void LCodeGen::DoAllocateObject(LAllocateObject* instr) { class DeferredAllocateObject: public LDeferredCode { public: DeferredAllocateObject(LCodeGen* codegen, LAllocateObject* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredAllocateObject(instr_); } virtual LInstruction* instr() { return instr_; } private: LAllocateObject* instr_; }; DeferredAllocateObject* deferred = new DeferredAllocateObject(this, instr); Register result = ToRegister(instr->result()); Register scratch = ToRegister(instr->TempAt(0)); Handle<JSFunction> constructor = instr->hydrogen()->constructor(); Handle<Map> initial_map(constructor->initial_map()); int instance_size = initial_map->instance_size(); ASSERT(initial_map->pre_allocated_property_fields() + initial_map->unused_property_fields() - initial_map->inobject_properties() == 0); // Allocate memory for the object. The initial map might change when // the constructor's prototype changes, but instance size and property // counts remain unchanged (if slack tracking finished). ASSERT(!constructor->shared()->IsInobjectSlackTrackingInProgress()); __ AllocateInNewSpace(instance_size, result, no_reg, scratch, deferred->entry(), TAG_OBJECT); // Load the initial map. Register map = scratch; __ LoadHeapObject(scratch, constructor); __ movq(map, FieldOperand(scratch, JSFunction::kPrototypeOrInitialMapOffset)); if (FLAG_debug_code) { __ AbortIfSmi(map); __ cmpb(FieldOperand(map, Map::kInstanceSizeOffset), Immediate(instance_size >> kPointerSizeLog2)); __ Assert(equal, "Unexpected instance size"); __ cmpb(FieldOperand(map, Map::kPreAllocatedPropertyFieldsOffset), Immediate(initial_map->pre_allocated_property_fields())); __ Assert(equal, "Unexpected pre-allocated property fields count"); __ cmpb(FieldOperand(map, Map::kUnusedPropertyFieldsOffset), Immediate(initial_map->unused_property_fields())); __ Assert(equal, "Unexpected unused property fields count"); __ cmpb(FieldOperand(map, Map::kInObjectPropertiesOffset), Immediate(initial_map->inobject_properties())); __ Assert(equal, "Unexpected in-object property fields count"); } // Initialize map and fields of the newly allocated object. ASSERT(initial_map->instance_type() == JS_OBJECT_TYPE); __ movq(FieldOperand(result, JSObject::kMapOffset), map); __ LoadRoot(scratch, Heap::kEmptyFixedArrayRootIndex); __ movq(FieldOperand(result, JSObject::kElementsOffset), scratch); __ movq(FieldOperand(result, JSObject::kPropertiesOffset), scratch); if (initial_map->inobject_properties() != 0) { __ LoadRoot(scratch, Heap::kUndefinedValueRootIndex); for (int i = 0; i < initial_map->inobject_properties(); i++) { int property_offset = JSObject::kHeaderSize + i * kPointerSize; __ movq(FieldOperand(result, property_offset), scratch); } } __ bind(deferred->exit()); } void LCodeGen::DoDeferredAllocateObject(LAllocateObject* instr) { Register result = ToRegister(instr->result()); Handle<JSFunction> constructor = instr->hydrogen()->constructor(); // TODO(3095996): Get rid of this. For now, we need to make the // result register contain a valid pointer because it is already // contained in the register pointer map. __ Set(result, 0); PushSafepointRegistersScope scope(this); __ PushHeapObject(constructor); CallRuntimeFromDeferred(Runtime::kNewObject, 1, instr); __ StoreToSafepointRegisterSlot(result, rax); } void LCodeGen::DoArrayLiteral(LArrayLiteral* instr) { Heap* heap = isolate()->heap(); ElementsKind boilerplate_elements_kind = instr->hydrogen()->boilerplate_elements_kind(); // Deopt if the array literal boilerplate ElementsKind is of a type different // than the expected one. The check isn't necessary if the boilerplate has // already been converted to FAST_ELEMENTS. if (boilerplate_elements_kind != FAST_ELEMENTS) { __ LoadHeapObject(rax, instr->hydrogen()->boilerplate_object()); __ movq(rbx, FieldOperand(rax, HeapObject::kMapOffset)); // Load the map's "bit field 2". __ movb(rbx, FieldOperand(rbx, Map::kBitField2Offset)); // Retrieve elements_kind from bit field 2. __ and_(rbx, Immediate(Map::kElementsKindMask)); __ cmpb(rbx, Immediate(boilerplate_elements_kind << Map::kElementsKindShift)); DeoptimizeIf(not_equal, instr->environment()); } // Set up the parameters to the stub/runtime call. __ movq(rax, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset)); __ push(FieldOperand(rax, JSFunction::kLiteralsOffset)); __ Push(Smi::FromInt(instr->hydrogen()->literal_index())); // Boilerplate already exists, constant elements are never accessed. // Pass an empty fixed array. __ Push(Handle<FixedArray>(heap->empty_fixed_array())); // Pick the right runtime function or stub to call. int length = instr->hydrogen()->length(); if (instr->hydrogen()->IsCopyOnWrite()) { ASSERT(instr->hydrogen()->depth() == 1); FastCloneShallowArrayStub::Mode mode = FastCloneShallowArrayStub::COPY_ON_WRITE_ELEMENTS; FastCloneShallowArrayStub stub(mode, length); CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); } else if (instr->hydrogen()->depth() > 1) { CallRuntime(Runtime::kCreateArrayLiteral, 3, instr); } else if (length > FastCloneShallowArrayStub::kMaximumClonedLength) { CallRuntime(Runtime::kCreateArrayLiteralShallow, 3, instr); } else { FastCloneShallowArrayStub::Mode mode = boilerplate_elements_kind == FAST_DOUBLE_ELEMENTS ? FastCloneShallowArrayStub::CLONE_DOUBLE_ELEMENTS : FastCloneShallowArrayStub::CLONE_ELEMENTS; FastCloneShallowArrayStub stub(mode, length); CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); } } void LCodeGen::EmitDeepCopy(Handle<JSObject> object, Register result, Register source, int* offset) { ASSERT(!source.is(rcx)); ASSERT(!result.is(rcx)); // Only elements backing stores for non-COW arrays need to be copied. Handle<FixedArrayBase> elements(object->elements()); bool has_elements = elements->length() > 0 && elements->map() != isolate()->heap()->fixed_cow_array_map(); // Increase the offset so that subsequent objects end up right after // this object and its backing store. int object_offset = *offset; int object_size = object->map()->instance_size(); int elements_offset = *offset + object_size; int elements_size = has_elements ? elements->Size() : 0; *offset += object_size + elements_size; // Copy object header. ASSERT(object->properties()->length() == 0); int inobject_properties = object->map()->inobject_properties(); int header_size = object_size - inobject_properties * kPointerSize; for (int i = 0; i < header_size; i += kPointerSize) { if (has_elements && i == JSObject::kElementsOffset) { __ lea(rcx, Operand(result, elements_offset)); } else { __ movq(rcx, FieldOperand(source, i)); } __ movq(FieldOperand(result, object_offset + i), rcx); } // Copy in-object properties. for (int i = 0; i < inobject_properties; i++) { int total_offset = object_offset + object->GetInObjectPropertyOffset(i); Handle<Object> value = Handle<Object>(object->InObjectPropertyAt(i)); if (value->IsJSObject()) { Handle<JSObject> value_object = Handle<JSObject>::cast(value); __ lea(rcx, Operand(result, *offset)); __ movq(FieldOperand(result, total_offset), rcx); __ LoadHeapObject(source, value_object); EmitDeepCopy(value_object, result, source, offset); } else if (value->IsHeapObject()) { __ LoadHeapObject(rcx, Handle<HeapObject>::cast(value)); __ movq(FieldOperand(result, total_offset), rcx); } else { __ movq(rcx, value, RelocInfo::NONE); __ movq(FieldOperand(result, total_offset), rcx); } } // Copy elements backing store header. ASSERT(!has_elements || elements->IsFixedArray()); if (has_elements) { __ LoadHeapObject(source, elements); for (int i = 0; i < FixedArray::kHeaderSize; i += kPointerSize) { __ movq(rcx, FieldOperand(source, i)); __ movq(FieldOperand(result, elements_offset + i), rcx); } } // Copy elements backing store content. ASSERT(!has_elements || elements->IsFixedArray()); int elements_length = has_elements ? elements->length() : 0; for (int i = 0; i < elements_length; i++) { int total_offset = elements_offset + FixedArray::OffsetOfElementAt(i); Handle<Object> value = JSObject::GetElement(object, i); if (value->IsJSObject()) { Handle<JSObject> value_object = Handle<JSObject>::cast(value); __ lea(rcx, Operand(result, *offset)); __ movq(FieldOperand(result, total_offset), rcx); __ LoadHeapObject(source, value_object); EmitDeepCopy(value_object, result, source, offset); } else if (value->IsHeapObject()) { __ LoadHeapObject(rcx, Handle<HeapObject>::cast(value)); __ movq(FieldOperand(result, total_offset), rcx); } else { __ movq(rcx, value, RelocInfo::NONE); __ movq(FieldOperand(result, total_offset), rcx); } } } void LCodeGen::DoFastLiteral(LFastLiteral* instr) { int size = instr->hydrogen()->total_size(); // Allocate all objects that are part of the literal in one big // allocation. This avoids multiple limit checks. Label allocated, runtime_allocate; __ AllocateInNewSpace(size, rax, rcx, rdx, &runtime_allocate, TAG_OBJECT); __ jmp(&allocated); __ bind(&runtime_allocate); __ Push(Smi::FromInt(size)); CallRuntime(Runtime::kAllocateInNewSpace, 1, instr); __ bind(&allocated); int offset = 0; __ LoadHeapObject(rbx, instr->hydrogen()->boilerplate()); EmitDeepCopy(instr->hydrogen()->boilerplate(), rax, rbx, &offset); ASSERT_EQ(size, offset); } void LCodeGen::DoObjectLiteral(LObjectLiteral* instr) { Handle<FixedArray> literals(instr->environment()->closure()->literals()); Handle<FixedArray> constant_properties = instr->hydrogen()->constant_properties(); // Set up the parameters to the stub/runtime call. __ PushHeapObject(literals); __ Push(Smi::FromInt(instr->hydrogen()->literal_index())); __ Push(constant_properties); int flags = instr->hydrogen()->fast_elements() ? ObjectLiteral::kFastElements : ObjectLiteral::kNoFlags; flags |= instr->hydrogen()->has_function() ? ObjectLiteral::kHasFunction : ObjectLiteral::kNoFlags; __ Push(Smi::FromInt(flags)); // Pick the right runtime function or stub to call. int properties_count = constant_properties->length() / 2; if (instr->hydrogen()->depth() > 1) { CallRuntime(Runtime::kCreateObjectLiteral, 4, instr); } else if (flags != ObjectLiteral::kFastElements || properties_count > FastCloneShallowObjectStub::kMaximumClonedProperties) { CallRuntime(Runtime::kCreateObjectLiteralShallow, 4, instr); } else { FastCloneShallowObjectStub stub(properties_count); CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); } } void LCodeGen::DoToFastProperties(LToFastProperties* instr) { ASSERT(ToRegister(instr->InputAt(0)).is(rax)); __ push(rax); CallRuntime(Runtime::kToFastProperties, 1, instr); } void LCodeGen::DoRegExpLiteral(LRegExpLiteral* instr) { Label materialized; // Registers will be used as follows: // rdi = JS function. // rcx = literals array. // rbx = regexp literal. // rax = regexp literal clone. __ movq(rdi, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset)); __ movq(rcx, FieldOperand(rdi, JSFunction::kLiteralsOffset)); int literal_offset = FixedArray::kHeaderSize + instr->hydrogen()->literal_index() * kPointerSize; __ movq(rbx, FieldOperand(rcx, literal_offset)); __ CompareRoot(rbx, Heap::kUndefinedValueRootIndex); __ j(not_equal, &materialized, Label::kNear); // Create regexp literal using runtime function // Result will be in rax. __ push(rcx); __ Push(Smi::FromInt(instr->hydrogen()->literal_index())); __ Push(instr->hydrogen()->pattern()); __ Push(instr->hydrogen()->flags()); CallRuntime(Runtime::kMaterializeRegExpLiteral, 4, instr); __ movq(rbx, rax); __ bind(&materialized); int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize; Label allocated, runtime_allocate; __ AllocateInNewSpace(size, rax, rcx, rdx, &runtime_allocate, TAG_OBJECT); __ jmp(&allocated); __ bind(&runtime_allocate); __ push(rbx); __ Push(Smi::FromInt(size)); CallRuntime(Runtime::kAllocateInNewSpace, 1, instr); __ pop(rbx); __ bind(&allocated); // Copy the content into the newly allocated memory. // (Unroll copy loop once for better throughput). for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) { __ movq(rdx, FieldOperand(rbx, i)); __ movq(rcx, FieldOperand(rbx, i + kPointerSize)); __ movq(FieldOperand(rax, i), rdx); __ movq(FieldOperand(rax, i + kPointerSize), rcx); } if ((size % (2 * kPointerSize)) != 0) { __ movq(rdx, FieldOperand(rbx, size - kPointerSize)); __ movq(FieldOperand(rax, size - kPointerSize), rdx); } } void LCodeGen::DoFunctionLiteral(LFunctionLiteral* instr) { // Use the fast case closure allocation code that allocates in new // space for nested functions that don't need literals cloning. Handle<SharedFunctionInfo> shared_info = instr->shared_info(); bool pretenure = instr->hydrogen()->pretenure(); if (!pretenure && shared_info->num_literals() == 0) { FastNewClosureStub stub(shared_info->language_mode()); __ Push(shared_info); CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); } else { __ push(rsi); __ Push(shared_info); __ PushRoot(pretenure ? Heap::kTrueValueRootIndex : Heap::kFalseValueRootIndex); CallRuntime(Runtime::kNewClosure, 3, instr); } } void LCodeGen::DoTypeof(LTypeof* instr) { LOperand* input = instr->InputAt(0); EmitPushTaggedOperand(input); CallRuntime(Runtime::kTypeof, 1, instr); } void LCodeGen::EmitPushTaggedOperand(LOperand* operand) { ASSERT(!operand->IsDoubleRegister()); if (operand->IsConstantOperand()) { Handle<Object> object = ToHandle(LConstantOperand::cast(operand)); if (object->IsSmi()) { __ Push(Handle<Smi>::cast(object)); } else { __ PushHeapObject(Handle<HeapObject>::cast(object)); } } else if (operand->IsRegister()) { __ push(ToRegister(operand)); } else { __ push(ToOperand(operand)); } } void LCodeGen::DoTypeofIsAndBranch(LTypeofIsAndBranch* instr) { Register input = ToRegister(instr->InputAt(0)); int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); Label* true_label = chunk_->GetAssemblyLabel(true_block); Label* false_label = chunk_->GetAssemblyLabel(false_block); Condition final_branch_condition = EmitTypeofIs(true_label, false_label, input, instr->type_literal()); if (final_branch_condition != no_condition) { EmitBranch(true_block, false_block, final_branch_condition); } } Condition LCodeGen::EmitTypeofIs(Label* true_label, Label* false_label, Register input, Handle<String> type_name) { Condition final_branch_condition = no_condition; if (type_name->Equals(heap()->number_symbol())) { __ JumpIfSmi(input, true_label); __ CompareRoot(FieldOperand(input, HeapObject::kMapOffset), Heap::kHeapNumberMapRootIndex); final_branch_condition = equal; } else if (type_name->Equals(heap()->string_symbol())) { __ JumpIfSmi(input, false_label); __ CmpObjectType(input, FIRST_NONSTRING_TYPE, input); __ j(above_equal, false_label); __ testb(FieldOperand(input, Map::kBitFieldOffset), Immediate(1 << Map::kIsUndetectable)); final_branch_condition = zero; } else if (type_name->Equals(heap()->boolean_symbol())) { __ CompareRoot(input, Heap::kTrueValueRootIndex); __ j(equal, true_label); __ CompareRoot(input, Heap::kFalseValueRootIndex); final_branch_condition = equal; } else if (FLAG_harmony_typeof && type_name->Equals(heap()->null_symbol())) { __ CompareRoot(input, Heap::kNullValueRootIndex); final_branch_condition = equal; } else if (type_name->Equals(heap()->undefined_symbol())) { __ CompareRoot(input, Heap::kUndefinedValueRootIndex); __ j(equal, true_label); __ JumpIfSmi(input, false_label); // Check for undetectable objects => true. __ movq(input, FieldOperand(input, HeapObject::kMapOffset)); __ testb(FieldOperand(input, Map::kBitFieldOffset), Immediate(1 << Map::kIsUndetectable)); final_branch_condition = not_zero; } else if (type_name->Equals(heap()->function_symbol())) { STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2); __ JumpIfSmi(input, false_label); __ CmpObjectType(input, JS_FUNCTION_TYPE, input); __ j(equal, true_label); __ CmpInstanceType(input, JS_FUNCTION_PROXY_TYPE); final_branch_condition = equal; } else if (type_name->Equals(heap()->object_symbol())) { __ JumpIfSmi(input, false_label); if (!FLAG_harmony_typeof) { __ CompareRoot(input, Heap::kNullValueRootIndex); __ j(equal, true_label); } __ CmpObjectType(input, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, input); __ j(below, false_label); __ CmpInstanceType(input, LAST_NONCALLABLE_SPEC_OBJECT_TYPE); __ j(above, false_label); // Check for undetectable objects => false. __ testb(FieldOperand(input, Map::kBitFieldOffset), Immediate(1 << Map::kIsUndetectable)); final_branch_condition = zero; } else { __ jmp(false_label); } return final_branch_condition; } void LCodeGen::DoIsConstructCallAndBranch(LIsConstructCallAndBranch* instr) { Register temp = ToRegister(instr->TempAt(0)); int true_block = chunk_->LookupDestination(instr->true_block_id()); int false_block = chunk_->LookupDestination(instr->false_block_id()); EmitIsConstructCall(temp); EmitBranch(true_block, false_block, equal); } void LCodeGen::EmitIsConstructCall(Register temp) { // Get the frame pointer for the calling frame. __ movq(temp, Operand(rbp, StandardFrameConstants::kCallerFPOffset)); // Skip the arguments adaptor frame if it exists. Label check_frame_marker; __ Cmp(Operand(temp, StandardFrameConstants::kContextOffset), Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)); __ j(not_equal, &check_frame_marker, Label::kNear); __ movq(temp, Operand(rax, StandardFrameConstants::kCallerFPOffset)); // Check the marker in the calling frame. __ bind(&check_frame_marker); __ Cmp(Operand(temp, StandardFrameConstants::kMarkerOffset), Smi::FromInt(StackFrame::CONSTRUCT)); } void LCodeGen::EnsureSpaceForLazyDeopt(int space_needed) { // Ensure that we have enough space after the previous lazy-bailout // instruction for patching the code here. int current_pc = masm()->pc_offset(); if (current_pc < last_lazy_deopt_pc_ + space_needed) { int padding_size = last_lazy_deopt_pc_ + space_needed - current_pc; __ Nop(padding_size); } } void LCodeGen::DoLazyBailout(LLazyBailout* instr) { EnsureSpaceForLazyDeopt(Deoptimizer::patch_size()); last_lazy_deopt_pc_ = masm()->pc_offset(); ASSERT(instr->HasEnvironment()); LEnvironment* env = instr->environment(); RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt); safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index()); } void LCodeGen::DoDeoptimize(LDeoptimize* instr) { DeoptimizeIf(no_condition, instr->environment()); } void LCodeGen::DoDeleteProperty(LDeleteProperty* instr) { LOperand* obj = instr->object(); LOperand* key = instr->key(); EmitPushTaggedOperand(obj); EmitPushTaggedOperand(key); ASSERT(instr->HasPointerMap() && instr->HasDeoptimizationEnvironment()); LPointerMap* pointers = instr->pointer_map(); RecordPosition(pointers->position()); // Create safepoint generator that will also ensure enough space in the // reloc info for patching in deoptimization (since this is invoking a // builtin) SafepointGenerator safepoint_generator( this, pointers, Safepoint::kLazyDeopt); __ Push(Smi::FromInt(strict_mode_flag())); __ InvokeBuiltin(Builtins::DELETE, CALL_FUNCTION, safepoint_generator); } void LCodeGen::DoIn(LIn* instr) { LOperand* obj = instr->object(); LOperand* key = instr->key(); EmitPushTaggedOperand(key); EmitPushTaggedOperand(obj); ASSERT(instr->HasPointerMap() && instr->HasDeoptimizationEnvironment()); LPointerMap* pointers = instr->pointer_map(); RecordPosition(pointers->position()); SafepointGenerator safepoint_generator( this, pointers, Safepoint::kLazyDeopt); __ InvokeBuiltin(Builtins::IN, CALL_FUNCTION, safepoint_generator); } void LCodeGen::DoDeferredStackCheck(LStackCheck* instr) { PushSafepointRegistersScope scope(this); __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); __ CallRuntimeSaveDoubles(Runtime::kStackGuard); RecordSafepointWithLazyDeopt(instr, RECORD_SAFEPOINT_WITH_REGISTERS, 0); ASSERT(instr->HasEnvironment()); LEnvironment* env = instr->environment(); safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index()); } void LCodeGen::DoStackCheck(LStackCheck* instr) { class DeferredStackCheck: public LDeferredCode { public: DeferredStackCheck(LCodeGen* codegen, LStackCheck* instr) : LDeferredCode(codegen), instr_(instr) { } virtual void Generate() { codegen()->DoDeferredStackCheck(instr_); } virtual LInstruction* instr() { return instr_; } private: LStackCheck* instr_; }; ASSERT(instr->HasEnvironment()); LEnvironment* env = instr->environment(); // There is no LLazyBailout instruction for stack-checks. We have to // prepare for lazy deoptimization explicitly here. if (instr->hydrogen()->is_function_entry()) { // Perform stack overflow check. Label done; __ CompareRoot(rsp, Heap::kStackLimitRootIndex); __ j(above_equal, &done, Label::kNear); StackCheckStub stub; CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr); EnsureSpaceForLazyDeopt(Deoptimizer::patch_size()); last_lazy_deopt_pc_ = masm()->pc_offset(); __ bind(&done); RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt); safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index()); } else { ASSERT(instr->hydrogen()->is_backwards_branch()); // Perform stack overflow check if this goto needs it before jumping. DeferredStackCheck* deferred_stack_check = new DeferredStackCheck(this, instr); __ CompareRoot(rsp, Heap::kStackLimitRootIndex); __ j(below, deferred_stack_check->entry()); EnsureSpaceForLazyDeopt(Deoptimizer::patch_size()); last_lazy_deopt_pc_ = masm()->pc_offset(); __ bind(instr->done_label()); deferred_stack_check->SetExit(instr->done_label()); RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt); // Don't record a deoptimization index for the safepoint here. // This will be done explicitly when emitting call and the safepoint in // the deferred code. } } void LCodeGen::DoOsrEntry(LOsrEntry* instr) { // This is a pseudo-instruction that ensures that the environment here is // properly registered for deoptimization and records the assembler's PC // offset. LEnvironment* environment = instr->environment(); environment->SetSpilledRegisters(instr->SpilledRegisterArray(), instr->SpilledDoubleRegisterArray()); // If the environment were already registered, we would have no way of // backpatching it with the spill slot operands. ASSERT(!environment->HasBeenRegistered()); RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt); ASSERT(osr_pc_offset_ == -1); osr_pc_offset_ = masm()->pc_offset(); } void LCodeGen::DoForInPrepareMap(LForInPrepareMap* instr) { __ CompareRoot(rax, Heap::kUndefinedValueRootIndex); DeoptimizeIf(equal, instr->environment()); Register null_value = rdi; __ LoadRoot(null_value, Heap::kNullValueRootIndex); __ cmpq(rax, null_value); DeoptimizeIf(equal, instr->environment()); Condition cc = masm()->CheckSmi(rax); DeoptimizeIf(cc, instr->environment()); STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE); __ CmpObjectType(rax, LAST_JS_PROXY_TYPE, rcx); DeoptimizeIf(below_equal, instr->environment()); Label use_cache, call_runtime; __ CheckEnumCache(null_value, &call_runtime); __ movq(rax, FieldOperand(rax, HeapObject::kMapOffset)); __ jmp(&use_cache, Label::kNear); // Get the set of properties to enumerate. __ bind(&call_runtime); __ push(rax); CallRuntime(Runtime::kGetPropertyNamesFast, 1, instr); __ CompareRoot(FieldOperand(rax, HeapObject::kMapOffset), Heap::kMetaMapRootIndex); DeoptimizeIf(not_equal, instr->environment()); __ bind(&use_cache); } void LCodeGen::DoForInCacheArray(LForInCacheArray* instr) { Register map = ToRegister(instr->map()); Register result = ToRegister(instr->result()); __ LoadInstanceDescriptors(map, result); __ movq(result, FieldOperand(result, DescriptorArray::kEnumerationIndexOffset)); __ movq(result, FieldOperand(result, FixedArray::SizeFor(instr->idx()))); Condition cc = masm()->CheckSmi(result); DeoptimizeIf(NegateCondition(cc), instr->environment()); } void LCodeGen::DoCheckMapValue(LCheckMapValue* instr) { Register object = ToRegister(instr->value()); __ cmpq(ToRegister(instr->map()), FieldOperand(object, HeapObject::kMapOffset)); DeoptimizeIf(not_equal, instr->environment()); } void LCodeGen::DoLoadFieldByIndex(LLoadFieldByIndex* instr) { Register object = ToRegister(instr->object()); Register index = ToRegister(instr->index()); Label out_of_object, done; __ SmiToInteger32(index, index); __ cmpl(index, Immediate(0)); __ j(less, &out_of_object); __ movq(object, FieldOperand(object, index, times_pointer_size, JSObject::kHeaderSize)); __ jmp(&done, Label::kNear); __ bind(&out_of_object); __ movq(object, FieldOperand(object, JSObject::kPropertiesOffset)); __ negl(index); // Index is now equal to out of object property index plus 1. __ movq(object, FieldOperand(object, index, times_pointer_size, FixedArray::kHeaderSize - kPointerSize)); __ bind(&done); } #undef __ } } // namespace v8::internal #endif // V8_TARGET_ARCH_X64
// REQUIRES: gwp_asan // RUN: %clangxx_gwp_asan %s -o %t // RUN: not %run %t 2>&1 | FileCheck %s // CHECK: GWP-ASan detected a memory error // CHECK: Invalid (wild) free at 0x{{[a-f0-9]+}} (1 byte to the right of a // CHECK-SAME: 1-byte allocation #include <cstdlib> int main() { char *Ptr = reinterpret_cast<char *>(malloc(1)); free(Ptr + 1); return 0; }
/* * Copyright (c) [2020] Huawei Technologies Co., Ltd. All rights reserved. * * OpenArkCompiler is licensed under the Mulan Permissive Software License v2. * You can use this software according to the terms and conditions of the MulanPSL - 2.0. * You may obtain a copy of MulanPSL - 2.0 at: * * https://opensource.org/licenses/MulanPSL-2.0 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR * FIT FOR A PARTICULAR PURPOSE. * See the MulanPSL - 2.0 for more details. */ #include <iostream> #include <fstream> #include "bb.h" #include "me_cfg.h" #include "ssa_mir_nodes.h" #include "me_irmap.h" #include "mir_builder.h" #include <algorithm> #include "name_mangler.h" #include <string> #include "me_loop_canon.h" #include "me_critical_edge.h" using namespace std; namespace maple { /* get next bb in bbVec*/ BB *MirCFG::NextBB(const BB *bb) { if (bb->id.idx == bbVec.size() - 1) { return nullptr; } uint32 i = bb->id.idx + 1; for (; i < bbVec.size(); i++) { if (bbVec[i] != nullptr) { return bbVec[i]; } } return nullptr; } /* get prev bb in bbVec*/ BB *MirCFG::PrevBB(const BB *bb) { if (bb->id.idx == 0) { return nullptr; } int32 i = bb->id.idx - 1; for (; i >= 0; i--) { if (bbVec[i] != nullptr) { return bbVec[i]; } } return nullptr; } void MirCFG::DeleteBasicBlock(const BB *bb) { ASSERT(bbVec[bb->id.idx] == bb, ""); /* update first_bb_ and last_bb if needed */ if (first_bb == bb) { first_bb = NextBB(bb); } else if (last_bb == bb) { last_bb = PrevBB(bb); } bbVec[bb->id.idx] = nullptr; return; } // determine if need to be replaced by assertnonnull bool MirCFG::IfReplaceWithAssertnonnull(BB *bb) { StmtNode *stmt = bb->stmtNodeList.first; GStrIdx npeGstringIdx = GlobalTables::GetStrTable().GetStrIdxFromName(string(NameMangler::kJavaLang) + string(NameMangler::kNullPointerException)); TyIdx npeTypeIdx = func->mirModule.typeNameTab->GetTyIdxFromGStrIdx(npeGstringIdx); /* match first stmt */ while (stmt && stmt->op == OP_comment) { stmt = stmt->GetNext(); } if (!stmt || stmt->op != OP_intrinsiccallwithtype) { return false; } IntrinsiccallNode *cnode = static_cast<IntrinsiccallNode *>(stmt); if (cnode->tyIdx != npeTypeIdx) { return false; } stmt = stmt->GetNext(); /* match second stmt */ while (stmt && stmt->op == OP_comment) { stmt = stmt->GetNext(); } if (!stmt || stmt->op != OP_dassign) { return false; } DassignNode *dassignNode = static_cast<DassignNode *>(stmt); if (dassignNode->GetRhs()->op != OP_gcmalloc) { return false; } GCMallocNode *gcMallocNode = static_cast<GCMallocNode *>(dassignNode->GetRhs()); if (gcMallocNode->tyIdx != npeTypeIdx) { return false; } stmt = stmt->GetNext(); /* match third stmt */ while (stmt && stmt->op == OP_comment) { stmt = stmt->GetNext(); } if (!stmt || stmt->op != OP_callassigned) { return false; } CallNode *callAssignedNode = static_cast<CallNode *>(stmt); if (GlobalTables::GetFunctionTable().GetFunctionFromPuidx(callAssignedNode->puIdx)->GetName() != (string(NameMangler::kJavaLang) + string(NameMangler::kNullPointerException) + string(NameMangler::kInitSuffix))) { return false; } stmt = stmt->GetNext(); // match last stmt while (stmt && stmt->op == OP_comment) { stmt = stmt->GetNext(); } if (stmt && stmt->op == OP_throw) { return true; } return false; } void MirCFG::BuildMirCFG() { std::vector<BB *> entryblocks; std::vector<BB *> exitblocks;; // bbVec[0,1] are common entry/exit bb for (uint32 i = commonExitBB->id.idx + 1; i < bbVec.size(); i++) { BB *bb = bbVec[i]; if (bb == nullptr) { continue; } if (bb->isEntry) { entryblocks.push_back(bb); } if (bb->isExit) { exitblocks.push_back(bb); } switch (bb->kind) { case kBBGoto: { StmtNode *lastStmt = bb->stmtNodeList.last; if (lastStmt->op == OP_throw) { break; } CHECK_FATAL(lastStmt->op == OP_goto, ""); GotoNode *gotostmt = static_cast<GotoNode *>(lastStmt); LabelIdx lblidx = (LabelIdx)gotostmt->offset; BB *meBb = labelBBIdMap[lblidx]; bb->succ.push_back(meBb); meBb->pred.push_back(bb); break; } case kBBCondGoto: { StmtNode *laststmt = bb->stmtNodeList.last; CHECK_FATAL(laststmt->IsCondBr(), ""); /* succ[0] is fallthru, succ[1] is gotobb */ BB *rightnextbb = NextBB(bb); CHECK_FATAL(rightnextbb, "null ptr check "); rightnextbb->pred.push_back(bb); bb->succ.push_back(rightnextbb); /* link goto */ CondGotoNode *gotostmt = static_cast<CondGotoNode *>(laststmt); LabelIdx lblidx = (LabelIdx)gotostmt->offset; BB *meBb = labelBBIdMap[lblidx]; bb->succ.push_back(meBb); meBb->pred.push_back(bb); /* can the gotostmt be replaced by assertnonnull ? */ if (IfReplaceWithAssertnonnull(meBb)) { pattern_set_.insert(lblidx); } break; } case kBBSwitch: { StmtNode *laststmt = bb->stmtNodeList.last; CHECK_FATAL(laststmt->op == OP_switch, ""); SwitchNode *switchstmt = static_cast<SwitchNode *>(laststmt); LabelIdx lblidx = switchstmt->defaultLabel; BB *mirbb = labelBBIdMap[lblidx]; bb->succ.push_back(mirbb); mirbb->pred.push_back(bb); for (uint32_t j = 0; j < switchstmt->switchTable.size(); j++) { lblidx = switchstmt->switchTable[j].second; BB *mebb = labelBBIdMap[lblidx]; // Avoid duplicate succs. MapleVector<BB *>::iterator it = std::find(bb->succ.begin(), bb->succ.end(), mebb); if (it == bb->succ.end()) { bb->succ.push_back(mebb); mebb->pred.push_back(bb); } } break; } case kBBIgoto: { for (LabelIdx lidx : func->mirFunc->labelTab->addrTakenLabels) { BB *mebb = labelBBIdMap[lidx]; bb->succ.push_back(mebb); mebb->pred.push_back(bb); } break; } case kBBReturn: break; default: { // fall through? BB *rightnextbb = NextBB(bb); if (rightnextbb) { rightnextbb->pred.push_back(bb); bb->succ.push_back(rightnextbb); } break; } } /* deal try blocks, add catch handler to try's succ */ if (func->mirModule.IsJavaModule() && bb->isTry) { ASSERT((bbTryNodeMap.find(bb) != bbTryNodeMap.end()), "try bb without try"); StmtNode *stmt = bbTryNodeMap[bb]; TryNode *trynode = static_cast<TryNode *>(stmt); bool hasfinallyhandler = false; /* add exception handler bb */ for (uint32 i = 0; i < trynode->offsets.size(); i++) { LabelIdx labelIdx = trynode->offsets[i]; ASSERT(labelBBIdMap.find(labelIdx) != labelBBIdMap.end(), ""); BB *meBb = labelBBIdMap[labelIdx]; ASSERT(meBb != nullptr && meBb->IsCatch(), ""); uint32 si = 0; if (meBb->IsJavaFinally() || meBb->IsCatch()) { hasfinallyhandler = true; } /* avoid redundant succ */ for (; si < bb->succ.size(); si++) { if (meBb == bb->succ[si]) { break; } } if (si == bb->succ.size()) { bb->succ.push_back(meBb); meBb->pred.push_back(bb); } } /* if try block don't have finally catch handler, add commonExitBB as its succ */ if (hasfinallyhandler == false) { if (!bb->isExit) { bb->isExit = true; // may exit exitblocks.push_back(bb); } } else if ((func->mirModule.IsJavaModule()) && bb->isExit) { // deal with throw bb, if throw bb in a tryblock and has finallyhandler StmtNode *lastStmt = bb->stmtNodeList.last; if (lastStmt && lastStmt->op == OP_throw) { bb->isExit = false; ASSERT(bb == exitblocks.back(), ""); exitblocks.pop_back(); } } } } // merge all blocks in entryblocks for (std::vector<BB *>::iterator it = entryblocks.begin(); it != entryblocks.end(); ++it) { commonEntryBB->succ.push_back(*it); } // merge all blocks in exitblocks for (std::vector<BB *>::iterator it = exitblocks.begin(); it != exitblocks.end(); ++it) { commonExitBB->pred.push_back(*it); } } // replace "if() throw NPE()" with assertnonnull void MirCFG::ReplaceWithAssertnonnull() { if (func->GetName() == (NameMangler::kJavaUtil + std::string("Objects_3B_7CrequireNonNull_7C_28") + NameMangler::kJavaLangObjectStr + NameMangler::kRightBracketStr + NameMangler::kJavaLangObjectStr)) { return; } for (LabelIdx lblidx : pattern_set_) { BB *bb = labelBBIdMap[lblidx]; /* if BB->pred.size()==0, it won't enter this function */ for (uint32 i = 0; i < bb->pred.size(); i++) { BB *innerBb = bb->pred[i]; if (innerBb->kind == kBBCondGoto) { StmtNode *stmt = innerBb->stmtNodeList.last; Opcode stmtop = stmt->op; if (!stmt->IsCondBr()) { continue; } CondGotoNode *cgotoNode = static_cast<CondGotoNode *>(stmt); if ((stmtop == OP_brtrue && cgotoNode->uOpnd->op != OP_eq) || (stmtop == OP_brfalse && cgotoNode->uOpnd->op != OP_ne)) { continue; } CompareNode *cmpNode = static_cast<CompareNode *>(cgotoNode->uOpnd); BaseNode *opnd = nullptr; if (cmpNode->opndType != PTY_ref && cmpNode->opndType != PTY_ptr) { continue; } if (cmpNode->bOpnd[0]->op == OP_constval) { ConstvalNode *constNode = static_cast<ConstvalNode *>(cmpNode->bOpnd[0]); if (!constNode->constVal->IsZero()) { continue; } opnd = cmpNode->bOpnd[1]; } else if (cmpNode->bOpnd[1]->op == OP_constval) { ConstvalNode *constNode = static_cast<ConstvalNode *>(cmpNode->bOpnd[1]); if (!constNode->constVal->IsZero()) { continue; } opnd = cmpNode->bOpnd[0]; } CHECK_FATAL(opnd != nullptr, "Compare with non-zero"); UnaryStmtNode *nullcheck = func->mirModule.mirBuilder->CreateStmtUnary(OP_assertnonnull, opnd); innerBb->ReplaceStmt(stmt, nullcheck); innerBb->kind = kBBFallthru; innerBb->RemoveBBFromSucc(bb); bb->RemoveBBFromPred(innerBb); i--; } } } return; } // used only after DSE because it looks at live field of VersionSt void MirCFG::ConvertPhis2IdentityAssigns(BB *mebb) { if (mebb->phiList) { MapleMap<OriginalSt *, PhiNode>::iterator phiIt = mebb->phiList->begin(); while (phiIt != mebb->phiList->end()) { if (!(*phiIt).second.result->IsLive()) { phiIt++; continue; } // replace phi with identify assignment as it only has 1 opnd OriginalSt *ost = (*phiIt).first; if (ost->ostType == OriginalSt::kSymbolOst && ost->indirectLev == 0) { MIRSymbol *st = ost->GetMIRSymbol(); MIRType *stype = GlobalTables::GetTypeTable().GetTypeFromTyIdx(st->GetTyIdx()); AddrofNode *dread = func->mirModule.mirBuilder->CreateDread(st, GetRegPrimType(stype->GetPrimType())); AddrofSSANode *dread2 = func->mirFunc->codeMemPool->New<AddrofSSANode>(dread); dread2->ssaVar = (*phiIt).second.phiOpnds[0]; DassignNode *dass = func->mirModule.mirBuilder->CreateStmtDassign(st, 0, dread2); func->meSSATab->stmtsSSAPart.SetSsapartOf(dass, func->meSSATab->stmtsSSAPart.ssaPartMp->New<MayDefPartWithVersionSt>( &func->meSSATab->stmtsSSAPart.ssaPartAlloc)); MayDefPartWithVersionSt *thessapart = static_cast<MayDefPartWithVersionSt *>(func->meSSATab->stmtsSSAPart.SsapartOf(dass)); thessapart->ssaVar = (*phiIt).second.result; mebb->PrependStmtNode(dass); } phiIt++; } mebb->phiList->clear(); // delete all the phis } MapleMap<OStIdx, MePhiNode *>::iterator mePhiIt = mebb->mePhiList.begin(); while (mePhiIt != mebb->mePhiList.end()) { if (!mePhiIt->second->isLive) { mePhiIt++; continue; } // replace phi with identify assignment as it only has 1 opnd OriginalSt *ost = func->meSSATab->GetOriginalStFromid(mePhiIt->first); if (ost->ostType == OriginalSt::kSymbolOst && ost->indirectLev == 0) { MePhiNode *phi = mePhiIt->second; AssignMeStmt *assign = nullptr; if (phi->UseReg()) { assign = func->irMap->New<AssignMeStmt>(OP_regassign, phi->lhs, phi->opnds[0]); } else { assign = func->irMap->NewInPool<DassignMeStmt>(phi->lhs, phi->opnds[0]); } assign->bb = phi->defBB; assign->isLive = phi->isLive; mebb->PrependMeStmt(assign); } mePhiIt++; } mebb->mePhiList.clear(); // delete all the phis } // analyse the CFG to find the BBs that are not reachable from function entries // and delete them void MirCFG::UnreachCodeAnalysis(bool updatePhi) { std::vector<bool> visitedBBs(NumBBs(), false); commonEntryBB->FindReachableBBs(visitedBBs); // delete the unreached bb BB *bb = nullptr; for (uint32_t i = 0; i < bbVec.size(); i++) { bb = bbVec[i]; if (!visitedBBs[i] && bb && !bb->isEntry && bb != commonExitBB) { bb->wontExit = true; /* avoid redundant pred before adding to commonExitBB's pred list */ uint32 pi = 0; for (; pi < commonExitBB->pred.size(); pi++) { if (bb == commonExitBB->pred[pi]) { break; } } if (pi == commonExitBB->pred.size()) { commonExitBB->pred.push_back(bb); } if (!MeOption::quiet) { LogInfo::MapleLogger() << "#### BB " << bb->id.idx << " deleted because unreachable\n"; } if (bb->isTryEnd) { // unreachable bb has try end info BB *trybb = endTryBB2TryBB[bb]; if (visitedBBs[trybb->id.idx]) { // corresponding try is still around // move endtry tag to previous non-deleted bb int j = static_cast<int>(i) - 1; for (; j >= 0; j--) { if (bbVec[j] != nullptr) { bbVec[j]->isTryEnd = true; endTryBB2TryBB[bbVec[j]] = endTryBB2TryBB[bb]; break; } } } } DeleteBasicBlock(bb); // remove the bb from its succ's pred list for (MapleVector<BB *>::iterator it = bb->succ.begin(); it != bb->succ.end(); it++) { BB *sucbb = *it; if (!updatePhi) { bb->RemoveBBFromVector(sucbb->pred); } else { sucbb->RemoveBBFromPred(bb); if (sucbb->pred.size() == 1) { ConvertPhis2IdentityAssigns(sucbb); } else if (sucbb->pred.empty()) { if (sucbb->phiList) { sucbb->phiList->clear(); } } } } // remove the bb from commonExitBB's pred list if it is there for (MapleVector<BB *>::iterator it = commonExitBB->pred.begin(); it != commonExitBB->pred.end(); it++) { if (*it == bb) { commonExitBB->RemoveBBFromPred(bb); break; } } } } } // analyse the CFG to find the BBs that will not reach any function exit; these // are BBs inside infinite loops; mark their wontExit flag and create // artificial edges from them to commonExitBB void MirCFG::WontExitAnalysis() { if (NumBBs() == 0) { return; } vector<bool> visitedBBs(NumBBs(), false); commonExitBB->FindWillExitBBs(visitedBBs); BB *bb = nullptr; uint32_t bbvecsize = bbVec.size(); for (uint32_t i = 0; i < bbvecsize; i++) { bb = bbVec[i]; if (!visitedBBs[i] && bb && (bb != commonEntryBB)) { bb->wontExit = true; if (!MeOption::quiet) { printf("#### BB %d wont exit\n", i); } if (bb->kind == kBBGoto) { // create artificial BB to transition to commonExitBB BB *newbb = func->NewBasicBlock(); newbb->kind = kBBReturn; newbb->isExit = true; newbb->artificial = true; bb->succ.push_back(newbb); newbb->pred.push_back(bb); commonExitBB->pred.push_back(newbb); } } } } // CFG Verify // Check bb-vec and bb-list are strictly consistent. void MirCFG::Verify() { // Check every bb in bb-list. for (BB *bb : bbVec) { if (bb == nullptr) { continue; } ASSERT(bb->id.idx < bbVec.size(), "CFG Error!"); ASSERT(bbVec[bb->id.idx] == bb, "CFG Error!"); if (bb->IsEmpty() || bb == commonEntryBB || bb == commonExitBB) { continue; } ASSERT(bb->kind != kBBUnknown, ""); /* verify succ[1] is goto bb */ StmtNode *lastStmt = bb->stmtNodeList.last; if (bb->kind == kBBCondGoto) { ASSERT(bb->isTry || bb->wontExit || (lastStmt != nullptr && bb->succ.size() == 2), ""); CondGotoNode *gotostmt = static_cast<CondGotoNode *>(lastStmt); BB *gotobb = bb->succ[1]; ASSERT(gotobb->bbLabel == gotostmt->offset, ""); } else if (bb->kind == kBBGoto) { if (lastStmt->op == OP_throw) { continue; } ASSERT(bb->isTry || bb->wontExit || (lastStmt != nullptr && bb->succ.size() == 1), ""); GotoNode *gotostmt = static_cast<GotoNode *>(lastStmt); BB *gotobb = bb->succ[0]; ASSERT(gotobb->bbLabel == gotostmt->offset, ""); } } } // check that all the target labels in jump statements are defined void MirCFG::VerifyLabels(void) { for (uint32_t i = 0; i < bbVec.size(); i++) { BB *mirbb = bbVec[i]; if (mirbb == nullptr) { continue; } if (mirbb->stmtNodeList.last == nullptr) { continue; } if (mirbb->kind == kBBGoto) { if (mirbb->stmtNodeList.last->op == OP_throw) { continue; } GotoNode *gotostmt = static_cast<GotoNode *>(mirbb->stmtNodeList.last); LabelIdx targetLabidx = (LabelIdx)gotostmt->offset; BB *bb = labelBBIdMap[targetLabidx]; CHECK_FATAL(bb->bbLabel == targetLabidx, "undefined label in goto"); } else if (mirbb->kind == kBBCondGoto) { CondGotoNode *cgotostmt = static_cast<CondGotoNode *>(mirbb->stmtNodeList.last); LabelIdx targetLabidx = (LabelIdx)cgotostmt->offset; BB *bb = labelBBIdMap[targetLabidx]; CHECK_FATAL(bb->bbLabel == targetLabidx, "undefined label in conditional branch"); } else if (mirbb->kind == kBBSwitch) { SwitchNode *switchstmt = static_cast<SwitchNode *>(mirbb->stmtNodeList.last); LabelIdx targetLabidx = switchstmt->defaultLabel; BB *bb = labelBBIdMap[targetLabidx]; CHECK_FATAL(bb->bbLabel == targetLabidx, "undefined label in switch"); for (uint32_t j = 0; j < switchstmt->switchTable.size(); j++) { targetLabidx = switchstmt->switchTable[j].second; bb = labelBBIdMap[targetLabidx]; CHECK_FATAL(bb->bbLabel == targetLabidx, "undefined switch target label"); } } } } void MirCFG::Dump() { // BSF Dump the cfg // map<uint32, uint32> visited_map; // set<uint32> visited_set; printf("####### CFG Dump: "); CHECK_FATAL(NumBBs() != 0, "size to be allocated is 0"); bool *visitedMap = static_cast<bool*>(calloc(NumBBs(), sizeof(bool))); if (visitedMap != nullptr) { queue<BB *> qu; qu.push(first_bb); while (!qu.empty()) { BB *bb = qu.front(); qu.pop(); if (bb == nullptr) { continue; } BBId id = bb->id; if (visitedMap[id.idx] == true) { continue; } printf("%zu ", id.idx); visitedMap[id.idx] = true; MapleVector<BB *>::iterator it = bb->succ.begin(); while (it != bb->succ.end()) { BB *kidbb = *it; if (!visitedMap[kidbb->id.idx]) { qu.push(kidbb); } it++; } } printf("\n"); free(visitedMap); } } /* replace special char in FunctionName for output file */ static void ReplaceFilename(string &filename) { for (uint32 i = 0; i < filename.length(); i++) { if (filename[i] == ';' || filename[i] == '/' || filename[i] == '|') { filename[i] = '_'; } } } static bool ContainsConststr(const BaseNode *x) { if (x->op == OP_conststr || x->op == OP_conststr16) { return true; } for (uint32 i = 0; i < x->numOpnds; i++) if (ContainsConststr(x->Opnd(i))) { return true; } return false; } /* generate dot file for cfg */ void MirCFG::DumpToFile(const char *prefix, bool dumpinstrs) { if (MeOption::noDot) { return; } ofstream cfgfile; streambuf *coutbuf = LogInfo::MapleLogger().rdbuf(); /* keep original LogInfo::MapleLogger() buffer */ streambuf *buf = cfgfile.rdbuf(); LogInfo::MapleLogger().rdbuf(buf); string filename; if (prefix != nullptr) { filename.append(prefix); filename.append("-"); } // the func name length may exceed OS's file name limit, so truncate after 80 chars if (func->GetName().size() <= 80) { filename.append(func->GetName()); } else { filename.append(func->GetName().c_str(), 80); } ReplaceFilename(filename); filename.append(".dot"); cfgfile.open(filename.c_str(), ios::trunc); cfgfile << "digraph {\n"; cfgfile << " # /*" << func->GetName().c_str() << " (red line is exception handler)*/\n"; /* dump edge */ for (BB *bb : bbVec) { if (bb == nullptr) { continue; } if (bb == commonExitBB) { /* specical case for commonExitBB */ for (auto it = bb->pred.begin(); it != bb->pred.end(); it++) { cfgfile << "BB" << (*it)->id.idx << " -> " << "BB" << bb->id.idx << "[style=dotted];\n"; } continue; } for (auto it = bb->succ.begin(); it != bb->succ.end(); it++) { cfgfile << "BB" << bb->id.idx << " -> " << "BB" << (*it)->id.idx; if (bb == commonEntryBB) { cfgfile << "[style=dotted];\n"; continue; } if ((*it)->IsCatch()) { /* succ is exception handler */ cfgfile << "[color=red];\n"; } else { cfgfile << ";\n"; } } } /* dump instruction in each BB */ if (dumpinstrs) { for (BB *bb : bbVec) { if (bb == nullptr || bb->IsEmpty()) { continue; } if (bb->kind == kBBCondGoto) { cfgfile << "BB" << bb->id.idx << "[shape=diamond,label= \" BB" << bb->id.idx << ":\n{ "; } else { cfgfile << "BB" << bb->id.idx << "[shape=box,label= \" BB" << bb->id.idx << ":\n{ "; } if (bb->bbLabel != 0) { cfgfile << "@" << func->mirFunc->GetLabelName(bb->bbLabel) << ":\n"; } MapleMap<OriginalSt *, PhiNode>::iterator phiIt; if (bb->phiList) { for (phiIt = bb->phiList->begin(); phiIt != bb->phiList->end(); phiIt++) { (*phiIt).second.Dump(&(func->mirModule)); } } StmtNode *stmt = bb->stmtNodeList.first; do { // avoid printing content that may contain " as this needs to be quoted if (stmt->op != OP_comment && !ContainsConststr(stmt)) { stmt->Dump(&(func->mirModule), 1); } if (stmt == bb->stmtNodeList.last) { break; } else { stmt = stmt->GetNext(); } } while (true); cfgfile << "}\"];\n"; } } cfgfile << "}\n"; cfgfile.flush(); cfgfile.close(); LogInfo::MapleLogger().rdbuf(coutbuf); } AnalysisResult *MeDoCfgBuild::Run(MeFunction *func, MeFuncResultMgr *m) { MemPool *cfgMp = mempoolctrler.NewMemPool(PhaseName().c_str()); MirCFG *cfg = cfgMp->New<MirCFG>(func, cfgMp); func->theCFG = cfg; func->CreateBasicBlocks(cfg); if (func->theCFG->NumBBs() == 0) { /* there's no basicblock generated */ return cfg; } func->RemoveEhEdgesInSyncRegion(); cfg->BuildMirCFG(); cfg->ReplaceWithAssertnonnull(); cfg->VerifyLabels(); cfg->UnreachCodeAnalysis(); cfg->WontExitAnalysis(); cfg->Verify(); if (!func->isLfo && MeOption::optLevel >= 2) { MeDoLoopCanon doLoopCanon(MeFuncPhase_LOOPCANON); if (!MeOption::quiet) { LogInfo::MapleLogger() << " == " << PhaseName() << " invokes [ " << doLoopCanon.PhaseName() << " ] ==\n"; } doLoopCanon.Run(func, m); MeDoSplitCEdge doSplitCEdge(MeFuncPhase_SPLITCEDGE); if (!MeOption::quiet) { LogInfo::MapleLogger() << " == " << PhaseName() << " invokes [ " << doSplitCEdge.PhaseName() << " ] ==\n"; } doSplitCEdge.Run(func, m); } return cfg; } } // namespace maple
/* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2018,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * GROMACS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ #include "gmxpre.h" #include "gmxapi/version.h" namespace gmxapi { version_t Version::majorVersion() { return c_majorVersion; } version_t Version::minorVersion() { return c_minorVersion; } version_t Version::patchVersion() { return c_patchVersion; } std::string Version::release() { return c_release; } bool Version::hasFeature(const std::string& featurename) { // For features introduced without an incompatible API change or where // semantic versioning is otherwise insufficient, we can consult a map, TBD. (void)featurename; return false; } bool Version::isAtLeast(version_t major, version_t minor, version_t patch) { if (Version::majorVersion() < major) { return false; } if (Version::majorVersion() > major) { return true; } if (Version::minorVersion() < minor) { return false; } if (Version::minorVersion() > minor) { return true; } return Version::patchVersion() >= patch; } } // end namespace gmxapi
#include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include "Constants.h" #include "Token.h" #include "Expressions/Expression.h" #include "Tokenizer.h" #include "Parser.h" using namespace std; int main() { ifstream file; while (true) { file.open("test.lang"); std::ostringstream out; out << file.rdbuf(); file.close(); string programText = out.str(); Tokenizer tokenizer; vector<Token> tokens = tokenizer.tokenize(programText); //vector<Token> tokens = tokenizer.tokenize("PI + 2"); for (int i = 0; i < tokens.size(); i++) { cout << tokens.at(i).m_type << " " << tokens.at(i).m_value << endl; } Parser parser; Statement* statement = parser.parse(tokens); statement->execute(); for (auto it = variables.begin(); it != variables.end(); it++) { //cout << it->first << "= " << it->second << endl; } system("pause"); } return 0; }
// g2o - General Graph Optimization // Copyright (C) 2011 R. Kuemmerle, G. Grisetti, W. Burgard // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A // PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "vertex_se3.h" #include "g2o/core/factory.h" #ifdef G2O_HAVE_OPENGL #include "g2o/stuff/opengl_wrapper.h" #include "g2o/stuff/opengl_primitives.h" #endif #include <iostream> #include "g2o/core/cache.h" using namespace Eigen; namespace g2o { VertexSE3::VertexSE3() : BaseVertex<6, Isometry3>(), _numOplusCalls(0) { setToOriginImpl(); updateCache(); } bool VertexSE3::read(std::istream& is) { Vector7 est; bool state = internal::readVector(is, est); setEstimate(internal::fromVectorQT(est)); return state; } bool VertexSE3::write(std::ostream& os) const { return internal::writeVector(os, internal::toVectorQT(estimate())); } VertexSE3WriteGnuplotAction::VertexSE3WriteGnuplotAction(): WriteGnuplotAction(typeid(VertexSE3).name()){} HyperGraphElementAction* VertexSE3WriteGnuplotAction::operator()(HyperGraph::HyperGraphElement* element, HyperGraphElementAction::Parameters* params_){ if (typeid(*element).name()!=_typeName) return nullptr; WriteGnuplotAction::Parameters* params=static_cast<WriteGnuplotAction::Parameters*>(params_); if (!params->os){ std::cerr << __PRETTY_FUNCTION__ << ": warning, no valid os specified" << std::endl; return nullptr; } VertexSE3* v = static_cast<VertexSE3*>(element); Vector6 est=internal::toVectorMQT(v->estimate()); for (int i=0; i<6; i++) *(params->os) << est[i] << " "; *(params->os) << std::endl; return this; } #ifdef G2O_HAVE_OPENGL void drawTriangle(float xSize, float ySize){ Vector3F p[3]; glBegin(GL_TRIANGLES); p[0] << 0., 0., 0.; p[1] << -xSize, ySize, 0.; p[2] << -xSize, -ySize, 0.; for (int i = 1; i < 2; ++i) { Vector3F normal = (p[i] - p[0]).cross(p[i+1] - p[0]); glNormal3f(normal.x(), normal.y(), normal.z()); glVertex3f(p[0].x(), p[0].y(), p[0].z()); glVertex3f(p[i].x(), p[i].y(), p[i].z()); glVertex3f(p[i+1].x(), p[i+1].y(), p[i+1].z()); } glEnd(); } VertexSE3DrawAction::VertexSE3DrawAction() : DrawAction(typeid(VertexSE3).name()), _triangleX(nullptr), _triangleY(nullptr) { _cacheDrawActions = 0; } bool VertexSE3DrawAction::refreshPropertyPtrs(HyperGraphElementAction::Parameters* params_){ if (!DrawAction::refreshPropertyPtrs(params_)) return false; if (_previousParams){ _triangleX = _previousParams->makeProperty<FloatProperty>(_typeName + "::TRIANGLE_X", .2f); _triangleY = _previousParams->makeProperty<FloatProperty>(_typeName + "::TRIANGLE_Y", .05f); } else { _triangleX = 0; _triangleY = 0; } return true; } HyperGraphElementAction* VertexSE3DrawAction::operator()(HyperGraph::HyperGraphElement* element, HyperGraphElementAction::Parameters* params_){ if (typeid(*element).name()!=_typeName) return nullptr; initializeDrawActionsCache(); refreshPropertyPtrs(params_); if (! _previousParams) return this; if (_show && !_show->value()) return this; VertexSE3* that = static_cast<VertexSE3*>(element); glColor3f(POSE_VERTEX_COLOR); glPushMatrix(); glMultMatrixd(that->estimate().matrix().cast<double>().eval().data()); opengl::drawArrow2D(_triangleX->value(), _triangleY->value(), _triangleX->value()*.3f); drawCache(that->cacheContainer(), params_); drawUserData(that->userData(), params_); glPopMatrix(); return this; } #endif }